fix absolute links to merge yes/no buttons. Fixes #30
[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
a471cb0f 8jQuery.removeFromArray = function(value, arr) {
9 return jQuery.grep(arr, function(elem, index) {
10 return elem !== value;
11 });
12};
13
a84ca4de 14function arrayUnique(array) {
15 var a = array.concat();
16 for(var i=0; i<a.length; ++i) {
17 for(var j=i+1; j<a.length; ++j) {
18 if(a[i] === a[j])
19 a.splice(j--, 1);
20 }
21 }
22 return a;
23};
24
5f15640c 25function getTextURL( which ) {
3f9d7ae5 26 return basepath + textid + '/' + which;
5f15640c 27}
28
29function getReadingURL( reading_id ) {
3f9d7ae5 30 return basepath + textid + '/reading/' + reading_id;
b28e606e 31}
32
45ee3b96 33// Make an XML ID into a valid selector
34function jq(myid) {
35 return '#' + myid.replace(/(:|\.)/g,'\\$1');
36}
37
065c7cf2 38// Actions for opening the reading panel
39function node_dblclick_listener( evt ) {
40 // Open the reading dialogue for the given node.
41 // First get the reading info
42 var reading_id = $(this).attr('id');
43 var reading_info = readingdata[reading_id];
44 // and then populate the dialog box with it.
45 // Set the easy properties first
46 $('#reading-form').dialog( 'option', 'title', 'Reading information for "' + reading_info['text'] + '"' );
47 $('#reading_id').val( reading_id );
798fa939 48 toggle_checkbox( $('#reading_is_nonsense'), reading_info['is_nonsense'] );
49 toggle_checkbox( $('#reading_grammar_invalid'), reading_info['grammar_invalid'] );
065c7cf2 50 // Use .text as a backup for .normal_form
51 var normal_form = reading_info['normal_form'];
52 if( !normal_form ) {
53 normal_form = reading_info['text'];
54 }
55 var nfboxsize = 10;
56 if( normal_form.length > 9 ) {
57 nfboxsize = normal_form.length + 1;
58 }
59 $('#reading_normal_form').attr( 'size', nfboxsize )
60 $('#reading_normal_form').val( normal_form );
5539cba3 61 if( editable ) {
62 // Fill in the witnesses for the de-collation box.
63 $('#reading_decollate_witnesses').empty();
64 $.each( reading_info['witnesses'], function( idx, wit ) {
65 $('#reading_decollate_witnesses').append( $('<option/>').attr(
66 'value', wit ).text( wit ) );
67 });
68 }
065c7cf2 69 // Now do the morphological properties.
0dcdd5ec 70 morphology_form( reading_info['lexemes'] );
065c7cf2 71 // and then open the dialog.
0dcdd5ec 72 $('#reading-form').dialog("open");
73}
74
798fa939 75function toggle_checkbox( box, value ) {
76 if( value == null ) {
77 value = false;
78 }
79 box.attr('checked', value );
80}
81
0dcdd5ec 82function morphology_form ( lexlist ) {
487674b9 83 if( lexlist.length ) {
84 $('#morph_outer').show();
85 $('#morphology').empty();
86 $.each( lexlist, function( idx, lex ) {
87 var morphoptions = [];
88 if( 'wordform_matchlist' in lex ) {
89 $.each( lex['wordform_matchlist'], function( tdx, tag ) {
90 var tagstr = stringify_wordform( tag );
91 morphoptions.push( tagstr );
92 });
93 }
94 var formtag = 'morphology_' + idx;
95 var formstr = '';
96 if( 'form' in lex ) {
97 formstr = stringify_wordform( lex['form'] );
98 }
99 var form_morph_elements = morph_elements(
100 formtag, lex['string'], formstr, morphoptions );
101 $.each( form_morph_elements, function( idx, el ) {
102 $('#morphology').append( el );
08f8443a 103 });
065c7cf2 104 });
487674b9 105 } else {
106 $('#morph_outer').hide();
107 }
065c7cf2 108}
109
110function stringify_wordform ( tag ) {
08f8443a 111 if( tag ) {
112 var elements = tag.split(' // ');
113 return elements[1] + ' // ' + elements[2];
114 }
115 return ''
065c7cf2 116}
117
d1132306 118function morph_elements ( formtag, formtxt, currform, morphoptions ) {
119 var clicktag = '(Click to select)';
120 if ( !currform ) {
121 currform = clicktag;
122 }
065c7cf2 123 var formlabel = $('<label/>').attr( 'id', 'label_' + formtag ).attr(
d1132306 124 'for', 'reading_' + formtag ).text( formtxt + ': ' );
065c7cf2 125 var forminput = $('<input/>').attr( 'id', 'reading_' + formtag ).attr(
0dcdd5ec 126 'name', 'reading_' + formtag ).attr( 'size', '50' ).attr(
127 'class', 'reading_morphology' ).val( currform );
d1132306 128 forminput.autocomplete({ source: morphoptions, minLength: 0 });
129 forminput.focus( function() {
130 if( $(this).val() == clicktag ) {
131 $(this).val('');
132 }
133 $(this).autocomplete('search', '')
134 });
065c7cf2 135 var morphel = [ formlabel, forminput, $('<br/>') ];
136 return morphel;
137}
138
4c41c02c 139function color_inactive ( el ) {
140 var reading_id = $(el).parent().attr('id');
141 var reading_info = readingdata[reading_id];
142 // If the reading info has any non-disambiguated lexemes, color it yellow;
143 // otherwise color it green.
144 $(el).attr( {stroke:'green', fill:'#b3f36d'} );
bb3230b1 145 if( reading_info ) {
146 $.each( reading_info['lexemes'], function ( idx, lex ) {
147 if( !lex['is_disambiguated'] || lex['is_disambiguated'] == 0 ) {
148 $(el).attr( {stroke:'orange', fill:'#fee233'} );
149 }
150 });
151 }
4c41c02c 152}
153
997ebe92 154function relemmatize () {
155 // Send the reading for a new lemmatization and reopen the form.
a0a66634 156 $('#relemmatize_pending').show();
997ebe92 157 var reading_id = $('#reading_id').val()
158 ncpath = getReadingURL( reading_id );
159 form_values = {
160 'normal_form': $('#reading_normal_form').val(),
161 'relemmatize': 1 };
162 var jqjson = $.post( ncpath, form_values, function( data ) {
163 // Update the form with the return
164 if( 'id' in data ) {
165 // We got back a good answer. Stash it
166 readingdata[reading_id] = data;
167 // and regenerate the morphology form.
168 morphology_form( data['lexemes'] );
169 } else {
170 alert("Could not relemmatize as requested: " + data['error']);
171 }
a0a66634 172 $('#relemmatize_pending').hide();
997ebe92 173 });
174}
175
065c7cf2 176// Initialize the SVG once it exists
b28e606e 177function svgEnlargementLoaded() {
fc018906 178 //Give some visual evidence that we are working
179 $('#loading_overlay').show();
180 lo_height = $("#enlargement_container").outerHeight();
181 lo_width = $("#enlargement_container").outerWidth();
182 $("#loading_overlay").height( lo_height );
183 $("#loading_overlay").width( lo_width );
184 $("#loading_overlay").offset( $("#enlargement_container").offset() );
185 $("#loading_message").offset(
186 { 'top': lo_height / 2 - $("#loading_message").height() / 2,
187 'left': lo_width / 2 - $("#loading_message").width() / 2 });
30d0ba1e 188 if( editable ) {
189 // Show the update toggle button.
190 $('#update_workspace_button').data('locked', false);
191 $('#update_workspace_button').css('background-position', '0px 44px');
192 }
065c7cf2 193 $('#svgenlargement ellipse').parent().dblclick( node_dblclick_listener );
9529f69c 194 var graph_svg = $('#svgenlargement svg');
195 var svg_g = $('#svgenlargement svg g')[0];
76f05423 196 if (!svg_g) return;
9529f69c 197 svg_root = graph_svg.svg().svg('get').root();
76f05423 198
199 // Find the real root and ignore any text nodes
200 for (i = 0; i < svg_root.childNodes.length; ++i) {
201 if (svg_root.childNodes[i].nodeName != '#text') {
202 svg_root_element = svg_root.childNodes[i];
203 break;
204 }
205 }
206
30d0ba1e 207 //Set viewbox width and height to width and height of $('#svgenlargement svg').
208 //This is essential to make sure zooming and panning works properly.
9529f69c 209 svg_root.viewBox.baseVal.width = graph_svg.attr( 'width' );
210 svg_root.viewBox.baseVal.height = graph_svg.attr( 'height' );
211 //Now set scale and translate so svg height is about 150px and vertically centered in viewbox.
212 //This is just to create a nice starting enlargement.
213 var initial_svg_height = 250;
214 var scale = initial_svg_height/graph_svg.attr( 'height' );
215 var additional_translate = (graph_svg.attr( 'height' ) - initial_svg_height)/(2*scale);
216 var transform = svg_g.getAttribute('transform');
217 var translate = parseFloat( transform.match( /translate\([^\)]*\)/ )[0].split('(')[1].split(' ')[1].split(')')[0] );
218 translate += additional_translate;
219 var transform = 'rotate(0) scale(' + scale + ') translate(4 ' + translate + ')';
220 svg_g.setAttribute('transform', transform);
221 //used to calculate min and max zoom level:
4c41c02c 222 start_element_height = $('#__START__').children('ellipse')[0].getBBox().height;
e538eccb 223 //some use of call backs to ensure succesive execution
224 add_relations( function() {
225 var rdgpath = getTextURL( 'readings' );
226 $.getJSON( rdgpath, function( data ) {
227 readingdata = data;
228 $('#svgenlargement ellipse').each( function( i, el ) { color_inactive( el ) });
9231663d 229 $('#loading_overlay').hide();
e538eccb 230 });
e538eccb 231 });
c1add777 232
233 //initialize marquee
234 marquee = new Marquee();
235
6afcd813 236}
237
fc018906 238function add_relations( callback_fn ) {
56e3972e 239 // Add the relationship types to the keymap list
56e3972e 240 $.each( relationship_types, function(index, typedef) {
671c04b1 241 li_elm = $('<li class="key">').css( "border-color",
242 relation_manager.relation_colors[index] ).text(typedef.name);
243 li_elm.append( $('<div>').attr('class', 'key_tip_container').append(
244 $('<div>').attr('class', 'key_tip').text(typedef.description) ) );
cfefd283 245 $('#keymaplist').append( li_elm );
56e3972e 246 });
247 // Now fetch the relationships themselves and add them to the graph
248 var rel_types = $.map( relationship_types, function(t) { return t.name });
249 // Save this list of names to the outer element data so that the relationship
250 // factory can access it
251 $('#keymap').data('relations', rel_types);
5f15640c 252 var textrelpath = getTextURL( 'relationships' );
56e3972e 253 $.getJSON( textrelpath, function(data) {
254 $.each(data, function( index, rel_info ) {
255 var type_index = $.inArray(rel_info.type, rel_types);
256 var source_found = get_ellipse( rel_info.source );
257 var target_found = get_ellipse( rel_info.target );
258 if( type_index != -1 && source_found.size() && target_found.size() ) {
259 var relation = relation_manager.create( rel_info.source, rel_info.target, type_index );
260 relation.data( 'type', rel_info.type );
261 relation.data( 'scope', rel_info.scope );
262 relation.data( 'note', rel_info.note );
30d0ba1e 263 if( editable ) {
264 var node_obj = get_node_obj(rel_info.source);
e538eccb 265 node_obj.set_selectable( false );
30d0ba1e 266 node_obj.ellipse.data( 'node_obj', null );
267 node_obj = get_node_obj(rel_info.target);
e538eccb 268 node_obj.set_selectable( false );
30d0ba1e 269 node_obj.ellipse.data( 'node_obj', null );
270 }
56e3972e 271 }
272 });
273 callback_fn.call();
274 });
b28e606e 275}
276
277function get_ellipse( node_id ) {
45ee3b96 278 return $( jq( node_id ) + ' ellipse');
b28e606e 279}
280
281function get_node_obj( node_id ) {
9529f69c 282 var node_ellipse = get_ellipse( node_id );
283 if( node_ellipse.data( 'node_obj' ) == null ) {
284 node_ellipse.data( 'node_obj', new node_obj(node_ellipse) );
285 };
286 return node_ellipse.data( 'node_obj' );
b28e606e 287}
288
b28e606e 289function node_obj(ellipse) {
290 this.ellipse = ellipse;
291 var self = this;
292
293 this.x = 0;
294 this.y = 0;
295 this.dx = 0;
296 this.dy = 0;
297 this.node_elements = node_elements_for(self.ellipse);
22a70299 298
b28e606e 299 this.get_id = function() {
45ee3b96 300 return $(self.ellipse).parent().attr('id')
b28e606e 301 }
302
e538eccb 303 this.set_selectable = function( clickable ) {
304 if( clickable && editable ) {
305 $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
306 $(self.ellipse).parent().hover( this.enter_node, this.leave_node );
307 $(self.ellipse).parent().mousedown( function(evt) { evt.stopPropagation() } );
308 $(self.ellipse).parent().click( function(evt) {
309 evt.stopPropagation();
310 if( $('ellipse[fill="#9999ff"]').size() > 0 ) {
311 $('ellipse[fill="#9999ff"]').each( function() {
312 $(this).data( 'node_obj' ).set_draggable( false );
313 } );
314 }
315 self.set_draggable( true )
316 });
317 } else {
318 $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
319 self.ellipse.siblings('text').attr('class', '');
320 $(self.ellipse).parent().unbind();
321 $('body').unbind('mousemove');
322 $('body').unbind('mouseup');
323 }
324 }
325
b28e606e 326 this.set_draggable = function( draggable ) {
30d0ba1e 327 if( draggable && editable ) {
e538eccb 328 $(self.ellipse).attr( {stroke:'black', fill:'#9999ff'} );
05485bfd 329 $(self.ellipse).parent().mousedown( this.mousedown_listener );
e538eccb 330 $(self.ellipse).parent().unbind( 'mouseenter' ).unbind( 'mouseleave' );
05485bfd 331 self.ellipse.siblings('text').attr('class', 'noselect draggable');
b28e606e 332 } else {
e538eccb 333 $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
05485bfd 334 self.ellipse.siblings('text').attr('class', '');
e538eccb 335 $(self.ellipse).parent().unbind( 'mousedown ');
336 $(self.ellipse).parent().mousedown( function(evt) { evt.stopPropagation() } );
337 $(self.ellipse).parent().hover( this.enter_node, this.leave_node );
b28e606e 338 }
339 }
340
341 this.mousedown_listener = function(evt) {
342 evt.stopPropagation();
343 self.x = evt.clientX;
344 self.y = evt.clientY;
345 $('body').mousemove( self.mousemove_listener );
346 $('body').mouseup( self.mouseup_listener );
05485bfd 347 $(self.ellipse).parent().unbind('mouseenter').unbind('mouseleave')
e538eccb 348 self.ellipse.attr( 'fill', '#6b6bb2' );
b28e606e 349 first_node_g_element = $("#svgenlargement g .node" ).filter( ":first" );
350 if( first_node_g_element.attr('id') !== self.get_g().attr('id') ) { self.get_g().insertBefore( first_node_g_element ) };
351 }
352
353 this.mousemove_listener = function(evt) {
9529f69c 354 self.dx = (evt.clientX - self.x) / mouse_scale;
355 self.dy = (evt.clientY - self.y) / mouse_scale;
b28e606e 356 self.move_elements();
05485bfd 357 evt.returnValue = false;
358 evt.preventDefault();
359 return false;
b28e606e 360 }
361
362 this.mouseup_listener = function(evt) {
363 if( $('ellipse[fill="#ffccff"]').size() > 0 ) {
45ee3b96 364 var source_node_id = $(self.ellipse).parent().attr('id');
05485bfd 365 var source_node_text = self.ellipse.siblings('text').text();
45ee3b96 366 var target_node_id = $('ellipse[fill="#ffccff"]').parent().attr('id');
05485bfd 367 var target_node_text = $('ellipse[fill="#ffccff"]').siblings("text").text();
b28e606e 368 $('#source_node_id').val( source_node_id );
05485bfd 369 $('#source_node_text').val( source_node_text );
b28e606e 370 $('#target_node_id').val( target_node_id );
05485bfd 371 $('#target_node_text').val( target_node_text );
b28e606e 372 $('#dialog-form').dialog( 'open' );
373 };
374 $('body').unbind('mousemove');
375 $('body').unbind('mouseup');
e538eccb 376 self.ellipse.attr( 'fill', '#9999ff' );
9529f69c 377 self.reset_elements();
b28e606e 378 }
f2fb96fc 379
b28e606e 380 this.cpos = function() {
381 return { x: self.ellipse.attr('cx'), y: self.ellipse.attr('cy') };
382 }
383
384 this.get_g = function() {
385 return self.ellipse.parent('g');
386 }
387
388 this.enter_node = function(evt) {
389 self.ellipse.attr( 'fill', '#ffccff' );
390 }
391
392 this.leave_node = function(evt) {
393 self.ellipse.attr( 'fill', '#fff' );
394 }
395
396 this.greyout_edges = function() {
397 $.each( self.node_elements, function(index, value) {
398 value.grey_out('.edge');
399 });
400 }
401
402 this.ungreyout_edges = function() {
403 $.each( self.node_elements, function(index, value) {
404 value.un_grey_out('.edge');
405 });
406 }
407
6c8d1880 408 this.reposition = function( dx, dy ) {
409 $.each( self.node_elements, function(index, value) {
410 value.reposition( dx, dy );
411 } );
412 }
413
b28e606e 414 this.move_elements = function() {
415 $.each( self.node_elements, function(index, value) {
6c8d1880 416 value.move( self.dx, self.dy );
22a70299 417 } );
b28e606e 418 }
419
420 this.reset_elements = function() {
421 $.each( self.node_elements, function(index, value) {
6c8d1880 422 value.reset();
22a70299 423 } );
b28e606e 424 }
425
426 this.update_elements = function() {
427 self.node_elements = node_elements_for(self.ellipse);
428 }
429
a84ca4de 430 this.get_witnesses = function() {
431 return readingdata[self.get_id()].witnesses
432 }
6c8d1880 433
e538eccb 434 self.set_selectable( true );
b28e606e 435}
436
437function svgshape( shape_element ) {
438 this.shape = shape_element;
6c8d1880 439 this.reposx = 0;
440 this.reposy = 0;
441 this.repositioned = this.shape.parent().data( 'repositioned' );
442 if( this.repositioned != null ) {
443 this.reposx = this.repositioned[0];
444 this.reposy = this.repositioned[1];
445 }
446 this.reposition = function (dx, dy) {
447 this.move( dx, dy );
448 this.reposx = this.reposx + dx;
449 this.reposy = this.reposy + dy;
450 this.shape.parent().data( 'repositioned', [this.reposx,this.reposy] );
451 }
b28e606e 452 this.move = function(dx,dy) {
6c8d1880 453 this.shape.attr( "transform", "translate( " + (this.reposx + dx) + " " + (this.reposy + dy) + " )" );
b28e606e 454 }
455 this.reset = function() {
6c8d1880 456 this.shape.attr( "transform", "translate( " + this.reposx + " " + this.reposy + " )" );
b28e606e 457 }
458 this.grey_out = function(filter) {
459 if( this.shape.parent(filter).size() != 0 ) {
460 this.shape.attr({'stroke':'#e5e5e5', 'fill':'#e5e5e5'});
461 }
462 }
463 this.un_grey_out = function(filter) {
464 if( this.shape.parent(filter).size() != 0 ) {
465 this.shape.attr({'stroke':'#000000', 'fill':'#000000'});
466 }
467 }
468}
469
470function svgpath( path_element, svg_element ) {
471 this.svg_element = svg_element;
472 this.path = path_element;
473 this.x = this.path.x;
474 this.y = this.path.y;
6c8d1880 475
476 this.reposition = function (dx, dy) {
477 this.x = this.x + dx;
478 this.y = this.y + dy;
479 this.path.x = this.x;
480 this.path.y = this.y;
481 }
482
b28e606e 483 this.move = function(dx,dy) {
484 this.path.x = this.x + dx;
485 this.path.y = this.y + dy;
486 }
6c8d1880 487
b28e606e 488 this.reset = function() {
489 this.path.x = this.x;
490 this.path.y = this.y;
491 }
6c8d1880 492
b28e606e 493 this.grey_out = function(filter) {
494 if( this.svg_element.parent(filter).size() != 0 ) {
495 this.svg_element.attr('stroke', '#e5e5e5');
496 this.svg_element.siblings('text').attr('fill', '#e5e5e5');
05485bfd 497 this.svg_element.siblings('text').attr('class', 'noselect');
b28e606e 498 }
499 }
500 this.un_grey_out = function(filter) {
501 if( this.svg_element.parent(filter).size() != 0 ) {
502 this.svg_element.attr('stroke', '#000000');
503 this.svg_element.siblings('text').attr('fill', '#000000');
05485bfd 504 this.svg_element.siblings('text').attr('class', '');
b28e606e 505 }
506 }
507}
508
509function node_elements_for( ellipse ) {
510 node_elements = get_edge_elements_for( ellipse );
511 node_elements.push( new svgshape( ellipse.siblings('text') ) );
512 node_elements.push( new svgshape( ellipse ) );
513 return node_elements;
514}
515
516function get_edge_elements_for( ellipse ) {
517 edge_elements = new Array();
45ee3b96 518 node_id = ellipse.parent().attr('id');
b28e606e 519 edge_in_pattern = new RegExp( node_id + '$' );
22a70299 520 edge_out_pattern = new RegExp( '^' + node_id + '-' );
b28e606e 521 $.each( $('#svgenlargement .edge,#svgenlargement .relation').children('title'), function(index) {
522 title = $(this).text();
523 if( edge_in_pattern.test(title) ) {
524 polygon = $(this).siblings('polygon');
525 if( polygon.size() > 0 ) {
526 edge_elements.push( new svgshape( polygon ) );
527 }
528 path_segments = $(this).siblings('path')[0].pathSegList;
529 edge_elements.push( new svgpath( path_segments.getItem(path_segments.numberOfItems - 1), $(this).siblings('path') ) );
530 }
531 if( edge_out_pattern.test(title) ) {
532 path_segments = $(this).siblings('path')[0].pathSegList;
533 edge_elements.push( new svgpath( path_segments.getItem(0), $(this).siblings('path') ) );
534 }
535 });
536 return edge_elements;
537}
538
539function relation_factory() {
540 var self = this;
541 this.color_memo = null;
542 //TODO: colors hard coded for now
543 this.temp_color = '#FFA14F';
544 this.relation_colors = [ "#5CCCCC", "#67E667", "#F9FE72", "#6B90D4", "#FF7673", "#E467B3", "#AA67D5", "#8370D8", "#FFC173" ];
545
546 this.create_temporary = function( source_node_id, target_node_id ) {
45ee3b96 547 var relation_id = get_relation_id( source_node_id, target_node_id );
548 var relation = $( jq( relation_id ) );
9529f69c 549 if( relation.size() == 0 ) {
b28e606e 550 draw_relation( source_node_id, target_node_id, self.temp_color );
551 } else {
552 self.color_memo = relation.children('path').attr( 'stroke' );
553 relation.children('path').attr( 'stroke', self.temp_color );
554 }
555 }
556 this.remove_temporary = function() {
557 var path_element = $('#svgenlargement .relation').children('path[stroke="' + self.temp_color + '"]');
558 if( self.color_memo != null ) {
559 path_element.attr( 'stroke', self.color_memo );
560 self.color_memo = null;
561 } else {
9529f69c 562 var temporary = path_element.parent('g').remove();
563 temporary.empty();
564 temporary = null;
b28e606e 565 }
566 }
567 this.create = function( source_node_id, target_node_id, color_index ) {
568 //TODO: Protect from (color_)index out of bound..
569 var relation_color = self.relation_colors[ color_index ];
9529f69c 570 var relation = draw_relation( source_node_id, target_node_id, relation_color );
571 get_node_obj( source_node_id ).update_elements();
572 get_node_obj( target_node_id ).update_elements();
573 return relation;
b28e606e 574 }
9529f69c 575 this.toggle_active = function( relation_id ) {
45ee3b96 576 var relation = $( jq( relation_id ) );
9529f69c 577 var relation_path = relation.children('path');
578 if( !relation.data( 'active' ) ) {
579 relation_path.css( {'cursor':'pointer'} );
580 relation_path.mouseenter( function(event) {
581 outerTimer = setTimeout( function() {
582 timer = setTimeout( function() {
45ee3b96 583 var related_nodes = get_related_nodes( relation_id );
584 var source_node_id = related_nodes[0];
585 var target_node_id = related_nodes[1];
9529f69c 586 $('#delete_source_node_id').val( source_node_id );
587 $('#delete_target_node_id').val( target_node_id );
588 self.showinfo(relation);
589 }, 500 )
590 }, 1000 );
591 });
592 relation_path.mouseleave( function(event) {
593 clearTimeout(outerTimer);
594 if( timer != null ) { clearTimeout(timer); }
595 });
596 relation.data( 'active', true );
597 } else {
598 relation_path.unbind( 'mouseenter' );
599 relation_path.unbind( 'mouseleave' );
600 relation_path.css( {'cursor':'inherit'} );
601 relation.data( 'active', false );
602 }
603 }
604 this.showinfo = function(relation) {
088a14af 605 $('#delete_relation_type').text( relation.data('type') );
606 $('#delete_relation_scope').text( relation.data('scope') );
69a19c91 607 if( relation.data( 'note' ) ) {
088a14af 608 $('#delete_relation_note').text('note: ' + relation.data( 'note' ) );
69a19c91 609 }
9529f69c 610 var points = relation.children('path').attr('d').slice(1).replace('C',' ').split(' ');
611 var xs = parseFloat( points[0].split(',')[0] );
612 var xe = parseFloat( points[1].split(',')[0] );
613 var ys = parseFloat( points[0].split(',')[1] );
614 var ye = parseFloat( points[3].split(',')[1] );
615 var p = svg_root.createSVGPoint();
616 p.x = xs + ((xe-xs)*1.1);
617 p.y = ye - ((ye-ys)/2);
76f05423 618 var ctm = svg_root_element.getScreenCTM();
9529f69c 619 var nx = p.matrixTransform(ctm).x;
620 var ny = p.matrixTransform(ctm).y;
621 var dialog_aria = $ ("div[aria-labelledby='ui-dialog-title-delete-form']");
622 $('#delete-form').dialog( 'open' );
623 dialog_aria.offset({ left: nx, top: ny });
624 }
625 this.remove = function( relation_id ) {
30d0ba1e 626 if( !editable ) {
627 return;
628 }
45ee3b96 629 var relation = $( jq( relation_id ) );
9529f69c 630 relation.remove();
b28e606e 631 }
632}
633
45ee3b96 634// Utility function to create/return the ID of a relation link between
635// a source and target.
636function get_relation_id( source_id, target_id ) {
637 var idlist = [ source_id, target_id ];
638 idlist.sort();
639 return 'relation-' + idlist[0] + '-...-' + idlist[1];
640}
641
642function get_related_nodes( relation_id ) {
643 var srctotarg = relation_id.substr( 9 );
644 return srctotarg.split('-...-');
645}
646
b28e606e 647function draw_relation( source_id, target_id, relation_color ) {
9529f69c 648 var source_ellipse = get_ellipse( source_id );
649 var target_ellipse = get_ellipse( target_id );
45ee3b96 650 var relation_id = get_relation_id( source_id, target_id );
9529f69c 651 var svg = $('#svgenlargement').children('svg').svg().svg('get');
652 var path = svg.createPath();
653 var sx = parseInt( source_ellipse.attr('cx') );
654 var rx = parseInt( source_ellipse.attr('rx') );
655 var sy = parseInt( source_ellipse.attr('cy') );
656 var ex = parseInt( target_ellipse.attr('cx') );
657 var ey = parseInt( target_ellipse.attr('cy') );
9231663d 658 var relation = svg.group( $("#svgenlargement svg g"), { 'class':'relation', 'id':relation_id } );
9529f69c 659 svg.title( relation, source_id + '->' + target_id );
660 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 661 var relation_element = $('#svgenlargement .relation').filter( ':last' );
662 relation_element.insertBefore( $('#svgenlargement g g').filter(':first') );
9529f69c 663 return relation_element;
b28e606e 664}
665
5fe117bc 666function detach_node( readings ) {
217f5e64 667 // separate out the deleted relationships, discard for now
b6f3476b 668 if( 'DELETED' in readings ) {
669 // Remove each of the deleted relationship links.
670 $.each( readings['DELETED'], function( idx, pair ) {
671 var relation_id = get_relation_id( pair[0], pair[1] );
672 var relation = $( jq( relation_id ) );
673 if( relation.size() == 0 ) {
674 relation_id = get_relation_id( pair[1], pair[0] );
675 }
676 relation_manager.remove( relation_id );
677 });
678 delete readings['DELETED'];
679 }
a471cb0f 680 // add new node(s)
681 $.extend( readingdata, readings );
682 // remove from existing readings the witnesses for the new nodes/readings
683 $.each( readings, function( node_id, reading ) {
684 $.each( reading.witnesses, function( index, witness ) {
685 var witnesses = readingdata[ reading.orig_rdg ].witnesses;
686 readingdata[ reading.orig_rdg ].witnesses = $.removeFromArray( witness, witnesses );
687 } );
688 } );
689
a471cb0f 690 detached_edges = [];
8cd2e785 691
692 // here we detach witnesses from the existing edges accoring to what's being relayed by readings
a471cb0f 693 $.each( readings, function( node_id, reading ) {
694 var edges = edges_of( get_ellipse( reading.orig_rdg ) );
695 incoming_remaining = [];
696 outgoing_remaining = [];
697 $.each( reading.witnesses, function( index, witness ) {
698 incoming_remaining.push( witness );
699 outgoing_remaining.push( witness );
700 } );
701 $.each( edges, function( index, edge ) {
702 detached_edge = edge.detach_witnesses( reading.witnesses );
703 if( detached_edge != null ) {
704 detached_edges.push( detached_edge );
705 $.each( detached_edge.witnesses, function( index, witness ) {
706 if( detached_edge.is_incoming == true ) {
707 incoming_remaining = $.removeFromArray( witness, incoming_remaining );
708 } else {
709 outgoing_remaining = $.removeFromArray( witness, outgoing_remaining );
710 }
711 } );
712 }
713 } );
8cd2e785 714
60c66cd2 715 // After detaching we still need to check if for *all* readings
8cd2e785 716 // an edge was detached. It may be that a witness was not
717 // explicitly named on an edge but was part of a 'majority' edge
718 // in which case we need to duplicate and name that edge after those
719 // remaining witnesses.
a471cb0f 720 if( outgoing_remaining.length > 0 ) {
a471cb0f 721 $.each( edges, function( index, edge ) {
a471cb0f 722 if( edge.get_label() == 'majority' && !edge.is_incoming ) {
723 detached_edges.push( edge.clone_for( outgoing_remaining ) );
724 }
725 } );
726 }
727 if( incoming_remaining.length > 0 ) {
a471cb0f 728 $.each( edges, function( index, edge ) {
729 if( edge.get_label() == 'majority' && edge.is_incoming ) {
dc8a13bd 730 detached_edges.push( edge.clone_for( incoming_remaining ) );
a471cb0f 731 }
732 } );
733 }
60c66cd2 734
22a70299 735 // Finally multiple selected nodes may share edges
736 var copy_array = [];
737 $.each( detached_edges, function( index, edge ) {
738 var do_copy = true;
739 $.each( copy_array, function( index, copy_edge ) {
740 if( copy_edge.g_elem.attr( 'id' ) == edge.g_elem.attr( 'id' ) ) { do_copy = false }
741 } );
742 if( do_copy == true ) {
743 copy_array.push( edge );
744 }
745 } );
746 detached_edges = copy_array;
747
60c66cd2 748 // Lots of unabstracted knowledge down here :/
749 // Clone original node/reading, rename/id it..
750 duplicate_node = get_ellipse( reading.orig_rdg ).parent().clone();
751 duplicate_node.attr( 'id', node_id );
752 duplicate_node.children( 'title' ).text( node_id );
6c8d1880 753
754 // This needs somehow to move to node or even to shapes! #repositioned
755 duplicate_node_data = get_ellipse( reading.orig_rdg ).parent().data( 'repositioned' );
22a70299 756 if( duplicate_node_data != null ) {
6c8d1880 757 duplicate_node.children( 'ellipse' ).parent().data( 'repositioned', duplicate_node_data );
22a70299 758 }
60c66cd2 759
760 // Add the node and all new edges into the graph
931ed236 761 var graph_root = $('#svgenlargement svg g.graph');
60c66cd2 762 graph_root.append( duplicate_node );
763 $.each( detached_edges, function( index, edge ) {
dc8a13bd 764 id_suffix = node_id.slice( node_id.indexOf( '_' ) );
765 edge.g_elem.attr( 'id', ( edge.g_elem.attr( 'id' ) + id_suffix ) );
60c66cd2 766 edge_title = edge.g_elem.children( 'title' ).text();
22a70299 767 edge_weight = 0.8 + ( 0.2 * edge.witnesses.length );
60c66cd2 768 edge_title = edge_title.replace( reading.orig_rdg, node_id );
769 edge.g_elem.children( 'title' ).text( edge_title );
22a70299 770 edge.g_elem.children( 'path').attr( 'stroke-width', edge_weight );
60c66cd2 771 // Reg unabstracted knowledge: isn't it more elegant to make
772 // it edge.append_to( graph_root )?
773 graph_root.append( edge.g_elem );
774 } );
22a70299 775
776 // Make the detached node a real node_obj
777 var ellipse_elem = get_ellipse( node_id );
778 var new_node = new node_obj( ellipse_elem );
779 ellipse_elem.data( 'node_obj', new_node );
780
60c66cd2 781 // Move the node somewhat up for 'dramatic effect' :-p
9231663d 782 new_node.reposition( 0, -70 );
60c66cd2 783
a471cb0f 784 } );
60c66cd2 785
9231663d 786}
a471cb0f 787
9231663d 788function merge_nodes( source_node_id, target_node_id, consequences ) {
789 if( consequences.status != null && consequences.status == 'ok' ) {
790 merge_node( source_node_id, target_node_id );
791 if( consequences.checkalign != null ) {
792 $.each( consequences.checkalign, function( index, node_ids ) {
0c4354f6 793 var temp_relation = draw_relation( node_ids[0], node_ids[1], "#89a02c" );
9231663d 794 var sy = parseInt( temp_relation.children('path').attr('d').split('C')[0].split(',')[1] );
795 var ey = parseInt( temp_relation.children('path').attr('d').split(' ')[2].split(',')[1] );
796 var yC = ey + (( sy - ey )/2);
797 // TODO: compute xC to be always the same distance to the amplitude of the curve
798 var xC = parseInt( temp_relation.children('path').attr('d').split(' ')[1].split(',')[0] );
799 var svg = $('#svgenlargement').children('svg').svg('get');
800 parent_g = svg.group( $('#svgenlargement svg g') );
801 var ids_text = node_ids[0] + '-' + node_ids[1];
802 var merge_id = 'merge-' + ids_text;
48156ccd 803 svg.image( parent_g, xC, (yC-8), 16, 16, merge_button_yes, { id: merge_id } );
804 svg.image( parent_g, (xC+20), (yC-8), 16, 16, merge_button_no, { id: 'no' + merge_id } );
9231663d 805 $( '#' + merge_id ).hover( function(){ $(this).addClass( 'draggable' ) }, function(){ $(this).removeClass( 'draggable' ) } );
806 $( '#no' + merge_id ).hover( function(){ $(this).addClass( 'draggable' ) }, function(){ $(this).removeClass( 'draggable' ) } );
807 $( '#' + merge_id ).click( function( evt ){
808 merge_node( node_ids[0], node_ids[1] );
809 temp_relation.remove();
810 $( '#' + merge_id ).parent().remove();
759f1868 811 //notify backend
812 var ncpath = getTextURL( 'merge' );
aaf27b2e 813 var form_values = "source_id=" + node_ids[0] + "&target_id=" + node_ids[1] + "&single=true";
759f1868 814 $.post( ncpath, form_values );
9231663d 815 } );
816 $( '#no' + merge_id ).click( function( evt ) {
817 temp_relation.remove();
818 $( '#' + merge_id ).parent().remove();
819 } );
820 } );
821 }
822 }
823}
824
825function merge_node( source_node_id, target_node_id ) {
826 $.each( edges_of( get_ellipse( source_node_id ) ), function( index, edge ) {
827 if( edge.is_incoming == true ) {
828 edge.attach_endpoint( target_node_id );
829 } else {
830 edge.attach_startpoint( target_node_id );
831 }
832 } );
833 $( jq( source_node_id ) ).remove();
a471cb0f 834}
835
c1add777 836function Marquee() {
837
838 var self = this;
839
f6516f22 840 this.x = 0;
841 this.y = 0;
842 this.dx = 0;
843 this.dy = 0;
c1add777 844 this.enlargementOffset = $('#svgenlargement').offset();
845 this.svg_rect = $('#svgenlargement svg').svg('get');
846
847 this.show = function( event ) {
f6516f22 848 self.x = event.clientX;
849 self.y = event.clientY;
c1add777 850 p = svg_root.createSVGPoint();
851 p.x = event.clientX - self.enlargementOffset.left;
852 p.y = event.clientY - self.enlargementOffset.top;
c1add777 853 self.svg_rect.rect( p.x, p.y, 0, 0, { fill: 'black', 'fill-opacity': '0.1', stroke: 'black', 'stroke-dasharray': '4,2', strokeWidth: '0.02em', id: 'marquee' } );
854 };
855
856 this.expand = function( event ) {
f6516f22 857 self.dx = (event.clientX - self.x);
858 self.dy = (event.clientY - self.y);
c1add777 859 var rect = $('#marquee');
f6516f22 860 if( rect.length != 0 ) {
861 var rect_w = Math.abs( self.dx );
862 var rect_h = Math.abs( self.dy );
863 var rect_x = self.x - self.enlargementOffset.left;
864 var rect_y = self.y - self.enlargementOffset.top;
865 if( self.dx < 0 ) { rect_x = rect_x - rect_w }
866 if( self.dy < 0 ) { rect_y = rect_y - rect_h }
867 rect.attr("x", rect_x).attr("y", rect_y).attr("width", rect_w).attr("height", rect_h);
c1add777 868 }
869 };
870
a84ca4de 871 this.select = function() {
c1add777 872 var rect = $('#marquee');
873 if( rect.length != 0 ) {
e538eccb 874 //unselect any possible selected first
22a70299 875 //TODO: unless SHIFT?
e538eccb 876 if( $('ellipse[fill="#9999ff"]').size() > 0 ) {
877 $('ellipse[fill="#9999ff"]').each( function() {
878 $(this).data( 'node_obj' ).set_draggable( false );
879 } );
880 }
881 //compute dimension of marquee
c1add777 882 var left = $('#marquee').offset().left;
883 var top = $('#marquee').offset().top;
884 var right = left + parseInt( $('#marquee').attr( 'width' ) );
885 var bottom = top + parseInt( $('#marquee').attr( 'height' ) );
886 var tf = svg_root_element.getScreenCTM().inverse();
887 var p = svg_root.createSVGPoint();
888 p.x=left;
889 p.y=top;
890 var cx_min = p.matrixTransform(tf).x;
891 var cy_min = p.matrixTransform(tf).y;
892 p.x=right;
893 p.y=bottom;
894 var cx_max = p.matrixTransform(tf).x;
895 var cy_max = p.matrixTransform(tf).y;
e538eccb 896 //select any node with its center inside the marquee
5fe117bc 897 var readings = [];
e538eccb 898 //also merge witness sets from nodes
a84ca4de 899 var witnesses = [];
c1add777 900 $('#svgenlargement ellipse').each( function( index ) {
901 var cx = parseInt( $(this).attr('cx') );
902 var cy = parseInt( $(this).attr('cy') );
6c8d1880 903
904 // This needs somehow to move to node or even to shapes! #repositioned
905 // We should ask something more aling the lines of: nodes.each { |item| node.selected? }
906 var org_translate = $(this).parent().data( 'repositioned' );
22a70299 907 if( org_translate != null ) {
908 cx = cx + org_translate[0];
909 cy = cy + org_translate[1];
910 }
6c8d1880 911
c1add777 912 if( cx > cx_min && cx < cx_max) {
913 if( cy > cy_min && cy < cy_max) {
914 // we actually heve no real 'selected' state for nodes, except coloring
e538eccb 915 $(this).attr( 'fill', '#9999ff' );
5fe117bc 916 // Take note of the selected reading(s) and applicable witness(es)
917 // so we can populate the multipleselect-form
918 readings.push( $(this).parent().attr('id') );
a84ca4de 919 var this_witnesses = $(this).data( 'node_obj' ).get_witnesses();
920 witnesses = arrayUnique( witnesses.concat( this_witnesses ) );
c1add777 921 }
922 }
923 });
e538eccb 924 if( $('ellipse[fill="#9999ff"]').size() > 0 ) {
5fe117bc 925 //add intersection of witnesses sets to the multi select form and open it
926 $('#detach_collated_form').empty();
927 $.each( readings, function( index, value ) {
928 $('#detach_collated_form').append( $('<input>').attr(
929 "type", "hidden").attr("name", "readings[]").attr(
930 "value", value ) );
931 });
932 $.each( witnesses, function( index, value ) {
933 $('#detach_collated_form').append(
934 '<input type="checkbox" name="witnesses[]" value="' + value
935 + '">' + value + '<br>' );
a84ca4de 936 });
5fe117bc 937 $('#multiple_selected_readings').attr('value', readings.join(',') );
a84ca4de 938 $('#multipleselect-form').dialog( 'open' );
939 }
c1add777 940 self.svg_rect.remove( $('#marquee') );
941 }
942 };
943
f6516f22 944 this.unselect = function() {
e538eccb 945 $('ellipse[fill="#9999ff"]').attr( 'fill', '#fff' );
f6516f22 946 }
947
c1add777 948}
949
b001c73d 950function readings_equivalent( source, target ) {
951 var sourcetext = readingdata[source].text;
952 var targettext = readingdata[target].text;
953 if( sourcetext === targettext ) {
954 return true;
955 }
956 // Lowercase and strip punctuation from both and compare again
957 var stlc = sourcetext.toLowerCase().replace(/[^\w\s]|_/g, "");
958 var ttlc = targettext.toLowerCase().replace(/[^\w\s]|_/g, "");
959 if( stlc === ttlc ) {
960 return true;
961 }
962 return false;
963}
964
9529f69c 965
b28e606e 966$(document).ready(function () {
9529f69c 967
968 timer = null;
b28e606e 969 relation_manager = new relation_factory();
970
c1add777 971 $('#update_workspace_button').data('locked', false);
b001c73d 972
973 // Set up the mouse events on the SVG enlargement
9529f69c 974 $('#enlargement').mousedown(function (event) {
b28e606e 975 $(this)
9529f69c 976 .data('down', true)
977 .data('x', event.clientX)
978 .data('y', event.clientY)
979 .data('scrollLeft', this.scrollLeft)
c1add777 980 stateTf = svg_root_element.getCTM().inverse();
981 var p = svg_root.createSVGPoint();
982 p.x = event.clientX;
983 p.y = event.clientY;
984 stateOrigin = p.matrixTransform(stateTf);
985
986 // Activate marquee if in interaction mode
987 if( $('#update_workspace_button').data('locked') == true ) { marquee.show( event ) };
988
989 event.returnValue = false;
990 event.preventDefault();
991 return false;
b28e606e 992 }).mouseup(function (event) {
a84ca4de 993 marquee.select();
c1add777 994 $(this).data('down', false);
b28e606e 995 }).mousemove(function (event) {
9529f69c 996 if( timer != null ) { clearTimeout(timer); }
997 if ( ($(this).data('down') == true) && ($('#update_workspace_button').data('locked') == false) ) {
998 var p = svg_root.createSVGPoint();
999 p.x = event.clientX;
1000 p.y = event.clientY;
1001 p = p.matrixTransform(stateTf);
1002 var matrix = stateTf.inverse().translate(p.x - stateOrigin.x, p.y - stateOrigin.y);
1003 var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
76f05423 1004 svg_root_element.setAttribute("transform", s);
b28e606e 1005 }
c1add777 1006 marquee.expand( event );
76f05423 1007 event.returnValue = false;
1008 event.preventDefault();
b28e606e 1009 }).mousewheel(function (event, delta) {
9529f69c 1010 event.returnValue = false;
1011 event.preventDefault();
1012 if ( $('#update_workspace_button').data('locked') == false ) {
76f05423 1013 if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
1014 if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
9529f69c 1015 if( delta < -9 ) { delta = -9 };
1016 var z = 1 + delta/10;
76f05423 1017 z = delta > 0 ? 1 : -1;
1018 var g = svg_root_element;
1019 if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 100))) {
9529f69c 1020 var root = svg_root;
1021 var p = root.createSVGPoint();
76f05423 1022 p.x = event.originalEvent.clientX;
1023 p.y = event.originalEvent.clientY;
9529f69c 1024 p = p.matrixTransform(g.getCTM().inverse());
76f05423 1025 var scaleLevel = 1+(z/20);
1026 var k = root.createSVGMatrix().translate(p.x, p.y).scale(scaleLevel).translate(-p.x, -p.y);
9529f69c 1027 var matrix = g.getCTM().multiply(k);
1028 var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
1029 g.setAttribute("transform", s);
1030 }
1031 }
b28e606e 1032 }).css({
1033 'overflow' : 'hidden',
1034 'cursor' : '-moz-grab'
1035 });
1036
c1add777 1037
b001c73d 1038 // Set up the relationship creation dialog. This also functions as the reading
1039 // merge dialog where appropriate.
b001c73d 1040
30d0ba1e 1041 if( editable ) {
9231663d 1042 $( '#dialog-form' ).dialog( {
30d0ba1e 1043 autoOpen: false,
1044 height: 270,
1045 width: 290,
1046 modal: true,
1047 buttons: {
9231663d 1048 'Merge readings': function( evt ) {
1049 $( evt.target ).button( 'disable' );
1050 $( '#status' ).empty();
1051 form_values = $( '#collapse_node_form' ).serialize();
b001c73d 1052 ncpath = getTextURL( 'merge' );
9231663d 1053 var jqjson = $.post( ncpath, form_values, function( data ) {
1054 merge_nodes( $( '#source_node_id' ).val(), $( '#target_node_id' ).val(), data );
bfb6d17f 1055 $(evt.target).button( 'enable' );
9231663d 1056 $( '#dialog-form' ).dialog( 'close' );
1057 } );
b001c73d 1058 },
1059 OK: function( evt ) {
9231663d 1060 $( evt.target ).button( 'disable' );
1061 $( '#status' ).empty();
1062 form_values = $( '#collapse_node_form' ).serialize();
30d0ba1e 1063 ncpath = getTextURL( 'relationships' );
9231663d 1064 var jqjson = $.post( ncpath, form_values, function( data ) {
1065 $.each( data, function( item, source_target ) {
30d0ba1e 1066 var source_found = get_ellipse( source_target[0] );
1067 var target_found = get_ellipse( source_target[1] );
9231663d 1068 var relation_found = $.inArray( source_target[2], $( '#keymap' ).data( 'relations' ) );
30d0ba1e 1069 if( source_found.size() && target_found.size() && relation_found > -1 ) {
1070 var relation = relation_manager.create( source_target[0], source_target[1], relation_found );
eeea8fb6 1071 relation.data( 'type', source_target[2] );
7b54e481 1072 relation.data( 'scope', $('#scope :selected').text() );
1073 relation.data( 'note', $('#note').val() );
45ee3b96 1074 relation_manager.toggle_active( relation.attr('id') );
7b54e481 1075 }
9231663d 1076 $(evt.target).button( 'enable' );
30d0ba1e 1077 });
9231663d 1078 $( '#dialog-form' ).dialog( 'close' );
30d0ba1e 1079 }, 'json' );
1080 },
1081 Cancel: function() {
9231663d 1082 $( this ).dialog( 'close' );
30d0ba1e 1083 }
1084 },
1085 create: function(event, ui) {
1086 $(this).data( 'relation_drawn', false );
a166dca8 1087 $('#rel_type').data( 'changed_after_open', false );
56e3972e 1088 $.each( relationship_types, function(index, typedef) {
1089 $('#rel_type').append( $('<option />').attr( "value", typedef.name ).text(typedef.name) );
1090 });
1091 $.each( relationship_scopes, function(index, value) {
1092 $('#scope').append( $('<option />').attr( "value", value ).text(value) );
a166dca8 1093 });
1094 // Handler to clear the annotation field, the first time the relationship is
1095 // changed after opening the form.
1096 $('#rel_type').change( function () {
1097 if( !$(this).data( 'changed_after_open' ) ) {
1098 $('#note').val('');
1099 }
1100 $(this).data( 'changed_after_open', true );
1101 });
30d0ba1e 1102 },
1103 open: function() {
b001c73d 1104 relation_manager.create_temporary(
1105 $('#source_node_id').val(), $('#target_node_id').val() );
1106 var buttonset = $(this).parent().find( '.ui-dialog-buttonset' )
1107 if( readings_equivalent( $('#source_node_id').val(),
1108 $('#target_node_id').val() ) ) {
1109 buttonset.find( "button:contains('Merge readings')" ).show();
1110 } else {
1111 buttonset.find( "button:contains('Merge readings')" ).hide();
1112 }
30d0ba1e 1113 $(".ui-widget-overlay").css("background", "none");
1114 $("#dialog_overlay").show();
1115 $("#dialog_overlay").height( $("#enlargement_container").height() );
1116 $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
1117 $("#dialog_overlay").offset( $("#enlargement_container").offset() );
a166dca8 1118 $('#rel_type').data( 'changed_after_open', false );
30d0ba1e 1119 },
1120 close: function() {
1121 relation_manager.remove_temporary();
1122 $( '#status' ).empty();
1123 $("#dialog_overlay").hide();
1124 }
1125 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
21e6ebc7 1126 if( ajaxSettings.url == getTextURL('relationships')
1127 && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
1128 var error;
1129 if( jqXHR.responseText.indexOf('do not have permission to modify') > -1 ) {
1130 error = 'You are not authorized to modify this tradition. (Try logging in again?)';
1131 } else {
1132 try {
1133 var errobj = jQuery.parseJSON( jqXHR.responseText );
1134 error = errobj.error + '</br>The relationship cannot be made.</p>';
1135 } catch(e) {
1136 error = jqXHR.responseText;
1137 }
1138 }
1139 $('#status').append( '<p class="error">Error: ' + error );
1140 }
1141 $(event.target).parent().find('.ui-button').button("enable");
30d0ba1e 1142 } );
1143 }
b28e606e 1144
b001c73d 1145 // Set up the relationship info display and deletion dialog.
9529f69c 1146 $( "#delete-form" ).dialog({
1147 autoOpen: false,
69a19c91 1148 height: 135,
088a14af 1149 width: 250,
9529f69c 1150 modal: false,
b001c73d 1151 buttons: {
1152 OK: function() { $( this ).dialog( "close" ); },
1153 "Delete all": function () { delete_relation( true ); },
1154 Delete: function() { delete_relation( false ); }
1155 },
9529f69c 1156 create: function(event, ui) {
30d0ba1e 1157 // TODO What is this logic doing?
a84ca4de 1158 // This scales the buttons in the dialog and makes it look proper
1159 // Not sure how essential it is, does anything break if it's not here?
9529f69c 1160 var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
b001c73d 1161 buttonset.find( "button:contains('OK')" ).css( 'float', 'right' );
a84ca4de 1162 // A: This makes sure that the pop up delete relation dialogue for a hovered over
1163 // relation auto closes if the user doesn't engage (mouseover) with it.
9529f69c 1164 var dialog_aria = $("div[aria-labelledby='ui-dialog-title-delete-form']");
1165 dialog_aria.mouseenter( function() {
1166 if( mouseWait != null ) { clearTimeout(mouseWait) };
1167 })
1168 dialog_aria.mouseleave( function() {
1169 mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
1170 })
1171 },
1172 open: function() {
b001c73d 1173 // Show the appropriate buttons...
1174 var buttonset = $(this).parent().find( '.ui-dialog-buttonset' )
1175 // If the user can't edit, show only the OK button
088a14af 1176 if( !editable ) {
b001c73d 1177 buttonset.find( "button:contains('Delete')" ).hide();
1178 // If the relationship scope is local, show only OK and Delete
088a14af 1179 } else if( $('#delete_relation_scope').text() === 'local' ) {
1180 $( this ).dialog( "option", "width", 160 );
b001c73d 1181 buttonset.find( "button:contains('Delete')" ).show();
1182 buttonset.find( "button:contains('Delete all')" ).hide();
1183 // Otherwise, show all three
088a14af 1184 } else {
1185 $( this ).dialog( "option", "width", 200 );
b001c73d 1186 buttonset.find( "button:contains('Delete')" ).show();
088a14af 1187 }
9529f69c 1188 mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
1189 },
088a14af 1190 close: function() {}
9529f69c 1191 });
1192
a84ca4de 1193 $( "#multipleselect-form" ).dialog({
1194 autoOpen: false,
1195 height: 150,
1196 width: 250,
1197 modal: true,
5fe117bc 1198 buttons: {
22a70299 1199 Cancel: function() { $( this ).dialog( "close" ); },
1200 Detach: function ( evt ) {
1201 var self = $(this);
1202 $( evt.target ).button( "disable" );
1203 var form_values = $('#detach_collated_form').serialize();
1204 ncpath = getTextURL( 'duplicate' );
1205 var jqjson = $.post( ncpath, form_values, function(data) {
1206 detach_node( data );
1207 $(evt.target).button("enable");
1208 self.dialog( "close" );
1209 } );
1210 }
7ef4a584 1211 },
1212 create: function(event, ui) {
a84ca4de 1213 var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
1214 buttonset.find( "button:contains('Cancel')" ).css( 'float', 'right' );
1215 },
1216 open: function() {
1217 $( this ).dialog( "option", "width", 200 );
e538eccb 1218 $(".ui-widget-overlay").css("background", "none");
5fe117bc 1219 $('#multipleselect-form-status').empty();
e538eccb 1220 $("#dialog_overlay").show();
1221 $("#dialog_overlay").height( $("#enlargement_container").height() );
1222 $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
1223 $("#dialog_overlay").offset( $("#enlargement_container").offset() );
a84ca4de 1224 },
e538eccb 1225 close: function() {
1226 marquee.unselect();
1227 $("#dialog_overlay").hide();
1228 }
5fe117bc 1229 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
1230 if( ajaxSettings.url == getTextURL('duplicate')
1231 && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
1232 var error;
1233 if( jqXHR.responseText.indexOf('do not have permission to modify') > -1 ) {
1234 error = 'You are not authorized to modify this tradition. (Try logging in again?)';
1235 } else {
1236 try {
1237 var errobj = jQuery.parseJSON( jqXHR.responseText );
1238 error = errobj.error + '</br>The relationship cannot be made.</p>';
1239 } catch(e) {
1240 error = jqXHR.responseText;
1241 }
1242 }
1243 $('#multipleselect-form-status').append( '<p class="error">Error: ' + error );
1244 }
1245 $(event.target).parent().find('.ui-button').button("enable");
1246 });
1247
a84ca4de 1248
088a14af 1249 // Helpers for relationship deletion
1250
1251 function delete_relation( scopewide ) {
1252 form_values = $('#delete_relation_form').serialize();
1253 if( scopewide ) {
1254 form_values += "&scopewide=true";
1255 }
1256 ncpath = getTextURL( 'relationships' );
1257 var jqjson = $.ajax({ url: ncpath, data: form_values, success: function(data) {
1258 $.each( data, function(item, source_target) {
1259 relation_manager.remove( get_relation_id( source_target[0], source_target[1] ) );
1260 });
1261 $( "#delete-form" ).dialog( "close" );
1262 }, dataType: 'json', type: 'DELETE' });
1263 }
1264
1265 function toggle_relation_active( node_id ) {
1266 $('#svgenlargement .relation').find( "title:contains('" + node_id + "')" ).each( function(index) {
1267 matchid = new RegExp( "^" + node_id );
1268 if( $(this).text().match( matchid ) != null ) {
1269 var relation_id = $(this).parent().attr('id');
1270 relation_manager.toggle_active( relation_id );
1271 };
1272 });
1273 }
1274
487674b9 1275 // function for reading form dialog should go here;
1276 // just hide the element for now if we don't have morphology
1277 if( can_morphologize ) {
5539cba3 1278 if( editable ) {
1279 $('#reading_decollate_witnesses').multiselect();
1280 } else {
1281 $('#decollation').hide();
1282 }
487674b9 1283 $('#reading-form').dialog({
1284 autoOpen: false,
1285 // height: 400,
1286 width: 450,
1287 modal: true,
1288 buttons: {
1289 Cancel: function() {
1290 $( this ).dialog( "close" );
1291 },
1292 Update: function( evt ) {
1293 // Disable the button
1294 $(evt.target).button("disable");
1295 $('#reading_status').empty();
1296 var reading_id = $('#reading_id').val()
1297 form_values = {
1298 'id' : reading_id,
1299 'is_nonsense': $('#reading_is_nonsense').is(':checked'),
1300 'grammar_invalid': $('#reading_grammar_invalid').is(':checked'),
1301 'normal_form': $('#reading_normal_form').val() };
1302 // Add the morphology values
1303 $('.reading_morphology').each( function() {
1304 if( $(this).val() != '(Click to select)' ) {
1305 var rmid = $(this).attr('id');
1306 rmid = rmid.substring(8);
1307 form_values[rmid] = $(this).val();
1308 }
45ee3b96 1309 });
487674b9 1310 // Make the JSON call
1311 ncpath = getReadingURL( reading_id );
1312 var reading_element = readingdata[reading_id];
1313 // $(':button :contains("Update")').attr("disabled", true);
1314 var jqjson = $.post( ncpath, form_values, function(data) {
1315 $.each( data, function(key, value) {
1316 reading_element[key] = value;
1317 });
1318 if( $('#update_workspace_button').data('locked') == false ) {
1319 color_inactive( get_ellipse( reading_id ) );
1320 }
1321 $(evt.target).button("enable");
1322 $( "#reading-form" ).dialog( "close" );
1323 });
1324 // Re-color the node if necessary
1325 return false;
1326 }
1327 },
1328 create: function() {
30d0ba1e 1329 if( !editable ) {
1330 // Get rid of the disallowed editing UI bits
1331 $( this ).dialog( "option", "buttons",
1332 [{ text: "OK", click: function() { $( this ).dialog( "close" ); }}] );
1333 $('#reading_relemmatize').hide();
1334 }
487674b9 1335 },
1336 open: function() {
1337 $(".ui-widget-overlay").css("background", "none");
5539cba3 1338 $('#reading_decollate_witnesses').multiselect("refresh");
1339 $('#reading_decollate_witnesses').multiselect("uncheckAll");
487674b9 1340 $("#dialog_overlay").show();
1341 $('#reading_status').empty();
1342 $("#dialog_overlay").height( $("#enlargement_container").height() );
1343 $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
1344 $("#dialog_overlay").offset( $("#enlargement_container").offset() );
1345 $("#reading-form").parent().find('.ui-button').button("enable");
1346 },
1347 close: function() {
1348 $("#dialog_overlay").hide();
1349 }
1350 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
21e6ebc7 1351 if( ajaxSettings.url.lastIndexOf( getReadingURL('') ) > -1
487674b9 1352 && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
21e6ebc7 1353 var error;
1354 if( jqXHR.responseText.indexOf('do not have permission to modify') > -1 ) {
1355 error = 'You are not authorized to modify this tradition. (Try logging in again?)';
1356 } else {
1357 try {
1358 var errobj = jQuery.parseJSON( jqXHR.responseText );
1359 error = errobj.error + '</br>The relationship cannot be made.</p>';
1360 } catch(e) {
1361 error = jqXHR.responseText;
1362 }
1363 }
1364 $('#status').append( '<p class="error">Error: ' + error );
1365 }
1366 $(event.target).parent().find('.ui-button').button("enable");
487674b9 1367 });
1368 } else {
1369 $('#reading-form').hide();
45ee3b96 1370 }
4c41c02c 1371
76f05423 1372
b28e606e 1373 $('#update_workspace_button').click( function() {
30d0ba1e 1374 if( !editable ) {
1375 return;
1376 }
b28e606e 1377 var svg_enlargement = $('#svgenlargement').svg().svg('get').root();
76f05423 1378 mouse_scale = svg_root_element.getScreenCTM().a;
9529f69c 1379 if( $(this).data('locked') == true ) {
1380 $('#svgenlargement ellipse' ).each( function( index ) {
1381 if( $(this).data( 'node_obj' ) != null ) {
1382 $(this).data( 'node_obj' ).ungreyout_edges();
e538eccb 1383 $(this).data( 'node_obj' ).set_selectable( false );
1384 color_inactive( $(this) );
9529f69c 1385 var node_id = $(this).data( 'node_obj' ).get_id();
1386 toggle_relation_active( node_id );
1387 $(this).data( 'node_obj', null );
1388 }
b28e606e 1389 })
b28e606e 1390 $(this).data('locked', false);
9529f69c 1391 $(this).css('background-position', '0px 44px');
b28e606e 1392 } else {
9529f69c 1393 var left = $('#enlargement').offset().left;
1394 var right = left + $('#enlargement').width();
76f05423 1395 var tf = svg_root_element.getScreenCTM().inverse();
9529f69c 1396 var p = svg_root.createSVGPoint();
1397 p.x=left;
1398 p.y=100;
1399 var cx_min = p.matrixTransform(tf).x;
1400 p.x=right;
1401 var cx_max = p.matrixTransform(tf).x;
1402 $('#svgenlargement ellipse').each( function( index ) {
1403 var cx = parseInt( $(this).attr('cx') );
1404 if( cx > cx_min && cx < cx_max) {
1405 if( $(this).data( 'node_obj' ) == null ) {
1406 $(this).data( 'node_obj', new node_obj( $(this) ) );
1407 } else {
e538eccb 1408 $(this).data( 'node_obj' ).set_selectable( true );
9529f69c 1409 }
1410 $(this).data( 'node_obj' ).greyout_edges();
1411 var node_id = $(this).data( 'node_obj' ).get_id();
1412 toggle_relation_active( node_id );
b28e606e 1413 }
9529f69c 1414 });
1415 $(this).css('background-position', '0px 0px');
b28e606e 1416 $(this).data('locked', true );
b28e606e 1417 }
1418 });
30d0ba1e 1419
1420 if( !editable ) {
1421 // Hide the unused elements
1422 $('#dialog-form').hide();
1423 $('#update_workspace_button').hide();
1424 }
1425
b28e606e 1426
e847b186 1427 $('.helptag').popupWindow({
1428 height:500,
1429 width:800,
1430 top:50,
1431 left:50,
1432 scrollbars:1
1433 });
1434
76f05423 1435 expandFillPageClients();
1436 $(window).resize(function() {
1437 expandFillPageClients();
1438 });
1439
9529f69c 1440});
b28e606e 1441
1442
76f05423 1443function expandFillPageClients() {
1444 $('.fillPage').each(function () {
1445 $(this).height($(window).height() - $(this).offset().top - MARGIN);
1446 });
1447}
1448
1449function loadSVG(svgData) {
1450 var svgElement = $('#svgenlargement');
1451
1452 $(svgElement).svg('destroy');
1453
1454 $(svgElement).svg({
1455 loadURL: svgData,
1456 onLoad : svgEnlargementLoaded
1457 });
1458}
1459
1460
c1add777 1461
76f05423 1462/* OS Gadget stuff
1463
1464function svg_select_callback(topic, data, subscriberData) {
1465 svgData = data;
1466 loadSVG(svgData);
1467}
1468
1469function loaded() {
1470 var prefs = new gadgets.Prefs();
1471 var preferredHeight = parseInt(prefs.getString('height'));
1472 if (gadgets.util.hasFeature('dynamic-height')) gadgets.window.adjustHeight(preferredHeight);
1473 expandFillPageClients();
1474}
1475
1476if (gadgets.util.hasFeature('pubsub-2')) {
1477 gadgets.HubSettings.onConnect = function(hum, suc, err) {
1478 subId = gadgets.Hub.subscribe("interedition.svg.selected", svg_select_callback);
1479 loaded();
1480 };
1481}
1482else gadgets.util.registerOnLoadHandler(loaded);
1483*/