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