Merged out conflicts
[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 ) });
5fe117bc 229 // detach_node(null);
e538eccb 230 });
231 $('#loading_overlay').hide();
232 });
c1add777 233
234 //initialize marquee
235 marquee = new Marquee();
236
6afcd813 237}
238
fc018906 239function add_relations( callback_fn ) {
56e3972e 240 // Add the relationship types to the keymap list
56e3972e 241 $.each( relationship_types, function(index, typedef) {
671c04b1 242 li_elm = $('<li class="key">').css( "border-color",
243 relation_manager.relation_colors[index] ).text(typedef.name);
244 li_elm.append( $('<div>').attr('class', 'key_tip_container').append(
245 $('<div>').attr('class', 'key_tip').text(typedef.description) ) );
cfefd283 246 $('#keymaplist').append( li_elm );
56e3972e 247 });
248 // Now fetch the relationships themselves and add them to the graph
249 var rel_types = $.map( relationship_types, function(t) { return t.name });
250 // Save this list of names to the outer element data so that the relationship
251 // factory can access it
252 $('#keymap').data('relations', rel_types);
5f15640c 253 var textrelpath = getTextURL( 'relationships' );
56e3972e 254 $.getJSON( textrelpath, function(data) {
255 $.each(data, function( index, rel_info ) {
256 var type_index = $.inArray(rel_info.type, rel_types);
257 var source_found = get_ellipse( rel_info.source );
258 var target_found = get_ellipse( rel_info.target );
259 if( type_index != -1 && source_found.size() && target_found.size() ) {
260 var relation = relation_manager.create( rel_info.source, rel_info.target, type_index );
261 relation.data( 'type', rel_info.type );
262 relation.data( 'scope', rel_info.scope );
263 relation.data( 'note', rel_info.note );
30d0ba1e 264 if( editable ) {
265 var node_obj = get_node_obj(rel_info.source);
e538eccb 266 node_obj.set_selectable( false );
30d0ba1e 267 node_obj.ellipse.data( 'node_obj', null );
268 node_obj = get_node_obj(rel_info.target);
e538eccb 269 node_obj.set_selectable( false );
30d0ba1e 270 node_obj.ellipse.data( 'node_obj', null );
271 }
56e3972e 272 }
273 });
274 callback_fn.call();
275 });
b28e606e 276}
277
278function get_ellipse( node_id ) {
45ee3b96 279 return $( jq( node_id ) + ' ellipse');
b28e606e 280}
281
282function get_node_obj( node_id ) {
9529f69c 283 var node_ellipse = get_ellipse( node_id );
284 if( node_ellipse.data( 'node_obj' ) == null ) {
285 node_ellipse.data( 'node_obj', new node_obj(node_ellipse) );
286 };
287 return node_ellipse.data( 'node_obj' );
b28e606e 288}
289
b28e606e 290function node_obj(ellipse) {
291 this.ellipse = ellipse;
292 var self = this;
293
22a70299 294 this.ox = 0;
295 this.oy = 0;
b28e606e 296 this.x = 0;
297 this.y = 0;
298 this.dx = 0;
299 this.dy = 0;
300 this.node_elements = node_elements_for(self.ellipse);
301
22a70299 302 if( $(self.ellipse).data( 'org_translate' ) != null ) {
303 var org_translate = $(self.ellipse).data( 'org_translate' );
304 this.ox = org_translate[0];
305 this.oy = org_translate[1];
306 }
307
b28e606e 308 this.get_id = function() {
45ee3b96 309 return $(self.ellipse).parent().attr('id')
b28e606e 310 }
311
e538eccb 312 this.set_selectable = function( clickable ) {
313 if( clickable && editable ) {
314 $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
315 $(self.ellipse).parent().hover( this.enter_node, this.leave_node );
316 $(self.ellipse).parent().mousedown( function(evt) { evt.stopPropagation() } );
317 $(self.ellipse).parent().click( function(evt) {
318 evt.stopPropagation();
319 if( $('ellipse[fill="#9999ff"]').size() > 0 ) {
320 $('ellipse[fill="#9999ff"]').each( function() {
321 $(this).data( 'node_obj' ).set_draggable( false );
322 } );
323 }
324 self.set_draggable( true )
325 });
326 } else {
327 $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
328 self.ellipse.siblings('text').attr('class', '');
329 $(self.ellipse).parent().unbind();
330 $('body').unbind('mousemove');
331 $('body').unbind('mouseup');
332 }
333 }
334
b28e606e 335 this.set_draggable = function( draggable ) {
30d0ba1e 336 if( draggable && editable ) {
e538eccb 337 $(self.ellipse).attr( {stroke:'black', fill:'#9999ff'} );
05485bfd 338 $(self.ellipse).parent().mousedown( this.mousedown_listener );
e538eccb 339 $(self.ellipse).parent().unbind( 'mouseenter' ).unbind( 'mouseleave' );
05485bfd 340 self.ellipse.siblings('text').attr('class', 'noselect draggable');
b28e606e 341 } else {
e538eccb 342 $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
05485bfd 343 self.ellipse.siblings('text').attr('class', '');
e538eccb 344 $(self.ellipse).parent().unbind( 'mousedown ');
345 $(self.ellipse).parent().mousedown( function(evt) { evt.stopPropagation() } );
346 $(self.ellipse).parent().hover( this.enter_node, this.leave_node );
b28e606e 347 }
348 }
349
350 this.mousedown_listener = function(evt) {
351 evt.stopPropagation();
352 self.x = evt.clientX;
353 self.y = evt.clientY;
354 $('body').mousemove( self.mousemove_listener );
355 $('body').mouseup( self.mouseup_listener );
05485bfd 356 $(self.ellipse).parent().unbind('mouseenter').unbind('mouseleave')
e538eccb 357 self.ellipse.attr( 'fill', '#6b6bb2' );
b28e606e 358 first_node_g_element = $("#svgenlargement g .node" ).filter( ":first" );
359 if( first_node_g_element.attr('id') !== self.get_g().attr('id') ) { self.get_g().insertBefore( first_node_g_element ) };
360 }
361
362 this.mousemove_listener = function(evt) {
9529f69c 363 self.dx = (evt.clientX - self.x) / mouse_scale;
364 self.dy = (evt.clientY - self.y) / mouse_scale;
b28e606e 365 self.move_elements();
05485bfd 366 evt.returnValue = false;
367 evt.preventDefault();
368 return false;
b28e606e 369 }
370
371 this.mouseup_listener = function(evt) {
372 if( $('ellipse[fill="#ffccff"]').size() > 0 ) {
45ee3b96 373 var source_node_id = $(self.ellipse).parent().attr('id');
05485bfd 374 var source_node_text = self.ellipse.siblings('text').text();
45ee3b96 375 var target_node_id = $('ellipse[fill="#ffccff"]').parent().attr('id');
05485bfd 376 var target_node_text = $('ellipse[fill="#ffccff"]').siblings("text").text();
b28e606e 377 $('#source_node_id').val( source_node_id );
05485bfd 378 $('#source_node_text').val( source_node_text );
b28e606e 379 $('#target_node_id').val( target_node_id );
05485bfd 380 $('#target_node_text').val( target_node_text );
b28e606e 381 $('#dialog-form').dialog( 'open' );
382 };
383 $('body').unbind('mousemove');
384 $('body').unbind('mouseup');
e538eccb 385 self.ellipse.attr( 'fill', '#9999ff' );
9529f69c 386 self.reset_elements();
b28e606e 387 }
f2fb96fc 388
b28e606e 389 this.cpos = function() {
390 return { x: self.ellipse.attr('cx'), y: self.ellipse.attr('cy') };
391 }
392
393 this.get_g = function() {
394 return self.ellipse.parent('g');
395 }
396
397 this.enter_node = function(evt) {
398 self.ellipse.attr( 'fill', '#ffccff' );
399 }
400
401 this.leave_node = function(evt) {
402 self.ellipse.attr( 'fill', '#fff' );
403 }
404
405 this.greyout_edges = function() {
406 $.each( self.node_elements, function(index, value) {
407 value.grey_out('.edge');
408 });
409 }
410
411 this.ungreyout_edges = function() {
412 $.each( self.node_elements, function(index, value) {
413 value.un_grey_out('.edge');
414 });
415 }
416
417 this.move_elements = function() {
418 $.each( self.node_elements, function(index, value) {
22a70299 419 value.move( ( self.ox + self.dx ) , ( self.oy + self.dy ) );
420 } );
b28e606e 421 }
422
423 this.reset_elements = function() {
424 $.each( self.node_elements, function(index, value) {
22a70299 425 value.move( self.ox, self.oy );
426 } );
b28e606e 427 }
428
429 this.update_elements = function() {
430 self.node_elements = node_elements_for(self.ellipse);
431 }
432
a84ca4de 433 this.get_witnesses = function() {
434 return readingdata[self.get_id()].witnesses
435 }
436
22a70299 437 this.relocate = function( dx, dy ) {
438 self.ox = self.ox + dx;
439 self.oy = self.oy + dy;
440 $(self.ellipse).data( 'org_translate', [self.ox, self.oy] );
441 self.move_elements();
442 }
443
e538eccb 444 self.set_selectable( true );
b28e606e 445}
446
447function svgshape( shape_element ) {
448 this.shape = shape_element;
449 this.move = function(dx,dy) {
22a70299 450 this.shape.attr( "transform", "translate(" + dx + " " + dy + ")" );
b28e606e 451 }
452 this.reset = function() {
453 this.shape.attr( "transform", "translate( 0, 0 )" );
454 }
455 this.grey_out = function(filter) {
456 if( this.shape.parent(filter).size() != 0 ) {
457 this.shape.attr({'stroke':'#e5e5e5', 'fill':'#e5e5e5'});
458 }
459 }
460 this.un_grey_out = function(filter) {
461 if( this.shape.parent(filter).size() != 0 ) {
462 this.shape.attr({'stroke':'#000000', 'fill':'#000000'});
463 }
464 }
465}
466
467function svgpath( path_element, svg_element ) {
468 this.svg_element = svg_element;
469 this.path = path_element;
470 this.x = this.path.x;
471 this.y = this.path.y;
472 this.move = function(dx,dy) {
473 this.path.x = this.x + dx;
474 this.path.y = this.y + dy;
475 }
476 this.reset = function() {
477 this.path.x = this.x;
478 this.path.y = this.y;
479 }
480 this.grey_out = function(filter) {
481 if( this.svg_element.parent(filter).size() != 0 ) {
482 this.svg_element.attr('stroke', '#e5e5e5');
483 this.svg_element.siblings('text').attr('fill', '#e5e5e5');
05485bfd 484 this.svg_element.siblings('text').attr('class', 'noselect');
b28e606e 485 }
486 }
487 this.un_grey_out = function(filter) {
488 if( this.svg_element.parent(filter).size() != 0 ) {
489 this.svg_element.attr('stroke', '#000000');
490 this.svg_element.siblings('text').attr('fill', '#000000');
05485bfd 491 this.svg_element.siblings('text').attr('class', '');
b28e606e 492 }
493 }
494}
495
496function node_elements_for( ellipse ) {
497 node_elements = get_edge_elements_for( ellipse );
498 node_elements.push( new svgshape( ellipse.siblings('text') ) );
499 node_elements.push( new svgshape( ellipse ) );
500 return node_elements;
501}
502
503function get_edge_elements_for( ellipse ) {
504 edge_elements = new Array();
45ee3b96 505 node_id = ellipse.parent().attr('id');
b28e606e 506 edge_in_pattern = new RegExp( node_id + '$' );
22a70299 507 edge_out_pattern = new RegExp( '^' + node_id + '-' );
b28e606e 508 $.each( $('#svgenlargement .edge,#svgenlargement .relation').children('title'), function(index) {
509 title = $(this).text();
510 if( edge_in_pattern.test(title) ) {
511 polygon = $(this).siblings('polygon');
512 if( polygon.size() > 0 ) {
513 edge_elements.push( new svgshape( polygon ) );
514 }
515 path_segments = $(this).siblings('path')[0].pathSegList;
516 edge_elements.push( new svgpath( path_segments.getItem(path_segments.numberOfItems - 1), $(this).siblings('path') ) );
517 }
518 if( edge_out_pattern.test(title) ) {
519 path_segments = $(this).siblings('path')[0].pathSegList;
520 edge_elements.push( new svgpath( path_segments.getItem(0), $(this).siblings('path') ) );
521 }
522 });
523 return edge_elements;
524}
525
526function relation_factory() {
527 var self = this;
528 this.color_memo = null;
529 //TODO: colors hard coded for now
530 this.temp_color = '#FFA14F';
531 this.relation_colors = [ "#5CCCCC", "#67E667", "#F9FE72", "#6B90D4", "#FF7673", "#E467B3", "#AA67D5", "#8370D8", "#FFC173" ];
532
533 this.create_temporary = function( source_node_id, target_node_id ) {
45ee3b96 534 var relation_id = get_relation_id( source_node_id, target_node_id );
535 var relation = $( jq( relation_id ) );
9529f69c 536 if( relation.size() == 0 ) {
b28e606e 537 draw_relation( source_node_id, target_node_id, self.temp_color );
538 } else {
539 self.color_memo = relation.children('path').attr( 'stroke' );
540 relation.children('path').attr( 'stroke', self.temp_color );
541 }
542 }
543 this.remove_temporary = function() {
544 var path_element = $('#svgenlargement .relation').children('path[stroke="' + self.temp_color + '"]');
545 if( self.color_memo != null ) {
546 path_element.attr( 'stroke', self.color_memo );
547 self.color_memo = null;
548 } else {
9529f69c 549 var temporary = path_element.parent('g').remove();
550 temporary.empty();
551 temporary = null;
b28e606e 552 }
553 }
554 this.create = function( source_node_id, target_node_id, color_index ) {
555 //TODO: Protect from (color_)index out of bound..
556 var relation_color = self.relation_colors[ color_index ];
9529f69c 557 var relation = draw_relation( source_node_id, target_node_id, relation_color );
558 get_node_obj( source_node_id ).update_elements();
559 get_node_obj( target_node_id ).update_elements();
560 return relation;
b28e606e 561 }
9529f69c 562 this.toggle_active = function( relation_id ) {
45ee3b96 563 var relation = $( jq( relation_id ) );
9529f69c 564 var relation_path = relation.children('path');
565 if( !relation.data( 'active' ) ) {
566 relation_path.css( {'cursor':'pointer'} );
567 relation_path.mouseenter( function(event) {
568 outerTimer = setTimeout( function() {
569 timer = setTimeout( function() {
45ee3b96 570 var related_nodes = get_related_nodes( relation_id );
571 var source_node_id = related_nodes[0];
572 var target_node_id = related_nodes[1];
9529f69c 573 $('#delete_source_node_id').val( source_node_id );
574 $('#delete_target_node_id').val( target_node_id );
575 self.showinfo(relation);
576 }, 500 )
577 }, 1000 );
578 });
579 relation_path.mouseleave( function(event) {
580 clearTimeout(outerTimer);
581 if( timer != null ) { clearTimeout(timer); }
582 });
583 relation.data( 'active', true );
584 } else {
585 relation_path.unbind( 'mouseenter' );
586 relation_path.unbind( 'mouseleave' );
587 relation_path.css( {'cursor':'inherit'} );
588 relation.data( 'active', false );
589 }
590 }
591 this.showinfo = function(relation) {
088a14af 592 $('#delete_relation_type').text( relation.data('type') );
593 $('#delete_relation_scope').text( relation.data('scope') );
69a19c91 594 if( relation.data( 'note' ) ) {
088a14af 595 $('#delete_relation_note').text('note: ' + relation.data( 'note' ) );
69a19c91 596 }
9529f69c 597 var points = relation.children('path').attr('d').slice(1).replace('C',' ').split(' ');
598 var xs = parseFloat( points[0].split(',')[0] );
599 var xe = parseFloat( points[1].split(',')[0] );
600 var ys = parseFloat( points[0].split(',')[1] );
601 var ye = parseFloat( points[3].split(',')[1] );
602 var p = svg_root.createSVGPoint();
603 p.x = xs + ((xe-xs)*1.1);
604 p.y = ye - ((ye-ys)/2);
76f05423 605 var ctm = svg_root_element.getScreenCTM();
9529f69c 606 var nx = p.matrixTransform(ctm).x;
607 var ny = p.matrixTransform(ctm).y;
608 var dialog_aria = $ ("div[aria-labelledby='ui-dialog-title-delete-form']");
609 $('#delete-form').dialog( 'open' );
610 dialog_aria.offset({ left: nx, top: ny });
611 }
612 this.remove = function( relation_id ) {
30d0ba1e 613 if( !editable ) {
614 return;
615 }
45ee3b96 616 var relation = $( jq( relation_id ) );
9529f69c 617 relation.remove();
b28e606e 618 }
619}
620
45ee3b96 621// Utility function to create/return the ID of a relation link between
622// a source and target.
623function get_relation_id( source_id, target_id ) {
624 var idlist = [ source_id, target_id ];
625 idlist.sort();
626 return 'relation-' + idlist[0] + '-...-' + idlist[1];
627}
628
629function get_related_nodes( relation_id ) {
630 var srctotarg = relation_id.substr( 9 );
631 return srctotarg.split('-...-');
632}
633
b28e606e 634function draw_relation( source_id, target_id, relation_color ) {
9529f69c 635 var source_ellipse = get_ellipse( source_id );
636 var target_ellipse = get_ellipse( target_id );
45ee3b96 637 var relation_id = get_relation_id( source_id, target_id );
9529f69c 638 var svg = $('#svgenlargement').children('svg').svg().svg('get');
639 var path = svg.createPath();
640 var sx = parseInt( source_ellipse.attr('cx') );
641 var rx = parseInt( source_ellipse.attr('rx') );
642 var sy = parseInt( source_ellipse.attr('cy') );
643 var ex = parseInt( target_ellipse.attr('cx') );
644 var ey = parseInt( target_ellipse.attr('cy') );
45ee3b96 645 var relation = svg.group( $("#svgenlargement svg g"),
646 { 'class':'relation', 'id':relation_id } );
9529f69c 647 svg.title( relation, source_id + '->' + target_id );
648 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 649 var relation_element = $('#svgenlargement .relation').filter( ':last' );
650 relation_element.insertBefore( $('#svgenlargement g g').filter(':first') );
9529f69c 651 return relation_element;
b28e606e 652}
653
5fe117bc 654function detach_node( readings ) {
60c66cd2 655
656 // This method is work in progress
657 // Todos:
658 // 1) Unproven/untested: readings.each will get us in trouble most likely for
659 // duplicating edges in a strand that both are incoming and outgoing
660 // like b and c in -i-> a -ii-> b -iii-> c -iv->
661 // 2) Added edges and nodes look rough and unsmoothed, what the f.?
662 //
663
a471cb0f 664 // add new node(s)
665 $.extend( readingdata, readings );
666 // remove from existing readings the witnesses for the new nodes/readings
667 $.each( readings, function( node_id, reading ) {
668 $.each( reading.witnesses, function( index, witness ) {
669 var witnesses = readingdata[ reading.orig_rdg ].witnesses;
670 readingdata[ reading.orig_rdg ].witnesses = $.removeFromArray( witness, witnesses );
671 } );
672 } );
673
a471cb0f 674 detached_edges = [];
8cd2e785 675
676 // here we detach witnesses from the existing edges accoring to what's being relayed by readings
a471cb0f 677 $.each( readings, function( node_id, reading ) {
678 var edges = edges_of( get_ellipse( reading.orig_rdg ) );
679 incoming_remaining = [];
680 outgoing_remaining = [];
681 $.each( reading.witnesses, function( index, witness ) {
682 incoming_remaining.push( witness );
683 outgoing_remaining.push( witness );
684 } );
685 $.each( edges, function( index, edge ) {
686 detached_edge = edge.detach_witnesses( reading.witnesses );
687 if( detached_edge != null ) {
688 detached_edges.push( detached_edge );
689 $.each( detached_edge.witnesses, function( index, witness ) {
690 if( detached_edge.is_incoming == true ) {
691 incoming_remaining = $.removeFromArray( witness, incoming_remaining );
692 } else {
693 outgoing_remaining = $.removeFromArray( witness, outgoing_remaining );
694 }
695 } );
696 }
697 } );
8cd2e785 698
60c66cd2 699 // After detaching we still need to check if for *all* readings
8cd2e785 700 // an edge was detached. It may be that a witness was not
701 // explicitly named on an edge but was part of a 'majority' edge
702 // in which case we need to duplicate and name that edge after those
703 // remaining witnesses.
a471cb0f 704 if( outgoing_remaining.length > 0 ) {
a471cb0f 705 $.each( edges, function( index, edge ) {
a471cb0f 706 if( edge.get_label() == 'majority' && !edge.is_incoming ) {
707 detached_edges.push( edge.clone_for( outgoing_remaining ) );
708 }
709 } );
710 }
711 if( incoming_remaining.length > 0 ) {
a471cb0f 712 $.each( edges, function( index, edge ) {
713 if( edge.get_label() == 'majority' && edge.is_incoming ) {
714 detached_edges.push( edge.clone_for( outgoing_remaining ) );
715 }
716 } );
717 }
60c66cd2 718
22a70299 719 // Finally multiple selected nodes may share edges
720 var copy_array = [];
721 $.each( detached_edges, function( index, edge ) {
722 var do_copy = true;
723 $.each( copy_array, function( index, copy_edge ) {
724 if( copy_edge.g_elem.attr( 'id' ) == edge.g_elem.attr( 'id' ) ) { do_copy = false }
725 } );
726 if( do_copy == true ) {
727 copy_array.push( edge );
728 }
729 } );
730 detached_edges = copy_array;
731
60c66cd2 732 // Lots of unabstracted knowledge down here :/
733 // Clone original node/reading, rename/id it..
734 duplicate_node = get_ellipse( reading.orig_rdg ).parent().clone();
735 duplicate_node.attr( 'id', node_id );
736 duplicate_node.children( 'title' ).text( node_id );
22a70299 737 duplicate_node_data = get_ellipse( reading.orig_rdg ).data( 'org_translate' );
738 if( duplicate_node_data != null ) {
739 duplicate_node.children( 'ellipse' ).data( 'org_translate', duplicate_node_data );
740 }
60c66cd2 741
742 // Add the node and all new edges into the graph
931ed236 743 var graph_root = $('#svgenlargement svg g.graph');
60c66cd2 744 graph_root.append( duplicate_node );
745 $.each( detached_edges, function( index, edge ) {
746 edge.g_elem.attr( 'id', ( edge.g_elem.attr( 'id' ) + "_0" ) );
747 edge_title = edge.g_elem.children( 'title' ).text();
22a70299 748 edge_weight = 0.8 + ( 0.2 * edge.witnesses.length );
60c66cd2 749 edge_title = edge_title.replace( reading.orig_rdg, node_id );
750 edge.g_elem.children( 'title' ).text( edge_title );
22a70299 751 edge.g_elem.children( 'path').attr( 'stroke-width', edge_weight );
60c66cd2 752 // Reg unabstracted knowledge: isn't it more elegant to make
753 // it edge.append_to( graph_root )?
754 graph_root.append( edge.g_elem );
755 } );
22a70299 756
757 // Make the detached node a real node_obj
758 var ellipse_elem = get_ellipse( node_id );
759 var new_node = new node_obj( ellipse_elem );
760 ellipse_elem.data( 'node_obj', new_node );
761
60c66cd2 762 // Move the node somewhat up for 'dramatic effect' :-p
22a70299 763 new_node.relocate( 0, -150 );
60c66cd2 764
a471cb0f 765 } );
60c66cd2 766
a471cb0f 767
768}
769
c1add777 770function Marquee() {
771
772 var self = this;
773
f6516f22 774 this.x = 0;
775 this.y = 0;
776 this.dx = 0;
777 this.dy = 0;
c1add777 778 this.enlargementOffset = $('#svgenlargement').offset();
779 this.svg_rect = $('#svgenlargement svg').svg('get');
780
781 this.show = function( event ) {
f6516f22 782 self.x = event.clientX;
783 self.y = event.clientY;
c1add777 784 p = svg_root.createSVGPoint();
785 p.x = event.clientX - self.enlargementOffset.left;
786 p.y = event.clientY - self.enlargementOffset.top;
c1add777 787 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' } );
788 };
789
790 this.expand = function( event ) {
f6516f22 791 self.dx = (event.clientX - self.x);
792 self.dy = (event.clientY - self.y);
c1add777 793 var rect = $('#marquee');
f6516f22 794 if( rect.length != 0 ) {
795 var rect_w = Math.abs( self.dx );
796 var rect_h = Math.abs( self.dy );
797 var rect_x = self.x - self.enlargementOffset.left;
798 var rect_y = self.y - self.enlargementOffset.top;
799 if( self.dx < 0 ) { rect_x = rect_x - rect_w }
800 if( self.dy < 0 ) { rect_y = rect_y - rect_h }
801 rect.attr("x", rect_x).attr("y", rect_y).attr("width", rect_w).attr("height", rect_h);
c1add777 802 }
803 };
804
a84ca4de 805 this.select = function() {
c1add777 806 var rect = $('#marquee');
807 if( rect.length != 0 ) {
e538eccb 808 //unselect any possible selected first
22a70299 809 //TODO: unless SHIFT?
e538eccb 810 if( $('ellipse[fill="#9999ff"]').size() > 0 ) {
811 $('ellipse[fill="#9999ff"]').each( function() {
812 $(this).data( 'node_obj' ).set_draggable( false );
813 } );
814 }
815 //compute dimension of marquee
c1add777 816 var left = $('#marquee').offset().left;
817 var top = $('#marquee').offset().top;
818 var right = left + parseInt( $('#marquee').attr( 'width' ) );
819 var bottom = top + parseInt( $('#marquee').attr( 'height' ) );
820 var tf = svg_root_element.getScreenCTM().inverse();
821 var p = svg_root.createSVGPoint();
822 p.x=left;
823 p.y=top;
824 var cx_min = p.matrixTransform(tf).x;
825 var cy_min = p.matrixTransform(tf).y;
826 p.x=right;
827 p.y=bottom;
828 var cx_max = p.matrixTransform(tf).x;
829 var cy_max = p.matrixTransform(tf).y;
e538eccb 830 //select any node with its center inside the marquee
5fe117bc 831 var readings = [];
e538eccb 832 //also merge witness sets from nodes
a84ca4de 833 var witnesses = [];
c1add777 834 $('#svgenlargement ellipse').each( function( index ) {
835 var cx = parseInt( $(this).attr('cx') );
836 var cy = parseInt( $(this).attr('cy') );
22a70299 837 var org_translate = $(this).data( 'org_translate' );
838 if( org_translate != null ) {
839 cx = cx + org_translate[0];
840 cy = cy + org_translate[1];
841 }
c1add777 842 if( cx > cx_min && cx < cx_max) {
843 if( cy > cy_min && cy < cy_max) {
844 // we actually heve no real 'selected' state for nodes, except coloring
e538eccb 845 $(this).attr( 'fill', '#9999ff' );
5fe117bc 846 // Take note of the selected reading(s) and applicable witness(es)
847 // so we can populate the multipleselect-form
848 readings.push( $(this).parent().attr('id') );
a84ca4de 849 var this_witnesses = $(this).data( 'node_obj' ).get_witnesses();
850 witnesses = arrayUnique( witnesses.concat( this_witnesses ) );
c1add777 851 }
852 }
853 });
e538eccb 854 if( $('ellipse[fill="#9999ff"]').size() > 0 ) {
5fe117bc 855 //add intersection of witnesses sets to the multi select form and open it
856 $('#detach_collated_form').empty();
857 $.each( readings, function( index, value ) {
858 $('#detach_collated_form').append( $('<input>').attr(
859 "type", "hidden").attr("name", "readings[]").attr(
860 "value", value ) );
861 });
862 $.each( witnesses, function( index, value ) {
863 $('#detach_collated_form').append(
864 '<input type="checkbox" name="witnesses[]" value="' + value
865 + '">' + value + '<br>' );
a84ca4de 866 });
5fe117bc 867 $('#multiple_selected_readings').attr('value', readings.join(',') );
a84ca4de 868 $('#multipleselect-form').dialog( 'open' );
869 }
c1add777 870 self.svg_rect.remove( $('#marquee') );
871 }
872 };
873
f6516f22 874 this.unselect = function() {
e538eccb 875 $('ellipse[fill="#9999ff"]').attr( 'fill', '#fff' );
f6516f22 876 }
877
c1add777 878}
879
b001c73d 880function readings_equivalent( source, target ) {
881 var sourcetext = readingdata[source].text;
882 var targettext = readingdata[target].text;
883 if( sourcetext === targettext ) {
884 return true;
885 }
886 // Lowercase and strip punctuation from both and compare again
887 var stlc = sourcetext.toLowerCase().replace(/[^\w\s]|_/g, "");
888 var ttlc = targettext.toLowerCase().replace(/[^\w\s]|_/g, "");
889 if( stlc === ttlc ) {
890 return true;
891 }
892 return false;
893}
894
9529f69c 895
b28e606e 896$(document).ready(function () {
9529f69c 897
898 timer = null;
b28e606e 899 relation_manager = new relation_factory();
900
c1add777 901 $('#update_workspace_button').data('locked', false);
b001c73d 902
903 // Set up the mouse events on the SVG enlargement
9529f69c 904 $('#enlargement').mousedown(function (event) {
b28e606e 905 $(this)
9529f69c 906 .data('down', true)
907 .data('x', event.clientX)
908 .data('y', event.clientY)
909 .data('scrollLeft', this.scrollLeft)
c1add777 910 stateTf = svg_root_element.getCTM().inverse();
911 var p = svg_root.createSVGPoint();
912 p.x = event.clientX;
913 p.y = event.clientY;
914 stateOrigin = p.matrixTransform(stateTf);
915
916 // Activate marquee if in interaction mode
917 if( $('#update_workspace_button').data('locked') == true ) { marquee.show( event ) };
918
919 event.returnValue = false;
920 event.preventDefault();
921 return false;
b28e606e 922 }).mouseup(function (event) {
a84ca4de 923 marquee.select();
c1add777 924 $(this).data('down', false);
b28e606e 925 }).mousemove(function (event) {
9529f69c 926 if( timer != null ) { clearTimeout(timer); }
927 if ( ($(this).data('down') == true) && ($('#update_workspace_button').data('locked') == false) ) {
928 var p = svg_root.createSVGPoint();
929 p.x = event.clientX;
930 p.y = event.clientY;
931 p = p.matrixTransform(stateTf);
932 var matrix = stateTf.inverse().translate(p.x - stateOrigin.x, p.y - stateOrigin.y);
933 var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
76f05423 934 svg_root_element.setAttribute("transform", s);
b28e606e 935 }
c1add777 936 marquee.expand( event );
76f05423 937 event.returnValue = false;
938 event.preventDefault();
b28e606e 939 }).mousewheel(function (event, delta) {
9529f69c 940 event.returnValue = false;
941 event.preventDefault();
942 if ( $('#update_workspace_button').data('locked') == false ) {
76f05423 943 if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
944 if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
9529f69c 945 if( delta < -9 ) { delta = -9 };
946 var z = 1 + delta/10;
76f05423 947 z = delta > 0 ? 1 : -1;
948 var g = svg_root_element;
949 if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 100))) {
9529f69c 950 var root = svg_root;
951 var p = root.createSVGPoint();
76f05423 952 p.x = event.originalEvent.clientX;
953 p.y = event.originalEvent.clientY;
9529f69c 954 p = p.matrixTransform(g.getCTM().inverse());
76f05423 955 var scaleLevel = 1+(z/20);
956 var k = root.createSVGMatrix().translate(p.x, p.y).scale(scaleLevel).translate(-p.x, -p.y);
9529f69c 957 var matrix = g.getCTM().multiply(k);
958 var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
959 g.setAttribute("transform", s);
960 }
961 }
b28e606e 962 }).css({
963 'overflow' : 'hidden',
964 'cursor' : '-moz-grab'
965 });
966
c1add777 967
b001c73d 968 // Set up the relationship creation dialog. This also functions as the reading
969 // merge dialog where appropriate.
b001c73d 970
30d0ba1e 971 if( editable ) {
972 $( "#dialog-form" ).dialog({
973 autoOpen: false,
974 height: 270,
975 width: 290,
976 modal: true,
977 buttons: {
b001c73d 978 "Merge readings": function( evt ) {
979 $(evt.target).button("disable");
980 $('#status').empty();
981 form_values = $('#collapse_node_form').serialize();
982 ncpath = getTextURL( 'merge' );
983 var jqjson = $.post( ncpath, form_values, function(data) {
984 alert( "Did a node merge" );
985 });
986 },
987 OK: function( evt ) {
30d0ba1e 988 $(evt.target).button("disable");
989 $('#status').empty();
990 form_values = $('#collapse_node_form').serialize();
991 ncpath = getTextURL( 'relationships' );
992 var jqjson = $.post( ncpath, form_values, function(data) {
993 $.each( data, function(item, source_target) {
994 var source_found = get_ellipse( source_target[0] );
995 var target_found = get_ellipse( source_target[1] );
996 var relation_found = $.inArray( source_target[2], $('#keymap').data('relations') );
997 if( source_found.size() && target_found.size() && relation_found > -1 ) {
998 var relation = relation_manager.create( source_target[0], source_target[1], relation_found );
eeea8fb6 999 relation.data( 'type', source_target[2] );
7b54e481 1000 relation.data( 'scope', $('#scope :selected').text() );
1001 relation.data( 'note', $('#note').val() );
45ee3b96 1002 relation_manager.toggle_active( relation.attr('id') );
7b54e481 1003 }
30d0ba1e 1004 $(evt.target).button("enable");
1005 });
1006 $( "#dialog-form" ).dialog( "close" );
1007 }, 'json' );
1008 },
1009 Cancel: function() {
1010 $( this ).dialog( "close" );
1011 }
1012 },
1013 create: function(event, ui) {
1014 $(this).data( 'relation_drawn', false );
a166dca8 1015 $('#rel_type').data( 'changed_after_open', false );
56e3972e 1016 $.each( relationship_types, function(index, typedef) {
1017 $('#rel_type').append( $('<option />').attr( "value", typedef.name ).text(typedef.name) );
1018 });
1019 $.each( relationship_scopes, function(index, value) {
1020 $('#scope').append( $('<option />').attr( "value", value ).text(value) );
a166dca8 1021 });
1022 // Handler to clear the annotation field, the first time the relationship is
1023 // changed after opening the form.
1024 $('#rel_type').change( function () {
1025 if( !$(this).data( 'changed_after_open' ) ) {
1026 $('#note').val('');
1027 }
1028 $(this).data( 'changed_after_open', true );
1029 });
30d0ba1e 1030 },
1031 open: function() {
b001c73d 1032 relation_manager.create_temporary(
1033 $('#source_node_id').val(), $('#target_node_id').val() );
1034 var buttonset = $(this).parent().find( '.ui-dialog-buttonset' )
1035 if( readings_equivalent( $('#source_node_id').val(),
1036 $('#target_node_id').val() ) ) {
1037 buttonset.find( "button:contains('Merge readings')" ).show();
1038 } else {
1039 buttonset.find( "button:contains('Merge readings')" ).hide();
1040 }
30d0ba1e 1041 $(".ui-widget-overlay").css("background", "none");
1042 $("#dialog_overlay").show();
1043 $("#dialog_overlay").height( $("#enlargement_container").height() );
1044 $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
1045 $("#dialog_overlay").offset( $("#enlargement_container").offset() );
a166dca8 1046 $('#rel_type').data( 'changed_after_open', false );
30d0ba1e 1047 },
1048 close: function() {
1049 relation_manager.remove_temporary();
1050 $( '#status' ).empty();
1051 $("#dialog_overlay").hide();
1052 }
1053 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
21e6ebc7 1054 if( ajaxSettings.url == getTextURL('relationships')
1055 && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
1056 var error;
1057 if( jqXHR.responseText.indexOf('do not have permission to modify') > -1 ) {
1058 error = 'You are not authorized to modify this tradition. (Try logging in again?)';
1059 } else {
1060 try {
1061 var errobj = jQuery.parseJSON( jqXHR.responseText );
1062 error = errobj.error + '</br>The relationship cannot be made.</p>';
1063 } catch(e) {
1064 error = jqXHR.responseText;
1065 }
1066 }
1067 $('#status').append( '<p class="error">Error: ' + error );
1068 }
1069 $(event.target).parent().find('.ui-button').button("enable");
30d0ba1e 1070 } );
1071 }
b28e606e 1072
b001c73d 1073 // Set up the relationship info display and deletion dialog.
9529f69c 1074 $( "#delete-form" ).dialog({
1075 autoOpen: false,
69a19c91 1076 height: 135,
088a14af 1077 width: 250,
9529f69c 1078 modal: false,
b001c73d 1079 buttons: {
1080 OK: function() { $( this ).dialog( "close" ); },
1081 "Delete all": function () { delete_relation( true ); },
1082 Delete: function() { delete_relation( false ); }
1083 },
9529f69c 1084 create: function(event, ui) {
30d0ba1e 1085 // TODO What is this logic doing?
a84ca4de 1086 // This scales the buttons in the dialog and makes it look proper
1087 // Not sure how essential it is, does anything break if it's not here?
9529f69c 1088 var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
b001c73d 1089 buttonset.find( "button:contains('OK')" ).css( 'float', 'right' );
a84ca4de 1090 // A: This makes sure that the pop up delete relation dialogue for a hovered over
1091 // relation auto closes if the user doesn't engage (mouseover) with it.
9529f69c 1092 var dialog_aria = $("div[aria-labelledby='ui-dialog-title-delete-form']");
1093 dialog_aria.mouseenter( function() {
1094 if( mouseWait != null ) { clearTimeout(mouseWait) };
1095 })
1096 dialog_aria.mouseleave( function() {
1097 mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
1098 })
1099 },
1100 open: function() {
b001c73d 1101 // Show the appropriate buttons...
1102 var buttonset = $(this).parent().find( '.ui-dialog-buttonset' )
1103 // If the user can't edit, show only the OK button
088a14af 1104 if( !editable ) {
b001c73d 1105 buttonset.find( "button:contains('Delete')" ).hide();
1106 // If the relationship scope is local, show only OK and Delete
088a14af 1107 } else if( $('#delete_relation_scope').text() === 'local' ) {
1108 $( this ).dialog( "option", "width", 160 );
b001c73d 1109 buttonset.find( "button:contains('Delete')" ).show();
1110 buttonset.find( "button:contains('Delete all')" ).hide();
1111 // Otherwise, show all three
088a14af 1112 } else {
1113 $( this ).dialog( "option", "width", 200 );
b001c73d 1114 buttonset.find( "button:contains('Delete')" ).show();
088a14af 1115 }
9529f69c 1116 mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
1117 },
088a14af 1118 close: function() {}
9529f69c 1119 });
1120
a84ca4de 1121 $( "#multipleselect-form" ).dialog({
1122 autoOpen: false,
1123 height: 150,
1124 width: 250,
1125 modal: true,
5fe117bc 1126 buttons: {
22a70299 1127 Cancel: function() { $( this ).dialog( "close" ); },
1128 Detach: function ( evt ) {
1129 var self = $(this);
1130 $( evt.target ).button( "disable" );
1131 var form_values = $('#detach_collated_form').serialize();
1132 ncpath = getTextURL( 'duplicate' );
1133 var jqjson = $.post( ncpath, form_values, function(data) {
1134 detach_node( data );
1135 $(evt.target).button("enable");
1136 self.dialog( "close" );
1137 } );
1138 }
7ef4a584 1139 },
1140 create: function(event, ui) {
a84ca4de 1141 var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
1142 buttonset.find( "button:contains('Cancel')" ).css( 'float', 'right' );
1143 },
1144 open: function() {
1145 $( this ).dialog( "option", "width", 200 );
e538eccb 1146 $(".ui-widget-overlay").css("background", "none");
5fe117bc 1147 $('#multipleselect-form-status').empty();
e538eccb 1148 $("#dialog_overlay").show();
1149 $("#dialog_overlay").height( $("#enlargement_container").height() );
1150 $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
1151 $("#dialog_overlay").offset( $("#enlargement_container").offset() );
a84ca4de 1152 },
e538eccb 1153 close: function() {
1154 marquee.unselect();
1155 $("#dialog_overlay").hide();
1156 }
5fe117bc 1157 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
1158 if( ajaxSettings.url == getTextURL('duplicate')
1159 && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
1160 var error;
1161 if( jqXHR.responseText.indexOf('do not have permission to modify') > -1 ) {
1162 error = 'You are not authorized to modify this tradition. (Try logging in again?)';
1163 } else {
1164 try {
1165 var errobj = jQuery.parseJSON( jqXHR.responseText );
1166 error = errobj.error + '</br>The relationship cannot be made.</p>';
1167 } catch(e) {
1168 error = jqXHR.responseText;
1169 }
1170 }
1171 $('#multipleselect-form-status').append( '<p class="error">Error: ' + error );
1172 }
1173 $(event.target).parent().find('.ui-button').button("enable");
1174 });
1175
a84ca4de 1176
088a14af 1177 // Helpers for relationship deletion
1178
1179 function delete_relation( scopewide ) {
1180 form_values = $('#delete_relation_form').serialize();
1181 if( scopewide ) {
1182 form_values += "&scopewide=true";
1183 }
1184 ncpath = getTextURL( 'relationships' );
1185 var jqjson = $.ajax({ url: ncpath, data: form_values, success: function(data) {
1186 $.each( data, function(item, source_target) {
1187 relation_manager.remove( get_relation_id( source_target[0], source_target[1] ) );
1188 });
1189 $( "#delete-form" ).dialog( "close" );
1190 }, dataType: 'json', type: 'DELETE' });
1191 }
1192
1193 function toggle_relation_active( node_id ) {
1194 $('#svgenlargement .relation').find( "title:contains('" + node_id + "')" ).each( function(index) {
1195 matchid = new RegExp( "^" + node_id );
1196 if( $(this).text().match( matchid ) != null ) {
1197 var relation_id = $(this).parent().attr('id');
1198 relation_manager.toggle_active( relation_id );
1199 };
1200 });
1201 }
1202
487674b9 1203 // function for reading form dialog should go here;
1204 // just hide the element for now if we don't have morphology
1205 if( can_morphologize ) {
5539cba3 1206 if( editable ) {
1207 $('#reading_decollate_witnesses').multiselect();
1208 } else {
1209 $('#decollation').hide();
1210 }
487674b9 1211 $('#reading-form').dialog({
1212 autoOpen: false,
1213 // height: 400,
1214 width: 450,
1215 modal: true,
1216 buttons: {
1217 Cancel: function() {
1218 $( this ).dialog( "close" );
1219 },
1220 Update: function( evt ) {
1221 // Disable the button
1222 $(evt.target).button("disable");
1223 $('#reading_status').empty();
1224 var reading_id = $('#reading_id').val()
1225 form_values = {
1226 'id' : reading_id,
1227 'is_nonsense': $('#reading_is_nonsense').is(':checked'),
1228 'grammar_invalid': $('#reading_grammar_invalid').is(':checked'),
1229 'normal_form': $('#reading_normal_form').val() };
1230 // Add the morphology values
1231 $('.reading_morphology').each( function() {
1232 if( $(this).val() != '(Click to select)' ) {
1233 var rmid = $(this).attr('id');
1234 rmid = rmid.substring(8);
1235 form_values[rmid] = $(this).val();
1236 }
45ee3b96 1237 });
487674b9 1238 // Make the JSON call
1239 ncpath = getReadingURL( reading_id );
1240 var reading_element = readingdata[reading_id];
1241 // $(':button :contains("Update")').attr("disabled", true);
1242 var jqjson = $.post( ncpath, form_values, function(data) {
1243 $.each( data, function(key, value) {
1244 reading_element[key] = value;
1245 });
1246 if( $('#update_workspace_button').data('locked') == false ) {
1247 color_inactive( get_ellipse( reading_id ) );
1248 }
1249 $(evt.target).button("enable");
1250 $( "#reading-form" ).dialog( "close" );
1251 });
1252 // Re-color the node if necessary
1253 return false;
1254 }
1255 },
1256 create: function() {
30d0ba1e 1257 if( !editable ) {
1258 // Get rid of the disallowed editing UI bits
1259 $( this ).dialog( "option", "buttons",
1260 [{ text: "OK", click: function() { $( this ).dialog( "close" ); }}] );
1261 $('#reading_relemmatize').hide();
1262 }
487674b9 1263 },
1264 open: function() {
1265 $(".ui-widget-overlay").css("background", "none");
5539cba3 1266 $('#reading_decollate_witnesses').multiselect("refresh");
1267 $('#reading_decollate_witnesses').multiselect("uncheckAll");
487674b9 1268 $("#dialog_overlay").show();
1269 $('#reading_status').empty();
1270 $("#dialog_overlay").height( $("#enlargement_container").height() );
1271 $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
1272 $("#dialog_overlay").offset( $("#enlargement_container").offset() );
1273 $("#reading-form").parent().find('.ui-button').button("enable");
1274 },
1275 close: function() {
1276 $("#dialog_overlay").hide();
1277 }
1278 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
21e6ebc7 1279 if( ajaxSettings.url.lastIndexOf( getReadingURL('') ) > -1
487674b9 1280 && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
21e6ebc7 1281 var error;
1282 if( jqXHR.responseText.indexOf('do not have permission to modify') > -1 ) {
1283 error = 'You are not authorized to modify this tradition. (Try logging in again?)';
1284 } else {
1285 try {
1286 var errobj = jQuery.parseJSON( jqXHR.responseText );
1287 error = errobj.error + '</br>The relationship cannot be made.</p>';
1288 } catch(e) {
1289 error = jqXHR.responseText;
1290 }
1291 }
1292 $('#status').append( '<p class="error">Error: ' + error );
1293 }
1294 $(event.target).parent().find('.ui-button').button("enable");
487674b9 1295 });
1296 } else {
1297 $('#reading-form').hide();
45ee3b96 1298 }
4c41c02c 1299
76f05423 1300
b28e606e 1301 $('#update_workspace_button').click( function() {
30d0ba1e 1302 if( !editable ) {
1303 return;
1304 }
b28e606e 1305 var svg_enlargement = $('#svgenlargement').svg().svg('get').root();
76f05423 1306 mouse_scale = svg_root_element.getScreenCTM().a;
9529f69c 1307 if( $(this).data('locked') == true ) {
1308 $('#svgenlargement ellipse' ).each( function( index ) {
1309 if( $(this).data( 'node_obj' ) != null ) {
1310 $(this).data( 'node_obj' ).ungreyout_edges();
e538eccb 1311 $(this).data( 'node_obj' ).set_selectable( false );
1312 color_inactive( $(this) );
9529f69c 1313 var node_id = $(this).data( 'node_obj' ).get_id();
1314 toggle_relation_active( node_id );
1315 $(this).data( 'node_obj', null );
1316 }
b28e606e 1317 })
b28e606e 1318 $(this).data('locked', false);
9529f69c 1319 $(this).css('background-position', '0px 44px');
b28e606e 1320 } else {
9529f69c 1321 var left = $('#enlargement').offset().left;
1322 var right = left + $('#enlargement').width();
76f05423 1323 var tf = svg_root_element.getScreenCTM().inverse();
9529f69c 1324 var p = svg_root.createSVGPoint();
1325 p.x=left;
1326 p.y=100;
1327 var cx_min = p.matrixTransform(tf).x;
1328 p.x=right;
1329 var cx_max = p.matrixTransform(tf).x;
1330 $('#svgenlargement ellipse').each( function( index ) {
1331 var cx = parseInt( $(this).attr('cx') );
1332 if( cx > cx_min && cx < cx_max) {
1333 if( $(this).data( 'node_obj' ) == null ) {
1334 $(this).data( 'node_obj', new node_obj( $(this) ) );
1335 } else {
e538eccb 1336 $(this).data( 'node_obj' ).set_selectable( true );
9529f69c 1337 }
1338 $(this).data( 'node_obj' ).greyout_edges();
1339 var node_id = $(this).data( 'node_obj' ).get_id();
1340 toggle_relation_active( node_id );
b28e606e 1341 }
9529f69c 1342 });
1343 $(this).css('background-position', '0px 0px');
b28e606e 1344 $(this).data('locked', true );
b28e606e 1345 }
1346 });
30d0ba1e 1347
1348 if( !editable ) {
1349 // Hide the unused elements
1350 $('#dialog-form').hide();
1351 $('#update_workspace_button').hide();
1352 }
1353
b28e606e 1354
e847b186 1355 $('.helptag').popupWindow({
1356 height:500,
1357 width:800,
1358 top:50,
1359 left:50,
1360 scrollbars:1
1361 });
1362
76f05423 1363 expandFillPageClients();
1364 $(window).resize(function() {
1365 expandFillPageClients();
1366 });
1367
9529f69c 1368});
b28e606e 1369
1370
76f05423 1371function expandFillPageClients() {
1372 $('.fillPage').each(function () {
1373 $(this).height($(window).height() - $(this).offset().top - MARGIN);
1374 });
1375}
1376
1377function loadSVG(svgData) {
1378 var svgElement = $('#svgenlargement');
1379
1380 $(svgElement).svg('destroy');
1381
1382 $(svgElement).svg({
1383 loadURL: svgData,
1384 onLoad : svgEnlargementLoaded
1385 });
1386}
1387
1388
c1add777 1389
76f05423 1390/* OS Gadget stuff
1391
1392function svg_select_callback(topic, data, subscriberData) {
1393 svgData = data;
1394 loadSVG(svgData);
1395}
1396
1397function loaded() {
1398 var prefs = new gadgets.Prefs();
1399 var preferredHeight = parseInt(prefs.getString('height'));
1400 if (gadgets.util.hasFeature('dynamic-height')) gadgets.window.adjustHeight(preferredHeight);
1401 expandFillPageClients();
1402}
1403
1404if (gadgets.util.hasFeature('pubsub-2')) {
1405 gadgets.HubSettings.onConnect = function(hum, suc, err) {
1406 subId = gadgets.Hub.subscribe("interedition.svg.selected", svg_select_callback);
1407 loaded();
1408 };
1409}
1410else gadgets.util.registerOnLoadHandler(loaded);
1411*/