morphology piece now works for main submit, not for relemmatization yet
[scpubgit/stemmatology.git] / stemmaweb / 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 getTextPath() {
9     var currpath = window.location.pathname;
10     // Get rid of trailing slash
11     if( currpath.lastIndexOf('/') == currpath.length - 1 ) { 
12         currpath = currpath.slice( 0, currpath.length - 1) 
13     };
14     // Get rid of query parameters
15     if( currpath.lastIndexOf('?') != -1 ) {
16         currpath = currpath.slice( 0, currpath.lastIndexOf('?') );
17     };
18     var path_elements = currpath.split('/');
19     var textid = path_elements.pop();
20     var basepath = path_elements.join( '/' );
21     var path_parts = [ basepath, textid ];
22     return path_parts;
23 }
24
25 function getRelativePath() {
26         var path_parts = getTextPath();
27         return path_parts[0];
28 }
29
30 function getTextURL( which ) {
31         var path_parts = getTextPath();
32         return path_parts[0] + '/' + path_parts[1] + '/' + which;
33 }
34
35 function getReadingURL( reading_id ) {
36         var path_parts = getTextPath();
37         return path_parts[0] + '/' + path_parts[1] + '/reading/' + reading_id;
38 }
39
40 // Make an XML ID into a valid selector
41 function jq(myid) { 
42         return '#' + myid.replace(/(:|\.)/g,'\\$1');
43 }
44
45 // Actions for opening the reading panel
46 function node_dblclick_listener( evt ) {
47         // Open the reading dialogue for the given node.
48         // First get the reading info
49         var reading_id = $(this).attr('id');
50         var reading_info = readingdata[reading_id];
51         // and then populate the dialog box with it.
52         // Set the easy properties first
53         $('#reading-form').dialog( 'option', 'title', 'Reading information for "' + reading_info['text'] + '"' );
54         $('#reading_id').val( reading_id );
55         $('#reading_is_nonsense').val( reading_info['is_nonsense'] );
56         $('#reading_grammar_invalid').val( reading_info['grammar_invalid'] );
57         // Use .text as a backup for .normal_form
58         var normal_form = reading_info['normal_form'];
59         if( !normal_form ) {
60                 normal_form = reading_info['text'];
61         }
62         var nfboxsize = 10;
63         if( normal_form.length > 9 ) {
64                 nfboxsize = normal_form.length + 1;
65         }
66         $('#reading_normal_form').attr( 'size', nfboxsize )
67         $('#reading_normal_form').val( normal_form );
68         // Now do the morphological properties.
69         morphology_form( reading_info['lexemes'] );
70         // and then open the dialog.
71         $('#reading-form').dialog("open");
72 }
73
74 function morphology_form ( lexlist ) {
75         $('#morphology').empty();
76         $.each( lexlist, function( idx, lex ) {
77                 var morphoptions = [];
78                 $.each( lex['wordform_matchlist'], function( tdx, tag ) {
79                         var tagstr = stringify_wordform( tag );
80                         morphoptions.push( tagstr );
81                 });
82                 var formtag = 'morphology_' + idx;
83                 //forminput.autocomplete('search', '');
84                 var formstr = '';
85                 if( lex['form'] ) {
86                         formstr = stringify_wordform( lex['form'] );
87                 } 
88                 var form_morph_elements = morph_elements( 
89                         formtag, lex['string'], formstr, morphoptions );
90                 $.each( form_morph_elements, function( idx, el ) {
91                         $('#morphology').append( el );
92                 });
93         });
94 }
95
96 function stringify_wordform ( tag ) {
97         var elements = tag.split(' // ');
98         return elements[1] + ' // ' + elements[2];
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         $.each( reading_info['lexemes'], function ( idx, lex ) {
129                 if( !lex['is_disambiguated'] ) {
130                         $(el).attr( {stroke:'orange', fill:'#fee233'} );
131                 }
132         });
133 }
134
135 // Initialize the SVG once it exists
136 function svgEnlargementLoaded() {
137         //Give some visual evidence that we are working
138         $('#loading_overlay').show();
139         lo_height = $("#enlargement_container").outerHeight();
140         lo_width = $("#enlargement_container").outerWidth();
141         $("#loading_overlay").height( lo_height );
142         $("#loading_overlay").width( lo_width );
143         $("#loading_overlay").offset( $("#enlargement_container").offset() );
144         $("#loading_message").offset(
145                 { 'top': lo_height / 2 - $("#loading_message").height() / 2,
146                   'left': lo_width / 2 - $("#loading_message").width() / 2 });
147     //Set viewbox widht and height to widht and height of $('#svgenlargement svg').
148     $('#update_workspace_button').data('locked', false);
149     $('#update_workspace_button').css('background-position', '0px 44px');
150     //This is essential to make sure zooming and panning works properly.
151         var rdgpath = getTextURL( 'readings' );
152                 $.getJSON( rdgpath, function( data ) {
153                 readingdata = data;
154             $('#svgenlargement ellipse').each( function( i, el ) { color_inactive( el ) });
155         });
156     $('#svgenlargement ellipse').parent().dblclick( node_dblclick_listener );
157     var graph_svg = $('#svgenlargement svg');
158     var svg_g = $('#svgenlargement svg g')[0];
159     if (!svg_g) return;
160     svg_root = graph_svg.svg().svg('get').root();
161
162     // Find the real root and ignore any text nodes
163     for (i = 0; i < svg_root.childNodes.length; ++i) {
164         if (svg_root.childNodes[i].nodeName != '#text') {
165                 svg_root_element = svg_root.childNodes[i];
166                 break;
167            }
168     }
169
170     svg_root.viewBox.baseVal.width = graph_svg.attr( 'width' );
171     svg_root.viewBox.baseVal.height = graph_svg.attr( 'height' );
172     //Now set scale and translate so svg height is about 150px and vertically centered in viewbox.
173     //This is just to create a nice starting enlargement.
174     var initial_svg_height = 250;
175     var scale = initial_svg_height/graph_svg.attr( 'height' );
176     var additional_translate = (graph_svg.attr( 'height' ) - initial_svg_height)/(2*scale);
177     var transform = svg_g.getAttribute('transform');
178     var translate = parseFloat( transform.match( /translate\([^\)]*\)/ )[0].split('(')[1].split(' ')[1].split(')')[0] );
179     translate += additional_translate;
180     var transform = 'rotate(0) scale(' + scale + ') translate(4 ' + translate + ')';
181     svg_g.setAttribute('transform', transform);
182     //used to calculate min and max zoom level:
183     start_element_height = $('#__START__').children('ellipse')[0].getBBox().height;
184     add_relations( function() { $('#loading_overlay').hide(); });
185 }
186
187 function add_relations( callback_fn ) {
188         var basepath = getRelativePath();
189         var textrelpath = getTextURL( 'relationships' );
190     $.getJSON( basepath + '/definitions', function(data) {
191         var rel_types = data.types.sort();
192         $.getJSON( textrelpath,
193         function(data) {
194             $.each(data, function( index, rel_info ) {
195                 var type_index = $.inArray(rel_info.type, rel_types);
196                 var source_found = get_ellipse( rel_info.source );
197                 var target_found = get_ellipse( rel_info.target );
198                 if( type_index != -1 && source_found.size() && target_found.size() ) {
199                     var relation = relation_manager.create( rel_info.source, rel_info.target, type_index );
200                     relation.data( 'type', rel_info.type );
201                     relation.data( 'scope', rel_info.scope );
202                     relation.data( 'note', rel_info.note );
203                     var node_obj = get_node_obj(rel_info.source);
204                     node_obj.set_draggable( false );
205                     node_obj.ellipse.data( 'node_obj', null );
206                     node_obj = get_node_obj(rel_info.target);
207                     node_obj.set_draggable( false );
208                     node_obj.ellipse.data( 'node_obj', null );
209                 }
210             });
211             callback_fn.call();
212         });
213     });
214 }
215
216 function get_ellipse( node_id ) {
217         return $( jq( node_id ) + ' ellipse');
218 }
219
220 function get_node_obj( node_id ) {
221     var node_ellipse = get_ellipse( node_id );
222     if( node_ellipse.data( 'node_obj' ) == null ) {
223         node_ellipse.data( 'node_obj', new node_obj(node_ellipse) );
224     };
225     return node_ellipse.data( 'node_obj' );
226 }
227
228 function node_obj(ellipse) {
229   this.ellipse = ellipse;
230   var self = this;
231   
232   this.x = 0;
233   this.y = 0;
234   this.dx = 0;
235   this.dy = 0;
236   this.node_elements = node_elements_for(self.ellipse);
237
238   this.get_id = function() {
239     return $(self.ellipse).parent().attr('id')
240   }
241   
242   this.set_draggable = function( draggable ) {
243     if( draggable ) {
244       $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
245       $(self.ellipse).parent().mousedown( this.mousedown_listener );
246       $(self.ellipse).parent().hover( this.enter_node, this.leave_node ); 
247       self.ellipse.siblings('text').attr('class', 'noselect draggable');
248     } else {
249       self.ellipse.siblings('text').attr('class', '');
250           $(self.ellipse).parent().unbind( 'mouseenter' ).unbind( 'mouseleave' ).unbind( 'mousedown' );     
251       color_inactive( self.ellipse );
252     }
253   }
254
255   this.mousedown_listener = function(evt) {
256     evt.stopPropagation();
257     self.x = evt.clientX;
258     self.y = evt.clientY;
259     $('body').mousemove( self.mousemove_listener );
260     $('body').mouseup( self.mouseup_listener );
261     $(self.ellipse).parent().unbind('mouseenter').unbind('mouseleave')
262     self.ellipse.attr( 'fill', '#ff66ff' );
263     first_node_g_element = $("#svgenlargement g .node" ).filter( ":first" );
264     if( first_node_g_element.attr('id') !== self.get_g().attr('id') ) { self.get_g().insertBefore( first_node_g_element ) };
265   }
266
267   this.mousemove_listener = function(evt) {
268     self.dx = (evt.clientX - self.x) / mouse_scale;
269     self.dy = (evt.clientY - self.y) / mouse_scale;
270     self.move_elements();
271     evt.returnValue = false;
272     evt.preventDefault();
273     return false;
274   }
275
276   this.mouseup_listener = function(evt) {    
277     if( $('ellipse[fill="#ffccff"]').size() > 0 ) {
278         var source_node_id = $(self.ellipse).parent().attr('id');
279         var source_node_text = self.ellipse.siblings('text').text();
280         var target_node_id = $('ellipse[fill="#ffccff"]').parent().attr('id');
281         var target_node_text = $('ellipse[fill="#ffccff"]').siblings("text").text();
282         $('#source_node_id').val( source_node_id );
283         $('#source_node_text').val( source_node_text );
284         $('#target_node_id').val( target_node_id );
285         $('#target_node_text').val( target_node_text );
286         $('#dialog-form').dialog( 'open' );
287     };
288     $('body').unbind('mousemove');
289     $('body').unbind('mouseup');
290     self.ellipse.attr( 'fill', '#fff' );
291     $(self.ellipse).parent().hover( self.enter_node, self.leave_node );
292     self.reset_elements();
293   }
294   
295   this.cpos = function() {
296     return { x: self.ellipse.attr('cx'), y: self.ellipse.attr('cy') };
297   }
298
299   this.get_g = function() {
300     return self.ellipse.parent('g');
301   }
302
303   this.enter_node = function(evt) {
304     self.ellipse.attr( 'fill', '#ffccff' );
305   }
306
307   this.leave_node = function(evt) {
308     self.ellipse.attr( 'fill', '#fff' );
309   }
310
311   this.greyout_edges = function() {
312       $.each( self.node_elements, function(index, value) {
313         value.grey_out('.edge');
314       });
315   }
316
317   this.ungreyout_edges = function() {
318       $.each( self.node_elements, function(index, value) {
319         value.un_grey_out('.edge');
320       });
321   }
322
323   this.move_elements = function() {
324     $.each( self.node_elements, function(index, value) {
325       value.move(self.dx,self.dy);
326     });
327   }
328
329   this.reset_elements = function() {
330     $.each( self.node_elements, function(index, value) {
331       value.reset();
332     });
333   }
334
335   this.update_elements = function() {
336       self.node_elements = node_elements_for(self.ellipse);
337   }
338
339   self.set_draggable( true );
340 }
341
342 function svgshape( shape_element ) {
343   this.shape = shape_element;
344   this.move = function(dx,dy) {
345     this.shape.attr( "transform", "translate(" + dx + " " + dy + ")" );
346   }
347   this.reset = function() {
348     this.shape.attr( "transform", "translate( 0, 0 )" );
349   }
350   this.grey_out = function(filter) {
351       if( this.shape.parent(filter).size() != 0 ) {
352           this.shape.attr({'stroke':'#e5e5e5', 'fill':'#e5e5e5'});
353       }
354   }
355   this.un_grey_out = function(filter) {
356       if( this.shape.parent(filter).size() != 0 ) {
357         this.shape.attr({'stroke':'#000000', 'fill':'#000000'});
358       }
359   }
360 }
361
362 function svgpath( path_element, svg_element ) {
363   this.svg_element = svg_element;
364   this.path = path_element;
365   this.x = this.path.x;
366   this.y = this.path.y;
367   this.move = function(dx,dy) {
368     this.path.x = this.x + dx;
369     this.path.y = this.y + dy;
370   }
371   this.reset = function() {
372     this.path.x = this.x;
373     this.path.y = this.y;
374   }
375   this.grey_out = function(filter) {
376       if( this.svg_element.parent(filter).size() != 0 ) {
377           this.svg_element.attr('stroke', '#e5e5e5');
378           this.svg_element.siblings('text').attr('fill', '#e5e5e5');
379           this.svg_element.siblings('text').attr('class', 'noselect');
380       }
381   }
382   this.un_grey_out = function(filter) {
383       if( this.svg_element.parent(filter).size() != 0 ) {
384           this.svg_element.attr('stroke', '#000000');
385           this.svg_element.siblings('text').attr('fill', '#000000');
386           this.svg_element.siblings('text').attr('class', '');
387       }
388   }
389 }
390
391 function node_elements_for( ellipse ) {
392   node_elements = get_edge_elements_for( ellipse );
393   node_elements.push( new svgshape( ellipse.siblings('text') ) );
394   node_elements.push( new svgshape( ellipse ) );
395   return node_elements;
396 }
397
398 function get_edge_elements_for( ellipse ) {
399   edge_elements = new Array();
400   node_id = ellipse.parent().attr('id');
401   edge_in_pattern = new RegExp( node_id + '$' );
402   edge_out_pattern = new RegExp( '^' + node_id );
403   $.each( $('#svgenlargement .edge,#svgenlargement .relation').children('title'), function(index) {
404     title = $(this).text();
405     if( edge_in_pattern.test(title) ) {
406         polygon = $(this).siblings('polygon');
407         if( polygon.size() > 0 ) {
408             edge_elements.push( new svgshape( polygon ) );
409         }
410         path_segments = $(this).siblings('path')[0].pathSegList;
411         edge_elements.push( new svgpath( path_segments.getItem(path_segments.numberOfItems - 1), $(this).siblings('path') ) );
412     }
413     if( edge_out_pattern.test(title) ) {
414       path_segments = $(this).siblings('path')[0].pathSegList;
415       edge_elements.push( new svgpath( path_segments.getItem(0), $(this).siblings('path') ) );
416     }
417   });
418   return edge_elements;
419
420
421 function relation_factory() {
422     var self = this;
423     this.color_memo = null;
424     //TODO: colors hard coded for now
425     this.temp_color = '#FFA14F';
426     this.relation_colors = [ "#5CCCCC", "#67E667", "#F9FE72", "#6B90D4", "#FF7673", "#E467B3", "#AA67D5", "#8370D8", "#FFC173" ];
427
428     this.create_temporary = function( source_node_id, target_node_id ) {
429         var relation_id = get_relation_id( source_node_id, target_node_id );
430         var relation = $( jq( relation_id ) );
431         if( relation.size() == 0 ) { 
432             draw_relation( source_node_id, target_node_id, self.temp_color );
433         } else {
434             self.color_memo = relation.children('path').attr( 'stroke' );
435             relation.children('path').attr( 'stroke', self.temp_color );
436         }
437     }
438     this.remove_temporary = function() {
439         var path_element = $('#svgenlargement .relation').children('path[stroke="' + self.temp_color + '"]');
440         if( self.color_memo != null ) {
441             path_element.attr( 'stroke', self.color_memo );
442             self.color_memo = null;
443         } else {
444             var temporary = path_element.parent('g').remove();
445             temporary.empty();
446             temporary = null; 
447         }
448     }
449     this.create = function( source_node_id, target_node_id, color_index ) {
450         //TODO: Protect from (color_)index out of bound..
451         var relation_color = self.relation_colors[ color_index ];
452         var relation = draw_relation( source_node_id, target_node_id, relation_color );
453         get_node_obj( source_node_id ).update_elements();
454         get_node_obj( target_node_id ).update_elements();
455         return relation;
456     }
457     this.toggle_active = function( relation_id ) {
458         var relation = $( jq( relation_id ) );
459         var relation_path = relation.children('path');
460         if( !relation.data( 'active' ) ) {
461             relation_path.css( {'cursor':'pointer'} );
462             relation_path.mouseenter( function(event) { 
463                 outerTimer = setTimeout( function() { 
464                     timer = setTimeout( function() { 
465                         var related_nodes = get_related_nodes( relation_id );
466                         var source_node_id = related_nodes[0];
467                         var target_node_id = related_nodes[1];
468                         $('#delete_source_node_id').val( source_node_id );
469                         $('#delete_target_node_id').val( target_node_id );
470                         self.showinfo(relation); 
471                     }, 500 ) 
472                 }, 1000 );
473             });
474             relation_path.mouseleave( function(event) {
475                 clearTimeout(outerTimer); 
476                 if( timer != null ) { clearTimeout(timer); } 
477             });
478             relation.data( 'active', true );
479         } else {
480             relation_path.unbind( 'mouseenter' );
481             relation_path.unbind( 'mouseleave' );
482             relation_path.css( {'cursor':'inherit'} );
483             relation.data( 'active', false );
484         }
485     }
486     this.showinfo = function(relation) {
487         var htmlstr = 'type: ' + relation.data( 'type' ) + '<br/>scope: ' + relation.data( 'scope' );
488         if( relation.data( 'note' ) ) {
489                 htmlstr = htmlstr + '<br/>note: ' + relation.data( 'note' );
490         }
491         $('#delete-form-text').html( htmlstr );
492         var points = relation.children('path').attr('d').slice(1).replace('C',' ').split(' ');
493         var xs = parseFloat( points[0].split(',')[0] );
494         var xe = parseFloat( points[1].split(',')[0] );
495         var ys = parseFloat( points[0].split(',')[1] );
496         var ye = parseFloat( points[3].split(',')[1] );
497         var p = svg_root.createSVGPoint();
498         p.x = xs + ((xe-xs)*1.1);
499         p.y = ye - ((ye-ys)/2);
500         var ctm = svg_root_element.getScreenCTM();
501         var nx = p.matrixTransform(ctm).x;
502         var ny = p.matrixTransform(ctm).y;
503         var dialog_aria = $ ("div[aria-labelledby='ui-dialog-title-delete-form']");
504         $('#delete-form').dialog( 'open' );
505         dialog_aria.offset({ left: nx, top: ny });
506     }
507     this.remove = function( relation_id ) {
508         var relation = $( jq( relation_id ) );
509         relation.remove();
510     }
511 }
512
513 // Utility function to create/return the ID of a relation link between
514 // a source and target.
515 function get_relation_id( source_id, target_id ) {
516         var idlist = [ source_id, target_id ];
517         idlist.sort();
518         return 'relation-' + idlist[0] + '-...-' + idlist[1];
519 }
520
521 function get_related_nodes( relation_id ) {
522         var srctotarg = relation_id.substr( 9 );
523         return srctotarg.split('-...-');
524 }
525
526 function draw_relation( source_id, target_id, relation_color ) {
527     var source_ellipse = get_ellipse( source_id );
528     var target_ellipse = get_ellipse( target_id );
529     var relation_id = get_relation_id( source_id, target_id );
530     var svg = $('#svgenlargement').children('svg').svg().svg('get');
531     var path = svg.createPath(); 
532     var sx = parseInt( source_ellipse.attr('cx') );
533     var rx = parseInt( source_ellipse.attr('rx') );
534     var sy = parseInt( source_ellipse.attr('cy') );
535     var ex = parseInt( target_ellipse.attr('cx') );
536     var ey = parseInt( target_ellipse.attr('cy') );
537     var relation = svg.group( $("#svgenlargement svg g"), 
538         { 'class':'relation', 'id':relation_id } );
539     svg.title( relation, source_id + '->' + target_id );
540     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});
541     var relation_element = $('#svgenlargement .relation').filter( ':last' );
542     relation_element.insertBefore( $('#svgenlargement g g').filter(':first') );
543     return relation_element;
544 }
545
546
547 $(document).ready(function () {
548     
549   timer = null;
550   relation_manager = new relation_factory();
551   $('#update_workspace_button').data('locked', false);
552   
553   $('#enlargement').mousedown(function (event) {
554     $(this)
555         .data('down', true)
556         .data('x', event.clientX)
557         .data('y', event.clientY)
558         .data('scrollLeft', this.scrollLeft)
559         stateTf = svg_root_element.getCTM().inverse();
560         var p = svg_root.createSVGPoint();
561         p.x = event.clientX;
562         p.y = event.clientY;
563         stateOrigin = p.matrixTransform(stateTf);
564         event.returnValue = false;
565         event.preventDefault();
566         return false;
567   }).mouseup(function (event) {
568         $(this).data('down', false);
569   }).mousemove(function (event) {
570     if( timer != null ) { clearTimeout(timer); } 
571     if ( ($(this).data('down') == true) && ($('#update_workspace_button').data('locked') == false) ) {
572         var p = svg_root.createSVGPoint();
573         p.x = event.clientX;
574         p.y = event.clientY;
575         p = p.matrixTransform(stateTf);
576         var matrix = stateTf.inverse().translate(p.x - stateOrigin.x, p.y - stateOrigin.y);
577         var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
578         svg_root_element.setAttribute("transform", s);
579     }
580     event.returnValue = false;
581     event.preventDefault();
582   }).mousewheel(function (event, delta) {
583     event.returnValue = false;
584     event.preventDefault();
585     if ( $('#update_workspace_button').data('locked') == false ) {
586         if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
587         if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
588         if( delta < -9 ) { delta = -9 }; 
589         var z = 1 + delta/10;
590         z = delta > 0 ? 1 : -1;
591         var g = svg_root_element;
592         if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 100))) {
593             var root = svg_root;
594             var p = root.createSVGPoint();
595             p.x = event.originalEvent.clientX;
596             p.y = event.originalEvent.clientY;
597             p = p.matrixTransform(g.getCTM().inverse());
598             var scaleLevel = 1+(z/20);
599             var k = root.createSVGMatrix().translate(p.x, p.y).scale(scaleLevel).translate(-p.x, -p.y);
600             var matrix = g.getCTM().multiply(k);
601             var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
602             g.setAttribute("transform", s);
603         }
604     }
605   }).css({
606     'overflow' : 'hidden',
607     'cursor' : '-moz-grab'
608   });
609   
610
611   $( "#dialog-form" ).dialog({
612     autoOpen: false,
613     height: 270,
614     width: 290,
615     modal: true,
616     buttons: {
617       "Ok": function() {
618         $('#status').empty();
619         form_values = $('#collapse_node_form').serialize();
620         ncpath = getTextURL( 'relationships' );
621         $(':button :contains("Ok")').attr("disabled", true);
622         var jqjson = $.post( ncpath, form_values, function(data) {
623             $.each( data, function(item, source_target) { 
624                 var source_found = get_ellipse( source_target[0] );
625                 var target_found = get_ellipse( source_target[1] );
626                 if( source_found.size() && target_found.size() ) {
627                     var relation = relation_manager.create( source_target[0], source_target[1], $('#rel_type')[0].selectedIndex-1 );
628                                         relation.data( 'type', $('#rel_type :selected').text()  );
629                                         relation.data( 'scope', $('#scope :selected').text()  );
630                                         relation.data( 'note', $('#note').val()  );
631                                         relation_manager.toggle_active( relation.attr('id') );
632                                 }
633             });
634             $( "#dialog-form" ).dialog( "close" );
635         }, 'json' );
636       },
637       Cancel: function() {
638           $( this ).dialog( "close" );
639       }
640     },
641     create: function(event, ui) { 
642         $(this).data( 'relation_drawn', false );
643         //TODO? Err handling?
644                 var basepath = getRelativePath();
645         var jqjson = $.getJSON( basepath + '/definitions', function(data) {
646             var types = data.types.sort();
647             $.each( types, function(index, value) {   
648                  $('#rel_type').append( $('<option />').attr( "value", value ).text(value) ); 
649                  $('#keymaplist').append( $('<li>').css( "border-color", relation_manager.relation_colors[index] ).text(value) ); 
650             });
651             var scopes = data.scopes;
652             $.each( scopes, function(index, value) {   
653                  $('#scope').append( $('<option />').attr( "value", value ).text(value) ); 
654             });
655         });        
656     },
657     open: function() {
658         relation_manager.create_temporary( $('#source_node_id').val(), $('#target_node_id').val() );
659         $(".ui-widget-overlay").css("background", "none");
660         $("#dialog_overlay").show();
661         $("#dialog_overlay").height( $("#enlargement_container").height() );
662         $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
663         $("#dialog_overlay").offset( $("#enlargement_container").offset() );
664     },
665     close: function() {
666         relation_manager.remove_temporary();
667         $( '#status' ).empty();
668         $("#dialog_overlay").hide();
669     }
670   }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
671       if( ( ajaxSettings.type == 'POST' ) && jqXHR.status == 403 ) {
672           var errobj = jQuery.parseJSON( jqXHR.responseText );
673           $('#status').append( '<p class="error">Error: ' + errobj.error + '</br>The relationship cannot be made.</p>' );
674       }
675   } );
676
677   $( "#delete-form" ).dialog({
678     autoOpen: false,
679     height: 135,
680     width: 160,
681     modal: false,
682     buttons: {
683         Cancel: function() {
684             $( this ).dialog( "close" );
685         },
686         Delete: function() {
687           form_values = $('#delete_relation_form').serialize();
688           ncpath = getTextURL( 'relationships' );
689           var jqjson = $.ajax({ url: ncpath, data: form_values, success: function(data) {
690               $.each( data, function(item, source_target) { 
691                   relation_manager.remove( get_relation_id( source_target[0], source_target[1] ) );
692               });
693               $( "#delete-form" ).dialog( "close" );
694           }, dataType: 'json', type: 'DELETE' });
695         }
696     },
697     create: function(event, ui) {
698         var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
699         buttonset.find( "button:contains('Cancel')" ).css( 'float', 'right' );
700         var dialog_aria = $("div[aria-labelledby='ui-dialog-title-delete-form']");  
701         dialog_aria.mouseenter( function() {
702             if( mouseWait != null ) { clearTimeout(mouseWait) };
703         })
704         dialog_aria.mouseleave( function() {
705             mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
706         })
707     },
708     open: function() {
709         mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
710     },
711     close: function() {
712     }
713   });
714
715   // function for reading form dialog should go here; for now hide the element
716   $('#reading-form').dialog({
717         autoOpen: false,
718         height: 400,
719         width: 600,
720         modal: true,
721         buttons: {
722                 Cancel: function() {
723                         $( this ).dialog( "close" );
724                 },
725                 Update: function() {
726                         var reading_id = $('#reading_id').val()
727                         form_values = {
728                                 'id' : reading_id,
729                                 'is_nonsense': $('#reading_is_nonsense').val(),
730                                 'grammar_invalid': $('#reading_grammar_invalid').val(),
731                                 'normal_form': $('#reading_normal_form').val() };
732                         // Add the morphology values
733                         $('.reading_morphology').each( function() {
734                                 var rmid = $(this).attr('id');
735                                 rmid = rmid.substring(8);
736                                 form_values[rmid] = $(this).val();
737                         });
738                         // Make the JSON call
739                         ncpath = getReadingURL( reading_id );
740                         var reading_element = readingdata[reading_id];
741                         $(':button :contains("Update")').attr("disabled", true);
742                         var jqjson = $.post( ncpath, form_values, function(data) {
743                                 $.each( data, function(key, value) { 
744                                         reading_element[key] = value;
745                                 });
746                                 if( $('#update_workspace_button').data('locked') == false ) {
747                                         color_inactive( get_ellipse( reading_id ) );
748                                 }
749                                 $( "#reading-form" ).dialog( "close" );
750                         });
751                         // Re-color the node if necessary
752                         return false;
753                 }
754         },
755         create: function() {
756                 // $('#reading_relemmatize').button();
757                 $('#reading_relemmatize').click( function () {
758                         // Send the reading for a new lemmatization and reopen the form.
759                         alert( "Got a click function for relemmatize button" );
760                         var reading_id = $('#reading_id').val()
761                         ncpath = getReadingURL( reading_id );
762                         form_values = { 
763                                 'normal_form': $('#reading_normal_form').val(), 
764                                 'relemmatize': 1 };
765                         var jqjson = $.post( ncpath, form_values, function( data ) {
766                                 // Update the form with the return
767                                 if( 'reading_id' in data ) {
768                                         // We got back a good answer. Stash it
769                                         readingdata[reading_id] = data;
770                                         // and regenerate the morphology form.
771                                         morphology_form( data['lexemes'] );
772                                 } // else throw an error with what is in ['error']
773                         });
774                         // Prevent submit
775                         return false;
776                 });
777         },
778         open: function() {
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         },
785         close: function() {
786                 $("#dialog_overlay").hide();
787         }
788   });
789   
790
791   $('#update_workspace_button').click( function() {
792      var svg_enlargement = $('#svgenlargement').svg().svg('get').root();
793      mouse_scale = svg_root_element.getScreenCTM().a;
794      if( $(this).data('locked') == true ) {
795          $('#svgenlargement ellipse' ).each( function( index ) {
796              if( $(this).data( 'node_obj' ) != null ) {
797                  $(this).data( 'node_obj' ).ungreyout_edges();
798                  $(this).data( 'node_obj' ).set_draggable( false );
799                  var node_id = $(this).data( 'node_obj' ).get_id();
800                  toggle_relation_active( node_id );
801                  $(this).data( 'node_obj', null );
802              }
803          })
804          $(this).data('locked', false);
805          $(this).css('background-position', '0px 44px');
806      } else {
807          var left = $('#enlargement').offset().left;
808          var right = left + $('#enlargement').width();
809          var tf = svg_root_element.getScreenCTM().inverse(); 
810          var p = svg_root.createSVGPoint();
811          p.x=left;
812          p.y=100;
813          var cx_min = p.matrixTransform(tf).x;
814          p.x=right;
815          var cx_max = p.matrixTransform(tf).x;
816          $('#svgenlargement ellipse').each( function( index ) {
817              var cx = parseInt( $(this).attr('cx') );
818              if( cx > cx_min && cx < cx_max) { 
819                  if( $(this).data( 'node_obj' ) == null ) {
820                      $(this).data( 'node_obj', new node_obj( $(this) ) );
821                  } else {
822                      $(this).data( 'node_obj' ).set_draggable( true );
823                  }
824                  $(this).data( 'node_obj' ).greyout_edges();
825                  var node_id = $(this).data( 'node_obj' ).get_id();
826                  toggle_relation_active( node_id );
827              }
828          });
829          $(this).css('background-position', '0px 0px');
830          $(this).data('locked', true );
831      }
832   });
833   
834   $('.helptag').popupWindow({ 
835           height:500, 
836           width:800, 
837           top:50, 
838           left:50,
839           scrollbars:1 
840   }); 
841
842   
843   function toggle_relation_active( node_id ) {
844       $('#svgenlargement .relation').find( "title:contains('" + node_id +  "')" ).each( function(index) {
845           matchid = new RegExp( "^" + node_id );
846           if( $(this).text().match( matchid ) != null ) {
847                   var relation_id = $(this).parent().attr('id');
848               relation_manager.toggle_active( relation_id );
849           };
850       });
851   }
852
853   expandFillPageClients();
854   $(window).resize(function() {
855     expandFillPageClients();
856   });
857
858 });
859
860
861 function expandFillPageClients() {
862         $('.fillPage').each(function () {
863                 $(this).height($(window).height() - $(this).offset().top - MARGIN);
864         });
865 }
866
867 function loadSVG(svgData) {
868         var svgElement = $('#svgenlargement');
869
870         $(svgElement).svg('destroy');
871
872         $(svgElement).svg({
873                 loadURL: svgData,
874                 onLoad : svgEnlargementLoaded
875         });
876 }
877
878
879 /*      OS Gadget stuff
880
881 function svg_select_callback(topic, data, subscriberData) {
882         svgData = data;
883         loadSVG(svgData);
884 }
885
886 function loaded() {
887         var prefs = new gadgets.Prefs();
888         var preferredHeight = parseInt(prefs.getString('height'));
889         if (gadgets.util.hasFeature('dynamic-height')) gadgets.window.adjustHeight(preferredHeight);
890         expandFillPageClients();
891 }
892
893 if (gadgets.util.hasFeature('pubsub-2')) {
894         gadgets.HubSettings.onConnect = function(hum, suc, err) {
895                 subId = gadgets.Hub.subscribe("interedition.svg.selected", svg_select_callback);
896                 loaded();
897         };
898 }
899 else gadgets.util.registerOnLoadHandler(loaded);
900 */