speccy.html 51.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<title>Speccy - A dynamic spectrum+template viewer</title>
<meta charset="UTF-8"> 
<meta name='description' content='Speccy - A dynamic spectrum+template viewer' />
<html>

<head>
<script src="http://www.mpe.mpg.de/~tdwelly/js/jquery-latest.js"></script>
<script src="http://www.mpe.mpg.de/~tdwelly/js/sprintf.js" type="text/javascript" ></script>
<script src="http://www.mpe.mpg.de/~tdwelly/js/fits.js" type="text/javascript" charset="utf-8"></script>

Tom Dwelly's avatar
Tom Dwelly committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<script>
        /*    
        @licstart  The following is the entire license notice for the 
        JavaScript code in this page.

        Copyright (C) 2015,2016  Tom Dwelly

        The JavaScript code in this page is free software: you can
        redistribute it and/or modify it under the terms of the GNU
        General Public License (GNU GPL) as published by the Free Software
        Foundation, either version 3 of the License, or (at your option)
        any later version.  The code is distributed WITHOUT ANY WARRANTY;
        without even the implied warranty of MERCHANTABILITY or FITNESS
        FOR A PARTICULAR PURPOSE.  See the GNU GPL for more details.

        You should have received a copy of the GNU General Public License
        along with this program.  If not, see <http://www.gnu.org/licenses/>.

        As additional permission under GNU GPL version 3 section 7, you
        may distribute non-source (e.g., minimized or compacted) forms of
        that code without the copy of the GNU GPL normally required by
        section 4, provided you include this license notice and a URL
        through which recipients can access the Corresponding Source.   


        @licend  The above is the entire license notice
        for the JavaScript code in this page.
        */
</script>



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
<style type='text/css'>
label {white-space: nowrap}
pre   {font-family: Courier, monospace; 
       font-size: 12px;
       margin:0;
       padding:0; }
</style>
</head>


<body  onload="startUpTasks()" onresize="plotData();">
<!--<h2>Speccy - A dynamic spectrum+template viewer</h2>!-->
<table border="1"  >
<tr>
<td colspan="3">
<canvas id="myCanvas" width="1000" height="500" style="border:1px solid #d3d3d3; cursor: crosshair;" tabindex="1">
Your browser does not support the HTML5 canvas element. Try e.g. a recent version of Firefox.
</canvas><br>
</td></tr>

<tr>
<td colspan="2">
<table border="1"  title="SDSS pipeline parameters">
<tr>
<th>PLATE</th>
<th>MJD</th>
<th>FIBERID</th>
<th>PLUG_RA</th>
<th>PLUG_DEC</th>
<th>Z</th>
<th>Z_ERR</th>
<th>ZWARNING</th>
<th>CLASS</th>
<th>SUBCLASS</th>
<th>SN_MEDIAN_ALL</th>
<th>Links</th>
</tr>
<tr>
<td id="pipeParams_PLATE"    ></td>
<td id="pipeParams_MJD"      ></td>
<td id="pipeParams_FIBERID"  ></td>
<td id="pipeParams_PLUG_RA"  ></td>
<td id="pipeParams_PLUG_DEC" ></td>
<td id="pipeParams_Z"        ></td>
<td id="pipeParams_Z_ERR"    ></td>
<td id="pipeParams_ZWARNING" ></td>
<td id="pipeParams_CLASS"    ></td>
<td id="pipeParams_SUBCLASS" ></td>
<td id="pipeParams_SN_MEDIAN_ALL"></td>
<td id="pipeParams_links"></td>
</tr>
</table>
</td>
<td rowspan="1">
Zoom: 
<input type="button" onclick="applyZoom(1.25,1.00)" value="out X"   title="zoom out X">
<input type="button" onclick="applyZoom(0.80,1.00)" value="in X"    title="zoom in X">
<input type="button" onclick="applyZoom(1.00,1.25)" value="out Y"   title="zoom out Y">
<input type="button" onclick="applyZoom(1.00,0.80)" value="in Y"    title="zoom in Y">
<br>
<input type="button" onclick="previousZoom()" value="Previous">
<input type="button" onclick="resetZoom()"    value="Reset">
</td>
</tr>

<tr>
<td>Current redshift:</td>
<td>
<input id="zinput" type="text" value="" onchange="updateFromzinput();" size="12" title="Current redshift of model+lines">
<!--<input type="button" onclick="updateFromzinput()" value="Update">!-->
<input type="button" onclick="resetTozpipe()" value="Reset to pipeline value" title="reset redshift to pipeline value">
<input type="button" onclick="setTominus1()" value="Set to -1" title="Set the redshift to -1 to represent an unknown value">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Increment/decrement redshift:
<input type="button" onclick="decrementRedshift(dznow_vcoarse)" value="<<<" title="large decrement">
<input type="button" onclick="decrementRedshift(dznow_coarse)"  value="<<"  title="coarse decrement">
<input type="button" onclick="decrementRedshift(dznow_fine)"    value="<"   title="fine decrement">
<input type="button" onclick="incrementRedshift(dznow_fine)"    value=">"   title="fine increment">
<input type="button" onclick="incrementRedshift(dznow_coarse)"  value=">>"  title="coarse increment">
<input type="button" onclick="incrementRedshift(dznow_vcoarse)" value=">>>" title="large increment">
</td>
<td rowspan="2">
Scroll window: 
<table style="float:right;">
<tr>
<td><input type="button" onclick="applyOffset(-0.2,+0.1)" value="&#8598;" title="Scroll view up and left"></td>
<td><input type="button" onclick="applyOffset(+0.0,+0.1)" value="&#8593;" title="Scroll view up"></td>
<td><input type="button" onclick="applyOffset(+0.2,+0.1)" value="&#8599;" title="Scroll view up and right"></td>
</tr>
<tr>
<td><input type="button" onclick="applyOffset(-0.2,+0.0)" value="&#8592;" title="Scroll view left"></td>
<td></td>
<td><input type="button" onclick="applyOffset(+0.2,+0.0)"  value="&#8594;" title="Scroll view right"></td>
</tr>
<tr>
<td><input type="button" onclick="applyOffset(-0.2,-0.1)" value="&#8601;" title="Scroll view down and left"></td>
<td><input type="button" onclick="applyOffset(+0.0,-0.1)" value="&#8595;" title="Scroll view down"></td>
<td><input type="button" onclick="applyOffset(+0.2,-0.1)" value="&#8600;" title="Scroll view down and right"></td>
</tr>
</table>
</td>

</tr>


<td>
Model Template:</td>
<td>
<select id="templateSelect" onchange="changeTemplate()" >
  <option value="fromspec" selected="true">From specfile</option>
  <option value="fromURL"    >From URL</option>
  <option value="qso1"       >QSO: Type-I</option>
  <option value="ellgal"     >Galaxy: Elliptical</option>
  <option value="Sabgal"     >Galaxy: Sab</option>
  <option value="Sbcgal"     >Galaxy: Sbc</option>
  <option value="Scdgal"     >Galaxy: Scd</option>
  <option value="Sdmgal"     >Galaxy: Sdm</option>
  <option value="sbgal"      >Galaxy: Starburst</option>
  <option value="pickles_o5v">Star: 05</option>
  <option value="pickles_b0v">Star: B0</option>
  <option value="pickles_a0v">Star: A0</option>
  <option value="pickles_f0v">Star: F0</option>
  <option value="pickles_g0v">Star: G0</option>
  <option value="pickles_k0v">Star: K0</option>
  <option value="pickles_k5v">Star: K5</option>
  <option value="pickles_m0v">Star: M0</option>
  <option value="pickles_m3v">Star: M3</option>
  <option value="pickles_m6v">Star: M6</option>
  <option value="ABeq0"      >Fnu=const</option>
</select> 
URL:
<input id="templateURL" type="text" value="" onchange="changeTemplate();" size="70" title="URL of template file"></input>
</td>


</tr>

<tr><td>
Z_CONF_PERSON:</td>
<td>
<label title="High level of certainty for both redshift and classification"><input type="radio" name="z_conf_person" onchange="writeVIinfo()" value="3" checked>3</label>
<label title="Uncertain redshift, certain classification"                  ><input type="radio" name="z_conf_person" onchange="writeVIinfo()" value="2"  >2</label>
<label title="Uncertain redshift and classification"                       ><input type="radio" name="z_conf_person" onchange="writeVIinfo()" value="1" >1</label>
<label title="No inspection, Bad, Unplugged etc"                           ><input type="radio" name="z_conf_person" onchange="writeVIinfo()" value="0" >0</label>
</td>


<td rowspan="2">Toggle:<br>
<label><input type="checkbox" onclick="plotData();" value="ToggleFlux" id="ToggleFlux" checked>
<font style="color: #000000;">Signal</font></label>
<label><input type="checkbox" onclick="plotData();" value="ToggleNoise" id="ToggleNoise">
<font style="color: #aaaaaa;">Noise</font></label>
<label><input type="checkbox" onclick="plotData();" value="ToggleModel" id="ToggleModel" checked>
<font style="color: #dd0000;">Model</font></label>
<br>
<label><input type="checkbox" onclick="plotData();" value="ToggleLines" id="ToggleLines" checked>
<font style="color: #008800;">Lines</font></label>
<label><input type="checkbox" onclick="plotData();" value="ToggleSky"   id="ToggleSky" >
<font style="color: #00dddd;">Sky</font>&nbsp;&#215;</label>
<input id="skyMult" type="text" value="0.05" onchange="plotData();" size="5" title="Sky flux multiplier">
</td>


</tr>

<tr>
<td>
CLASS_PERSON:</td>
<td>
<input type="radio" name="class_person" onchange="writeVIinfo()" value="NONE"                            >NONE
<input type="radio" name="class_person" onchange="writeVIinfo()" value="STAR"    id="class_person_star"  >STAR
<input type="radio" name="class_person" onchange="writeVIinfo()" value="GALAXY"  id="class_person_galaxy">GALAXY
<input type="radio" name="class_person" onchange="writeVIinfo()" value="QSO"     id="class_person_qso"   >QSO
<input type="radio" name="class_person" onchange="writeVIinfo()" value="QSO_BAL"                         >QSO_BAL
<input type="radio" name="class_person" onchange="writeVIinfo()" value="BLAZAR"                          >BLAZAR
</td>


</tr>

<tr><td>
ISSUE:</td>
<td>
<select id="issueSelect" onchange="writeVIinfo()" >
  <option value="None" selected="true">None</option>
  <option value="low SN">Low S/N</option>
  <option value="Line Ambiguity">Line Ambiguity</option>
  <option value="Distorted Red/Blue Spectrum">Distorted Red/Blue Spectrum</option>
  <option value="Sky Subtraction">Sky Subtraction</option>
  <option value="Little/No Data">Little/No Data</option>
  <option value="Superposition">Superposition</option>
  <option value="Other/Unknown">Other/Unknown</option>
</select> 
</td>

<td rowspan="2" title="Apply smoothing using a boxcar with the selected width (in pixels)">
Smoothing:
<label><input type="radio" name="smoothing" onchange="updateSmoothing()" value="1" checked />Off</label>
<label><input type="radio" name="smoothing" onchange="updateSmoothing()" value="3"  />3</label>
<label><input type="radio" name="smoothing" onchange="updateSmoothing()" value="5"  />5</label>
<label><input type="radio" name="smoothing" onchange="updateSmoothing()" value="7"  />7</label>
<label><input type="radio" name="smoothing" onchange="updateSmoothing()" value="9"  />9</label>
<label><input type="radio" name="smoothing" onchange="updateSmoothing()" value="11" />11</label>
<label><input type="radio" name="smoothing" onchange="updateSmoothing()" value="15" />15</label>
<label><input type="radio" name="smoothing" onchange="updateSmoothing()" value="31" />31</label>
</td>

</tr>

<tr><td>
COMMENTS:</td>
<td>
<!-- <input id="commentBox" type="text" onchange="writeVIinfo()" value="" size="50"> !-->
<input id="commentBox" type="text" onchange="writeVIinfo()" value="" size="50" style="width: 100%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box;">
</td></tr>

<tr>
<td colspan="2">
<!-- <textarea rows="1" cols="105" id="resultBox" style="background-color: lightgrey;">-</textarea> !-->
<textarea  rows="1" id="resultBox" style="background-color: lightgrey; border: none; width: 100%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box;">-</textarea>
</td>
<td>
<input type="button" onclick="writeVIinfo()"  value="Print Formatted Details" />
<input type="hidden" onclick="submitVIinfo()" value="Submit Inspection Results" id="submitButton" title="Submit your visual inspection results to the server"/>
</td>

</tr>
</table>
<p id="inspectInBrowser"></p>

<hr>
<p style="color: red;"> Warning! Speccy is still in development, so please be wary of (and report) unexpected behaviour.</p>
<h4>Usage:</h4> 
<p>http://www.mpe.mpg.de/~tdwelly/speccy/speccy.html?specfile={URL} (substitute URL of a valid speccy file)<br>
* The cursor (arrow) keys move the template in redshift and normalisation<br>
* To zoom into a region: click and hold the right mouse button at one corner of the region of interest, 
then drag the pointer to the opposite corner of the region where you then release the right button 
(visual feedback is not yet available). <br>
* Left-clicking the button displayes the coordinates of the pointer position at the time of the click. <br>
* Please send comments, complaints and suggestions to <a href="mailto:dwelly@mpe.mpg.de">dwelly@mpe.mpg.de</a>.
<p>

<h4>Speccy File format:</h4> 
<p>These are plain ASCII text files.<br>
Header entries are prefixed by a hash and contain "key = value" pairs.<br>
Main body should contain five comma-separated columns: <br>
<tt>ObservedVacuumWavelength(&#x212b;),Flux,FluxError,SkyFlux,ModelFlux</tt> <br>
(all fluxes in units 10<sup>-17</sup> erg cm<sup>-2</sup> s<sup>-1</sup>&#x212b;<sup>-1</sup>)<br>
Template files should contain just two comma-separated columns: <br>
<tt>RestframeVacuumWavelength(&#x212b;),ModelFlux(F<sub>&lambda;</sub>)</tt>
<br>
Here is a script that can be used to convert a plateful of eBOSS pectra from "spPlate*"+"spZbest*" format into speccy format:
<a href="http://www.mpe.mpg.de/~tdwelly/speccy/convert_sdss_plate_to_speccy.csh"> convert_sdss_plate_to_speccy.csh</a>
</p>
</body>

<h4>CLASS_PERSON / Z_CONF_PERSON matrix :</h4> 
<table border="1">
<tr>
<th rowspan="2">CLASS_PERSON</th>
<th colspan="4">Z_CONF_PERSON</th>
</tr>
<tr>
<th>0</th>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
<tr> <th>NONE</th>    <td>No inspection</td> <td>Bad, ?</td><td>Unplugged </td><td>       </td> </tr>
<tr> <th>STAR</th>    <td>             </td> <td>Star_?</td><td>          </td><td>Star   </td> </tr>
<tr> <th>QSO</th>     <td>             </td> <td>QSO_? </td><td>QSO_Z?    </td><td>QSO    </td> </tr>
<tr> <th>GALAXY</th>  <td>             </td> <td>      </td><td>Galaxy_Z? </td><td>Galaxy </td> </tr>
<tr> <th>QSO_BAL</th> <td>             </td> <td>      </td><td>QSO_BAL_Z?</td><td>QSO_BAL</td> </tr>
<tr> <th>BLAZAR</th>  <td>             </td> <td>      </td><td>BLAZAR_Z? </td><td>BLAZAR </td> </tr>
</table>







<script type="text/javascript">
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");  
ctx.canvas.width  = window.innerWidth * 0.96;
ctx.canvas.height = window.innerHeight * 0.6;

var specfile = "";
var submit_button = 0;
var submit_php = 'http://www.mpe.mpg.de/~tdwelly/SPIDERS/speccy_results/receive_speccy_submissions.php';
var lambdaArray = [];
var fluxArray   = [];
var fluxerrArray= [];
var skyArray    = [];
var modelArray  = [];
var smoothedArray = [];
var templatelambdaArray = [];
var templatefluxArray = [];
var templateLength = 0;
var templateMean = 0.0;
var fluxMean = 0.0;
//var skymult = 0.05;
var padx1 = 50;
var padx2 = 10;
var padx = padx1 + padx2;
var pady = 50;
//var xsize = canvas.width;
//var ysize = canvas.height; 


////Add a placeholder function for browsers that don't have setLineDash()
//if (!ctx.setLineDash) {
//    ctx.setLineDash = function () {}
//}

//var zorig = -99.9;
var modelz0 =  -99.9;           //the redshift that the model template has already been redshifted by
var modelz0_zpipe = -99.9;   //pipe
var znow = -99.9;       // the redshift that we want to display right now
var dznow_fine    = 1.0002;      //the factors in dznow that you get by pressing left or right mouse buttons
var dznow_coarse  = 1.005;       //
var dznow_vcoarse = 1.05;       //
var renorm = 1.0;
var drenorm = 1.02;

//these params control the wavelength+flux range plotted
var x0=1e10; //will derive values of these params from spectrum 
var x1=0.0;//
var y0=0.0;  //
var y1=0.0;  //
var orig_x0;
var orig_x1;
var orig_y0;
var orig_y1;
var prev_x0;
var prev_x1;
var prev_y0;
var prev_y1;

var mousePos_old;
var leftclick = 0, middleclick = 1, rightclick = 2;
var nkeys = 0;
var keynames = [];
var keyvals = [];

// I have now made sure that all these lines are given with _vacuum_ wavelengths
// line wavelengths are mainly from here:
// "msw"       http://www.star.ucl.ac.uk/~msw/lines.html
// "B12"       Bolton et al., 2012, http://arxiv.org/abs/1207.7326v1
// "spZ"       http://data.sdss3.org/datamodel/files/BOSS_SPECTRO_REDUX/RUN2D/PLATE4/RUN1D/spZline.html
// "Charlton"  http://ned.ipac.caltech.edu/level5/Charlton/Charlton1_1.html
// "NIST"      http://physics.nist.gov/PhysRefData/ASD/lines_form.html (then converted to vacuum wavelengths)
// "NIST_Fe"   http://physics.nist.gov/PhysRefData/Handbook/Tables/irontable2.htm
var linelist_ea = [];    //lines that often appear in emission or absorption
var linelist_ab = [];    //lines that usually appear in absorption
linelist_ea.push({name:"Ly limit   "          , lambda:  912.    }); // Charlton
linelist_ea.push({name:"Ly\u03B3   "          , lambda:  972.537 }); // Charlton
linelist_ea.push({name:"Ly\u03B2   "          , lambda: 1025.722 }); // Charlton
linelist_ea.push({name:"Ly\u03B1   "          , lambda: 1215.67  }); // spZ
linelist_ea.push({name:"NV         "          , lambda: 1240.81  }); // spZ
linelist_ea.push({name:"SiIV       "          , lambda: 1393.755 }); // Charlton
linelist_ea.push({name:"SiIV       "          , lambda: 1402.770 }); // Charlton
linelist_ea.push({name:"CIV        "          , lambda: 1549.48  }); // spZ
linelist_ea.push({name:"HeII       "          , lambda: 1640.42  }); // spZ
linelist_ea.push({name:"CIII]      "          , lambda: 1908.734 }); // spZ
409
410
//linelist_ea.push({name:"FeII       "          , lambda: 2382.765 }); // Charlton
//linelist_ea.push({name:"FeII       "          , lambda: 2600.173 }); // Charlton
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//linelist_ea.push({name:"MgII       "          , lambda: 2800.3152}); // spZ
linelist_ea.push({name:"MgII       "          , lambda: 2796.3522}); // NIST
linelist_ea.push({name:"MgII       "          , lambda: 2803.5300}); // NIST
linelist_ea.push({name:"[NeV]      "          , lambda: 3426.852 }); // NIST
linelist_ea.push({name:"[OII]      "          , lambda: 3727.0917}); // spZ
linelist_ea.push({name:"[OII]      "          , lambda: 3729.8754}); // spZ
linelist_ea.push({name:"[NeIII]    "          , lambda: 3869.81  }); // msw
//linelist_ea.push({name:"[NeIII]  "          , lambda: 3968.53  }); // msw (deliberately excluded) 
linelist_ea.push({name:"Hz         "          , lambda: 3890.15  }); // msw Hzeta
linelist_ab.push({name:"CaII K     "          , lambda: 3934.777 }); // msw
linelist_ab.push({name:"CaII H     "          , lambda: 3969.591 }); // msw
//linelist_ea.push({name:"            H\u03B5", lambda: 3971.19  }); // msw Hepsilon
linelist_ea.push({name:"H\u03B4    "          , lambda: 4102.92  }); // msw Hdelta
linelist_ab.push({name:"G-band     "          , lambda: 4305.2   }); // no ref - converted from lambda_air=4304A 
linelist_ea.push({name:"H\u03B3    "          , lambda: 4341.69  }); // msw Hgamma
426
//linelist_ea.push({name:"     [OIII]"          , lambda: 4364.44  }); // msw
427
428
429
430
431
432
433
434
435
linelist_ea.push({name:"HeII       "          , lambda: 4686.9915}); // spZ
linelist_ea.push({name:"H\u03B2    "          , lambda: 4862.69  }); // msw Hbeta
linelist_ea.push({name:"[OIII]     "          , lambda: 4960.30  }); // msw
linelist_ea.push({name:"[OIII]     "          , lambda: 5008.24  }); // msw
linelist_ab.push({name:"Mgb        "          , lambda: 5168.761 }); // msw
linelist_ab.push({name:"Mgb        "          , lambda: 5174.125 }); // msw 
linelist_ab.push({name:"Mgb        "          , lambda: 5185.048 }); // msw 
linelist_ea.push({name:"NI         "          , lambda: 5199.35  }); // NIST 
linelist_ea.push({name:"NI         "          , lambda: 5201.71  }); // NIST 
436
//linelist_ea.push({name:"FeII       "          , lambda: 5271.50  }); // NIST - strongest one of a blend
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
linelist_ea.push({name:"[OI]       "          , lambda: 5578.8878}); // spZ
linelist_ea.push({name:"HeII       "          , lambda: 5413.0245}); // spZ
linelist_ea.push({name:"[NII]      "          , lambda: 5756.1862}); // spZ
linelist_ea.push({name:"HeI        "          , lambda: 5877.3086}); // spZ
linelist_ab.push({name:"      NaD  "          , lambda: 5891.583 }); // msw
linelist_ab.push({name:"      NaD  "          , lambda: 5897.558 }); // msw
linelist_ea.push({name:"[OI]       "          , lambda: 6302.0464}); // spZ
linelist_ea.push({name:"      [SIII]"         , lambda: 6313.8056}); // spZ
linelist_ea.push({name:"[OI]       "          , lambda: 6363.776 }); // spZ
linelist_ea.push({name:"      [NII]"          , lambda: 6549.8590}); // spZ
linelist_ea.push({name:"H\u03B1    "          , lambda: 6564.6140}); // spZ Halpha
linelist_ea.push({name:"      [NII]"          , lambda: 6585.2685}); // spZ
linelist_ea.push({name:"[SII]      "          , lambda: 6718.2943}); // spZ
linelist_ea.push({name:"[SII]      "          , lambda: 6732.6782}); // spZ
linelist_ea.push({name:"[ArIII]    "          , lambda: 7137.7572}); // spZ
linelist_ea.push({name:"[ArIII]    "          , lambda: 7753.2   }); // msw
linelist_ab.push({name:"CaII       "          , lambda: 8500.36  }); // msw
linelist_ab.push({name:"CaII       "          , lambda: 8544.44  }); // msw
linelist_ab.push({name:"CaII       "          , lambda: 8664.52  }); // msw


canvas.oncontextmenu = function() {
     return false;  
} 

function startUpTasks()
{
  interpURL();
  if ( specfile != "" ) {
    readSpecFile();   //the get is asynchronous, so don't put anything after this that depends on the read
    changeTemplate();
  }
}


function getUrlVars()
{
  var vars = [], hash;
  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  for(var i = 0; i < hashes.length; i++)
  {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
  }
  return vars;
}

function interpURL ()
{
  var ni = document.getElementById('baseDiv');
  var token_list = new getUrlVars();
  for (var i=0;i<token_list.length;i++){
    var par_name = token_list[i].toUpperCase();
    var par_val  = token_list[token_list[i]];
    var str = par_name + "=" + par_val;
    if ( par_name == "SPECFILE" ) {
      specfile = par_val;
    }
    else if ( par_name == "Z" ) {   //control the initial redshift that the model is plotted at
      znow = Number(par_val);
    }
    else if ( par_name == "SUBMIT_BUTTON" ) {   //see if we should add a submit button
      submit_button = Number(par_val);
      if ( submit_button > 0 ) {
	document.getElementById("submitButton").type = "button";
      }
    }	   
    else if ( par_name == "SUBMIT_PHP" ) {    //see which php page to submit the results to 
      submit_php = par_val;
    }	   
  }
}

function AjaxError(x, e) {
  if (x.status == 0) {
    alert(' Check Your Network.');
  } else if (x.status == 404) {
    alert('Requested URL not found.');
  } else if (x.status == 500) {
    alert('Internal Server Error.');
  }  else {
     alert('Unknow Error.\n' + x.responseText);
  }
}


function readSpecFileFITS()
{
  alert('FITS files are not yet fully implemented!');
 
//   var FITS = astro.FITS;
// 
//   // Define a callback function for when the FITS file is received
//   var callback = function() {
// 
//     // Get the first header-dataunit containing a dataunit
//     var hdu = this.getHDU();
// 
//     // or we can do
//     var header = hdu.header;
// 
//     // Read a card from the header
//     var bitpix = header.get('BITPIX');
// 
//     // Get the dataunit object
//     var dataunit = hdu.data;
// 
//     // Do some wicked client side processing ...
//     console.log("Read in fits file");
//   }
// 
//   // Initialize a new FITS File object
//   var fits = new FITS(specfile, callback);

}

function readSpecFileASCII()
{
   $.ajaxSetup({
        error: AjaxError
   });

  //read in the spec file
  var jQResult = jQuery.get(specfile, function(data) {
     var lines = [];
     lines = data.split("\n");
     var j = 0;
     var dy = 0.0;
     fluxMean = 0.0;
     nfluxMean = 0;

     //file format: lambda,flux,fluxerr,sky,model; 
     // lambda in AA; fluxes in units 1e-17 erg/cm/s/AA
     for(var i=0;i<lines.length;i++) 
     {
       var data = [];
       if ( lines[i].substr(0,1) == "#" ) {
         data  = (lines[i].substr(1)).split("=");
         if (data.length>=2 && (data[0].trim()).substr(0,1) != "#"){
           keynames[nkeys] = (data[0].trim()).toUpperCase();
           keyvals[nkeys]  = data[1].trim();
           if ( keynames[nkeys] == "Z" ) {
             modelz0_zpipe = Number(keyvals[nkeys]);
             modelz0 = modelz0_zpipe;
           }
           else if ( keynames[nkeys] == "CLASS" ) 
           {
             if (keyvals[nkeys].indexOf("QSO")  >= 0 ){
              document.getElementById("class_person_qso").checked = 1;
             } 
             else if (keyvals[nkeys].indexOf("GALAXY")  >= 0 ) {
               document.getElementById("class_person_galaxy").checked = 1;
             } 
             else if (keyvals[nkeys].indexOf("STAR")  >= 0 ) {
               document.getElementById("class_person_star").checked = 1;
             }
           }

           nkeys ++;
         }
       }
       else
       {
         data  = lines[i].split(",");
         if ( data.length >= 5 ) {
           lambdaArray[j]  = Number(data[0]);
           fluxArray[j]    = Number(data[1]);
           fluxerrArray[j] = Number(data[2]);
           skyArray[j]     = Number(data[3]);
           modelArray[j]   = Number(data[4]);
           if (  modelArray[j] > 1.0 * fluxerrArray[j] ) 
           {   // the numeric value is the number of sigmas to accept
             if ( fluxArray[j] < y0 ) y0 = fluxArray[j];
             if ( fluxArray[j] > y1 ) y1 = fluxArray[j];
             if ( fluxArray[j] > -1e10) {
               fluxMean = fluxMean + Number(fluxArray[j]); 
               nfluxMean++;
             }
           }
         }
         j ++;
       }
     };
     if (lambdaArray.length < 2) {
      var str = "There was a problem with the specified specfile='"+specfile+"' (lambdaArray.length="+lambdaArray.length+")";
      alert(str);
     }else{
       dy = (y1-Math.max(y0,0.0))*0.02; //only expand the range a little
       y1 = y1 + dy;
       if(y0>=0.0) {
         y0 = y0 - dy;
       }
       else if ( y1 > 0.0 && Math.abs(y0) > 0.5 * y1 )
       {
	 y0 =  -0.5 * Math.abs(y1);
       } 
       x0 = Number(lambdaArray[0]) - 100;
       x1 = Number(lambdaArray[(lambdaArray.length - 2)])+100.0;
       orig_x0 = x0;
       orig_x1 = x1;
       orig_y0 = y0;
       orig_y1 = y1;
       fluxMean = fluxMean / (Math.max(nfluxMean,1));

       if ( znow <= -99. ) {
         znow =  modelz0;
       } 
       var elem = document.getElementById("zinput");
       elem.value = znow;

       //calc the smoothed flux array
       var boxsize =  $("input[type='radio'][name='smoothing']:checked").val();
       smoothArray(fluxArray, smoothedArray, boxsize)

       plotData();
       writePipeInfo();
     }
  });

}

function readSpecFile()
{
  var extension = specfile.split('.').pop();
  console.log(extension);
  if ( extension === "fits" ) {
    readSpecFileFITS();
  } else {
    readSpecFileASCII();
  };
}


//things to do when the template is changed
//load new data
//replot
//switch on the value of the template select box
function changeTemplate() {
  var options = document.getElementById("templateSelect");
  var templateCode = document.getElementById("templateSelect").value; 
  var fluxcolnum;
  var templateURL = "not defined";
  if ( templateCode == "fromspec" ){
    templateURL = specfile; 
    fluxcolnum = 4;  
    modelz0 = modelz0_zpipe;
    for(var i=0;i<nkeys;i++) 
    {
     if ( keynames[i] == "CLASS" ) {
      if (keyvals[i].indexOf("QSO")  >= 0 ){
        document.getElementById("class_person_qso").checked = 1;
      } 
      else if (keyvals[i].indexOf("GALAXY")  >= 0 ) {
        document.getElementById("class_person_galaxy").checked = 1;
      } 
      else if (keyvals[i].indexOf("STAR")  >= 0 ) {
        document.getElementById("class_person_star").checked = 1;
      }
    }
  }
    
  }
  else if ( templateCode == "fromURL" ){
    templateURL =  document.getElementById("templateURL").value;	    
    modelz0 = 0.0;
    fluxcolnum = 1;  
  }
  else
  {
    templateURL = "http://www.mpe.mpg.de/~tdwelly/speccy/templates/template_"+templateCode+".txt"; 
    modelz0 = 0.0;
    fluxcolnum = 1;  
    var template_text = options[options.selectedIndex].text;
    if (template_text.indexOf("Star:") >= 0 )
    {
      var elem = document.getElementById("zinput");
      znow = 0.0;
      elem.value = znow;
      elem = document.getElementById("class_person_star");
      elem.checked = 1;
    }
    else if (template_text.indexOf("Galaxy:") >= 0 )
    {
      elem = document.getElementById("class_person_galaxy");
      elem.checked = 1;
    } 
    else if (template_text.indexOf("QSO:") >= 0 )
    {
      elem = document.getElementById("class_person_qso");
      elem.checked = 1;
    }
  }

   $.ajaxSetup({
        error: AjaxError
   });

   //read in the file
   var jQResult = jQuery.get(templateURL, function(data) {
     var lines = [];
     lines = data.split("\n");
     //file format: lambda,flux
     templateLength = 0;
     var templateNmean = 0;
     templateMean = 0.0;
     for(var i=0;i<lines.length;i++) {
       var data = [];
       data  = lines[i].split(",");
       templatelambdaArray[i] = Number(data[0]);
       templatefluxArray[i]   = Number(data[fluxcolnum]);
       if ( templatelambdaArray[i]*(1.+znow) >= orig_x0 && 
            templatelambdaArray[i]*(1.+znow) <= orig_x1 )
       {
         templateMean += templatefluxArray[i];
         templateNmean ++;
       }
       templateLength ++;
     };
     if (templateLength < 2) {
      var str = "There was a problem with the specified template='"+templateURL+"'";
      alert(str);
     }
     else {
       if ( templateCode != "fromspec" && templateNmean > 0 )
       {
         templateMean = templateMean / templateNmean;
         renorm = fluxMean / templateMean;
         //var str = "templateMean="+templateMean+" templateNmean="+templateNmean+" renorm="+renorm+" fluxMean="+fluxMean;
         //console.log(str);
       }
       else
       {
         renorm = 1.0;
       }
       plotData();
     }
  });

}



function plotData() {
  ctx.canvas.width  = window.innerWidth * 0.96;
  ctx.canvas.height = window.innerHeight * 0.5;
  var xsize = canvas.width;
  var ysize = canvas.height; 

  ctx.stroke();
  ctx.font = "14px Arial";
  ctx.textAlign="center"; 
  var zratio = (1. + znow)/(1. + modelz0);
  var dx_inv = (xsize-padx)/(x1-x0);
  var dy_inv = (ysize-padx)/(y1-y0);
  var dx2_inv = (xsize-padx)*(1.+znow)/(x1-x0);
  ctx.clearRect (0 ,0,canvas.width, canvas.height);
  ctx.strokeStyle = "#000000";

  //determine the tics to use
  ctx.beginPath();
  var xtic_spacing;
  var ytic_spacing;
  if      (x1-x0 > 5000.0) { xtic_spacing = 1000; }
  else if (x1-x0 > 2500.0) { xtic_spacing = 500; }
  else if (x1-x0 > 1000.0) { xtic_spacing = 200; }
  else if (x1-x0 >  500.0) { xtic_spacing = 100; }
  else if (x1-x0 >  250.0) { xtic_spacing =  50; }
  else if (x1-x0 >  100.0) { xtic_spacing =  20; }
  else {xtic_spacing = 10;}
  var mxtic_spacing = 0.1*xtic_spacing;

  for(var xtic=0;xtic<=x1;xtic+=xtic_spacing){
    var x =         padx1 + (xtic-x0)*dx_inv;
    if ( x > padx1 && x < xsize-padx2){
      ctx.fillText(xtic, x, ysize-0.6*pady);
      ctx.moveTo(x,ysize-1.1*pady);
      ctx.lineTo(x,ysize-1.2*pady);
    }
  }
  for(var xtic=0;xtic<=x1;xtic+=mxtic_spacing){
    var x =         padx1 + (xtic-x0)*dx_inv;
    if ( x > padx1 && x < xsize-padx2){
      ctx.moveTo(x,ysize-1.0*pady);
      ctx.lineTo(x,ysize-1.1*pady);
    }
  }

  ctx.stroke();
  ctx.closePath();

  ctx.beginPath();
  ctx.strokeStyle = "#aaaaaa";
  ctx.fillStyle = "#aaaaaa";
  // do the restframe wavelength tics 
  for(var xtic=0;xtic<=x1;xtic+=xtic_spacing){
    var x =         padx1 + (xtic*(1.+znow)-x0)*dx_inv;
    if ( x > padx1 && x < xsize-padx2){
        ctx.fillText(xtic, x, 0.8*pady);
        ctx.moveTo(x,1.1*pady);
        ctx.lineTo(x,1.2*pady);
    }
  }
  for(var xtic=0;xtic<=x1;xtic+=mxtic_spacing){
    var x =         padx1 + (xtic*(1.+znow)-x0)*dx_inv;
    if ( x > padx1 && x < xsize-padx2){
      ctx.moveTo(x,1.0*pady);
      ctx.lineTo(x,1.1*pady);
    }
  }
  var str_xlabel = "Restframe Vacuum Wavelength ("+ String.fromCharCode(8491)+")";
  ctx.fillText(str_xlabel, xsize*0.5, 0.3*pady);
  ctx.stroke();
  ctx.closePath();
  ctx.beginPath();
  ctx.strokeStyle = "#000000";
  ctx.fillStyle = "#000000";

  if      (y1-y0 > 50000.0) { ytic_spacing = 10000; }
  else if (y1-y0 > 25000.0) { ytic_spacing =  5000; }
  else if (y1-y0 > 10000.0) { ytic_spacing =  2000; }
  else if (y1-y0 >  5000.0) { ytic_spacing =  1000; }
  else if (y1-y0 >  2500.0) { ytic_spacing =   500; }
  else if (y1-y0 >  1000.0) { ytic_spacing =   200; }
  else if (y1-y0 >   500.0) { ytic_spacing =   100; }
  else if (y1-y0 >   250.0) { ytic_spacing =   50; }
  else if (y1-y0 >   100.0) { ytic_spacing =   20; }
  else if (y1-y0 >    50.0) { ytic_spacing =   10; }
  else if (y1-y0 >    25.0) { ytic_spacing =    5; }
  else if (y1-y0 >    10.0) { ytic_spacing =    2; }
  else if (y1-y0 >     5.0) { ytic_spacing =    1; }
  else {ytic_spacing = 0.5;}
  for(var ytic=0;ytic<=y1;ytic+=ytic_spacing){
    var y =  ysize - pady - (ytic-y0)*dy_inv;
    if ( y > pady && y < ysize-pady){
      ctx.fillText(ytic, 0.6*padx1, y);
      ctx.moveTo(padx1*1.1,y);
      ctx.lineTo(padx1*1.2,y);
    }
  }
  var mytic_spacing = 0.2*ytic_spacing;


  for(var ytic=-ytic_spacing;ytic>=y0;ytic-=ytic_spacing){
    var y =  ysize - pady - (ytic-y0)*dy_inv;
    if ( y > pady && y < ysize-pady){
      ctx.fillText(ytic, 0.6*padx1, y);
      ctx.moveTo(padx1*1.1,y);
      ctx.lineTo(padx1*1.2,y);
    }
  }

  for(var ytic=0;ytic<=y1;ytic+=mytic_spacing){
    var y =  ysize - pady - (ytic-y0)*dy_inv;
    if ( y > pady && y < ysize-pady){
      ctx.moveTo(padx1,y);
      ctx.lineTo(padx1*1.1,y);
    }
  }
  for(var ytic=-mytic_spacing;ytic>=y0;ytic-=mytic_spacing){
    var y =  ysize - pady - (ytic-y0)*dy_inv;
    if ( y > pady && y < ysize-pady){
      ctx.moveTo(padx1,y);
      ctx.lineTo(padx1*1.1,y);
    }
  }
  //draw horizontal line at flux=0
  {
    var y =  ysize - pady - (0.0-y0)*dy_inv;
    if ( y > pady && y < ysize-pady){
      ctx.moveTo(padx1,y);
      ctx.lineTo(xsize-padx2,y);
    }
  }
  ctx.stroke();
  ctx.closePath();

  //draw the axis labels
  ctx.beginPath();
  var str_xlabel = "Observed Vacuum Wavelength ("+ String.fromCharCode(8491)+")";
  ctx.fillText(str_xlabel, xsize*0.5, ysize-0.2*pady);
  ctx.save();
  ctx.translate(0,ysize);
  ctx.rotate(-Math.PI/2);
  ctx.textAlign = "center";
//  ctx.fillText("Flux (1e-17 erg cm^-2 s^-1 AA^-1)",  padx1*0.2, ysize*0.5);
  var str_ylabel = "Flux (10"+String.fromCharCode(8315,185,8311)+" erg cm"+String.fromCharCode(8315,178) +" s"+ String.fromCharCode(8315,185) + " " + String.fromCharCode(8491,8315,185)+")";
  ctx.fillText(str_ylabel,  ysize*0.5, padx1*0.3);
  ctx.restore();
  ctx.stroke();
  ctx.closePath();


  //now draw wavelengths of common lines
  if ( document.getElementById("ToggleLines").checked )
  {  
    var last_name = "";
    var last_x    = -1.;
    ctx.strokeStyle = "#008800";
    ctx.fillStyle = "#008800";
    ctx.font = "12px Arial";
    ctx.textAlign="left"; 
    ctx.save();
    ctx.translate(0,ysize);
    ctx.rotate(-Math.PI/2);
    ctx.beginPath();
      
    for(var lineindex=0; lineindex < linelist_ea.length; lineindex++)
    {
      var lobs = (1.0+znow)*Number(linelist_ea[lineindex].lambda);
      var x = padx1 + (lobs-x0)*dx_inv;
      if ( x > padx1 && x < xsize-padx2) {
        if ( linelist_ea[lineindex].name != last_name || 
             x > (last_x + 8.))
        {
          ctx.fillText(linelist_ea[lineindex].name, ysize-0.95*pady, x+4.0);
        }
        ctx.moveTo(pady,x);
        ctx.lineTo(ysize-pady,x);
        last_name = linelist_ea[lineindex].name;
        last_x = x;
      }
    }
    ctx.stroke();
    ctx.closePath();

    //now draw the pure absorption lines
    ctx.beginPath();
    ctx.strokeStyle = "#888800";
    ctx.fillStyle = "#888800";
    for(var lineindex=0; lineindex < linelist_ab.length; lineindex++)
    {
      var lobs = (1.0+znow)*Number(linelist_ab[lineindex].lambda);
      var x = padx1 + (lobs-x0)*dx_inv;
      if ( x > padx1 && x < xsize-padx2) {
        if ( linelist_ab[lineindex].name != last_name || 
             x > (last_x + 8.))
        {
          ctx.fillText(linelist_ab[lineindex].name, ysize-0.95*pady, x+4.0);
        }
        ctx.moveTo(pady,x);
        ctx.lineTo(ysize-pady,x);
        last_name = linelist_ab[lineindex].name;
        last_x = x;
      }
    }
    ctx.stroke();


    ctx.restore();
    ctx.closePath();
    ctx.fillStyle = "#000000";
    ctx.strokeStyle = "#000000";
    ctx.font = "14px Arial";
    ctx.textAlign="center"; 
  }


  //draw the sky curve
  if ( document.getElementById("ToggleSky").checked )
  {  
    var skymult = Number(document.getElementById("skyMult").value);
    ctx.strokeStyle = "#00dddd";
    ctx.beginPath();
    for(var i=0;i<lambdaArray.length;i++){
      var x = padx1 + (lambdaArray[i]-x0)*dx_inv;
      if ( x >= padx1 && x <= xsize-padx2)
      {
        var y = ysize - pady - (skyArray[i]*skymult-y0)*dy_inv;
        var clip_y = Math.max(Math.min(y,ysize-pady),pady);
        if ( i>=1) { ctx.lineTo(x,clip_y);}
        else       { ctx.moveTo(x,clip_y);}
      }
    }
    ctx.stroke();
    ctx.closePath();
  }


  //draw the observed flux curve
  if ( document.getElementById("ToggleFlux").checked )
  {  
//    ctx.strokeStyle = "#0000dd";
    ctx.strokeStyle = "#000000";
    ctx.beginPath();
    for(var i=0;i<lambdaArray.length;i++){
      var x =         padx1 + (lambdaArray[i]-x0)*dx_inv;
      if ( x >= padx1 && x <= xsize-padx2 ) 
      { 
        var y = ysize - pady - (smoothedArray[i]-y0)*dy_inv;
        var clip_y = Math.max(Math.min(y,ysize-pady),pady);
        if ( i>=1) { ctx.lineTo(x,clip_y);}
        else       { ctx.moveTo(x,clip_y);}
      }
    }
    ctx.stroke();
    ctx.closePath();
  }

  //draw the model curve
  if ( document.getElementById("ToggleModel").checked )
  {  
    ctx.beginPath();
    ctx.strokeStyle = "#ff0000";
    for(var i=0;i<templateLength;i++){
      var x =         padx1 + (templatelambdaArray[i]*zratio-x0)*dx_inv;
      if ( x >= padx1 && x <= xsize-padx2 )
      {
        var y = ysize - pady - (templatefluxArray[i]*renorm-y0)*dy_inv;
        var clip_y = Math.max(Math.min(y,ysize-pady),pady);
        if ( i>=1) { ctx.lineTo(x,clip_y);}
        else       { ctx.moveTo(x,clip_y);}
      }
    }
    ctx.stroke();
    ctx.closePath();
  }

  //draw the noise curve
  if ( document.getElementById("ToggleNoise").checked )
  {  
    ctx.beginPath();
    ctx.strokeStyle = "#aaaaaa";
    for(var i=0;i<lambdaArray.length;i++){
      var x =         padx1 + (lambdaArray[i]-x0)*dx_inv;
      if ( x >= padx1 && x <= xsize-padx2 ) 
      { 
        var y = ysize - pady - (fluxerrArray[i]-y0)*dy_inv;
        var clip_y = Math.max(Math.min(y,ysize-pady),pady);
        if ( i>=1) { ctx.lineTo(x,clip_y);}
        else       { ctx.moveTo(x,clip_y);}
      }
    }
    ctx.stroke();
    ctx.closePath();
  }


  //draw the border
  ctx.strokeStyle = "#000000";
  ctx.beginPath();
  ctx.moveTo(padx1,pady);
  ctx.lineTo(padx1,ysize-pady);
  ctx.lineTo(xsize-padx2,ysize-pady);
  ctx.lineTo(xsize-padx2,pady);
  ctx.lineTo(padx1,pady);
  ctx.stroke();
  ctx.closePath();


}

function incrementRedshift(zfactor)
{
  var elem = document.getElementById("zinput");
  znow = (1. + znow)*zfactor - 1.0;
//  elem.value = znow;
  elem.value = sprintf("%.7g",znow);
  plotData();
  writeVIinfo();
}
function decrementRedshift(zfactor)
{
  var elem = document.getElementById("zinput");
  znow = (1. + znow)/zfactor - 1.0;
//  elem.value = znow;
  elem.value = sprintf("%.7g",znow);
  plotData();
  writeVIinfo();
}

function updateFromzinput(){
  var zinput = Number(document.getElementById("zinput").value); 
  znow = zinput;
  plotData();
  writeVIinfo();
}

function resetTozpipe()
{
  var elem = document.getElementById("zinput"); 
  znow = modelz0_zpipe;
  elem.value = znow;
  plotData();
  writeVIinfo();
}
function setTominus1()
{
  var elem = document.getElementById("zinput"); 
  znow = -1.0;
  elem.value = znow;
  plotData();
  writeVIinfo();
}


function updateSmoothing(){
  //re-calc the smoothed flux array
  var boxsize =  $("input[type='radio'][name='smoothing']:checked").val();
  smoothArray(fluxArray, smoothedArray, boxsize);
  plotData();
}


function resetZoom(){
  x0 = orig_x0;
  x1 = orig_x1;
  y0 = orig_y0;
  y1 = orig_y1;
  plotData();
}
function previousZoom(){
  x0 = prev_x0;
  x1 = prev_x1;
  y0 = prev_y0;
  y1 = prev_y1;
  plotData();
}

function applyZoom(xfactor,yfactor){
  prev_x0 = x0;
  prev_x1 = x1;
  prev_y0 = y0;
  prev_y1 = y1;
  x0 = 0.5*(prev_x0+prev_x1) - 0.5*(prev_x1-prev_x0)*xfactor;
  x1 = 0.5*(prev_x0+prev_x1) + 0.5*(prev_x1-prev_x0)*xfactor;
  y0 = 0.5*(prev_y0+prev_y1) - 0.5*(prev_y1-prev_y0)*yfactor;
  y1 = 0.5*(prev_y0+prev_y1) + 0.5*(prev_y1-prev_y0)*yfactor;
  plotData();
}
function applyOffset(xfrac,yfrac){
  prev_x0 = x0;
  prev_x1 = x1;
  prev_y0 = y0;
  prev_y1 = y1;
  var xmid = 0.5*(prev_x0+prev_x1) + (prev_x1-prev_x0)*xfrac;
  var ymid = 0.5*(prev_y0+prev_y1) + (prev_y1-prev_y0)*yfrac;
  x0 = xmid - 0.5*(prev_x1-prev_x0);
  x1 = xmid + 0.5*(prev_x1-prev_x0);
  y0 = ymid - 0.5*(prev_y1-prev_y0);
  y1 = ymid + 0.5*(prev_y1-prev_y0);
  plotData();
}

//see guide at https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Sending_forms_through_JavaScript
//write required values to url encoded string and send using an XMLHttpRequest
function submitVIinfo(){
  var XHR = new XMLHttpRequest();
  var FD  = new FormData();

  //gather the data
  var plate = "-";
  var mjd = "-";
  var fiberid = "-";
  var ra = "-";
  var dec = "-";
  var z_conf_person = $("input[type='radio'][name='z_conf_person']:checked").val();
  var class_person  = $("input[type='radio'][name='class_person']:checked").val();
  var issue         = document.getElementById("issueSelect").value; 
  var comments      = document.getElementById("commentBox").value; 
  var run1d = "-";
  var run2d = "-";
  for(var i=0;i<nkeys;i++) 
  {
    switch (keynames[i]) {
      case "PLATE":    plate   = keyvals[i]; break;
      case "MJD":      mjd     = keyvals[i]; break;
      case "FIBERID":  fiberid = keyvals[i]; break;
      case "PLUG_RA":  ra      = keyvals[i]; break;
      case "PLUG_DEC": dec     = keyvals[i]; break;
      case "Z":        zpipe   = keyvals[i]; break;
      case "RUN1D":    run1d   = keyvals[i]; break;
      case "RUN2D":    run2d   = keyvals[i]; break;
    }
  }

   FD.append("PLATE"        ,plate);
   FD.append("MJD"          ,mjd);
   FD.append("FIBERID"      ,fiberid);
   FD.append("RA"           ,ra);
   FD.append("DEC"          ,dec);
   FD.append("Z_PIPE"       ,zpipe);
   FD.append("Z_VI"         ,znow);
   FD.append("Z_CONF_PERSON",z_conf_person);
   FD.append("CLASS_PERSON" ,class_person);
   FD.append("ISSUE"        ,issue);
   FD.append("COMMENTS"     ,comments);
   FD.append("RUN1D"        ,run1d);
   FD.append("RUN2D"        ,run2d);


//   // -----------------------------
//   // The following doesn't seem to do anything....maybe it catches errors that I've not tested against? 
//   // We define what will happen if the data are successfully sent
//   XHR.addEventListener('load', function(event) { 
//     //    alert('Success! Data sent and response loaded.');
//     //add a pip to the submission button
//     document.getElementById("submitButton").value += ".";
//   });
// 
//   // We define what will happen in case of error
//   XHR.addEventListener('error', function(event) {
//     alert('Error! Something went wrong when submitting your results.');
//   });
//   // -----------------------------

  // We setup our request ('false' flag specifies that this should be synchronous)
  XHR.open('POST', submit_php, false);

  // We just send our FormData object, HTTP headers are set automatically
  XHR.send(FD);

  // This catches some errors
  if (XHR.status != 0) {
    var success_text = "Success!"; 
    if (XHR.responseText.substring(0, success_text.length) === success_text) {
      //add a pip to the submission button
      document.getElementById("submitButton").value += ".";
    } else {
      alert('Error! Something went badly wrong when submitting your results (see console for details).');
      console.log(XHR.responseText); //debug output for those who are interested
    };
  };
}

			 
//write formatted description of the current fit
//requires that the header keywords are in the input spec file and stored in the keynames[],keyvals[] arrays
function writeVIinfo(){
  var outbox = document.getElementById("resultBox"); 
  var str = "";
  var plate = "-";
  var mjd = "-";
  var fiberid = "-";
  var ra = "-";
  var dec = "-";
  var z_conf_person = $("input[type='radio'][name='z_conf_person']:checked").val();
  var class_person  = $("input[type='radio'][name='class_person']:checked").val();
  var issue         = document.getElementById("issueSelect").value; 
  var comments      = document.getElementById("commentBox").value; 
  for(var i=0;i<nkeys;i++) 
  {
    switch (keynames[i]) {
      case "PLATE":    plate   = keyvals[i]; break;
      case "MJD":      mjd     = keyvals[i]; break;
      case "FIBERID":  fiberid = keyvals[i]; break;
      case "PLUG_RA":  ra      = keyvals[i]; break;
      case "PLUG_DEC": dec     = keyvals[i]; break;
      case "Z":        zpipe   = keyvals[i]; break;
    }
  }
  str = sprintf("SDSSOBJECT %5d %5d %4d %12.7f %12.7f %10s %.7g %3s \"%8s\" \"%s\" \"%s\"\n", 
		  plate, mjd, fiberid, ra, dec, zpipe, znow, z_conf_person, class_person, issue, comments);
  outbox.value = str;
}

function writePipeInfo(){
  var ra = -99.9;
  var dec = -99.9;
  for(var i=0;i<nkeys;i++) 
  {
    switch (keynames[i]) {
      case "PLATE":         document.getElementById("pipeParams_PLATE"        ).innerHTML = keyvals[i]; break;
      case "MJD":           document.getElementById("pipeParams_MJD"          ).innerHTML = keyvals[i]; break;
      case "FIBERID":       document.getElementById("pipeParams_FIBERID"      ).innerHTML = keyvals[i]; break;
      case "PLUG_RA":       document.getElementById("pipeParams_PLUG_RA"      ).innerHTML = keyvals[i]; ra  = Number(keyvals[i]); break;
      case "PLUG_DEC":      document.getElementById("pipeParams_PLUG_DEC"     ).innerHTML = keyvals[i]; dec = Number(keyvals[i]); break;
      case "Z":             document.getElementById("pipeParams_Z"            ).innerHTML = keyvals[i]; break;
      case "Z_ERR":         document.getElementById("pipeParams_Z_ERR"        ).innerHTML = keyvals[i]; break;
      case "CLASS":         document.getElementById("pipeParams_CLASS"        ).innerHTML = keyvals[i]; break;
      case "SUBCLASS":      document.getElementById("pipeParams_SUBCLASS"     ).innerHTML = keyvals[i]; break;
      case "SN_MEDIAN_ALL": document.getElementById("pipeParams_SN_MEDIAN_ALL").innerHTML = keyvals[i]; break;
      case "ZWARNING":      
        var str = sprintf("<a href='http://www.mpe.mpg.de/~tdwelly/SPIDERS/bitmask_decoder.html?ZWARNING=%s' target=_blank title='decode the ZWARNING flag'>%s</a>", 
                  keyvals[i],keyvals[i]);
        document.getElementById("pipeParams_ZWARNING"     ).innerHTML = str; break;
    }
  }

  var str = "";
  if ( ra > -99. && dec > -99) {
    var str1 = sprintf("<a href='http://skyserver.sdss.org/dr12/en/tools/explore/summary.aspx?ra=%g&dec=%g' target='_blank' title='View imaging for this object in the SDSS Explore service'>Explore</a>", ra, dec); 
    var str2 = sprintf("<a href='http://irsa.ipac.caltech.edu/applications/finderchart/#id=Hydra_finderchart_finder_chart&RequestClass=ServerRequest&DoSearch=true&subsize=0.0166667&thumbnail_size=medium&sources=DSS,SDSS,twomass,WISE&UserTargetWorldPt=%s;%s;EQ_J2000&SimpleTargetPanel.field.resolvedBy=nedthensimbad&projectId=finderchart&searchName=finder_chart&isDrillDownRoot=true&isSearchResult=true' target='_blank' title='View imaging for this object in the IRSA Hydra finder chart service'>IRSA</a>", ra, dec); 
    var str3 = sprintf("<a href='http://simbad.u-strasbg.fr/simbad/sim-coo?output.format=HTML&Coord=%s+%s&Radius=10&Radius.unit=arcsec' target='_blank' title='Search around this position in the Simbad service'>Simbad</a> ", ra, dec); 
    str = str1.concat(",",str2,",",str3); 
  } 
  document.getElementById("pipeParams_links").innerHTML = str;

  str = sprintf("Inspect the original specfile in your browser: <a href='%s' target='_blank' title='Inspect the original specfile in your browser' >%s</a>", specfile, specfile);
  document.getElementById("inspectInBrowser").innerHTML = str;
}



function smoothArray(original, smoothed, boxsize)
{
  if ( boxsize == 1 ) 
  {
    for (var i=0; i < original.length; i++) smoothed[i] = original[i];
  }
  else if (  boxsize > 1 )
  {
    var halfbox = Math.floor(boxsize/2);
    for (var i=0; i < original.length; i++)
    {
      var n   = 0;
      var sum = 0.0;
      for (var j=i-halfbox; j <= i+halfbox; j++)
      {
        if ( j >= 0 && j < original.length )
        {
          sum += original[j];
          n += 1;
        }
      }
      smoothed[i] = sum / ( n > 0 ? n : 1);
    }
  }
}


//deal with key presses
canvas.addEventListener('keydown',doKeyDown,true);

function doKeyDown(evt){
//  console.log(evt.keyCode);
  switch (evt.keyCode) {
  case 38:  /* Up arrow was pressed */
    renorm *= drenorm;
    plotData();
  break;
  case 40:  /* Down arrow was pressed */
    renorm /= drenorm;
    plotData();
  break;
  case 37:  /* Left arrow was pressed */ 
    decrementRedshift(dznow_fine);
  break;
  case 39:  /* Right arrow was pressed */
    incrementRedshift(dznow_fine);
  break;
  }
}




///deal with mouse zooming etc

function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return {
     x: Math.round((evt.clientX-rect.left)/(rect.right-rect.left)*canvas.width),
     y: Math.round((evt.clientY-rect.top)/(rect.bottom-rect.top)*canvas.height)
  };
}

function getMousePosExact(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return {
     x: ((evt.clientX-rect.left)/(rect.right-rect.left)*canvas.width),
     y: ((evt.clientY-rect.top)/(rect.bottom-rect.top)*canvas.height)
  };
}

document.body.addEventListener('mousedown', function (evt){
  if(evt.button === rightclick  ){
      //record the current cursor position;
      mousePos_old = getMousePos(canvas, evt);
  }
  else if(evt.button === leftclick )
  {
    //display the current position of the cursor
    var mousePos = getMousePosExact(canvas, evt);
    var xsize = canvas.width;
    var ysize = canvas.height; 
    if ( mousePos.x >= 0.0 && mousePos.x <= xsize && 
         mousePos.y >= 0.0 && mousePos.y <= ysize ) {
      var dx = (x1-x0)/(xsize-padx);
      var dy = (y1-y0)/(ysize-2.*pady);
      var lobs = (mousePos.x - padx1)*dx + x0;
      var flux  = (ysize - mousePos.y - pady)*dy + y0;
      var lrest = lobs / (znow + 1.); 
      var str = sprintf("(%s,%s,F%s)=(%.2f%s, %.2f%s, %.2f%s)", 
           String.fromCharCode(955,8338), String.fromCharCode(955,7523), String.fromCharCode(955),
           lobs,String.fromCharCode(8491),lrest,String.fromCharCode(8491),flux, 
           String.fromCharCode(215)+"10"+String.fromCharCode(8315,185,8311)+" erg cm"+String.fromCharCode(8315,178) +" s"+ String.fromCharCode(8315,185) + " " + String.fromCharCode(8491,8315,185));
      ctx.clearRect (xsize-44.*padx2, ysize-0.6*pady, xsize, ysize);
      ctx.fillText(str,  xsize-22.*padx2, ysize-0.2*pady);
    }
  }
  else
  {
    console.log(evt.button);
  }
}, false);

document.body.addEventListener('mouseup', function (evt){
  if(evt.button === rightclick )
  {
    //record the current cursor position;
    //then set the new x0,x1,y0,y1
    var xsize = canvas.width;
    var ysize = canvas.height; 
    var dx_inv = (xsize-padx)/(x1-x0);
    var dy_inv = (ysize-2.*pady)/(y1-y0);
    var mousePos_new = getMousePos(canvas, evt);
    var min_x = Math.min(mousePos_old.x,mousePos_new.x);
    var max_x = Math.max(mousePos_old.x,mousePos_new.x);
    var min_y = Math.min(mousePos_old.y,mousePos_new.y);
    var max_y = Math.max(mousePos_old.y,mousePos_new.y);
    
    prev_x0 = x0;
    prev_x1 = x1;
    prev_y0 = y0;
    prev_y1 = y1;
    x0 = prev_x0 + (min_x - padx1)/dx_inv; 
    x1 = prev_x0 + (max_x - padx1)/dx_inv; 
    y0 = prev_y0 + (ysize - pady - max_y)/dy_inv; 
    y1 = prev_y0 + (ysize - pady - min_y)/dy_inv; 
    plotData();
  }

}, false);


</script>
</html>