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