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