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