forked from bolidozor/js9
-
Notifications
You must be signed in to change notification settings - Fork 0
/
js9.min.js
executable file
·384 lines (384 loc) · 195 KB
/
js9.min.js
1
2
3
4
5
6
7
8
9
10
11
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
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
var JS9;if(JS9&&("object"!==typeof JS9||JS9.NAME))throw Error("Namespace 'JS9' already exists");JS9={NAME:"JS9",VERSION:"1.8",COPYRIGHT:"Copyright (c) 2012-2016 Smithsonian Institution"};
JS9=function(a){a.DEFID="JS9";a.ANON="[anonymous]";a.PREFSFILE="js9Prefs.json";a.ZINDEX=0;a.SHAPEZINDEX=7;a.MESSZINDEX=8;a.BTNZINDEX=10;a.MENUZINDEX=1E3;a.COLORSIZE=1024;a.SCALESIZE=16384;a.INSTALLDIR="";a.TOROOT="";a.PLUGINS="";a.LIGHTWIN="dhtml";a.ANTIALIAS=!1;a.SCALEIREG=!0;a.NOMOVE=3;a.DBLCLICK=500;a.TIMEOUT=250;a.SPINOUT=250;a.SUPERMENU=/^SUPERMENU_/;a.RESIZEDIST=20;a.RESIZEFUDGE=5;a.RAWID0="raw0";a.RAWIDX="alt";a.REPROJDIM=2200;var C=a,z=navigator.platform,G=navigator.appName,D=navigator.userAgent,
E,A=D.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);E=D.match(/version\/([\.\d]+)/i);A&&null!==E&&(A[2]=E[1]);A=A?[A[1],A[2],z]:[G,navigator.appVersion,"-?",z];A.push(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(D));C.BROWSER=A;C=a;z=document.createElement("canvas").getContext("2d");C.PIXEL_RATIO=(window.devicePixelRatio||1)/(z.webkitBackingStorePixelRatio||z.mozBackingStorePixelRatio||z.msBackingStorePixelRatio||z.oBackingStorePixelRatio||z.backingStorePixelRatio||1);a.globalOpts=
{helperType:"none",helperPort:2718,winType:"light",rgb:{active:!1,rim:null,gim:null,bim:null},defcolor:"#00FF00",pngisfits:!0,fits2png:!1,alerts:!0,internalValPos:!0,internalContrastBias:!0,htimeout:1E4,xtimeout:18E4,extlist:"EVENTS STDEVT",dims:[1024,1024],helperProtocol:location.protocol,maxMemory:75E7,corsURL:"params/loadcors.html",proxyURL:"params/loadproxy.html",loadProxy:!1,archivesURL:"help/archives.html",imsectionURL:"params/imsection.html",postMessage:!1,waitType:"spinner",spinColor:"#FF0000",
spinOpacity:0.35,resize:!0,resizeHandle:!0,debug:0};a.imageOpts={contrast:1,bias:0.5,invert:!1,exp:1E3,colormap:"grey",scale:"linear",scaleclipping:"dataminmax",zscalecontrast:0.25,zscalesamples:600,zscaleline:120,wcssys:"native",wcsunits:"sexagesimal",lcs:"physical",valpos:!0,opacity:1,sigma:"none",maskOpacity:0.4,alpha:255,alpha1:100,zoom:1,zooms:5,nancolor:"#000000",wcsalign:!0,listonchange:!1};a.regionOpts={};a.analOpts={epattern:/^(ERROR:[^\n]*)\n/,dpathURL:"params/datapath.html",prependJS9Dir:!0,
dataDir:null};a.lightOpts={nclick:0,dhtml:{top:".dhtmlwindow",drag:".drag-contentarea",dragBar:"drag-handle",format:"width=%spx,height=%spx,center=1,resize=%s,scrolling=0",textWin:"width=830px,height=400px,center=1,resize=1,scrolling=1",plotWin:"width=830px,height=420px,center=1,resize=1,scrolling=1",dpathWin:"width=830px,height=175px,center=1,resize=1,scrolling=1",paramWin:"width=830px,height=230px,center=1,resize=1,scrolling=1",imageWin:"width=512px,height=542px,center=1,resize=1,scrolling=1",lineWin:"width=400px,height=10px,center=1,resize=1,scrolling=1"}};
a.textColorOpts={regions:"#00FF00",info:"#00FF00",inimage:"#000000"};a.plotOpts={zoomStack:!0,selection:{mode:"xy"},series:{clickable:!0,hoverable:!0,lines:{show:!0},points:{show:!1}}};a.helpOpts={user:{type:"help",url:"user.html",title:"JS9 User Manual"},install:{type:"help",url:"install.html",title:"Installing JS9"},webpage:{type:"help",url:"webpage.html",title:"Adding JS9 To A Web Page"},yourdata:{type:"help",url:"yourdata.html",title:"Adding Data To A Web Page"},localtasks:{type:"help",url:"localtasks.html",
title:"Local Analysis with JS9"},publicapi:{type:"help",url:"publicapi.html",title:"The JS9 Public API"},helper:{type:"help",url:"helper.html",title:"Adding Server-side Analysis"},serverside:{type:"help",url:"serverside.html",title:"Server-side Analysis with JS9"},repfile:{type:"help",url:"repfile.html",title:"Dealing with Large Files"},regions:{type:"help",url:"regions.html",title:"JS9 Regions Format"},extmsg:{type:"help",url:"extmsg.html",title:"JS9 External Messaging"},python:{type:"help",url:"python.html",
title:"JS9 with Python and Jupyter"},preferences:{type:"help",url:"preferences.html",title:"JS9 Site Preferences"},changelog:{type:"help",url:"changelog.html",title:"JS9 ChangeLog"},issues:{type:"help",url:"knownissues.html",title:"Known Issues"}};a.menuButtonOptsArr=[{name:"file",label:"File"},{name:"view",label:"View"},{name:"zoom",label:"Zoom"},{name:"scale",label:"Scale"},{name:"color",label:"Color"},{name:"region",label:"Region"},{name:"wcs",label:"WCS"},{name:"analysis",label:"Analysis"},{name:"help",
label:"Help"}];a.images=[];a.displays=[];a.colormaps=[];a.commands=[];a.plugins=[];a.preloads=[];a.auxFiles=[];a.publics={};a.helper={};a.fits={};a.userOpts={};a.scales="linear log pow sqrt squared asinh sinh".split(" ");a.wcssyss="FK4 FK5 ICRS galactic ecliptic native image physical".split(" ");a.wcsunitss=["degrees","sexagesimal","pixels"];a.menubarHTML="";a.consoleHTML="<form name='form' onsubmit='return false;' class='JS9CmdForm' action=''><table class='JS9CmdTable'><tr class='JS9Tr'><td><div id='JS9CmdPrompt' class='JS9CmdPrompt'>@@PR@@</div></td><td class='JS9CmdTd'><input type='text' class='JS9CmdIn' autocapitalize='off' autocorrect='off' autocomplete='off' value='' /></td></tr></table></form>";
a.bugs={};a.bugs.hide_menu=!0;"Firefox"===a.BROWSER[0]&&0<=a.BROWSER[2].search(/Linux/)&&(a.bugs.firefox_linux=!0);if("Chrome"===a.BROWSER[0]||"Safari"===a.BROWSER[0])a.bugs.webkit_resize=!0;"Chrome"===a.BROWSER[0]&&(a.globalOpts.maxMemory=Math.min(a.globalOpts.maxMemory,45E7));a.Image=function(c,b,d){var e,f,g=this,h=null,j=function(a,c){var d,b=[];void 0!==c.xcen&&b.push(c.xcen);void 0!==c.ycen&&b.push(c.ycen);void 0!==c.zoom&&(d=a.parseZoom(c.zoom))&&b.push(d);return b},k=function(c){var d,b;this.clearMessage();
a.images.push(this);if(c)try{a.xeqByName(c,window,this)}catch(e){a.error("in image onload callback",e,!1)}for(d in this.display.pluginInstances)if(this.display.pluginInstances.hasOwnProperty(d)&&(c=this.display.pluginInstances[d],b=c.plugin.opts,c.isActive("onimageload")))try{b.onimageload.call(c,this)}catch(f){c.errLog("onimageload",f)}this.updateshapes&&this.updateShapes("regions","all","update");this.status.load="complete";a.waiting(!1)};b&&("object"===typeof b?(h=b,h.display&&(f=h.display)):f=
b);f||(f=0<a.displays.length?a.displays[0].id:a.DEFID);this.type="image";this.display=a.lookupDisplay(f);this.params={};this.tmp={};this.params.scalemin=Number.Nan;this.params.scalemax=Number.Nan;this.params.xeqonchange=!0;this.params.plotOpts=$.extend(!0,{},a.plotOpts);this.params=$.extend(!0,this.params,a.imageOpts,h);this.setColormap(this.params.colormap);this.displayMode=!0;this.evstate=-1;this.rclick=0;this.queried=!1;h&&h.proxyFile&&(this.proxyFile=h.proxyFile);h&&h.parentFile&&(this.parentFile=
h.parentFile);this.wcsiy=this.wcsix=this.iy=this.ix=0;this.png={};this.png.image=new Image;this.status={};this.rgb={};this.rgb.sect={zoom:1,ozoom:1};this.layers={};this.lcs={};this.aux={};this.binning={bin:1,obin:1};this.raws=[];this.blend={active:void 0,mode:"normal",opacity:1};this.updateshapes=!1;a.waiting(!0,this.display.divjq[0]);switch(typeof c){case "object":this.source="fits";this.mkRawDataFromHDU(c,{file:c.filename});"zscale"===this.params.scaleclipping&&this.zscale(!0);this.mkSection();
e=j(this,h);e.length&&this.mkSection.apply(this,e);h&&h.rgbFile?(this.rgbFile=h.rgbFile,$(this.png.image).on("load",function(){var c;if(g.png.image.width!==g.raw.width||g.png.image.height!==g.raw.height)c=sprintf("rgb dims [%s,%s] don't match image [%s,%s]",g.png.image.width,g.png.image.height,g.raw.width,g.raw.height),a.error(c);g.mkOffScreenCanvas();g.displayImage("all",h);k.call(g,d)}).on("error",function(){a.waiting(!1);g.status.load="error";a.error("could not load image: "+g.id)}),this.png.image.src=
this.rgbFile):(this.displayImage("all",h),k.call(this,d));break;case "string":this.source="fits2png";this.imtab="image";this.file=c;this.oid=this.file.split("/").reverse()[0];this.id=a.getImageID(this.oid,this.display.id);this.status.load="loading";$(this.png.image).on("load",function(){g.mkOffScreenCanvas();g.mkRawDataFromPNG();"zscale"===g.params.scaleclipping&&g.zscale(!0);g.mkSection();e=j(g,h);e.length&&g.mkSection.apply(g,e);g.displayImage("all",h);k.call(g,d);a.DEBUG&&a.log("JS9 image: %s dims(%d,%d) min/max(%d,%d)",
g.file,g.raw.width,g.raw.height,g.raw.dmin,g.raw.dmax)}).on("error",function(){a.waiting(!1);g.status.load="error";a.error("could not load image: "+g.id)});this.png.image.src=c;break;default:a.log("unknown specification type for Load: "+typeof c)}};a.Image.prototype.getImageData=function(a){var b=null;if(a)if("array"===a)b=Array.prototype.slice.call(this.raw.data);else if("base64"===a){var b="",d=new Uint8Array(this.raw.data.buffer),e=d.byteLength;for(a=0;a<e;a++)b+=String.fromCharCode(d[a]);b=window.btoa(b)}else a&&
"false"!==a&&(b=this.raw.data);return{id:this.id,file:this.file,fits:this.fitsFile||"",source:this.source,imtab:this.imtab,width:this.raw.width,height:this.raw.height,bitpix:this.raw.bitpix,header:this.raw.header,data:b}};a.Image.prototype.closeImage=function(){var c,b,d,e,f,g;d=a.images.length;var h=this.display,j=function(c){c.stderr?a.error(c.stderr):c.stdout&&a.log(c.stdout)};for(c=0;c<d;c++)if(this===a.images[c]){d=a.images[c];d.clearMessage();d.display.context.clear();for(e in d.display.pluginInstances)if(d.display.pluginInstances.hasOwnProperty(e)&&
(f=d.display.pluginInstances[e],g=f.plugin.opts,f.isActive("onimageclose")))try{g.onimageclose.call(f,d)}catch(k){f.errLog("onimageclose",k)}for(b in d.layers)d.layers.hasOwnProperty(b)&&d.layers[b].canvas.clear();d.display.image=null;switch(d.cmapObj.name){case "red":a.globalOpts.rgb.rim=null;break;case "green":a.globalOpts.rgb.gim=null;break;case "blue":a.globalOpts.rgb.bim=null}if(a.fits.cleanupFITSFile)for(b=0;b<d.raws.length;b++)d.raws[b].hdu&&d.raws[b].hdu.fits&&a.fits.cleanupFITSFile(d.raws[b].hdu.fits,
!0);d.proxyFile&&a.Send("removeproxy",{cmd:"js9Xeq removeproxy "+d.proxyFile},j);d.rgb=null;d.offscreen=null;d.raw=null;d.colorData=null;d.colorCells=null;d.psColors=null;d=d.psInverse=null;a.images.splice(c,1);break}for(c=0;c<a.images.length;c++)if(d=a.images[c],h===d.display){d.displayImage("display");d.refreshLayers();break}};a.Image.prototype.mkOffScreenCanvas=function(){if(!this.png||!this.png.image)return this;this.offscreen={};this.offscreen.canvas=document.createElement("canvas");this.offscreen.canvas.setAttribute("width",
this.png.image.width);this.offscreen.canvas.setAttribute("height",this.png.image.height);this.offscreen.context=this.offscreen.canvas.getContext("2d");a.ANTIALIAS||(this.offscreen.context.imageSmoothingEnabled=!1,this.offscreen.context.mozImageSmoothingEnabled=!1,this.offscreen.context.webkitImageSmoothingEnabled=!1);this.offscreen.context.drawImage(this.png.image,0,0);try{this.offscreen.img=this.offscreen.context.getImageData(0,0,this.png.image.width,this.png.image.height)}catch(c){"Chrome"===a.BROWSER[0]&&
""===document.domain?alert("When using the file:// URI, Chrome must be run with the --allow-file-access-from-files switch to permit JS9 to access data."):alert("could not read off-screen image data [same-origin policy violation?]")}return this};a.Image.prototype.initLCS=function(a){var b=[[0,0,0],[0,0,0],[0,0,0]],d=function(a){var c,d,b=0,j=0,k=[[0,0,0],[0,0,0],[0,0,0]],m=a[0][0]*a[1][1];for(c=0;3>c;c++)for(d=0;2>d;d++)if(void 0===a[c][d]||isNaN(a[c][d]))return null;0<=m?b+=m:j+=m;m=-a[0][1]*a[1][0];
0<=m?b+=m:j+=m;c=b+j;if(0===c||1E-15>Math.abs(c/(b-j)))return null;c=1/c;k[0][0]=a[1][1]*c;k[1][0]=-a[1][0]*c;k[0][1]=-a[0][1]*c;k[1][1]=a[0][0]*c;k[2][0]=-(a[2][0]*k[0][0]+a[2][1]*k[1][0]);k[2][1]=-(a[2][0]*k[0][1]+a[2][1]*k[1][1]);return k};a&&(b[0][0]=a.LTM1_1||1,b[1][0]=a.LTM2_1||0,b[0][1]=a.LTM1_2||0,b[1][1]=a.LTM2_2||1,b[2][0]=a.LTV1||0,b[2][1]=a.LTV2||0,this.lcs.physical={forward:$.extend(!0,[],b),reverse:d(b)},this.lcs.physical.reverse||delete this.lcs.physical,b[0][0]=a.DTM1_1||1,b[1][0]=
a.DTM2_1||0,b[0][1]=a.DTM1_2||0,b[1][1]=a.DTM2_2||1,b[2][0]=a.DTV1||0,b[2][1]=a.DTV2||0,this.lcs.detector={forward:$.extend(!0,[],b),reverse:d(b)},this.lcs.detector.reverse||delete this.lcs.detector,b[0][0]=a.ATM1_1||1,b[1][0]=a.ATM2_1||0,b[0][1]=a.ATM1_2||0,b[1][1]=a.ATM2_2||1,b[2][0]=a.ATV1||0,b[2][1]=a.ATV2||0,this.lcs.amplifier={forward:$.extend(!0,[],b),reverse:d(b)},this.lcs.amplifier.reverse||delete this.lcs.amplifier,this.lcs[this.params.lcs]||(this.params.lcs="image"),this.params.wcssys0||
(this.setWCSSys("physical"),this.params.wcssys0=this.params.lcs))};a.Image.prototype.mkRawDataFromIMG=function(c){var b,d,e,f,g,h;if(c){b=c.height;d=c.width;e=c.data;this.raws.push({from:"img"});this.raw=this.raws[this.raws.length-1];this.raw.id=a.RAWID0;this.raw.data=new Float32Array(b*d);for(g=c=0;g<b;g++)for(f=0;f<d;f++)h=0.299*e[c]+0.587*e[c+1]+0.114*e[c+2],this.raw.data[(b-g)*d+f]=h,c+=4;this.raw.width=d;this.raw.height=b;this.raw.bitpix=-32;this.raw.dmin=Number.MAX_VALUE;this.raw.dmax=Number.MIN_VALUE;
for(c=0;c<b*d;c++)isNaN(this.raw.data[c])||(this.raw.dmin=Math.min(this.raw.dmin,this.raw.data[c]),this.raw.dmax=Math.max(this.raw.dmax,this.raw.data[c]));isNaN(this.params.scalemin)&&(this.params.scalemin=this.raw.dmin);isNaN(this.params.scalemax)&&(this.params.scalemax=this.raw.dmax);this.source="png";this.raw.header={SIMPLE:!0,NAXIS:2,NAXIS1:this.raw.width,NAXIS2:this.raw.height,BITPIX:this.raw.bitpix};return this}};a.Image.prototype.mkRawDataFromPNG=function(){var c,b,d,e,f,g,h,j;h=[];d=new ArrayBuffer(8);
var k=new Uint8Array(d),m=new DataView(d);if(!this.offscreen.img)return this;this.raws.push({from:"png"});this.raw=this.raws[this.raws.length-1];this.raw.id=a.RAWID0;e=this.offscreen.img.data;for(c=d=0;d<e.length&&0!==e[d];d++)if(255!==e[d]&&(h[c]=String.fromCharCode(e[d]),c++),15===c&&'{"js9Protocol":'!==h.join("")){f=!0;break}if(!(15>c||f)){c=h.join("");2<a.DEBUG&&a.log("jsonHeader: %s",c);try{b=JSON.parse(c)}catch(n){a.error("can't read FITS header from PNG file: "+c,n)}if(1===b.js9Protocol)this.raw.header=
b,this.raw.endian=this.raw.header.js9Endian,this.raw.protocol=this.raw.header.js9Protocol;else{this.raw.endian=b.js9Endian;this.raw.protocol=b.js9Protocol;this.raw.cardstr=b.cardstr;this.raw.ncard=b.ncard;this.raw.header={};b=this.raw.ncard;for(c=0;c<b;c++)f=this.raw.cardstr.slice(80*c,80*(c+1)),f=a.cardpars(f),void 0!==f&&(this.raw.header[f[0]]=f[1])}d+=1;this.raw.header.NAXIS1?this.raw.width=this.raw.header.NAXIS1:a.error("NAXIS1 missing from PNG-based FITS header");this.raw.header.NAXIS2?this.raw.height=
this.raw.header.NAXIS2:a.error("NAXIS2 missing from PNG-based FITS header");this.raw.header.BITPIX?this.raw.bitpix=this.raw.header.BITPIX:a.error("BITPIX missing from PNG-based FITS header");"little"===this.raw.endian?j=!0:"big"===this.raw.endian?j=!1:a.error("js9Endian missing from PNG-based FITS header");this.object=this.raw.header.OBJECT;this.raw.dmin=Number.MAX_VALUE;this.raw.dmax=Number.MIN_VALUE;b=this.raw.width*this.raw.height;f=d%4;switch(this.raw.bitpix){case 8:this.raw.data=new Uint8Array(b);
for(c=0;c<b;c++){switch(f){case 0:g=e[d];d+=1;f=1;break;case 1:g=e[d];d+=1;f=2;break;case 2:g=e[d];d+=2;f=0;break;case 3:g=e[d+1],d+=2,f=1}this.raw.data[c]=g;isNaN(g)||(this.raw.dmin=Math.min(this.raw.dmin,g),this.raw.dmax=Math.max(this.raw.dmax,g))}break;case 16:case -16:16===this.raw.bitpix?(this.raw.data=new Int16Array(b),h=DataView.prototype.getInt16):(this.raw.data=new Uint16Array(b),h=DataView.prototype.getUint16);for(c=0;c<b;c++){switch(f){case 0:k[0]=e[d];k[1]=e[d+1];g=h.call(m,0,j);d+=2;
f=2;break;case 1:k[0]=e[d];k[1]=e[d+1];g=h.call(m,0,j);d+=3;f=0;break;case 2:k[0]=e[d];k[1]=e[d+2];g=h.call(m,0,j);d+=3;f=1;break;case 3:k[0]=e[d+1],k[1]=e[d+2],g=h.call(m,0,j),d+=3,f=2}this.raw.data[c]=g;isNaN(g)||(this.raw.dmin=Math.min(this.raw.dmin,g),this.raw.dmax=Math.max(this.raw.dmax,g))}break;case 32:case -32:32===this.raw.bitpix?(this.raw.data=new Int32Array(b),h=DataView.prototype.getInt32):(this.raw.data=new Float32Array(b),h=DataView.prototype.getFloat32);for(c=0;c<b;c++){switch(f){case 0:k[0]=
e[d];k[1]=e[d+1];k[2]=e[d+2];k[3]=e[d+4];g=h.call(m,0,j);d+=5;f=1;break;case 1:k[0]=e[d];k[1]=e[d+1];k[2]=e[d+3];k[3]=e[d+4];g=h.call(m,0,j);d+=5;f=2;break;case 2:k[0]=e[d];k[1]=e[d+2];k[2]=e[d+3];k[3]=e[d+4];g=h.call(m,0,j);d+=6;f=0;break;case 3:k[0]=e[d+1],k[1]=e[d+2],k[2]=e[d+3],k[3]=e[d+5],g=h.call(m,0,j),d+=6,f=1}this.raw.data[c]=g;isNaN(g)||(this.raw.dmin=Math.min(this.raw.dmin,g),this.raw.dmax=Math.max(this.raw.dmax,g))}break;case -64:this.raw.data=new Float64Array(b);for(c=0;c<b;c++){switch(f){case 0:case 4:k[0]=
e[d];k[1]=e[d+1];k[2]=e[d+2];k[3]=e[d+4];k[4]=e[d+5];k[5]=e[d+6];k[6]=e[d+8];k[7]=e[d+9];g=m.getFloat64(0,j);d+=10;f=2;break;case 1:case 5:k[0]=e[d];k[1]=e[d+1];k[2]=e[d+3];k[3]=e[d+4];k[4]=e[d+5];k[5]=e[d+7];k[6]=e[d+8];k[7]=e[d+9];g=m.getFloat64(0,j);d+=11;f=0;break;case 2:case 6:k[0]=e[d];k[1]=e[d+2];k[2]=e[d+3];k[3]=e[d+4];k[4]=e[d+6];k[5]=e[d+7];k[6]=e[d+8];k[7]=e[d+10];g=m.getFloat64(0,j);d+=11;f=1;break;case 3:case 7:k[0]=e[d+1],k[1]=e[d+2],k[2]=e[d+3],k[3]=e[d+5],k[4]=e[d+6],k[5]=e[d+7],k[6]=
e[d+9],k[7]=e[d+10],g=m.getFloat64(0,j),d+=11,f=2}this.raw.data[c]=g;isNaN(g)||(this.raw.dmin=Math.min(this.raw.dmin,g),this.raw.dmax=Math.max(this.raw.dmax,g))}break;default:a.error("unsupported bitpix in PNG file: "+this.raw.bitpix)}isNaN(this.params.scalemin)&&(this.params.scalemin=this.raw.dmin);isNaN(this.params.scalemax)&&(this.params.scalemax=this.raw.dmax);this.offscreen.img=null;this.wcs=a.initwcs(a.raw2FITS(this.raw));0<this.wcs&&(this.setWCSSys(this.params.wcssys),this.params.wcssys0=this.params.wcssys.trim());
this.initLCS(this.raw.header);return this}};a.Image.prototype.mkRawDataFromHDU=function(c,b){var d,e,f,g,h,j,k;b=b||{};$.isArray(c)||a.isTypedArray(c)||c instanceof ArrayBuffer?($.isArray(c[0])&&(c=c.reduce(function(a,c){return a.concat(c)})),g={image:c}):"object"===typeof c?g=c:a.error("unknown or missing input for HDU creation");g.data&&!g.image&&(g.image=g.data);g.image||a.error("data missing from JS9 FITS object"+JSON.stringify(g));2>g.naxis&&a.error("can't image a FITS file with less than 2 dimensions");
b.file?this.file=b.file:g.filename&&(this.file=g.filename);this.file=this.file||a.ANON;this.id||(this.oid=this.file.split("/").reverse()[0],this.id=a.getImageID(this.oid,this.display.id));this.raw&&(h=this.raw.width,j=this.raw.height,k=this.raw.bitpix);if(f=this.raws.length){b.rawid=b.rawid||a.RAWIDX;for(d=e=0;d<f;d++)if(b.rawid===this.raws[d].id){this.raws[d]={};this.raw=this.raws[d];e++;break}e||(this.raws.push({from:"hdu",id:b.rawid}),this.raw=this.raws[f])}else this.raws.push({from:"hdu"}),this.raw=
this.raws[f],this.raw.id=a.RAWID0;this.raw.hdu=g;g.axis?(this.raw.width=g.axis[1],this.raw.height=g.axis[2]):g.naxis1&&g.naxis2?(this.raw.width=g.naxis1,this.raw.height=g.naxis2):h&&j&&(this.raw.width=h,this.raw.height=j);g.bitpix?this.raw.bitpix=g.bitpix:k&&(this.raw.bitpix=k);if("base64"===g.encoding){e=window.atob(g.image);g.image=new ArrayBuffer(e.length);f=new Uint8Array(g.image);for(d=0;d<e.length;d++)f[d]=e.charCodeAt(d)}$.isArray(g.image[0])&&(g.image=g.image.reduce(function(a,c){return a.concat(c)}));
switch(this.raw.bitpix){case 8:this.raw.data=new Uint8Array(g.image);break;case 16:this.raw.data=new Int16Array(g.image);break;case -16:this.raw.data=new Uint16Array(g.image);break;case 32:this.raw.data=new Int32Array(g.image);break;case -32:this.raw.data=new Float32Array(g.image);break;case -64:this.raw.data=new Float64Array(g.image)}this.raw.card=g.card;this.raw.cardstr=g.cardstr;this.raw.ncard=g.ncard;if(g.head)this.raw.header=g.head;else if(this.raw.card){this.raw.header={};e=this.raw.card.length;
for(d=0;d<e;d++)f=a.cardpars(this.raw.card[d]),void 0!==f&&(this.raw.header[f[0]]=f[1])}else if(this.raw.cardstr){this.raw.header={};e=this.raw.ncard;for(d=0;d<e;d++)f=this.raw.cardstr.slice(80*d,80*(d+1)),f=a.cardpars(f),void 0!==f&&(this.raw.header[f[0]]=f[1])}else this.raw.header={},this.raw.header.SIMPLE=!0,this.raw.header.NAXIS=2,this.raw.header.NAXIS1=this.raw.width,this.raw.header.NAXIS2=this.raw.height,this.raw.header.BITPIX=this.raw.bitpix;if(g.dmin&&g.dmax)this.raw.dmin=g.dmin,this.raw.dmax=
g.dmax;else{this.raw.dmin=Number.MAX_VALUE;this.raw.dmax=Number.MIN_VALUE;e=this.raw.width*this.raw.height;for(d=0;d<e;d++)isNaN(this.raw.data[d])||(this.raw.dmin=Math.min(this.raw.dmin,this.raw.data[d]),this.raw.dmax=Math.max(this.raw.dmax,this.raw.data[d]))}this.imtab=g.imtab?g.imtab:g.table?"table":"image";this.object=this.raw.header.OBJECT;this.binning.bin="table"===this.imtab&&g.table?Number(g.table.bin)||1:1;this.wcs=a.initwcs(a.raw2FITS(this.raw));0<this.wcs&&(this.setWCSSys(this.params.wcssys),
this.params.wcssys0=this.params.wcssys.trim(),this.setWCSUnits(this.params.wcsunits));this.initLCS(this.raw.header);isNaN(this.params.scalemin)&&(this.params.scalemin=this.raw.dmin);isNaN(this.params.scalemax)&&(this.params.scalemax=this.raw.dmax);return this};a.Image.prototype.mkSection=function(a,b,d){var e=this.rgb.sect;switch(arguments.length){case 0:e.xcen=Math.floor(this.raw.width/2);e.ycen=Math.floor(this.raw.height/2);e.width=Math.min(this.raw.width,this.display.canvas.width);e.height=Math.min(this.raw.height,
this.display.canvas.height);break;case 1:e.ozoom=e.zoom;e.zoom=a;e.width=Math.min(this.raw.width*e.zoom,this.display.canvas.width);e.height=Math.min(this.raw.height*e.zoom,this.display.canvas.height);break;case 2:e.xcen=parseInt(a,10);e.ycen=parseInt(b,10);break;case 3:e.xcen=parseInt(a,10),e.ycen=parseInt(b,10),e.ozoom=e.zoom,e.zoom=d,e.width=Math.min(this.raw.width*e.zoom,this.display.canvas.width),e.height=Math.min(this.raw.height*e.zoom,this.display.canvas.height)}e.width=Math.floor(e.width);
e.height=Math.floor(e.height);e.x0=Math.floor(e.xcen-(e.width+1)/(2*e.zoom)+1);e.y0=Math.floor(e.ycen-(e.height+1)/(2*e.zoom)+1);e.x1=Math.floor(e.xcen+e.width/(2*e.zoom));e.y1=Math.floor(e.ycen+e.height/(2*e.zoom));0>e.x0&&(e.x1-=e.x0,e.x0=0);0>e.y0&&(e.y1-=e.y0,e.y0=0);e.x1>this.raw.width&&(e.x0-=e.x1-this.raw.width,e.x1=this.raw.width);e.y1>this.raw.height&&(e.y0-=e.y1-this.raw.height,e.y1=this.raw.height);e.x0=Math.max(0,e.x0);e.y0=Math.max(0,e.y0);this.offscreenRGB=null;return this};a.Image.prototype.mkColorData=
function(){var c,b,d=a.SCALESIZE,e=this.params.scalemin,f=this.params.scalemax,g=this.raw.width*this.raw.height,h=(d-1)/(f-e);this.colorData||(this.colorData=[]);for(c=0;c<g;c++)b=this.raw.data[c],this.colorData[c]=b<=e?0:b>=f?d-1:Math.floor((b-e)*h+0.5);return this};a.Image.prototype.calcContrastBias=function(c){var b=a.COLORSIZE,d=this.params.bias,e=this.params.contrast;if(1E-4>d-0.5&&1E-4>e-1)return c;this.params.invert&&(d=1-d);c=Math.floor(((c/b-d)*e+0.5)*b);return 0>c?0:c>=b?b-1:c};a.Image.prototype.mkColorCells=
function(){var c,b,d=a.COLORSIZE;this.colorCells||(this.colorCells=[]);for(c=0;c<d;c++)b=this.params.invert?d-c-1:c,b=this.calcContrastBias(b),this.colorCells[c]=this.cmapObj.mkColorCell(b);return this};a.Image.prototype.mkScaledCells=function(){var c,b,d,e,f,g,h=a.COLORSIZE,j=a.SCALESIZE;if(!this.colorCells)return this;if(!this.psColors){c=this.psColors=[];b=this.params.nancolor;var k=[];"#"===b.charAt(0)&&(b=b.slice(1));b=b.toUpperCase();for(e=d=0;6>d;d+=2,e++)f="0123456789ABCDEF".indexOf(b.charAt(d)),
g="0123456789ABCDEF".indexOf(b.charAt(d+1)),k[e]=16*f+g;c[NaN]=k}this.psInverse||(this.psInverse=[],this.psInverse[NaN]=0);b=this.params.scalemax-this.params.scalemin;g=this.params.scalemin;switch(this.params.scale){case "linear":for(d=0;d<j;d++)c=d/j,e=Math.floor(c*h),this.psColors[d]=this.colorCells[e],this.psInverse[d]=c*b+g;break;case "log":f=this.params.exp;for(d=0;d<j;d++)c=Math.log(f*d/j+1)/Math.log(f),e=Math.floor(c*h),e>=h&&(e=h-1),this.psColors[d]=this.colorCells[e],c=(Math.pow(f,d/j)-1)/
f,this.psInverse[d]=c*b+g;break;case "pow":f=this.params.exp;for(d=0;d<j;d++)c=(Math.pow(f,d/j)-1)/f,e=Math.floor(c*h),e>=h&&(e=h-1),this.psColors[d]=this.colorCells[e],c=Math.log(f*d/j+1)/Math.log(f),this.psInverse[d]=c*b+g;break;case "sqrt":for(d=0;d<j;d++)c=d/j,e=Math.floor(Math.sqrt(c)*h),e>=h&&(e=h-1),this.psColors[d]=this.colorCells[e],this.psInverse[d]=c*c*b+g;break;case "squared":for(d=0;d<j;d++)c=d/j,e=Math.floor(c*c*h),e>=h&&(e=h-1),this.psColors[d]=this.colorCells[e],c=Math.sqrt(d/j),this.psInverse[d]=
c*b+g;break;case "asinh":for(d=0;d<j;d++)c=d/j,e=Math.floor(Math.asinh(10*c)/3*h),e>=h&&(e=h-1),this.psColors[d]=this.colorCells[e],e=Math.sinh(3*c)/10,this.psInverse[d]=e*b+g;break;case "sinh":for(d=0;d<j;d++)c=d/j,e=Math.floor(Math.sinh(3*c)/10*h),e>=h&&(e=h-1),this.psColors[d]=this.colorCells[e],e=Math.asinh(10*c)/3,this.psInverse[d]=e*b+g;break;default:a.log("unknown scale '"+this.params.scale+"'")}return this};a.Image.prototype.mkRGBImage=function(){var c,b,d,e,f,g,h,j,k,m,n,p,r,l,q,s,t,v,u,
w,y=null,x=null,B=null,F=!1;if(!this.rgb)return this;if(a.globalOpts.rgb.active&&(this===a.globalOpts.rgb.rim||this===a.globalOpts.rgb.gim||this===a.globalOpts.rgb.bim))F=!0,a.globalOpts.rgb.rim&&(y=a.globalOpts.rgb.rim),a.globalOpts.rgb.gim&&(x=a.globalOpts.rgb.gim),a.globalOpts.rgb.bim&&(B=a.globalOpts.rgb.bim);h=this.display.context;c=this.rgb;b=c.sect;if(this.MakeRGBImage&&"function"===typeof this.MakeRGBImage&&this.MakeRGBImage()||this.MakePrimaryImage&&"function"===typeof this.MakePrimaryImage&&
this.MakePrimaryImage())return this;if(this.rgbFile){f=b.width/b.zoom;g=b.height/b.zoom;d=b.x0;e=this.offscreen.canvas.height-1-(b.y0+g);e=this.offscreen.context.getImageData(d,e,f,g);if(1===b.zoom)c.img=e;else{c.img=h.createImageData(b.width,b.height);c=c.img;for(m=j=0;j<e.height;j++,m++){s=j*e.width;p=m*b.zoom;for(k=h=0;h<e.width;h++,k++){d=4*(s+h);n=k*b.zoom;for(r=0;r<b.zoom;r++){l=Math.floor(p+r);t=l*b.width;for(l=0;l<b.zoom;l++)q=Math.floor(n+l),q=4*(t+q),c.data[q]=e.data[d],c.data[q+1]=e.data[d+
1],c.data[q+2]=e.data[d+2],c.data[q+3]=e.data[d+3]}}}}return this}if(!c.img||c.img.width!==b.width||c.img.height!==b.height)c.img=h.createImageData(b.width,b.height);c=c.img;if(!this.psColors)return this;v=void 0!==this.params.opacity?255*this.params.opacity:void 0!==this.params.alpha?this.params.alpha:255;this.maskData&&(this.params.maskInvert?void 0!==this.params.opacity&&void 0!==this.params.maskOpacity?(e=255*this.params.opacity,f=255*this.params.maskOpacity):void 0!==this.params.alpha1&&void 0!==
this.params.alpha2?(e=this.params.alpha2,f=this.params.alpha1):(e=0,f=255):void 0!==this.params.opacity&&void 0!==this.params.maskOpacity?(e=255*this.params.maskOpacity,f=255*this.params.opacity):void 0!==this.params.alpha1&&void 0!==this.params.alpha2?(e=this.params.alpha1,f=this.params.alpha2):(e=255,f=0));j=b.y1-1;for(m=0;j>=b.y0;j--,m++){s=j*this.raw.width;p=m*b.zoom;h=b.x0;for(k=0;h<b.x1;h++,k++){if(F){if(g=y?y.colorData[s+h]:0,u=x?x.colorData[s+h]:0,w=B?B.colorData[s+h]:0,void 0===g||void 0===
u||void 0===w)return a.globalOpts.rgb.active=!1,a.error("RGB images are incompatible. Turning off RGB mode.","",!1),a.Image.prototype.mkRGBImage.call(this),this}else d=this.colorData[s+h];this.maskData&&(v=0<this.maskData[s+h]?e:f);n=k*b.zoom;for(r=0;r<b.zoom;r++){l=Math.floor(p+r);t=l*b.width;for(l=0;l<b.zoom;l++)q=Math.floor(n+l),q=4*(t+q),F?(c.data[q]=y?y.psColors[g][0]:0,c.data[q+1]=x?x.psColors[u][1]:0,c.data[q+2]=B?B.psColors[w][2]:0):(c.data[q]=this.psColors[d][0],c.data[q+1]=this.psColors[d][1],
c.data[q+2]=this.psColors[d][2]),c.data[q+3]=v}}}return this};a.Image.prototype.blendImage=function(c,b,d){var e=/normal|multiply|screen|overlay|darken|lighten|color-dodge|color-burn|hard-light|soft-light|difference|exclusion|hue|saturation|color|luminosity|clear|copy|source-over|destination-over|source-in|destination-in|source-out|destination-out|source-atop|destination-atop|xor|lighter/i;if(0===arguments.length)return this.blend;if(!0===c||!1===c)return this.blend.active=c,this.display.blendMode&&
this.displayImage(),this;if(a.notNull(c)||a.notNull(b))a.notNull(c)&&(e.test(c)||a.error("invalid composite/blend operation: "+c),this.blend.mode=c),a.notNull(b)&&(this.blend.opacity=b),a.notNull(d)&&(this.blend.active=d),this.display.blendMode&&this.blend.active&&this.displayImage();return this};a.noff=0;a.Image.prototype.putImage=function(c){var b,d,e=this.rgb;b=this.display;var f=b.context,g=function(c,d){var b,e;c.offscreenRGB||(e=document.createElement("canvas"),b=e.getContext("2d"),e.width=
d.width,e.height=d.height,a.ANTIALIAS||(b.imageSmoothingEnabled=!1,b.mozImageSmoothingEnabled=!1,b.webkitImageSmoothingEnabled=!1),b.putImageData(d,0,0),c.offscreenRGB={canvas:e,context:b});return c.offscreenRGB.canvas};c=c||{};this.ix=Math.floor((b.canvas.width-e.img.width)/2);this.iy=Math.floor((b.canvas.height-e.img.height)/2);"reproject"===this.rawDataLayer()&&(c.wcsim&&this.params.wcsalign)&&(b=c.wcsim.logicalToDisplayPos({x:c.wcsim.raw.header.CRPIX1,y:c.wcsim.raw.header.CRPIX2}),d=this.logicalToDisplayPos({x:this.raw.header.CRPIX1,
y:this.raw.header.CRPIX2}),this.wcsix=b.x-d.x,this.wcsiy=b.y-d.y);this.params.wcsalign&&(this.ix+=this.wcsix*this.rgb.sect.zoom,this.iy+=this.wcsiy*this.rgb.sect.zoom);a.notNull(c.opacity)||a.notNull(c.blend)?(f.save(),void 0!==c.opacity&&(f.globalAlpha=c.opacity),void 0!==c.blend&&(f.globalCompositeOperation=c.blend),f.drawImage(g(this,e.img),this.ix,this.iy),f.restore()):f.putImageData(e.img,this.ix,this.iy)};a.Image.prototype.displayImage=function(c,b){var d,e,f,g;g=0;var h=[],j={};if(!1===c)return this.displayMode=
!1,this;!0===c&&(this.displayMode=!0,c="all");if(!this.displayMode)return this;"object"===typeof c&&(b=c,c=null);c?"all"===c?(c="colors,scaled,rgb,display,plugins",j.notify=!0):"rgbonly"===c?(c="rgb,nodisplay",j.notify=!0):"display"===c&&(j.notify=!0):c="rgb";c.split(",").forEach(function(a){a=a.trim();j[a]=!0;switch(a){case "colors":j.scaled=!0;j.rgb=!0;break;case "scaled":j.rgb=!0}});j.display=!0;j.plugins=!0;this.rgbFile&&(c.colors=!1,c.scaled=!1);b=b||{};if(this.display.blendMode)for(d=0;d<a.images.length;d++)e=
a.images[d],e.display===this.display&&e.blend.active&&(h.push(e),g++);j.colors&&(this.mkColorData(),this.offscreenRGB=null);j.scaled&&(this.mkColorCells(),this.mkScaledCells(),this.offscreenRGB=null);if(j.rgb&&(this.mkRGBImage(),this.offscreenRGB=null,g))for(d=h.length-1;0<=d;d--)e=h[d],e.mkRGBImage(),e.offscreenRGB=null;if(j.nodisplay)return this;if(j.display){this.display.context.clear();if(g)for(d=h.length-1;0<=d;d--)e=h[d],g={blend:e.blend.mode,opacity:e.blend.opacity},e.putImage(g),e===this&&
(e.displayShapeLayers(),j.notify&&e.notifyHelper());else this.putImage(b),this.displayShapeLayers(),j.notify&&this.notifyHelper();this.display.image=this}if(j.plugins)for(f in this.display.pluginInstances)if(this.display.pluginInstances.hasOwnProperty(f)&&(d=this.display.pluginInstances[f],e=d.plugin.opts,d.isActive("onimagedisplay")&&("JS9Panner"===f||j.display)))try{e.onimagedisplay.call(d,this)}catch(k){d.errLog("onimagedisplay",k)}return this};a.Image.prototype.refreshImage=function(c,b){var d,
e,f,g,h,j;b=b||{};b.rawid=b.rawid||a.RAWID0;"function"===typeof b&&(b={onrefresh:b});!b.onrefresh&&a.imageOpts.onrefresh&&(b.onrefresh=a.imageOpts.onrefresh);d=this.rgb.sect.xcen;e=this.rgb.sect.ycen;h=this.rgb.sect.zoom;f=this.raw.width;g=this.raw.height;this.binning.obin=this.binning.bin;this.mkRawDataFromHDU(c,b);this.raw.width===f&&this.raw.height===g?this.mkSection(d,e,h):(this.mkSection(),this.mkSection(h));this.displayImage("colors",b);this.refreshLayers();this.updateShapes("regions","all",
"binning");if(b.onrefresh)try{a.xeqByName(b.onrefresh,window,this)}catch(k){a.error("in image refresh callback",k)}for(j in this.display.pluginInstances)if(this.display.pluginInstances.hasOwnProperty(j)&&(d=this.display.pluginInstances[j],e=d.plugin.opts,d.isActive("onimagerefresh")))try{e.onimagerefresh.call(d,this)}catch(m){d.errLog("onimagerefresh",m)}};a.Image.prototype.toArray=function(){var c,b,d,e,f,g,h,j,k,m;k=this.raw.data.buffer;g=a.raw2FITS(this.raw);h=2880-g.length%2880;2880===h&&(h=0);
for(c=0;c<h;c++)g+=" ";h=2880-k.byteLength%2880;2880===h&&(h=0);c=new ArrayBuffer(g.length+k.byteLength+h);j=new Uint8Array(c);for(c=0;c<g.length;c++)j[c]=g.charCodeAt(c);if(0<(new Int8Array((new Int16Array([1])).buffer))[0]){f=g.length;e=Math.abs(this.raw.bitpix)/8;m=new Uint8Array(k);for(c=0;c<m.byteLength;c+=e){b=c+e-1;for(d=0;d<e;b--,d++)j[f++]=m[b]}}else j.set(new Uint8Array(k),g.length);f=g.length+k.byteLength;for(c=0;c<h;c++)j[f++]=0;return j};a.Image.prototype.getPan=function(){return{x:(this.rgb.sect.x0+
this.rgb.sect.x1)/2+1,y:(this.rgb.sect.y0+this.rgb.sect.y1)/2+1}};a.Image.prototype.setPan=function(c,b){var d,e,f,g,h,j=this.raw.width/2,k=this.raw.height/2;0===arguments.length&&(c=j,b=k);this.mkSection(c,b);if(this.display.blendMode)for(d=0;d<a.images.length;d++)h=a.images[d],h!==this&&(h.display===this.display&&h.blend.active)&&(f=h.raw.width/2,g=h.raw.height/2,0!==arguments.length&&(f-=j-c,g-=k-b),a.Image.prototype.mkSection.call(h,f,g));this.displayImage("rgb");for(e in this.layers)this.layers.hasOwnProperty(e)&&
this.layers[e].show&&this.layers[e].opts.panzoom&&this.refreshShapes(e);return this};a.Image.prototype.getZoom=function(){return this.rgb.sect.zoom};a.Image.prototype.parseZoom=function(a){var b;b=this.rgb.sect.zoom;switch(typeof a){case "string":switch(a.charAt(0)){case "*":case "x":case "X":a=b*parseFloat(a.slice(1));break;case "/":a=b/parseFloat(a.slice(1));break;case "I":case "i":a=2*b;break;case "O":case "o":a=b/2;break;case "T":case "t":a=Math.min(this.display.width,this.display.height)/Math.max(this.raw.width,
this.raw.height);break;default:a=parseFloat(a)}break;case "number":break;default:return}return a};a.Image.prototype.setZoom=function(c){var b,d,e;if(b=this.parseZoom(c)){this.mkSection(b);if(this.display.blendMode)for(c=0;c<a.images.length;c++)e=a.images[c],e!==this&&(e.display===this.display&&e.blend.active)&&a.Image.prototype.mkSection.call(e,b);this.displayImage("rgb");for(d in this.layers)this.layers.hasOwnProperty(d)&&this.layers[d].show&&this.layers[d].opts.panzoom&&this.refreshShapes(d);return this}};
a.Image.prototype.refreshLayers=function(){this.setZoom(this.getZoom())};a.Image.prototype.imageToLogicalPos=function(a,b){var d,e=a.x,f=a.y,g="image";b=b||this.params.lcs||"image";switch(b){case "physical":this.lcs.physical&&(g=b,d=this.lcs.physical.reverse);break;case "detector":this.lcs.detector&&(g=b,d=this.lcs.detector.reverse);break;case "amplifier":this.lcs.amplifier&&(g=b,d=this.lcs.amplifier.reverse)}d&&(e=a.x*d[0][0]+a.y*d[1][0]+d[2][0],f=a.x*d[0][1]+a.y*d[1][1]+d[2][1]);return{x:e,y:f,
sys:g}};a.Image.prototype.logicalToImagePos=function(a,b){var d,e={x:a.x,y:a.y};b=b||this.params.lcs||"image";switch(b){case "physical":this.lcs.physical&&(d=this.lcs.physical.forward);break;case "detector":this.lcs.detector&&(d=this.lcs.detector.forward);break;case "amplifier":this.lcs.amplifier&&(d=this.lcs.amplifier.forward)}d&&(e.x=a.x*d[0][0]+a.y*d[1][0]+d[2][0],e.y=a.x*d[0][1]+a.y*d[1][1]+d[2][1]);return e};a.Image.prototype.displayToImagePos=function(a){var b=this.rgb,d=this.rgb.sect,e={};
1>=d.zoom?(e.x=(a.x-this.ix)/d.zoom+d.x0+1,e.y=(b.img.height-1-(a.y-this.iy))/d.zoom+d.y0+1):(e.x=(a.x-this.ix)/d.zoom+d.x0+1-0.5,e.y=(b.img.height-1-(a.y-this.iy))/d.zoom+d.y0+1-0.5);return e};a.Image.prototype.imageToDisplayPos=function(a){var b=this.rgb,d=this.rgb.sect,e={};1>=d.zoom?(e.x=(a.x-1-d.x0)*d.zoom+this.ix,e.y=(d.y0-(a.y-1))*d.zoom+(b.img.height-1)+this.iy):(e.x=(a.x-1+0.5-d.x0)*d.zoom+this.ix,e.y=(d.y0-(a.y-1+0.5))*d.zoom+(b.img.height-1)+this.iy);return e};a.Image.prototype.logicalToDisplayPos=
function(a){return this.imageToDisplayPos(this.logicalToImagePos(a))};a.Image.prototype.displayToLogicalPos=function(a){return this.imageToLogicalPos(this.displayToImagePos(a))};a.Image.prototype.getWCSSys=function(){if(this.params.wcssys)return this.params.wcssys};a.Image.prototype.setWCSSys=function(c){if("image"===c)this.params.wcssys="image",this.params.wcsunits="pixels";else if("physical"===c)this.params.wcssys="physical",this.params.wcsunits="pixels";else if(this.wcs&&0<this.wcs){"native"===
c&&(c=this.params.wcssys0);if(c=a.wcssys(this.wcs,c))this.params.wcssys=c.trim(),c="pixels"===this.params.wcsunits?a.imageOpts.wcsunits:this.params.wcsunits,this.setWCSUnits(c),this.updateShapes("regions","all","update");return this}};a.Image.prototype.getWCSUnits=function(){return this.params.wcsunits?this.params.wcsunits:"pixels"};a.Image.prototype.setWCSUnits=function(c){var b;if("pixels"===c)this.params.wcssys="physical",this.params.wcsunits="pixels";else{if(this.wcs&&0<this.wcs){if("image"===
this.params.wcssys||"physical"===this.params.wcssys)b=a.imageOpts.wcssys,this.setWCSSys(this.wcs,b);if(c=a.wcsunits(this.wcs,c))this.params.wcsunits=c.trim(),this.updateShapes("regions","all","update")}return this}};a.Image.prototype.notifyHelper=function(){var c,b=this;a.helper.connected&&this.file!==a.ANON&&a.helper.send("image",{image:this.file},function(d){var e,f;"object"===typeof d?(e=d.stdout,d.stderr&&1<a.DEBUG&&a.log(d.stderr)):e=d;if(e){e=e.trim().split(/ +/);if((d=a.lookupImage(e[0],b.display.id||
a.DEFID))&&!d.fitsFile)if(e=e[1],"?"!==e){if(a.analOpts.dataDir)f=e.lastIndexOf("/")+1,d.fitsFile=a.analOpts.dataDir+"/"+e.slice(f);else{d.fitsFile=e;if(0>d.fitsFile.indexOf("/")&&(c=d.file.match(/.*\//)))d.fitsFile=c+d.fitsFile;a.analOpts.prependJS9Dir&&(d.fitsFile&&"/"!==d.fitsFile.charAt(0)&&(d.fitsFile="${JS9_DIR}/"+d.fitsFile),d.parentFile&&"/"!==d.parentFile.charAt(0)&&(d.parentFile="${JS9_DIR}/"+d.parentFile))}1<a.DEBUG&&a.log("JS9 fitsFile: %s %s",d.file,d.fitsFile)}b.queried||(b.queryHelper("all"),
b.queried=!0)}});return this};a.Image.prototype.queryHelper=function(c){var b=this;c=c||"all";if(a.helper.connected&&("all"===c||"getAnalysis"===c))this.analysisPackages||a.helper.send("getAnalysis",{fits:this.fitsFile},function(c){if(c)try{b.analysisPackages=JSON.parse(c)}catch(e){a.log("can't get analysis",e)}});return this};a.Image.prototype.expandMacro=function(c,b){var d,e,f=this;if(c)return d=c.replace(/\$([a-zA-Z0-9_()]+)/g,function(c,d){var j,k;j=function(a,c){var d=a.params.wcssys;if(c)switch(c){case "wcs":if("physical"===
d||"image"===d)a.params.wcssys=a.params.wcssys0;break;case "physical":case "image":a.params.wcssys=c}return d};var m=d.split("(");m[1]&&(m[1]=m[1].replace(/\)$/,""));switch(m[0]){case "id":k=f.display.divjq.attr("id");break;case "image":case "png":k=f.id;break;case "filename":"parent"===m[1]&&f.parentFile?k=f.parentFile:f.fitsFile?(k=f.fitsFile,"table"===f.imtab&&f.raw.hdu.table.filter&&(k+="[EVENTS]["+f.raw.hdu.table.filter+"]")):a.error("no FITS file for "+f.id);break;case "fits":f.fitsFile||a.error("no FITS file for "+
f.id);k=f.fitsFile;"table"===f.imtab&&f.raw.hdu.table.filter&&(k+="[EVENTS]["+f.raw.hdu.table.filter+"]");break;case "parent":f.parentFile||a.error("no parent FITS file for "+f.id);k=f.parentFile;break;case "ext":f.fitsFile?k=f.fitsFile.match(/\[.*\]/):a.error("no FITS file for "+f.id);break;case "sregions":j=j(f,m[1]);k=f.listRegions("source",0).replace(/\s+/g,"");j&&(f.params.wcssys=j);break;case "bregions":j=j(f,m[1]);k=f.listRegions("background",0).replace(/\s+/g,"");j&&(f.params.wcssys=j);break;
case "regions":j=j(f,m[1]);k=f.listRegions("all",0).replace(/\s+/g,"");j&&(f.params.wcssys=j);break;default:if(b){e=b.length;for(j=0;j<e;j++)if(b[j].name===d){k=b[j].value;break}k||(k="false")}k||(k=c)}return k})};a.Image.prototype.lookupAnalysis=function(a){var b,d,e,f=null;if(this.analysisPackages){for(d=0;d<this.analysisPackages.length&&!f;d++){e=this.analysisPackages[d];for(b=0;b<e.length;b++){f=e[b];if(f.xclass&&f.xclass+":"+f.name===a)break;f=null}}if(f)return f;for(d=0;d<this.analysisPackages.length&&
!f;d++){e=this.analysisPackages[d];for(b=0;b<e.length;b++){f=e[b];if(f.name===a)break;f=null}}}return f};a.Image.prototype.runAnalysis=function(c,b,d){var e,f,g=this,h={};if(a.helper.connected&&this.analysisPackages)if(e=this.lookupAnalysis(c)){e.action&&(h.cmd=this.expandMacro(e.action,b));if(e.keys){h.keys={};for(c=0;c<e.keys.length;c++)h.keys[e.keys[c]]=this.expandMacro("$"+e.keys[c],b)}h.id=this.expandMacro("$id");h.image=this.file;h.fits=this.fitsFile;h.rtype=e.rtype;switch(a.helper.type){case "nodejs":case "socket.io":b=
e.xclass?e.xclass+":"+e.name:e.name;break;default:b="runAnalysis"}a.waiting(!0,this.display.divjq[0]);a.helper.send(b,h,function(c){var b;a.waiting(!1);b="object"===typeof c?c:0<=c.search(a.analOpts.epattern)?{stderr:c}:{stdout:c};b.errcode=b.errcode||0;if(d)d(b.stdout,b.stderr,b.errcode,e);else{if(b.errcode||b.stderr)c=b.stderr?b.stderr:sprintf("ERROR: while executing %s [%s]",e.name,b.errcode),0<=c.search(/WARNING/i)?a.log(c):a.error(c,a.analOpts.epattern);switch(e.rtype){case "text":case void 0:g.displayAnalysis("text",
b.stdout);break;case "plot":g.displayAnalysis("plot",b.stdout);break;case "alert":b.stdout&&alert(b.stdout);break;case "fits":case "png":f=b.stdout.trim();"/"!==f.charAt(0)&&(f=a.InstallDir(f));a.Load(f,{proxyFile:f},{display:g.display});break;case "none":break;default:a.error("unknown analysis result type: "+e.rtype)}}})}else a.error("could not find analysis task: "+c)};a.Image.prototype.displayAnalysis=function(c,b,d,e){var f,g,h,j=a.lightOpts[a.LIGHTWIN];!d&&this&&(d=this.fitsFile||this.id,d=d.split("/").reverse()[0],
d="AnalysisResults: "+d);f="Analysis_"+a.uniqueID();switch(c){case "text":g="<div class='JS9Analysis'></div>";b&&(g+="<pre class='JS9AnalysisText'>"+b+"</pre>");g=a.lightWin(f,"inline",g+"</div>",d,e||j.textWin);break;case "plot":try{h=JSON.parse(b)}catch(k){a.error("can't plot return data: "+b,k)}if(!h)return;g=sprintf("<div id='%s' class='JS9Analysis'><div id='%sPlot' class='JS9Plot' ></div></div>",f,f);g=a.lightWin(f,"inline",g,d,e||j.plotWin);b=$("#"+f+" #"+f+"Plot");if(h.data){e=this?this.params.plotOpts:
a.plotOpts;try{$.plot(b,[h],e)}catch(m){a.error("can't plot data",m)}}break;case "params":g=a.allinone?a.lightWin(f,"inline",b,d,e||j.paramWin):a.lightWin(f,"ajax",b,d,e||j.paramWin);break;case "textline":g=a.allinone?a.lightWin(f,"inline",b,d,e||j.dpathWin):a.lightWin(f,"ajax",b,d,e||j.dpathWin)}return g};a.Image.prototype.loadAuxFile=function(c,b){var d=this,e,f,g,h,j=a.auxFiles.length,k=[],m=function(){d.aux[f.name]=f;a.Image.prototype.mkOffScreenCanvas.call(h);a.Image.prototype.mkRawDataFromPNG.call(h);
if(b)try{a.xeqByName(b,window,d,f)}catch(c){a.error("in aux mask onload callback",c)}a.DEBUG&&a.log("JS9 %s: %s dims(%d,%d) min/max(%d,%d)",h.type,h.file,h.raw.width,h.raw.height,h.raw.dmin,h.raw.dmax)},n=function(c){d.aux[f.name]=f;f.regions=c;if(b)try{a.xeqByName(b,window,d,f)}catch(e){a.error("in aux region onload callback",e)}},p=function(c){d.aux[f.name]=f;f.text=c;if(b)try{a.xeqByName(b,window,d,f)}catch(e){a.error("in aux text onload callback",e)}},r=function(c,d){a.log(sprintf("could not load auxiliary file: %s [%s]",
f.url,d))};if(c&&j){for(e=0;e<j;e++)f=a.auxFiles[e],f.image&&!f.regex&&(f.regex=RegExp(f.image));g=c.split(":");for(e=0;e<j;e++)if(f=a.auxFiles[e],g[0]===f.name&&this.id.match(f.regex)&&(1===g.length||g[1]===f.type))switch(f.type){case "mask":if(f.im){if(this.aux[f.name]=f,b)try{a.xeqByName(b,window,this,f)}catch(l){a.error("in aux mask callback",l)}}else k.push(f);break;case "regions":if(f.layer){if(this.aux[f.name]=f,b)try{a.xeqByName(b,window,this,f)}catch(q){a.error("in aux regions callback",
q)}}else k.push(f);break;case "text":if(f.text){if(this.aux[f.name]=f,b)try{a.xeqByName(b,window,this,f)}catch(s){a.error("in aux text callback",s)}}else k.push(f)}for(e=0;e<k.length;e++)switch(f=k[e],f.type){case "mask":f.im={};h=f.im;h.type="aux";h.file=f.url;h.id=h.file.split("/").reverse()[0];h.params={};h.params.scalemin=Number.Nan;h.params.scalemax=Number.Nan;h.png={};h.png.image=new Image;$(h.png.image).on("load",m).on("error",r);h.png.image.src=a.InstallDir(f.url);break;case "regions":f.layer=
this.display.newShapeLayer(c,a.Regions.opts);g=a.InstallDir(f.url);$.ajax({url:g,cache:!1,dataType:"json",success:n,error:r});break;case "text":g=a.InstallDir(f.url),$.ajax({url:g,cache:!1,dataType:"text",success:p,error:r})}}};a.Image.prototype.saveFITS=function(c){var b;window.hasOwnProperty("saveAs")?(c=c||"js9.fits",b=this.toArray(),b=new Blob([b],{type:"application/octet-binary"}),saveAs(b,c)):a.error("no saveAs function available to save FITS file");return c};a.Image.prototype.saveIMG=function(c,
b,d){var e,f,g;if(window.hasOwnProperty("saveAs")){c=c||"js9.png";f=document.createElement("canvas");f.setAttribute("width",this.display.width);f.setAttribute("height",this.display.height);g=f.getContext("2d");g.drawImage(this.display.canvas,0,0);for(e in this.layers)this.layers.hasOwnProperty(e)&&"main"===this.layers[e].dlayer.dtype&&this.layers[e].show&&g.drawImage(this.layers[e].dlayer.canvasjq[0],0,0);if(void 0!==d&&(0>d||1<d))d=0.95;f.toBlob(function(a){saveAs(a,c)},b||"image/png",d)}else a.error("no saveAs function available for saving image");
return c};a.Image.prototype.savePNG=function(a){this.saveIMG(a||"js9.png","image/png")};a.Image.prototype.saveJPEG=function(a,b){this.saveIMG(a||"js9.jpeg","image/jpeg",b)};a.Image.prototype.updateValpos=function(c,b){var d,e,f,g,h;d=null;f=a.floatPrecision(this.params.scalemin,this.params.scalemax);e=function(a,c){return a.toFixed(c||3)};var j=function(a,c){var d="",b="";c=c||3;0>a&&(a=Math.abs(a),b="-");for(d+=a;d.length<c;)d="0"+d;return b+d};if(this.params.valpos){void 0===b&&(b=!0);if(this.valpos)return b&&
this.displayMessage("info",this.valpos),this.valpos;g={x:c.x,y:c.y,sys:"image"};h="image"===this.params.wcssys?g:this.imageToLogicalPos(c);d=this.raw.data[Math.floor(c.y-0.5)*this.raw.width+Math.floor(c.x-0.5)];switch(this.raw.bitpix){case 8:case 16:case -16:case 32:f=j(d);break;case -32:case -64:f=a.floatFormattedString(d,f,0);break;default:f=j(d)}e="value("+f+") "+h.sys+"("+e(h.x,3)+", "+e(h.y,3)+")";d={ix:g.x,iy:g.y,isys:"image",px:h.x,py:h.y,psys:h.sys,ra:"",dec:"",wcssys:"",val:d,val3:f,vstr:e,
id:this.id,file:this.file,object:this.object};0<this.wcs&&("image"!==this.params.wcssys&&"physical"!==this.params.wcssys)&&(g=a.pix2wcs(this.wcs,c.x,c.y).trim().split(/\s+/),e=e+" "+g[2]+"("+g[0]+", "+g[1]+")",d.ra=g[0],d.dec=g[1],d.wcssys=g[2],d.vstr=e);b&&this.displayMessage("info",d)}return d};a.Image.prototype.getColormap=function(){if(this.cmapObj)return{colormap:this.cmapObj.name,contrast:this.params.contrast,bias:this.params.bias}};a.Image.prototype.setColormap=function(c,b,d){switch(arguments.length){case 1:case 3:switch(c){case "rgb":a.globalOpts.rgb.active=
!a.globalOpts.rgb.active;break;case "invert":this.params.invert=!this.params.invert;break;case "reset":this.params.invert=a.imageOpts.invert;this.params.contrast=a.imageOpts.contrast;this.params.bias=a.imageOpts.bias;break;default:if(this.cmapObj)switch(this.cmapObj.name){case "red":a.globalOpts.rgb.rim=null;break;case "green":a.globalOpts.rgb.gim=null;break;case "blue":a.globalOpts.rgb.bim=null}this.cmapObj=a.lookupColormap(c);this.params.colormap=this.cmapObj.name;switch(c){case "red":a.globalOpts.rgb.rim=
this;break;case "green":a.globalOpts.rgb.gim=this;break;case "blue":a.globalOpts.rgb.bim=this}}3===arguments.length&&(isNaN(b)||(this.params.contrast=b),isNaN(d)||(this.params.bias=d));break;case 2:isNaN(c)||(this.params.contrast=c),isNaN(b)||(this.params.bias=b)}this.displayImage("colors");return this};a.Image.prototype.getScale=function(){if(this.params.scale)return{scale:this.params.scale,scalemin:this.params.scalemin,scalemax:this.params.scalemax}};a.Image.prototype.setScale=function(c,b,d){var e=
this,f=function(c){0<=a.scales.indexOf(c)?e.params.scale=c:a.error("unknown scale: "+c)};if(arguments.length){switch(arguments.length){case 1:f(c);break;case 2:this.params.scalemin=parseInt(c,10);this.params.scalemax=parseInt(b,10);this.mkColorData();break;default:f(c),this.params.scalemin=parseInt(b,10),this.params.scalemax=parseInt(d,10),this.mkColorData()}this.displayImage("scaled")}return this};a.Image.prototype.zscale=function(c){var b,d,e;if(!a.zscale||!this.raw||!this.raw.data)return this;
b=this.raw.data;d=b.length*b.BYTES_PER_ELEMENT;try{e=a.vmalloc(d)}catch(f){a.error("image too large for zscale malloc: "+d,f)}try{a.vmemcpy(new Uint8Array(b.buffer),e)}catch(g){a.error("can't copy image to zscale heap: "+d,g)}b=a.zscale(e,this.raw.width,this.raw.height,this.raw.bitpix,this.params.zscalecontrast,this.params.zscalesamples,this.params.zscaleline);a.vfree(e);e=b.trim().split(" ");this.params.z1=parseFloat(e[0]);this.params.z2=parseFloat(e[1]);c&&(this.params.scalemin=this.params.z1,this.params.scalemax=
this.params.z2);return this};a.Image.prototype.rawDataLayer=function(c,b){var d,e,f,g,h,j;if(!arguments.length)return this.raw.id;if("string"===typeof c)if("function"===typeof b)c={rawid:c};else{for(d=0;d<this.raws.length;d++)if(c===this.raws[d].id){if("remove"===b)return"raw0"===c&&a.error("can't remove raw0 data layer"),this.raw=this.raws[d].current0&&this.raws[d].current0.id?this.raws[d].current0:this.raws[0],this.raws.splice(d,1),this.displayImage("all",c),!0;this.raw=this.raws[d];this.mkSection();
this.displayImage("all",c);return!0}return!1}if("function"!==typeof b)return!1;c=c||{};g=c.rawid||a.RAWIDX;void 0===c.oraw&&(c.oraw="current0");if("current"===c.oraw)e=this.raw;else if("current0"===c.oraw){for(d=0;d<this.raws.length;d++)if(g===this.raws[d].id){e=this.raws[d].current0;break}e||(e=this.raw)}else for(d=0;d<this.raws.length;d++)if(c.oraw===this.raws[d].id){e=this.raws[d];break}e||(e=this.raws[0]);h=-1;for(d=0;d<this.raws.length;d++)if(g===this.raws[d].id){f=this.raws[d];h=d;break}if(0>
h||c.alwaysCopy){f=$.extend(!0,{},e);f.current0||(f.current0=e);if(c.bitpix){switch(c.bitpix){case 8:f.data=new Uint8Array(e.height*e.width);break;case 16:f.data=new Int16Array(e.height*e.width);break;case -16:f.data=new Uint16Array(e.height*e.width);break;case 32:f.data=new Int32Array(e.height*e.width);break;case -32:f.data=new Float32Array(e.height*e.width);break;case -64:f.data=new Float64Array(e.height*e.width)}j=f.width*f.height;for(d=0;d<j;d++)f.data[d]=e.data[d];f.bitpix=c.bitpix}else switch(e.bitpix){case 8:f.data=
new Uint8Array(e.data);break;case 16:f.data=new Int16Array(e.data);break;case -16:f.data=new Uint16Array(e.data);break;case 32:f.data=new Int32Array(e.data);break;case -32:f.data=new Float32Array(e.data);break;case -64:f.data=new Float64Array(e.data)}f.id=g;f.from=c.from||f.from||"func"}b.call(this,e,f,c)&&(0<=h?this.raws[h]=f:this.raws.push(f),this.raw=f,this.displayImage("all",c));return!0};a.Image.prototype.gaussBlurData=function(c){var b={};void 0===c&&a.error("missing sigma value for gaussBlurData");
b=b||{};b.bitpix=-64===this.raw.bitpix?-64:-32;b.oraw="current0";b.alwaysCopy=!0;b.rawid="gaussBlur";b.sigma=c;this.rawDataLayer(b,function(d,b){var f;switch(b.bitpix){case -32:f=new Float32Array(b.data);break;case -64:f=new Float64Array(b.data);break;default:a.error("invalid temp bitpix for gaussBlur: "+b.bitpix)}gaussBlur(f,b.data,b.width,b.height,c);return!0})};a.Image.prototype.shiftData=function(c,b,d){(void 0===c||void 0===b)&&a.error("missing translation value(s) for shiftData");d=d||{};d.rawid=
"shift";d.x=c;d.y=b;this.rawDataLayer(d,function(a,c,d){var b,j,k,m,n=a.data.BYTES_PER_ELEMENT;void 0===c.xoff&&(c.xoff=0);void 0===c.yoff&&(c.yoff=0);c.xoff+=d.x;c.yoff+=d.y;if(!d.fill||"clear"===d.fill)if("function"===typeof c.data.fill)c.data.fill(0);else for(d=0;d<c.data.length;d++)c.data[d]=0;for(d=0;d<a.height;d++)if(k=d+c.yoff,!(0>k||k>=a.height)){b=0;j=b+c.xoff;m=a.width;0>j&&(b-=j,m+=j,j=0);j+m>a.width&&(m-=j+m-a.width);if(0>=m)return!1;b=(d*a.width+b)*n;b=new Uint8Array(a.data.buffer,b,
m*n);j=(k*a.width+j)*n;m=new Uint8Array(c.data.buffer,j,m*n);m.set(b)}return!0})};a.Image.prototype.reprojectData=function(c,b){var d=this,e={},f=!1,g,h,j,k,m,n,p,r,l;l=/NAXIS|NAXIS[1-4]|AMDX|AMDY|CD[1-2]_[1-2]|CDELT[1-4]|CNPIX[1-4]|CO1_[1-9][0-9]|CO2_[1-9][0-9]|CROTA[1-4]|CRPIX[1-4]|CRVAL[1-4]|CTYPE[1-4]|CUNIT[1-4]|DATE|DATE_OBS|DC-FLAG|DEC|DETSEC|DETSIZE|EPOCH|EQUINOX|EQUINOX[a-z]|IMAGEH|IMAGEW|LATPOLE|LONGPOLE|MJD-OBS|PC00[1-4]00[1-4]|PC[1-4]_[1-4]|PIXSCALE|PIXSCAL[1-2]|PLTDECH|PLTDECM|PLTDECS|PLTDECSN|PLTRAH|PLTRAM|PLTRAS|PPO|PROJP[1-9]|PROJR0|PV[1-3]_[1-3]|PV[1-4]_[1-4]|RA|RADECSYS|SECPIX|SECPIX|SECPIX[1-2]|UT|UTMID|VELOCITY|VSOURCE|WCSAXES|WCSDEP|WCSDIM|WCSNAME|XPIXSIZE|YPIXSIZE|ZSOURCE|LTM|LTV/;
var q=function(c){d.refreshImage(c,n);a.waiting(!1)};if(this.wcs&&c&&a.reproject&&a.fits.handleFITSFile){b=b||{};a.waiting(!0,this.display.divjq[0]);"string"===typeof c&&((h=a.getImage(c))?c=h:a.error("unknown WCS for reproject: "+c));h=$.extend(!0,{},this.raw.header);for(r in h)h.hasOwnProperty(r)&&l.test(r)&&delete h[r];c.raw&&c.raw.header?j=c.raw.header:c.BITPIX&&c.NAXIS1&&c.NAXIS2?j=c:a.error("invalid wcs object input to reproject()");for(r in j)j.hasOwnProperty(r)&&l.test(r)&&(e[r]=j[r]);e=$.extend(!0,
{},h,e);(!e.NAXIS||!e.NAXIS1||!e.NAXIS2)&&a.error("invalid FITS image header");e.NAXIS1*e.NAXIS2>a.REPROJDIM*a.REPROJDIM&&a.error("for now, the maximum image size for reprojection is approximately "+a.REPROJDIM+" * "+a.REPROJDIM);e=a.raw2FITS(e,!0);g="wcs_"+a.uniqueID()+".txt";a.vfile(g,e);this.raw.hdu&&this.raw.hdu.vfile?k=this.raw.hdu.vfile:(e=this.toArray(),k=this.id.replace(/\.png$/,"_png.fits"),a.vfile(k,e));e=this.id.replace(/\.png$/,".fits").replace(/\.gz$/,"");m="reprojected_"+a.uniqueID()+
"_"+e;"table"===this.imtab&&(l=this.raw.hdu.table,e=Math.floor(l.cx-(l.nx+1)/2+1),j=Math.floor(l.cx+l.nx/2),r=Math.floor(l.cy-(l.ny+1)/2+1),l=Math.floor(l.cy+l.ny/2),e=sprintf("[EVENTS][bin X=%s:%s,Y=%s:%s]",e,j,r,l),k+=e);window.setTimeout(function(){var d,e,h,j;try{d=m.lastIndexOf("."),0<=d&&(e=m.substring(0,d)+"_area"+m.substring(d)),j=b.cmdswitches||"",p=a.reproject(k,m,g,j),1<a.DEBUG&&a.log("reproject: %s %s %s -> %s",k,m,g,p),a.vunlink(e),a.vunlink(g),0>p.search(/\[struct stat="OK"/)&&(f=!0,
(h=p.match(/msg="([^"]*)"/))&&h[1]?a.error(h[1]+" (from mProjectPP)"):a.error(p))}catch(l){if(f)return;a.vunlink(e);a.vunlink(g);p?a.error(p):a.error("WCS reproject failed",l)}n=$.extend(!0,{},b||{},a.fits.options);n.rawid=n.rawid||"reproject";n.wcsim=c;try{a.fits.handleFITSFile(m,n,q)}catch(r){a.error("can't process reprojected FITS file",r)}},a.SPINOUT)}};a.Image.prototype.filterRGBImage=function(c){var b,d=[],e=Array.prototype.slice.call(arguments);if(!c){for(b in a.ImageFilters)a.ImageFilters.hasOwnProperty(b)&&
d.push(b);return d}"reset"!==c&&!a.ImageFilters[c]&&a.error("JS9 image filter '"+c+"' not available");if("reset"===c)return this.setColormap("reset"),this;e.shift();e.unshift(this.rgb.img);try{a.ImageFilters[c].apply(null,e)}catch(f){a.error("JS9 image filter '"+c+"' failed",f)}this.displayImage("display");return this};a.Colormap=function(c,b,d,e){this.name=c;switch(arguments.length){case 2:this.type="lut";this.colors=b;break;case 4:this.type="sao";this.vertices=[b,d,e];break;default:a.error("colormap requires a colormap name and 1 or 3 array args")}a.colormaps.push(this);
1<a.DEBUG&&a.log("JS9 colormap: %s",this.name)};a.Colormap.prototype.mkColorCell=function(c){var b,d=a.COLORSIZE,e=[0,0,0];switch(this.type){case "sao":var f,g;c/=d;for(f=0;3>f;f++){g=this.vertices[f];b=g.length;for(d=0;d<b&&!(g[d][0]>c);d++);d=0===d?g[0][1]:d===b?g[b-1][1]:(b=(g[d][1]-g[d-1][1])/(g[d][0]-g[d-1][0]))?b*(c-g[d-1][0])+g[d-1][1]:g[d][1];e[f]=255*d}break;case "lut":f=this.colors.length;c=Math.floor(c*f/d);0>c?(e[0]=255*this.colors[0][0],e[1]=255*this.colors[0][1],e[2]=255*this.colors[0][2]):
c<f?(e[0]=255*this.colors[c][0],e[1]=255*this.colors[c][1],e[2]=255*this.colors[c][2]):(e[0]=255*this.colors[f-1][0],e[1]=255*this.colors[f-1][1],e[2]=255*this.colors[f-1][2]);break;default:a.error("unknown colormap type")}return e};a.Display=function(c){var b=this;this.divjq=c instanceof jQuery?c:"object"===typeof c?$(c):$("#"+c);this.divjq.attr("id")||this.divjq.attr("id",a.DEFID);this.id=this.divjq.attr("id");this.divjq.addClass("JS9");this.width=this.divjq.attr("data-width");this.width||(this.width=
a.WIDTH);this.divjq.css("width",this.width);this.width=parseInt(this.divjq.css("width"),10);this.height=this.divjq.attr("data-height");this.height||(this.height=a.HEIGHT);this.divjq.css("height",this.height);this.height=parseInt(this.divjq.css("height"),10);this.canvas=document.createElement("canvas");this.canvasjq=$(this.canvas).addClass("JS9Image").attr("id",this.id+"Image").attr("width",this.width).attr("height",this.height).css("z-index",a.ZINDEX);this.displayConjq=$("<div>").addClass("JS9Container").css("z-index",
a.ZINDEX).attr("tabindex","0").append(this.canvasjq).appendTo(this.divjq);a.globalOpts.resizeHandle&&window.hasOwnProperty("ResizeSensor")&&(this.divjq.css("resize","both").css("overflow","hidden"),a.bugs.webkit_resize&&(this.owidth=parseInt(this.divjq.css("width"),10),this.oheight=parseInt(this.divjq.css("height"),10),this.divjq.css("width",this.width+a.RESIZEFUDGE).css("height",this.height+a.RESIZEFUDGE)),this.resizeSensor=new ResizeSensor(this.divjq,function(){var c=b.divjq.width(),e=b.divjq.height();
a.bugs.webkit_resize&&(c-=a.RESIZEFUDGE,e-=a.RESIZEFUDGE);b.resizing=1;b.resize(c,e)}));this.context=this.canvas.getContext("2d");a.ANTIALIAS||(this.context.imageSmoothingEnabled=!1,this.context.mozImageSmoothingEnabled=!1,this.context.webkitImageSmoothingEnabled=!1);this.tooltip=$("<div>").attr("id","tooltip_"+this.id).addClass("JS9Tooltip").appendTo(this.divjq);this.image=null;this.pluginInstances={};this.layers={};this.initMessages();this.blendMode=!1;this.divjq.on("mouseover",this,function(c){return a.mouseOverCB(c)});
this.divjq.on("mousedown touchstart",this,function(c){return a.mouseDownCB(c)});this.divjq.on("mousemove touchmove",this,function(c){return a.mouseMoveCB(c)});this.divjq.on("mouseup touchend",this,function(c){return a.mouseUpCB(c)});this.divjq.on("mouseout",this,function(c){return a.mouseOutCB(c)});this.divjq.on("keypress",this,function(c){return a.keyPressCB(c)});this.divjq.on("keydown",this,function(c){return a.keyDownCB(c)});this.divjq.on("dragenter",this,function(c){return a.dragenter(this.id,
c.originalEvent)});this.divjq.on("dragover",this,function(c){return a.dragover(this.id,c.originalEvent)});this.divjq.on("dragexit",this,function(c){return a.dragexit(this.id,c.originalEvent)});this.divjq.on("drop",this,function(c){return a.dragdrop(this.id,c.originalEvent,a.NewFITSImage)});this.divjq.append('<div style="visibility:hidden; position:relative; top:-50;left:-50"> <input type="file" id="openLocalFile-'+this.id+'" multiple="true" onchange="javascript:for(var i=0; i<this.files.length; i++){JS9.Load(this.files[i], {display:\''+
this.id+"'}); }\"> </div>");this.divjq.append('<div style="visibility:hidden; position:relative; top:-50;left:-50"> <input type="file" id="refreshLocalFile-'+this.id+'" multiple="true" onchange="javascript:for(var i=0; i<this.files.length; i++){JS9.RefreshImage(this.files[i], {display:\''+this.id+"'}); }\"> </div>");this.divjq.append('<div style="visibility:hidden; position:relative; top:-50;left:-50"> <input type="file" id="openLocalRegions-'+this.id+'" multiple="true" onchange="javascript:for(var i=0; i<this.files.length; i++){JS9.LoadRegions(this.files[i], {display:\''+
this.id+"'}); }\"> </div>");this.divjq.append('<div style="visibility:hidden; position:relative; top:-50;left:-50"> <input type="file" id="openLocalColormap-'+this.id+'" multiple="true" onchange="javascript:for(var i=0; i<this.files.length; i++){JS9.AddColormap(this.files[i], {display:\''+this.id+"'}); }\"> </div>");a.displays.push(this);a.DEBUG&&a.log("JS9 display: %s (%d,%d)",this.id,this.x,this.y)};a.Display.prototype.initMessages=function(){this.messageContainer=$("<div>").addClass("JS9Container").css("z-index",
a.MESSZINDEX).appendTo(this.divjq);this.infoArea=$("<div>").addClass("JS9Message").appendTo(this.messageContainer);this.regionsArea=$("<div>").addClass("JS9Message").appendTo(this.messageContainer);return this};a.Display.prototype.displayPlugin=function(c){var b,d,e,f,g,h,j,k;h=this.pluginInstances[c.name];switch(a.globalOpts.winType){case "light":b=a.lightOpts[a.LIGHTWIN];if(!h||!h.status){if(d=c.name.replace(/\s/g,"_"),e=this.id+"_"+d+"_lightDiv",f=this.id+"_"+d+"_outerDiv",d=this.id+"_"+d+"_innerDiv",
h||(g=$("<div>").attr("id",f).css("display","none").appendTo($(this.divjq)),$("<div>").addClass(c.name).attr("id",d).attr("data-js9id",this.divjq.attr("id")).css("height","100%").css("width","100%").appendTo(g)),g=c.opts.winDims[0]||a.WIDTH,j=c.opts.winDims[1]||a.HEIGHT,k=c.opts.winResize?"1":"0",b=sprintf(b.format,g,j,k),g=c.opts.toolbarHTML&&0<=c.opts.toolbarHTML.search(/\$title/)?"":c.opts.winTitle||"",f=a.lightWin(e,"div",f,g,b),e=$("#"+e+" #"+d),h=a.instantiatePlugin(e,c,f),h.winHandle.onclose=
function(){h.winHandle.hide();h.status="inactive";return!1},h.status="active",c.opts.plugindisplay)try{c.opts.plugindisplay.call(h,this.image)}catch(m){a.log("plugindisplayCB: %s [%s]\n%s",c.name,m.message,a.strace(m))}}else if("inactive"===h.status){if(h.winHandle&&(h.winHandle.show(),h.status="active",c.opts.plugindisplay))try{c.opts.plugindisplay.call(h,this.image)}catch(n){a.log("plugindisplayCB: %s [%s]\n%s",c.name,n.message,a.strace(n))}}else"active"===h.status&&h.winHandle&&(h.winHandle.hide(),
h.status="inactive");break;case "new":a.error("external window support for plugins not yet implemented")}};a.Display.prototype.resize=function(c,b,d){var e,f,g,h,j=function(a){a.left+=g;a.top+=h;a.setCoords()};a.globalOpts.resize||a.error("display resize not enabled");if(!c&&!b)return{width:this.width,height:this.height};c=Math.floor(c);b=b?Math.floor(b):c;(10>c||10>b)&&a.error("invalid dimension(s) passed to display resize");if(c===this.width&&b===this.height)return this;d=d||{};e=b;g=(c-this.width)/
2;h=(e-this.height)/2;this.width=c;this.height=e;this.divjq.css("width",c);this.divjq.css("height",e);this.canvasjq.attr("width",c);this.canvasjq.attr("height",e);a.bugs.webkit_resize&&!this.resizing&&(this.owidth=Math.min(this.owidth,c),this.oheight=Math.min(this.oheight,e));(void 0===d.resizeMenubar||d.resizeMenubar)&&$("#"+this.id+"Menubar").css("width",c);for(f in this.layers)this.layers.hasOwnProperty(f)&&(b=this.layers[f],"main"===b.dtype&&(b.divjq.css("width",c),b.divjq.css("height",e),b.canvasjq.attr("width",
c),b.canvasjq.attr("height",e),b.canvas.setWidth(c),b.canvas.setHeight(e),b.canvas.calcOffset()));for(c=0;c<a.images.length;c++)if(e=a.images[c],e.mkSection(),e.display&&this===e.display&&(e.resize?(e.resize.left+=g,e.resize.top+=h):e.resize={left:g,top:h},e===e.display.image))for(f in e.layers)e.layers.hasOwnProperty(f)&&(b=e.layers[f],b.json||(b.canvas.getObjects().forEach(j),b.canvas.renderAll()));a.bugs.webkit_resize&&this.divjq.css("width",this.width+a.RESIZEFUDGE).css("height",this.height+a.RESIZEFUDGE);
this.image&&(this.image.displayImage("all",d),this.image.refreshLayers());return this};a.Display.prototype.inResize=function(c){return a.globalOpts.resizeHandle&&c.x+a.RESIZEDIST>=this.divjq.width()&&c.y+a.RESIZEDIST>=this.divjq.height()?!0:!1};a.Command=function(c){for(var b in c)c.hasOwnProperty(b)&&(this[b]=c[b]);c.name||a.error("command has no name");!c.get&&!c.set&&a.error("command requires get and/or set routine");a.commands.push(this);1<a.DEBUG&&a.log("JS9 command: %s",this.name)};a.Command.prototype.getDisplayInfo=
function(a){a&&a.id&&(this.display=a,this.image=a.image);return this};a.Command.prototype.getWhich=function(a){return this.get&&!this.set?"get":this.set&&!this.get?"set":this.which?this.which(a):0===a.length?"get":"set"};a.Console=function(c,b){this.display.conMode=2;this.hist=[];this.histtemp=this.histpos=0;this.histused=!1;this.consoleConjq=$("<div>").addClass("JS9ConsoleContainer").appendTo(this.divjq);"light"!==this.winType&&(this.width=this.divjq.attr("data-width"),this.width||(this.width=c||
a.CONWIDTH),this.divjq.css("width",this.width),this.width=parseInt(this.divjq.css("width"),10),this.height=this.divjq.attr("data-height"),this.height||(this.height=b||a.CONHEIGHT),this.divjq.css("height",this.height),this.height=parseInt(this.divjq.css("height"),10),this.consoleConjq.css("width",this.width).css("height",this.height));this.consoleConjq.attr("tabindex","0");this.consoleConjq.on("keydown",this,function(c){return a.consoleKeyDownCB(c)});this.out("Type 'help' for a list of commands","info");
this.inp()};a.Console.prototype.inp=function(){var c;this.consoleConjq.find(".JS9CmdIn:last").attr("readonly","readonly");this.consoleConjq.append(a.consoleHTML.replace(/@@PR@@/g,"js9>"));c=this.consoleConjq.find(".JS9CmdIn:last");c.focus().attr("autocapitalize","off").attr("autocorrect","off").attr("autocomplete","off");a.jupyterFocus(c.parent());return this};a.Console.prototype.out=function(a,b){switch(b.toLowerCase()){case "error":a="ERROR: "+a;b="Error";break;case "info":b="Info";break;case "out":b=
"Out";break;default:b="Out"}$("<div>").addClass("JS9Cmd"+b).html(a).appendTo(this.consoleConjq);return this};a.Console.prototype.xeq=function(){var c,b,d,e,f=this.consoleConjq.find(".JS9CmdIn:last").val(),g=f.replace(/ {2,}/g," ").split(" "),h=[];if(!g[0])return this;b=g[0];for(c=1;c<g.length;c++)h.push(g[c]);this.histused||(this.hist[this.hist.length]=f);this.histpos=this.hist.length;this.histused=!1;try{if(d=a.lookupCommand(b))switch(d.getDisplayInfo(this.display),d.getWhich(h)){case "get":e=d.get(h)||
"";this.out(e,"ok");break;case "set":(e=d.set(h))&&this.out(e,"ok");break;default:e=sprintf("unknown cmd type for '%s'",b),a.error(e)}else e=sprintf("unknown command '%s'",b),0<h.length&&(e=e+" "+h),a.error(e)}catch(j){this.out(j.message,"error")}return this};a.Info={};a.Info.CLASS="JS9";a.Info.NAME="Info";a.Info.opts={infoURL:"./params/info.html",infoHTML:'<table id="info" class="js9InfoTable"><tr><td>file:</td><td colspan="2"><input type="text" id="id" size="28" value="" readonly="readonly" /></td></tr> <tr><td>object:</td><td colspan="2"><input type="text" id="object" size="28" value="" readonly="readonly" /></td></tr> <tr><td>value:</td><td colspan="2"><input type="text" id="val3" size="28" value="" readonly="readonly" /></td></tr> <tr><td><input type="text" id="isys" size="10" value="" readonly="readonly" /></td><td><input type="text" id="ix" size="13" value="" readonly="readonly" /></td><td><input type="text" id="iy" size="13" value="" readonly="readonly" /></td></tr> <tr><td><input type="text" id="psys" size="10" value="" readonly="readonly" /></td><td><input type="text" id="px" size="13" value="" readonly="readonly" /></td><td><input type="text" id="py" size="13" value="" readonly="readonly" /></td></tr> <tr><td><input type="text" id="wcssys" size="10" value="" readonly="readonly" /></span></td><td><input type="text" id="ra" size="13" value="" readonly="readonly" /></td><td><input type="text" id="dec" size="13" value="" readonly="readonly" /></td></tr> <tr><td colspan="3"><textarea style="background: #E9E9E9; border: #CCCCCC solid 1px" id="regions" rows="4" cols="40" value="" readonly="readonly" /></td></tr></table>'};
a.Info.init=function(c,b){this.width=this.divjq.attr("data-width");this.width||(this.width=c||a.INFOWIDTH);this.divjq.css("width",this.width);this.width=parseInt(this.divjq.css("width"),10);this.height=this.divjq.attr("data-height");this.height||(this.height=b||a.INFOHEIGHT);this.divjq.css("height",this.height);this.height=parseInt(this.divjq.css("height"),10);this.infoConjq=$("<div>").addClass("JS9Container").append(a.Info.opts.infoHTML).appendTo(this.divjq);this.jq=this.infoConjq.find("#info")};
a.Info.display=function(c,b,d){var e,f,g,h;this.display&&this.display.pluginInstances&&(f=this.display.pluginInstances.JS9Info);d=d?d:f&&"active"===f.status?f:this.display?this.display:this;if(d===f){switch(typeof b){case "string":g=f.jq.find("#"+c);0<g.length&&g.val(b);break;case "object":for(h in b)if(b.hasOwnProperty(h)){switch(h){case "wcssys":b[h]||(b[h]="wcs")}g=f.jq.find("#"+h);0<g.length&&g.val(b[h])}}return this}d.infoheight=d.infoArea.height()+4;d.regheight=Math.max(2*d.infoheight+10,d.infoheight+
d.regionsArea.height()+10);switch(c){case "regions":f=d.regionsArea;h=!this.display.image||this.display.image.iy>d.regheight?a.textColorOpts.inimage:a.textColorOpts.regions;e=";";break;case "info":f=d.infoArea;h=!this.display.image||this.display.image.iy>d.infoheight?a.textColorOpts.inimage:a.textColorOpts.info;e="";break;default:f=d.infoArea,h=!this.display.image||this.display.image.iy>d.infoheight?a.textColorOpts.inimage:a.textColorOpts.info}switch(typeof b){case "string":g=b;break;case "object":g=
b.vstr}""!==e&&(b=g.split(e),2<b.length&&(b=RegExp(e,"g"),g=g.replace(b,"<br>")));f.css("color",h).html(g);return this};a.Image.prototype.displayMessage=a.Info.display;a.Info.clear=function(a){a?this.displayMessage(a,""):(this.displayMessage("info",""),this.displayMessage("regions",""));return this};a.Image.prototype.clearMessage=a.Info.clear;a.Info.clearMain=function(a){a&&(a.displayMessage("info","",a.display),a.displayMessage("regions","",a.display))};a.Menubar=function(c,b){var d,e,f,g=this;this.width=
this.divjq.attr("data-width");this.width||(this.width=c||a.MENUWIDTH);this.divjq.css("width",this.width);this.width=parseInt(this.divjq.css("width"),10);this.height=this.divjq.attr("data-height");this.height||(this.height=b||a.MENUHEIGHT);this.divjq.css("height",this.height);this.height=parseInt(this.divjq.css("height"),10);if(""===a.menubarHTML){a.menubarHTML="<span id='JS9Menus_@@ID@@'>";for(d=0;d<a.menuButtonOptsArr.length;d++)e=a.menuButtonOptsArr[d].name,f=a.menuButtonOptsArr[d].label,a.allinone&&
"help"===e||("#"===e[0]?(e=e.slice(1),a.menubarHTML+="<button type='button' id='"+e+"Menu@@ID@@' class='JS9Button' disabled='disabled'>"+f+" </button>"):a.menubarHTML+="<button type='button' id='"+e+"Menu@@ID@@' class='JS9Button'>"+f+"</button>");a.menubarHTML+="<button type='button' id='hiddenRegionMenu@@ID@@'class='JS9Button' style='display:none'>R</button>";a.menubarHTML+="<button type='button' id='hiddenAnchorMenu@@ID@@'class='JS9Button' style='display:none'>R</button>";a.menubarHTML+="</span>"}this.display=
a.lookupDisplay(this.id);this.display.menubar=this;d=a.menubarHTML.replace(/@@ID@@/g,this.id);this.menuConjq=$("<div>").addClass("JS9MenubarContainer").attr("width",this.width).attr("height",this.height).html(d).appendTo(this.divjq);$(function(){function c(){var b=g.display;a.bugs.hide_menu&&b.image&&b.image.displayImage("rgb")}function b(){var c,d,e,f=[];if(0<=g.id.search(a.SUPERMENU))if(d=g.divjq.data("displays").split(","),"*"===d[0])for(c=0;c<a.displays.length;c++)f.push(a.displays[c]);else for(c=
0;c<d.length;c++)(e=a.lookupDisplay(d[c]))&&f.push(e);f.length||f.push(g.display);return f}$("#fileMenu"+g.id).on("mousedown",function(a){a.preventDefault();$("#fileMenu"+g.id).contextMenu()});$.contextMenu({selector:"#fileMenu"+g.id,zIndex:a.MENUZINDEX,events:{hide:c},build:function(){var c,d,e,f,g=0,h={},q=b()[0],s=q.image;f=a.images.length;for(c=0;c<f;c++)d=a.images[c],d.display===q&&(e=d.id,a.globalOpts.rgb.active&&(d===a.globalOpts.rgb.rim&&(e+=" (red)"),d===a.globalOpts.rgb.gim&&(e+=" (green)"),
d===a.globalOpts.rgb.bim&&(e+=" (blue)")),h[e]={name:e},q.image&&q.image.id===d.id&&(h[e].icon="sun"),g++);g||(h.noimg={name:"[no images]",events:{keyup:function(){}}});h["sep"+g++]="------";h.open={name:"open local file ..."};h.archives={name:" accessing data archives ..."};h.archives.disabled=a.allinone?!0:!1;h.loadproxy={name:"open link via proxy ..."};h.loadproxy.disabled=!a.allinone&&"none"!==a.globalOpts.helperType&&a.globalOpts.workDir&&a.globalOpts.loadProxy?!1:!0;h.loadcors={name:"open link via CORS ..."};
h.loadcors.disabled=window.hasOwnProperty("Jupyter")?!0:!1;h.imsection={name:"extract image section ..."};h.imsection.disabled=!a.allinone&&"none"!==a.globalOpts.helperType&&a.globalOpts.workDir&&s&&s.parentFile?!1:!0;h["sep"+g++]="------";h.print={name:"print ..."};h.header={name:"display FITS header"};h.pageid={name:"display pageid"};h.savefits={name:"save image as FITS"};h.savepng={name:"save image as PNG"};h.savejpeg={name:"save image as JPEG"};h.close={name:"close image"};h["sep"+g++]="------";
h.lite={name:"new JS9 light window"};h.xnew={name:"new JS9 separate window"};2<a.DEBUG&&(h["sep"+g++]="------",h.refresh={name:"debug: refresh ..."});return{callback:function(c){b().forEach(function(b){var d,e,f,g;e=b.image;switch(c){case "close":e&&e.closeImage();break;case "header":e&&(e.raw.header?e.displayAnalysis("text",a.raw2FITS(e.raw,!0),"FITSHeader_"+e.id):a.error("no FITS header for "+e.id));break;case "lite":a.LoadWindow(null,null,"light");break;case "xnew":a.LoadWindow(null,null,"new");
break;case "pageid":b="<center><p>Usage: js9 -pageid [pageid] ...<p>"+a.helper.pageid||"none</center>";a.lightWin("fileid"+a.uniqueID(),"inline",b,"page ID",a.lightOpts[a.LIGHTWIN].lineWin);break;case "open":a.OpenFileMenu({display:b});break;case "loadcors":e=a.allinone?a.Image.prototype.displayAnalysis.call(null,"textline",a.allinone.loadCorsHTML,"Open a shared CORS link"):a.Image.prototype.displayAnalysis.call(null,"textline",a.InstallDir(a.globalOpts.corsURL),"Open a shared CORS link");$(e).data("dispid",
b.id);break;case "archives":a.DisplayHelp(a.InstallDir(a.globalOpts.archivesURL));break;case "loadproxy":e=a.Image.prototype.displayAnalysis.call(null,"textline",a.InstallDir(a.globalOpts.proxyURL),"Open a link via server proxy");$(e).data("dispid",b.id).data("aname","loadproxy");break;case "imsection":f=a.Regions.opts.onchange;$("#dhtmlwindowholder").arrive("#imageSectionForm",{onceOnly:!0},function(){a.Regions.opts.onchange=function(a,c){var b,d;f&&f(a,c);a.parentFile&&("region"===$("#imageSectionForm input:radio[name=imode]:checked").val()&&
"box"===c.shape)&&(b=a.raw.header.LTM1_1||1,b=c.width/b,d=a.raw.header.LTM2_2||1,d=c.height/d,$("#imageSectionForm #xcen").val(Math.floor(c.lcs.x)),$("#imageSectionForm #ycen").val(Math.floor(c.lcs.y)),$("#imageSectionForm #xdim").val(Math.floor(b)),$("#imageSectionForm #ydim").val(Math.floor(d)))}});$("#dhtmlwindowholder").leave("#imageSectionForm",{onceOnly:!0},function(){a.Regions.opts.onchange=f});e=a.Image.prototype.displayAnalysis.call(null,"params",a.InstallDir(a.globalOpts.imsectionURL),"Extract Image Section From a 'Parent' File",
"width=440px,height=230px,center=1,resize=1,scrolling=1");$(e).data("dispid",b.id).data("aname","imsection");break;case "refresh":$("#refreshLocalFile-"+b.id).click();break;case "savefits":e&&(b=e.id.replace(/\.png/i,".fits").replace(/\.gz$/i,"").replace(/\[.*\]/,""),e.saveFITS(b));break;case "savepng":e&&(b=e.id.replace(/\.fit[s]?/i,".png").replace(/\.gz$/i,"").replace(/\[.*\]/,""),e.savePNG(b));break;case "savejpeg":e&&(b=e.id.replace(/\.fit[s]?/i,".jpeg").replace(/\.png$/i,".jpeg").replace(/\.gz$/i,
"").replace(/\[.*\]/,""),e.saveJPEG(b));break;case "print":e&&e.print();break;default:for(d=0;d<a.images.length;d++)if(e=a.images[d],g=c.replace(/ *\((red|green|blue)\)/,""),b.id===e.display.id&&e.id===g){e.displayImage("display");e.refreshLayers();e.clearMessage();break}}})},items:h}}});$("#viewMenu"+g.id).on("mousedown",function(a){a.preventDefault();$("#viewMenu"+g.id).contextMenu()});$.contextMenu({selector:"#viewMenu"+g.id,zIndex:a.MENUZINDEX,events:{hide:c},build:function(){var c,d,e,f,h,l=
"",q=0,s=0,t={},v=b()[0],u=v.image,w=function(c,b){var d,e;if(b.resize)switch(e=b.resize.split(/[\s,\/]+/),e.length){case 0:break;case 1:a.isNumber(e[0])&&(d=parseInt(e[0],10),c.resize(d,d));break;default:a.isNumber(e[0])&&a.isNumber(e[1])&&(d=parseInt(e[0],10),e=parseInt(e[1],10),c.resize(d,e))}},y=function(a){var c=$.contextMenu.getInputValues(a.data),b=g.display;switch(a.which||a.keyCode){case 9:case 13:w(b,c);a.data.edited=!1;break;default:a.data.edited=!0}};for(c=0;c<a.plugins.length;c++)if(d=
a.plugins[c],e=d.name,d.opts.menuItem&&"view"===d.opts.menu&&(f=v.pluginInstances[e],!f||f.winHandle))d.xclass!==l&&(q+=1),l=d.xclass,t[e]={name:d.opts.menuItem},f&&"active"===f.status&&(t[e].icon="sun");t["sep"+q++]="------";if(u){for(h in u.layers)u.layers.hasOwnProperty(h)&&"main"===u.layers[h].dlayer.dtype&&(s++,t[h]={name:h},u.layers[h].show&&(t[h].icon="sun"));1<s&&(t.hide={name:"HideAll"},t.show={name:"ShowAll"},t["sep"+q++]="------")}t.valpos={name:"display value/position"};v.image&&v.image.params.valpos&&
(t.valpos.icon="sun");if(u&&1<u.raws.length){t["sep"+q++]="------";t.rawlayer={name:"raw data layers",items:{}};for(c=0;c<u.raws.length;c++)h="rawlayer_"+u.raws[c].id,t.rawlayer.items[h]={name:u.raws[c].id},u.raw===u.raws[c]&&(t.rawlayer.items[h].icon="sun")}a.globalOpts.resize&&(t["sep"+q++]="------",t.resize={events:{keyup:y},name:"change width/height:",type:"text"});return{callback:function(c){b().forEach(function(b){var d,e,f,g=b.image;switch(c){case "valpos":g&&(g.params.valpos=!g.params.valpos,
g.params.valpos||g.clearMessage());break;case "show":case "hide":if(g)for(e in g.layers)g.layers.hasOwnProperty(e)&&"main"===g.layers[e].dlayer.dtype&&(g.showShapeLayer(e,c),"show"===c&&g.refreshLayers());break;default:for(d=0;d<a.plugins.length;d++)if(f=a.plugins[d],f.name===c){b.displayPlugin(f);return}if(g)for(e in g.layers)if(g.layers.hasOwnProperty(e)&&c===e){b=g.layers[e].show?"hide":"show";g.showShapeLayer(e,b);"show"===b&&g.refreshLayers();return}u&&c.match(/^rawlayer_/)&&u.rawDataLayer(c.replace(/^rawlayer_/,
""))}})},events:{show:function(c){var b=g.display,d={};b&&(d.resize=sprintf("%d %d",b.width,b.height),$.contextMenu.setInputValues(c,d),a.jupyterFocus(".context-menu-item"))},hide:function(a){var c=g.display;c&&a.edited&&(delete a.edited,a=$.contextMenu.getInputValues(a),w(c,a))}},items:t}}});$("#zoomMenu"+g.id).on("mousedown",function(a){a.preventDefault();$("#zoomMenu"+g.id).contextMenu()});$.contextMenu({selector:"#zoomMenu"+g.id,zIndex:a.MENUZINDEX,events:{hide:c},build:function(){var c,d,e,f,
h=0,l=b()[0].image,q={zoomtitle:{name:"Zoom Factors:",disabled:!0}};for(c=a.imageOpts.zooms;1<=c;c--)d=Math.pow(2,-c),e=Math.pow(2,c),f=sprintf("zoom%s",d),e=sprintf("zoom 1/%s",e),q[f]={name:e},l&&l.rgb.sect.zoom===d&&(q[f].icon="sun");for(c=0;c<=a.imageOpts.zooms;c++)d=Math.pow(2,c),f=sprintf("zoom%s",d),e=sprintf("zoom %s",d),q[f]={name:e},l&&l.rgb.sect.zoom===d&&(q[f].icon="sun");q["sep"+h++]="------";q.zoomiotitle={name:"Zoom In/Out:",disabled:!0};q.zoomIn={name:"zoom in"};q.zoomOut={name:"zoom out"};
q.zoomToFit={name:"zoom to fit"};q["sep"+h++]="------";q.zoom={events:{keyup:function(a){var c=$.contextMenu.getInputValues(a.data),b=g.display.image;switch(a.which||a.keyCode){case 9:case 13:b&&(isNaN(c.zoom)||b.setZoom(c.zoom),a.data.edited=!1);break;default:a.data.edited=!0}}},name:"numeric zoom value:",type:"text"};q["sep"+h++]="------";q.center={name:"pan to center"};q.reset={name:"reset zoom/pan"};return{callback:function(a){b().forEach(function(c){if(c=c.image)switch(a){case "zoomIn":c.setZoom("x2");
break;case "zoomOut":c.setZoom("/2");break;case "zoomToFit":c.setZoom("tofit");break;case "center":c.setPan();break;case "reset":c.setZoom("1");c.setPan();break;default:a.match(/^zoom/)&&c.setZoom(a.slice(4))}})},events:{show:function(c){var b=g.display.image,d={};b&&(d.zoom=String(b.rgb.sect.zoom));$.contextMenu.setInputValues(c,d);a.jupyterFocus(".context-menu-item")},hide:function(a){var c=g.display.image;c&&a.edited&&(delete a.edited,a=$.contextMenu.getInputValues(a),isNaN(a.zoom)||c.setZoom(a.zoom))}},
items:q}}});$("#scaleMenu"+g.id).on("mousedown",function(a){a.preventDefault();$("#scaleMenu"+g.id).contextMenu()});$.contextMenu({selector:"#scaleMenu"+g.id,zIndex:a.MENUZINDEX,events:{hide:c},build:function(){var c,d,e,f=0,h={},l=b()[0],q=function(c,b){a.isNumber(b.scalemin)&&(c.params.scalemin=parseFloat(b.scalemin));a.isNumber(b.scalemax)&&(c.params.scalemax=parseFloat(b.scalemax));c.displayImage("colors")},s=function(a){var c=$.contextMenu.getInputValues(a.data),b=g.display.image;switch(a.which||
a.keyCode){case 9:case 13:q(b,c);a.data.edited=!1;break;default:a.data.edited=!0}};h.scaletitle={name:"Scaling Algorithms:",disabled:!0};for(c=0;c<a.scales.length;c++)e=d=a.scales[c],h[d]={name:e},l.image&&l.image.params.scale===d&&(h[d].icon="sun");h["sep"+f++]="------";h.scalemin={events:{keyup:s},name:"low limit for clipping:",type:"text"};h.scalemax={events:{keyup:s},name:"high limit for clipping:",type:"text"};h["sep"+f++]="------";h.dminmax={name:"set limits to data min/max"};h.zscale={name:"set limits to zscale z1/z2"};
return{callback:function(a,c){b().forEach(function(b){if(b=b.image)switch(a){case "dminmax":return b.params.scaleclipping="dataminmax",b.params.scalemin=b.raw.dmin,b.params.scalemax=b.raw.dmax,$.contextMenu.setInputValues(c,{scalemin:String(b.params.scalemin),scalemax:String(b.params.scalemax)}),b.displayImage("colors"),!1;case "zscale":return(!b.params.z1||b.params.z2)&&b.zscale(!1),b.params.scaleclipping="zscale",b.params.scalemin=b.params.z1,b.params.scalemax=b.params.z2,$.contextMenu.setInputValues(c,
{scalemin:String(b.params.scalemin),scalemax:String(b.params.scalemax)}),b.displayImage("colors"),!1;default:b.setScale(a)}})},events:{show:function(c){var b=g.display.image,d={};b&&(d.scalemin=String(b.params.scalemin),d.scalemax=String(b.params.scalemax));$.contextMenu.setInputValues(c,d);a.jupyterFocus(".context-menu-item")},hide:function(a){var c=g.display.image;c&&a.edited&&(delete a.edited,a=$.contextMenu.getInputValues(a),q(c,a))}},items:h}}});$("#colorMenu"+g.id).on("mousedown",function(a){a.preventDefault();
$("#colorMenu"+g.id).contextMenu()});$.contextMenu({selector:"#colorMenu"+g.id,zIndex:a.MENUZINDEX,events:{hide:c},build:function(){var c,d,e,f=0,h={},l=b()[0],q=function(a,c){c.contrast&&!isNaN(c.contrast)&&(a.params.contrast=parseFloat(c.contrast));c.bias&&!isNaN(c.bias)&&(a.params.bias=parseFloat(c.bias));isNaN(c.opacity)||(a.params.opacity=""!==c.opacity?parseFloat(c.opacity):1);a.displayImage("colors")},s=function(a){var c=$.contextMenu.getInputValues(a.data),b=g.display.image;switch(a.which||
a.keyCode){case 9:case 13:q(b,c);a.data.edited=!1;break;default:a.data.edited=!0}};h.cmaptitle={name:"Colormaps:",disabled:!0};for(c=0;c<a.colormaps.length;c++)e=d=a.colormaps[c].name,h[d]={name:e},l.image&&l.image.cmapObj.name===d&&(h[d].icon="sun");h["sep"+f++]="------";h.contrast={events:{keyup:s},name:"contrast value:",type:"text"};h.bias={events:{keyup:s},name:"bias value:",type:"text"};h.opacity={events:{keyup:s},name:"opacity value:",type:"text"};h["sep"+f++]="------";h.reset={name:"reset contrast/bias"};
h["sep"+f++]="------";h.loadcmap={name:"load colormap"};h.savecmap={name:"save colormap"};h.invert={name:"invert colormap"};l.image&&l.image.params.invert&&(h.invert.icon="sun");h["sep"+f++]="------";h.rgb={name:"RGB mode"};a.globalOpts.rgb.active&&(h.rgb.icon="sun");return{callback:function(c){b().forEach(function(b){var d=b.image;if(d)switch(c){case "loadcmap":a.OpenColormapMenu({display:b});break;case "savecmap":a.SaveColormap({display:b});break;default:d.setColormap(c)}})},events:{show:function(c){var b=
g.display.image,d={};b&&(d.contrast=String(b.params.contrast),d.bias=String(b.params.bias),d.opacity=String(b.params.opacity),d.sigma=String(b.params.sigma));$.contextMenu.setInputValues(c,d);a.jupyterFocus(".context-menu-item")},hide:function(a){var c=g.display.image;c&&a.edited&&(delete a.edited,a=$.contextMenu.getInputValues(a),q(c,a))}},items:h}}});$("#regionMenu"+g.id).on("mousedown",function(a){a.preventDefault();$("#regionMenu"+g.id).contextMenu()});$.contextMenu({selector:"#regionMenu"+g.id,
zIndex:a.MENUZINDEX,events:{hide:c},build:function(){var c=b()[0].image,d={regiontitle:{name:"Regions:",disabled:!0},annulus:{name:"annulus"},box:{name:"box"},circle:{name:"circle"},ellipse:{name:"ellipse"},line:{name:"line"},point:{name:"point"},polygon:{name:"polygon"},text:{name:"text"},sep2:"------",loadRegions:{name:"load regions"},saveRegions:{name:"save regions"},listRegions:{name:"list regions"},deleteRegions:{name:"delete regions"},listonchange:{name:"list on change"},xeqonchange:{name:"xeq on change"}};
c&&c.params.listonchange&&(d.listonchange.icon="sun");c&&c.params.xeqonchange&&(d.xeqonchange.icon="sun");return{callback:function(c){b().forEach(function(b){var d=b.image;if(d)switch(c){case "deleteRegions":d.removeShapes("regions","all");d.clearMessage("regions");break;case "loadRegions":a.OpenRegionsMenu({display:b});break;case "saveRegions":d.saveRegions("js9.reg","all");break;case "listRegions":d.listRegions("all",2);break;case "xeqonchange":d.params.xeqonchange=!d.params.xeqonchange;break;case "listonchange":d.params.listonchange=
!d.params.listonchange;break;default:d.addShapes("regions",c,{ireg:!0})}})},items:d}}});$("#wcsMenu"+g.id).on("mousedown",function(a){a.preventDefault();$("#wcsMenu"+g.id).contextMenu()});$.contextMenu({selector:"#wcsMenu"+g.id,zIndex:a.MENUZINDEX,events:{hide:c},build:function(){var c,d,e,f=0,g=0,h={},q=b()[0],s=q.image;h.wcssystitle={name:"WCS Systems:",disabled:!0};for(c=0;c<a.wcssyss.length;c++)e=d=a.wcssyss[c],h[d]={name:e},q.image&&q.image.params.wcssys===d&&(h[d].icon="sun");h["sep"+f++]="------";
h.wcsutitle={name:"WCS Units:",disabled:!0};for(c=0;c<a.wcsunitss.length;c++)e=d=a.wcsunitss[c],h[d]={name:e},q.image&&q.image.params.wcsunits===d&&(h[d].icon="sun");h["sep"+f++]="------";h.reproject={name:"reproject",items:{reprojtitle:{name:"wcs from:",disabled:!0}}};for(c=0;c<a.images.length;c++)s!==a.images[c]&&a.images[c].wcs&&(d="reproject_"+a.images[c].id,h.reproject.items[d]={name:a.images[c].id},g++);0===g?h.reproject.items.notasks={name:"[none]",disabled:!0,events:{keyup:function(){}}}:
(h.reproject.items["sep"+f++]="------",h.reproject.items.reproject_wcsalign={name:"display wcs-aligned"},q.image&&q.image.params.wcsalign&&(h.reproject.items.reproject_wcsalign.icon="sun"));return{callback:function(c){b().forEach(function(b){var d;d=RegExp(c);if(b=b.image)c.match(/^reproject_/)?"reproject_wcsalign"===c?(b.params.wcsalign=!b.params.wcsalign,b.displayImage("display")):(d=c.replace(/^reproject_/,""),b.reprojectData(d)):0<=a.wcssyss.join("@").search(d)?b.setWCSSys(c):0<=a.wcsunitss.join("@").search(d)?
b.setWCSUnits(c):a.error("unknown wcs sys/units: "+c)})},items:h}}});$("#analysisMenu"+g.id).on("mousedown",function(a){a.preventDefault();$("#analysisMenu"+g.id).contextMenu()});$.contextMenu({selector:"#analysisMenu"+g.id,zIndex:a.MENUZINDEX,events:{hide:c},build:function(){var c,d,e,f,h,l=0,q=0,s={};h=b()[0];var t=h.image,v="",u=function(a,c){c.sigma||(c.sigma="none");"none"===c.sigma?(a.params.sigma=c.sigma,a.rawDataLayer("gaussBlur","remove")):(a.params.sigma=parseFloat(c.sigma),a.gaussBlurData(a.params.sigma))},
w=function(a){var c=$.contextMenu.getInputValues(a.data),b=g.display.image;switch(a.which||a.keyCode){case 9:case 13:u(b,c);a.data.edited=!1;break;default:a.data.edited=!0}};for(c=0;c<a.plugins.length;c++)if(d=a.plugins[c],f=d.name,d.opts.menuItem&&"analysis"===d.opts.menu&&(e=h.pluginInstances[f],!e||e.winHandle))d.xclass!==v&&(s["sep"+q++]="------",s["sep"+q++]={name:d.xclass+" Plugins:"},s["sep"+(q-1)].disabled=!0),v=d.xclass,s[f]={name:d.opts.menuItem},e&&"active"===e.status&&(s[f].icon="sun"),
q++;if(!a.allinone){0<q&&(s["sep"+q++]="------");s.remotetitle={name:"Server-side Tasks:",disabled:!0};if(t&&t.analysisPackages){f=t.analysisPackages;for(d=0;d<f.length;d++){h=f[d];for(c=0;c<h.length;c++)if(!h[c].hidden&&("fits"!==h[c].files||t.fitsFile)&&!("png"===h[c].files&&"fits2png"!==t.source))e=h[c].title,h[c].purl&&(e+=" ..."),s[h[c].name]={name:e},l++}}l||(s.notasks={name:"[none]",disabled:!0,events:{keyup:function(){}}});s["sep"+q++]="------";s.sigma={events:{keyup:w},name:"gaussian blur sigma:",
type:"text"};s.dpath={name:"set data path ..."}}return{callback:function(c){b().forEach(function(b){var d,e,f;e=b.image;for(d=0;d<a.plugins.length;d++)if(f=a.plugins[d],f.name===c){b.displayPlugin(f);return}if(e)switch(c){case "dpath":$("#dhtmlwindowholder").arrive("#dataPathForm",{onceOnly:!0},function(){$("#dataPath").val(a.globalOpts.dataPath)});e=e.displayAnalysis("textline",a.InstallDir(a.analOpts.dpathURL),"Data Path for Drag and Drop");$(e).data("dispid",b.id);break;default:if(d=e.lookupAnalysis(c))d.purl?
(e=e.displayAnalysis("params",a.InstallDir(d.purl),d.title+": "+e.fitsFile),$(e).data("dispid",b.id).data("aname",d.name)):e.runAnalysis(d.name)}})},events:{show:function(c){var d=g.display.image,b={};d&&(b.sigma=String(d.params.sigma));$.contextMenu.setInputValues(c,b);a.jupyterFocus(".context-menu-item")},hide:function(a){var c=g.display.image;c&&a.edited&&(delete a.edited,a=$.contextMenu.getInputValues(a),u(c,a))}},items:s}}});$("#helpMenu"+g.id).on("mousedown",function(a){a.preventDefault();$("#helpMenu"+
g.id).contextMenu()});$.contextMenu({selector:"#helpMenu"+g.id,zIndex:a.MENUZINDEX,events:{hide:c},build:function(){var c,d,b=1,e="",f={helptitle:{name:"JS9 Help:",disabled:!0}};for(c in a.helpOpts)a.helpOpts.hasOwnProperty(c)&&(d=a.helpOpts[c],""!==e&&d.type!==e&&(f["sep"+b++]="------",d.heading&&(f["sep"+b++]={name:d.heading+" Help:"},f["sep"+(b-1)].disabled=!0)),e=d.type,f[c]={name:d.title});f["sep"+b++]="------";f.about={name:"About JS9"};return{callback:function(c){switch(c){case "about":alert(sprintf("JS9: image display right in your browser\nversion: %s\nprincipals: Eric Mandel (lead), Alexey Vikhlinin (science,management)\ncontact: [email protected]\n%s",
a.VERSION,a.COPYRIGHT));break;default:a.DisplayHelp(c)}},items:f}}})})};a.Helper=function(){this.helper=this.connected=!1;this.type=a.globalOpts.helperType||"sock.io";this.pageid=null;this.connect()};a.Helper.prototype.connectinfo=function(){if(null===a.helper.connected)return"notConfigured";if(a.helper.connected){var c=sprintf("connected %s %s",a.helper.type,a.helper.url);a.helper.pageid&&(c+="<p>"+a.helper.pageid);return c}return sprintf("notConnected %s",a.helper.type)};a.Helper.prototype.connect=
function(c){var b=this;c&&(this.type=c);if(this.socket){try{this.socket.disconnect()}catch(d){a.log("warning: can't disconnect from socket")}this.socket=null}this.url=a.globalOpts.helperURL?0<=a.globalOpts.helperURL.search(/:\/\//)?a.globalOpts.helperURL:a.globalOpts.helperProtocol+a.globalOpts.helperURL:document.domain?a.globalOpts.helperProtocol+document.domain:a.globalOpts.helperProtocol+"localhost";switch(this.type){case "none":this.connected=null;a.Preload(!0);break;case "get":case "post":a.globalOpts.helperCGI||
a.error("cgi script name missing for helper");this.url+="/"+a.globalOpts.helperCGI;this.helper=this.connected=!0;a.DEBUG&&a.log("JS9 helper: connect: "+this.type);a.Preload(!0);break;case "sock.io":case "nodejs":a.globalOpts.helperPort||a.error("port missing for helper");this.url+=":"+a.globalOpts.helperPort;this.sockurl=this.url+"/socket.io/socket.io.js";$.ajax({url:this.sockurl,dataType:"script",timeout:a.globalOpts.htimeout,success:function(){var c,d;b.socket=io.connect(b.url,{reconnection:!0,
reconnectionDelay:1E4,reconnectionDelayMax:1E4,reconnectionAttempts:6,timeout:a.globalOpts.htimeout});b.socket.on("connect",function(){b.connected=!0;b.helper=!0;d=[];for(c=0;c<a.displays.length;c++)d.push(a.displays[c].id);b.socket.emit("displays",{displays:d},function(a){b.pageid=a});a.Preload(!0);a.DEBUG&&a.log("JS9 helper: connect: "+b.type)});b.socket.on("connect_error",function(){b.connected=!1;b.helper=!1;a.Preload(!0);1<a.DEBUG&&a.log("JS9 helper: connect error")});b.socket.on("connect_timeout",
function(){b.connected=!1;b.helper=!1;a.Preload(!0);1<a.DEBUG&&a.log("JS9 helper: connect timeout")});b.socket.on("disconnect",function(){b.connected=!1;b.helper=!1;1<a.DEBUG&&a.log("JS9 helper: disconnect")});b.socket.on("reconnect",function(){b.connected=!0;b.helper=!0;1<a.DEBUG&&a.log("JS9 helper: reconnect")});b.socket.on("msg",a.msgHandler)},error:function(c,d,g){b.connected=!1;b.helper=!1;a.Preload(!0);a.DEBUG&&a.log("JS9 helper: connect failure: "+d+" "+g)}});break;default:a.error("unknown helper type: "+
this.type)}};a.Helper.prototype.send=function(c,b,d){if(!this.connected)return null;b&&"object"===typeof b?(b.cookie=document.cookie,a.globalOpts.dataPath&&!b.dataPath&&(b.dataPath=a.globalOpts.dataPath+":.")):b={dataPath:"."};a.TOROOT&&(b.dataPath+=":"+a.TOROOT);switch(this.type){case "get":case "post":b.key=c;a.DEBUG&&a.log("JS9 cgi helper [%s, %s]: %s",this.type,JSON.stringify(b),this.url);$.ajax({url:this.url,type:this.type.toUpperCase(),data:b,dataType:"text",success:function(c){"string"===typeof c&&
0<=c.search(a.analOpts.epattern)&&a.log(c);d&&d(c)},error:function(c,d,b){a.DEBUG&&a.log("JS9 helper: "+this.type+" failure: "+d+" "+b)}});break;case "sock.io":case "nodejs":a.helper.socket.emit(c,b,d)}return this};a.Fabric={};a.Fabric.elements="cornerSize cornerColor borderColor transparentCorners selectionLineWidth centeredScaling hasControls hasRotatingPoint hasBorders params pub".split(" ");a.Fabric.opts={originX:"center",originY:"center",strokeWidth:2,selectionLineWidth:2,borderColor:"#00FF00",
cornerColor:"#00FF00",cornerSize:fabric.isTouchSupported?12:8,hasControls:!0,hasRotatingPoint:!0,hasBorders:!0,transparentCorners:!1,centeredScaling:!0,selectable:!0,padding:0,canvas:{selection:!0,zindex:a.SHAPEZINDEX},fill:"transparent"};a.Fabric.rescaleStrokeWidth=function(c,b){var d=(this.scaleX+this.scaleY)/2;c=c||1;c*=d;!b&&this.params&&(b=this.params.sw1);b&&("group"===this.type?this.forEachObject(function(d){a.Fabric.rescaleStrokeWidth.call(d,c,b)}):this.setStrokeWidth(b/c))};a.Fabric.rescaleEvenly=
function(){var a;if(this.params&&this.scaleX!==this.scaleY)switch(this.params.shape){case "annulus":case "circle":a=this.params.lastscale||1,this.scaleX!==a?this.scaleY=this.scaleX:this.scaleY!==a&&(this.scaleX=this.scaleY),this.params.lastscale=this.scaleX}};fabric.Object.prototype.rescaleBorder=a.Fabric.rescaleStrokeWidth;fabric.Object.prototype.rescaleEvenly=a.Fabric.rescaleEvenly;a.Fabric.newShapeLayer=function(c,b,d){var e,f;if(this&&c){if(this.layers[c])return this.layers[c];this.layers[c]=
{};f=this.layers[c];f.params=[];f.params.sel=null;f.params.sellayer=null;d?f.dtype="other":(f.dtype="main",d=this.divjq);e=d.attr("id")+"-"+c.replace(/\s+/,"_")+"-shapeLayer";f.display=this;f.opts=$.extend(!0,{},b);f.opts.canvas=f.opts.canvas||{};void 0===f.opts.canvas.selection&&(f.opts.canvas.selection=!0);f.opts.canvas.zindex=f.opts.canvas.zindex||a.SHAPEZINDEX;f.el=a.Fabric.elements;f.divjq=$("<div>").addClass("JS9Container").css("z-index",0).appendTo(d);f.canvasjq=$("<canvas>").addClass("JS9Layer").attr("id",
e).attr("width",d.css("width")).attr("height",d.css("height")).appendTo(f.divjq);a.bugs.webkit_resize&&"main"===f.dtype&&f.canvasjq.attr("width",this.width).attr("height",this.height);f.canvas=new fabric.Canvas(f.canvasjq[0]);f.canvas.renderOnAddRemove=!1;f.opts.movable&&(f.opts.hasControls=!0,f.opts.hasRotatingPoint=!0,f.opts.hasBorders=!0,f.opts.lockMovementX=!1,f.opts.lockMovementY=!1,f.opts.lockRotation=!1,f.opts.lockScalingX=!1,f.opts.lockScalingY=!1,f.opts.lockUniScaling=!1,f.opts.selectable=
!0,f.opts.evented=!0,f.opts.usekeyboard=!0);f.opts.selectable&&(f.opts.canvas.selection=!0);if(f.opts.onmousedown||f.opts.onmouseup||f.opts.onmousemove||f.opts.tooltip||f.opts.onmouseover||f.opts.onmouseout){f.opts.evented=!0;if(f.opts.onmousedown)f.canvas.on("mouse:down",function(c){if(f.display.image&&c.target)"main"===f.dtype&&(f.display.image.rclick=1),f.opts.onmousedown.call(this,f.display.image,c.target.pub,c.e,c.target);else if(this._selection=this.selection)this.selection=a.specialKey(c.e)});
else f.canvas.on("mouse:down",function(c){if(this._selection=this.selection)this.selection=a.specialKey(c.e)});if(f.opts.onmouseup)f.canvas.on("mouse:up",function(a){f.display.image&&a.target&&f.opts.onmouseup.call(this,f.display.image,a.target.pub,a.e,a.target);this.selection=this._selection||this.selection});else f.canvas.on("mouse:up",function(){this.selection=this._selection||this.selection});if(f.opts.onmousemove)f.canvas.on("mouse:move",function(a){f.display.image&&a.target&&f.opts.onmousemove.call(this,
f.display.image,a.target.pub,a.e,a.target)});if(f.opts.onmouseover)f.canvas.on("mouse:over",function(a){f.display.image&&a.target&&f.opts.onmouseover.call(this,f.display.image,a.target.pub,a.e,a.target)});if(f.opts.onmouseout)f.canvas.on("mouse:out",function(a){f.display.image&&a.target&&f.opts.onmouseout.call(this,f.display.image,a.target.pub,a.e,a.target)});f.opts.tooltip&&(f.canvas.on("mouse:over",function(c){f.display.image&&c.target&&a.tooltip(c.target.left,c.target.top,f.opts.tooltip,f.display.image,
c.target.pub,c.e,c.target)}),f.canvas.on("mouse:out",function(c){f.display.image&&c.target&&a.tooltip(c.target.left,c.target.top,null,f.display.image,c.target.pub,c.e,c.target)}))}else f.canvas.on("mouse:down",function(c){if(this._selection=this.selection)this.selection=a.specialKey(c.e)}),f.canvas.on("mouse:up",function(){this.selection=this._selection||this.selection});if(f.opts.ongroupcreate&&(f.opts.canvas.selection=!0,f.opts.selectable=!0,f.opts.ongroupcreate))f.canvas.on("selection:created",
function(a){var c=[],d=[];f.display.image&&"group"===a.target.type&&(a.target.forEachObject(function(a){a.pub&&(d.push(a),c.push(a.pub))}),f.opts.ongroupcreate.call(this,f.display.image,c,a.e,d))});f.canvas.on("object:scaling",function(a){a.target.rescaleEvenly();a.target.rescaleBorder()});f.canvas.on("object:selected",function(d){f.params.sel&&(d.target.params&&f.params.sel!==d.target)&&f.canvas.fire("before:selection:cleared",{target:f.params.sel});switch(d.target.type){case "polyline":case "polygon":a.Fabric.addPolygonAnchors(f,
d.target),f.canvas.renderAll()}d.target.polyparams?f.params.sel=d.target.polyparams.polygon:d.target.params&&(f.params.sel=d.target);f.display.image&&(f.display.image.layer=c)});f.canvas.on("before:selection:cleared",function(c){f.params.sel=null;f.display.image&&(f.display.image.layer=null);switch(c.target.type){case "polyline":case "polygon":a.Fabric.removePolygonAnchors(f,c.target),f.canvas.renderAll()}});if(f.divjq.closest(a.lightOpts[a.LIGHTWIN].drag).length)if(fabric.isTouchSupported)f.divjq.on("touchstart",
function(){f.canvas.calcOffset()});else f.divjq.on("mouseenter",function(){f.canvas.calcOffset()});return f}};a.Fabric.showShapeLayer=function(c,b){var d=this,e=0,f,g,h,j;if(g=this.getShapeLayer(c)){j=g.canvas;h=this.display.layers[c];if("show"===b||!0===b){"show"===b&&(g.show=!0);g.json&&g.show&&j.loadFromJSON(g.json,function(){var b,e,f,p;d.resize&&(j.getObjects().forEach(function(a){a.left+=d.resize.left;a.top+=d.resize.top;a.setCoords()}),j.calcOffset());j.renderAll();j.selection=g.opts.canvas.selection;
e=h.opts.canvas.zindex;h.divjq.css("z-index",e);for(b in d.layers)if(d.layers.hasOwnProperty(b)&&(c!==b&&d.layers[b].show)&&(f=d.display.layers[b],f.divjq.css("z-index")<e&&(p=f.canvas.getActiveObject())))a.Fabric.removePolygonAnchors(f,p),f.canvas.discardActiveObject();g.json=null});for(f in this.layers)this.layers.hasOwnProperty(f)&&this.layers[f].json&&e++;e||(this.resize=null)}else if("hide"===b||!1===b)g.show&&(j.forEachObject(function(c){a.Fabric.removePolygonAnchors(h,c);c.params&&c.params.winid&&
(c.params.winid.close(),c.params.winid=null)}),e=j.toJSON(g.dlayer.el),g.json=JSON.stringify(e),j.selection=!1,h.divjq.css("z-index",0),j.clear()),"hide"===b&&(g.show=!1);return this}};a.Fabric.displayShapeLayers=function(){var a;if(this!==this.display.image){if(this.display.image&&this.display.image.layers)for(a in this.display.image.layers)this.display.image.layers.hasOwnProperty(a)&&this.display.image.showShapeLayer(a,!1);if(this.layers)for(a in this.layers)this.layers.hasOwnProperty(a)&&this.showShapeLayer(a,
!0)}};a.Fabric.getShapeLayer=function(a){var b,d;if(!a)return null;d=this.layers[a];if(!d){b=this.display.layers[a];if(!b)return null;this.layers[a]={};d=this.layers[a];d.show=!0;d.nshape=0;d.dlayer=b;d.opts=d.dlayer.opts;d.canvas=d.dlayer.canvas;d.canvas.calcOffset()}return d};a.Fabric._parseShapeOptions=function(c,b,d){var e,f,g,h,j,k,m,n={},p={};h="main"===this.display.layers[c].dtype?this.rgb.sect.zoom:1;j=h/("main"===this.display.layers[c].dtype?this.binning.bin||1:1);if(b.remove)return{remove:b.remove};
p.tags=[];if(b.tags)if("string"===typeof b.tags){f=b.tags.toLowerCase().split(",");for(c=0;c<f.length;c++)p.tags[c]=f[c].trim()}else if($.isArray(b.tags))for(c=0;c<b.tags.length;c++)p.tags[c]=b.tags[c].trim();void 0!==b.angle&&(n.angle=-b.angle);void 0!==b.x&&void 0!==b.y&&(e=this.imageToDisplayPos(b),n.left=e.x,n.top=e.y);void 0!==b.left&&(n.left=b.left);void 0!==b.top&&(n.top=b.top);void 0===n.left&&(n.left=d&&void 0!==d.left?d.left:this.display.canvasjq.attr("width")/2-1);void 0===n.top&&(n.top=
d&&void 0!==d.top?d.top:this.display.canvasjq.attr("height")/2-1+1);b.dx&&(n.left+=b.dx);b.dy&&(n.top-=b.dy);switch(b.shape){case "annulus":p.radii=[];if(void 0!==b.radii)if("string"===typeof b.radii){p.radii=b.radii.replace(/ /g,"").split(",");for(e=c=0;c<p.radii.length;c++)""!==p.radii[c]&&(p.radii[e++]=parseInt(p.radii[c],10))}else p.radii=b.radii;else{b.ireg&&a.SCALEIREG&&(b.iradius&&(b.iradius/=j),b.oradius&&(b.oradius/=j));h=(b.oradius-b.iradius)/b.nannuli;j=b.nannuli+1;for(c=0;c<j;c++)f=b.iradius+
h*c,p.radii.push(f)}break;case "box":b.ireg&&a.SCALEIREG&&(b.width&&(b.width/=j),b.height&&(b.height/=j));break;case "circle":b.ireg&&a.SCALEIREG&&b.radius&&(b.radius/=j);break;case "ellipse":b.ireg&&a.SCALEIREG&&(b.r1&&(b.r1/=j),b.r2&&(b.r2/=j));break;case "point":switch(b.ptshape){case "box":b.width=2*b.ptsize;b.height=2*b.ptsize;break;case "circle":b.radius=b.ptsize;break;case "ellipse":b.rx=b.ptsize,b.ry=b.ptsize/2}b.lockRotation=!0;b.lockScalingX=!0;b.lockScalingY=!0;b.lockUniScaling=!0;b.hasControls=
!1;b.hasRotatingPoint=!1;b.hasBorders=!0;break;case "line":case "polygon":if(b.pts&&b.pts.length){if("string"===typeof b.pts){g=b.pts.replace(/ /g,"").split(",");f=g.length;if("string"===typeof g[0])for(c=0;c<f;c++)g[c]=parseFloat(g[c]);b.pts=[];for(e=c=0;c<f;c+=2,e++)b.pts[e]={x:g[c],y:g[c+1]}}f=b.pts.length;for(c=0;c<f;c++)b.pts[c]=this.imageToDisplayPos(b.pts[c]);b.left&&b.top?g={x:b.left,y:b.top}:(g=a.centroidPolygon(b.pts),n.left=g.x,n.top=g.y);b.points=[];for(c=0;c<f;c++)e={x:(b.pts[c].x-g.x)/
h,y:(b.pts[c].y-g.y)/h},b.points.push(e)}else"polygon"===b.shape&&b.polypoints?b.points=b.polypoints:"line"===b.shape&&b.linepoints&&(b.points=b.linepoints);if(b.ireg&&a.SCALEIREG){f=b.points.length;for(c=0;c<f;c++)b.points[c].x/=j,b.points[c].y/=j}}for(k in b)if(b.hasOwnProperty(k))switch(k){case "tags":case "x":case "y":case "dx":case "dy":case "pts":case "left":case "top":case "angle":case "radii":case "ireg":break;case "type":case "originX":case "originY":case "width":case "height":case "scaleX":case "scaleY":case "flipX":case "flipY":case "opacity":case "cornerSize":case "transparentCorners":case "hoverCursor":case "padding":case "borderColor":case "cornerColor":case "centeredScaling":case "centeredRotation":case "fill":case "fillRule":case "backgroundColor":case "stroke":case "strokeWidth":case "strokeDashArray":case "strokeLineCap":case "strokeLineJoin":case "strokeMiterLimit":case "shadow":case "borderOpacityWhenMoving":case "borderScaleFactor":case "transformMatrix":case "minScaleLimit":case "selectable":case "evented":case "visible":case "hasControls":case "hasBorders":case "hasRotatingPoint":case "rotatingPointOffset":case "perPixelTargetFind":case "includeDefaultValues":case "clipTo":case "lockMovementX":case "lockMovementY":case "lockRotation":case "lockScalingX":case "lockScalingY":case "lockUniScaling":case "radius":case "rx":case "ry":case "points":case "selectionLineWidth":case "fontFamily":case "fontSize":case "fontStyle":case "fontWeight":case "text":case "textDecoration":case "textAlign":case "lineHeight":case "textBackgroundColor":n[k]=
b[k];break;case "shape":m=b[k];break;default:p[k]=b[k]}if(!(b=p.color)){b=p.tags;k=p.tagcolors;var r,l;k=k||{};for(r in k)if(k.hasOwnProperty(r)&&(c=r.split("_"),0===$(b).not(c).length&&0===$(c).not(b).length)){l=k[r];break}if(!l)for(r in k)if(k.hasOwnProperty(r)&&(c=r.split("_"),0===$(b).not(c).length)){l=k[r];break}if(!l)for(r in k)if(k.hasOwnProperty(r)&&(c=r.split("_"),0===$(c).not(b).length)){l=k[r];break}b=l=l||d&&d.get("stroke")||k.defcolor||a.globalOpts.defcolor||"#000000"}n.stroke=b;n.selectColor=
n.stroke;n.cornerColor=n.stroke;n.borderColor=n.stroke;void 0!==p.fixinplace&&(d=p.fixinplace,void 0===n.lockMovementX&&(n.lockMovementX=d),void 0===n.lockMovementY&&(n.lockMovementY=d),void 0===n.lockRotation&&(n.lockRotation=d),void 0===n.lockScalingX&&(n.lockScalingX=d),void 0===n.lockScalingY&&(n.lockScalingY=d),void 0===n.hasControls&&(n.hasControls=!d),void 0===n.hasRotatingPoint&&(n.hasRotatingPoint=!d),void 0===n.hasBorders&&(n.hasBorders=!d));return{shape:m,opts:n,params:p}};a.Fabric.addShapes=
function(c,b,d){var e,f,g,h,j,k,m,n,p,r=[],l={};if((j=this.getShapeLayer(c))&&j.show){k=j.canvas;"main"===this.display.layers[c].dtype?(m=this.rgb.sect.zoom,n=this.binning.bin||1):n=m=1;if("string"===typeof b)e=this.parseRegions(b),b="string"===typeof e?[{shape:e}]:e;else if(!$.isArray(b))if("object"===typeof b)b=[b];else return;if("string"===typeof d)try{g=JSON.parse(d)}catch(q){return a.error("can't parse shape opts: "+d,q),null}else g=d;k.size()||(d=this.display.layers[c],"regions"===c&&d.opts.canvas.zindex++,
d.divjq.css("z-index",d.opts.canvas.zindex));h=$.extend(!0,{},a.Fabric.opts,j.opts,g);for(g=0;g<b.length;g++){d=$.extend(!0,{},h,b[g]);f=a.Fabric._parseShapeOptions.call(this,c,d);if(f.remove){if(!0===f.remove||"true"===f.remove)f.remove="all";if(!1!==f.remove&&"false"!==f.remove){this.removeShapes(c,f.remove);continue}}if(f.shape){d=f.opts;l=f.params;l.id=++j.nshape;switch(f.shape){case "annulus":l.shape="annulus";f=d.top;p=d.left;d.top=0;d.left=0;if(l.radii)for(e=0;e<l.radii.length;e++)d.radius=
l.radii[e],r.push(new fabric.Circle(d));d.top=f;d.left=p;d.width=2*d.radius;d.height=2*d.radius;e=new fabric.Group(r,d);break;case "box":l.shape="box";e=new fabric.Rect(d);break;case "circle":l.shape="circle";e=new fabric.Circle(d);break;case "ellipse":l.shape="ellipse";d.rx=l.r1;d.ry=l.r2;e=new fabric.Ellipse(d);break;case "point":l.shape="point";switch(l.ptshape){case "box":e=new fabric.Rect(d);break;case "circle":e=new fabric.Circle(d);break;case "ellipse":e=new fabric.Ellipse(d);break;default:e=
new fabric.Rect(d)}break;case "line":l.shape="line";e=new fabric.Polyline(d.points,d);break;case "polygon":l.shape="polygon";e=new fabric.Polygon(d.points,d,!0);break;case "text":l.shape="text";l.text=d.text||"Double-click to add text here";d.fill=d.stroke;d.strokeWidth=0;e=new fabric.Text(l.text,d);break;default:a.error("unknown shape: "+f.shape)}k.add(e);l.layerName=c;l.sw1=e.strokeWidth;l.listonchange=!1;e.params=l;if(j.opts.panzoom)switch(l.shape){case "point":case "text":break;default:e.scale(m/
n)}e.rescaleBorder();a.Fabric._updateShape.call(this,c,e,null,"add",l)}}(void 0===l.redraw||l.redraw)&&k.renderAll();return l.id}};a.Fabric.selectShapes=function(a,b,d){var e,f,g,h,j=this;if(!this.layers||!a||!this.layers[a])return null;b=b||"all";a=this.layers[a].canvas;f=a.getActiveGroup();g={group:null};switch(typeof b){case "object":b.params&&(g.group=f&&f.contains(b)?f:null,d.call(j,b,g));break;case "number":a.forEachObject(function(a){a.params&&b===a.params.id&&(g.group=f&&f.contains(a)?f:null,
d.call(j,a,g))});break;case "string":h=b.toLowerCase().replace("box","rect"),"selected"===b?a.getActiveObject()?(a=a.getActiveObject(),a.params&&(g.group=null,d.call(j,a,g))):f&&(g.group=f,f.forEachObject(function(a){a.params&&d.call(j,a,g)})):a.forEachObject(function(a){if(a.params)if(g.group=f&&f.contains(a)?f:null,"all"===b)d.call(j,a,g);else if(b===a.stroke)d.call(j,a,g);else if(h===a.type)d.call(j,a,g);else if(a.params.tags)for(e=0;e<a.params.tags.length;e++)b===a.params.tags[e]&&d.call(j,a,
g)})}return this};a.Fabric.updateShapes=function(c,b,d,e){var f=this;this.selectShapes(c,b,function(b,h){a.Fabric._updateShape.call(f,c,b,h,d,e)});return this};a.Fabric._updateShape=function(c,b,d,e,f){var g,h,j,k,m,n,p,r,l={},q=this.layers[c],s=function(a){return a.toFixed(1)};d=d||{};f=f||{};n=this.display;j="main"===this.display.layers[c].dtype?this.rgb.sect.zoom:1;l.mode=e||"update";l.id=b.params.id;l.shape=b.params.shape;l.layer=c;l.color=b.stroke;l.tags=b.params.tags;e=b.getCenterPoint();d.group&&
(p=d.group.getCenterPoint(),e={x:e.x+p.x,y:e.y+p.y});p=this.displayToImagePos(e);l.x=p.x;l.y=p.y;l.imsys="image";l.lcs=this.imageToLogicalPos(p);"image"===this.params.wcssys?(k=l.x,m=l.y):(k=l.lcs.x,m=l.lcs.y,l.imsys=l.lcs.sys);l.angle=-b.angle;d.group&&(l.angle-=d.group.angle);for(;0>l.angle;)l.angle+=360;for(;360<l.angle;)l.angle-=360;e=1*(b.scaleX/j);j=1*(b.scaleY/j);d.group&&(e*=d.group.scaleX,j*=d.group.scaleY);switch(l.shape){case "annulus":l.shape="annulus";l.radii=[];l.imstr="annulus("+s(k)+
", "+s(m)+", ";h="annulus "+l.x+" "+l.y+" ";r=b.getObjects();j=r.length;for(d=0;d<j;d++)k=r[d].radius*e,l.imstr+=s(k),h+=l.x+" "+l.y+" "+(l.x+k)+" "+l.y+" ",l.imstr=d===j-1?l.imstr+")":l.imstr+", ",l.radii.push(k);break;case "box":l.shape="box";l.width=b.width*e;l.height=b.height*j;l.imstr="box("+s(k)+", "+s(m)+", "+s(l.width)+", "+s(l.height)+", "+l.angle.toFixed(4)+")";h="box "+l.x+" "+l.y+" "+l.x+" "+l.y+" "+(l.x+l.width)+" "+l.y+" "+l.x+" "+l.y+" "+l.x+" "+(l.y+l.height)+" "+l.angle*Math.PI/180;
break;case "circle":l.radius=b.radius*e;l.imstr="circle("+s(k)+", "+s(m)+", "+s(l.radius)+")";h="circle "+l.x+" "+l.y+" "+l.x+" "+l.y+" "+(l.x+l.radius)+" "+l.y;break;case "ellipse":l.r1=b.width*e/2;l.r2=b.height*j/2;l.imstr="ellipse("+s(k)+", "+s(m)+", "+s(l.r1)+", "+s(l.r2)+", "+l.angle.toFixed(4)+")";h="ellipse "+l.x+" "+l.y+" "+l.x+" "+l.y+" "+(l.x+l.r1)+" "+l.y+" "+l.x+" "+l.y+" "+l.x+" "+(l.y+l.r2)+" "+l.angle*Math.PI/180;break;case "point":l.width=b.width*e;l.height=b.height*j;l.imstr="point("+
s(k)+", "+s(m)+")";h="point "+l.x+" "+l.y;break;case "line":case "polygon":l.imstr=l.shape+"(";h=l.shape+" ";l.pts=[];for(d=0;d<b.points.length;d++)0<d&&(l.imstr+=", ",h+=" "),k={x:l.x+b.points[d].x*e,y:l.y-b.points[d].y*j},k=a.rotatePoint(k,l.angle,{x:l.x,y:l.y}),"image"===this.params.wcssys?l.imstr+=s(k.x)+", "+s(k.y):(m=this.imageToLogicalPos(k),l.imstr+=s(m.x)+", "+s(m.y)),h+=k.x+" "+k.y,l.pts.push(k),"line"===l.shape&&(0===d?r=0:(m=l.pts[d-1],r+=Math.sqrt((k.x-m.x)*(k.x-m.x)+(k.y-m.y)*(k.y-m.y))));
l.imstr="line"===l.shape?l.imstr+(') {"size":'+s(r)+',"units":"pixels"}'):l.imstr+")";break;case "text":l.imstr="text("+s(k)+", "+s(m)+', "'+b.text+'")',l.text=b.text,h="text "+l.x+" "+l.y+' "'+b.text+'"'}if(this.wcs&&0<this.wcs){if("regions"===c&&!1!==f.dowcsstr||"regions"!==c&&!0===f.dowcsstr)l.wcsstr=a.reg2wcs(this.wcs,h).replace(/;$/,"");h=a.pix2wcs(this.wcs,p.x,p.y).trim().split(/\s+/);l.ra=h[0];l.dec=h[1];l.wcssys=h[2]}l.data=b.params.data;b.set("pub",l);b.params.winid&&($(b.params.winid).is(":visible")?
a.Regions.initConfigForm.call(this,b):b.params.winid=null);if(f.nocb)return l;if("regions"===c&&this.params.xeqonchange&&q.show&&this.onregionschange)try{this.params.xeqonchange=!1,a.xeqByName(this.onregionschange,window,this,l)}catch(t){a.log("error in xeqonchange: %s [%s]\n%s",this.id,t.message,a.strace(t))}finally{this.params.xeqonchange=!0}if(this.params.xeqonchange&&q.show&&q.opts.onchange)try{this.params.xeqonchange=!1,a.xeqByName(q.opts.onchange,window,this,l)}catch(v){a.log("error in onchange: %s [%s]\n%s",
this.id,v.message,a.strace(v))}finally{this.params.xeqonchange=!0}f="on"+c+"change";for(g in n.pluginInstances)if(n.pluginInstances.hasOwnProperty(g)&&(c=n.pluginInstances[g],b=c.plugin.opts,c.isActive(f)))try{b[f].call(c,this,l)}catch(u){c.errLog(f,u)}return l};a.Fabric.removeShapes=function(c,b){var d=this,e,f;if(e=this.getShapeLayer(c))return f=e.canvas,this.selectShapes(c,b,function(b,e){a.Fabric._updateShape.call(d,c,b,e,"remove");e&&e.group&&e.group.remove(b);b.params&&b.params.winid&&b.params.winid.close();
f.remove(b)}),f.getActiveGroup()&&f.discardActiveGroup(),f.renderAll(),this};a.Fabric.getShapes=function(a,b){var d=[];this.selectShapes(a,b,function(a){d.push(a.pub||{})});return d};a.Fabric.changeShapes=function(c,b,d){var e,f,g,h,j,k,m,n,p,r,l,q,s=this;if((j=this.getShapeLayer(c))&&d)return k=j.canvas,"main"===this.display.layers[c].dtype?(l=this.rgb.sect.zoom,q=this.binning.bin||1):q=l=1,m=k.getActiveObject(),this.selectShapes(c,b,function(b,v){h=$.extend(!0,{},b.params,d);g=a.Fabric._parseShapeOptions.call(this,
c,h,b);if(g.remove){if(!0===g.remove||"true"===g.remove)g.remove="all";if(!1!==g.remove&&"false"!==g.remove){this.removeShapes(c,g.remove||"all");return}}switch(b.params.shape){case "text":g.opts.stroke&&(g.opts.fill=g.opts.stroke),g.opts.strokeWidth=0}b.set(g.opts);b.params=$.extend(!1,{},b.params,g.params);switch(b.params.shape){case "annulus":if(d.radii&&d.radii.length){p=b.get("stroke");b.forEachObject(function(a){b.remove(a);k.remove(a)});n=b.params.radii.length;for(e=r=0;e<n;e++)f=new fabric.Circle({radius:b.params.radii[e],
stroke:p}),r=Math.max(r,b.params.radii[e]),b.add(f);b.scaleX=l/q;b.scaleY=l/q;b.width=2*r;b.height=2*r;m===b&&k.setActiveObject(b)}break;case "box":d.width&&(b.scaleX=l/q);d.height&&(b.scaleY=l/q);break;case "circle":d.radius&&(b.scaleX=l/q,b.scaleY=l/q);break;case "ellipse":d.r1&&(b.rx=d.r1,b.scaleX=l/q,b.width=2*b.rx);d.r2&&(b.ry=d.r2,b.scaleY=l/q,b.height=2*b.ry);break;case "line":case "polygon":d.points&&d.points.length&&(b.scaleX=l/q,b.scaleY=l/q),m===b&&(a.Fabric.removePolygonAnchors(j.dlayer,
b),a.Fabric.addPolygonAnchors(j.dlayer,b)),a.resetPolygonCenter(b)}b.rescaleBorder();b.setCoords();a.Fabric._updateShape.call(s,c,b,v,"update")}),(void 0===d.redraw||d.redraw)&&k.renderAll(),this};a.Fabric.refreshShapes=function(c){var b,d,e,f,g,h,j,k,m,n=!1,p=this;if(m=this.getShapeLayer(c))return"main"===this.display.layers[c].dtype&&(n=!0),n?(e=this.binning.bin,f=this.rgb.sect.zoom,g=this.binning.obin/this.rgb.sect.ozoom*f/e,h=this.binning.obin/this.rgb.sect.ozoom*f/e):(e=1,h=g=f=this.rgb.sect.zoom),
e=m.canvas,e.getActiveGroup()&&e.discardActiveGroup(),d=e.getActiveObject(),this.selectShapes(c,"all",function(c){b=p.logicalToDisplayPos(c.pub.lcs);c.setLeft(b.x);c.setTop(b.y);switch(c.params.shape){case "point":case "text":break;default:j=g,k=h,n&&(j*=c.scaleX,k*=c.scaleY),c.scaleX=j,c.scaleY=k,c.rescaleBorder()}c.setCoords();switch(c.type){case "polyline":case "polygon":d===c&&(a.Fabric.removePolygonAnchors(m.dlayer,c),a.Fabric.addPolygonAnchors(m.dlayer,c))}}),n&&(this.binning.obin=this.binning.bin,
this.rgb.sect.ozoom=this.rgb.sect.zoom),e&&e.renderAll(),this};a.Fabric.addPolygonPoint=function(c,b,d){var e,f,g,h,j,k,m,n,p,r={},l,q,s,t,v,u=Number.MAX_VALUE;if(b&&b.points){r=a.eventToDisplayPos(d);d=b.getCenterPoint().x;g=b.getCenterPoint().y;d=(r.x-d)/b.get("scaleX");l=(r.y-g)/b.get("scaleY");for(g=-b.get("angle")*Math.PI/180;g>2*Math.PI;)g-=2*Math.PI;r=Math.cos(g)*d-Math.sin(g)*l;l=Math.sin(g)*d+Math.cos(g)*l;d=b.points;for(g=0;g<d.length;g++)f=d[g],h=d[(g+1)%d.length],j=f.x<h.x?f.x:h.x,k=f.y<
h.y?f.y:h.y,m=f.x>h.x?f.x:h.x,n=f.y>h.y?f.y:h.y,e=f.x-h.x,f=f.y-h.y,p=Math.sqrt(e*e+f*f),0!==p&&(e/=p,f/=p),p=r-h.x,v=l-h.y,p=p*e+v*f,e=h.x+e*p,h=h.y+f*p,e<j?e=j:e>m&&(e=m),h<k?h=k:h>n&&(h=n),j=(e-r)*(e-r)+(h-l)*(h-l),j<u&&(u=j,q=e,s=h,t=g===d.length?0:g);c=this.getShapeLayer(c);a.Fabric.removePolygonAnchors(c.dlayer,b);d.splice(t+1,0,{x:q,y:s});c.canvas.setActiveObject(b)}};a.Fabric.removePolygonPoint=function(c,b){var d,e,f,g;b&&b.polyparams&&(e=b.polyparams.polygon,f=e.points,g=b.polyparams.point,
d=this.getShapeLayer(c),a.Fabric.removePolygonAnchors(d.dlayer,e),f.splice(g,1),a.resetPolygonCenter(e),d.canvas.setActiveObject(e))};a.Fabric.addPolygonAnchors=function(c,b){var d,e,f={},g=c.canvas,h=function(){var b=this.polyparams.polygon,d=this.polyparams.point,e=b.get("points"),h=c.display.image;b.angle?f=a.rotatePoint({x:this.left,y:this.top},-b.angle,{x:b.left,y:b.top}):(f.x=this.left,f.y=this.top);e[d].x=(f.x-b.left)/b.scaleX;e[d].y=(f.y-b.top)/b.scaleY;a.resetPolygonCenter(b);a.Fabric._updateShape.call(h,
b.params.layerName,b,null,"update");h&&(h.params.listonchange||b.params.listonchange)&&h.listRegions(b,2);g.renderAll()},j=function(c){var b,d={};for(b=0;b<c.params.anchors.length;b++)d.x=c.left+c.points[b].x*c.scaleX,d.y=c.top+c.points[b].y*c.scaleY,c.angle&&(d=a.rotatePoint(d,c.angle,{x:c.left,y:c.top})),c.params.anchors[b].set({left:d.x,top:d.y,angle:c.angle}),c.params.anchors[b].setCoords();c._calcDimensions(!0);g.renderAll()};if(!b.params.anchors){b.params.anchors=[];for(d=0;d<b.points.length;d++)f.x=
b.left+b.points[d].x*b.scaleX,f.y=b.top+b.points[d].y*b.scaleY,b.angle&&(f=a.rotatePoint(f,b.angle,b.getCenterPoint())),e=new fabric.Rect({left:f.x,top:f.y,hasControls:!1,hasRotatingPoint:!1,hasBorders:!1,selectable:!0,fill:b.get("stroke"),hoverCursor:"pointer",width:a.Fabric.opts.cornerSize,height:a.Fabric.opts.cornerSize,padding:2}),e.on("moving",h),e.polyparams={},e.polyparams.polygon=b,e.polyparams.point=d,b.params.anchors[d]=e,g.add(e);b.on("moving",function(){j(b)});b.on("rotating",function(){j(b)});
b.on("scaling",function(){j(b)});b.setCoords()}};a.Fabric.removePolygonAnchors=function(a,b){var d,e=a.canvas;if(b.params&&b.params.anchors){for(d=0;d<b.params.anchors.length;d++)e.remove(b.params.anchors[d]);delete b.params.anchors}};a.resetPolygonCenter=function(c){var b,d,e,f={};c._calcDimensions();d=(c.minX+c.width/2)*c.scaleX;b=(c.minY+c.height/2)*c.scaleY;c.angle?f=a.rotatePoint({x:c.left+d,y:c.top+b},c.angle,{x:c.left,y:c.top}):(f.x=c.left+d,f.y=c.top+b);if(5<=fabric.version.split(".")[1]){d/=
c.scaleX;e=b/c.scaleY;for(b=0;b<c.points.length;b++)c.points[b].x-=d,c.points[b].y-=e}c.left=f.x;c.top=f.y;c.setCoords()};a.Fabric.print=function(c){var b,d,e,f,g;d=sprintf("width=%s,height=%s,menubar=1,toolbar=1,status=0,scrollbars=1,resizable=1",this.display.canvasjq.attr("width"),this.display.canvasjq.attr("height"));c=c||{};g=0;if(d=window.open(null,this.id,d)){d.document.open();d.document.write("<html><body style='padding: 0px; margin: 0px' onload='window.print(); return false'>");e=this.display.canvas.toDataURL("image/png");
f=sprintf("<div style='position:absolute; left:%spx; top:%spx'>",0,g);d.document.write(f);d.document.write("<img src='");d.document.write(e);d.document.write("'>");d.document.write("</div>");for(b in this.layers)this.layers.hasOwnProperty(b)&&("main"===this.layers[b].dlayer.dtype&&this.layers[b].show)&&(f=sprintf("<div style='position:absolute; left:%spx; top:%spx'>",0,g),d.document.write(f),d.document.write(this.layers[b].dlayer.canvas.toSVG()),d.document.write("</div>"));if(void 0===c.colorbar||
c.colorbar)if((c=this.display.pluginInstances.JS9Colorbar)&&c.isActive())g+=2,e=c.colorbarjq[0].toDataURL("image/png"),g+=this.display.height,f=sprintf("<div style='position:absolute; left:%spx; top:%spx'>",0,g),d.document.write(f),d.document.write(sprintf("<img ")),d.document.write(sprintf(" src='%s'>",e)),d.document.write("</div>"),e=c.textjq[0].toDataURL("image/png"),g+=c.colorbarjq.height()+1,f=sprintf("<div style='position:absolute; left:%spx; top:%spx'>",0,g),d.document.write(f),d.document.write(sprintf("<img style='width:%spx;'",
this.display.width)),d.document.write(sprintf("src='%s'>",e)),d.document.write("</div>");d.document.write("</body></html>");d.document.close()}else a.error("could not create print window (check your pop-up blockers)")};a.Fabric.initGraphics=function(){var c;a.Display.prototype.newShapeLayer=a.Fabric.newShapeLayer;a.Image.prototype.addShapes=a.Fabric.addShapes;a.Image.prototype.selectShapes=a.Fabric.selectShapes;a.Image.prototype.updateShapes=a.Fabric.updateShapes;a.Image.prototype.updateShape=a.Fabric._updateShape;
a.Image.prototype.getShapes=a.Fabric.getShapes;a.Image.prototype.changeShapes=a.Fabric.changeShapes;a.Image.prototype.removeShapes=a.Fabric.removeShapes;a.Image.prototype.refreshShapes=a.Fabric.refreshShapes;a.Image.prototype.getShapeLayer=a.Fabric.getShapeLayer;a.Image.prototype.showShapeLayer=a.Fabric.showShapeLayer;a.Image.prototype.displayShapeLayers=a.Fabric.displayShapeLayers;a.Image.prototype.print=a.Fabric.print;for(c in a.Fabric.opts)a.Fabric.opts.hasOwnProperty(c)&&(fabric.Object.prototype[c]=
a.Fabric.opts[c])};a.Fabric.initGraphics();a.Regions={};a.Regions.CLASS="JS9";a.Regions.NAME="Regions";a.Regions.opts={canvas:{zindex:a.SHAPEZINDEX+2},panzoom:!0,tags:"source,include",strokeWidth:2,iradius:0,oradius:30,nannuli:10,width:60,height:60,radius:30,r1:30,r2:20,ptshape:"box",ptsize:2,linepoints:[{x:-30,y:30},{x:30,y:-30}],polypoints:[{x:-30,y:30},{x:30,y:30},{x:0,y:-30}],fontFamily:"Helvetica",fontSize:14,fontStyle:"normal",fontWeight:300,textAlign:"left",angle:0,aradius1:4,aradius2:8,configURL:"./params/regionsconfig.html",
tagcolors:{include_source:"#00FF00",exclude_source:"#FF0000",include_background:"#FFD700",exclude_background:"#FF8C00",source:"#00FF00",background:"#FFD700",defcolor:"#00FF00"},onmousedown:function(c,b,d,e){var f;!a.specialKey(d)&&e.params&&(b=(new Date).getTime(),e.params.lasttime&&b-e.params.lasttime<a.DBLCLICK&&(f=!0),e.params.lasttime=b);f?e.params.winid||($("#dhtmlwindowholder").arrive("#regionsConfigForm",{onceOnly:!0},function(){e.pub&&a.Regions.initConfigForm.call(c,e)}),e.params.winid=a.allinone?
c.displayAnalysis("params",a.allinone.regionsConfigHTML,"Region Configuration"):c.displayAnalysis("params",a.InstallDir(a.Regions.opts.configURL),"Region Configuration")):a.specialKey(d)&&("polygon"===e.type||"polyline"===e.type?(a.Fabric.addPolygonPoint.call(c,e.params.layerName,e,d),a.Fabric._updateShape.call(c,e.params.layerName,e,null,"update")):e.polyparams&&e.polyparams.polygon&&(f=e.polyparams.polygon,a.Fabric.removePolygonPoint.call(c,f.params.layerName,e,d),a.Fabric._updateShape.call(c,f.params.layerName,
f,null,"update")))},onmouseup:function(){var a,b=[];this.getActiveObject()&&b.push(this.getActiveObject());this.getActiveGroup()&&(b=this.getActiveGroup().getObjects());for(a=0;a<b.length;a++)b[a].polyparams&&this.setActiveObject(b[a].polyparams.polygon)},onchange:null};a.Regions.init=function(c){var b;a.Image.prototype.parseRegions=a.Regions.parseRegions;a.Image.prototype.saveRegions=a.Regions.saveRegions;a.Image.prototype.listRegions=a.Regions.listRegions;b=this.display.newShapeLayer(c||"regions",
a.Regions.opts);b.canvas.on("mouse:up",function(){var a,c,f=[];if(b.display.image){c=b.display.image;this.getActiveObject()&&f.push(this.getActiveObject());this.getActiveGroup()&&(f=this.getActiveGroup().getObjects());for(a=0;a<f.length;a++)if(f[a].params){c.params.listonchange?c.listRegions("all",2):f[a].params.listonchange&&c.listRegions("selected",2);break}}});return this};a.Regions.onchange=function(c,b){if(a.Regions.opts.onchange&&"function"===typeof a.Regions.opts.onchange)try{a.Regions.opts.onchange(c,
b)}catch(d){}};a.Regions.initConfigForm=function(a){var b,d,e=a.params.winid,f="#"+$(e).attr("id")+" #regionsConfigForm ";$(f+"."+a.pub.shape).each(function(){$(this).removeClass("nodisplay")});$(f+".val").each(function(){d="";b=$(this).attr("name");switch(b){case "pts":a.pub.pts?a.pub.pts.forEach(function(a){d&&(d+=", ");d+=sprintf("%s, %s",a.x,a.y)}):a.pub.imstr&&(d=a.pub.imstr.replace(/^.*\(/,"").replace(/\)$/,""));break;default:void 0!==a.pub[b]&&(d=a.pub[b])}$(this).val(d)});a.pub.wcsstr&&$(f+
".wcs").removeClass("nodisplay");void 0===a.params.listonchange&&(a.params.listonchange=!1);a.params.listonchange?$(f+"[name='listonchange']").attr("checked","checked"):$(f+"[name='listonchange']").removeAttr("checked");void 0===a.params.fixinplace&&(a.params.fixinplace=!1);a.params.fixinplace?$(f+"[name='fixinplace']").attr("checked","checked"):$(f+"[name='fixinplace']").removeAttr("checked");switch(a.pub.shape){case "box":case "ellipse":case "line":case "polygon":case "text":$(f+".angle").removeClass("nodisplay")}$(f).data("im",
this);$(f).data("shape",a);$(f).data("winid",e)};a.Regions.processConfigForm=function(c,b,d){var e,f,g,h=d.length,j={},k=function(a,c,b){return"remove"===c||void 0!==a.pub[c]&&String(a.pub[c])!==b||void 0!==a.params[c]&&String(a.params[c])!==b?!0:!1},m=function(a){return"true"===a?!0:"false"===a?!1:""===a||isNaN(a)?a:parseFloat(a)};for(e=0;e<h;e++)switch(f=d[e].name,g=d[e].value,f){case "x":k(c,f,g)&&(j[f]=m(g),void 0===j.y&&(j.y=c.pub.y));break;case "y":k(c,f,g)&&(j[f]=m(g),void 0===j.x&&(j.x=c.pub.x));
break;default:k(c,f,g)&&(j[f]=m(g))}this.changeShapes(c.pub.layer,c,j);a.Regions.initConfigForm.call(this,c,b)};a.Regions.listRegions=function(a,b){var d,e,f,g,h,j,k="",m="none",n=!1,p=[];void 0===b&&(b=2);p=this.getShapes("regions",a);f=p.length;if(b)for(d=0;d<f;d++)if(e=p[d],"source,include"!==e.tags.join(",")){n=!0;break}for(d=0;d<f;d++)e=p[d],h=e.tags.join(","),j=0<=h.indexOf("exclude")?"-":"",n&&(g=" # "+h),e.wcsstr&&"image"!==this.params.wcssys&&"physical"!==this.params.wcssys?("wcs"!==m&&("none"!==
m&&(k+="; "),k+=this.params.wcssys,m="wcs"),k+="; "+j+e.wcsstr):e.imstr&&(m!==e.imsys&&("none"!==m&&(k+="; "),k+=e.imsys,m=e.imsys),k+="; "+j+e.imstr),n&&(k+=g);1<b&&this.displayMessage("regions",k);return k};a.Regions.parseRegions=function(c){var b=[],d,e,f,g,h,j,k,m,n,p,r,l,q=/(annulus)|(box)|(circle)|(ellipse)|(line)|(polygon)|(point)|(text)/,s=/(fk4)|(fk5)|(icrs)|(galactic)|(ecliptic)|(image)|(physical)/,t=/\(\s*([^)]+?)\s*\)/,v=/(\{[^}]*\})/,u=/\s*,\s*/,w=function(c){c=a.saostrtod(c);var b=String.fromCharCode(a.saodtype());
switch(b){case '"':c/=3600;break;case "'":c/=60;break;case "r":c*=180/Math.PI}return{dval:c,dtype:b}},y=function(c,b){var d,e;e=w(c);d=w(b);if(":"===e.dtype||":"===d.dtype)n=!0;m||n?(":"===e.dtype&&("galactic"!==k&&"ecliptic"!==k)&&(e.dval*=15),d=a.wcs2pix(this.wcs,e.dval,d.dval).split(/ +/),e=parseFloat(d[0])-1,d=parseFloat(d[1])-1):"physical"===k?(d=this.logicalToImagePos({x:e.dval,y:d.dval}),e=d.x,d=d.y):(e=e.dval,d=d.dval);return[e,d]},x=function(a,c){var b=w(a);if((m||n)&&b.dtype&&"."!==b.dtype)b.dval=
Math.abs(b.dval/r["cdelt"+c]);return b.dval};c=c.trim();if(!c.match(/(\(|\{|#|;|\n)/))return c;try{r=JSON.parse(a.wcsinfo(this.wcs))}catch(z){r={cdelt1:1,cdelt2:1,crot:0,imflip:0}}j=this.getWCSSys();k="physical";this.setWCSSys(k);m="image"!==k&&"physical"!==k;f=c.split(/\n|;/);for(c=0;c<f.length;c++)if("#"!==f[c].trim().substr(0,1)){n=!1;g=f[c];h=void 0;d={opts:{},args:[],isregion:0};d.cmd=0<=g.indexOf("(")?g.split("(")[0].trim().toLowerCase():0<=g.indexOf("{")?g.split("{")[0].trim().toLowerCase():
0<=g.indexOf("#")?g.split("#")[0].trim().toLowerCase():g.trim().toLowerCase();d.cmd&&(d.isregion=0<=d.cmd.search(q));d.comment=g.split("#")[1];d.comment&&(d.comment=d.comment.trim().toLowerCase());if((h=v.exec(g))&&h[1])try{d.opts=JSON.parse(h[1].trim())}catch(A){d.opts={}}if((h=t.exec(g))&&h[1])d.args=h[1].split(u);d.isregion&&0===d.cmd.indexOf("-")&&(d.cmd=d.cmd.slice(1),d.comment=d.comment?d.comment+",exclude":"exclude");h=d;l=h.args.length;if(h.isregion){g=$.extend(!0,{},h.opts);g.shape=h.cmd;
2<=l&&(p=y.call(this,h.args[0],h.args[1]),g.x=p[0],g.y=p[1]);switch(h.cmd){case "annulus":g.radii=[];for(d=2;d<l;d++)g.radii.push(x.call(this,h.args[d],1));break;case "box":3<=l&&(g.width=x.call(this,h.args[2],1));4<=l&&(g.height=x.call(this,h.args[3],2));5<=l&&(g.angle=w(h.args[4]).dval);break;case "circle":3<=l&&(g.radius=x.call(this,h.args[2],1));break;case "ellipse":3<=l&&(g.r1=x.call(this,h.args[2],1));4<=l&&(g.r2=x.call(this,h.args[3],2));5<=l&&(g.angle=w(h.args[4]).dval);break;case "line":case "polygon":g.pts=
[];for(e=d=0;d<l;d+=2,e++)p=y.call(this,h.args[d],h.args[d+1]),g.pts[e]={x:p[0],y:p[1]};delete g.x;delete g.y;break;case "text":3<=l&&(d=g,e=h.args[2].replace(/^['"]/,"").replace(/['"]$/,""),d.text=e)}h.comment&&(g.tags=h.comment);b.push(g)}else h.cmd.match(s)?(this.setWCSSys(h.cmd),k=this.getWCSSys(),m="image"!==k&&"physical"!==k):("remove"===h.cmd||"delete"===h.cmd)&&b.push({remove:!0})}this.setWCSSys(j);return b};a.Regions.saveRegions=function(c,b){var d=sprintf("# Region file format: JS9 version 1.0"),
e=this.listRegions(b,1),d=sprintf("%s\n%s\n",d,e.replace(/; */g,"\n")),d=new Blob([d],{type:"text/plain;charset=utf-8"});c=c||"js9.reg";window.hasOwnProperty("saveAs")?saveAs(d,c):a.error("no saveAs function available to save region file");return c};a.Regions.keyDownCB=function(a,b,d,e){var f,g;b={evt:d};var h=d.which||d.keyCode;e=e||"regions";g=a.display.layers[e].canvas;switch(h){case 8:case 46:d.preventDefault();f="removeRegion";break;case 37:d.preventDefault();f="editRegion";b.dx=-1;break;case 38:d.preventDefault();
f="editRegion";b.dy=1;break;case 39:d.preventDefault();f="editRegion";b.dx=1;break;case 40:d.preventDefault();f="editRegion";b.dy=-1;break;case 68:f="downRegion";break;case 85:f="upRegion"}switch(f){case "removeRegion":a.removeShapes(e,"selected");a.clearMessage(e);g.fire("mouse:up");break;case "editRegion":a.changeShapes(e,"selected",b);g.fire("mouse:up");break;case "downRegion":a.selectShapes(e,"selected",function(a){g.sendToBack(a)});break;case "upRegion":a.selectShapes(e,"selected",function(a){g.bringToFront(a)})}};
a.Magnifier={};a.Magnifier.CLASS="JS9";a.Magnifier.NAME="Magnifier";a.Magnifier.opts={originX:"left",originY:"top",hasControls:!1,hasRotatingPoint:!1,hasBorders:!1,selectable:!1,zoom:4,canvas:{selection:!1},tagcolors:{defcolor:"#00FF00"}};a.Magnifier.HTML="<span><button type='button' class='JS9Button' onClick='JS9.bcall(this, \"zoomMagnifier\", \"x2\"); return false'>x2</button><button type='button' class='JS9Button' onClick='JS9.bcall(this, \"zoomMagnifier\", \"/2\"); return false'>/2</button><button type='button' class='JS9Button' onClick='JS9.bcall(this, \"zoomMagnifier\", \""+
a.Magnifier.opts.zoom+"\"); return false'>"+a.Magnifier.opts.zoom+"</button></span>";a.Magnifier.init=function(c,b){this.width=this.divjq.attr("data-width");this.width||(this.width=c||a.MAGWIDTH);this.divjq.css("width",this.width);this.width=parseInt(this.divjq.css("width"),10);this.height=this.divjq.attr("data-height");this.height||(this.height=b||a.MAGHEIGHT);this.divjq.css("height",this.height);this.height=parseInt(this.divjq.css("height"),10);this.canvas=document.createElement("canvas");this.canvasjq=
$(this.canvas);this.canvasjq.addClass("JS9Magnifier");this.canvasjq.css("z-index",a.ZINDEX);this.canvasjq.attr("width",this.width);this.canvasjq.attr("height",this.height);this.context=this.canvas.getContext("2d");a.ANTIALIAS||(this.context.imageSmoothingEnabled=!1,this.context.mozImageSmoothingEnabled=!1,this.context.webkitImageSmoothingEnabled=!1);this.containerjq=$("<div>").addClass("JS9Container").append(this.canvasjq).appendTo(this.divjq);this.display.newShapeLayer("magnifier",a.Magnifier.opts,
this.divjq)};a.Magnifier.display=function(c,b){var d,e,f,g,h,j,k,m,n,p,r,l;c&&(c.display.pluginInstances.JS9Magnifier&&"active"===c.display.pluginInstances.JS9Magnifier.status)&&(c.magnifier||(c.magnifier={zoom:a.Magnifier.opts.zoom,posx:0,posy:0}),e=c.display.pluginInstances.JS9Magnifier,g=c.display.canvas,f=c.magnifier.zoom,k=Math.floor(e.width/f),m=Math.floor(e.height/f),b?(d=c.imageToDisplayPos(b),h=d.x-k/2,j=d.y-m/2,c.magnifier.posx=h,c.magnifier.posy=j):(h=c.magnifier.posx,j=c.magnifier.posy),
p=n=0,r=e.canvas.width,l=e.canvas.height,0>h&&(k+=h,n-=h*f,r+=h*f,h=0),d=h+k-g.width,0<d&&(k-=d,r=k*f),0>j&&(m+=j,p-=j*f,l+=j*f,j=0),d=j+m-g.height,0<d&&(m-=d,l=m*f),e.context.clear(),e.context.drawImage(g,h,j,k,m,n,p,r,l),c.magnifier.boxid||(c.magnifier.boxid=c.addShapes("magnifier","box"),$(e.canvas).css("background-color","black")),g=e.width/2,e=e.height/2,c.changeShapes("magnifier",c.magnifier.boxid,{left:g,top:e,width:f,height:f}))};a.Magnifier.zoom=function(c,b){var d,e;if(c&&c.magnifier){d=
c.magnifier;e=d.zoom;switch(b.charAt(0)){case "x":case "*":e*=parseFloat(b.slice(1));break;case "/":e/=parseFloat(b.slice(1));break;default:e=parseFloat(b)}if(!e||1>e)e=1;d.zoom=e;a.Magnifier.display(c)}};a.Magnifier.close=function(a){var b=a.display.pluginInstances.JS9Magnifier;b&&(b.context.clear(),a.removeShapes("magnifier","all"));return a};a.Panner={};a.Panner.CLASS="JS9";a.Panner.NAME="Panner";a.Panner.opts={hasControls:!1,hasRotatingPoint:!1,hasBorders:!1,zoom:4,canvas:{selection:!0},tagcolors:{defcolor:"#00FF00"}};
a.Panner.HTML="<span><button type='button' class='JS9Button' onClick='JS9.bcall(this, \"zoomPanner\", \"x2\"); return false'>x2</button><button type='button' class='JS9Button' onClick='JS9.bcall(this, \"zoomPanner\", \"/2\"); return false'>/2</button><button type='button' class='JS9Button' onClick='JS9.bcall(this, \"zoomPanner\", \"1\"); return false'>Zoom1</button><button type='button' class='JS9Button' onClick='JS9.bcall(this, \"panImage\"); return false'>Center</button></span>";a.Panner.init=function(c,
b){var d,e=this;this.width=this.divjq.attr("data-width");this.width||(this.width=c||a.PANWIDTH);this.divjq.css("width",this.width);this.width=parseInt(this.divjq.css("width"),10);this.height=this.divjq.attr("data-height");this.height||(this.height=b||a.PANHEIGHT);this.divjq.css("height",this.height);this.height=parseInt(this.divjq.css("height"),10);this.canvas=document.createElement("canvas");this.canvasjq=$(this.canvas);this.canvasjq.addClass("JS9Panner");this.canvasjq.css("z-index",a.ZINDEX);this.canvasjq.attr("width",
this.width);this.canvasjq.attr("height",this.height);this.context=this.canvas.getContext("2d");a.ANTIALIAS||(this.context.imageSmoothingEnabled=!1,this.context.mozImageSmoothingEnabled=!1,this.context.webkitImageSmoothingEnabled=!1);this.containerjq=$("<div>").addClass("JS9Container").append(this.canvasjq).appendTo(this.divjq);d=this.display.newShapeLayer("panner",a.Panner.opts,this.divjq);d.canvas.on("object:modified",function(c){var b=e.display.image;if(b){var h=c.target.getCenterPoint();c=(h.x-
b.panner.ix)*b.panner.xblock/b.panner.zoom+b.panner.x0;h=(d.canvas.height-(h.y+b.panner.iy))*b.panner.yblock/b.panner.zoom+b.panner.y0;try{b.display.pluginInstances.JS9Panner.status="inactive",b.setPan(c,h)}catch(j){a.log("couldn't pan image",j)}finally{b.display.pluginInstances.JS9Panner.status="active"}}});this.display.image&&a.Panner.display(this.display.image)};a.Panner.create=function(a){var b,d,e,f,g,h,j,k,m,n,p,r,l;if(a&&a.raw&&a.display.pluginInstances.JS9Panner){a.panner||(a.panner={});a.panner.zoom||
(a.panner.zoom=1);b=a.display.pluginInstances.JS9Panner;d=a.panner;e=a.rgb.sect;r=Math.min(a.raw.width,b.width);l=Math.min(a.raw.height,b.height);d.xblock=a.raw.width/r;d.yblock=a.raw.height/l;d.xblock>d.yblock?(l=Math.floor(l/d.xblock*d.yblock+0.5),d.yblock=d.xblock):d.yblock>d.xblock&&(r=Math.floor(r/d.yblock*d.xblock+0.5),d.xblock=d.yblock);b=a.display.context.createImageData(r,l);1===d.zoom?(g=d.xblock,h=d.yblock,e=f=0):(g=d.xblock/d.zoom,h=d.yblock/d.zoom,f=Math.max(0,(e.x0+e.x1-r*g)/2),e=Math.max(0,
(e.y0+e.y1-l*h)/2));d.x0=f;d.y0=e;d.img=b;d.ix=0;d.iy=0;if(a.rgbFile){for(j=0;j<l;j++){m=Math.floor(e+j*h)*a.offscreen.img.width;n=j*r;for(d=0;d<r;d++)k=Math.floor(f+d*g),k=4*(k+m),p=4*(n+d),b.data[p]=a.offscreen.img.data[k],b.data[p+1]=a.offscreen.img.data[k+1],b.data[p+2]=a.offscreen.img.data[k+2],b.data[p+3]=255}return a}for(j=0;j<l;j++){m=Math.floor(e+(l-j-1)*h)*a.raw.width;n=j*r;for(d=0;d<r;d++)k=Math.floor(f+d*g),k=a.colorData[k+m],p=4*(n+d),a.psColors[k]&&(b.data[p]=a.psColors[k][0],b.data[p+
1]=a.psColors[k][1],b.data[p+2]=a.psColors[k][2],b.data[p+3]=255)}return a}};a.Panner.display=function(c){var b,d,e,f,g,h,j;if(c&&(c.display.pluginInstances.JS9Panner&&"active"===c.display.pluginInstances.JS9Panner.status)&&(a.Panner.create(c),d=c.panner,b=c.display.pluginInstances.JS9Panner,e=c.rgb.sect,d.img))return d.img.width<b.canvas.width&&(d.ix=Math.floor((b.canvas.width-d.img.width)/2)),d.img.height<b.canvas.height&&(d.iy=Math.floor((b.canvas.height-d.img.height)/2)),b.context.clear(),b.context.putImageData(d.img,
d.ix,d.iy),f=d.zoom/d.xblock,g=d.zoom/d.yblock,h=e.width*f/e.zoom,j=e.height*g/e.zoom,f=(e.x0-d.x0)*f+d.ix,b=b.height-1-((e.y1-d.y0)*g+d.iy),f=f+1+h/2,b=b+1+j/2,f=Math.floor(f),b=Math.floor(b),h=Math.floor(h),j=Math.floor(j),h={left:f,top:b,width:h,height:j},c.panner.boxid?c.changeShapes("panner",c.panner.boxid,h):c.panner.boxid=c.addShapes("panner","box",h),c};a.Panner.zoom=function(c,b){var d,e,f;if(c&&c.panner&&c.display.pluginInstances.JS9Panner){e=c.panner;d=c.display.pluginInstances.JS9Panner;
f=e.zoom;switch(b.charAt(0)){case "*":case "x":case "X":d=Math.min(Math.min(d.width,d.height),f*parseFloat(b.slice(1)));break;case "/":d=Math.max(1,f/parseFloat(b.slice(1)));break;default:d=parseFloat(b)}if(!d||1>d)d=1;e.zoom=d;a.Panner.display(c);return c}};a.Panner.close=function(a){var b=a.display.pluginInstances.JS9Panner;b&&(b.context.clear(),a.removeShapes("panner","all"));return a};a.Catalogs={};a.Catalogs.CLASS="JS9";a.Catalogs.NAME="Catalogs";a.Catalogs.opts={hasControls:!1,hasRotatingPoint:!1,
hasBorders:!1,evented:!1,lockMovementX:!0,lockMovementY:!0,lockRotation:!0,lockScalingX:!0,lockScalingY:!0,lockUniScaling:!0,selectable:!1,canvas:{selection:!1},panzoom:!0,shape:"circle",strokeWidth:2,width:10,height:10,radius:5,eradius:{x:5,y:3},angle:0,tagcolors:{defcolor:"#00FF00"}};"function"!==typeof Object.create&&(Object.create=function(a){var b=function(){};b.prototype=a;return new b});Math.asinh=Math.asinh||function(a){return-Infinity===a?a:Math.log(a+Math.sqrt(a*a+1))};Math.sinh=Math.sinh||
function(a){return(Math.exp(a)-Math.exp(-a))/2};a.jupyterFocus=function(a,b){var d;window.hasOwnProperty("Jupyter")&&(d=a instanceof jQuery?a:$(a),d.find(b||"input, textarea").each(function(){Jupyter.keyboard_manager.register_events($(this))}))};a.getImageID=function(c,b){var d,e,f=0,g=1,h=a.images.length,j=/.*<([0-9][0-9]*)>$/;for(d=0;d<h;d++)e=a.images[d],e.display.id===b&&c===e.oid&&(0<=e.id.search(j)&&(e=e.id.replace(j,"$1"),g=Math.max(g,parseInt(e,10))),f++);return f?c+"<"+String(g+1)+">":c};
var H=1;a.uniqueID=function(){return H++};a.waiting=function(c,b){var d;switch(c){case !0:window.hasOwnProperty("Spinner")&&"spinner"===a.globalOpts.waitType?(b=b||$("body").get(0),a.spinner||(a.spinner={},d={color:a.globalOpts.spinColor,opacity:a.globalOpts.spinOpacity},a.spinner.spinner=new Spinner(d)),a.spinner.spinner.spin(b)):$("body").addClass("waiting");break;case !1:window.hasOwnProperty("Spinner")&&"spinner"===a.globalOpts.waitType?a.spinner&&a.spinner.spinner.stop():$("body").removeClass("waiting")}};
a.msgHandler=function(c,b){var d,e,f,g=[],h=c.cmd,j=c.id;b&&(a.globalOpts.alerts=!1);if(a.publics[h]){$.isArray(c.args)||(c.args=[c.args]);g=$.extend(!0,[],c.args);j&&g.push({display:j});try{f=a.publics[h].apply(null,g)}catch(k){f=sprintf("ERROR: %s",k.message)}b&&(a.globalOpts.alerts=!0,b(f));return f}if(!h||"#"===h)b&&b(""),b&&(a.globalOpts.alerts=!0);else{d=a.lookupCommand(h);e=a.lookupDisplay(j);if(d&&e)switch(d.getDisplayInfo(e),c.args?g=$.extend(!0,[],c.args):c.paramlist&&(g=c.paramlist.split(/ +/)),
d.getWhich(g)){case "get":try{f=d.get(g)||""}catch(m){f="ERROR: "+m.message}break;case "set":try{f=d.set(g)||"OK"}catch(n){f="ERROR: "+n.message}break;default:f=sprintf("ERROR: unknown cmd type for '%s'",h)}else d||(f=sprintf("ERROR: unknown cmd '%s'",h)),e||(f=sprintf("ERROR: unknown display (%s)",j));b&&(a.globalOpts.alerts=!0,b(f));return f}};a.lightWin=function(c,b,d,e,f){var g;switch(a.LIGHTWIN){case "dhtml":g=dhtmlwindow.open(c,b,d,e,f),/iPad|iPhone|iPod/.test(navigator.platform)&&$("#"+c+" "+
a.lightOpts.dhtml.drag).css("-webkit-overflow-scrolling","touch").css("overflow-y","scroll"),$("#"+c+" ."+a.lightOpts.dhtml.dragBar).doubletap(function(){g.close()},null,400),$("#"+c+" ."+a.lightOpts.dhtml.dragBar).on("touchend",this,function(){!dhtmlwindow.distancex&&!dhtmlwindow.distancey?2<=a.lightOpts.nclick?(alert("trouble closing this window? double-tap the window handle"),a.lightOpts.nclick=-1):0<=a.lightOpts.nclick&&a.lightOpts.nclick++:0<a.lightOpts.nclick&&(a.lightOpts.nclick=0)})}return g};
a.checkNew=function(c){c||a.error("internal failure in a JS9 constructor")};a.specialKey=function(a){return a.metaKey||a.ctrlKey};a.strace=function(c){var b="";1<a.DEBUG&&(b=c.stack||c.stacktrace||"");return b};a.bcall=function(c,b,d){var e,f;(e=$(c).closest("div[class^=JS9PluginToolbar]").data("displayid"))?f=a.getImage(e):a.error("can't find display for cmd: "+b);f||a.error("can't find image for cmd: "+b);switch(b){case "zoomPanner":3>arguments.length&&a.error("missing argument(s) for cmd: "+b);
try{a.Panner.zoom(f,d)}catch(g){a.error("error calling zoomPanner()",g)}break;case "zoomMagnifier":3>arguments.length&&a.error("missing argument(s) for cmd: "+b);try{a.Magnifier.zoom(f,d)}catch(h){a.error("error calling zoomMagnifier()",h)}break;case "panImage":try{f.setPan()}catch(j){a.error("error calling setPan()",j)}}};a.floatPrecision=function(a,b){var d,e;d=Math.floor(Math.log10(a));e=Math.floor(Math.log10(b));return d!==e?d>e?d:e:1};a.floatFormattedString=function(a,b,d){-2>b?a=sprintf("%.2e",
a):0>b?a=a.toFixed(Math.abs(b)+3):2>b?(b="%."+Math.abs(b)+"f",a=sprintf(b,a)):a=5>b?a.toFixed(d):sprintf("%.2e",a);return a};a.centroidPolygon=function(a){var b,d,e=0,f=0;if(a&&a.length){d=a.length;for(b=0;b<d;b++)e+=a[b].x,f+=a[b].y;return{x:e/d,y:f/d}}};a.lookupImage=function(c,b){var d,e,f=a.images.length;for(d=0;d<f;d++)if(e=a.images[d],c===e||c===e.id||c===e.file||c===a.TOROOT+e.file||e.fitsFile&&c===e.fitsFile)if(0<$("#"+e.display.id).length&&(!b||b===e.display.id))return e;return null};a.lookupDisplay=
function(c){var b,d=RegExp(sprintf("[-_]?(%s)$",a.PLUGINS));if(c&&"*"!==c&&0>c.toString().search(a.SUPERMENU)){for(b=0;b<a.displays.length;b++)if(c===a.displays[b]||c===a.displays[b].id)return a.displays[b];if("string"===typeof c){c=c.replace(d,"");for(b=0;b<a.displays.length;b++)if(c===a.displays[b]||c===a.displays[b].id)return a.displays[b]}a.error("can't find JS9 display with id: "+c)}return a.displays[0]};a.getImage=function(c){var b=null,d=null,b=a.lookupImage(c);if(!b&&(d=a.lookupDisplay(c)))b=
d.image;return b};a.onFileList=function(c,b,d){var e,f=function(c,b,d){var e;if(a.fits.handleFITSFile){c.name&&(b.filename=c.name);b.display&&(e=a.lookupDisplay(b.display))&&(e=e.divjq[0]);a.waiting(!0,e);try{a.fits.handleFITSFile(c,b,d)}catch(f){a.error("can't process FITS file from file list",f)}}else a.error("no FITS module available to load FITS file")};for(e=0;e<c.length;e++)if(-1!==c[e].type.indexOf("image/"))switch(c[e].type){case "image/fits":f(c[e],b,d);break;default:a.handleImageFile(c[e],
b,d)}else f(c[e],b,d)};a.fetchURL=function(c,b,d,e){var f=new XMLHttpRequest,g;b||(b=c,c=/([^\\\/]+)$/.exec(b)[1]);g=$.extend(!0,{},d,a.fits.options);f.open("GET",b,!0);f.responseType=d.responseType?d.responseType:"blob";a.globalOpts.xtimeout&&(f.timeout=a.globalOpts.xtimeout);f.onload=function(){var h;4===this.readyState&&(200===this.status||0===this.status?"blob"===f.responseType?(h=new Blob([this.response]),h.name=c.match("://")?c.split("/").reverse()[0].replace(/\?.*$/,""):c,"uc"===h.name&&(h.name=
"google_"+a.uniqueID()+".fits"),a.onFileList([h],g,e)):d.display?e(this.response,d,{display:d.display}):e(this.response,d):404===this.status?a.error("could not find "+b):a.error(sprintf("can't load: %s %s (%s) ",b,f.statusText,f.status)))};f.onerror=function(){a.error(sprintf("cannot load: %s %s (%s) ",b,f.statusText,f.status))};f.ontimeout=function(){a.error("timeout awaiting response from server: "+b)};try{f.send()}catch(h){a.error("request to load "+b+" failed",h)}};a.fitsLibrary=function(c){var b;
if(!c)return a.fits.name;b=c.toLowerCase();switch(b){case "fitsy":a.fits=Fitsy;a.fits.datahandler(a.NewFitsImage);a.fits.options=a.userOpts.fits||a.fits.options||{};break;case "astroem":case "cfitsio":a.fits=Astroem;a.fits.options=a.fits.options||{};a.fits.options.handler=a.NewFitsImage;a.userOpts.fits?(a.fits.options.extlist=a.userOpts.fits.extlist,a.fits.options.table={nx:a.userOpts.fits.table.nx,ny:a.userOpts.fits.table.ny}):(a.fits.options.extlist=a.globalOpts.extlist,a.fits.options.table={nx:a.globalOpts.dims[0],
ny:a.globalOpts.dims[1]});a.fits.maxFITSMemory&&a.globalOpts.maxMemory&&a.fits.maxFITSMemory(a.globalOpts.maxMemory);break;default:a.error("unknown fits library: "+c)}a.fits.name=b;a.fits.options.error=a.error;a.fits.options.waiting=a.waiting;return b};a.handleImageFile=function(c,b,d){b=$.extend(!0,{},b,a.fits.options);void 0===d&&(d=a.Load);var e=new FileReader;e.onload=function(a){var e=new Image;e.src=a.target.result;e.onload=function(){var a,f,k,m=0;a=document.createElement("canvas");f=a.getContext("2d");
var n=e.height,p=e.width;a.width=p;a.height=n;f.drawImage(e,0,0);var r=f.getImageData(0,0,p,n).data,l=new Float32Array(n*p);for(f=0;f<n;f++)for(a=0;a<p;a++)k=0.299*r[m]+0.587*r[m+1]+0.114*r[m+2],l[(n-f)*p+a]=k,m+=4;a={head:{},name:c.name,filedata:l,naxis:2,axis:[0,p,n],bitpix:-32,data:l};a.dmin=Number.MAX_VALUE;a.dmax=Number.MIN_VALUE;for(m=0;m<n*p;m++)a.dmin=Math.min(a.dmin,a.data[m]),a.dmax=Math.max(a.dmax,a.data[m]);d(a,b)}};e.readAsDataURL(c)};a.lookupColormap=function(c){var b;c||(c=a.imageOpts.colormap);
if(c)for(b=0;b<a.colormaps.length;b++)if(a.colormaps[b].name===c)return a.colormaps[b];a.error("unknown colormap '"+c+"'")};a.lookupCommand=function(c){var b,d;if(c){d=c.toLowerCase();for(b=0;b<a.commands.length;b++)if(c=a.commands[b],c.name===d||c.alias===d||c.alias2===d)return c}return null};a.error=function(c,b,d){var e,f,g="",h="",j=!0;a.waiting(!1);"string"===typeof b?(f=c.match(b))?f[1]?c=f[1]:f[0]&&(c=f[0]):j=!1:"object"===typeof b&&(e=b);3>arguments.length&&(d=!0);if(j&&(e&&e.message?c+=sprintf(" (%s)",
e.message):c&&(e=Error(c)),(f=a.strace(e))&&(h="\n\nStacktrace:\n"+f),a.globalOpts.alerts&&(c&&("string"===typeof c&&0>c.search(/ERROR/))&&(g="JS9 ERROR: "),alert(g+(c+h))),d))throw e;};a.eventToDisplayPos=function(a){var b,d;a||(a=window.event);a.target?b=a.target:a.srcElement&&(b=a.srcElement);3===b.nodeType&&(b=b.parentNode);a.originalEvent&&a.originalEvent.changedTouches&&a.originalEvent.changedTouches.length?(d=a.originalEvent.changedTouches[0].pageX,a=a.originalEvent.changedTouches[0].pageY):
(d=a.pageX,a=a.pageY);d-=$(b).offset().left;b=a-$(b).offset().top;return{x:Math.floor(d-1),y:Math.floor(b-1)}};a.rotatePoint=function(a,b,d){var e;d=d||{x:0,y:0};b=Math.PI*b/180;e=Math.cos(b);b=Math.sin(b);return{x:e*(a.x-d.x)-b*(a.y-d.y)+d.x,y:b*(a.x-d.x)+e*(a.y-d.y)+d.y}};a.log=function(){if(void 0!==window.console&&void 0!==window.console.log)try{console.log.apply(console,arguments)}catch(a){Function.prototype.bind.call(console.log,console).apply(console,arguments)}};a.isNumber=function(a){return!isNaN(parseFloat(a))&&
isFinite(a)};a.notNull=function(a){return void 0!==a&&null!==a};a.cardpars=function(c){var b;if("="===c[8])return b=c.slice(0,8).trim(),c=c.slice(10).replace(/\'/g," ").replace(/\/.*/,"").trim(),"T"===c?c=!0:"F"===c?c=!1:a.isNumber(c)&&(c=parseFloat(c)),[b,c]};a.raw2FITS=function(a,b){var d,e,f,g=!1,h="";if(!a)return h;if(a.card)for(d=0;d<a.card.length;d++)e=a.card[d],h+=e,"END "===e.substring(0,4)&&(g=!0),b&&(h+="\n");else if(a.cardstr)for(d=0;d<a.ncard;d++)e=a.cardstr.slice(80*d,80*(d+1)),h+=e,
"END "===e.substring(0,4)&&(g=!0),b&&(h+="\n");else if(a.header)for(e in d=a.header,d){if(d.hasOwnProperty(e)&&!("js9Protocol"===e||"js9Endian"===e))"END"===e&&(g=!0),f=d[e],!0===f&&(f="T"),h+=sprintf("%-8s%-2s%-70s",e,"=",f),b&&(h+="\n")}else if(a.BITPIX)for(e in d=a,d)if(d.hasOwnProperty(e)&&!("js9Protocol"===e||"js9Endian"===e))"END"===e&&(g=!0),f=d[e],!0===f&&(f="T"),h+=sprintf("%-8s%-2s%-70s",e,"=",f),b&&(h+="\n");g||(h+=sprintf("%-8s%-72s","END"," "),b&&(h+="\n"));return h};CanvasRenderingContext2D.prototype.clear=
CanvasRenderingContext2D.prototype.clear||function(a){a&&(this.save(),this.setTransform(1,0,0,1,0,0));this.clearRect(0,0,this.canvas.width,this.canvas.height);a&&this.restore()};a.tooltip=function(a,b,d,e,f,g){d?(d=d.replace(/\$([a-zA-Z0-9_.]+)/g,function(a,b){var c,d,n=b.split(".");switch(n[0]){case "im":d=e;break;case "xreg":d=f;break;case "evt":d=g;break;default:return a}for(c=1;c<n.length;c++)d=d[n[c]];return d}),e.display.tooltip.html(d).css({left:a,top:b,display:"inline-block"})):e.display.tooltip.html("").css({left:-9999,
display:"none"})};a.xeqByName=function(c,b){var d,e,f,g;e=Array.prototype.slice.call(arguments,2);d=typeof c;switch(d){case "function":return c.apply(b,e);case "string":f=c.split(".");g=f.pop();for(d=0;d<f.length;d++)b=b[f[d]];return b[g].apply(b,e);default:a.error("unknown function type: "+d)}};a.loadPrefs=function(c,b){$.ajax({url:c,dataType:"json",async:!1,success:function(b){var c,f,g;for(g in b)if(b.hasOwnProperty(g)&&a.hasOwnProperty(g)&&(f=typeof a[g],c=typeof b[g],f===c||"string"===c))switch(f){case "object":$.isArray(b[g])?
a[g]=b[g]:$.extend(!0,a[g],b[g]);break;case "number":case "string":a[g]=b[g]}},error:function(){b&&("Chrome"===a.BROWSER[0]&&""===document.domain?a.log("When using the file:// URI, Chrome must be run with the --allow-file-access-from-files switch to permit JS9 to access the preference file."):a.log("JS9 prefs file not available: %s",c))}})};a.isTypedArray=function(a){a=Object.prototype.toString.call(a);return{"[object Int8Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Int16Array]":!0,
"[object Uint16Array]":!0,"[object Int32Array]":!0,"[object Uint32Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0}.hasOwnProperty(a)};a.mouseDownCB=function(c){var b,d,e,f,g=c.data,h=g.image;if(h)if(d=a.eventToDisplayPos(c),g.inResize(d)||c.preventDefault(),2<a.DEBUG&&a.log("m-down: %d %d %s",d.x,d.y,h.rclick),f=h.displayToImagePos(d),h.dnpos=d,h.rclick)h.clearMessage("regions");else{g.blendMode&&(g.blendMode=0);if(!a.specialKey(c))for(b in g.pluginInstances)if(g.pluginInstances.hasOwnProperty(b)&&
(d=g.pluginInstances[b],e=d.plugin.opts,d.isActive("onmousedown")&&(!h.rclick||e.mousedownRegions)))try{e.onmousedown.call(d,h,f,c.originalEvent||c)}catch(j){d.errLog("onmousedown",j)}h.evstate=c.button;c.originalEvent&&(c.originalEvent.touches&&c.originalEvent.touches.length)&&(h.evstate=c.originalEvent.touches.length-2);$("body").on("mousemove",g,function(b){return a.mouseMoveCB(b)});$("body").on("mouseup",g,function(b){return a.mouseUpCB(b)})}};a.mouseUpCB=function(c){var b,d,e,f,g=c.data,h=g.image;
if(h){b=a.eventToDisplayPos(c);g.inResize(b)||c.preventDefault();2<a.DEBUG&&a.log("m-up: %d %d %s",b.x,b.y,h.rclick);d=h.displayToImagePos(b);h.rclick?h.dnpos&&Math.abs(h.dnpos.x-b.x)<a.NOMOVE&&Math.abs(h.dnpos.y-b.y)<a.NOMOVE?h.updateShapes("regions","selected","select"):h.updateShapes("regions","selected","update"):a.specialKey(c)&&(h.dnpos&&Math.abs(h.dnpos.x-b.x)<a.NOMOVE&&Math.abs(h.dnpos.y-b.y)<a.NOMOVE)&&h.setPan(d.x,d.y);0===g.blendMode&&(g.blendMode=!0,h.displayImage("rgb"));if(!a.specialKey(c))for(e in g.pluginInstances)if(g.pluginInstances.hasOwnProperty(e)&&
(b=g.pluginInstances[e],f=b.plugin.opts,b.isActive("onmouseup")&&(!h.rclick||f.mouseupRegions)))try{f.onmouseup.call(b,h,d,c.originalEvent||c)}catch(j){b.errLog("onmouseup",j)}h.rclick=0;h.evstate=-1;g.resizing&&(g.resizing=0,a.bugs.webkit_resize&&(c=parseInt(g.divjq.css("width"),10),d=parseInt(g.divjq.css("height"),10),c<g.owidth&&g.divjq.css("width",g.owidth+a.RESIZEFUDGE),d<g.oheight&&g.divjq.css("height",g.oheight+a.RESIZEFUDGE)));$("body").off("mouseup");$("body").off("mousemove")}};a.mouseMoveCB=
function(c){var b,d,e,f,g=c.data,h=g.image;if(h&&!g.resizing){b=a.eventToDisplayPos(c);g.inResize(b)||c.preventDefault();3<a.DEBUG&&a.log("m-move: %d %d %s",b.x,b.y,h.rclick);d=h.displayToImagePos(b);h.valpos=null;if(h.rclick&&(h.rclick=2,(f=h.display.layers.regions.params.sel)&&(h.params.listonchange||f.params.listonchange)))h.updateShape("regions",f,null,"update",!0),h.listRegions("selected",2);switch(h.evstate){case -1:if(0<d.x&&(0<d.y&&d.x<h.raw.width&&d.y<h.raw.height)&&!a.specialKey(c))for(e in a.globalOpts.internalValPos&&
(h.valpos=h.updateValpos(d)),g.pluginInstances)if(g.pluginInstances.hasOwnProperty(e)&&(b=g.pluginInstances[e],f=b.plugin.opts,b.isActive("onmousemove")&&(!h.rclick||f.mousemoveRegions)))try{f.onmousemove.call(b,h,d,c.originalEvent||c)}catch(j){b.errLog("onmousemove",j)}break;case 0:case 1:if(!a.globalOpts.internalContrastBias)break;if(h.rclick||a.specialKey(c))break;if(h.rgbFile)break;if(h.dnpos&&Math.abs(h.dnpos.x-b.x)<a.NOMOVE&&Math.abs(h.dnpos.y-b.y)<a.NOMOVE)break;d.x=Math.floor(b.x+0.5);d.y=
Math.floor(b.y+0.5);if(0>d.x||0>d.y||d.x>=g.canvas.width||d.y>=g.canvas.height)break;h.params.bias=d.x/g.canvas.width;h.params.contrast=10*(d.y/g.canvas.height);a.bugs.firefox_linux?window.setTimeout(function(){h.displayImage("scaled")},0):h.displayImage("scaled")}}};a.mouseOverCB=function(c){var b,d,e,f,g=c.data,h=g.image;b=$(document).scrollLeft();e=$(document).scrollTop();c.preventDefault();if(h&&(h.display.displayConjq.focus(),window.scrollTo(b,e),!a.specialKey(c)))for(d in b=a.eventToDisplayPos(c),
b=h.displayToImagePos(b),g.pluginInstances)if(g.pluginInstances.hasOwnProperty(d)&&(e=g.pluginInstances[d],f=e.plugin.opts,e.isActive("onmouseover")&&(!h.rclick||f.mouseoverRegions)))try{f.onmouseover.call(e,h,b,c.originalEvent||c)}catch(j){e.errLog("onmouseover",j)}};a.mouseOutCB=function(c){var b,d,e,f,g=c.data,h=g.image;c.preventDefault();if(h&&(h.display.displayConjq.blur(),!a.specialKey(c)))for(d in b=a.eventToDisplayPos(c),b=h.displayToImagePos(b),g.pluginInstances)if(g.pluginInstances.hasOwnProperty(d)&&
(e=g.pluginInstances[d],f=e.plugin.opts,e.isActive("onmouseout")&&(!h.rclick||f.mouseoutRegions)))try{f.onmouseout.call(e,h,b,c.originalEvent||c)}catch(j){e.errLog("onmouseout",j)}};a.keyPressCB=function(c){var b,d,e,f,g=c.data,h=g.image;b=c.which||c.keyCode;c.preventDefault();3<a.DEBUG&&a.log("keypress: %d ",b);b=a.eventToDisplayPos(c);b=h.displayToImagePos(b);for(d in g.pluginInstances)if(g.pluginInstances.hasOwnProperty(d)&&(e=g.pluginInstances[d],f=e.plugin.opts,e.isActive("onkeypress")))try{f.onkeypress.call(e,
h,b,c.originalEvent||c)}catch(j){e.errLog("onkeypress",j)}};a.keyDownCB=function(c){var b,d,e,f,g=c.data,h=g.image;b=c.which||c.keyCode;3<a.DEBUG&&a.log("keydown: %d ",b);b=a.eventToDisplayPos(c);b=h.displayToImagePos(b);for(d in g.pluginInstances)if(g.pluginInstances.hasOwnProperty(d)&&(e=g.pluginInstances[d],f=e.plugin.opts,e.isActive("onkeydown")))try{f.onkeydown.call(e,h,b,c.originalEvent||c)}catch(j){e.errLog("onkeydown",j)}h.layer&&h.layers[h.layer].opts.usekeyboard&&a.Regions.keyDownCB(h,b,
c,h.layer)};a.dragenter=function(a,b){b.stopPropagation();b.preventDefault()};a.dragover=function(a,b){b.stopPropagation();b.preventDefault()};a.dragexit=function(a,b){b.stopPropagation();b.preventDefault()};a.dragdrop=function(c,b,d){var e=b.target.files||b.dataTransfer.files,f=$.extend(!0,{},a.fits.options);b.stopPropagation();b.preventDefault();void 0===f.display&&(f.display=c);void 0===f.extlist&&(f.extlist=a.globalOpts.extlist);a.onFileList(e,f,d)};a.consoleKeyDownCB=function(c){var b=c.data,
d=c.which||c.keyCode;if(!a.specialKey(c)){c=b.consoleConjq.find(".JS9CmdIn:last");c.focus();if(b.hist.length&&(38===d||40===d)){b.hist[b.histpos]?b.hist[b.histpos]=c.val():b.histtemp=c.val();switch(d){case 38:b.histpos--;0>b.histpos&&(b.histpos=0);break;case 40:b.histpos++;b.histpos>b.hist.length&&(b.histpos=b.hist.length);break;default:a.error("internal keycode switch mixup")}b.hist[b.histpos]?(c.val(b.hist[b.histpos]),b.histused=b.histpos!==b.hist.length?!0:!1):(c.val(b.histtemp),b.histused=!1)}13===
d&&(a.globalOpts.alerts=!1,b.xeq(),a.globalOpts.alerts=!0,b.inp())}};a.RegisterPlugin=function(c,b,d,e){var f;if(c&&(b&&d)&&(f=c+b,e?(e.viewMenuItem&&(e.menuItem=e.viewMenuItem),e.menuItem&&!e.menu&&(e.menu="view"),e.menu&&(e.menu=e.menu.toLowerCase())):e=[],a.PLUGINS&&(a.PLUGINS+="|"),a.PLUGINS+=f.replace(/JS9/,""),a.plugins.push({xclass:c,xname:b,name:f,opts:e,func:d,instances:[]}),e.help)){var g;d=e.help.match(/^.*[\\\/]/);d[0]&&(g="plugins/"+d[0].replace(/[\\\/]+$/,""));d=e.help.replace(/^.*[\\\/]/,
"");a.helpOpts[b]={type:g,url:d,heading:c,title:e.menuItem?e.menuItem:f}}};a.instantiatePlugin=function(c,b,d,e){var f,g,h;if("string"===typeof b){for(f=0;f<a.plugins.length;f++)if(g=a.plugins[f],g.name===b){b=g;break}"string"===typeof b&&a.error("unknown plugin: "+b)}g=Object.create(b.func.prototype);g.name=b.name;g.isActive=function(a){if("active"!==this.status||a&&!this.plugin.opts.hasOwnProperty(a))return!1;switch(this.winType){case "virtual":return!0;default:return this.divjq.is(":visible")}};
g.errLog=function(b,c){a.log("error in %s: %s [%s]\n%s",b,this.name,c.message,a.strace(c))};if(c){h=c instanceof jQuery?c:"object"===typeof c?$(c):$("#"+c);for(f=0;f<b.instances.length;f++)if(h.is(b.instances[f].odivjq))return b.instances[f]}else h=$("div");if(c)if(d)g.id=h.attr("id")||b.name,g.winType="light",g.winHandle=d,g.odivjq=h,g.divjq=h,g.outerdivjq=g.divjq.closest(a.lightOpts[a.LIGHTWIN].top);else{if(g.id=h.attr("id")||b.name,g.winType="div",d=h.attr("id")||"JS9Plugin",h.wrap("<div class='JS9PluginContainer'>"),
g.odivjq=h,g.divjq=h,g.divjq.addClass(b.xclass+"Plugin").addClass("JS9Plugin"),g.odivjq.attr("id")||g.odivjq.attr("id",g.id),g.outerdivjq=g.divjq.closest(".JS9PluginContainer"),b.opts.toolbarSeparate||h.data("toolbarseparate"))d="<div class='"+a.lightOpts[a.LIGHTWIN].dragBar+"'>",$(d).insertBefore(g.divjq)}else g.id=b.name,g.winType="virtual";g.plugin=b;g.el=c;g.status="active";b.instances.push(g);if("virtual"===g.winType)for(f=0;f<a.displays.length;f++)a.displays[f].pluginInstances[b.name]||(g.div=
null,g.display=a.displays[f],b.func.apply(g,e),a.displays[f].pluginInstances[b.name]=g);else{g.div=g.divjq[0];g.outerdiv=g.outerdivjq[0];if(b.opts.winDims&&(!g.divjq.width()||!g.divjq.height()))g.divjq.css("width",b.opts.winDims[0]),g.divjq.css("height",b.opts.winDims[1]);d=g.divjq.data("js9id")||g.id;g.display=a.lookupDisplay(d);if(h=h.data("toolbarhtml")||b.opts.toolbarHTML)h=a.Image.prototype.expandMacro.call(null,h,[{name:"title",value:b.opts.winTitle||""}]),c=g.divjq.closest(a.lightOpts[a.LIGHTWIN].drag),
0===c.length&&(c=g.divjq),$("<div class='JS9PluginToolbar-"+g.winType+"'>").css("z-index",a.BTNZINDEX).html(h).data("displayid",g.display.id).insertAfter(c);g.display.pluginInstances[b.name]=g;b.func.apply(g,e)}return g};a.instantiatePlugins=function(){var c,b=function(b){$("div."+b.name).each(function(){a.instantiatePlugin($(this),b,null,b.opts.divArgs)});!b.opts.menuItem&&(b.opts.winDims&&!b.opts.winDims[0]&&!b.opts.winDims[1])&&a.instantiatePlugin(null,b,null,b.opts.divArgs)};for(c=0;c<a.plugins.length;c++)b(a.plugins[c])};
a.init=function(){var c;window.HTMLCanvasElement||a.error("sorry: your browser does not support JS9 (no HTML5 canvas support). Try a modern version of Firefox, Chrome, or Safari.");JSON||a.error("sorry: your browser does not support JS9 (no JSON support). Try a modern version of Firefox, Chrome, or Safari.");if(!a.INSTALLDIR){try{a.INSTALLDIR=$('link[href$="js9.css"]').attr("href").replace(/js9\.css$/,"")||""}catch(b){a.INSTALLDIR=""}a.TOROOT=a.INSTALLDIR.replace(/([^\/.])+/g,"..")}window.hasOwnProperty("Kinetic")&&
!window.hasOwnProperty("fabric")&&a.error("please load fabric.js instead of Kinetic.js");a.WIDTH=a.WIDTH||512;a.HEIGHT=a.HEIGHT||512;a.INFOWIDTH=a.INFOWIDTH||345;a.INFOHEIGHT=a.INFOHEIGHT||265;a.MENUWIDTH=a.MENUWIDTH||a.WIDTH;a.MENUHEIGHT=a.MENUHEIGHT||"auto";a.CONWIDTH=a.CONWIDTH||a.WIDTH;a.CONHEIGHT=a.CONHEIGHT||180;a.MAGWIDTH=a.MAGWIDTH||a.WIDTH/2;a.MAGHEIGHT=a.MAGHEIGHT||a.HEIGHT/2;a.PANWIDTH=a.PANWIDTH||320;a.PANHEIGHT=a.PANHEIGHT||320;a.DS9WIDTH=a.DS9WIDTH||250;a.DS9HEIGHT=a.DS9HEIGHT||250;
"dhtml"===a.LIGHTWIN&&($("<div>").attr("id","dhtmlwindowholder").appendTo($(document.body)).append("<span style='display:none'>.</span>"),dhtmlwindow.imagefiles=a.allinone?[a.allinone.min,a.allinone.close,a.allinone.restore,a.allinone.resize]:[a.InstallDir("images/min.gif"),a.InstallDir("images/close.gif"),a.InstallDir("images/restore.gif"),a.InstallDir("images/resize.gif")],window.hasOwnProperty("Jupyter")&&$("#dhtmlwindowholder").arrive("input",function(){a.jupyterFocus($(this).parent())}));a.PREFSFILE&&
(a.loadPrefs(a.InstallDir(a.PREFSFILE),1),a.loadPrefs(a.PREFSFILE,0),$.extend(!0,a.Regions.opts,a.regionOpts));"file:"===a.globalOpts.helperProtocol&&(a.globalOpts.helperProtocol="http:");a.globalOpts.resize||(a.globalOpts.resizeHandle=!1);a.BROWSER[3]&&(a.globalOpts.resizeHandle=!1);a.globalOpts.helperProtocol+="//";if(window.hasOwnProperty("localStorage")){try{c=localStorage.getItem("images")}catch(d){c=null}if(c){try{a.userOpts.images=JSON.parse(c)}catch(e){}a.userOpts.images&&$.extend(!0,a.imageOpts,
a.userOpts.images)}try{c=localStorage.getItem("regions")}catch(f){c=null}if(c){try{a.userOpts.regions=JSON.parse(c)}catch(g){}a.userOpts.regions&&$.extend(!0,a.Regions.opts,a.userOpts.regions)}try{c=localStorage.getItem("fits")}catch(h){c=null}if(c)try{a.userOpts.fits=JSON.parse(c)}catch(j){}}a.globalOpts.postMessage&&window.addEventListener("message",function(b){var c;b=b.data;if("string"===typeof b)try{c=JSON.parse(b)}catch(d){a.error("can't parse msg: "+b,d)}else"object"===typeof b?c=b:a.error("invalid msg from postMessage");
(b=a.msgHandler(c))&&parent.postMessage({cmd:c.cmd,res:b},"*")},!1);a.DEBUG=a.DEBUG||a.globalOpts.debug||0;window.hasOwnProperty("ImageFilters")&&(a.ImageFilters=ImageFilters);window.hasOwnProperty("Astroem")&&(a.vmalloc=Astroem.vmalloc,a.vfree=Astroem.vfree,a.vheap=Astroem.vheap,a.vmemcpy=Astroem.vmemcpy,a.vfile=Astroem.vfile,a.vunlink=Astroem.vunlink,a.arrfile=Astroem.arrfile,a.initwcs=Astroem.initwcs,a.wcsinfo=Astroem.wcsinfo,a.wcssys=Astroem.wcssys,a.wcsunits=Astroem.wcsunits,a.pix2wcs=Astroem.pix2wcs,
a.wcs2pix=Astroem.wcs2pix,a.reg2wcs=Astroem.reg2wcs,a.saostrtod=Astroem.saostrtod,a.saodtype=Astroem.saodtype,a.zscale=Astroem.zscale,a.reproject=Astroem.reproject);window.hasOwnProperty("Fitsy")?(a.fitsLibrary("fitsy"),a.fits=Fitsy):window.hasOwnProperty("Astroem")&&(a.fitsLibrary("cfitsio"),a.fits=Astroem);$("div.JS9").each(function(){a.checkNew(new a.Display($(this)))});a.RegisterPlugin("JS9","Menubar",a.Menubar);a.RegisterPlugin("JS9","Console",a.Console,{menuItem:"Console",winTitle:"JS9 Console",
winResize:!0,winDims:[a.WIDTH,180]});a.RegisterPlugin("JS9","Info",a.Info.init,{menuItem:"InfoBox",plugindisplay:a.Info.clearMain,winTitle:"JS9 Info",winResize:!0,winDims:[a.INFOWIDTH,a.INFOHEIGHT]});a.RegisterPlugin(a.Regions.CLASS,a.Regions.NAME,a.Regions.init,{onkeydown:a.Regions.keyDownCB,onregionschange:a.Regions.onchange,divArgs:["regions"],winDims:[0,0]});a.RegisterPlugin(a.Magnifier.CLASS,a.Magnifier.NAME,a.Magnifier.init,{menuItem:"Magnifier",toolbarSeparate:!1,toolbarHTML:a.Magnifier.HTML,
onmousemove:a.Magnifier.display,onimageclose:a.Magnifier.close,winTitle:"JS9 Magnifier",winDims:[a.MAGWIDTH,a.MAGHEIGHT],divArgs:[a.DS9WIDTH,a.DS9HEIGHT]});a.RegisterPlugin(a.Panner.CLASS,a.Panner.NAME,a.Panner.init,{menuItem:"Panner",toolbarSeparate:!1,toolbarHTML:a.Panner.HTML,onimagedisplay:a.Panner.display,onimageclose:a.Panner.close,winTitle:"JS9 Panner",winDims:[a.PANWIDTH,a.PANHEIGHT],divArgs:[a.DS9WIDTH,a.DS9HEIGHT]});a.instantiatePlugins();a.checkNew(new a.Colormap("grey",[[0,0],[1,1]],[[0,
0],[1,1]],[[0,0],[1,1]]));a.checkNew(new a.Colormap("red",[[0,0],[1,1]],[[0,0],[0,0]],[[0,0],[0,0]]));a.checkNew(new a.Colormap("green",[[0,0],[0,0]],[[0,0],[1,1]],[[0,0],[0,0]]));a.checkNew(new a.Colormap("blue",[[0,0],[0,0]],[[0,0],[0,0]],[[0,0],[1,1]]));a.checkNew(new a.Colormap("a",[[0,0],[0.25,0],[0.5,1],[1,1]],[[0,0],[0.25,1],[0.5,0],[0.77,0],[1,1]],[[0,0],[0.125,0],[0.5,1],[0.64,0.5],[0.77,0],[1,0]]));a.checkNew(new a.Colormap("b",[[0,0],[0.25,0],[0.5,1],[1,1]],[[0,0],[0.5,0],[0.75,1],[1,1]],
[[0,0],[0.25,1],[0.5,0],[0.75,0],[1,1]]));a.checkNew(new a.Colormap("bb",[[0,0],[0.5,1],[1,1]],[[0,0],[0.25,0],[0.75,1],[1,1]],[[0,0],[0.5,0],[1,1]]));a.checkNew(new a.Colormap("he",[[0,0],[0.015,0.5],[0.25,0.5],[0.5,0.75],[1,1]],[[0,0],[0.065,0],[0.125,0.5],[0.25,0.75],[0.5,0.81],[1,1]],[[0,0],[0.015,0.125],[0.03,0.375],[0.065,0.625],[0.25,0.25],[1,1]]));a.checkNew(new a.Colormap("i8",[[0,0,0],[0,1,0],[0,0,1],[0,1,1],[1,0,0],[1,1,0],[1,0,1],[1,1,1]]));a.checkNew(new a.Colormap("aips0",[[0.196,0.196,
0.196],[0.475,0,0.608],[0,0,0.785],[0.373,0.655,0.925],[0,0.596,0],[0,0.965,0],[1,1,0],[1,0.694,0],[1,0,0]]));a.checkNew(new a.Colormap("sls",[[0,0,0],[0.043442,0,0.052883],[0.086883,0,0.105767],[0.130325,0,0.15865],[0.173767,0,0.211533],[0.217208,0,0.264417],[0.26065,0,0.3173],[0.304092,0,0.370183],[0.347533,0,0.423067],[0.390975,0,0.47595],[0.434417,0,0.528833],[0.477858,0,0.581717],[0.5213,0,0.6346],[0.506742,0,0.640217],[0.492183,0,0.645833],[0.477625,0,0.65145],[0.463067,0,0.657067],[0.448508,
0,0.662683],[0.43395,0,0.6683],[0.419392,0,0.673917],[0.404833,0,0.679533],[0.390275,0,0.68515],[0.375717,0,0.690767],[0.361158,0,0.696383],[0.3466,0,0.702],[0.317717,0,0.712192],[0.288833,0,0.722383],[0.25995,0,0.732575],[0.231067,0,0.742767],[0.202183,0,0.752958],[0.1733,0,0.76315],[0.144417,0,0.773342],[0.115533,0,0.783533],[0.08665,0,0.793725],[0.057767,0,0.803917],[0.028883,0,0.814108],[0,0,0.8243],[0,0.019817,0.838942],[0,0.039633,0.853583],[0,0.05945,0.868225],[0,0.079267,0.882867],[0,0.099083,
0.897508],[0,0.1189,0.91215],[0,0.138717,0.926792],[0,0.158533,0.941433],[0,0.17835,0.956075],[0,0.198167,0.970717],[0,0.217983,0.985358],[0,0.2378,1],[0,0.268533,1],[0,0.299267,1],[0,0.33,1],[0,0.360733,1],[0,0.391467,1],[0,0.4222,1],[0,0.452933,1],[0,0.483667,1],[0,0.5144,1],[0,0.545133,1],[0,0.575867,1],[0,0.6066,1],[0,0.631733,0.9753],[0,0.656867,0.9506],[0,0.682,0.9259],[0,0.707133,0.9012],[0,0.732267,0.8765],[0,0.7574,0.8518],[0,0.782533,0.8271],[0,0.807667,0.8024],[0,0.8328,0.7777],[0,0.857933,
0.753],[0,0.883067,0.7283],[0,0.9082,0.7036],[0,0.901908,0.676675],[0,0.895617,0.64975],[0,0.889325,0.622825],[0,0.883033,0.5959],[0,0.876742,0.568975],[0,0.87045,0.54205],[0,0.864158,0.515125],[0,0.857867,0.4882],[0,0.851575,0.461275],[0,0.845283,0.43435],[0,0.838992,0.407425],[0,0.8327,0.3805],[0,0.832308,0.354858],[0,0.831917,0.329217],[0,0.831525,0.303575],[0,0.831133,0.277933],[0,0.830742,0.252292],[0,0.83035,0.22665],[0,0.829958,0.201008],[0,0.829567,0.175367],[0,0.829175,0.149725],[0,0.828783,
0.124083],[0,0.828392,0.098442],[0,0.828,0.0728],[0.033167,0.834167,0.066733],[0.066333,0.840333,0.060667],[0.0995,0.8465,0.0546],[0.132667,0.852667,0.048533],[0.165833,0.858833,0.042467],[0.199,0.865,0.0364],[0.232167,0.871167,0.030333],[0.265333,0.877333,0.024267],[0.2985,0.8835,0.0182],[0.331667,0.889667,0.012133],[0.364833,0.895833,0.006067],[0.398,0.902,0],[0.43095,0.902,0],[0.4639,0.902,0],[0.49685,0.902,0],[0.5298,0.902,0],[0.56275,0.902,0],[0.5957,0.902,0],[0.62865,0.902,0],[0.6616,0.902,
0],[0.69455,0.902,0],[0.7275,0.902,0],[0.76045,0.902,0],[0.7934,0.902,0],[0.810617,0.897133,0.003983],[0.827833,0.892267,0.007967],[0.84505,0.8874,0.01195],[0.862267,0.882533,0.015933],[0.879483,0.877667,0.019917],[0.8967,0.8728,0.0239],[0.913917,0.867933,0.027883],[0.931133,0.863067,0.031867],[0.94835,0.8582,0.03585],[0.965567,0.853333,0.039833],[0.982783,0.848467,0.043817],[1,0.8436,0.0478],[0.995725,0.824892,0.0516],[0.99145,0.806183,0.0554],[0.987175,0.787475,0.0592],[0.9829,0.768767,0.063],[0.978625,
0.750058,0.0668],[0.97435,0.73135,0.0706],[0.970075,0.712642,0.0744],[0.9658,0.693933,0.0782],[0.961525,0.675225,0.082],[0.95725,0.656517,0.0858],[0.952975,0.637808,0.0896],[0.9487,0.6191,0.0934],[0.952975,0.600408,0.085617],[0.95725,0.581717,0.077833],[0.961525,0.563025,0.07005],[0.9658,0.544333,0.062267],[0.970075,0.525642,0.054483],[0.97435,0.50695,0.0467],[0.978625,0.488258,0.038917],[0.9829,0.469567,0.031133],[0.987175,0.450875,0.02335],[0.99145,0.432183,0.015567],[0.995725,0.413492,0.007783],
[1,0.3948,0],[0.998342,0.3619,0],[0.996683,0.329,0],[0.995025,0.2961,0],[0.993367,0.2632,0],[0.991708,0.2303,0],[0.99005,0.1974,0],[0.988392,0.1645,0],[0.986733,0.1316,0],[0.985075,0.0987,0],[0.983417,0.0658,0],[0.981758,0.0329,0],[0.9801,0,0],[0.955925,0,0],[0.93175,0,0],[0.907575,0,0],[0.8834,0,0],[0.859225,0,0],[0.83505,0,0],[0.810875,0,0],[0.7867,0,0],[0.762525,0,0],[0.73835,0,0],[0.714175,0,0],[0.69,0,0],[0.715833,0.083333,0.083333],[0.741667,0.166667,0.166667],[0.7675,0.25,0.25],[0.793333,0.333333,
0.333333],[0.819167,0.416667,0.416667],[0.845,0.5,0.5],[0.870833,0.583333,0.583333],[0.896667,0.666667,0.666667],[0.9225,0.75,0.75],[0.948333,0.833333,0.833333],[0.974167,0.916667,0.916667],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]]));a.checkNew(new a.Colormap("hsv",function(){var a,b,c,d,e,f,g,h=[],j=0;for(a=0;200>a;a++,j++){b=1-a/199;c=360*b+270;d=Math.abs(Math.sin(3.1416*b));for(b=Math.pow(1-b,1/3);360<=c;)c-=360;c/=60;g=Math.floor(c);e=c-g;c=b*(1-d);f=b*(1-d*e);d=b*(1-d*
(1-e));h[j]=[];switch(g){case 0:h[j].push(b);h[j].push(d);h[j].push(c);break;case 1:h[j].push(f);h[j].push(b);h[j].push(c);break;case 2:h[j].push(c);h[j].push(b);h[j].push(d);break;case 3:h[j].push(c);h[j].push(f);h[j].push(b);break;case 4:h[j].push(d);h[j].push(c);h[j].push(b);break;case 5:h[j].push(b),h[j].push(c),h[j].push(f)}}return h}()));a.checkNew(new a.Colormap("heat",[[0,0],[0.34,1],[1,1]],[[0,0],[1,1]],[[0,0],[0.65,0],[0.98,1],[1,1]]));a.checkNew(new a.Colormap("cool",[[0,0],[0.29,0],[0.76,
0.1],[1,1]],[[0,0],[0.22,0],[0.96,1],[1,1]],[[0,0],[0.53,1],[1,1]]));a.checkNew(new a.Colormap("rainbow",[[0,1],[0.2,0],[0.6,0],[0.8,1],[1,1]],[[0,0],[0.2,0],[0.4,1],[0.8,1],[1,0]],[[0,1],[0.4,1],[0.6,0],[1,0]]));a.checkNew(new a.Colormap("standard",[[0,0],[0.333,0.3],[0.333,0],[0.666,0.3],[0.666,0.3],[1,1]],[[0,0],[0.333,0.3],[0.333,0.3],[0.666,1],[0.666,0],[1,0.3]],[[0,0],[0.333,1],[0.333,0],[0.666,0.3],[0.666,0],[1,0.3]]));a.checkNew(new a.Colormap("staircase",function(){var a,b,c=[],d=0;for(a=
1;5>=a;a++,d++)b=a/5,c[d]=[],c[d].push(0.3*b),c[d].push(0.3*b),c[d].push(b);for(a=1;5>=a;a++,d++)b=a/5,c[d]=[],c[d].push(0.3*b),c[d].push(b),c[d].push(0.3*b);for(a=1;5>=a;a++,d++)b=a/5,c[d]=[],c[d].push(b),c[d].push(0.3*b),c[d].push(0.3*b);return c}()));a.checkNew(new a.Colormap("color",[[0,0,0],[0.18431,0.18431,0.18431],[0.37255,0.37255,0.37255],[0.56078,0.56078,0.56078],[0.74902,0.74902,0.74902],[0.93725,0.93725,0.93725],[0,0.18431,0.93725],[0,0.37255,0.74902],[0,0.49804,0.49804],[0,0.74902,0.3098],
[0,0.93725,0],[0.3098,0.62353,0],[0.49804,0.49804,0],[0.62353,0.3098,0],[0.93725,0,0],[0.74902,0,0.3098]]));a.checkNew(new a.Colormap("viridis",[[0.26700401,0.00487433,0.32941519],[0.26851048,0.00960483,0.33542652],[0.26994384,0.01462494,0.34137895],[0.27130489,0.01994186,0.34726862],[0.27259384,0.02556309,0.35309303],[0.27380934,0.03149748,0.35885256],[0.27495242,0.03775181,0.36454323],[0.27602238,0.04416723,0.37016418],[0.2770184,0.05034437,0.37571452],[0.27794143,0.05632444,0.38119074],[0.27879067,
0.06214536,0.38659204],[0.2795655,0.06783587,0.39191723],[0.28026658,0.07341724,0.39716349],[0.28089358,0.07890703,0.40232944],[0.28144581,0.0843197,0.40741404],[0.28192358,0.08966622,0.41241521],[0.28232739,0.09495545,0.41733086],[0.28265633,0.10019576,0.42216032],[0.28291049,0.10539345,0.42690202],[0.28309095,0.11055307,0.43155375],[0.28319704,0.11567966,0.43611482],[0.28322882,0.12077701,0.44058404],[0.28318684,0.12584799,0.44496],[0.283072,0.13089477,0.44924127],[0.28288389,0.13592005,0.45342734],
[0.28262297,0.14092556,0.45751726],[0.28229037,0.14591233,0.46150995],[0.28188676,0.15088147,0.46540474],[0.28141228,0.15583425,0.46920128],[0.28086773,0.16077132,0.47289909],[0.28025468,0.16569272,0.47649762],[0.27957399,0.17059884,0.47999675],[0.27882618,0.1754902,0.48339654],[0.27801236,0.18036684,0.48669702],[0.27713437,0.18522836,0.48989831],[0.27619376,0.19007447,0.49300074],[0.27519116,0.1949054,0.49600488],[0.27412802,0.19972086,0.49891131],[0.27300596,0.20452049,0.50172076],[0.27182812,0.20930306,
0.50443413],[0.27059473,0.21406899,0.50705243],[0.26930756,0.21881782,0.50957678],[0.26796846,0.22354911,0.5120084],[0.26657984,0.2282621,0.5143487],[0.2651445,0.23295593,0.5165993],[0.2636632,0.23763078,0.51876163],[0.26213801,0.24228619,0.52083736],[0.26057103,0.2469217,0.52282822],[0.25896451,0.25153685,0.52473609],[0.25732244,0.2561304,0.52656332],[0.25564519,0.26070284,0.52831152],[0.25393498,0.26525384,0.52998273],[0.25219404,0.26978306,0.53157905],[0.25042462,0.27429024,0.53310261],[0.24862899,
0.27877509,0.53455561],[0.2468114,0.28323662,0.53594093],[0.24497208,0.28767547,0.53726018],[0.24311324,0.29209154,0.53851561],[0.24123708,0.29648471,0.53970946],[0.23934575,0.30085494,0.54084398],[0.23744138,0.30520222,0.5419214],[0.23552606,0.30952657,0.54294396],[0.23360277,0.31382773,0.54391424],[0.2316735,0.3181058,0.54483444],[0.22973926,0.32236127,0.54570633],[0.22780192,0.32659432,0.546532],[0.2258633,0.33080515,0.54731353],[0.22392515,0.334994,0.54805291],[0.22198915,0.33916114,0.54875211],
[0.22005691,0.34330688,0.54941304],[0.21812995,0.34743154,0.55003755],[0.21620971,0.35153548,0.55062743],[0.21429757,0.35561907,0.5511844],[0.21239477,0.35968273,0.55171011],[0.2105031,0.36372671,0.55220646],[0.20862342,0.36775151,0.55267486],[0.20675628,0.37175775,0.55311653],[0.20490257,0.37574589,0.55353282],[0.20306309,0.37971644,0.55392505],[0.20123854,0.38366989,0.55429441],[0.1994295,0.38760678,0.55464205],[0.1976365,0.39152762,0.55496905],[0.19585993,0.39543297,0.55527637],[0.19410009,0.39932336,
0.55556494],[0.19235719,0.40319934,0.55583559],[0.19063135,0.40706148,0.55608907],[0.18892259,0.41091033,0.55632606],[0.18723083,0.41474645,0.55654717],[0.18555593,0.4185704,0.55675292],[0.18389763,0.42238275,0.55694377],[0.18225561,0.42618405,0.5571201],[0.18062949,0.42997486,0.55728221],[0.17901879,0.43375572,0.55743035],[0.17742298,0.4375272,0.55756466],[0.17584148,0.44128981,0.55768526],[0.17427363,0.4450441,0.55779216],[0.17271876,0.4487906,0.55788532],[0.17117615,0.4525298,0.55796464],[0.16964573,
0.45626209,0.55803034],[0.16812641,0.45998802,0.55808199],[0.1666171,0.46370813,0.55811913],[0.16511703,0.4674229,0.55814141],[0.16362543,0.47113278,0.55814842],[0.16214155,0.47483821,0.55813967],[0.16066467,0.47853961,0.55811466],[0.15919413,0.4822374,0.5580728],[0.15772933,0.48593197,0.55801347],[0.15626973,0.4896237,0.557936],[0.15481488,0.49331293,0.55783967],[0.15336445,0.49700003,0.55772371],[0.1519182,0.50068529,0.55758733],[0.15047605,0.50436904,0.55742968],[0.14903918,0.50805136,0.5572505],
[0.14760731,0.51173263,0.55704861],[0.14618026,0.51541316,0.55682271],[0.14475863,0.51909319,0.55657181],[0.14334327,0.52277292,0.55629491],[0.14193527,0.52645254,0.55599097],[0.14053599,0.53013219,0.55565893],[0.13914708,0.53381201,0.55529773],[0.13777048,0.53749213,0.55490625],[0.1364085,0.54117264,0.55448339],[0.13506561,0.54485335,0.55402906],[0.13374299,0.54853458,0.55354108],[0.13244401,0.55221637,0.55301828],[0.13117249,0.55589872,0.55245948],[0.1299327,0.55958162,0.55186354],[0.12872938,0.56326503,
0.55122927],[0.12756771,0.56694891,0.55055551],[0.12645338,0.57063316,0.5498411],[0.12539383,0.57431754,0.54908564],[0.12439474,0.57800205,0.5482874],[0.12346281,0.58168661,0.54744498],[0.12260562,0.58537105,0.54655722],[0.12183122,0.58905521,0.54562298],[0.12114807,0.59273889,0.54464114],[0.12056501,0.59642187,0.54361058],[0.12009154,0.60010387,0.54253043],[0.11973756,0.60378459,0.54139999],[0.11951163,0.60746388,0.54021751],[0.11942341,0.61114146,0.53898192],[0.11948255,0.61481702,0.53769219],[0.11969858,
0.61849025,0.53634733],[0.12008079,0.62216081,0.53494633],[0.12063824,0.62582833,0.53348834],[0.12137972,0.62949242,0.53197275],[0.12231244,0.63315277,0.53039808],[0.12344358,0.63680899,0.52876343],[0.12477953,0.64046069,0.52706792],[0.12632581,0.64410744,0.52531069],[0.12808703,0.64774881,0.52349092],[0.13006688,0.65138436,0.52160791],[0.13226797,0.65501363,0.51966086],[0.13469183,0.65863619,0.5176488],[0.13733921,0.66225157,0.51557101],[0.14020991,0.66585927,0.5134268],[0.14330291,0.66945881,0.51121549],
[0.1466164,0.67304968,0.50893644],[0.15014782,0.67663139,0.5065889],[0.15389405,0.68020343,0.50417217],[0.15785146,0.68376525,0.50168574],[0.16201598,0.68731632,0.49912906],[0.1663832,0.69085611,0.49650163],[0.1709484,0.69438405,0.49380294],[0.17570671,0.6978996,0.49103252],[0.18065314,0.70140222,0.48818938],[0.18578266,0.70489133,0.48527326],[0.19109018,0.70836635,0.48228395],[0.19657063,0.71182668,0.47922108],[0.20221902,0.71527175,0.47608431],[0.20803045,0.71870095,0.4728733],[0.21400015,0.72211371,
0.46958774],[0.22012381,0.72550945,0.46622638],[0.2263969,0.72888753,0.46278934],[0.23281498,0.73224735,0.45927675],[0.2393739,0.73558828,0.45568838],[0.24606968,0.73890972,0.45202405],[0.25289851,0.74221104,0.44828355],[0.25985676,0.74549162,0.44446673],[0.26694127,0.74875084,0.44057284],[0.27414922,0.75198807,0.4366009],[0.28147681,0.75520266,0.43255207],[0.28892102,0.75839399,0.42842626],[0.29647899,0.76156142,0.42422341],[0.30414796,0.76470433,0.41994346],[0.31192534,0.76782207,0.41558638],[0.3198086,
0.77091403,0.41115215],[0.3277958,0.77397953,0.40664011],[0.33588539,0.7770179,0.40204917],[0.34407411,0.78002855,0.39738103],[0.35235985,0.78301086,0.39263579],[0.36074053,0.78596419,0.38781353],[0.3692142,0.78888793,0.38291438],[0.37777892,0.79178146,0.3779385],[0.38643282,0.79464415,0.37288606],[0.39517408,0.79747541,0.36775726],[0.40400101,0.80027461,0.36255223],[0.4129135,0.80304099,0.35726893],[0.42190813,0.80577412,0.35191009],[0.43098317,0.80847343,0.34647607],[0.44013691,0.81113836,0.3409673],
[0.44936763,0.81376835,0.33538426],[0.45867362,0.81636288,0.32972749],[0.46805314,0.81892143,0.32399761],[0.47750446,0.82144351,0.31819529],[0.4870258,0.82392862,0.31232133],[0.49661536,0.82637633,0.30637661],[0.5062713,0.82878621,0.30036211],[0.51599182,0.83115784,0.29427888],[0.52577622,0.83349064,0.2881265],[0.5356211,0.83578452,0.28190832],[0.5455244,0.83803918,0.27562602],[0.55548397,0.84025437,0.26928147],[0.5654976,0.8424299,0.26287683],[0.57556297,0.84456561,0.25641457],[0.58567772,0.84666139,
0.24989748],[0.59583934,0.84871722,0.24332878],[0.60604528,0.8507331,0.23671214],[0.61629283,0.85270912,0.23005179],[0.62657923,0.85464543,0.22335258],[0.63690157,0.85654226,0.21662012],[0.64725685,0.85839991,0.20986086],[0.65764197,0.86021878,0.20308229],[0.66805369,0.86199932,0.19629307],[0.67848868,0.86374211,0.18950326],[0.68894351,0.86544779,0.18272455],[0.69941463,0.86711711,0.17597055],[0.70989842,0.86875092,0.16925712],[0.72039115,0.87035015,0.16260273],[0.73088902,0.87191584,0.15602894],
[0.74138803,0.87344918,0.14956101],[0.75188414,0.87495143,0.14322828],[0.76237342,0.87642392,0.13706449],[0.77285183,0.87786808,0.13110864],[0.78331535,0.87928545,0.12540538],[0.79375994,0.88067763,0.12000532],[0.80418159,0.88204632,0.11496505],[0.81457634,0.88339329,0.11034678],[0.82494028,0.88472036,0.10621724],[0.83526959,0.88602943,0.1026459],[0.84556056,0.88732243,0.09970219],[0.8558096,0.88860134,0.09745186],[0.86601325,0.88986815,0.09595277],[0.87616824,0.89112487,0.09525046],[0.88627146,0.89237353,
0.09537439],[0.89632002,0.89361614,0.09633538],[0.90631121,0.89485467,0.09812496],[0.91624212,0.89609127,0.1007168],[0.92610579,0.89732977,0.10407067],[0.93590444,0.8985704,0.10813094],[0.94563626,0.899815,0.11283773],[0.95529972,0.90106534,0.11812832],[0.96489353,0.90232311,0.12394051],[0.97441665,0.90358991,0.13021494],[0.98386829,0.90486726,0.13689671],[0.99324789,0.90615657,0.1439362]]));a.checkNew(new a.Command({name:"analysis",alias:"run",help:"list/run analysis for current image",get:function(){var a,
b,c,d,e,f="",g=this.image;if(g&&g.analysisPackages)for(b=0;b<g.analysisPackages.length;b++){e=g.analysisPackages[b];for(a=0;a<e.length;a++)d=e[a],f&&(f+=", "),c=d.xclass?d.xclass+":"+d.name:d.name,f+=sprintf("%s (%s)",d.title,c);b<g.analysisPackages.length-1&&(f+="\n")}return f},set:function(b){var c,d=this.image;d&&((c=d.lookupAnalysis(b[0]))?c.purl?(b=d.displayAnalysis("params",a.InstallDir(c.purl),c.title+": "+d.fitsFile),$(b).data("dispid",d.display.id).data("aname",c.name)):d.runAnalysis(c.name):
a.error("unknown analysis command '"+b[0]+"'"))}}));a.checkNew(new a.Command({name:"colormap",alias:"cmap",help:"set/get colormap for current image",get:function(){var a;if(a=this.image)return a=a.getColormap(),sprintf("%s %s %s",a.colormap,a.contrast,a.bias)},set:function(a){var b=this.image;b&&b.setColormap.apply(b,a)}}));a.checkNew(new a.Command({name:"colormaps",alias:"cmaps",help:"get list of available colormaps",get:function(){var b,c="";for(b=0;b<a.colormaps.length;b++)c&&(c+=", "),c+=a.colormaps[b].name;
return c}}));a.checkNew(new a.Command({name:"help",help:"get list of available commmands",get:function(){var b,c,d;d="<table>";for(b=0;b<a.commands.length;b++)c=a.commands[b],d+="<tr><td>"+c.name+"</td><td>"+c.help,c.alias&&(d+=" ("+c.alias,c.alias2&&(d+=", "+c.alias2),d+=")"),d+="</td></tr>";return d+"</table>"}}));a.checkNew(new a.Command({name:"helper",help:"get/set helper connection",get:function(){return a.helper.connectinfo()},set:function(b){a.helper.connect(b[0].trim())}}));a.checkNew(new a.Command({name:"image",
help:"get name of currently loaded image or display specified image",get:function(){var a=this.image;if(a)return a.file},set:function(b){var c,d;for(c=0;c<a.images.length;c++)if(d=a.images[c],0<=d.file.search(b[0])&&d.display===this.display){d.displayImage("display");break}}}));a.checkNew(new a.Command({name:"images",help:"get list of currently loaded images",get:function(){var b,c,d="";for(b=0;b<a.images.length;b++)c=a.images[b],c.display===this.display&&(d&&(d+=", "),d+=c.file);return d}}));a.checkNew(new a.Command({name:"load",
help:"load image(s)",set:function(b){var c;for(c=0;c<b.length;c++)a.Load(b[c],{display:this.display.id})}}));a.checkNew(new a.Command({name:"pan",help:"set/get pan location for current image",get:function(){var a;if(a=this.image)return a=a.getPan(),sprintf("%s %s",a.x,a.y)},set:function(a){var b=this.image;b&&b.setPan.apply(b,a)}}));a.checkNew(new a.Command({name:"pix2wcs",help:"get image pixel value for specified wcs position",set:function(b){var c=this.image;if(c)return b=a.Pix2WCS(parseFloat(b[0]),
parseFloat(b[1]),{display:c}),b.str}}));a.checkNew(new a.Command({name:"print",help:"print image window",get:function(){var a=this.image;a&&a.print()}}));a.checkNew(new a.Command({name:"regions",alias:"reg",alias2:"region",help:"add region to current image or list all regions",get:function(){var a=this.image;if(a)return a.listRegions("all",0)||""},set:function(a){var b=this.image;b&&("delete"===a[0]||"remove"===a[0]?(a=a.slice(1).join(" "),b.removeShapes("regions",a)):(a=a.join(" "),b.addShapes("regions",
a)))}}));a.checkNew(new a.Command({name:"resize",help:"get/set display size for current image",get:function(){var a;if(a=this.image)return a=a.display,sprintf("%s %s",a.width,a.height)},set:function(a){var b;b=this.image;var c;b&&a.length&&(b=b.display,c=parseInt(a[0],10),a=1<a.length?parseInt(a[1],10):c,b.resize(c,a))}}));a.checkNew(new a.Command({name:"scale",help:"set/get scaling for current image",get:function(){var a;if(a=this.image)return a=a.getScale(),sprintf("%s %s %s",a.scale,a.scalemin,
a.scalemax)},set:function(a){var b=this.image;b&&b.setScale.apply(b,a)}}));a.checkNew(new a.Command({name:"scales",help:"get list of available scales",get:function(){return a.scales.join(", ")}}));a.checkNew(new a.Command({name:"status",help:"get status for specified (or current) image",get:function(b){var c,d,e,f="";for(c=0;c<a.images.length;c++)if(d=a.images[c],0<=d.file.search(b[0])){e=d;break}e?c=1:(c=0,e=this.image);if(e){if(c>b.length)return e.status.load;for(;c<b.length;c++)switch(d=b[c].toLowerCase().trim(),
d){case "load":f&&(f+="\n"),f+=e.status.load}}return f}}));a.checkNew(new a.Command({name:"url",help:"display a url",set:function(b){a.DisplayHelp(b[0])}}));a.checkNew(new a.Command({name:"wcssys",help:"set/get wcs system for current image",get:function(){var a=this.image;if(a)return a.getWCSSys()},set:function(a){var b=this.image;b&&b.setWCSSys(a[0])}}));a.checkNew(new a.Command({name:"wcsu",help:"set/get wcs units used for current image",get:function(){var a=this.image;if(a)return a.getWCSUnits()},
set:function(a){var b=this.image;b&&b.setWCSUnits(a[0])}}));a.checkNew(new a.Command({name:"wcssystems",help:"get list of available wcs systems",get:function(){return a.wcssyss.join(", ")}}));a.checkNew(new a.Command({name:"wcsunits",help:"get list of available wcs units",get:function(){return a.wcsunitss.join(", ")}}));a.checkNew(new a.Command({name:"wcs2pix",help:"get wcs position for specified image pixel",set:function(b){var c=this.image;if(c)return b=a.WCS2Pix(parseFloat(b[0]),parseFloat(b[1]),
{display:c}),b.str}}));a.checkNew(new a.Command({name:"zoom",help:"set/get zoom for current image",get:function(){var a=this.image;if(a)return a.getZoom()},set:function(a){var b=this.image;b&&b.setZoom(a[0])}}));a.helper=new a.Helper;$(document).on("keyup keypress",".js9AnalysisForm",function(a){if(13===(a.keyCode||a.which))return a.preventDefault(),!1});$(document).scrollTop(0)};a.parsePublicArgs=function(a){var b=null;a=Array.prototype.slice.call(a);var d=a[a.length-1];d&&("object"===typeof d&&
d.hasOwnProperty("display")&&1===Object.keys(d).length)&&(b=d.display,a.pop());return{argv:a,display:b}};a.mkPublic=function(c,b){"string"===typeof b?a.Image.prototype[b]?(a[c]=function(){var c;c=a.parsePublicArgs(arguments);var e=a.getImage(c.display);if(e)return c=e[b].apply(e,c.argv),c===e||c===e.display?"OK":c},a.publics[c]=a[c]):a.error("unknown image function for mkPublic: "+b):"function"===typeof b?(a[c]=b,a.publics[c]=a[c]):a.error("unsupported type for mkPublic: "+typeof b)};a.mkPublic("CloseImage",
"closeImage");a.mkPublic("DisplayImage","displayImage");a.mkPublic("BlendImage","blendImage");a.mkPublic("GetColormap","getColormap");a.mkPublic("SetColormap","setColormap");a.mkPublic("GetZoom","getZoom");a.mkPublic("SetZoom","setZoom");a.mkPublic("GetPan","getPan");a.mkPublic("SetPan","setPan");a.mkPublic("GetScale","getScale");a.mkPublic("SetScale","setScale");a.mkPublic("GetValPos","updateValpos");a.mkPublic("ImageToDisplayPos","imageToDisplayPos");a.mkPublic("DisplayToImagePos","displayToImagePos");
a.mkPublic("ImageToLogicalPos","imageToLogicalPos");a.mkPublic("LogicalToImagePos","logicalToImagePos");a.mkPublic("GetWCSUnits","getWCSUnits");a.mkPublic("SetWCSUnits","setWCSUnits");a.mkPublic("GetWCSSys","getWCSSys");a.mkPublic("SetWCSSys","setWCSSys");a.mkPublic("ShowShapeLayer","showShapeLayer");a.mkPublic("AddShapes","addShapes");a.mkPublic("RemoveShapes","removeShapes");a.mkPublic("GetShapes","getShapes");a.mkPublic("ChangeShapes","changeShapes");a.mkPublic("Print","print");a.mkPublic("SavePNG",
"savePNG");a.mkPublic("SaveJPEG","saveJPEG");a.mkPublic("SaveFITS","saveFITS");a.mkPublic("RunAnalysis","runAnalysis");a.mkPublic("DisplayMessage","displayMessage");a.mkPublic("RawDataLayer","rawDataLayer");a.mkPublic("ShiftData","shiftData");a.mkPublic("GaussBlurData","gaussBlurData");a.mkPublic("ReprojectData","reprojectData");a.mkPublic("FilterRGBImage","filterRGBImage");a.mkPublic("AddColormap",function(c,b,d,e){var f,g,h=a.parsePublicArgs(arguments),j=function(b){b.vertices?a.AddColormap(b.name,
b.vertices[0],b.vertices[1],b.vertices[2]):b.colors?a.AddColormap(b.name,b.colors):a.error("invalid colormap object for JS9.AddColormap()")};if(h.argv[0]instanceof Blob)f=new FileReader,f.onload=function(b){try{g=JSON.parse(b.target.result)}catch(c){a.error("can't parse json colormap",c)}j(g)},f.readAsText(h.argv[0]);else if("object"===typeof h.argv[0])j(h.argv[0]);else switch(h.argv.length){case 1:try{g=JSON.parse(c)}catch(k){a.error("can't parse JSON colormap",k)}j(g);break;case 2:a.checkNew(new a.Colormap(c,
b));break;case 4:a.checkNew(new a.Colormap(c,b,d,e));break;default:a.error("AddColormap() requires a colormap name and 1 or 3 args")}});a.mkPublic("SetValPos",function(c){var b=null,d=a.parsePublicArgs(arguments),e=a.getImage(d.display);e&&(c=d.argv[0],b=e.params.valpos,e.params.valpos=c);return b});a.mkPublic("Load",function(c,b){var d,e,f;e=a.parsePublicArgs(arguments);c=e.argv[0];b=e.argv[1];if(c)if(e=e.display?e.display:0<a.displays.length?a.displays[0].id:a.DEFID,b=b||{},b.display=b.display||
e,b.onload?f=b.onload:a.imageOpts.onload&&(f=a.imageOpts.onload,b.onload=f),c instanceof Blob){if(c.name){if(e=a.lookupImage(c.name,e)){e.displayImage("display",b);e.refreshLayers();e.clearMessage();return}b.filename=c.name}b.filename||(b.filename=a.ANON);if(a.fits.handleFITSFile){e=$.extend(!0,{},b,a.fits.options);try{a.fits.handleFITSFile(c,e,a.NewFitsImage)}catch(g){a.error("can't process FITS file",g)}}else a.error("no FITS module available to load this FITS blob")}else if("object"===typeof c)a.checkNew(new a.Image(c,
b,f));else if("string"!==typeof c&&a.error("unknown file type for Load: "+typeof c),"U0lNUExFICA9"===c.slice(0,12)&&(c=window.atob(c)),"SIMPLE ="===c.slice(0,9)){e=[];for(d=0;d<c.length;d++)e[d]=c.charCodeAt(d);d=new Blob([new Uint8Array(e)]);b.filename||(b.filename=a.ANON);d.name=b.filename;if(a.fits.handleFITSFile){e=$.extend(!0,{},b,a.fits.options);try{a.fits.handleFITSFile(d,e,a.NewFitsImage)}catch(h){a.error("can't process FITS file",h)}}else a.error("no FITS module available to process this memory FITS")}else(e=
a.lookupImage(c,e))?(e.displayImage("display",b),e.clearMessage()):(c=c.trim(),e=c.split(".").pop().toLowerCase(),"png"===e?a.globalOpts.pngisfits?a.checkNew(new a.Image(c,b,f)):a.fetchURL(null,c,b,a.NewFitsImage):b.fits2png||void 0===b.fits2png&&a.globalOpts.fits2png?a.helper.connected?a.helper.send("fits2png",{fits:c},function(c){var d;c="object"===typeof c?c:0<=c.search(a.analOpts.epattern)?{stderr:c}:{stdout:c};c.stderr&&a.error(c.stderr,a.analOpts.epattern);c.stdout&&(c=c.stdout.replace(/\n*$/,
"").split("\n").pop(),d=c.split(".").pop().toLowerCase(),"png"===d?a.checkNew(new a.Image(c,b,f)):a.error("fits2png conversion failed: "+c))}):a.error("no JS9 helper available to convert image: "+c):(b.display&&(d=a.lookupDisplay(b.display))&&(d=d.divjq[0]),a.waiting(!0,d),d=c.replace(/\[.*\]/,""),a.fetchURL(c,d,b,a.NewFitsImage)));else a.error("JS9.Load: no file specified for image load")});a.mkPublic("SaveRegions",function(c,b){var d;d=a.parsePublicArgs(arguments);return(d=a.getImage(d.display))?
d.saveRegions(c,b):c});a.mkPublic("LoadRegions",function(c,b){var d,e;e=a.parsePublicArgs(arguments);c=e.argv[0];b=e.argv[1]||{};c||a.error("JS9.LoadRegions: no file specified for regions load");d=e.display?e.display:b.display?b.display:0<a.displays.length?a.displays[0].id:a.DEFID;"object"===typeof c?(e=new FileReader,e.onload=function(c){a.AddRegions(c.target.result,b,{display:d})},e.readAsText(c)):"string"===typeof c?(b.responseType="text",b.display=d,a.fetchURL(null,c,b,a.AddRegions)):a.error("unknown file type for LoadRegions: "+
typeof c)});a.mkPublic("LoadWindow",function(c,b,d,e,f){var g;g=a.helper.pageid||d||"win";b=b||{};switch(d){case "light":return b.id?(d=b.id,delete b.id):d=g+a.uniqueID(),g="d"+d,e=e||sprintf("<hr class='hline0'><div class='JS9Menubar' id='%sMenubar'></div><div class='JS9' id='%s'></div>",d,d),f=f||a.lightOpts[a.LIGHTWIN].imageWin,a.lightWin(g,"inline",e,c,f),a.checkNew(new a.Display(d)),a.instantiatePlugins(),b.display=d,c&&a.Load(c,b),d;case "new":return b.id?(d=b.id,delete b.id):d=g+a.uniqueID(),
f=document.getElementsByTagName("head")[0].innerHTML,!f.match(/src=["'].*js9\.js/)&&!f.match(/src=["'].*js9\.min\.js/)&&(f+=sprintf('<%s type="text/javascript" src="js9.min.js"></%s>',"script","script")),g=e||sprintf("<div class='JS9Menubar' id='%sMenubar'></div><div class='JS9' id='%s'></div>",d,d),e=sprintf("<html><head>%s</head><body",f),c&&(e+=sprintf(" onload='JS9.Preload(\"%s\",%s);'",c,JSON.stringify(b))),e+=sprintf(">%s</body></html>\n",g),c=window.open(null,d,"width=540, height=560"),c=c.document,
c.open(),c.write(e),c.close(),d}});a.mkPublic("LoadProxy",function(c,b){var d,e,f=a.parsePublicArgs(arguments);c=f.argv[0];b=f.argv[1];a.globalOpts.loadProxy||a.error("proxy load not available for this server");a.globalOpts.workDir||a.error("proxy load requires a temp workDir this server");c||a.error("no url specified for proxy load");c=c.trim();c.match(/dropbox\.com/)?(c=c.replace("www.dropbox.com","dl.dropboxusercontent.com"),c=c.replace("?dl=0","")+"?raw=1"):c.match(/drive\.google\.com/)&&(c=c.replace(/\/file\/d\/(\w+)\/\w+\?usp=sharing/,
"/uc?export=download&id=$1"));f.display&&(e=a.lookupDisplay(f.display))&&(e=e.divjq[0]);a.waiting(!0,e);a.Send("loadproxy",{cmd:"js9Xeq loadproxy "+c},function(c){c="object"===typeof c?c:0<=c.search(a.analOpts.epattern)?{stderr:c}:{stdout:c};c.errcode=c.errcode||0;c.stderr?a.error(c.stderr):c.stdout?(b=b||{},void 0===b.fits2png&&(b.fits2png=!1),d=c.stdout.trim(),"/"!==d.charAt(0)&&(d=a.InstallDir(d)),b.proxyFile=d,a.Load(d,b,{display:f.display})):a.error("internal error: no return from load proxy command")})});
a.mkPublic("Preload",function(c){var b,d,e="",f=null,g=arguments.length;b=a.parsePublicArgs(arguments);c=b.argv[0];b.display&&(f={display:b.display},g-=1);switch(g){case 0:b=(null===a.helper.connected||a.helper.connected)&&0<a.preloads.length?2:3;break;case 1:b="boolean"===typeof c?0<a.preloads.length?2:3:null===a.helper.connected||a.helper.connected?1:0;break;default:b=null===a.helper.connected||a.helper.connected?1:0}switch(b){case 0:for(b=0;b<g;b++)d=b+1,d<g&&"object"===typeof arguments[d]?(a.preloads.push([arguments[b],
arguments[d],f]),b++):a.preloads.push([arguments[b],null,f]);break;case 1:a.globalOpts.alerts=!1;for(b=0;b<g;b++)if(d=b+1,d<g&&"object"===typeof arguments[d]){try{f?a.Load(arguments[b],arguments[d],f):a.Load(arguments[b],arguments[d])}catch(h){e=e+" "+arguments[b]}b++}else try{f?a.Load(arguments[b],null,f):a.Load(arguments[b],null)}catch(j){e=e+" "+arguments[b]}a.globalOpts.alerts=!0;e&&a.error("could not preload image(s): "+e);break;case 2:a.globalOpts.alerts=!1;for(b=0;b<a.preloads.length;b++)try{a.preloads[b][2]?
a.Load(a.preloads[b][0],a.preloads[b][1],a.preloads[b][2]):a.Load(a.preloads[b][0],a.preloads[b][1])}catch(k){e=e+" "+a.preloads[b][0]}a.globalOpts.alerts=!0;e&&a.error("could not preload image(s): "+e);a.preloads=[]}});a.mkPublic("RefreshImage",function(c,b){var d=a.parsePublicArgs(arguments),e=a.getImage(d.display),f=function(c){a.Image.prototype.refreshImage.call(e,c,b)};c=d.argv[0];b=d.argv[1]||{};if(e)if(c instanceof Blob)if(a.fits.handleFITSFile){!b.rawid&&(a.fits.cleanupFITSFile&&e.raw.hdu&&
e.raw.hdu.fits)&&a.fits.cleanupFITSFile(e.raw.hdu.fits,!0);try{a.fits.handleFITSFile(c,a.fits.options,f)}catch(g){a.error("can't refresh FITS file",g)}}else a.error("no FITS module available to refresh this image");else a.Image.prototype.refreshImage.apply(e,d.argv);else c instanceof Blob&&a.Load.apply(null,arguments)});a.mkPublic("GetLoadStatus",function(c){var b=a.parsePublicArgs(arguments),d=a.getImage(b.display);return d?(c=b.argv[0],!c||d.oid===c?d.status.load:"other"):"none"});a.mkPublic("OpenFileMenu",
function(){var c=a.parsePublicArgs(arguments);(c=a.lookupDisplay(c.display))&&$("#openLocalFile-"+c.id).click()});a.mkPublic("OpenRegionsMenu",function(){var c=a.parsePublicArgs(arguments);(c=a.lookupDisplay(c.display))&&$("#openLocalRegions-"+c.id).click()});a.mkPublic("OpenColormapMenu",function(){var c=a.parsePublicArgs(arguments);(c=a.lookupDisplay(c.display))&&$("#openLocalColormap-"+c.id).click()});a.mkPublic("SaveColormap",function(c){var b,d=a.parsePublicArgs(arguments);if(window.hasOwnProperty("saveAs")){if(b=
a.getImage(d.display))c=d.argv[0]||"js9.cmap",b=$.extend(!0,{},b.cmapObj),delete b.type,b=JSON.stringify(b),b=new Blob([b],{type:"text/plain"}),saveAs(b,c)}else a.error("no saveAs function available to save colormap");return c});a.mkPublic("DisplayPlugin",function(c){var b,d,e,f;b=a.parsePublicArgs(arguments);var g=a.lookupDisplay(b.display);if(g&&b.argv[0]){c=b.argv[0];f=c.toLowerCase();for(b=0;b<a.plugins.length;b++)if(d=a.plugins[b],e=d.name,e===c||e.toLowerCase().substr(-f.length)===f){g.displayPlugin(d);
return}a.error("can't find plugin: "+c)}});a.mkPublic("NewFitsImage",function(c,b){var d;b&&b.onload&&(d=b.onload);a.checkNew(new a.Image(c,b,d))});a.mkPublic("GetImage",function(c){var b;c&&"string"!==typeof c&&(b=a.parsePublicArgs(arguments),c=b.display);return a.getImage(c)});a.mkPublic("GetImageData",function(c){var b=a.parsePublicArgs(arguments),d=a.getImage(b.display);return d?(c=b.argv[0],d.getImageData(c)):null});a.mkPublic("GetDisplayData",function(c){var b,d,e,f=[];b=a.parsePublicArgs(arguments);
d=b.display||a.displays[0].id;c=b.argv[0];for(b=0;b<a.images.length;b++)e=a.images[b],e.display.id===d&&f.push(e.getImageData(c));return f});a.mkPublic("GetFITSHeader",function(c){var b="",d=a.parsePublicArgs(arguments),e=a.getImage(d.display);e&&e.raw&&(c=d.argv[0],b=a.raw2FITS(e.raw,c));return b});a.mkPublic("BlendDisplay",function(c){var b,d,e=[],f=a.parsePublicArgs(arguments).display||a.DEFID;(b=a.lookupDisplay(f))||a.error("no JS9 display found: "+f);if(void 0===c||"mode"===c)return b.blendMode;
if("list"===c){for(b=0;b<a.images.length;b++)d=a.images[b],d.display.id===f&&d.blend.active&&e.push(d.id);return e}b.blendMode=!!c;b.image&&b.image.displayImage();return b.blendMode});a.mkPublic("LoadAuxFile",function(c,b){var d=a.parsePublicArgs(arguments),e=a.getImage(d.display);e?(c=d.argv[0],b=d.argv[1],e.loadAuxFile(c,b)):a.error("could not find image for aux file: "+c)});a.mkPublic("SubmitAnalysis",function(c,b,d){var e,f,g;e=a.lightOpts[a.LIGHTWIN];var h=a.parsePublicArgs(arguments);c=h.argv[0];
b=h.argv[1];d=h.argv[2];b?e=a.lookupDisplay(h.display).id:(e=$(c).closest(e.top),b=e.data("aname"),e=e.data("dispid"));b?e&&(f=a.getImage(e)):g="internal error: could not find analysis task name";if(f){e=$(c).closest("form");try{h=e.serializeArray()}catch(j){h=null}f.runAnalysis(b,h,d)}else g="internal error: could not find image";g&&a.error(g);return!1});a.mkPublic("Send",function(c,b,d){a.helper.connected?a.helper.send(c,b,d):a.error("no JS9 helper available")});a.mkPublic("EventToDisplayPos",function(c){return a.eventToDisplayPos(c)});
a.mkPublic("PixToWCS",function(c,b){var d,e,f=1;d=a.parsePublicArgs(arguments);var g=a.getImage(d.display);if(g&&(c=d.argv[0],b=d.argv[1],(!a.isNumber(c)||!a.isNumber(b))&&a.error("invalid input for PixToWCS"),0<g.wcs))return d=a.pix2wcs(g.wcs,c,b).trim(),e=d.split(/ +/),"sexagesimal"===g.params.wcsunits&&("galactic"!==g.params.wcssys&&"ecliptic"!==g.params.wcssys)&&(f=15),{ra:a.saostrtod(e[0])*f,dec:a.saostrtod(e[1]),sys:e[2],str:d}});a.Pix2WCS=a.PixToWCS;a.mkPublic("WCSToPix",function(c,b){var d,
e,f;e=a.parsePublicArgs(arguments);if(d=a.getImage(e.display))if(c=e.argv[0],b=e.argv[1],(!a.isNumber(c)||!a.isNumber(b))&&a.error("invalid input for WCSToPix"),0<d.wcs)return d=a.wcs2pix(d.wcs,c,b).trim().split(/ +/),e=parseFloat(d[0]),f=parseFloat(d[1]),d=sprintf("%f %f",e,f),{x:e,y:f,str:d};return null});a.WCS2Pix=a.WCSToPix;a.mkPublic("DisplayHelp",function(c){var b,d,e=a.lightOpts.dhtml.textWin,f;c&&(d=c.split("/").reverse()[0],b="help_"+a.uniqueID(),(f=a.helpOpts[c])?(c=a.InstallDir(f.type+
"/"+f.url),a.lightWin(b,"iframe",c,f.title||d,e)):a.lightWin(b,"iframe",c,d,e))});a.mkPublic("NewShapeLayer",function(c,b){var d=a.parsePublicArgs(arguments),e=a.getImage(d.display);return e?(c=d.argv[0],b=d.argv[1],e.display.newShapeLayer(c,b)):null});a.mkPublic("AddRegions",function(c,b){var d=a.parsePublicArgs(arguments),e=a.getImage(d.display);return e?(c=d.argv[0],b=d.argv[1],c||a.error("no region specified for AddRegions"),b=d.argv[1],e.addShapes("regions",c,b)):null});a.mkPublic("RemoveRegions",
function(c){var b=a.parsePublicArgs(arguments),d=a.getImage(b.display);return d?(c=b.argv[0],d.removeShapes("regions",c),d.clearMessage("regions"),"OK"):null});a.mkPublic("GetRegions",function(c){var b=a.parsePublicArgs(arguments),d=a.getImage(b.display);return d?(b.argv.unshift("regions"),d.getShapes.apply(d,b.argv)):null});a.mkPublic("ChangeRegions",function(c,b){var d=a.parsePublicArgs(arguments),e=a.getImage(d.display);e&&((c=d.argv[0])||a.error("no region specified for GetRegions"),b=d.argv[1],
e.changeShapes("regions",c,b));return null});a.mkPublic("InstallDir",function(c){return a.INSTALLDIR+c});a.mkPublic("AddDivs",function(){var c,b=a.parsePublicArgs(arguments);for(c=0;c<b.argv.length;c++)a.checkNew(new a.Display(b.argv[c]));a.instantiatePlugins()});a.mkPublic("ResizeDisplay",function(){var c;c=a.parsePublicArgs(arguments);var b=a.lookupDisplay(c.display);b||a.error("invalid display for resize");c=a.Display.prototype.resize.apply(b,c.argv);c===b&&(c="OK");return c});return a}(JS9);$(document).ready(function(){JS9.init()});