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