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