add main 'about' page, move most index page JS into componentload, rationalize the...
[scpubgit/stemmaweb.git] / root / js / componentload.js
1 // Global state variables
2 var selectedTextID;
3 var selectedTextInfo;
4 var selectedStemmaID = -1;
5 var stemmata = [];
6
7 // Load the names of the appropriate traditions into the directory div.
8 function refreshDirectory () {
9         var lmesg = $('#loading_message').clone();
10         $('#directory').empty().append( lmesg.contents() );
11     $('#directory').load( _get_url(["directory"]), 
12         function(response, status, xhr) {
13                         if (status == "error") {
14                                 var msg = "An error occurred: ";
15                                 $("#directory").html(msg + xhr.status + " " + xhr.statusText);
16                         } else {
17                                 if( textOnLoad != "" ) {
18                                         // Call the click callback for the relevant text, if it is
19                                         // in the page.
20                                         $('#'+textOnLoad).click();
21                                         textOnLoad = "";
22                                 }
23                         }
24                 }
25         );
26 }
27
28 // Load a tradition with its information and stemmata into the tradition
29 // view pane. Calls load_textinfo.
30 function loadTradition( textid, textname, editable ) {
31         selectedTextID = textid;
32     // First insert the placeholder image and register an error handler
33     $('#textinfo_load_status').empty();
34     $('#stemma_graph').empty();
35     $('#textinfo_waitbox').show();
36     $('#textinfo_container').hide().ajaxError( 
37         function(event, jqXHR, ajaxSettings, thrownError) {
38         if( ajaxSettings.url.indexOf( 'textinfo' ) > -1 && ajaxSettings.type == 'GET'  ) {
39                         $('#textinfo_waitbox').hide();
40                         $('#textinfo_container').show();
41                         display_error( jqXHR, $("#textinfo_load_status") );
42         }
43     });
44     
45     // Hide the functionality that is irrelevant
46     if( editable ) {
47         $('#open_stemma_add').show();
48         $('#open_stemma_edit').show();
49         $('#open_textinfo_edit').show();
50     } else {
51         $('#open_stemma_add').hide();
52         $('#open_stemma_edit').hide();
53         $('#open_textinfo_edit').hide();
54     }
55
56     // Then get and load the actual content.
57     // TODO: scale #stemma_graph both horizontally and vertically
58     // TODO: load svgs from SVG.Jquery (to make scaling react in Safari)
59     $.getJSON( _get_url([ "textinfo", textid ]), function (textdata) {
60         // Add the scalar data
61         selectedTextInfo = textdata;
62         load_textinfo();
63         // Add the stemma(ta) and set up the stexaminer button
64         stemmata = textdata.stemmata;
65         if( stemmata.length ) {
66                 selectedStemmaID = 0;
67                         $('#run_stexaminer').show();
68         } else {
69                 selectedStemmaID = -1;
70                         $('#open_stemma_edit').hide();
71                         $('#run_stexaminer').hide();
72                 }
73                 load_stemma( selectedStemmaID );
74         // Set up the relationship mapper button
75                 $('#run_relater').attr( 'action', _get_url([ "relation", textid ]) );
76         });
77 }
78
79 // Load the metadata about a tradition into the appropriate div.
80 function load_textinfo() {
81         $('#textinfo_waitbox').hide();
82         $('#textinfo_load_status').empty();
83         $('#textinfo_container').show();
84         $('.texttitle').empty().append( selectedTextInfo.name );
85         // Witnesses
86         $('#witness_num').empty().append( selectedTextInfo.witnesses.size );
87         $('#witness_list').empty().append( selectedTextInfo.witnesses.join( ', ' ) );
88         // Who the owner is
89         $('#owner_id').empty().append('no one');
90         if( selectedTextInfo.owner ) {
91                 $('#owner_id').empty().append( selectedTextInfo.owner );
92         }
93         // Whether or not it is public
94         $('#not_public').empty();
95         if( selectedTextInfo['public'] == false ) {
96                 $('#not_public').append('NOT ');
97         }
98         // What language setting it has, if any
99         $('#marked_language').empty().append('no language set');
100         if( selectedTextInfo.language && selectedTextInfo.language != 'Default' ) {
101                 $('#marked_language').empty().append( selectedTextInfo.language );
102         }
103 }       
104
105 // Enable / disable the appropriate buttons for paging through the stemma.
106 function show_stemmapager () {
107       $('.pager_left_button').unbind('click').addClass( 'greyed_out' );
108       $('.pager_right_button').unbind('click').addClass( 'greyed_out' );
109       if( selectedStemmaID > 0 ) {
110               $('.pager_left_button').click( function () {
111                       load_stemma( selectedStemmaID - 1 );
112               }).removeClass( 'greyed_out' );
113       }       
114       if( selectedStemmaID + 1 < stemmata.length ) {
115               $('.pager_right_button').click( function () {
116                       load_stemma( selectedStemmaID + 1 );
117               }).removeClass( 'greyed_out' );
118       }
119 }
120
121 // Load a given stemma SVG into the stemmagraph box.
122 function load_stemma( idx ) {
123         // Load the stemma at idx
124         selectedStemmaID = idx;
125         show_stemmapager();
126         if( idx > -1 ) {
127                 $('#stemma_graph').empty();
128                 $('#stemma_graph').append( stemmata[idx] );
129                 // Stexaminer submit action
130                 var stexpath = _get_url([ "stexaminer", selectedTextID, idx ]);
131                 $('#run_stexaminer').attr( 'action', stexpath );
132         setTimeout( 'start_element_height = $("#stemma_graph .node")[0].getBBox().height;', 500 );
133         }
134 }
135
136 // General-purpose error-handling function.
137 // TODO make sure this gets used throughout, where appropriate.
138 function display_error( jqXHR, el ) {
139         var errmsg;
140         if( jqXHR.responseText == "" ) {
141                 errmsg = "perhaps the server went down?"
142         } else {
143                 var errobj;
144                 try {
145                         errobj = jQuery.parseJSON( jqXHR.responseText );
146                         errmsg = errobj.error;
147                 } catch ( parse_err ) {
148                         errmsg = "something went wrong on the server."
149                 }
150         }
151         var msghtml = $('<span>').attr('class', 'error').text( "An error occurred: " + errmsg );
152         $(el).empty().append( msghtml ).show();
153 }
154
155 function start_upload_dialog() {
156     if( typeof uploader != 'undefined' ){ uploader.destroy() };
157     $('#upload-collation-dialog').dialog('option', 'attach_uploader')();
158     $('#upload_status').empty();
159     $('#upload_button').button('disable');
160     $('#upload-collation-dialog').dialog('open');
161 }
162
163 // Utility function to neatly construct an application URL
164 function _get_url( els ) {
165         return basepath + els.join('/');
166 }
167
168 $(document).ready( function() {
169     // call out to load the directory div
170     $('#textinfo_container').hide();
171     $('#textinfo_waitbox').hide();
172         refreshDirectory();
173         
174         // Set up the textinfo edit dialog
175         $('#textinfo-edit-dialog').dialog({
176                 autoOpen: false,
177                 height: 200,
178                 width: 300,
179                 modal: true,
180                 buttons: {
181                         Save: function (evt) {
182                                 $("#edit_textinfo_status").empty();
183                                 $(evt.target).button("disable");
184                                 var requrl = _get_url([ "textinfo", selectedTextID ]);
185                                 var reqparam = $('#edit_textinfo').serialize();
186                                 $.post( requrl, reqparam, function (data) {
187                                         // Reload the selected text fields
188                                         selectedTextInfo = data;
189                                         load_textinfo();
190                                         // Reenable the button and close the form
191                                         $(evt.target).button("enable");
192                                         $('#textinfo-edit-dialog').dialog('close');
193                                 }, 'json' );
194                         },
195                         Cancel: function() {
196                                 $('#textinfo-edit-dialog').dialog('close');
197                         }
198                 },
199                 open: function() {
200                         $("#edit_textinfo_status").empty();
201                         // Populate the form fields with the current values
202                         // edit_(name, language, public, owner)
203                         $.each([ 'name', 'language', 'owner' ], function( idx, k ) {
204                                 var fname = '#edit_' + k;
205                                 // Special case: language Default is basically language null
206                                 if( k == 'language' && selectedTextInfo[k] == 'Default' ) {
207                                         $(fname).val( "" );
208                                 } else {
209                                         $(fname).val( selectedTextInfo[k] );
210                                 }
211                         });
212                         if( selectedTextInfo['public'] == true ) {
213                                 $('#edit_public').attr('checked','true');
214                         } else {
215                                 $('#edit_public').removeAttr('checked');
216                         }
217                 },
218         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
219                 $(event.target).parent().find('.ui-button').button("enable");
220         if( ajaxSettings.url.indexOf( 'textinfo' ) > -1 
221                 && ajaxSettings.type == 'POST' ) {
222                         display_error( jqXHR, $("#edit_textinfo_status") );
223         }
224         });
225
226         
227         // Set up the stemma editor dialog
228         $('#stemma-edit-dialog').dialog({
229                 autoOpen: false,
230                 height: 700,
231                 width: 600,
232                 modal: true,
233                 buttons: {
234                         Save: function (evt) {
235                                 $("#edit_stemma_status").empty();
236                                 $(evt.target).button("disable");
237                                 var stemmaseq = $('#stemmaseq').val();
238                                 var requrl = _get_url([ "stemma", selectedTextID, stemmaseq ]);
239                                 var reqparam = { 'dot': $('#dot_field').val() };
240                                 // TODO We need to stash the literal SVG string in stemmata
241                                 // somehow. Implement accept header on server side to decide
242                                 // whether to send application/json or application/xml?
243                                 $.post( requrl, reqparam, function (data) {
244                                         // We received a stemma SVG string in return. 
245                                         // Update the current stemma sequence number
246                                         selectedStemmaID = data.stemmaid;
247                                         // Stash the answer in our SVG array
248                                         stemmata[selectedStemmaID] = data.stemmasvg;
249                                         // Display the new stemma
250                                         load_stemma( selectedStemmaID );
251                                         // Reenable the button and close the form
252                                         $(evt.target).button("enable");
253                                         $('#stemma-edit-dialog').dialog('close');
254                                 }, 'json' );
255                         },
256                         Cancel: function() {
257                                 $('#stemma-edit-dialog').dialog('close');
258                         }
259                 },
260                 open: function(evt) {
261                         $("#edit_stemma_status").empty();
262                         var stemmaseq = $('#stemmaseq').val();
263                         if( stemmaseq == 'n' ) {
264                                 // If we are creating a new stemma, populate the textarea with a
265                                 // bare digraph.
266                                 $(evt.target).dialog('option', 'title', 'Add a new stemma')
267                                 $('#dot_field').val( "digraph stemma {\n\n}" );
268                         } else {
269                                 // If we are editing a stemma, grab its stemmadot and populate the
270                                 // textarea with that.
271                                 $(evt.target).dialog('option', 'title', 'Edit selected stemma')
272                                 $('#dot_field').val( 'Loading, please wait...' );
273                                 var doturl = _get_url([ "stemmadot", selectedTextID, stemmaseq ]);
274                                 $.getJSON( doturl, function (data) {
275                                         // Re-insert the line breaks
276                                         var dotstring = data.dot.replace(/\|n/gm, "\n");                                        
277                                         $('#dot_field').val( dotstring );
278                                 });
279                         }
280                 },
281         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
282                 $(event.target).parent().find('.ui-button').button("enable");
283         if( ajaxSettings.url.indexOf( 'stemma' ) > -1 
284                 && ajaxSettings.type == 'POST' ) {
285                         display_error( jqXHR, $("#edit_stemma_status") );
286         }
287         });
288                 
289         $('#upload-collation-dialog').dialog({
290                 autoOpen: false,
291                 height: 325,
292                 width: 480,
293                 modal: true,
294                 buttons: {
295                   pick: {
296                     text: "Pick File",
297                     id: "pick_uploadfile_button",
298                     click: function() {}       
299                   },
300                   upload: {
301                     text: 'Upload',
302                     id: 'upload_button',
303                     click: function() {
304                             $('#upload_status').empty();
305                 uploader.start();
306                 return false;
307             }
308                   },
309                   Cancel: function() {
310                     $('#upload-collation-dialog').dialog('close');
311                   }
312                 },
313                 attach_uploader: function() {
314                     create_uploader( _get_url([ "newtradition" ]) );
315                     $('#filelist').empty().html( 'Use the \'Pick\' button to choose a source fileā€¦' );
316                 }
317         });
318         
319         $('#stemma_graph').mousedown( function(evt) {
320         evt.stopPropagation();
321         $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
322         $('body').mousemove( function(evt) {
323             mouse_scale = 1; // for now, was:  mouse_scale = svg_root_element.getScreenCTM().a;
324             dx = (evt.clientX - $('#stemma_graph').data( 'mousedown_xy' )[0]) / mouse_scale;
325             dy = (evt.clientY - $('#stemma_graph').data( 'mousedown_xy' )[1]) / mouse_scale;
326             $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
327             var svg_root = $('#stemma_graph svg').svg().svg('get').root();
328             var g = $('g.graph', svg_root).get(0);
329             current_translate = g.getAttribute( 'transform' ).split(/translate\(/)[1].split(')',1)[0].split(' ');
330             new_transform = g.getAttribute( 'transform' ).replace( /translate\([^\)]*\)/, 'translate(' + (parseFloat(current_translate[0]) + dx) + ' ' + (parseFloat(current_translate[1]) + dy) + ')' );
331             g.setAttribute( 'transform', new_transform );
332             evt.returnValue = false;
333             evt.preventDefault();
334             return false;
335         });
336         $('body').mouseup( function(evt) {
337             $('body').unbind('mousemove');
338             $('body').unbind('mouseup');
339         });
340         });
341          
342         $('#stemma_graph').mousewheel(function (event, delta) {
343         event.returnValue = false;
344         event.preventDefault();
345         if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
346         if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
347         if( delta < -9 ) { delta = -9 }; 
348         var z = 1 + delta/10;
349         z = delta > 0 ? 1 : -1;
350         var svg_root = $('#stemma_graph svg').svg().svg('get').root();
351         var g = $('g.graph', svg_root).get(0);
352         if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 1000))) {
353             var scaleLevel = z/10;
354             current_scale = parseFloat( g.getAttribute( 'transform' ).split(/scale\(/)[1].split(')',1)[0].split(' ')[0] );
355             new_transform = g.getAttribute( 'transform' ).replace( /scale\([^\)]*\)/, 'scale(' + (current_scale + scaleLevel) + ')' );
356             g.setAttribute( 'transform', new_transform );
357         }
358     });
359     
360 });