Reuse the stemweb dialog for queries. Fixes #44
[scpubgit/stemmaweb.git] / root / js / componentload.js
1 // Global state variables
2 var selectedTextID;
3 var selectedTextInfo;
4 var selectedTextEditable;
5 var selectedStemmaID = -1;
6 var stemmata = [];
7
8 // Load the names of the appropriate traditions into the directory div.
9 function refreshDirectory () {
10         var lmesg = $('#loading_message').clone();
11         $('#directory').empty().append( lmesg.contents() );
12     $('#directory').load( _get_url(["directory"]), 
13         function(response, status, xhr) {
14                         if (status == "error") {
15                                 var msg = "An error occurred: ";
16                                 $("#directory").html(msg + xhr.status + " " + xhr.statusText);
17                         } else {
18                                 if( textOnLoad != "" ) {
19                                         // Call the click callback for the relevant text, if it is
20                                         // in the page.
21                                         $('#'+textOnLoad).click();
22                                         textOnLoad = "";
23                                 }
24                         }
25                 }
26         );
27 }
28
29 // Load a tradition with its information and stemmata into the tradition
30 // view pane. Calls load_textinfo.
31 function loadTradition( textid, textname, editable ) {
32         selectedTextID = textid;
33         selectedTextEditable = editable;
34     // First insert the placeholder image and register an error handler
35     $('#textinfo_load_status').empty();
36     $('#stemma_graph').empty();
37     $('#textinfo_waitbox').show();
38     $('#textinfo_container').hide().ajaxError( 
39         function(event, jqXHR, ajaxSettings, thrownError) {
40         if( ajaxSettings.url.indexOf( 'textinfo' ) > -1 && ajaxSettings.type == 'GET'  ) {
41                         $('#textinfo_waitbox').hide();
42                         $('#textinfo_container').show();
43                         display_error( jqXHR, $("#textinfo_load_status") );
44         }
45     });
46     
47     // Hide the functionality that is irrelevant
48     if( editable ) {
49         $('#open_stemma_add').show();
50         $('#open_textinfo_edit').show();
51         $('#relatebutton_label').text('View collation and edit relationships');
52     } else {
53         $('#open_stemma_add').hide();
54         $('#open_stemweb_ui').hide();
55         $('#query_stemweb_ui').hide();
56         $('#open_textinfo_edit').hide();
57         $('#relatebutton_label').text('View collation and relationships');
58     }
59
60     // Then get and load the actual content.
61     // TODO: scale #stemma_graph both horizontally and vertically
62     // TODO: load svgs from SVG.Jquery (to make scaling react in Safari)
63     $.getJSON( _get_url([ "textinfo", textid ]), function (textdata) {
64         // Add the scalar data
65         selectedTextInfo = textdata;
66         load_textinfo();
67         // Add the stemma(ta)
68         stemmata = textdata.stemmata;
69         if( stemmata.length ) {
70                 selectedStemmaID = 0;
71         } else {
72                 selectedStemmaID = -1;
73                 }
74                 load_stemma( selectedStemmaID );
75         // Set up the relationship mapper button
76                 $('#run_relater').attr( 'action', _get_url([ "relation", textid ]) );
77                 // Set up the download button
78                 $('#dl_tradition').attr( 'href', _get_url([ "download", textid ]) );
79                 $('#dl_tradition').attr( 'download', selectedTextInfo.name + '.xml' );
80         });
81 }
82
83 // Load the metadata about a tradition into the appropriate div.
84 function load_textinfo() {
85         $('#textinfo_waitbox').hide();
86         $('#textinfo_load_status').empty();
87         $('#textinfo_container').show();
88         $('.texttitle').empty().append( selectedTextInfo.name );
89         // Witnesses
90         $('#witness_num').empty().append( selectedTextInfo.witnesses.size );
91         $('#witness_list').empty().append( selectedTextInfo.witnesses.join( ', ' ) );
92         // Who the owner is
93         $('#owner_id').empty().append('no one');
94         if( selectedTextInfo.owner ) {
95                 var owneremail = selectedTextInfo.owner;
96                 var chop = owneremail.indexOf( '@' );
97                 if( chop > -1 ) {
98                         owneremail = owneremail.substr( 0, chop + 1 ) + '...';
99                 }
100                 $('#owner_id').empty().append( owneremail );
101         }
102         // Whether or not it is public
103         $('#not_public').empty();
104         if( selectedTextInfo['public'] == false ) {
105                 $('#not_public').append('NOT ');
106         }
107         // What language setting it has, if any
108         $('#marked_language').empty().append('no language set');
109         if( selectedTextInfo.language && selectedTextInfo.language != 'Default' ) {
110                 $('#marked_language').empty().append( selectedTextInfo.language );
111         }
112 }       
113
114 // Enable / disable the appropriate buttons for paging through the stemma.
115 function show_stemmapager () {
116       $('.pager_left_button').unbind('click').addClass( 'greyed_out' );
117       $('.pager_right_button').unbind('click').addClass( 'greyed_out' );
118       if( selectedStemmaID > 0 ) {
119               $('.pager_left_button').click( function () {
120                       load_stemma( selectedStemmaID - 1, selectedTextEditable );
121               }).removeClass( 'greyed_out' );
122       }       
123       if( selectedStemmaID + 1 < stemmata.length ) {
124               $('.pager_right_button').click( function () {
125                       load_stemma( selectedStemmaID + 1, selectedTextEditable );
126               }).removeClass( 'greyed_out' );
127       }
128 }
129
130 // Load a given stemma SVG into the stemmagraph box.
131 function load_stemma( idx ) {
132         // Load the stemma at idx
133         selectedStemmaID = idx;
134         show_stemmapager( selectedTextEditable );
135         $('#open_stemma_edit').hide();
136         $('#run_stexaminer').hide();
137         $('#stemma_identifier').empty();
138         // Add the relevant Stemweb functionality
139         if( selectedTextEditable ) {
140                 switch_stemweb_ui();
141         }
142         if( idx > -1 ) {
143                 // Load the stemma and its properties
144                 var stemmadata = stemmata[idx];
145                 if( selectedTextEditable ) {
146                         $('#open_stemma_edit').show();
147                 }
148                 if( stemmadata.directed ) {
149                         // Stexaminer submit action
150                         var stexpath = _get_url([ "stexaminer", selectedTextID, idx ]);
151                         $('#run_stexaminer').attr( 'action', stexpath );
152                         $('#run_stexaminer').show();
153                 }
154                 loadSVG( stemmadata.svg );
155                 $('#stemma_identifier').text( stemmadata.name );
156         setTimeout( 'start_element_height = $("#stemma_graph .node")[0].getBBox().height;', 500 );
157         }
158 }
159
160 function switch_stemweb_ui() {
161         if( selectedTextInfo.stemweb_jobid == 0 ) {
162                 // We want to run Stemweb.
163                 $('#open_stemweb_ui').show();
164                 $('#call_stemweb').show()
165                 $('#query_stemweb_ui').hide();
166                 $('#stemweb_run_button').show();
167         } else {
168                 $('#query_stemweb_ui').show();
169                 $('#open_stemweb_ui').hide();
170                 $('#call_stemweb').hide();
171                 $('#stemweb_run_button').hide();
172         }
173 }
174
175 function query_stemweb_progress() {
176         var requrl = _get_url([ "stemweb", "query", selectedTextInfo.stemweb_jobid ]);
177         $('#stemweb-ui-dialog').dialog('open');
178         $('#stemweb_run_status').empty().append( 
179                                 _make_message( 'notification', 'Querying Stemweb for calculation progress...') );
180         $.getJSON( requrl, function (data) {
181                 process_stemweb_result( data );
182         });
183         // TODO need an error handler
184 }
185
186 function process_stemweb_result(data) {
187         // Look for a status message, either success, running, or notfound.
188         if( data.status === 'success' ) {
189                 // Add the new stemmata to the textinfo and tell the user.
190                 selectedTextInfo.stemweb_jobid = 0;
191                 if( data.stemmata.length > 0 ) {
192                         stemmata = stemmata.concat( data.stemmata );
193                         if( selectedStemmaID == -1 ) {
194                                 // We have a stemma for the first time; load the first one.
195                                 load_stemma( 0, true );
196                         } else {
197                                 // Move to the index of the first added stemma.
198                                 var newIdx = stemmata.length - data.stemmata.length;
199                                 load_stemma( newIdx, true );
200                         } 
201                         $('#stemweb_run_status').empty().append( 
202                                 _make_message( 'notification', 'You have one or more new stemmata!' ) );
203                 } else {
204                         $('#stemweb_run_status').empty().append( 
205                                 _make_message( 'warning', 'Stemweb run finished with no stemmata...huh?!' ) );
206                 }
207         } else if( data.status === 'running' ) {
208                 // Just tell the user.
209                 $('#stemweb_run_status').empty().append( 
210                                 _make_message( 'notification', 'Your Stemweb query is still running!' ) );
211         } else if( data.status === 'notfound' ) {
212                 // Ask the user to refresh, for now.
213                 $('#stemweb_run_status').empty().append( 
214                                 _make_message( 'warning', 'Your Stemweb query probably finished and reported back. Please reload to check.' ) );
215         } else if( data.status === 'failed' ) {
216                 selectedTextInfo.stemweb_jobid = 0;
217                 failureMsg = 'Your stemweb query failed';
218                 if( data.message ) {
219                         failureMsg = failureMsg + ' with the following message: ' + data.message
220                 }
221                 $('#stemweb_run_status').empty().append( 
222                                 _make_message( 'error', failuremsg + '.' ) );
223         }
224         switch_stemweb_ui();
225 }
226
227 function _make_message( type, msg ) {
228         theMessage = $('<span>').attr( 'class', type );
229         theMessage.append( msg );
230         return theMessage;
231 }
232
233 // Load the SVG we are given
234 function loadSVG(svgData) {
235         var svgElement = $('#stemma_graph');
236
237         $(svgElement).svg('destroy');
238
239         $(svgElement).svg({
240                 loadURL: svgData,
241                 onLoad : function () {
242                         var theSVG = svgElement.find('svg');
243                         var svgoffset = theSVG.offset();
244                         var browseroffset = 1;
245                         // Firefox needs a different offset, stupidly enough
246                         if( navigator.userAgent.indexOf('Firefox') > -1 ) {
247                                 browseroffset = 3; // works for tall images
248                                 // ...but if the SVG is wider than it is tall, Firefox treats
249                                 // the top as being the top of the graph, loaded into the middle
250                                 // of the canvas, but then the margin at the top of the canvas
251                                 // extends upward. So we have to find the actual top of the canvas
252                                 // and correct for *that* instead.
253                                 var vbdim = svgElement.svg().svg('get').root().viewBox.baseVal;
254                                 if( vbdim.height < vbdim.width ) {
255                                         var vbscale = svgElement.width() / vbdim.width;
256                                         var vbrealheight = vbdim.height * vbscale;
257                                         browseroffset = 3 + ( svgElement.height() - vbrealheight ) / 2;
258                                 }
259                         }
260                         var topoffset = theSVG.position().top - svgElement.position().top - browseroffset;
261                         theSVG.offset({ top: svgoffset.top - topoffset, left: svgoffset.left });
262                         set_stemma_interactive( theSVG );
263                 }
264         });
265 }
266
267 function set_stemma_interactive( svg_element ) {
268         if( selectedTextEditable ) {
269                 $( "#root_tree_dialog_button_ok" ).click( function() {
270                         var requrl = _get_url([ "stemmaroot", selectedTextID, selectedStemmaID ]);
271                         var targetnode = $('#root_tree_dialog').data( 'selectedNode' );
272                         $.post( requrl, { root: targetnode }, function (data) {
273                                 // Reload the new stemma
274                                 stemmata[selectedStemmaID] = data;
275                                 load_stemma( selectedStemmaID );
276                                 // Put away the dialog
277                                 $('#root_tree_dialog').data( 'selectedNode', null ).hide();
278                         } );
279                 } ).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
280                         if( ajaxSettings.url.indexOf( 'stemmaroot' ) > -1 
281                                 && ajaxSettings.type == 'POST' ) {
282                                 display_error( jqXHR, $("#stemma_load_status") );
283                         }
284                 } );
285                 // TODO Clear error at some appropriate point
286                 $.each( $( 'ellipse', svg_element ), function(index) {
287                         var ellipse = $(this);
288                         var g = ellipse.parent( 'g' );
289                         g.click( function(evt) {
290                                 if( typeof root_tree_dialog_timeout !== 'undefined' ) { clearTimeout( root_tree_dialog_timeout ) };
291                                 g.unbind( 'mouseleave' );
292                                 var dialog = $( '#root_tree_dialog' );
293                                 // Note which node triggered the dialog
294                                 dialog.data( 'selectedNode', g.attr('id') );
295                                 // Position the dialog
296                                 dialog.hide();
297                                 dialog.css( 'top', evt.pageY + 3 );
298                                 dialog.css( 'left', evt.pageX + 3 );
299                                 dialog.show();
300                                 root_tree_dialog_timeout = setTimeout( function() {
301                                         $( '#root_tree_dialog' ).data( 'selectedNode', null ).hide();
302                                         ellipse.removeClass( 'stemma_node_highlight' );
303                                         g.mouseleave( function() { ellipse.removeClass( 'stemma_node_highlight' ) } );
304                                 }, 3000 );
305                         } );
306                         g.mouseenter( function() { 
307                                 $( 'ellipse.stemma_node_highlight' ).removeClass( 'stemma_node_highlight' );
308                                 ellipse.addClass( 'stemma_node_highlight' ) 
309                         } );
310                         g.mouseleave( function() { ellipse.removeClass( 'stemma_node_highlight' ) } );
311                 } );
312         }
313 }
314
315 // General-purpose error-handling function.
316 // TODO make sure this gets used throughout, where appropriate.
317 function display_error( jqXHR, el ) {
318         var errmsg;
319         if( jqXHR.responseText == "" ) {
320                 errmsg = "perhaps the server went down?"
321         } else {
322                 var errobj;
323                 try {
324                         errobj = jQuery.parseJSON( jqXHR.responseText );
325                         errmsg = errobj.error;
326                 } catch ( parse_err ) {
327                         errmsg = "something went wrong on the server."
328                 }
329         }
330         var msghtml = $('<span>').attr('class', 'error').text( "An error occurred: " + errmsg );
331         $(el).empty().append( msghtml ).show();
332 }
333
334 // Event to enable the upload button when a file has been selected
335 function file_selected( e ) {
336         if( e.files.length == 1 ) {
337                 $('#upload_button').button('enable');
338                 $('#new_file_name_container').html( '<span id="new_file_name">' + e.files[0].name + '</span>' );
339         } else {
340                 $('#upload_button').button('disable');
341                 $('#new_file_name_container').html( '(Use \'pick file\' to select a tradition file to upload.)' );
342         }
343 }
344
345 // Implement our own AJAX method that uses the features of XMLHttpRequest2
346 // but try to let it have a similar interface to jquery.post
347 // The data var needs to be a FormData() object.
348 // The callback will be given a single argument, which is the response data
349 // of the given type.
350
351 function post_xhr2( url, data, cb, type ) {
352         if( !type ) {
353                 type = 'json';
354         }
355         var xhr = new XMLHttpRequest();
356         // Set the expected response type
357         if( type === 'data' ) {
358                 xhr.responseType = 'blob';
359         } else if( type === 'xml' ) {
360                 xhr.responseType = 'document';
361         } 
362         // Post the form
363         // Gin up an AJAX settings object
364         $.ajaxSetup({ url: url, type: 'POST' });
365         xhr.open( 'POST', url, true );
366         // Handle the results
367         xhr.onload = function( e ) {
368                 // Get the response and parse it
369                 // Call the callback with the response, whatever it was
370                 var xhrs = e.target;
371                 if( xhrs.status > 199 && xhrs.status < 300  ) { // Success
372                         var resp;
373                         if( type === 'json' ) {
374                                 resp = $.parseJSON( xhrs.responseText );
375                         } else if ( type === 'xml' ) {
376                                 resp = xhrs.responseXML;
377                         } else if ( type === 'text' ) {
378                                 resp = xhrs.responseText;
379                         } else {
380                                 resp = xhrs.response;
381                         }
382                         cb( resp );
383                 } else {
384                         // Trigger the ajaxError...
385                         _trigger_ajaxerror( e );
386                 }
387         };
388         xhr.onerror = _trigger_ajaxerror;
389         xhr.onabort = _trigger_ajaxerror;
390         xhr.send( data );
391 }
392
393 function _trigger_ajaxerror( e ) {
394         var xhr = e.target;
395         var thrown = xhr.statusText || 'Request error';
396         jQuery.event.trigger( 'ajaxError', [ xhr, $.ajaxSettings, thrown ]);
397 }
398
399 function upload_new () {
400         // Serialize the upload form, get the file and attach it to the request,
401         // POST the lot and handle the response.
402         var newfile = $('#new_file').get(0).files[0];
403         var reader = new FileReader();
404         reader.onload = function( evt ) {
405                 var data = new FormData();
406                 $.each( $('#new_tradition').serializeArray(), function( i, o ) {
407                                 data.append( o.name, o.value );
408                         });
409                 data.append( 'file', newfile );
410                 var upload_url = _get_url([ 'newtradition' ]);
411                 post_xhr2( upload_url, data, function( ret ) {
412                         if( ret.id ) {
413                                 $('#upload-collation-dialog').dialog('close');
414                                 refreshDirectory();
415                                 loadTradition( ret.id, ret.name, 1 );
416                         } else if( ret.error ) {
417                                 $('#upload_status').empty().append( 
418                                         $('<span>').attr('class', 'error').append( ret.error ) );
419                         }
420                 }, 'json' );
421         };
422         reader.onerror = function( evt ) {
423                 var err_resp = 'File read error';
424                 if( e.name == 'NotFoundError' ) {
425                         err_resp = 'File not found';
426                 } else if ( e.name == 'NotReadableError' ) {
427                         err_resp == 'File unreadable - is it yours?';
428                 } else if ( e.name == 'EncodingError' ) {
429                         err_resp == 'File cannot be encoded - is it too long?';
430                 } else if ( e.name == 'SecurityError' ) {
431                         err_resp == 'File read security error';
432                 }
433                 // Fake a jqXHR object that we can pass to our generic error handler.
434                 var jqxhr = { responseText: '{error:"' + err_resp + '"}' };
435                 display_error( jqxhr, $('#upload_status') );
436                 $('#upload_button').button('disable');
437         }
438         
439         reader.readAsBinaryString( newfile );
440 }
441
442 // Utility function to neatly construct an application URL
443 function _get_url( els ) {
444         return basepath + els.join('/');
445 }
446
447 // TODO Attach unified ajaxError handler to document
448 $(document).ready( function() {
449         // See if we have the browser functionality we need
450         // TODO Also think of a test for SVG readiness
451         if( !!window.FileReader && !!window.File ) {
452                 $('#compatibility_check').empty();
453         }
454
455     // hide dialog not yet in use
456     $('#root_tree_dialog').hide();
457         
458     // call out to load the directory div
459     $('#textinfo_container').hide();
460     $('#textinfo_waitbox').hide();
461         refreshDirectory();
462         
463         // Set up the textinfo edit dialog
464         $('#textinfo-edit-dialog').dialog({
465                 autoOpen: false,
466                 height: 200,
467                 width: 300,
468                 modal: true,
469                 buttons: {
470                         Save: function (evt) {
471                                 $("#edit_textinfo_status").empty();
472                                 var mybuttons = $(evt.target).closest('button').parent().find('button');
473                                 mybuttons.button( 'disable' );
474                                 var requrl = _get_url([ "textinfo", selectedTextID ]);
475                                 var reqparam = $('#edit_textinfo').serialize();
476                                 $.post( requrl, reqparam, function (data) {
477                                         // Reload the selected text fields
478                                         selectedTextInfo = data;
479                                         load_textinfo();
480                                         // Reenable the button and close the form
481                                         mybuttons.button("enable");
482                                         $('#textinfo-edit-dialog').dialog('close');
483                                 }, 'json' );
484                         },
485                         Cancel: function() {
486                                 $('#textinfo-edit-dialog').dialog('close');
487                         }
488                 },
489                 open: function() {
490                         $("#edit_textinfo_status").empty();
491                         // Populate the form fields with the current values
492                         // edit_(name, language, public, owner)
493                         $.each([ 'name', 'language', 'owner' ], function( idx, k ) {
494                                 var fname = '#edit_' + k;
495                                 // Special case: language Default is basically language null
496                                 if( k == 'language' && selectedTextInfo[k] == 'Default' ) {
497                                         $(fname).val( "" );
498                                 } else {
499                                         $(fname).val( selectedTextInfo[k] );
500                                 }
501                         });
502                         if( selectedTextInfo['public'] == true ) {
503                                 $('#edit_public').attr('checked','true');
504                         } else {
505                                 $('#edit_public').removeAttr('checked');
506                         }
507                 },
508         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
509                 $(event.target).parent().find('.ui-button').button("enable");
510         if( ajaxSettings.url.indexOf( 'textinfo' ) > -1 
511                 && ajaxSettings.type == 'POST' ) {
512                         display_error( jqXHR, $("#edit_textinfo_status") );
513         }
514         });
515
516         
517         // Set up the stemma editor dialog
518         $('#stemma-edit-dialog').dialog({
519                 autoOpen: false,
520                 height: 700,
521                 width: 600,
522                 modal: true,
523                 buttons: {
524                         Save: function (evt) {
525                                 $("#edit_stemma_status").empty();
526                                 var mybuttons = $(evt.target).closest('button').parent().find('button');
527                                 mybuttons.button( 'disable' );
528                                 var stemmaseq = $('#stemmaseq').val();
529                                 var requrl = _get_url([ "stemma", selectedTextID, stemmaseq ]);
530                                 var reqparam = { 'dot': $('#dot_field').val() };
531                                 // TODO We need to stash the literal SVG string in stemmata
532                                 // somehow. Implement accept header on server side to decide
533                                 // whether to send application/json or application/xml?
534                                 $.post( requrl, reqparam, function (data) {
535                                         // We received a stemma SVG string in return. 
536                                         // Update the current stemma sequence number
537                                         selectedStemmaID = data.stemmaid;
538                                         delete data.stemmaid;
539                                         // Stash the answer in the appropriate spot in our stemma array
540                                         stemmata[selectedStemmaID] = data;
541                                         // Display the new stemma
542                                         load_stemma( selectedStemmaID, true );
543                                         // Reenable the button and close the form
544                                         mybuttons.button("enable");
545                                         $('#stemma-edit-dialog').dialog('close');
546                                 }, 'json' );
547                         },
548                         Cancel: function() {
549                                 $('#stemma-edit-dialog').dialog('close');
550                         }
551                 },
552                 open: function(evt) {
553                         $("#edit_stemma_status").empty();
554                         var stemmaseq = $('#stemmaseq').val();
555                         if( stemmaseq == 'n' ) {
556                                 // If we are creating a new stemma, populate the textarea with a
557                                 // bare digraph.
558                                 $(evt.target).dialog('option', 'title', 'Add a new stemma')
559                                 $('#dot_field').val( "digraph \"NAME STEMMA HERE\" {\n\n}" );
560                         } else {
561                                 // If we are editing a stemma, grab its stemmadot and populate the
562                                 // textarea with that.
563                                 $(evt.target).dialog('option', 'title', 'Edit selected stemma')
564                                 $('#dot_field').val( 'Loading, please wait...' );
565                                 var doturl = _get_url([ "stemmadot", selectedTextID, stemmaseq ]);
566                                 $.getJSON( doturl, function (data) {
567                                         // Re-insert the line breaks
568                                         var dotstring = data.dot.replace(/\|n/gm, "\n");                                        
569                                         $('#dot_field').val( dotstring );
570                                 });
571                         }
572                 },
573         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
574                 $(event.target).parent().find('.ui-button').button("enable");
575         if( ajaxSettings.url.indexOf( 'stemma' ) > -1 
576                 && ajaxSettings.type == 'POST' ) {
577                         display_error( jqXHR, $("#edit_stemma_status") );
578         }
579         });
580
581         $('#stemweb-ui-dialog').dialog({
582                 autoOpen: false,
583                 height: 'auto',
584                 width: 520,
585                 modal: true,
586                 buttons: {
587                         Run: {
588                                 id: 'stemweb_run_button',
589                                 text: 'Run',
590                                 click: function (evt) {
591                                 $("#stemweb_run_status").empty();
592                                 var mybuttons = $(evt.target).closest('button').parent().find('button');
593                                 mybuttons.button( 'disable' );
594                                 var requrl = _get_url([ "stemweb", "request" ]);
595                                 var reqparam = $('#call_stemweb').serialize();
596                                 // TODO We need to stash the literal SVG string in stemmata
597                                 // somehow. Implement accept header on server side to decide
598                                 // whether to send application/json or application/xml?
599                                 $.getJSON( requrl, reqparam, function (data) {
600                                         mybuttons.button("enable");
601                                         $('#stemweb-ui-dialog').dialog('close');
602                                         if( 'jobid' in data ) {
603                                                 // There is a pending job.
604                                                 selectedTextInfo.stemweb_jobid = data.jobid;
605                                                 alert("Your request has been submitted to Stemweb.\nThe resulting tree will appear in due course.");
606                                                 // Reload the current stemma to rejigger the buttons
607                                                 load_stemma( selectedStemmaID, true );
608                                         } else {
609                                                 // We appear to have an answer; process it.
610                                                 process_stemweb_result( data );
611                                         }
612                                 }, 'json' );
613                                 },
614                         },
615                         Close: {
616                                 id: 'stemweb_close_button',
617                                 text: 'Close',
618                                 click: function() {
619                                 $('#stemweb-ui-dialog').dialog('close');
620                                 },
621                         },
622                 },
623                 create: function(evt) {
624                         // Call out to Stemweb to get the algorithm options, with which we
625                         // populate the form.
626                         var algorithmTypes = {};
627                         var algorithmArgs = {};
628                         var requrl = _get_url([ "stemweb", "available" ]);
629                         $.getJSON( requrl, function( data ) {
630                                 $.each( data, function( i, o ) {
631                                         if( o.model === 'algorithms.algorithm' ) {
632                                                 // it's an algorithm.
633                                                 algorithmTypes[ o.pk ] = o.fields;
634                                         } else if( o.model == 'algorithms.algorithmarg' && o.fields.external ) {
635                                                 // it's an option for an algorithm that we should display.
636                                                 algorithmArgs[ o.pk ] = o.fields;
637                                         }
638                                 });
639                                 // TODO if it is an empty object, disable Stemweb entirely.
640                                 if( !jQuery.isEmptyObject( algorithmTypes ) ) {
641                                         $.each( algorithmTypes, function( pk, fields ) {
642                                                 var algopt = $('<option>').attr( 'value', pk ).append( fields.name );
643                                                 $('#stemweb_algorithm').append( algopt );
644                                         });
645                                         // Set up the relevant options for whichever algorithm is chosen.
646                                         // "key" -> form name, option ID "stemweb_$key_opt"
647                                         // "name" -> form label
648                                         $('#stemweb_algorithm_help').click( function() {
649                                                 $('#stemweb_algorithm_desc_text').toggle( 'blind' );
650                                                 });
651                                         $('#stemweb_algorithm').change( function() {
652                                                 var pk = $(this).val();
653                                                 // Display a link to the popup description, and fill in
654                                                 // the description itself, if we have one.
655                                                 if( 'desc' in algorithmTypes[pk] ) {
656                                                         $('#stemweb_algorithm_desc_text').empty().append( algorithmTypes[pk].desc );
657                                                         $('#stemweb_algorithm_desc').show();
658                                                 } else {
659                                                         $('#stemweb_algorithm_desc').hide();
660                                                 }
661                                                 $('#stemweb_runtime_options').empty();
662                                                 $.each( algorithmTypes[pk].args, function( i, apk ) {
663                                                         var argInfo = algorithmArgs[apk];
664                                                         if( argInfo ) {
665                                                                 // Make the element ID
666                                                                 var optId = 'stemweb_' + argInfo.key + '_opt';
667                                                                 // Make the label
668                                                                 var optLabel = $('<label>').attr( 'for', optId )
669                                                                         .append( argInfo.name + ": " );
670                                                                 var optCtrl;
671                                                                 var argType = argInfo.value;
672                                                                 if( argType === 'positive_integer' ) {
673                                                                         // Make it an input field of smallish size.
674                                                                         optCtrl = $('<input>').attr( 'size', 4 );
675                                                                 } else if ( argType === 'boolean' ) {
676                                                                         // Make it a checkbox.
677                                                                         optCtrl = $('<checkbox>');
678                                                                 }
679                                                                 // Add the name and element ID
680                                                                 optCtrl.attr( 'name', argInfo.key ).attr( 'id', optId );
681                                                                 // Append the label and the option itself to the form.
682                                                                 $('#stemweb_runtime_options').append( optLabel )
683                                                                         .append( optCtrl ).append( $('<br>') );
684                                                         }
685                                                 });
686                                         });
687                                         $('#stemweb_algorithm').change();
688                                 }
689                         });
690                         // Prime the initial options
691                 },
692                 open: function(evt) {
693                         $('#stemweb_run_status').empty();
694                         $('#stemweb_tradition').attr('value', selectedTextID );
695                         if( selectedTextInfo.stemweb_jobid == 0 ) {
696                                 $('#stemweb_merge_reltypes').empty();
697                                 $.each( selectedTextInfo.reltypes, function( i, r ) {
698                                         var relation_opt = $('<option>').attr( 'value', r ).append( r );
699                                         $('#stemweb_merge_reltypes').append( relation_opt );
700                                 });
701                                 $('#stemweb_merge_reltypes').multiselect({ 
702                                         header: false,
703                                         selectedList: 3
704                                 });
705                         }
706                 },
707         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
708                 $(event.target).parent().find('.ui-button').button("enable");
709         if( ajaxSettings.url.indexOf( 'stemweb/' ) > -1 ) {
710                         display_error( jqXHR, $("#stemweb_run_status") );
711         }
712         });
713                 
714         // Set up the download dialog
715         $('#download-dialog').dialog({
716                 autoOpen: false,
717                 height: 150,
718                 width: 300,
719                 modal: true,
720                 buttons: {
721                         Download: function (evt) {
722                                 var dlurl = _get_url([ "download", $('#download_tradition').val(), $('#download_format').val() ]);
723                                 window.location = dlurl;
724                         },
725                         Done: function() {
726                                 $('#download-dialog').dialog('close');
727                         }
728                 },
729                 open: function() {
730                         $('#download_tradition').attr('value', selectedTextID );
731                 },
732         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
733                 $(event.target).parent().find('.ui-button').button("enable");
734         if( ajaxSettings.url.indexOf( 'download' ) > -1 
735                 && ajaxSettings.type == 'POST' ) {
736                         display_error( jqXHR, $("#download_status") );
737         }
738         });
739
740         $('#upload-collation-dialog').dialog({
741                 autoOpen: false,
742                 height: 360,
743                 width: 480,
744                 modal: true,
745                 buttons: {
746                   upload: {
747                     text: 'Upload',
748                     id: 'upload_button',
749                     click: function() {
750                             $('#upload_status').empty();
751                             $('#upload_button').button("disable");
752                 upload_new();
753             }
754                   },
755                   pick_file: {
756                     text: 'Pick File',
757                     id: 'pick_file_button',
758                     click: function() {
759                 $('#new_file').click();
760             }
761                   },
762                   Cancel: function() {
763                     $('#upload-collation-dialog').dialog('close');
764                   }
765                 },
766                 open: function() {
767                         // Set the upload button to its correct state based on
768                         // whether a file is loaded
769                         file_selected( $('#new_file').get(0) );
770                         $('#upload_status').empty();
771                 }
772         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
773                 // Reset button state
774                 file_selected( $('#new_file').get(0) );
775                 // Display error message if applicable
776         if( ajaxSettings.url.indexOf( 'newtradition' ) > -1 
777                 && ajaxSettings.type == 'POST' ) {
778                         display_error( jqXHR, $("#upload_status") );
779         }
780         });;
781         
782         $('#stemma_graph').mousedown( function(evt) {
783         evt.stopPropagation();
784         $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
785         $('body').mousemove( function(evt) {
786             mouse_scale = 1; // for now, was:  mouse_scale = svg_root_element.getScreenCTM().a;
787             dx = (evt.clientX - $('#stemma_graph').data( 'mousedown_xy' )[0]) / mouse_scale;
788             dy = (evt.clientY - $('#stemma_graph').data( 'mousedown_xy' )[1]) / mouse_scale;
789             $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
790             var svg_root = $('#stemma_graph svg').svg().svg('get').root();
791             var g = $('g.graph', svg_root).get(0);
792             current_translate = g.getAttribute( 'transform' ).split(/translate\(/)[1].split(')',1)[0].split(' ');
793             new_transform = g.getAttribute( 'transform' ).replace( /translate\([^\)]*\)/, 'translate(' + (parseFloat(current_translate[0]) + dx) + ' ' + (parseFloat(current_translate[1]) + dy) + ')' );
794             g.setAttribute( 'transform', new_transform );
795             evt.returnValue = false;
796             evt.preventDefault();
797             return false;
798         });
799         $('body').mouseup( function(evt) {
800             $('body').unbind('mousemove');
801             $('body').unbind('mouseup');
802         });
803         });
804          
805         $('#stemma_graph').mousewheel(function (event, delta) {
806         event.returnValue = false;
807         event.preventDefault();
808         if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
809         if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
810         if( delta < -9 ) { delta = -9 }; 
811         var z = 1 + delta/10;
812         z = delta > 0 ? 1 : -1;
813         var svg_root = $('#stemma_graph svg').svg().svg('get').root();
814         var g = $('g.graph', svg_root).get(0);
815         if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 1000))) {
816             var scaleLevel = z/10;
817             current_scale = parseFloat( g.getAttribute( 'transform' ).split(/scale\(/)[1].split(')',1)[0].split(' ')[0] );
818             new_transform = g.getAttribute( 'transform' ).replace( /scale\([^\)]*\)/, 'scale(' + (current_scale + scaleLevel) + ')' );
819             g.setAttribute( 'transform', new_transform );
820         }
821     });
822     
823 });