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