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