comparison d3s_examples/python-neo4jrestclient/static/platin/platin.js @ 8:18ef6948d689

new d3s examples
author Dirk Wintergruen <dwinter@mpiwg-berlin.mpg.de>
date Thu, 01 Oct 2015 17:17:27 +0200
parents
children
comparison
equal deleted inserted replaced
7:45dad9e38c82 8:18ef6948d689
1 (function($){
2
3 var jQuery = $;
4 /*
5 * basic.js
6 *
7 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 3 of the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22 * MA 02110-1301 USA
23 */
24
25 /**
26 * basic code which is included first for the minified version
27 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
28 * @release 1.0
29 * @release date: 2012-07-27
30 * @version date: 2012-07-27
31 */
32
33 var arrayIndex = function(array, obj) {
34 if (Array.indexOf) {
35 return array.indexOf(obj);
36 }
37 for (var i = 0; i < array.length; i++) {
38 if (array[i] == obj) {
39 return i;
40 }
41 }
42 return -1;
43 }
44 var GeoTemCoMinifier_urlPrefix;
45 for (var i = 0; i < document.getElementsByTagName("script").length; i++) {
46 var script = document.getElementsByTagName("script")[i];
47 var index = script.src.indexOf("platin.js");
48 if (index == -1) {
49 index = script.src.indexOf("platin-min.js");
50 }
51 if (index != -1) {
52 GeoTemCoMinifier_urlPrefix = script.src.substring(0, index);
53 break;
54 }
55 }
56 // Copyright 2006 Google Inc.
57 //
58 // Licensed under the Apache License, Version 2.0 (the "License");
59 // you may not use this file except in compliance with the License.
60 // You may obtain a copy of the License at
61 //
62 // http://www.apache.org/licenses/LICENSE-2.0
63 //
64 // Unless required by applicable law or agreed to in writing, software
65 // distributed under the License is distributed on an "AS IS" BASIS,
66 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
67 // See the License for the specific language governing permissions and
68 // limitations under the License.
69
70
71 // Known Issues:
72 //
73 // * Patterns are not implemented.
74 // * Radial gradient are not implemented. The VML version of these look very
75 // different from the canvas one.
76 // * Clipping paths are not implemented.
77 // * Coordsize. The width and height attribute have higher priority than the
78 // width and height style values which isn't correct.
79 // * Painting mode isn't implemented.
80 // * Canvas width/height should is using content-box by default. IE in
81 // Quirks mode will draw the canvas using border-box. Either change your
82 // doctype to HTML5
83 // (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype)
84 // or use Box Sizing Behavior from WebFX
85 // (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html)
86 // * Non uniform scaling does not correctly scale strokes.
87 // * Optimize. There is always room for speed improvements.
88
89 // Only add this code if we do not already have a canvas implementation
90 if (!document.createElement('canvas').getContext) {
91
92 (function() {
93
94 // alias some functions to make (compiled) code shorter
95 var m = Math;
96 var mr = m.round;
97 var ms = m.sin;
98 var mc = m.cos;
99 var abs = m.abs;
100 var sqrt = m.sqrt;
101
102 // this is used for sub pixel precision
103 var Z = 10;
104 var Z2 = Z / 2;
105
106 /**
107 * This funtion is assigned to the <canvas> elements as element.getContext().
108 * @this {HTMLElement}
109 * @return {CanvasRenderingContext2D_}
110 */
111 function getContext() {
112 return this.context_ ||
113 (this.context_ = new CanvasRenderingContext2D_(this));
114 }
115
116 var slice = Array.prototype.slice;
117
118 /**
119 * Binds a function to an object. The returned function will always use the
120 * passed in {@code obj} as {@code this}.
121 *
122 * Example:
123 *
124 * g = bind(f, obj, a, b)
125 * g(c, d) // will do f.call(obj, a, b, c, d)
126 *
127 * @param {Function} f The function to bind the object to
128 * @param {Object} obj The object that should act as this when the function
129 * is called
130 * @param {*} var_args Rest arguments that will be used as the initial
131 * arguments when the function is called
132 * @return {Function} A new function that has bound this
133 */
134 function bind(f, obj, var_args) {
135 var a = slice.call(arguments, 2);
136 return function() {
137 return f.apply(obj, a.concat(slice.call(arguments)));
138 };
139 }
140
141 var G_vmlCanvasManager_ = {
142 init: function(opt_doc) {
143 if (/MSIE/.test(navigator.userAgent) && !window.opera) {
144 var doc = opt_doc || document;
145 // Create a dummy element so that IE will allow canvas elements to be
146 // recognized.
147 doc.createElement('canvas');
148 doc.attachEvent('onreadystatechange', bind(this.init_, this, doc));
149 }
150 },
151
152 init_: function(doc) {
153 // create xmlns
154 if (!doc.namespaces['g_vml_']) {
155 doc.namespaces.add('g_vml_', 'urn:schemas-microsoft-com:vml',
156 '#default#VML');
157
158 }
159 if (!doc.namespaces['g_o_']) {
160 doc.namespaces.add('g_o_', 'urn:schemas-microsoft-com:office:office',
161 '#default#VML');
162 }
163
164 // Setup default CSS. Only add one style sheet per document
165 if (!doc.styleSheets['ex_canvas_']) {
166 var ss = doc.createStyleSheet();
167 ss.owningElement.id = 'ex_canvas_';
168 ss.cssText = 'canvas{display:inline-block;overflow:hidden;' +
169 // default size is 300x150 in Gecko and Opera
170 'text-align:left;width:300px;height:150px}' +
171 'g_vml_\\:*{behavior:url(#default#VML)}' +
172 'g_o_\\:*{behavior:url(#default#VML)}';
173
174 }
175
176 // find all canvas elements
177 var els = doc.getElementsByTagName('canvas');
178 for (var i = 0; i < els.length; i++) {
179 this.initElement(els[i]);
180 }
181 },
182
183 /**
184 * Public initializes a canvas element so that it can be used as canvas
185 * element from now on. This is called automatically before the page is
186 * loaded but if you are creating elements using createElement you need to
187 * make sure this is called on the element.
188 * @param {HTMLElement} el The canvas element to initialize.
189 * @return {HTMLElement} the element that was created.
190 */
191 initElement: function(el) {
192 if (!el.getContext) {
193
194 el.getContext = getContext;
195
196 // Remove fallback content. There is no way to hide text nodes so we
197 // just remove all childNodes. We could hide all elements and remove
198 // text nodes but who really cares about the fallback content.
199 el.innerHTML = '';
200
201 // do not use inline function because that will leak memory
202 el.attachEvent('onpropertychange', onPropertyChange);
203 el.attachEvent('onresize', onResize);
204
205 var attrs = el.attributes;
206 if (attrs.width && attrs.width.specified) {
207 // TODO: use runtimeStyle and coordsize
208 // el.getContext().setWidth_(attrs.width.nodeValue);
209 el.style.width = attrs.width.nodeValue + 'px';
210 } else {
211 el.width = el.clientWidth;
212 }
213 if (attrs.height && attrs.height.specified) {
214 // TODO: use runtimeStyle and coordsize
215 // el.getContext().setHeight_(attrs.height.nodeValue);
216 el.style.height = attrs.height.nodeValue + 'px';
217 } else {
218 el.height = el.clientHeight;
219 }
220 //el.getContext().setCoordsize_()
221 }
222 return el;
223 }
224 };
225
226 function onPropertyChange(e) {
227 var el = e.srcElement;
228
229 switch (e.propertyName) {
230 case 'width':
231 el.style.width = el.attributes.width.nodeValue + 'px';
232 el.getContext().clearRect();
233 break;
234 case 'height':
235 el.style.height = el.attributes.height.nodeValue + 'px';
236 el.getContext().clearRect();
237 break;
238 }
239 }
240
241 function onResize(e) {
242 var el = e.srcElement;
243 if (el.firstChild) {
244 el.firstChild.style.width = el.clientWidth + 'px';
245 el.firstChild.style.height = el.clientHeight + 'px';
246 }
247 }
248
249 G_vmlCanvasManager_.init();
250
251 // precompute "00" to "FF"
252 var dec2hex = [];
253 for (var i = 0; i < 16; i++) {
254 for (var j = 0; j < 16; j++) {
255 dec2hex[i * 16 + j] = i.toString(16) + j.toString(16);
256 }
257 }
258
259 function createMatrixIdentity() {
260 return [
261 [1, 0, 0],
262 [0, 1, 0],
263 [0, 0, 1]
264 ];
265 }
266
267 function matrixMultiply(m1, m2) {
268 var result = createMatrixIdentity();
269
270 for (var x = 0; x < 3; x++) {
271 for (var y = 0; y < 3; y++) {
272 var sum = 0;
273
274 for (var z = 0; z < 3; z++) {
275 sum += m1[x][z] * m2[z][y];
276 }
277
278 result[x][y] = sum;
279 }
280 }
281 return result;
282 }
283
284 function copyState(o1, o2) {
285 o2.fillStyle = o1.fillStyle;
286 o2.lineCap = o1.lineCap;
287 o2.lineJoin = o1.lineJoin;
288 o2.lineWidth = o1.lineWidth;
289 o2.miterLimit = o1.miterLimit;
290 o2.shadowBlur = o1.shadowBlur;
291 o2.shadowColor = o1.shadowColor;
292 o2.shadowOffsetX = o1.shadowOffsetX;
293 o2.shadowOffsetY = o1.shadowOffsetY;
294 o2.strokeStyle = o1.strokeStyle;
295 o2.globalAlpha = o1.globalAlpha;
296 o2.arcScaleX_ = o1.arcScaleX_;
297 o2.arcScaleY_ = o1.arcScaleY_;
298 o2.lineScale_ = o1.lineScale_;
299 }
300
301 function processStyle(styleString) {
302 var str, alpha = 1;
303
304 styleString = String(styleString);
305 if (styleString.substring(0, 3) == 'rgb') {
306 var start = styleString.indexOf('(', 3);
307 var end = styleString.indexOf(')', start + 1);
308 var guts = styleString.substring(start + 1, end).split(',');
309
310 str = '#';
311 for (var i = 0; i < 3; i++) {
312 str += dec2hex[Number(guts[i])];
313 }
314
315 if (guts.length == 4 && styleString.substr(3, 1) == 'a') {
316 alpha = guts[3];
317 }
318 } else {
319 str = styleString;
320 }
321
322 return {color: str, alpha: alpha};
323 }
324
325 function processLineCap(lineCap) {
326 switch (lineCap) {
327 case 'butt':
328 return 'flat';
329 case 'round':
330 return 'round';
331 case 'square':
332 default:
333 return 'square';
334 }
335 }
336
337 /**
338 * This class implements CanvasRenderingContext2D interface as described by
339 * the WHATWG.
340 * @param {HTMLElement} surfaceElement The element that the 2D context should
341 * be associated with
342 */
343 function CanvasRenderingContext2D_(surfaceElement) {
344 this.m_ = createMatrixIdentity();
345
346 this.mStack_ = [];
347 this.aStack_ = [];
348 this.currentPath_ = [];
349
350 // Canvas context properties
351 this.strokeStyle = '#000';
352 this.fillStyle = '#000';
353
354 this.lineWidth = 1;
355 this.lineJoin = 'miter';
356 this.lineCap = 'butt';
357 this.miterLimit = Z * 1;
358 this.globalAlpha = 1;
359 this.canvas = surfaceElement;
360
361 var el = surfaceElement.ownerDocument.createElement('div');
362 el.style.width = surfaceElement.clientWidth + 'px';
363 el.style.height = surfaceElement.clientHeight + 'px';
364 el.style.overflow = 'hidden';
365 el.style.position = 'absolute';
366 surfaceElement.appendChild(el);
367
368 this.element_ = el;
369 this.arcScaleX_ = 1;
370 this.arcScaleY_ = 1;
371 this.lineScale_ = 1;
372 }
373
374 var contextPrototype = CanvasRenderingContext2D_.prototype;
375 contextPrototype.clearRect = function() {
376 this.element_.innerHTML = '';
377 };
378
379 contextPrototype.beginPath = function() {
380 // TODO: Branch current matrix so that save/restore has no effect
381 // as per safari docs.
382 this.currentPath_ = [];
383 };
384
385 contextPrototype.moveTo = function(aX, aY) {
386 var p = this.getCoords_(aX, aY);
387 this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y});
388 this.currentX_ = p.x;
389 this.currentY_ = p.y;
390 };
391
392 contextPrototype.lineTo = function(aX, aY) {
393 var p = this.getCoords_(aX, aY);
394 this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y});
395
396 this.currentX_ = p.x;
397 this.currentY_ = p.y;
398 };
399
400 contextPrototype.bezierCurveTo = function(aCP1x, aCP1y,
401 aCP2x, aCP2y,
402 aX, aY) {
403 var p = this.getCoords_(aX, aY);
404 var cp1 = this.getCoords_(aCP1x, aCP1y);
405 var cp2 = this.getCoords_(aCP2x, aCP2y);
406 bezierCurveTo(this, cp1, cp2, p);
407 };
408
409 // Helper function that takes the already fixed cordinates.
410 function bezierCurveTo(self, cp1, cp2, p) {
411 self.currentPath_.push({
412 type: 'bezierCurveTo',
413 cp1x: cp1.x,
414 cp1y: cp1.y,
415 cp2x: cp2.x,
416 cp2y: cp2.y,
417 x: p.x,
418 y: p.y
419 });
420 self.currentX_ = p.x;
421 self.currentY_ = p.y;
422 }
423
424 contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) {
425 // the following is lifted almost directly from
426 // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes
427
428 var cp = this.getCoords_(aCPx, aCPy);
429 var p = this.getCoords_(aX, aY);
430
431 var cp1 = {
432 x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_),
433 y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_)
434 };
435 var cp2 = {
436 x: cp1.x + (p.x - this.currentX_) / 3.0,
437 y: cp1.y + (p.y - this.currentY_) / 3.0
438 };
439
440 bezierCurveTo(this, cp1, cp2, p);
441 };
442
443 contextPrototype.arc = function(aX, aY, aRadius,
444 aStartAngle, aEndAngle, aClockwise) {
445 aRadius *= Z;
446 var arcType = aClockwise ? 'at' : 'wa';
447
448 var xStart = aX + mc(aStartAngle) * aRadius - Z2;
449 var yStart = aY + ms(aStartAngle) * aRadius - Z2;
450
451 var xEnd = aX + mc(aEndAngle) * aRadius - Z2;
452 var yEnd = aY + ms(aEndAngle) * aRadius - Z2;
453
454 // IE won't render arches drawn counter clockwise if xStart == xEnd.
455 if (xStart == xEnd && !aClockwise) {
456 xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something
457 // that can be represented in binary
458 }
459
460 var p = this.getCoords_(aX, aY);
461 var pStart = this.getCoords_(xStart, yStart);
462 var pEnd = this.getCoords_(xEnd, yEnd);
463
464 this.currentPath_.push({type: arcType,
465 x: p.x,
466 y: p.y,
467 radius: aRadius,
468 xStart: pStart.x,
469 yStart: pStart.y,
470 xEnd: pEnd.x,
471 yEnd: pEnd.y});
472
473 };
474
475 contextPrototype.rect = function(aX, aY, aWidth, aHeight) {
476 this.moveTo(aX, aY);
477 this.lineTo(aX + aWidth, aY);
478 this.lineTo(aX + aWidth, aY + aHeight);
479 this.lineTo(aX, aY + aHeight);
480 this.closePath();
481 };
482
483 contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) {
484 var oldPath = this.currentPath_;
485 this.beginPath();
486
487 this.moveTo(aX, aY);
488 this.lineTo(aX + aWidth, aY);
489 this.lineTo(aX + aWidth, aY + aHeight);
490 this.lineTo(aX, aY + aHeight);
491 this.closePath();
492 this.stroke();
493
494 this.currentPath_ = oldPath;
495 };
496
497 contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) {
498 var oldPath = this.currentPath_;
499 this.beginPath();
500
501 this.moveTo(aX, aY);
502 this.lineTo(aX + aWidth, aY);
503 this.lineTo(aX + aWidth, aY + aHeight);
504 this.lineTo(aX, aY + aHeight);
505 this.closePath();
506 this.fill();
507
508 this.currentPath_ = oldPath;
509 };
510
511 contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) {
512 var gradient = new CanvasGradient_('gradient');
513 gradient.x0_ = aX0;
514 gradient.y0_ = aY0;
515 gradient.x1_ = aX1;
516 gradient.y1_ = aY1;
517 return gradient;
518 };
519
520 contextPrototype.createRadialGradient = function(aX0, aY0, aR0,
521 aX1, aY1, aR1) {
522 var gradient = new CanvasGradient_('gradientradial');
523 gradient.x0_ = aX0;
524 gradient.y0_ = aY0;
525 gradient.r0_ = aR0;
526 gradient.x1_ = aX1;
527 gradient.y1_ = aY1;
528 gradient.r1_ = aR1;
529 return gradient;
530 };
531
532 contextPrototype.drawImage = function(image, var_args) {
533 var dx, dy, dw, dh, sx, sy, sw, sh;
534
535 // to find the original width we overide the width and height
536 var oldRuntimeWidth = image.runtimeStyle.width;
537 var oldRuntimeHeight = image.runtimeStyle.height;
538 image.runtimeStyle.width = 'auto';
539 image.runtimeStyle.height = 'auto';
540
541 // get the original size
542 var w = image.width;
543 var h = image.height;
544
545 // and remove overides
546 image.runtimeStyle.width = oldRuntimeWidth;
547 image.runtimeStyle.height = oldRuntimeHeight;
548
549 if (arguments.length == 3) {
550 dx = arguments[1];
551 dy = arguments[2];
552 sx = sy = 0;
553 sw = dw = w;
554 sh = dh = h;
555 } else if (arguments.length == 5) {
556 dx = arguments[1];
557 dy = arguments[2];
558 dw = arguments[3];
559 dh = arguments[4];
560 sx = sy = 0;
561 sw = w;
562 sh = h;
563 } else if (arguments.length == 9) {
564 sx = arguments[1];
565 sy = arguments[2];
566 sw = arguments[3];
567 sh = arguments[4];
568 dx = arguments[5];
569 dy = arguments[6];
570 dw = arguments[7];
571 dh = arguments[8];
572 } else {
573 throw Error('Invalid number of arguments');
574 }
575
576 var d = this.getCoords_(dx, dy);
577
578 var w2 = sw / 2;
579 var h2 = sh / 2;
580
581 var vmlStr = [];
582
583 var W = 10;
584 var H = 10;
585
586 // For some reason that I've now forgotten, using divs didn't work
587 vmlStr.push(' <g_vml_:group',
588 ' coordsize="', Z * W, ',', Z * H, '"',
589 ' coordorigin="0,0"' ,
590 ' style="width:', W, 'px;height:', H, 'px;position:absolute;');
591
592 // If filters are necessary (rotation exists), create them
593 // filters are bog-slow, so only create them if abbsolutely necessary
594 // The following check doesn't account for skews (which don't exist
595 // in the canvas spec (yet) anyway.
596
597 if (this.m_[0][0] != 1 || this.m_[0][1]) {
598 var filter = [];
599
600 // Note the 12/21 reversal
601 filter.push('M11=', this.m_[0][0], ',',
602 'M12=', this.m_[1][0], ',',
603 'M21=', this.m_[0][1], ',',
604 'M22=', this.m_[1][1], ',',
605 'Dx=', mr(d.x / Z), ',',
606 'Dy=', mr(d.y / Z), '');
607
608 // Bounding box calculation (need to minimize displayed area so that
609 // filters don't waste time on unused pixels.
610 var max = d;
611 var c2 = this.getCoords_(dx + dw, dy);
612 var c3 = this.getCoords_(dx, dy + dh);
613 var c4 = this.getCoords_(dx + dw, dy + dh);
614
615 max.x = m.max(max.x, c2.x, c3.x, c4.x);
616 max.y = m.max(max.y, c2.y, c3.y, c4.y);
617
618 vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z),
619 'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(',
620 filter.join(''), ", sizingmethod='clip');")
621 } else {
622 vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;');
623 }
624
625 vmlStr.push(' ">' ,
626 '<g_vml_:image src="', image.src, '"',
627 ' style="width:', Z * dw, 'px;',
628 ' height:', Z * dh, 'px;"',
629 ' cropleft="', sx / w, '"',
630 ' croptop="', sy / h, '"',
631 ' cropright="', (w - sx - sw) / w, '"',
632 ' cropbottom="', (h - sy - sh) / h, '"',
633 ' />',
634 '</g_vml_:group>');
635
636 this.element_.insertAdjacentHTML('BeforeEnd',
637 vmlStr.join(''));
638 };
639
640 contextPrototype.stroke = function(aFill) {
641 var lineStr = [];
642 var lineOpen = false;
643 var a = processStyle(aFill ? this.fillStyle : this.strokeStyle);
644 var color = a.color;
645 var opacity = a.alpha * this.globalAlpha;
646
647 var W = 10;
648 var H = 10;
649
650 lineStr.push('<g_vml_:shape',
651 ' filled="', !!aFill, '"',
652 ' style="position:absolute;width:', W, 'px;height:', H, 'px;"',
653 ' coordorigin="0 0" coordsize="', Z * W, ' ', Z * H, '"',
654 ' stroked="', !aFill, '"',
655 ' path="');
656
657 var newSeq = false;
658 var min = {x: null, y: null};
659 var max = {x: null, y: null};
660
661 for (var i = 0; i < this.currentPath_.length; i++) {
662 var p = this.currentPath_[i];
663 var c;
664
665 switch (p.type) {
666 case 'moveTo':
667 c = p;
668 lineStr.push(' m ', mr(p.x), ',', mr(p.y));
669 break;
670 case 'lineTo':
671 lineStr.push(' l ', mr(p.x), ',', mr(p.y));
672 break;
673 case 'close':
674 lineStr.push(' x ');
675 p = null;
676 break;
677 case 'bezierCurveTo':
678 lineStr.push(' c ',
679 mr(p.cp1x), ',', mr(p.cp1y), ',',
680 mr(p.cp2x), ',', mr(p.cp2y), ',',
681 mr(p.x), ',', mr(p.y));
682 break;
683 case 'at':
684 case 'wa':
685 lineStr.push(' ', p.type, ' ',
686 mr(p.x - this.arcScaleX_ * p.radius), ',',
687 mr(p.y - this.arcScaleY_ * p.radius), ' ',
688 mr(p.x + this.arcScaleX_ * p.radius), ',',
689 mr(p.y + this.arcScaleY_ * p.radius), ' ',
690 mr(p.xStart), ',', mr(p.yStart), ' ',
691 mr(p.xEnd), ',', mr(p.yEnd));
692 break;
693 }
694
695
696 // TODO: Following is broken for curves due to
697 // move to proper paths.
698
699 // Figure out dimensions so we can do gradient fills
700 // properly
701 if (p) {
702 if (min.x == null || p.x < min.x) {
703 min.x = p.x;
704 }
705 if (max.x == null || p.x > max.x) {
706 max.x = p.x;
707 }
708 if (min.y == null || p.y < min.y) {
709 min.y = p.y;
710 }
711 if (max.y == null || p.y > max.y) {
712 max.y = p.y;
713 }
714 }
715 }
716 lineStr.push(' ">');
717
718 if (!aFill) {
719 var lineWidth = this.lineScale_ * this.lineWidth;
720
721 // VML cannot correctly render a line if the width is less than 1px.
722 // In that case, we dilute the color to make the line look thinner.
723 if (lineWidth < 1) {
724 opacity *= lineWidth;
725 }
726
727 lineStr.push(
728 '<g_vml_:stroke',
729 ' opacity="', opacity, '"',
730 ' joinstyle="', this.lineJoin, '"',
731 ' miterlimit="', this.miterLimit, '"',
732 ' endcap="', processLineCap(this.lineCap), '"',
733 ' weight="', lineWidth, 'px"',
734 ' color="', color, '" />'
735 );
736 } else if (typeof this.fillStyle == 'object') {
737 var fillStyle = this.fillStyle;
738 var angle = 0;
739 var focus = {x: 0, y: 0};
740
741 // additional offset
742 var shift = 0;
743 // scale factor for offset
744 var expansion = 1;
745
746 if (fillStyle.type_ == 'gradient') {
747 var x0 = fillStyle.x0_ / this.arcScaleX_;
748 var y0 = fillStyle.y0_ / this.arcScaleY_;
749 var x1 = fillStyle.x1_ / this.arcScaleX_;
750 var y1 = fillStyle.y1_ / this.arcScaleY_;
751 var p0 = this.getCoords_(x0, y0);
752 var p1 = this.getCoords_(x1, y1);
753 var dx = p1.x - p0.x;
754 var dy = p1.y - p0.y;
755 angle = Math.atan2(dx, dy) * 180 / Math.PI;
756
757 // The angle should be a non-negative number.
758 if (angle < 0) {
759 angle += 360;
760 }
761
762 // Very small angles produce an unexpected result because they are
763 // converted to a scientific notation string.
764 if (angle < 1e-6) {
765 angle = 0;
766 }
767 } else {
768 var p0 = this.getCoords_(fillStyle.x0_, fillStyle.y0_);
769 var width = max.x - min.x;
770 var height = max.y - min.y;
771 focus = {
772 x: (p0.x - min.x) / width,
773 y: (p0.y - min.y) / height
774 };
775
776 width /= this.arcScaleX_ * Z;
777 height /= this.arcScaleY_ * Z;
778 var dimension = m.max(width, height);
779 shift = 2 * fillStyle.r0_ / dimension;
780 expansion = 2 * fillStyle.r1_ / dimension - shift;
781 }
782
783 // We need to sort the color stops in ascending order by offset,
784 // otherwise IE won't interpret it correctly.
785 var stops = fillStyle.colors_;
786 stops.sort(function(cs1, cs2) {
787 return cs1.offset - cs2.offset;
788 });
789
790 var length = stops.length;
791 var color1 = stops[0].color;
792 var color2 = stops[length - 1].color;
793 var opacity1 = stops[0].alpha * this.globalAlpha;
794 var opacity2 = stops[length - 1].alpha * this.globalAlpha;
795
796 var colors = [];
797 for (var i = 0; i < length; i++) {
798 var stop = stops[i];
799 colors.push(stop.offset * expansion + shift + ' ' + stop.color);
800 }
801
802 // When colors attribute is used, the meanings of opacity and o:opacity2
803 // are reversed.
804 lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"',
805 ' method="none" focus="100%"',
806 ' color="', color1, '"',
807 ' color2="', color2, '"',
808 ' colors="', colors.join(','), '"',
809 ' opacity="', opacity2, '"',
810 ' g_o_:opacity2="', opacity1, '"',
811 ' angle="', angle, '"',
812 ' focusposition="', focus.x, ',', focus.y, '" />');
813 } else {
814 lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity,
815 '" />');
816 }
817
818 lineStr.push('</g_vml_:shape>');
819
820 this.element_.insertAdjacentHTML('beforeEnd', lineStr.join(''));
821 };
822
823 contextPrototype.fill = function() {
824 this.stroke(true);
825 }
826
827 contextPrototype.closePath = function() {
828 this.currentPath_.push({type: 'close'});
829 };
830
831 /**
832 * @private
833 */
834 contextPrototype.getCoords_ = function(aX, aY) {
835 var m = this.m_;
836 return {
837 x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2,
838 y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2
839 }
840 };
841
842 contextPrototype.save = function() {
843 var o = {};
844 copyState(this, o);
845 this.aStack_.push(o);
846 this.mStack_.push(this.m_);
847 this.m_ = matrixMultiply(createMatrixIdentity(), this.m_);
848 };
849
850 contextPrototype.restore = function() {
851 copyState(this.aStack_.pop(), this);
852 this.m_ = this.mStack_.pop();
853 };
854
855 function matrixIsFinite(m) {
856 for (var j = 0; j < 3; j++) {
857 for (var k = 0; k < 2; k++) {
858 if (!isFinite(m[j][k]) || isNaN(m[j][k])) {
859 return false;
860 }
861 }
862 }
863 return true;
864 }
865
866 function setM(ctx, m, updateLineScale) {
867 if (!matrixIsFinite(m)) {
868 return;
869 }
870 ctx.m_ = m;
871
872 if (updateLineScale) {
873 // Get the line scale.
874 // Determinant of this.m_ means how much the area is enlarged by the
875 // transformation. So its square root can be used as a scale factor
876 // for width.
877 var det = m[0][0] * m[1][1] - m[0][1] * m[1][0];
878 ctx.lineScale_ = sqrt(abs(det));
879 }
880 }
881
882 contextPrototype.translate = function(aX, aY) {
883 var m1 = [
884 [1, 0, 0],
885 [0, 1, 0],
886 [aX, aY, 1]
887 ];
888
889 setM(this, matrixMultiply(m1, this.m_), false);
890 };
891
892 contextPrototype.rotate = function(aRot) {
893 var c = mc(aRot);
894 var s = ms(aRot);
895
896 var m1 = [
897 [c, s, 0],
898 [-s, c, 0],
899 [0, 0, 1]
900 ];
901
902 setM(this, matrixMultiply(m1, this.m_), false);
903 };
904
905 contextPrototype.scale = function(aX, aY) {
906 this.arcScaleX_ *= aX;
907 this.arcScaleY_ *= aY;
908 var m1 = [
909 [aX, 0, 0],
910 [0, aY, 0],
911 [0, 0, 1]
912 ];
913
914 setM(this, matrixMultiply(m1, this.m_), true);
915 };
916
917 contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) {
918 var m1 = [
919 [m11, m12, 0],
920 [m21, m22, 0],
921 [dx, dy, 1]
922 ];
923
924 setM(this, matrixMultiply(m1, this.m_), true);
925 };
926
927 contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) {
928 var m = [
929 [m11, m12, 0],
930 [m21, m22, 0],
931 [dx, dy, 1]
932 ];
933
934 setM(this, m, true);
935 };
936
937 /******** STUBS ********/
938 contextPrototype.clip = function() {
939 // TODO: Implement
940 };
941
942 contextPrototype.arcTo = function() {
943 // TODO: Implement
944 };
945
946 contextPrototype.createPattern = function() {
947 return new CanvasPattern_;
948 };
949
950 // Gradient / Pattern Stubs
951 function CanvasGradient_(aType) {
952 this.type_ = aType;
953 this.x0_ = 0;
954 this.y0_ = 0;
955 this.r0_ = 0;
956 this.x1_ = 0;
957 this.y1_ = 0;
958 this.r1_ = 0;
959 this.colors_ = [];
960 }
961
962 CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) {
963 aColor = processStyle(aColor);
964 this.colors_.push({offset: aOffset,
965 color: aColor.color,
966 alpha: aColor.alpha});
967 };
968
969 function CanvasPattern_() {}
970
971 // set up externs
972 G_vmlCanvasManager = G_vmlCanvasManager_;
973 CanvasRenderingContext2D = CanvasRenderingContext2D_;
974 CanvasGradient = CanvasGradient_;
975 CanvasPattern = CanvasPattern_;
976
977 })();
978
979 } // if
980 /*----------------------------------------------------------------------------\
981 | Range Class |
982 |-----------------------------------------------------------------------------|
983 | Created by Erik Arvidsson |
984 | (http://webfx.eae.net/contact.html#erik) |
985 | For WebFX (http://webfx.eae.net/) |
986 |-----------------------------------------------------------------------------|
987 | Used to model the data used when working with sliders, scrollbars and |
988 | progress bars. Based on the ideas of the javax.swing.BoundedRangeModel |
989 | interface defined by Sun for Java; http://java.sun.com/products/jfc/ |
990 | swingdoc-api-1.0.3/com/sun/java/swing/BoundedRangeModel.html |
991 |-----------------------------------------------------------------------------|
992 | Copyright (c) 2002, 2005, 2006 Erik Arvidsson |
993 |-----------------------------------------------------------------------------|
994 | Licensed under the Apache License, Version 2.0 (the "License"); you may not |
995 | use this file except in compliance with the License. You may obtain a copy |
996 | of the License at http://www.apache.org/licenses/LICENSE-2.0 |
997 | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
998 | Unless required by applicable law or agreed to in writing, software |
999 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
1000 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
1001 | License for the specific language governing permissions and limitations |
1002 | under the License. |
1003 |-----------------------------------------------------------------------------|
1004 | 2002-10-14 | Original version released |
1005 | 2005-10-27 | Use Math.round instead of Math.floor |
1006 | 2006-05-28 | Changed license to Apache Software License 2.0. |
1007 |-----------------------------------------------------------------------------|
1008 | Created 2002-10-14 | All changes are in the log above. | Updated 2006-05-28 |
1009 \----------------------------------------------------------------------------*/
1010
1011
1012 function Range() {
1013 this._value = 0;
1014 this._minimum = 0;
1015 this._maximum = 100;
1016 this._extent = 0;
1017
1018 this._isChanging = false;
1019 }
1020
1021 Range.prototype.setValue = function (value) {
1022 value = Math.round(parseFloat(value));
1023 if (isNaN(value)) return;
1024 if (this._value != value) {
1025 if (value + this._extent > this._maximum)
1026 this._value = this._maximum - this._extent;
1027 else if (value < this._minimum)
1028 this._value = this._minimum;
1029 else
1030 this._value = value;
1031 if (!this._isChanging && typeof this.onchange == "function")
1032 this.onchange();
1033 }
1034 };
1035
1036 Range.prototype.getValue = function () {
1037 return this._value;
1038 };
1039
1040 Range.prototype.setExtent = function (extent) {
1041 if (this._extent != extent) {
1042 if (extent < 0)
1043 this._extent = 0;
1044 else if (this._value + extent > this._maximum)
1045 this._extent = this._maximum - this._value;
1046 else
1047 this._extent = extent;
1048 if (!this._isChanging && typeof this.onchange == "function")
1049 this.onchange();
1050 }
1051 };
1052
1053 Range.prototype.getExtent = function () {
1054 return this._extent;
1055 };
1056
1057 Range.prototype.setMinimum = function (minimum) {
1058 if (this._minimum != minimum) {
1059 var oldIsChanging = this._isChanging;
1060 this._isChanging = true;
1061
1062 this._minimum = minimum;
1063
1064 if (minimum > this._value)
1065 this.setValue(minimum);
1066 if (minimum > this._maximum) {
1067 this._extent = 0;
1068 this.setMaximum(minimum);
1069 this.setValue(minimum)
1070 }
1071 if (minimum + this._extent > this._maximum)
1072 this._extent = this._maximum - this._minimum;
1073
1074 this._isChanging = oldIsChanging;
1075 if (!this._isChanging && typeof this.onchange == "function")
1076 this.onchange();
1077 }
1078 };
1079
1080 Range.prototype.getMinimum = function () {
1081 return this._minimum;
1082 };
1083
1084 Range.prototype.setMaximum = function (maximum) {
1085 if (this._maximum != maximum) {
1086 var oldIsChanging = this._isChanging;
1087 this._isChanging = true;
1088
1089 this._maximum = maximum;
1090
1091 if (maximum < this._value)
1092 this.setValue(maximum - this._extent);
1093 if (maximum < this._minimum) {
1094 this._extent = 0;
1095 this.setMinimum(maximum);
1096 this.setValue(this._maximum);
1097 }
1098 if (maximum < this._minimum + this._extent)
1099 this._extent = this._maximum - this._minimum;
1100 if (maximum < this._value + this._extent)
1101 this._extent = this._maximum - this._value;
1102
1103 this._isChanging = oldIsChanging;
1104 if (!this._isChanging && typeof this.onchange == "function")
1105 this.onchange();
1106 }
1107 };
1108
1109 Range.prototype.getMaximum = function () {
1110 return this._maximum;
1111 };
1112 /*----------------------------------------------------------------------------\
1113 | Slider 1.02 |
1114 |-----------------------------------------------------------------------------|
1115 | Created by Erik Arvidsson |
1116 | (http://webfx.eae.net/contact.html#erik) |
1117 | For WebFX (http://webfx.eae.net/) |
1118 |-----------------------------------------------------------------------------|
1119 | A slider control that degrades to an input control for non supported |
1120 | browsers. |
1121 |-----------------------------------------------------------------------------|
1122 | Copyright (c) 2002, 2003, 2006 Erik Arvidsson |
1123 |-----------------------------------------------------------------------------|
1124 | Licensed under the Apache License, Version 2.0 (the "License"); you may not |
1125 | use this file except in compliance with the License. You may obtain a copy |
1126 | of the License at http://www.apache.org/licenses/LICENSE-2.0 |
1127 | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
1128 | Unless required by applicable law or agreed to in writing, software |
1129 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
1130 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
1131 | License for the specific language governing permissions and limitations |
1132 | under the License. |
1133 |-----------------------------------------------------------------------------|
1134 | Dependencies: timer.js - an OO abstraction of timers |
1135 | range.js - provides the data model for the slider |
1136 | winclassic.css or any other css file describing the look |
1137 |-----------------------------------------------------------------------------|
1138 | 2002-10-14 | Original version released |
1139 | 2003-03-27 | Added a test in the constructor for missing oElement arg |
1140 | 2003-11-27 | Only use mousewheel when focused |
1141 | 2006-05-28 | Changed license to Apache Software License 2.0. |
1142 |-----------------------------------------------------------------------------|
1143 | Created 2002-10-14 | All changes are in the log above. | Updated 2006-05-28 |
1144 \----------------------------------------------------------------------------*/
1145
1146 Slider.isSupported = typeof document.createElement != "undefined" &&
1147 typeof document.documentElement != "undefined" &&
1148 typeof document.documentElement.offsetWidth == "number";
1149
1150
1151 function Slider(oElement, oInput, sOrientation) {
1152 if (!oElement) return;
1153 this._orientation = sOrientation || "horizontal";
1154 this._range = new Range();
1155 this._range.setExtent(0);
1156 this._blockIncrement = 10;
1157 this._unitIncrement = 1;
1158 this._timer = new Timer(100);
1159
1160
1161 if (Slider.isSupported && oElement) {
1162
1163 this.document = oElement.ownerDocument || oElement.document;
1164
1165 this.element = oElement;
1166 this.element.slider = this;
1167 this.element.unselectable = "on";
1168
1169 // add class name tag to class name
1170 this.element.className = this._orientation + " " + this.classNameTag + " " + this.element.className;
1171
1172 // create line
1173 this.line = this.document.createElement("DIV");
1174 this.line.className = "line";
1175 this.line.unselectable = "on";
1176 this.line.appendChild(this.document.createElement("DIV"));
1177 this.element.appendChild(this.line);
1178
1179 // create handle
1180 this.handle = this.document.createElement("DIV");
1181 this.handle.className = "handle";
1182 this.handle.unselectable = "on";
1183 this.handle.appendChild(this.document.createElement("DIV"));
1184 this.handle.firstChild.appendChild(
1185 this.document.createTextNode(String.fromCharCode(160)));
1186 this.element.appendChild(this.handle);
1187 }
1188
1189 this.input = oInput;
1190
1191 // events
1192 var oThis = this;
1193 this._range.onchange = function () {
1194 oThis.recalculate();
1195 if (typeof oThis.onchange == "function")
1196 oThis.onchange();
1197 };
1198
1199 if (Slider.isSupported && oElement) {
1200 this.element.onfocus = Slider.eventHandlers.onfocus;
1201 this.element.onblur = Slider.eventHandlers.onblur;
1202 this.element.onmousedown = Slider.eventHandlers.onmousedown;
1203 this.element.onmouseover = Slider.eventHandlers.onmouseover;
1204 this.element.onmouseout = Slider.eventHandlers.onmouseout;
1205 this.element.onkeydown = Slider.eventHandlers.onkeydown;
1206 this.element.onkeypress = Slider.eventHandlers.onkeypress;
1207 this.element.onmousewheel = Slider.eventHandlers.onmousewheel;
1208 this.handle.onselectstart =
1209 this.element.onselectstart = function () { return false; };
1210
1211 this._timer.ontimer = function () {
1212 oThis.ontimer();
1213 };
1214
1215 // extra recalculate for ie
1216 window.setTimeout(function() {
1217 oThis.recalculate();
1218 }, 1);
1219 }
1220 else {
1221 this.input.onchange = function (e) {
1222 oThis.setValue(oThis.input.value);
1223 };
1224 }
1225 }
1226
1227 Slider.eventHandlers = {
1228
1229 // helpers to make events a bit easier
1230 getEvent: function (e, el) {
1231 if (!e) {
1232 if (el)
1233 e = el.document.parentWindow.event;
1234 else
1235 e = window.event;
1236 }
1237 if (!e.srcElement) {
1238 var el = e.target;
1239 while (el != null && el.nodeType != 1)
1240 el = el.parentNode;
1241 e.srcElement = el;
1242 }
1243 if (typeof e.offsetX == "undefined") {
1244 e.offsetX = e.layerX;
1245 e.offsetY = e.layerY;
1246 }
1247
1248 return e;
1249 },
1250
1251 getDocument: function (e) {
1252 if (e.target)
1253 return e.target.ownerDocument;
1254 return e.srcElement.document;
1255 },
1256
1257 getSlider: function (e) {
1258 var el = e.target || e.srcElement;
1259 while (el != null && el.slider == null) {
1260 el = el.parentNode;
1261 }
1262 if (el)
1263 return el.slider;
1264 return null;
1265 },
1266
1267 getLine: function (e) {
1268 var el = e.target || e.srcElement;
1269 while (el != null && el.className != "line") {
1270 el = el.parentNode;
1271 }
1272 return el;
1273 },
1274
1275 getHandle: function (e) {
1276 var el = e.target || e.srcElement;
1277 var re = /handle/;
1278 while (el != null && !re.test(el.className)) {
1279 el = el.parentNode;
1280 }
1281 return el;
1282 },
1283 // end helpers
1284
1285 onfocus: function (e) {
1286 var s = this.slider;
1287 s._focused = true;
1288 s.handle.className = "handle hover";
1289 },
1290
1291 onblur: function (e) {
1292 var s = this.slider
1293 s._focused = false;
1294 s.handle.className = "handle";
1295 },
1296
1297 onmouseover: function (e) {
1298 e = Slider.eventHandlers.getEvent(e, this);
1299 var s = this.slider;
1300 if (e.srcElement == s.handle)
1301 s.handle.className = "handle hover";
1302 },
1303
1304 onmouseout: function (e) {
1305 e = Slider.eventHandlers.getEvent(e, this);
1306 var s = this.slider;
1307 if (e.srcElement == s.handle && !s._focused)
1308 s.handle.className = "handle";
1309 },
1310
1311 onmousedown: function (e) {
1312 e = Slider.eventHandlers.getEvent(e, this);
1313 var s = this.slider;
1314 if (s.element.focus)
1315 s.element.focus();
1316
1317 Slider._currentInstance = s;
1318 var doc = s.document;
1319
1320 if (doc.addEventListener) {
1321 doc.addEventListener("mousemove", Slider.eventHandlers.onmousemove, true);
1322 doc.addEventListener("mouseup", Slider.eventHandlers.onmouseup, true);
1323 }
1324 else if (doc.attachEvent) {
1325 doc.attachEvent("onmousemove", Slider.eventHandlers.onmousemove);
1326 doc.attachEvent("onmouseup", Slider.eventHandlers.onmouseup);
1327 doc.attachEvent("onlosecapture", Slider.eventHandlers.onmouseup);
1328 s.element.setCapture();
1329 }
1330
1331 if (Slider.eventHandlers.getHandle(e)) { // start drag
1332 Slider._sliderDragData = {
1333 screenX: e.screenX,
1334 screenY: e.screenY,
1335 dx: e.screenX - s.handle.offsetLeft,
1336 dy: e.screenY - s.handle.offsetTop,
1337 startValue: s.getValue(),
1338 slider: s
1339 };
1340 }
1341 else {
1342 return;
1343 var lineEl = Slider.eventHandlers.getLine(e);
1344 s._mouseX = e.offsetX + (lineEl ? s.line.offsetLeft : 0);
1345 s._mouseY = e.offsetY + (lineEl ? s.line.offsetTop : 0);
1346 s._increasing = null;
1347 s.ontimer();
1348 }
1349 },
1350
1351 onmousemove: function (e) {
1352 e = Slider.eventHandlers.getEvent(e, this);
1353
1354 if (Slider._sliderDragData) { // drag
1355 var s = Slider._sliderDragData.slider;
1356
1357 var boundSize = s.getMaximum() - s.getMinimum();
1358 var size, pos, reset;
1359
1360 if (s._orientation == "horizontal") {
1361 size = s.element.offsetWidth - s.handle.offsetWidth;
1362 pos = e.screenX - Slider._sliderDragData.dx;
1363 reset = Math.abs(e.screenY - Slider._sliderDragData.screenY) > 100;
1364 }
1365 else {
1366 size = s.element.offsetHeight - s.handle.offsetHeight;
1367 pos = s.element.offsetHeight - s.handle.offsetHeight -
1368 (e.screenY - Slider._sliderDragData.dy);
1369 reset = Math.abs(e.screenX - Slider._sliderDragData.screenX) > 100;
1370 }
1371 s.setValue(reset ? Slider._sliderDragData.startValue :
1372 s.getMinimum() + boundSize * pos / size);
1373 return false;
1374 }
1375 else {
1376 return;
1377 var s = Slider._currentInstance;
1378 if (s != null) {
1379 var lineEl = Slider.eventHandlers.getLine(e);
1380 s._mouseX = e.offsetX + (lineEl ? s.line.offsetLeft : 0);
1381 s._mouseY = e.offsetY + (lineEl ? s.line.offsetTop : 0);
1382 }
1383 }
1384
1385 },
1386
1387 onmouseup: function (e) {
1388 e = Slider.eventHandlers.getEvent(e, this);
1389 var s = Slider._currentInstance;
1390 var doc = s.document;
1391 if (doc.removeEventListener) {
1392 doc.removeEventListener("mousemove", Slider.eventHandlers.onmousemove, true);
1393 doc.removeEventListener("mouseup", Slider.eventHandlers.onmouseup, true);
1394 }
1395 else if (doc.detachEvent) {
1396 doc.detachEvent("onmousemove", Slider.eventHandlers.onmousemove);
1397 doc.detachEvent("onmouseup", Slider.eventHandlers.onmouseup);
1398 doc.detachEvent("onlosecapture", Slider.eventHandlers.onmouseup);
1399 s.element.releaseCapture();
1400 }
1401
1402 if (Slider._sliderDragData) { // end drag
1403 Slider._sliderDragData = null;
1404 }
1405 else {
1406 return;
1407 s._timer.stop();
1408 s._increasing = null;
1409 }
1410 Slider._currentInstance = null;
1411 },
1412
1413 onkeydown: function (e) {
1414 return;
1415 e = Slider.eventHandlers.getEvent(e, this);
1416 //var s = Slider.eventHandlers.getSlider(e);
1417 var s = this.slider;
1418 var kc = e.keyCode;
1419 switch (kc) {
1420 case 33: // page up
1421 s.setValue(s.getValue() + s.getBlockIncrement());
1422 break;
1423 case 34: // page down
1424 s.setValue(s.getValue() - s.getBlockIncrement());
1425 break;
1426 case 35: // end
1427 s.setValue(s.getOrientation() == "horizontal" ?
1428 s.getMaximum() :
1429 s.getMinimum());
1430 break;
1431 case 36: // home
1432 s.setValue(s.getOrientation() == "horizontal" ?
1433 s.getMinimum() :
1434 s.getMaximum());
1435 break;
1436 case 38: // up
1437 case 39: // right
1438 s.setValue(s.getValue() + s.getUnitIncrement());
1439 break;
1440
1441 case 37: // left
1442 case 40: // down
1443 s.setValue(s.getValue() - s.getUnitIncrement());
1444 break;
1445 }
1446
1447 if (kc >= 33 && kc <= 40) {
1448 return false;
1449 }
1450 },
1451
1452 onkeypress: function (e) {
1453 return;
1454 e = Slider.eventHandlers.getEvent(e, this);
1455 var kc = e.keyCode;
1456 if (kc >= 33 && kc <= 40) {
1457 return false;
1458 }
1459 },
1460
1461 onmousewheel: function (e) {
1462 return;
1463 e = Slider.eventHandlers.getEvent(e, this);
1464 var s = this.slider;
1465 if (s._focused) {
1466 s.setValue(s.getValue() + e.wheelDelta / 120 * s.getUnitIncrement());
1467 // windows inverts this on horizontal sliders. That does not
1468 // make sense to me
1469 return false;
1470 }
1471 }
1472 };
1473
1474
1475
1476 Slider.prototype.classNameTag = "dynamic-slider-control",
1477
1478 Slider.prototype.setValue = function (v) {
1479 this._range.setValue(v);
1480 this.input.value = this.getValue();
1481 };
1482
1483 Slider.prototype.getValue = function () {
1484 return this._range.getValue();
1485 };
1486
1487 Slider.prototype.setMinimum = function (v) {
1488 this._range.setMinimum(v);
1489 this.input.value = this.getValue();
1490 };
1491
1492 Slider.prototype.getMinimum = function () {
1493 return this._range.getMinimum();
1494 };
1495
1496 Slider.prototype.setMaximum = function (v) {
1497 this._range.setMaximum(v);
1498 this.input.value = this.getValue();
1499 };
1500
1501 Slider.prototype.getMaximum = function () {
1502 return this._range.getMaximum();
1503 };
1504
1505 Slider.prototype.setUnitIncrement = function (v) {
1506 this._unitIncrement = v;
1507 };
1508
1509 Slider.prototype.getUnitIncrement = function () {
1510 return this._unitIncrement;
1511 };
1512
1513 Slider.prototype.setBlockIncrement = function (v) {
1514 this._blockIncrement = v;
1515 };
1516
1517 Slider.prototype.getBlockIncrement = function () {
1518 return this._blockIncrement;
1519 };
1520
1521 Slider.prototype.getOrientation = function () {
1522 return this._orientation;
1523 };
1524
1525 Slider.prototype.setOrientation = function (sOrientation) {
1526 if (sOrientation != this._orientation) {
1527 if (Slider.isSupported && this.element) {
1528 // add class name tag to class name
1529 this.element.className = this.element.className.replace(this._orientation,
1530 sOrientation);
1531 }
1532 this._orientation = sOrientation;
1533 this.recalculate();
1534
1535 }
1536 };
1537
1538 Slider.prototype.recalculate = function() {
1539 if (!Slider.isSupported || !this.element) return;
1540
1541 var w = this.element.offsetWidth;
1542 var h = this.element.offsetHeight;
1543 var hw = this.handle.offsetWidth;
1544 var hh = this.handle.offsetHeight;
1545 var lw = this.line.offsetWidth;
1546 var lh = this.line.offsetHeight;
1547
1548 // this assumes a border-box layout
1549
1550 if (this._orientation == "horizontal") {
1551 this.handle.style.left = (w - hw) * (this.getValue() - this.getMinimum()) /
1552 (this.getMaximum() - this.getMinimum()) + "px";
1553 this.handle.style.top = (h - hh) / 2 + "px";
1554
1555 this.line.style.top = (h - lh) / 2 + "px";
1556 this.line.style.left = hw / 2 + "px";
1557 //this.line.style.right = hw / 2 + "px";
1558 this.line.style.width = Math.max(0, w - hw - 2)+ "px";
1559 this.line.firstChild.style.width = Math.max(0, w - hw - 4)+ "px";
1560 }
1561 else {
1562 this.handle.style.left = (w - hw) / 2 + "px";
1563 this.handle.style.top = h - hh - (h - hh) * (this.getValue() - this.getMinimum()) /
1564 (this.getMaximum() - this.getMinimum()) + "px";
1565
1566 this.line.style.left = (w - lw) / 2 + "px";
1567 this.line.style.top = hh / 2 + "px";
1568 this.line.style.height = Math.max(0, h - hh - 2) + "px"; //hard coded border width
1569 //this.line.style.bottom = hh / 2 + "px";
1570 this.line.firstChild.style.height = Math.max(0, h - hh - 4) + "px"; //hard coded border width
1571 }
1572 };
1573
1574 Slider.prototype.ontimer = function () {
1575 var hw = this.handle.offsetWidth;
1576 var hh = this.handle.offsetHeight;
1577 var hl = this.handle.offsetLeft;
1578 var ht = this.handle.offsetTop;
1579
1580 if (this._orientation == "horizontal") {
1581 if (this._mouseX > hl + hw &&
1582 (this._increasing == null || this._increasing)) {
1583 this.setValue(this.getValue() + this.getBlockIncrement());
1584 this._increasing = true;
1585 }
1586 else if (this._mouseX < hl &&
1587 (this._increasing == null || !this._increasing)) {
1588 this.setValue(this.getValue() - this.getBlockIncrement());
1589 this._increasing = false;
1590 }
1591 }
1592 else {
1593 if (this._mouseY > ht + hh &&
1594 (this._increasing == null || !this._increasing)) {
1595 this.setValue(this.getValue() - this.getBlockIncrement());
1596 this._increasing = false;
1597 }
1598 else if (this._mouseY < ht &&
1599 (this._increasing == null || this._increasing)) {
1600 this.setValue(this.getValue() + this.getBlockIncrement());
1601 this._increasing = true;
1602 }
1603 }
1604
1605 this._timer.start();
1606 };
1607 /*----------------------------------------------------------------------------\
1608 | Timer Class |
1609 |-----------------------------------------------------------------------------|
1610 | Created by Erik Arvidsson |
1611 | (http://webfx.eae.net/contact.html#erik) |
1612 | For WebFX (http://webfx.eae.net/) |
1613 |-----------------------------------------------------------------------------|
1614 | Object Oriented Encapsulation of setTimeout fires ontimer when the timer |
1615 | is triggered. Does not work in IE 5.00 |
1616 |-----------------------------------------------------------------------------|
1617 | Copyright (c) 2002, 2006 Erik Arvidsson |
1618 |-----------------------------------------------------------------------------|
1619 | Licensed under the Apache License, Version 2.0 (the "License"); you may not |
1620 | use this file except in compliance with the License. You may obtain a copy |
1621 | of the License at http://www.apache.org/licenses/LICENSE-2.0 |
1622 | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
1623 | Unless required by applicable law or agreed to in writing, software |
1624 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
1625 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
1626 | License for the specific language governing permissions and limitations |
1627 | under the License. |
1628 |-----------------------------------------------------------------------------|
1629 | 2002-10-14 | Original version released |
1630 | 2006-05-28 | Changed license to Apache Software License 2.0. |
1631 |-----------------------------------------------------------------------------|
1632 | Created 2002-10-14 | All changes are in the log above. | Updated 2006-05-28 |
1633 \----------------------------------------------------------------------------*/
1634
1635 function Timer(nPauseTime) {
1636 this._pauseTime = typeof nPauseTime == "undefined" ? 1000 : nPauseTime;
1637 this._timer = null;
1638 this._isStarted = false;
1639 }
1640
1641 Timer.prototype.start = function () {
1642 if (this.isStarted())
1643 this.stop();
1644 var oThis = this;
1645 this._timer = window.setTimeout(function () {
1646 if (typeof oThis.ontimer == "function")
1647 oThis.ontimer();
1648 }, this._pauseTime);
1649 this._isStarted = false;
1650 };
1651
1652 Timer.prototype.stop = function () {
1653 if (this._timer != null)
1654 window.clearTimeout(this._timer);
1655 this._isStarted = false;
1656 };
1657
1658 Timer.prototype.isStarted = function () {
1659 return this._isStarted;
1660 };
1661
1662 Timer.prototype.getPauseTime = function () {
1663 return this._pauseTime;
1664 };
1665
1666 Timer.prototype.setPauseTime = function (nPauseTime) {
1667 this._pauseTime = nPauseTime;
1668 };
1669 /*
1670
1671 OpenLayers.js -- OpenLayers Map Viewer Library
1672
1673 Copyright (c) 2006-2013 by OpenLayers Contributors
1674 Published under the 2-clause BSD license.
1675 See http://openlayers.org/dev/license.txt for the full text of the license, and http://openlayers.org/dev/authors.txt for full list of contributors.
1676
1677 Includes compressed code under the following licenses:
1678
1679 (For uncompressed versions of the code used, please see the
1680 OpenLayers Github repository: <https://github.com/openlayers/openlayers>)
1681
1682 */
1683
1684 /**
1685 * Contains XMLHttpRequest.js <http://code.google.com/p/xmlhttprequest/>
1686 * Copyright 2007 Sergey Ilinsky (http://www.ilinsky.com)
1687 *
1688 * Licensed under the Apache License, Version 2.0 (the "License");
1689 * you may not use this file except in compliance with the License.
1690 * You may obtain a copy of the License at
1691 * http://www.apache.org/licenses/LICENSE-2.0
1692 */
1693
1694 /**
1695 * OpenLayers.Util.pagePosition is based on Yahoo's getXY method, which is
1696 * Copyright (c) 2006, Yahoo! Inc.
1697 * All rights reserved.
1698 *
1699 * Redistribution and use of this software in source and binary forms, with or
1700 * without modification, are permitted provided that the following conditions
1701 * are met:
1702 *
1703 * * Redistributions of source code must retain the above copyright notice,
1704 * this list of conditions and the following disclaimer.
1705 *
1706 * * Redistributions in binary form must reproduce the above copyright notice,
1707 * this list of conditions and the following disclaimer in the documentation
1708 * and/or other materials provided with the distribution.
1709 *
1710 * * Neither the name of Yahoo! Inc. nor the names of its contributors may be
1711 * used to endorse or promote products derived from this software without
1712 * specific prior written permission of Yahoo! Inc.
1713 *
1714 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
1715 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1716 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1717 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
1718 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
1719 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
1720 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
1721 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
1722 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
1723 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
1724 * POSSIBILITY OF SUCH DAMAGE.
1725 */
1726 var OpenLayers={VERSION_NUMBER:"Release 2.13.1",singleFile:!0,_getScriptLocation:function(){for(var a=/(^|(.*?\/))(OpenLayers[^\/]*?\.js)(\?|$)/,b=document.getElementsByTagName("script"),c,d="",e=0,f=b.length;e<f;e++)if(c=b[e].getAttribute("src"))if(c=c.match(a)){d=c[1];break}return function(){return d}}(),ImgPath:""};OpenLayers.Class=function(){var a=arguments.length,b=arguments[0],c=arguments[a-1],d="function"==typeof c.initialize?c.initialize:function(){b.prototype.initialize.apply(this,arguments)};1<a?(a=[d,b].concat(Array.prototype.slice.call(arguments).slice(1,a-1),c),OpenLayers.inherit.apply(null,a)):d.prototype=c;return d};
1727 OpenLayers.inherit=function(a,b){var c=function(){};c.prototype=b.prototype;a.prototype=new c;var d,e,c=2;for(d=arguments.length;c<d;c++)e=arguments[c],"function"===typeof e&&(e=e.prototype),OpenLayers.Util.extend(a.prototype,e)};OpenLayers.Util=OpenLayers.Util||{};OpenLayers.Util.extend=function(a,b){a=a||{};if(b){for(var c in b){var d=b[c];void 0!==d&&(a[c]=d)}"function"==typeof window.Event&&b instanceof window.Event||(!b.hasOwnProperty||!b.hasOwnProperty("toString"))||(a.toString=b.toString)}return a};OpenLayers.String={startsWith:function(a,b){return 0==a.indexOf(b)},contains:function(a,b){return-1!=a.indexOf(b)},trim:function(a){return a.replace(/^\s\s*/,"").replace(/\s\s*$/,"")},camelize:function(a){a=a.split("-");for(var b=a[0],c=1,d=a.length;c<d;c++)var e=a[c],b=b+(e.charAt(0).toUpperCase()+e.substring(1));return b},format:function(a,b,c){b||(b=window);return a.replace(OpenLayers.String.tokenRegEx,function(a,e){for(var f,g=e.split(/\.+/),h=0;h<g.length;h++){0==h&&(f=b);if(void 0===f)break;
1728 f=f[g[h]]}"function"==typeof f&&(f=c?f.apply(null,c):f());return"undefined"==typeof f?"undefined":f})},tokenRegEx:/\$\{([\w.]+?)\}/g,numberRegEx:/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/,isNumeric:function(a){return OpenLayers.String.numberRegEx.test(a)},numericIf:function(a,b){var c=a;!0===b&&(null!=a&&a.replace)&&(a=a.replace(/^\s*|\s*$/g,""));return OpenLayers.String.isNumeric(a)?parseFloat(a):c}};
1729 OpenLayers.Number={decimalSeparator:".",thousandsSeparator:",",limitSigDigs:function(a,b){var c=0;0<b&&(c=parseFloat(a.toPrecision(b)));return c},format:function(a,b,c,d){b="undefined"!=typeof b?b:0;c="undefined"!=typeof c?c:OpenLayers.Number.thousandsSeparator;d="undefined"!=typeof d?d:OpenLayers.Number.decimalSeparator;null!=b&&(a=parseFloat(a.toFixed(b)));var e=a.toString().split(".");1==e.length&&null==b&&(b=0);a=e[0];if(c)for(var f=/(-?[0-9]+)([0-9]{3})/;f.test(a);)a=a.replace(f,"$1"+c+"$2");
1730 0==b?b=a:(c=1<e.length?e[1]:"0",null!=b&&(c+=Array(b-c.length+1).join("0")),b=a+d+c);return b},zeroPad:function(a,b,c){for(a=a.toString(c||10);a.length<b;)a="0"+a;return a}};
1731 OpenLayers.Function={bind:function(a,b){var c=Array.prototype.slice.apply(arguments,[2]);return function(){var d=c.concat(Array.prototype.slice.apply(arguments,[0]));return a.apply(b,d)}},bindAsEventListener:function(a,b){return function(c){return a.call(b,c||window.event)}},False:function(){return!1},True:function(){return!0},Void:function(){}};
1732 OpenLayers.Array={filter:function(a,b,c){var d=[];if(Array.prototype.filter)d=a.filter(b,c);else{var e=a.length;if("function"!=typeof b)throw new TypeError;for(var f=0;f<e;f++)if(f in a){var g=a[f];b.call(c,g,f,a)&&d.push(g)}}return d}};OpenLayers.Bounds=OpenLayers.Class({left:null,bottom:null,right:null,top:null,centerLonLat:null,initialize:function(a,b,c,d){OpenLayers.Util.isArray(a)&&(d=a[3],c=a[2],b=a[1],a=a[0]);null!=a&&(this.left=OpenLayers.Util.toFloat(a));null!=b&&(this.bottom=OpenLayers.Util.toFloat(b));null!=c&&(this.right=OpenLayers.Util.toFloat(c));null!=d&&(this.top=OpenLayers.Util.toFloat(d))},clone:function(){return new OpenLayers.Bounds(this.left,this.bottom,this.right,this.top)},equals:function(a){var b=!1;null!=
1733 a&&(b=this.left==a.left&&this.right==a.right&&this.top==a.top&&this.bottom==a.bottom);return b},toString:function(){return[this.left,this.bottom,this.right,this.top].join()},toArray:function(a){return!0===a?[this.bottom,this.left,this.top,this.right]:[this.left,this.bottom,this.right,this.top]},toBBOX:function(a,b){null==a&&(a=6);var c=Math.pow(10,a),d=Math.round(this.left*c)/c,e=Math.round(this.bottom*c)/c,f=Math.round(this.right*c)/c,c=Math.round(this.top*c)/c;return!0===b?e+","+d+","+c+","+f:d+
1734 ","+e+","+f+","+c},toGeometry:function(){return new OpenLayers.Geometry.Polygon([new OpenLayers.Geometry.LinearRing([new OpenLayers.Geometry.Point(this.left,this.bottom),new OpenLayers.Geometry.Point(this.right,this.bottom),new OpenLayers.Geometry.Point(this.right,this.top),new OpenLayers.Geometry.Point(this.left,this.top)])])},getWidth:function(){return this.right-this.left},getHeight:function(){return this.top-this.bottom},getSize:function(){return new OpenLayers.Size(this.getWidth(),this.getHeight())},
1735 getCenterPixel:function(){return new OpenLayers.Pixel((this.left+this.right)/2,(this.bottom+this.top)/2)},getCenterLonLat:function(){this.centerLonLat||(this.centerLonLat=new OpenLayers.LonLat((this.left+this.right)/2,(this.bottom+this.top)/2));return this.centerLonLat},scale:function(a,b){null==b&&(b=this.getCenterLonLat());var c,d;"OpenLayers.LonLat"==b.CLASS_NAME?(c=b.lon,d=b.lat):(c=b.x,d=b.y);return new OpenLayers.Bounds((this.left-c)*a+c,(this.bottom-d)*a+d,(this.right-c)*a+c,(this.top-d)*a+
1736 d)},add:function(a,b){if(null==a||null==b)throw new TypeError("Bounds.add cannot receive null values");return new OpenLayers.Bounds(this.left+a,this.bottom+b,this.right+a,this.top+b)},extend:function(a){if(a)switch(a.CLASS_NAME){case "OpenLayers.LonLat":this.extendXY(a.lon,a.lat);break;case "OpenLayers.Geometry.Point":this.extendXY(a.x,a.y);break;case "OpenLayers.Bounds":this.centerLonLat=null;if(null==this.left||a.left<this.left)this.left=a.left;if(null==this.bottom||a.bottom<this.bottom)this.bottom=
1737 a.bottom;if(null==this.right||a.right>this.right)this.right=a.right;if(null==this.top||a.top>this.top)this.top=a.top}},extendXY:function(a,b){this.centerLonLat=null;if(null==this.left||a<this.left)this.left=a;if(null==this.bottom||b<this.bottom)this.bottom=b;if(null==this.right||a>this.right)this.right=a;if(null==this.top||b>this.top)this.top=b},containsLonLat:function(a,b){"boolean"===typeof b&&(b={inclusive:b});b=b||{};var c=this.contains(a.lon,a.lat,b.inclusive),d=b.worldBounds;d&&!c&&(c=d.getWidth(),
1738 d=Math.round((a.lon-(d.left+d.right)/2)/c),c=this.containsLonLat({lon:a.lon-d*c,lat:a.lat},{inclusive:b.inclusive}));return c},containsPixel:function(a,b){return this.contains(a.x,a.y,b)},contains:function(a,b,c){null==c&&(c=!0);if(null==a||null==b)return!1;a=OpenLayers.Util.toFloat(a);b=OpenLayers.Util.toFloat(b);var d=!1;return d=c?a>=this.left&&a<=this.right&&b>=this.bottom&&b<=this.top:a>this.left&&a<this.right&&b>this.bottom&&b<this.top},intersectsBounds:function(a,b){"boolean"===typeof b&&(b=
1739 {inclusive:b});b=b||{};if(b.worldBounds){var c=this.wrapDateLine(b.worldBounds);a=a.wrapDateLine(b.worldBounds)}else c=this;null==b.inclusive&&(b.inclusive=!0);var d=!1,e=c.left==a.right||c.right==a.left||c.top==a.bottom||c.bottom==a.top;if(b.inclusive||!e)var d=a.top>=c.bottom&&a.top<=c.top||c.top>a.bottom&&c.top<a.top,e=a.left>=c.left&&a.left<=c.right||c.left>=a.left&&c.left<=a.right,f=a.right>=c.left&&a.right<=c.right||c.right>=a.left&&c.right<=a.right,d=(a.bottom>=c.bottom&&a.bottom<=c.top||c.bottom>=
1740 a.bottom&&c.bottom<=a.top||d)&&(e||f);if(b.worldBounds&&!d){var g=b.worldBounds,e=g.getWidth(),f=!g.containsBounds(c),g=!g.containsBounds(a);f&&!g?(a=a.add(-e,0),d=c.intersectsBounds(a,{inclusive:b.inclusive})):g&&!f&&(c=c.add(-e,0),d=a.intersectsBounds(c,{inclusive:b.inclusive}))}return d},containsBounds:function(a,b,c){null==b&&(b=!1);null==c&&(c=!0);var d=this.contains(a.left,a.bottom,c),e=this.contains(a.right,a.bottom,c),f=this.contains(a.left,a.top,c);a=this.contains(a.right,a.top,c);return b?
1741 d||e||f||a:d&&e&&f&&a},determineQuadrant:function(a){var b="",c=this.getCenterLonLat(),b=b+(a.lat<c.lat?"b":"t");return b+=a.lon<c.lon?"l":"r"},transform:function(a,b){this.centerLonLat=null;var c=OpenLayers.Projection.transform({x:this.left,y:this.bottom},a,b),d=OpenLayers.Projection.transform({x:this.right,y:this.bottom},a,b),e=OpenLayers.Projection.transform({x:this.left,y:this.top},a,b),f=OpenLayers.Projection.transform({x:this.right,y:this.top},a,b);this.left=Math.min(c.x,e.x);this.bottom=Math.min(c.y,
1742 d.y);this.right=Math.max(d.x,f.x);this.top=Math.max(e.y,f.y);return this},wrapDateLine:function(a,b){b=b||{};var c=b.leftTolerance||0,d=b.rightTolerance||0,e=this.clone();if(a){for(var f=a.getWidth();e.left<a.left&&e.right-d<=a.left;)e=e.add(f,0);for(;e.left+c>=a.right&&e.right>a.right;)e=e.add(-f,0);c=e.left+c;c<a.right&&(c>a.left&&e.right-d>a.right)&&(e=e.add(-f,0))}return e},CLASS_NAME:"OpenLayers.Bounds"});
1743 OpenLayers.Bounds.fromString=function(a,b){var c=a.split(",");return OpenLayers.Bounds.fromArray(c,b)};OpenLayers.Bounds.fromArray=function(a,b){return!0===b?new OpenLayers.Bounds(a[1],a[0],a[3],a[2]):new OpenLayers.Bounds(a[0],a[1],a[2],a[3])};OpenLayers.Bounds.fromSize=function(a){return new OpenLayers.Bounds(0,a.h,a.w,0)};OpenLayers.Bounds.oppositeQuadrant=function(a){var b;b=""+("t"==a.charAt(0)?"b":"t");return b+="l"==a.charAt(1)?"r":"l"};OpenLayers.Element={visible:function(a){return"none"!=OpenLayers.Util.getElement(a).style.display},toggle:function(){for(var a=0,b=arguments.length;a<b;a++){var c=OpenLayers.Util.getElement(arguments[a]),d=OpenLayers.Element.visible(c)?"none":"";c.style.display=d}},remove:function(a){a=OpenLayers.Util.getElement(a);a.parentNode.removeChild(a)},getHeight:function(a){a=OpenLayers.Util.getElement(a);return a.offsetHeight},hasClass:function(a,b){var c=a.className;return!!c&&RegExp("(^|\\s)"+b+"(\\s|$)").test(c)},
1744 addClass:function(a,b){OpenLayers.Element.hasClass(a,b)||(a.className+=(a.className?" ":"")+b);return a},removeClass:function(a,b){var c=a.className;c&&(a.className=OpenLayers.String.trim(c.replace(RegExp("(^|\\s+)"+b+"(\\s+|$)")," ")));return a},toggleClass:function(a,b){OpenLayers.Element.hasClass(a,b)?OpenLayers.Element.removeClass(a,b):OpenLayers.Element.addClass(a,b);return a},getStyle:function(a,b){a=OpenLayers.Util.getElement(a);var c=null;if(a&&a.style){c=a.style[OpenLayers.String.camelize(b)];
1745 c||(document.defaultView&&document.defaultView.getComputedStyle?c=(c=document.defaultView.getComputedStyle(a,null))?c.getPropertyValue(b):null:a.currentStyle&&(c=a.currentStyle[OpenLayers.String.camelize(b)]));var d=["left","top","right","bottom"];window.opera&&(-1!=OpenLayers.Util.indexOf(d,b)&&"static"==OpenLayers.Element.getStyle(a,"position"))&&(c="auto")}return"auto"==c?null:c}};OpenLayers.LonLat=OpenLayers.Class({lon:0,lat:0,initialize:function(a,b){OpenLayers.Util.isArray(a)&&(b=a[1],a=a[0]);this.lon=OpenLayers.Util.toFloat(a);this.lat=OpenLayers.Util.toFloat(b)},toString:function(){return"lon="+this.lon+",lat="+this.lat},toShortString:function(){return this.lon+", "+this.lat},clone:function(){return new OpenLayers.LonLat(this.lon,this.lat)},add:function(a,b){if(null==a||null==b)throw new TypeError("LonLat.add cannot receive null values");return new OpenLayers.LonLat(this.lon+
1746 OpenLayers.Util.toFloat(a),this.lat+OpenLayers.Util.toFloat(b))},equals:function(a){var b=!1;null!=a&&(b=this.lon==a.lon&&this.lat==a.lat||isNaN(this.lon)&&isNaN(this.lat)&&isNaN(a.lon)&&isNaN(a.lat));return b},transform:function(a,b){var c=OpenLayers.Projection.transform({x:this.lon,y:this.lat},a,b);this.lon=c.x;this.lat=c.y;return this},wrapDateLine:function(a){var b=this.clone();if(a){for(;b.lon<a.left;)b.lon+=a.getWidth();for(;b.lon>a.right;)b.lon-=a.getWidth()}return b},CLASS_NAME:"OpenLayers.LonLat"});
1747 OpenLayers.LonLat.fromString=function(a){a=a.split(",");return new OpenLayers.LonLat(a[0],a[1])};OpenLayers.LonLat.fromArray=function(a){var b=OpenLayers.Util.isArray(a);return new OpenLayers.LonLat(b&&a[0],b&&a[1])};OpenLayers.Pixel=OpenLayers.Class({x:0,y:0,initialize:function(a,b){this.x=parseFloat(a);this.y=parseFloat(b)},toString:function(){return"x="+this.x+",y="+this.y},clone:function(){return new OpenLayers.Pixel(this.x,this.y)},equals:function(a){var b=!1;null!=a&&(b=this.x==a.x&&this.y==a.y||isNaN(this.x)&&isNaN(this.y)&&isNaN(a.x)&&isNaN(a.y));return b},distanceTo:function(a){return Math.sqrt(Math.pow(this.x-a.x,2)+Math.pow(this.y-a.y,2))},add:function(a,b){if(null==a||null==b)throw new TypeError("Pixel.add cannot receive null values");
1748 return new OpenLayers.Pixel(this.x+a,this.y+b)},offset:function(a){var b=this.clone();a&&(b=this.add(a.x,a.y));return b},CLASS_NAME:"OpenLayers.Pixel"});OpenLayers.Size=OpenLayers.Class({w:0,h:0,initialize:function(a,b){this.w=parseFloat(a);this.h=parseFloat(b)},toString:function(){return"w="+this.w+",h="+this.h},clone:function(){return new OpenLayers.Size(this.w,this.h)},equals:function(a){var b=!1;null!=a&&(b=this.w==a.w&&this.h==a.h||isNaN(this.w)&&isNaN(this.h)&&isNaN(a.w)&&isNaN(a.h));return b},CLASS_NAME:"OpenLayers.Size"});OpenLayers.Console={log:function(){},debug:function(){},info:function(){},warn:function(){},error:function(){},userError:function(a){alert(a)},assert:function(){},dir:function(){},dirxml:function(){},trace:function(){},group:function(){},groupEnd:function(){},time:function(){},timeEnd:function(){},profile:function(){},profileEnd:function(){},count:function(){},CLASS_NAME:"OpenLayers.Console"};
1749 (function(){for(var a=document.getElementsByTagName("script"),b=0,c=a.length;b<c;++b)if(-1!=a[b].src.indexOf("firebug.js")&&console){OpenLayers.Util.extend(OpenLayers.Console,console);break}})();OpenLayers.Lang={code:null,defaultCode:"en",getCode:function(){OpenLayers.Lang.code||OpenLayers.Lang.setCode();return OpenLayers.Lang.code},setCode:function(a){var b;a||(a="msie"==OpenLayers.BROWSER_NAME?navigator.userLanguage:navigator.language);a=a.split("-");a[0]=a[0].toLowerCase();"object"==typeof OpenLayers.Lang[a[0]]&&(b=a[0]);if(a[1]){var c=a[0]+"-"+a[1].toUpperCase();"object"==typeof OpenLayers.Lang[c]&&(b=c)}b||(OpenLayers.Console.warn("Failed to find OpenLayers.Lang."+a.join("-")+" dictionary, falling back to default language"),
1750 b=OpenLayers.Lang.defaultCode);OpenLayers.Lang.code=b},translate:function(a,b){var c=OpenLayers.Lang[OpenLayers.Lang.getCode()];(c=c&&c[a])||(c=a);b&&(c=OpenLayers.String.format(c,b));return c}};OpenLayers.i18n=OpenLayers.Lang.translate;OpenLayers.Util=OpenLayers.Util||{};OpenLayers.Util.getElement=function(){for(var a=[],b=0,c=arguments.length;b<c;b++){var d=arguments[b];"string"==typeof d&&(d=document.getElementById(d));if(1==arguments.length)return d;a.push(d)}return a};OpenLayers.Util.isElement=function(a){return!(!a||1!==a.nodeType)};OpenLayers.Util.isArray=function(a){return"[object Array]"===Object.prototype.toString.call(a)};OpenLayers.Util.removeItem=function(a,b){for(var c=a.length-1;0<=c;c--)a[c]==b&&a.splice(c,1);return a};
1751 OpenLayers.Util.indexOf=function(a,b){if("function"==typeof a.indexOf)return a.indexOf(b);for(var c=0,d=a.length;c<d;c++)if(a[c]==b)return c;return-1};OpenLayers.Util.dotless=/\./g;
1752 OpenLayers.Util.modifyDOMElement=function(a,b,c,d,e,f,g,h){b&&(a.id=b.replace(OpenLayers.Util.dotless,"_"));c&&(a.style.left=c.x+"px",a.style.top=c.y+"px");d&&(a.style.width=d.w+"px",a.style.height=d.h+"px");e&&(a.style.position=e);f&&(a.style.border=f);g&&(a.style.overflow=g);0<=parseFloat(h)&&1>parseFloat(h)?(a.style.filter="alpha(opacity="+100*h+")",a.style.opacity=h):1==parseFloat(h)&&(a.style.filter="",a.style.opacity="")};
1753 OpenLayers.Util.createDiv=function(a,b,c,d,e,f,g,h){var k=document.createElement("div");d&&(k.style.backgroundImage="url("+d+")");a||(a=OpenLayers.Util.createUniqueID("OpenLayersDiv"));e||(e="absolute");OpenLayers.Util.modifyDOMElement(k,a,b,c,e,f,g,h);return k};
1754 OpenLayers.Util.createImage=function(a,b,c,d,e,f,g,h){var k=document.createElement("img");a||(a=OpenLayers.Util.createUniqueID("OpenLayersDiv"));e||(e="relative");OpenLayers.Util.modifyDOMElement(k,a,b,c,e,f,null,g);h&&(k.style.display="none",b=function(){k.style.display="";OpenLayers.Event.stopObservingElement(k)},OpenLayers.Event.observe(k,"load",b),OpenLayers.Event.observe(k,"error",b));k.style.alt=a;k.galleryImg="no";d&&(k.src=d);return k};OpenLayers.IMAGE_RELOAD_ATTEMPTS=0;
1755 OpenLayers.Util.alphaHackNeeded=null;OpenLayers.Util.alphaHack=function(){if(null==OpenLayers.Util.alphaHackNeeded){var a=navigator.appVersion.split("MSIE"),a=parseFloat(a[1]),b=!1;try{b=!!document.body.filters}catch(c){}OpenLayers.Util.alphaHackNeeded=b&&5.5<=a&&7>a}return OpenLayers.Util.alphaHackNeeded};
1756 OpenLayers.Util.modifyAlphaImageDiv=function(a,b,c,d,e,f,g,h,k){OpenLayers.Util.modifyDOMElement(a,b,c,d,f,null,null,k);b=a.childNodes[0];e&&(b.src=e);OpenLayers.Util.modifyDOMElement(b,a.id+"_innerImage",null,d,"relative",g);OpenLayers.Util.alphaHack()&&("none"!=a.style.display&&(a.style.display="inline-block"),null==h&&(h="scale"),a.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+b.src+"', sizingMethod='"+h+"')",0<=parseFloat(a.style.opacity)&&1>parseFloat(a.style.opacity)&&
1757 (a.style.filter+=" alpha(opacity="+100*a.style.opacity+")"),b.style.filter="alpha(opacity=0)")};OpenLayers.Util.createAlphaImageDiv=function(a,b,c,d,e,f,g,h,k){var l=OpenLayers.Util.createDiv();k=OpenLayers.Util.createImage(null,null,null,null,null,null,null,k);k.className="olAlphaImg";l.appendChild(k);OpenLayers.Util.modifyAlphaImageDiv(l,a,b,c,d,e,f,g,h);return l};OpenLayers.Util.upperCaseObject=function(a){var b={},c;for(c in a)b[c.toUpperCase()]=a[c];return b};
1758 OpenLayers.Util.applyDefaults=function(a,b){a=a||{};var c="function"==typeof window.Event&&b instanceof window.Event,d;for(d in b)if(void 0===a[d]||!c&&b.hasOwnProperty&&b.hasOwnProperty(d)&&!a.hasOwnProperty(d))a[d]=b[d];!c&&(b&&b.hasOwnProperty&&b.hasOwnProperty("toString")&&!a.hasOwnProperty("toString"))&&(a.toString=b.toString);return a};
1759 OpenLayers.Util.getParameterString=function(a){var b=[],c;for(c in a){var d=a[c];if(null!=d&&"function"!=typeof d){if("object"==typeof d&&d.constructor==Array){for(var e=[],f,g=0,h=d.length;g<h;g++)f=d[g],e.push(encodeURIComponent(null===f||void 0===f?"":f));d=e.join(",")}else d=encodeURIComponent(d);b.push(encodeURIComponent(c)+"="+d)}}return b.join("&")};OpenLayers.Util.urlAppend=function(a,b){var c=a;if(b)var d=(a+" ").split(/[?&]/),c=c+(" "===d.pop()?b:d.length?"&"+b:"?"+b);return c};
1760 OpenLayers.Util.getImagesLocation=function(){return OpenLayers.ImgPath||OpenLayers._getScriptLocation()+"img/"};OpenLayers.Util.getImageLocation=function(a){return OpenLayers.Util.getImagesLocation()+a};OpenLayers.Util.Try=function(){for(var a=null,b=0,c=arguments.length;b<c;b++){var d=arguments[b];try{a=d();break}catch(e){}}return a};
1761 OpenLayers.Util.getXmlNodeValue=function(a){var b=null;OpenLayers.Util.Try(function(){b=a.text;b||(b=a.textContent);b||(b=a.firstChild.nodeValue)},function(){b=a.textContent});return b};OpenLayers.Util.mouseLeft=function(a,b){for(var c=a.relatedTarget?a.relatedTarget:a.toElement;c!=b&&null!=c;)c=c.parentNode;return c!=b};OpenLayers.Util.DEFAULT_PRECISION=14;OpenLayers.Util.toFloat=function(a,b){null==b&&(b=OpenLayers.Util.DEFAULT_PRECISION);"number"!==typeof a&&(a=parseFloat(a));return 0===b?a:parseFloat(a.toPrecision(b))};
1762 OpenLayers.Util.rad=function(a){return a*Math.PI/180};OpenLayers.Util.deg=function(a){return 180*a/Math.PI};OpenLayers.Util.VincentyConstants={a:6378137,b:6356752.3142,f:1/298.257223563};
1763 OpenLayers.Util.distVincenty=function(a,b){for(var c=OpenLayers.Util.VincentyConstants,d=c.a,e=c.b,c=c.f,f=OpenLayers.Util.rad(b.lon-a.lon),g=Math.atan((1-c)*Math.tan(OpenLayers.Util.rad(a.lat))),h=Math.atan((1-c)*Math.tan(OpenLayers.Util.rad(b.lat))),k=Math.sin(g),g=Math.cos(g),l=Math.sin(h),h=Math.cos(h),m=f,n=2*Math.PI,p=20;1E-12<Math.abs(m-n)&&0<--p;){var q=Math.sin(m),r=Math.cos(m),s=Math.sqrt(h*q*h*q+(g*l-k*h*r)*(g*l-k*h*r));if(0==s)return 0;var r=k*l+g*h*r,t=Math.atan2(s,r),u=Math.asin(g*h*
1764 q/s),v=Math.cos(u)*Math.cos(u),q=r-2*k*l/v,w=c/16*v*(4+c*(4-3*v)),n=m,m=f+(1-w)*c*Math.sin(u)*(t+w*s*(q+w*r*(-1+2*q*q)))}if(0==p)return NaN;d=v*(d*d-e*e)/(e*e);c=d/1024*(256+d*(-128+d*(74-47*d)));return(e*(1+d/16384*(4096+d*(-768+d*(320-175*d))))*(t-c*s*(q+c/4*(r*(-1+2*q*q)-c/6*q*(-3+4*s*s)*(-3+4*q*q))))).toFixed(3)/1E3};
1765 OpenLayers.Util.destinationVincenty=function(a,b,c){var d=OpenLayers.Util,e=d.VincentyConstants,f=e.a,g=e.b,h=e.f,e=a.lon;a=a.lat;var k=d.rad(b);b=Math.sin(k);k=Math.cos(k);a=(1-h)*Math.tan(d.rad(a));var l=1/Math.sqrt(1+a*a),m=a*l,n=Math.atan2(a,k);a=l*b;for(var p=1-a*a,f=p*(f*f-g*g)/(g*g),q=1+f/16384*(4096+f*(-768+f*(320-175*f))),r=f/1024*(256+f*(-128+f*(74-47*f))),f=c/(g*q),s=2*Math.PI;1E-12<Math.abs(f-s);)var t=Math.cos(2*n+f),u=Math.sin(f),v=Math.cos(f),w=r*u*(t+r/4*(v*(-1+2*t*t)-r/6*t*(-3+4*
1766 u*u)*(-3+4*t*t))),s=f,f=c/(g*q)+w;c=m*u-l*v*k;g=Math.atan2(m*v+l*u*k,(1-h)*Math.sqrt(a*a+c*c));b=Math.atan2(u*b,l*v-m*u*k);k=h/16*p*(4+h*(4-3*p));t=b-(1-k)*h*a*(f+k*u*(t+k*v*(-1+2*t*t)));Math.atan2(a,-c);return new OpenLayers.LonLat(e+d.deg(t),d.deg(g))};
1767 OpenLayers.Util.getParameters=function(a,b){b=b||{};a=null===a||void 0===a?window.location.href:a;var c="";if(OpenLayers.String.contains(a,"?"))var d=a.indexOf("?")+1,c=OpenLayers.String.contains(a,"#")?a.indexOf("#"):a.length,c=a.substring(d,c);for(var d={},c=c.split(/[&;]/),e=0,f=c.length;e<f;++e){var g=c[e].split("=");if(g[0]){var h=g[0];try{h=decodeURIComponent(h)}catch(k){h=unescape(h)}g=(g[1]||"").replace(/\+/g," ");try{g=decodeURIComponent(g)}catch(l){g=unescape(g)}!1!==b.splitArgs&&(g=g.split(","));
1768 1==g.length&&(g=g[0]);d[h]=g}}return d};OpenLayers.Util.lastSeqID=0;OpenLayers.Util.createUniqueID=function(a){a=null==a?"id_":a.replace(OpenLayers.Util.dotless,"_");OpenLayers.Util.lastSeqID+=1;return a+OpenLayers.Util.lastSeqID};OpenLayers.INCHES_PER_UNIT={inches:1,ft:12,mi:63360,m:39.37,km:39370,dd:4374754,yd:36};OpenLayers.INCHES_PER_UNIT["in"]=OpenLayers.INCHES_PER_UNIT.inches;OpenLayers.INCHES_PER_UNIT.degrees=OpenLayers.INCHES_PER_UNIT.dd;OpenLayers.INCHES_PER_UNIT.nmi=1852*OpenLayers.INCHES_PER_UNIT.m;
1769 OpenLayers.METERS_PER_INCH=0.0254000508001016;
1770 OpenLayers.Util.extend(OpenLayers.INCHES_PER_UNIT,{Inch:OpenLayers.INCHES_PER_UNIT.inches,Meter:1/OpenLayers.METERS_PER_INCH,Foot:0.3048006096012192/OpenLayers.METERS_PER_INCH,IFoot:0.3048/OpenLayers.METERS_PER_INCH,ClarkeFoot:0.3047972651151/OpenLayers.METERS_PER_INCH,SearsFoot:0.30479947153867626/OpenLayers.METERS_PER_INCH,GoldCoastFoot:0.3047997101815088/OpenLayers.METERS_PER_INCH,IInch:0.0254/OpenLayers.METERS_PER_INCH,MicroInch:2.54E-5/OpenLayers.METERS_PER_INCH,Mil:2.54E-8/OpenLayers.METERS_PER_INCH,
1771 Centimeter:0.01/OpenLayers.METERS_PER_INCH,Kilometer:1E3/OpenLayers.METERS_PER_INCH,Yard:0.9144018288036576/OpenLayers.METERS_PER_INCH,SearsYard:0.914398414616029/OpenLayers.METERS_PER_INCH,IndianYard:0.9143985307444408/OpenLayers.METERS_PER_INCH,IndianYd37:0.91439523/OpenLayers.METERS_PER_INCH,IndianYd62:0.9143988/OpenLayers.METERS_PER_INCH,IndianYd75:0.9143985/OpenLayers.METERS_PER_INCH,IndianFoot:0.30479951/OpenLayers.METERS_PER_INCH,IndianFt37:0.30479841/OpenLayers.METERS_PER_INCH,IndianFt62:0.3047996/
1772 OpenLayers.METERS_PER_INCH,IndianFt75:0.3047995/OpenLayers.METERS_PER_INCH,Mile:1609.3472186944373/OpenLayers.METERS_PER_INCH,IYard:0.9144/OpenLayers.METERS_PER_INCH,IMile:1609.344/OpenLayers.METERS_PER_INCH,NautM:1852/OpenLayers.METERS_PER_INCH,"Lat-66":110943.31648893273/OpenLayers.METERS_PER_INCH,"Lat-83":110946.25736872235/OpenLayers.METERS_PER_INCH,Decimeter:0.1/OpenLayers.METERS_PER_INCH,Millimeter:0.001/OpenLayers.METERS_PER_INCH,Dekameter:10/OpenLayers.METERS_PER_INCH,Decameter:10/OpenLayers.METERS_PER_INCH,
1773 Hectometer:100/OpenLayers.METERS_PER_INCH,GermanMeter:1.0000135965/OpenLayers.METERS_PER_INCH,CaGrid:0.999738/OpenLayers.METERS_PER_INCH,ClarkeChain:20.1166194976/OpenLayers.METERS_PER_INCH,GunterChain:20.11684023368047/OpenLayers.METERS_PER_INCH,BenoitChain:20.116782494375872/OpenLayers.METERS_PER_INCH,SearsChain:20.11676512155/OpenLayers.METERS_PER_INCH,ClarkeLink:0.201166194976/OpenLayers.METERS_PER_INCH,GunterLink:0.2011684023368047/OpenLayers.METERS_PER_INCH,BenoitLink:0.20116782494375873/OpenLayers.METERS_PER_INCH,
1774 SearsLink:0.2011676512155/OpenLayers.METERS_PER_INCH,Rod:5.02921005842012/OpenLayers.METERS_PER_INCH,IntnlChain:20.1168/OpenLayers.METERS_PER_INCH,IntnlLink:0.201168/OpenLayers.METERS_PER_INCH,Perch:5.02921005842012/OpenLayers.METERS_PER_INCH,Pole:5.02921005842012/OpenLayers.METERS_PER_INCH,Furlong:201.1684023368046/OpenLayers.METERS_PER_INCH,Rood:3.778266898/OpenLayers.METERS_PER_INCH,CapeFoot:0.3047972615/OpenLayers.METERS_PER_INCH,Brealey:375/OpenLayers.METERS_PER_INCH,ModAmFt:0.304812252984506/
1775 OpenLayers.METERS_PER_INCH,Fathom:1.8288/OpenLayers.METERS_PER_INCH,"NautM-UK":1853.184/OpenLayers.METERS_PER_INCH,"50kilometers":5E4/OpenLayers.METERS_PER_INCH,"150kilometers":15E4/OpenLayers.METERS_PER_INCH});
1776 OpenLayers.Util.extend(OpenLayers.INCHES_PER_UNIT,{mm:OpenLayers.INCHES_PER_UNIT.Meter/1E3,cm:OpenLayers.INCHES_PER_UNIT.Meter/100,dm:100*OpenLayers.INCHES_PER_UNIT.Meter,km:1E3*OpenLayers.INCHES_PER_UNIT.Meter,kmi:OpenLayers.INCHES_PER_UNIT.nmi,fath:OpenLayers.INCHES_PER_UNIT.Fathom,ch:OpenLayers.INCHES_PER_UNIT.IntnlChain,link:OpenLayers.INCHES_PER_UNIT.IntnlLink,"us-in":OpenLayers.INCHES_PER_UNIT.inches,"us-ft":OpenLayers.INCHES_PER_UNIT.Foot,"us-yd":OpenLayers.INCHES_PER_UNIT.Yard,"us-ch":OpenLayers.INCHES_PER_UNIT.GunterChain,
1777 "us-mi":OpenLayers.INCHES_PER_UNIT.Mile,"ind-yd":OpenLayers.INCHES_PER_UNIT.IndianYd37,"ind-ft":OpenLayers.INCHES_PER_UNIT.IndianFt37,"ind-ch":20.11669506/OpenLayers.METERS_PER_INCH});OpenLayers.DOTS_PER_INCH=72;OpenLayers.Util.normalizeScale=function(a){return 1<a?1/a:a};OpenLayers.Util.getResolutionFromScale=function(a,b){var c;a&&(null==b&&(b="degrees"),c=1/(OpenLayers.Util.normalizeScale(a)*OpenLayers.INCHES_PER_UNIT[b]*OpenLayers.DOTS_PER_INCH));return c};
1778 OpenLayers.Util.getScaleFromResolution=function(a,b){null==b&&(b="degrees");return a*OpenLayers.INCHES_PER_UNIT[b]*OpenLayers.DOTS_PER_INCH};
1779 OpenLayers.Util.pagePosition=function(a){var b=[0,0],c=OpenLayers.Util.getViewportElement();if(!a||a==window||a==c)return b;var d=OpenLayers.IS_GECKO&&document.getBoxObjectFor&&"absolute"==OpenLayers.Element.getStyle(a,"position")&&(""==a.style.top||""==a.style.left),e=null;if(a.getBoundingClientRect)a=a.getBoundingClientRect(),e=window.pageYOffset||c.scrollTop,b[0]=a.left+(window.pageXOffset||c.scrollLeft),b[1]=a.top+e;else if(document.getBoxObjectFor&&!d)a=document.getBoxObjectFor(a),c=document.getBoxObjectFor(c),
1780 b[0]=a.screenX-c.screenX,b[1]=a.screenY-c.screenY;else{b[0]=a.offsetLeft;b[1]=a.offsetTop;e=a.offsetParent;if(e!=a)for(;e;)b[0]+=e.offsetLeft,b[1]+=e.offsetTop,e=e.offsetParent;c=OpenLayers.BROWSER_NAME;if("opera"==c||"safari"==c&&"absolute"==OpenLayers.Element.getStyle(a,"position"))b[1]-=document.body.offsetTop;for(e=a.offsetParent;e&&e!=document.body;){b[0]-=e.scrollLeft;if("opera"!=c||"TR"!=e.tagName)b[1]-=e.scrollTop;e=e.offsetParent}}return b};
1781 OpenLayers.Util.getViewportElement=function(){var a=arguments.callee.viewportElement;void 0==a&&(a="msie"==OpenLayers.BROWSER_NAME&&"CSS1Compat"!=document.compatMode?document.body:document.documentElement,arguments.callee.viewportElement=a);return a};
1782 OpenLayers.Util.isEquivalentUrl=function(a,b,c){c=c||{};OpenLayers.Util.applyDefaults(c,{ignoreCase:!0,ignorePort80:!0,ignoreHash:!0,splitArgs:!1});a=OpenLayers.Util.createUrlObject(a,c);b=OpenLayers.Util.createUrlObject(b,c);for(var d in a)if("args"!==d&&a[d]!=b[d])return!1;for(d in a.args){if(a.args[d]!=b.args[d])return!1;delete b.args[d]}for(d in b.args)return!1;return!0};
1783 OpenLayers.Util.createUrlObject=function(a,b){b=b||{};if(!/^\w+:\/\//.test(a)){var c=window.location,d=c.port?":"+c.port:"",d=c.protocol+"//"+c.host.split(":").shift()+d;0===a.indexOf("/")?a=d+a:(c=c.pathname.split("/"),c.pop(),a=d+c.join("/")+"/"+a)}b.ignoreCase&&(a=a.toLowerCase());c=document.createElement("a");c.href=a;d={};d.host=c.host.split(":").shift();d.protocol=c.protocol;d.port=b.ignorePort80?"80"==c.port||"0"==c.port?"":c.port:""==c.port||"0"==c.port?"80":c.port;d.hash=b.ignoreHash||"#"===
1784 c.hash?"":c.hash;var e=c.search;e||(e=a.indexOf("?"),e=-1!=e?a.substr(e):"");d.args=OpenLayers.Util.getParameters(e,{splitArgs:b.splitArgs});d.pathname="/"==c.pathname.charAt(0)?c.pathname:"/"+c.pathname;return d};OpenLayers.Util.removeTail=function(a){var b=null,b=a.indexOf("?"),c=a.indexOf("#");return b=-1==b?-1!=c?a.substr(0,c):a:-1!=c?a.substr(0,Math.min(b,c)):a.substr(0,b)};OpenLayers.IS_GECKO=function(){var a=navigator.userAgent.toLowerCase();return-1==a.indexOf("webkit")&&-1!=a.indexOf("gecko")}();
1785 OpenLayers.CANVAS_SUPPORTED=function(){var a=document.createElement("canvas");return!(!a.getContext||!a.getContext("2d"))}();OpenLayers.BROWSER_NAME=function(){var a="",b=navigator.userAgent.toLowerCase();-1!=b.indexOf("opera")?a="opera":-1!=b.indexOf("msie")?a="msie":-1!=b.indexOf("safari")?a="safari":-1!=b.indexOf("mozilla")&&(a=-1!=b.indexOf("firefox")?"firefox":"mozilla");return a}();OpenLayers.Util.getBrowserName=function(){return OpenLayers.BROWSER_NAME};
1786 OpenLayers.Util.getRenderedDimensions=function(a,b,c){var d,e,f=document.createElement("div");f.style.visibility="hidden";for(var g=c&&c.containerElement?c.containerElement:document.body,h=!1,k=null,l=g;l&&"body"!=l.tagName.toLowerCase();){var m=OpenLayers.Element.getStyle(l,"position");if("absolute"==m){h=!0;break}else if(m&&"static"!=m)break;l=l.parentNode}!h||0!==g.clientHeight&&0!==g.clientWidth||(k=document.createElement("div"),k.style.visibility="hidden",k.style.position="absolute",k.style.overflow=
1787 "visible",k.style.width=document.body.clientWidth+"px",k.style.height=document.body.clientHeight+"px",k.appendChild(f));f.style.position="absolute";b&&(b.w?(d=b.w,f.style.width=d+"px"):b.h&&(e=b.h,f.style.height=e+"px"));c&&c.displayClass&&(f.className=c.displayClass);b=document.createElement("div");b.innerHTML=a;b.style.overflow="visible";if(b.childNodes)for(a=0,c=b.childNodes.length;a<c;a++)b.childNodes[a].style&&(b.childNodes[a].style.overflow="visible");f.appendChild(b);k?g.appendChild(k):g.appendChild(f);
1788 d||(d=parseInt(b.scrollWidth),f.style.width=d+"px");e||(e=parseInt(b.scrollHeight));f.removeChild(b);k?(k.removeChild(f),g.removeChild(k)):g.removeChild(f);return new OpenLayers.Size(d,e)};
1789 OpenLayers.Util.getScrollbarWidth=function(){var a=OpenLayers.Util._scrollbarWidth;if(null==a){var b=null,c=null,b=a=0,b=document.createElement("div");b.style.position="absolute";b.style.top="-1000px";b.style.left="-1000px";b.style.width="100px";b.style.height="50px";b.style.overflow="hidden";c=document.createElement("div");c.style.width="100%";c.style.height="200px";b.appendChild(c);document.body.appendChild(b);a=c.offsetWidth;b.style.overflow="scroll";b=c.offsetWidth;document.body.removeChild(document.body.lastChild);
1790 OpenLayers.Util._scrollbarWidth=a-b;a=OpenLayers.Util._scrollbarWidth}return a};
1791 OpenLayers.Util.getFormattedLonLat=function(a,b,c){c||(c="dms");a=(a+540)%360-180;var d=Math.abs(a),e=Math.floor(d),f=d=(d-e)/(1/60),d=Math.floor(d),f=Math.round(10*((f-d)/(1/60))),f=f/10;60<=f&&(f-=60,d+=1,60<=d&&(d-=60,e+=1));10>e&&(e="0"+e);e+="\u00b0";0<=c.indexOf("dm")&&(10>d&&(d="0"+d),e+=d+"'",0<=c.indexOf("dms")&&(10>f&&(f="0"+f),e+=f+'"'));return e="lon"==b?e+(0>a?OpenLayers.i18n("W"):OpenLayers.i18n("E")):e+(0>a?OpenLayers.i18n("S"):OpenLayers.i18n("N"))};OpenLayers.Format=OpenLayers.Class({options:null,externalProjection:null,internalProjection:null,data:null,keepData:!1,initialize:function(a){OpenLayers.Util.extend(this,a);this.options=a},destroy:function(){},read:function(a){throw Error("Read not implemented.");},write:function(a){throw Error("Write not implemented.");},CLASS_NAME:"OpenLayers.Format"});OpenLayers.Format.CSWGetRecords=function(a){a=OpenLayers.Util.applyDefaults(a,OpenLayers.Format.CSWGetRecords.DEFAULTS);var b=OpenLayers.Format.CSWGetRecords["v"+a.version.replace(/\./g,"_")];if(!b)throw"Unsupported CSWGetRecords version: "+a.version;return new b(a)};OpenLayers.Format.CSWGetRecords.DEFAULTS={version:"2.0.2"};OpenLayers.Control=OpenLayers.Class({id:null,map:null,div:null,type:null,allowSelection:!1,displayClass:"",title:"",autoActivate:!1,active:null,handlerOptions:null,handler:null,eventListeners:null,events:null,initialize:function(a){this.displayClass=this.CLASS_NAME.replace("OpenLayers.","ol").replace(/\./g,"");OpenLayers.Util.extend(this,a);this.events=new OpenLayers.Events(this);if(this.eventListeners instanceof Object)this.events.on(this.eventListeners);null==this.id&&(this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+
1792 "_"))},destroy:function(){this.events&&(this.eventListeners&&this.events.un(this.eventListeners),this.events.destroy(),this.events=null);this.eventListeners=null;this.handler&&(this.handler.destroy(),this.handler=null);if(this.handlers){for(var a in this.handlers)this.handlers.hasOwnProperty(a)&&"function"==typeof this.handlers[a].destroy&&this.handlers[a].destroy();this.handlers=null}this.map&&(this.map.removeControl(this),this.map=null);this.div=null},setMap:function(a){this.map=a;this.handler&&
1793 this.handler.setMap(a)},draw:function(a){null==this.div&&(this.div=OpenLayers.Util.createDiv(this.id),this.div.className=this.displayClass,this.allowSelection||(this.div.className+=" olControlNoSelect",this.div.setAttribute("unselectable","on",0),this.div.onselectstart=OpenLayers.Function.False),""!=this.title&&(this.div.title=this.title));null!=a&&(this.position=a.clone());this.moveTo(this.position);return this.div},moveTo:function(a){null!=a&&null!=this.div&&(this.div.style.left=a.x+"px",this.div.style.top=
1794 a.y+"px")},activate:function(){if(this.active)return!1;this.handler&&this.handler.activate();this.active=!0;this.map&&OpenLayers.Element.addClass(this.map.viewPortDiv,this.displayClass.replace(/ /g,"")+"Active");this.events.triggerEvent("activate");return!0},deactivate:function(){return this.active?(this.handler&&this.handler.deactivate(),this.active=!1,this.map&&OpenLayers.Element.removeClass(this.map.viewPortDiv,this.displayClass.replace(/ /g,"")+"Active"),this.events.triggerEvent("deactivate"),
1795 !0):!1},CLASS_NAME:"OpenLayers.Control"});OpenLayers.Control.TYPE_BUTTON=1;OpenLayers.Control.TYPE_TOGGLE=2;OpenLayers.Control.TYPE_TOOL=3;OpenLayers.Event={observers:!1,KEY_SPACE:32,KEY_BACKSPACE:8,KEY_TAB:9,KEY_RETURN:13,KEY_ESC:27,KEY_LEFT:37,KEY_UP:38,KEY_RIGHT:39,KEY_DOWN:40,KEY_DELETE:46,element:function(a){return a.target||a.srcElement},isSingleTouch:function(a){return a.touches&&1==a.touches.length},isMultiTouch:function(a){return a.touches&&1<a.touches.length},isLeftClick:function(a){return a.which&&1==a.which||a.button&&1==a.button},isRightClick:function(a){return a.which&&3==a.which||a.button&&2==a.button},stop:function(a,
1796 b){b||OpenLayers.Event.preventDefault(a);a.stopPropagation?a.stopPropagation():a.cancelBubble=!0},preventDefault:function(a){a.preventDefault?a.preventDefault():a.returnValue=!1},findElement:function(a,b){for(var c=OpenLayers.Event.element(a);c.parentNode&&(!c.tagName||c.tagName.toUpperCase()!=b.toUpperCase());)c=c.parentNode;return c},observe:function(a,b,c,d){a=OpenLayers.Util.getElement(a);d=d||!1;"keypress"==b&&(navigator.appVersion.match(/Konqueror|Safari|KHTML/)||a.attachEvent)&&(b="keydown");
1797 this.observers||(this.observers={});if(!a._eventCacheID){var e="eventCacheID_";a.id&&(e=a.id+"_"+e);a._eventCacheID=OpenLayers.Util.createUniqueID(e)}e=a._eventCacheID;this.observers[e]||(this.observers[e]=[]);this.observers[e].push({element:a,name:b,observer:c,useCapture:d});a.addEventListener?a.addEventListener(b,c,d):a.attachEvent&&a.attachEvent("on"+b,c)},stopObservingElement:function(a){a=OpenLayers.Util.getElement(a)._eventCacheID;this._removeElementObservers(OpenLayers.Event.observers[a])},
1798 _removeElementObservers:function(a){if(a)for(var b=a.length-1;0<=b;b--){var c=a[b];OpenLayers.Event.stopObserving.apply(this,[c.element,c.name,c.observer,c.useCapture])}},stopObserving:function(a,b,c,d){d=d||!1;a=OpenLayers.Util.getElement(a);var e=a._eventCacheID;"keypress"==b&&(navigator.appVersion.match(/Konqueror|Safari|KHTML/)||a.detachEvent)&&(b="keydown");var f=!1,g=OpenLayers.Event.observers[e];if(g)for(var h=0;!f&&h<g.length;){var k=g[h];if(k.name==b&&k.observer==c&&k.useCapture==d){g.splice(h,
1799 1);0==g.length&&delete OpenLayers.Event.observers[e];f=!0;break}h++}f&&(a.removeEventListener?a.removeEventListener(b,c,d):a&&a.detachEvent&&a.detachEvent("on"+b,c));return f},unloadCache:function(){if(OpenLayers.Event&&OpenLayers.Event.observers){for(var a in OpenLayers.Event.observers)OpenLayers.Event._removeElementObservers.apply(this,[OpenLayers.Event.observers[a]]);OpenLayers.Event.observers=!1}},CLASS_NAME:"OpenLayers.Event"};
1800 OpenLayers.Event.observe(window,"unload",OpenLayers.Event.unloadCache,!1);
1801 OpenLayers.Events=OpenLayers.Class({BROWSER_EVENTS:"mouseover mouseout mousedown mouseup mousemove click dblclick rightclick dblrightclick resize focus blur touchstart touchmove touchend keydown".split(" "),listeners:null,object:null,element:null,eventHandler:null,fallThrough:null,includeXY:!1,extensions:null,extensionCount:null,clearMouseListener:null,initialize:function(a,b,c,d,e){OpenLayers.Util.extend(this,e);this.object=a;this.fallThrough=d;this.listeners={};this.extensions={};this.extensionCount=
1802 {};this._msTouches=[];null!=b&&this.attachToElement(b)},destroy:function(){for(var a in this.extensions)"boolean"!==typeof this.extensions[a]&&this.extensions[a].destroy();this.extensions=null;this.element&&(OpenLayers.Event.stopObservingElement(this.element),this.element.hasScrollEvent&&OpenLayers.Event.stopObserving(window,"scroll",this.clearMouseListener));this.eventHandler=this.fallThrough=this.object=this.listeners=this.element=null},addEventType:function(a){},attachToElement:function(a){this.element?
1803 OpenLayers.Event.stopObservingElement(this.element):(this.eventHandler=OpenLayers.Function.bindAsEventListener(this.handleBrowserEvent,this),this.clearMouseListener=OpenLayers.Function.bind(this.clearMouseCache,this));this.element=a;for(var b=!!window.navigator.msMaxTouchPoints,c,d=0,e=this.BROWSER_EVENTS.length;d<e;d++)c=this.BROWSER_EVENTS[d],OpenLayers.Event.observe(a,c,this.eventHandler),b&&0===c.indexOf("touch")&&this.addMsTouchListener(a,c,this.eventHandler);OpenLayers.Event.observe(a,"dragstart",
1804 OpenLayers.Event.stop)},on:function(a){for(var b in a)"scope"!=b&&a.hasOwnProperty(b)&&this.register(b,a.scope,a[b])},register:function(a,b,c,d){a in OpenLayers.Events&&!this.extensions[a]&&(this.extensions[a]=new OpenLayers.Events[a](this));if(null!=c){null==b&&(b=this.object);var e=this.listeners[a];e||(e=[],this.listeners[a]=e,this.extensionCount[a]=0);b={obj:b,func:c};d?(e.splice(this.extensionCount[a],0,b),"object"===typeof d&&d.extension&&this.extensionCount[a]++):e.push(b)}},registerPriority:function(a,
1805 b,c){this.register(a,b,c,!0)},un:function(a){for(var b in a)"scope"!=b&&a.hasOwnProperty(b)&&this.unregister(b,a.scope,a[b])},unregister:function(a,b,c){null==b&&(b=this.object);a=this.listeners[a];if(null!=a)for(var d=0,e=a.length;d<e;d++)if(a[d].obj==b&&a[d].func==c){a.splice(d,1);break}},remove:function(a){null!=this.listeners[a]&&(this.listeners[a]=[])},triggerEvent:function(a,b){var c=this.listeners[a];if(c&&0!=c.length){null==b&&(b={});b.object=this.object;b.element=this.element;b.type||(b.type=
1806 a);for(var c=c.slice(),d,e=0,f=c.length;e<f&&(d=c[e],d=d.func.apply(d.obj,[b]),void 0==d||!1!=d);e++);this.fallThrough||OpenLayers.Event.stop(b,!0);return d}},handleBrowserEvent:function(a){var b=a.type,c=this.listeners[b];if(c&&0!=c.length){if((c=a.touches)&&c[0]){for(var d=0,e=0,f=c.length,g,h=0;h<f;++h)g=this.getTouchClientXY(c[h]),d+=g.clientX,e+=g.clientY;a.clientX=d/f;a.clientY=e/f}this.includeXY&&(a.xy=this.getMousePosition(a));this.triggerEvent(b,a)}},getTouchClientXY:function(a){var b=window.olMockWin||
1807 window,c=b.pageXOffset,b=b.pageYOffset,d=a.clientX,e=a.clientY;if(0===a.pageY&&Math.floor(e)>Math.floor(a.pageY)||0===a.pageX&&Math.floor(d)>Math.floor(a.pageX))d-=c,e-=b;else if(e<a.pageY-b||d<a.pageX-c)d=a.pageX-c,e=a.pageY-b;a.olClientX=d;a.olClientY=e;return{clientX:d,clientY:e}},clearMouseCache:function(){this.element.scrolls=null;this.element.lefttop=null;this.element.offsets=null},getMousePosition:function(a){this.includeXY?this.element.hasScrollEvent||(OpenLayers.Event.observe(window,"scroll",
1808 this.clearMouseListener),this.element.hasScrollEvent=!0):this.clearMouseCache();if(!this.element.scrolls){var b=OpenLayers.Util.getViewportElement();this.element.scrolls=[window.pageXOffset||b.scrollLeft,window.pageYOffset||b.scrollTop]}this.element.lefttop||(this.element.lefttop=[document.documentElement.clientLeft||0,document.documentElement.clientTop||0]);this.element.offsets||(this.element.offsets=OpenLayers.Util.pagePosition(this.element));return new OpenLayers.Pixel(a.clientX+this.element.scrolls[0]-
1809 this.element.offsets[0]-this.element.lefttop[0],a.clientY+this.element.scrolls[1]-this.element.offsets[1]-this.element.lefttop[1])},addMsTouchListener:function(a,b,c){function d(a){c(OpenLayers.Util.applyDefaults({stopPropagation:function(){for(var a=e.length-1;0<=a;--a)e[a].stopPropagation()},preventDefault:function(){for(var a=e.length-1;0<=a;--a)e[a].preventDefault()},type:b},a))}var e=this._msTouches;switch(b){case "touchstart":return this.addMsTouchListenerStart(a,b,d);case "touchend":return this.addMsTouchListenerEnd(a,
1810 b,d);case "touchmove":return this.addMsTouchListenerMove(a,b,d);default:throw"Unknown touch event type";}},addMsTouchListenerStart:function(a,b,c){var d=this._msTouches;OpenLayers.Event.observe(a,"MSPointerDown",function(a){for(var b=!1,g=0,h=d.length;g<h;++g)if(d[g].pointerId==a.pointerId){b=!0;break}b||d.push(a);a.touches=d.slice();c(a)});OpenLayers.Event.observe(a,"MSPointerUp",function(a){for(var b=0,c=d.length;b<c;++b)if(d[b].pointerId==a.pointerId){d.splice(b,1);break}})},addMsTouchListenerMove:function(a,
1811 b,c){var d=this._msTouches;OpenLayers.Event.observe(a,"MSPointerMove",function(a){if(a.pointerType!=a.MSPOINTER_TYPE_MOUSE||0!=a.buttons)if(1!=d.length||d[0].pageX!=a.pageX||d[0].pageY!=a.pageY){for(var b=0,g=d.length;b<g;++b)if(d[b].pointerId==a.pointerId){d[b]=a;break}a.touches=d.slice();c(a)}})},addMsTouchListenerEnd:function(a,b,c){var d=this._msTouches;OpenLayers.Event.observe(a,"MSPointerUp",function(a){for(var b=0,g=d.length;b<g;++b)if(d[b].pointerId==a.pointerId){d.splice(b,1);break}a.touches=
1812 d.slice();c(a)})},CLASS_NAME:"OpenLayers.Events"});OpenLayers.Events.buttonclick=OpenLayers.Class({target:null,events:"mousedown mouseup click dblclick touchstart touchmove touchend keydown".split(" "),startRegEx:/^mousedown|touchstart$/,cancelRegEx:/^touchmove$/,completeRegEx:/^mouseup|touchend$/,initialize:function(a){this.target=a;for(a=this.events.length-1;0<=a;--a)this.target.register(this.events[a],this,this.buttonClick,{extension:!0})},destroy:function(){for(var a=this.events.length-1;0<=a;--a)this.target.unregister(this.events[a],this,this.buttonClick);
1813 delete this.target},getPressedButton:function(a){var b=3,c;do{if(OpenLayers.Element.hasClass(a,"olButton")){c=a;break}a=a.parentNode}while(0<--b&&a);return c},ignore:function(a){var b=3,c=!1;do{if("a"===a.nodeName.toLowerCase()){c=!0;break}a=a.parentNode}while(0<--b&&a);return c},buttonClick:function(a){var b=!0,c=OpenLayers.Event.element(a);if(c&&(OpenLayers.Event.isLeftClick(a)||!~a.type.indexOf("mouse")))if(c=this.getPressedButton(c)){if("keydown"===a.type)switch(a.keyCode){case OpenLayers.Event.KEY_RETURN:case OpenLayers.Event.KEY_SPACE:this.target.triggerEvent("buttonclick",
1814 {buttonElement:c}),OpenLayers.Event.stop(a),b=!1}else if(this.startEvt){if(this.completeRegEx.test(a.type)){var b=OpenLayers.Util.pagePosition(c),d=OpenLayers.Util.getViewportElement(),e=window.pageYOffset||d.scrollTop;b[0]-=window.pageXOffset||d.scrollLeft;b[1]-=e;this.target.triggerEvent("buttonclick",{buttonElement:c,buttonXY:{x:this.startEvt.clientX-b[0],y:this.startEvt.clientY-b[1]}})}this.cancelRegEx.test(a.type)&&delete this.startEvt;OpenLayers.Event.stop(a);b=!1}this.startRegEx.test(a.type)&&
1815 (this.startEvt=a,OpenLayers.Event.stop(a),b=!1)}else b=!this.ignore(OpenLayers.Event.element(a)),delete this.startEvt;return b}});OpenLayers.Util=OpenLayers.Util||{};
1816 OpenLayers.Util.vendorPrefix=function(){function a(a){return a?a.replace(/([A-Z])/g,function(a){return"-"+a.toLowerCase()}).replace(/^ms-/,"-ms-"):null}function b(a,b){if(void 0===g[b]){var c,e=0,f=d.length,p="undefined"!==typeof a.cssText;for(g[b]=null;e<f;e++)if((c=d[e])?(p||(c=c.toLowerCase()),c=c+b.charAt(0).toUpperCase()+b.slice(1)):c=b,void 0!==a[c]){g[b]=c;break}}return g[b]}function c(a){return b(e,a)}var d=["","O","ms","Moz","Webkit"],e=document.createElement("div").style,f={},g={};return{css:function(b){if(void 0===
1817 f[b]){var d=b.replace(/(-[\s\S])/g,function(a){return a.charAt(1).toUpperCase()}),d=c(d);f[b]=a(d)}return f[b]},js:b,style:c,cssCache:f,jsCache:g}}();OpenLayers.Animation=function(a){var b=OpenLayers.Util.vendorPrefix.js(a,"requestAnimationFrame"),c=!!b,d=function(){var c=a[b]||function(b,c){a.setTimeout(b,16)};return function(b,d){c.apply(a,[b,d])}}(),e=0,f={};return{isNative:c,requestFrame:d,start:function(a,b,c){b=0<b?b:Number.POSITIVE_INFINITY;var l=++e,m=+new Date;f[l]=function(){f[l]&&+new Date-m<=b?(a(),f[l]&&d(f[l],c)):delete f[l]};d(f[l],c);return l},stop:function(a){delete f[a]}}}(window);OpenLayers.Tween=OpenLayers.Class({easing:null,begin:null,finish:null,duration:null,callbacks:null,time:null,minFrameRate:null,startTime:null,animationId:null,playing:!1,initialize:function(a){this.easing=a?a:OpenLayers.Easing.Expo.easeOut},start:function(a,b,c,d){this.playing=!0;this.begin=a;this.finish=b;this.duration=c;this.callbacks=d.callbacks;this.minFrameRate=d.minFrameRate||30;this.time=0;this.startTime=(new Date).getTime();OpenLayers.Animation.stop(this.animationId);this.animationId=null;
1818 this.callbacks&&this.callbacks.start&&this.callbacks.start.call(this,this.begin);this.animationId=OpenLayers.Animation.start(OpenLayers.Function.bind(this.play,this))},stop:function(){this.playing&&(this.callbacks&&this.callbacks.done&&this.callbacks.done.call(this,this.finish),OpenLayers.Animation.stop(this.animationId),this.animationId=null,this.playing=!1)},play:function(){var a={},b;for(b in this.begin){var c=this.begin[b],d=this.finish[b];if(null==c||null==d||isNaN(c)||isNaN(d))throw new TypeError("invalid value for Tween");
1819 a[b]=this.easing.apply(this,[this.time,c,d-c,this.duration])}this.time++;this.callbacks&&this.callbacks.eachStep&&((new Date).getTime()-this.startTime)/this.time<=1E3/this.minFrameRate&&this.callbacks.eachStep.call(this,a);this.time>this.duration&&this.stop()},CLASS_NAME:"OpenLayers.Tween"});OpenLayers.Easing={CLASS_NAME:"OpenLayers.Easing"};OpenLayers.Easing.Linear={easeIn:function(a,b,c,d){return c*a/d+b},easeOut:function(a,b,c,d){return c*a/d+b},easeInOut:function(a,b,c,d){return c*a/d+b},CLASS_NAME:"OpenLayers.Easing.Linear"};
1820 OpenLayers.Easing.Expo={easeIn:function(a,b,c,d){return 0==a?b:c*Math.pow(2,10*(a/d-1))+b},easeOut:function(a,b,c,d){return a==d?b+c:c*(-Math.pow(2,-10*a/d)+1)+b},easeInOut:function(a,b,c,d){return 0==a?b:a==d?b+c:1>(a/=d/2)?c/2*Math.pow(2,10*(a-1))+b:c/2*(-Math.pow(2,-10*--a)+2)+b},CLASS_NAME:"OpenLayers.Easing.Expo"};
1821 OpenLayers.Easing.Quad={easeIn:function(a,b,c,d){return c*(a/=d)*a+b},easeOut:function(a,b,c,d){return-c*(a/=d)*(a-2)+b},easeInOut:function(a,b,c,d){return 1>(a/=d/2)?c/2*a*a+b:-c/2*(--a*(a-2)-1)+b},CLASS_NAME:"OpenLayers.Easing.Quad"};OpenLayers.Projection=OpenLayers.Class({proj:null,projCode:null,titleRegEx:/\+title=[^\+]*/,initialize:function(a,b){OpenLayers.Util.extend(this,b);this.projCode=a;"object"==typeof Proj4js&&(this.proj=new Proj4js.Proj(a))},getCode:function(){return this.proj?this.proj.srsCode:this.projCode},getUnits:function(){return this.proj?this.proj.units:null},toString:function(){return this.getCode()},equals:function(a){var b=!1;a&&(a instanceof OpenLayers.Projection||(a=new OpenLayers.Projection(a)),"object"==
1822 typeof Proj4js&&this.proj.defData&&a.proj.defData?b=this.proj.defData.replace(this.titleRegEx,"")==a.proj.defData.replace(this.titleRegEx,""):a.getCode&&(b=this.getCode(),a=a.getCode(),b=b==a||!!OpenLayers.Projection.transforms[b]&&OpenLayers.Projection.transforms[b][a]===OpenLayers.Projection.nullTransform));return b},destroy:function(){delete this.proj;delete this.projCode},CLASS_NAME:"OpenLayers.Projection"});OpenLayers.Projection.transforms={};
1823 OpenLayers.Projection.defaults={"EPSG:4326":{units:"degrees",maxExtent:[-180,-90,180,90],yx:!0},"CRS:84":{units:"degrees",maxExtent:[-180,-90,180,90]},"EPSG:900913":{units:"m",maxExtent:[-2.003750834E7,-2.003750834E7,2.003750834E7,2.003750834E7]}};
1824 OpenLayers.Projection.addTransform=function(a,b,c){if(c===OpenLayers.Projection.nullTransform){var d=OpenLayers.Projection.defaults[a];d&&!OpenLayers.Projection.defaults[b]&&(OpenLayers.Projection.defaults[b]=d)}OpenLayers.Projection.transforms[a]||(OpenLayers.Projection.transforms[a]={});OpenLayers.Projection.transforms[a][b]=c};
1825 OpenLayers.Projection.transform=function(a,b,c){if(b&&c)if(b instanceof OpenLayers.Projection||(b=new OpenLayers.Projection(b)),c instanceof OpenLayers.Projection||(c=new OpenLayers.Projection(c)),b.proj&&c.proj)a=Proj4js.transform(b.proj,c.proj,a);else{b=b.getCode();c=c.getCode();var d=OpenLayers.Projection.transforms;if(d[b]&&d[b][c])d[b][c](a)}return a};OpenLayers.Projection.nullTransform=function(a){return a};
1826 (function(){function a(a){a.x=180*a.x/d;a.y=180/Math.PI*(2*Math.atan(Math.exp(a.y/d*Math.PI))-Math.PI/2);return a}function b(a){a.x=a.x*d/180;var b=Math.log(Math.tan((90+a.y)*Math.PI/360))/Math.PI*d;a.y=Math.max(-2.003750834E7,Math.min(b,2.003750834E7));return a}function c(c,d){var e=OpenLayers.Projection.addTransform,f=OpenLayers.Projection.nullTransform,g,p,q,r,s;g=0;for(p=d.length;g<p;++g)for(q=d[g],e(c,q,b),e(q,c,a),s=g+1;s<p;++s)r=d[s],e(q,r,f),e(r,q,f)}var d=2.003750834E7,e=["EPSG:900913","EPSG:3857",
1827 "EPSG:102113","EPSG:102100"],f=["CRS:84","urn:ogc:def:crs:EPSG:6.6:4326","EPSG:4326"],g;for(g=e.length-1;0<=g;--g)c(e[g],f);for(g=f.length-1;0<=g;--g)c(f[g],e)})();OpenLayers.Map=OpenLayers.Class({Z_INDEX_BASE:{BaseLayer:100,Overlay:325,Feature:725,Popup:750,Control:1E3},id:null,fractionalZoom:!1,events:null,allOverlays:!1,div:null,dragging:!1,size:null,viewPortDiv:null,layerContainerOrigin:null,layerContainerDiv:null,layers:null,controls:null,popups:null,baseLayer:null,center:null,resolution:null,zoom:0,panRatio:1.5,options:null,tileSize:null,projection:"EPSG:4326",units:null,resolutions:null,maxResolution:null,minResolution:null,maxScale:null,minScale:null,
1828 maxExtent:null,minExtent:null,restrictedExtent:null,numZoomLevels:16,theme:null,displayProjection:null,fallThrough:!1,autoUpdateSize:!0,eventListeners:null,panTween:null,panMethod:OpenLayers.Easing.Expo.easeOut,panDuration:50,zoomTween:null,zoomMethod:OpenLayers.Easing.Quad.easeOut,zoomDuration:20,paddingForPopups:null,layerContainerOriginPx:null,minPx:null,maxPx:null,initialize:function(a,b){1===arguments.length&&"object"===typeof a&&(a=(b=a)&&b.div);this.tileSize=new OpenLayers.Size(OpenLayers.Map.TILE_WIDTH,
1829 OpenLayers.Map.TILE_HEIGHT);this.paddingForPopups=new OpenLayers.Bounds(15,15,15,15);this.theme=OpenLayers._getScriptLocation()+"theme/default/style.css";this.options=OpenLayers.Util.extend({},b);OpenLayers.Util.extend(this,b);OpenLayers.Util.applyDefaults(this,OpenLayers.Projection.defaults[this.projection instanceof OpenLayers.Projection?this.projection.projCode:this.projection]);!this.maxExtent||this.maxExtent instanceof OpenLayers.Bounds||(this.maxExtent=new OpenLayers.Bounds(this.maxExtent));
1830 !this.minExtent||this.minExtent instanceof OpenLayers.Bounds||(this.minExtent=new OpenLayers.Bounds(this.minExtent));!this.restrictedExtent||this.restrictedExtent instanceof OpenLayers.Bounds||(this.restrictedExtent=new OpenLayers.Bounds(this.restrictedExtent));!this.center||this.center instanceof OpenLayers.LonLat||(this.center=new OpenLayers.LonLat(this.center));this.layers=[];this.id=OpenLayers.Util.createUniqueID("OpenLayers.Map_");this.div=OpenLayers.Util.getElement(a);this.div||(this.div=document.createElement("div"),
1831 this.div.style.height="1px",this.div.style.width="1px");OpenLayers.Element.addClass(this.div,"olMap");var c=this.id+"_OpenLayers_ViewPort";this.viewPortDiv=OpenLayers.Util.createDiv(c,null,null,null,"relative",null,"hidden");this.viewPortDiv.style.width="100%";this.viewPortDiv.style.height="100%";this.viewPortDiv.className="olMapViewport";this.div.appendChild(this.viewPortDiv);this.events=new OpenLayers.Events(this,this.viewPortDiv,null,this.fallThrough,{includeXY:!0});OpenLayers.TileManager&&null!==
1832 this.tileManager&&(this.tileManager instanceof OpenLayers.TileManager||(this.tileManager=new OpenLayers.TileManager(this.tileManager)),this.tileManager.addMap(this));c=this.id+"_OpenLayers_Container";this.layerContainerDiv=OpenLayers.Util.createDiv(c);this.layerContainerDiv.style.zIndex=this.Z_INDEX_BASE.Popup-1;this.layerContainerOriginPx={x:0,y:0};this.applyTransform();this.viewPortDiv.appendChild(this.layerContainerDiv);this.updateSize();if(this.eventListeners instanceof Object)this.events.on(this.eventListeners);
1833 !0===this.autoUpdateSize&&(this.updateSizeDestroy=OpenLayers.Function.bind(this.updateSize,this),OpenLayers.Event.observe(window,"resize",this.updateSizeDestroy));if(this.theme){for(var c=!0,d=document.getElementsByTagName("link"),e=0,f=d.length;e<f;++e)if(OpenLayers.Util.isEquivalentUrl(d.item(e).href,this.theme)){c=!1;break}c&&(c=document.createElement("link"),c.setAttribute("rel","stylesheet"),c.setAttribute("type","text/css"),c.setAttribute("href",this.theme),document.getElementsByTagName("head")[0].appendChild(c))}null==
1834 this.controls&&(this.controls=[],null!=OpenLayers.Control&&(OpenLayers.Control.Navigation?this.controls.push(new OpenLayers.Control.Navigation):OpenLayers.Control.TouchNavigation&&this.controls.push(new OpenLayers.Control.TouchNavigation),OpenLayers.Control.Zoom?this.controls.push(new OpenLayers.Control.Zoom):OpenLayers.Control.PanZoom&&this.controls.push(new OpenLayers.Control.PanZoom),OpenLayers.Control.ArgParser&&this.controls.push(new OpenLayers.Control.ArgParser),OpenLayers.Control.Attribution&&
1835 this.controls.push(new OpenLayers.Control.Attribution)));e=0;for(f=this.controls.length;e<f;e++)this.addControlToMap(this.controls[e]);this.popups=[];this.unloadDestroy=OpenLayers.Function.bind(this.destroy,this);OpenLayers.Event.observe(window,"unload",this.unloadDestroy);b&&b.layers&&(delete this.center,delete this.zoom,this.addLayers(b.layers),b.center&&!this.getCenter()&&this.setCenter(b.center,b.zoom));this.panMethod&&(this.panTween=new OpenLayers.Tween(this.panMethod));this.zoomMethod&&this.applyTransform.transform&&
1836 (this.zoomTween=new OpenLayers.Tween(this.zoomMethod))},getViewport:function(){return this.viewPortDiv},render:function(a){this.div=OpenLayers.Util.getElement(a);OpenLayers.Element.addClass(this.div,"olMap");this.viewPortDiv.parentNode.removeChild(this.viewPortDiv);this.div.appendChild(this.viewPortDiv);this.updateSize()},unloadDestroy:null,updateSizeDestroy:null,destroy:function(){if(!this.unloadDestroy)return!1;this.panTween&&(this.panTween.stop(),this.panTween=null);this.zoomTween&&(this.zoomTween.stop(),
1837 this.zoomTween=null);OpenLayers.Event.stopObserving(window,"unload",this.unloadDestroy);this.unloadDestroy=null;this.updateSizeDestroy&&OpenLayers.Event.stopObserving(window,"resize",this.updateSizeDestroy);this.paddingForPopups=null;if(null!=this.controls){for(var a=this.controls.length-1;0<=a;--a)this.controls[a].destroy();this.controls=null}if(null!=this.layers){for(a=this.layers.length-1;0<=a;--a)this.layers[a].destroy(!1);this.layers=null}this.viewPortDiv&&this.viewPortDiv.parentNode&&this.viewPortDiv.parentNode.removeChild(this.viewPortDiv);
1838 this.viewPortDiv=null;this.tileManager&&(this.tileManager.removeMap(this),this.tileManager=null);this.eventListeners&&(this.events.un(this.eventListeners),this.eventListeners=null);this.events.destroy();this.options=this.events=null},setOptions:function(a){var b=this.minPx&&a.restrictedExtent!=this.restrictedExtent;OpenLayers.Util.extend(this,a);b&&this.moveTo(this.getCachedCenter(),this.zoom,{forceZoomChange:!0})},getTileSize:function(){return this.tileSize},getBy:function(a,b,c){var d="function"==
1839 typeof c.test;return OpenLayers.Array.filter(this[a],function(a){return a[b]==c||d&&c.test(a[b])})},getLayersBy:function(a,b){return this.getBy("layers",a,b)},getLayersByName:function(a){return this.getLayersBy("name",a)},getLayersByClass:function(a){return this.getLayersBy("CLASS_NAME",a)},getControlsBy:function(a,b){return this.getBy("controls",a,b)},getControlsByClass:function(a){return this.getControlsBy("CLASS_NAME",a)},getLayer:function(a){for(var b=null,c=0,d=this.layers.length;c<d;c++){var e=
1840 this.layers[c];if(e.id==a){b=e;break}}return b},setLayerZIndex:function(a,b){a.setZIndex(this.Z_INDEX_BASE[a.isBaseLayer?"BaseLayer":"Overlay"]+5*b)},resetLayersZIndex:function(){for(var a=0,b=this.layers.length;a<b;a++)this.setLayerZIndex(this.layers[a],a)},addLayer:function(a){for(var b=0,c=this.layers.length;b<c;b++)if(this.layers[b]==a)return!1;if(!1===this.events.triggerEvent("preaddlayer",{layer:a}))return!1;this.allOverlays&&(a.isBaseLayer=!1);a.div.className="olLayerDiv";a.div.style.overflow=
1841 "";this.setLayerZIndex(a,this.layers.length);a.isFixed?this.viewPortDiv.appendChild(a.div):this.layerContainerDiv.appendChild(a.div);this.layers.push(a);a.setMap(this);a.isBaseLayer||this.allOverlays&&!this.baseLayer?null==this.baseLayer?this.setBaseLayer(a):a.setVisibility(!1):a.redraw();this.events.triggerEvent("addlayer",{layer:a});a.events.triggerEvent("added",{map:this,layer:a});a.afterAdd();return!0},addLayers:function(a){for(var b=0,c=a.length;b<c;b++)this.addLayer(a[b])},removeLayer:function(a,
1842 b){if(!1!==this.events.triggerEvent("preremovelayer",{layer:a})){null==b&&(b=!0);a.isFixed?this.viewPortDiv.removeChild(a.div):this.layerContainerDiv.removeChild(a.div);OpenLayers.Util.removeItem(this.layers,a);a.removeMap(this);a.map=null;if(this.baseLayer==a&&(this.baseLayer=null,b))for(var c=0,d=this.layers.length;c<d;c++){var e=this.layers[c];if(e.isBaseLayer||this.allOverlays){this.setBaseLayer(e);break}}this.resetLayersZIndex();this.events.triggerEvent("removelayer",{layer:a});a.events.triggerEvent("removed",
1843 {map:this,layer:a})}},getNumLayers:function(){return this.layers.length},getLayerIndex:function(a){return OpenLayers.Util.indexOf(this.layers,a)},setLayerIndex:function(a,b){var c=this.getLayerIndex(a);0>b?b=0:b>this.layers.length&&(b=this.layers.length);if(c!=b){this.layers.splice(c,1);this.layers.splice(b,0,a);for(var c=0,d=this.layers.length;c<d;c++)this.setLayerZIndex(this.layers[c],c);this.events.triggerEvent("changelayer",{layer:a,property:"order"});this.allOverlays&&(0===b?this.setBaseLayer(a):
1844 this.baseLayer!==this.layers[0]&&this.setBaseLayer(this.layers[0]))}},raiseLayer:function(a,b){var c=this.getLayerIndex(a)+b;this.setLayerIndex(a,c)},setBaseLayer:function(a){if(a!=this.baseLayer&&-1!=OpenLayers.Util.indexOf(this.layers,a)){var b=this.getCachedCenter(),c=OpenLayers.Util.getResolutionFromScale(this.getScale(),a.units);null==this.baseLayer||this.allOverlays||this.baseLayer.setVisibility(!1);this.baseLayer=a;if(!this.allOverlays||this.baseLayer.visibility)this.baseLayer.setVisibility(!0),
1845 !1===this.baseLayer.inRange&&this.baseLayer.redraw();null!=b&&(a=this.getZoomForResolution(c||this.resolution,!0),this.setCenter(b,a,!1,!0));this.events.triggerEvent("changebaselayer",{layer:this.baseLayer})}},addControl:function(a,b){this.controls.push(a);this.addControlToMap(a,b)},addControls:function(a,b){for(var c=1===arguments.length?[]:b,d=0,e=a.length;d<e;d++)this.addControl(a[d],c[d]?c[d]:null)},addControlToMap:function(a,b){a.outsideViewport=null!=a.div;this.displayProjection&&!a.displayProjection&&
1846 (a.displayProjection=this.displayProjection);a.setMap(this);var c=a.draw(b);c&&!a.outsideViewport&&(c.style.zIndex=this.Z_INDEX_BASE.Control+this.controls.length,this.viewPortDiv.appendChild(c));a.autoActivate&&a.activate()},getControl:function(a){for(var b=null,c=0,d=this.controls.length;c<d;c++){var e=this.controls[c];if(e.id==a){b=e;break}}return b},removeControl:function(a){a&&a==this.getControl(a.id)&&(a.div&&a.div.parentNode==this.viewPortDiv&&this.viewPortDiv.removeChild(a.div),OpenLayers.Util.removeItem(this.controls,
1847 a))},addPopup:function(a,b){if(b)for(var c=this.popups.length-1;0<=c;--c)this.removePopup(this.popups[c]);a.map=this;this.popups.push(a);if(c=a.draw())c.style.zIndex=this.Z_INDEX_BASE.Popup+this.popups.length,this.layerContainerDiv.appendChild(c)},removePopup:function(a){OpenLayers.Util.removeItem(this.popups,a);if(a.div)try{this.layerContainerDiv.removeChild(a.div)}catch(b){}a.map=null},getSize:function(){var a=null;null!=this.size&&(a=this.size.clone());return a},updateSize:function(){var a=this.getCurrentSize();
1848 if(a&&!isNaN(a.h)&&!isNaN(a.w)){this.events.clearMouseCache();var b=this.getSize();null==b&&(this.size=b=a);if(!a.equals(b)){this.size=a;a=0;for(b=this.layers.length;a<b;a++)this.layers[a].onMapResize();a=this.getCachedCenter();null!=this.baseLayer&&null!=a&&(b=this.getZoom(),this.zoom=null,this.setCenter(a,b))}}this.events.triggerEvent("updatesize")},getCurrentSize:function(){var a=new OpenLayers.Size(this.div.clientWidth,this.div.clientHeight);if(0==a.w&&0==a.h||isNaN(a.w)&&isNaN(a.h))a.w=this.div.offsetWidth,
1849 a.h=this.div.offsetHeight;if(0==a.w&&0==a.h||isNaN(a.w)&&isNaN(a.h))a.w=parseInt(this.div.style.width),a.h=parseInt(this.div.style.height);return a},calculateBounds:function(a,b){var c=null;null==a&&(a=this.getCachedCenter());null==b&&(b=this.getResolution());if(null!=a&&null!=b)var c=this.size.w*b/2,d=this.size.h*b/2,c=new OpenLayers.Bounds(a.lon-c,a.lat-d,a.lon+c,a.lat+d);return c},getCenter:function(){var a=null,b=this.getCachedCenter();b&&(a=b.clone());return a},getCachedCenter:function(){!this.center&&
1850 this.size&&(this.center=this.getLonLatFromViewPortPx({x:this.size.w/2,y:this.size.h/2}));return this.center},getZoom:function(){return this.zoom},pan:function(a,b,c){c=OpenLayers.Util.applyDefaults(c,{animate:!0,dragging:!1});if(c.dragging)0==a&&0==b||this.moveByPx(a,b);else{var d=this.getViewPortPxFromLonLat(this.getCachedCenter());a=d.add(a,b);if(this.dragging||!a.equals(d))d=this.getLonLatFromViewPortPx(a),c.animate?this.panTo(d):(this.moveTo(d),this.dragging&&(this.dragging=!1,this.events.triggerEvent("moveend")))}},
1851 panTo:function(a){if(this.panTween&&this.getExtent().scale(this.panRatio).containsLonLat(a)){var b=this.getCachedCenter();if(!a.equals(b)){var b=this.getPixelFromLonLat(b),c=this.getPixelFromLonLat(a),d=0,e=0;this.panTween.start({x:0,y:0},{x:c.x-b.x,y:c.y-b.y},this.panDuration,{callbacks:{eachStep:OpenLayers.Function.bind(function(a){this.moveByPx(a.x-d,a.y-e);d=Math.round(a.x);e=Math.round(a.y)},this),done:OpenLayers.Function.bind(function(b){this.moveTo(a);this.dragging=!1;this.events.triggerEvent("moveend")},
1852 this)}})}}else this.setCenter(a)},setCenter:function(a,b,c,d){this.panTween&&this.panTween.stop();this.zoomTween&&this.zoomTween.stop();this.moveTo(a,b,{dragging:c,forceZoomChange:d})},moveByPx:function(a,b){var c=this.size.w/2,d=this.size.h/2,e=c+a,f=d+b,g=this.baseLayer.wrapDateLine,h=0,k=0;this.restrictedExtent&&(h=c,k=d,g=!1);a=g||e<=this.maxPx.x-h&&e>=this.minPx.x+h?Math.round(a):0;b=f<=this.maxPx.y-k&&f>=this.minPx.y+k?Math.round(b):0;if(a||b){this.dragging||(this.dragging=!0,this.events.triggerEvent("movestart"));
1853 this.center=null;a&&(this.layerContainerOriginPx.x-=a,this.minPx.x-=a,this.maxPx.x-=a);b&&(this.layerContainerOriginPx.y-=b,this.minPx.y-=b,this.maxPx.y-=b);this.applyTransform();d=0;for(e=this.layers.length;d<e;++d)c=this.layers[d],c.visibility&&(c===this.baseLayer||c.inRange)&&(c.moveByPx(a,b),c.events.triggerEvent("move"));this.events.triggerEvent("move")}},adjustZoom:function(a){if(this.baseLayer&&this.baseLayer.wrapDateLine){var b=this.baseLayer.resolutions,c=this.getMaxExtent().getWidth()/this.size.w;
1854 if(this.getResolutionForZoom(a)>c)if(this.fractionalZoom)a=this.getZoomForResolution(c);else for(var d=a|0,e=b.length;d<e;++d)if(b[d]<=c){a=d;break}}return a},getMinZoom:function(){return this.adjustZoom(0)},moveTo:function(a,b,c){null==a||a instanceof OpenLayers.LonLat||(a=new OpenLayers.LonLat(a));c||(c={});null!=b&&(b=parseFloat(b),this.fractionalZoom||(b=Math.round(b)));var d=b;b=this.adjustZoom(b);b!==d&&(a=this.getCenter());var d=c.dragging||this.dragging,e=c.forceZoomChange;this.getCachedCenter()||
1855 this.isValidLonLat(a)||(a=this.maxExtent.getCenterLonLat(),this.center=a.clone());if(null!=this.restrictedExtent){null==a&&(a=this.center);null==b&&(b=this.getZoom());var f=this.getResolutionForZoom(b),f=this.calculateBounds(a,f);if(!this.restrictedExtent.containsBounds(f)){var g=this.restrictedExtent.getCenterLonLat();f.getWidth()>this.restrictedExtent.getWidth()?a=new OpenLayers.LonLat(g.lon,a.lat):f.left<this.restrictedExtent.left?a=a.add(this.restrictedExtent.left-f.left,0):f.right>this.restrictedExtent.right&&
1856 (a=a.add(this.restrictedExtent.right-f.right,0));f.getHeight()>this.restrictedExtent.getHeight()?a=new OpenLayers.LonLat(a.lon,g.lat):f.bottom<this.restrictedExtent.bottom?a=a.add(0,this.restrictedExtent.bottom-f.bottom):f.top>this.restrictedExtent.top&&(a=a.add(0,this.restrictedExtent.top-f.top))}}e=e||this.isValidZoomLevel(b)&&b!=this.getZoom();f=this.isValidLonLat(a)&&!a.equals(this.center);if(e||f||d){d||this.events.triggerEvent("movestart",{zoomChanged:e});f&&(!e&&this.center&&this.centerLayerContainer(a),
1857 this.center=a.clone());a=e?this.getResolutionForZoom(b):this.getResolution();if(e||null==this.layerContainerOrigin){this.layerContainerOrigin=this.getCachedCenter();this.layerContainerOriginPx.x=0;this.layerContainerOriginPx.y=0;this.applyTransform();var f=this.getMaxExtent({restricted:!0}),h=f.getCenterLonLat(),g=this.center.lon-h.lon,h=h.lat-this.center.lat,k=Math.round(f.getWidth()/a),l=Math.round(f.getHeight()/a);this.minPx={x:(this.size.w-k)/2-g/a,y:(this.size.h-l)/2-h/a};this.maxPx={x:this.minPx.x+
1858 Math.round(f.getWidth()/a),y:this.minPx.y+Math.round(f.getHeight()/a)}}e&&(this.zoom=b,this.resolution=a);a=this.getExtent();this.baseLayer.visibility&&(this.baseLayer.moveTo(a,e,c.dragging),c.dragging||this.baseLayer.events.triggerEvent("moveend",{zoomChanged:e}));a=this.baseLayer.getExtent();for(b=this.layers.length-1;0<=b;--b)f=this.layers[b],f===this.baseLayer||f.isBaseLayer||(g=f.calculateInRange(),f.inRange!=g&&((f.inRange=g)||f.display(!1),this.events.triggerEvent("changelayer",{layer:f,property:"visibility"})),
1859 g&&f.visibility&&(f.moveTo(a,e,c.dragging),c.dragging||f.events.triggerEvent("moveend",{zoomChanged:e})));this.events.triggerEvent("move");d||this.events.triggerEvent("moveend");if(e){b=0;for(c=this.popups.length;b<c;b++)this.popups[b].updatePosition();this.events.triggerEvent("zoomend")}}},centerLayerContainer:function(a){var b=this.getViewPortPxFromLonLat(this.layerContainerOrigin),c=this.getViewPortPxFromLonLat(a);if(null!=b&&null!=c){var d=this.layerContainerOriginPx.x;a=this.layerContainerOriginPx.y;
1860 var e=Math.round(b.x-c.x),b=Math.round(b.y-c.y);this.applyTransform(this.layerContainerOriginPx.x=e,this.layerContainerOriginPx.y=b);d-=e;a-=b;this.minPx.x-=d;this.maxPx.x-=d;this.minPx.y-=a;this.maxPx.y-=a}},isValidZoomLevel:function(a){return null!=a&&0<=a&&a<this.getNumZoomLevels()},isValidLonLat:function(a){var b=!1;null!=a&&(b=this.getMaxExtent(),b=b.containsLonLat(a,{worldBounds:this.baseLayer.wrapDateLine&&b}));return b},getProjection:function(){var a=this.getProjectionObject();return a?a.getCode():
1861 null},getProjectionObject:function(){var a=null;null!=this.baseLayer&&(a=this.baseLayer.projection);return a},getMaxResolution:function(){var a=null;null!=this.baseLayer&&(a=this.baseLayer.maxResolution);return a},getMaxExtent:function(a){var b=null;a&&a.restricted&&this.restrictedExtent?b=this.restrictedExtent:null!=this.baseLayer&&(b=this.baseLayer.maxExtent);return b},getNumZoomLevels:function(){var a=null;null!=this.baseLayer&&(a=this.baseLayer.numZoomLevels);return a},getExtent:function(){var a=
1862 null;null!=this.baseLayer&&(a=this.baseLayer.getExtent());return a},getResolution:function(){var a=null;null!=this.baseLayer?a=this.baseLayer.getResolution():!0===this.allOverlays&&0<this.layers.length&&(a=this.layers[0].getResolution());return a},getUnits:function(){var a=null;null!=this.baseLayer&&(a=this.baseLayer.units);return a},getScale:function(){var a=null;null!=this.baseLayer&&(a=this.getResolution(),a=OpenLayers.Util.getScaleFromResolution(a,this.baseLayer.units));return a},getZoomForExtent:function(a,
1863 b){var c=null;null!=this.baseLayer&&(c=this.baseLayer.getZoomForExtent(a,b));return c},getResolutionForZoom:function(a){var b=null;this.baseLayer&&(b=this.baseLayer.getResolutionForZoom(a));return b},getZoomForResolution:function(a,b){var c=null;null!=this.baseLayer&&(c=this.baseLayer.getZoomForResolution(a,b));return c},zoomTo:function(a,b){var c=this;if(c.isValidZoomLevel(a))if(c.baseLayer.wrapDateLine&&(a=c.adjustZoom(a)),c.zoomTween){var d=c.getResolution(),e=c.getResolutionForZoom(a),f={scale:1},
1864 d={scale:d/e};c.zoomTween.playing&&c.zoomTween.duration<3*c.zoomDuration?c.zoomTween.finish={scale:c.zoomTween.finish.scale*d.scale}:(b||(e=c.getSize(),b={x:e.w/2,y:e.h/2}),c.zoomTween.start(f,d,c.zoomDuration,{minFrameRate:50,callbacks:{eachStep:function(a){var d=c.layerContainerOriginPx;a=a.scale;c.applyTransform(d.x+((a-1)*(d.x-b.x)|0),d.y+((a-1)*(d.y-b.y)|0),a)},done:function(a){c.applyTransform();a=c.getResolution()/a.scale;var d=c.getZoomForResolution(a,!0);c.moveTo(c.getZoomTargetCenter(b,
1865 a),d,!0)}}}))}else f=b?c.getZoomTargetCenter(b,c.getResolutionForZoom(a)):null,c.setCenter(f,a)},zoomIn:function(){this.zoomTo(this.getZoom()+1)},zoomOut:function(){this.zoomTo(this.getZoom()-1)},zoomToExtent:function(a,b){a instanceof OpenLayers.Bounds||(a=new OpenLayers.Bounds(a));var c=a.getCenterLonLat();if(this.baseLayer.wrapDateLine){c=this.getMaxExtent();for(a=a.clone();a.right<a.left;)a.right+=c.getWidth();c=a.getCenterLonLat().wrapDateLine(c)}this.setCenter(c,this.getZoomForExtent(a,b))},
1866 zoomToMaxExtent:function(a){a=this.getMaxExtent({restricted:a?a.restricted:!0});this.zoomToExtent(a)},zoomToScale:function(a,b){var c=OpenLayers.Util.getResolutionFromScale(a,this.baseLayer.units),d=this.size.w*c/2,c=this.size.h*c/2,e=this.getCachedCenter(),d=new OpenLayers.Bounds(e.lon-d,e.lat-c,e.lon+d,e.lat+c);this.zoomToExtent(d,b)},getLonLatFromViewPortPx:function(a){var b=null;null!=this.baseLayer&&(b=this.baseLayer.getLonLatFromViewPortPx(a));return b},getViewPortPxFromLonLat:function(a){var b=
1867 null;null!=this.baseLayer&&(b=this.baseLayer.getViewPortPxFromLonLat(a));return b},getZoomTargetCenter:function(a,b){var c=null,d=this.getSize(),e=d.w/2-a.x,d=a.y-d.h/2,f=this.getLonLatFromPixel(a);f&&(c=new OpenLayers.LonLat(f.lon+e*b,f.lat+d*b));return c},getLonLatFromPixel:function(a){return this.getLonLatFromViewPortPx(a)},getPixelFromLonLat:function(a){a=this.getViewPortPxFromLonLat(a);a.x=Math.round(a.x);a.y=Math.round(a.y);return a},getGeodesicPixelSize:function(a){var b=a?this.getLonLatFromPixel(a):
1868 this.getCachedCenter()||new OpenLayers.LonLat(0,0),c=this.getResolution();a=b.add(-c/2,0);var d=b.add(c/2,0),e=b.add(0,-c/2),b=b.add(0,c/2),c=new OpenLayers.Projection("EPSG:4326"),f=this.getProjectionObject()||c;f.equals(c)||(a.transform(f,c),d.transform(f,c),e.transform(f,c),b.transform(f,c));return new OpenLayers.Size(OpenLayers.Util.distVincenty(a,d),OpenLayers.Util.distVincenty(e,b))},getViewPortPxFromLayerPx:function(a){var b=null;null!=a&&(b=a.add(this.layerContainerOriginPx.x,this.layerContainerOriginPx.y));
1869 return b},getLayerPxFromViewPortPx:function(a){var b=null;null!=a&&(b=a.add(-this.layerContainerOriginPx.x,-this.layerContainerOriginPx.y),isNaN(b.x)||isNaN(b.y))&&(b=null);return b},getLonLatFromLayerPx:function(a){a=this.getViewPortPxFromLayerPx(a);return this.getLonLatFromViewPortPx(a)},getLayerPxFromLonLat:function(a){a=this.getPixelFromLonLat(a);return this.getLayerPxFromViewPortPx(a)},applyTransform:function(a,b,c){c=c||1;var d=this.layerContainerOriginPx,e=1!==c;a=a||d.x;b=b||d.y;var f=this.layerContainerDiv.style,
1870 g=this.applyTransform.transform,h=this.applyTransform.template;if(void 0===g&&(g=OpenLayers.Util.vendorPrefix.style("transform"),this.applyTransform.transform=g)){var k=OpenLayers.Element.getStyle(this.viewPortDiv,OpenLayers.Util.vendorPrefix.css("transform"));k&&"none"===k||(h=["translate3d(",",0) ","scale3d(",",1)"],f[g]=[h[0],"0,0",h[1]].join(""));h&&~f[g].indexOf(h[0])||(h=["translate(",") ","scale(",")"]);this.applyTransform.template=h}null===g||"translate3d("!==h[0]&&!0!==e?(f.left=a+"px",f.top=
1871 b+"px",null!==g&&(f[g]="")):(!0===e&&"translate("===h[0]&&(a-=d.x,b-=d.y,f.left=d.x+"px",f.top=d.y+"px"),f[g]=[h[0],a,"px,",b,"px",h[1],h[2],c,",",c,h[3]].join(""))},CLASS_NAME:"OpenLayers.Map"});OpenLayers.Map.TILE_WIDTH=256;OpenLayers.Map.TILE_HEIGHT=256;OpenLayers.Handler=OpenLayers.Class({id:null,control:null,map:null,keyMask:null,active:!1,evt:null,touch:!1,initialize:function(a,b,c){OpenLayers.Util.extend(this,c);this.control=a;this.callbacks=b;(a=this.map||a.map)&&this.setMap(a);this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_")},setMap:function(a){this.map=a},checkModifiers:function(a){return null==this.keyMask?!0:((a.shiftKey?OpenLayers.Handler.MOD_SHIFT:0)|(a.ctrlKey?OpenLayers.Handler.MOD_CTRL:0)|(a.altKey?OpenLayers.Handler.MOD_ALT:
1872 0)|(a.metaKey?OpenLayers.Handler.MOD_META:0))==this.keyMask},activate:function(){if(this.active)return!1;for(var a=OpenLayers.Events.prototype.BROWSER_EVENTS,b=0,c=a.length;b<c;b++)this[a[b]]&&this.register(a[b],this[a[b]]);return this.active=!0},deactivate:function(){if(!this.active)return!1;for(var a=OpenLayers.Events.prototype.BROWSER_EVENTS,b=0,c=a.length;b<c;b++)this[a[b]]&&this.unregister(a[b],this[a[b]]);this.active=this.touch=!1;return!0},startTouch:function(){if(!this.touch){this.touch=!0;
1873 for(var a="mousedown mouseup mousemove click dblclick mouseout".split(" "),b=0,c=a.length;b<c;b++)this[a[b]]&&this.unregister(a[b],this[a[b]])}},callback:function(a,b){a&&this.callbacks[a]&&this.callbacks[a].apply(this.control,b)},register:function(a,b){this.map.events.registerPriority(a,this,b);this.map.events.registerPriority(a,this,this.setEvent)},unregister:function(a,b){this.map.events.unregister(a,this,b);this.map.events.unregister(a,this,this.setEvent)},setEvent:function(a){this.evt=a;return!0},
1874 destroy:function(){this.deactivate();this.control=this.map=null},CLASS_NAME:"OpenLayers.Handler"});OpenLayers.Handler.MOD_NONE=0;OpenLayers.Handler.MOD_SHIFT=1;OpenLayers.Handler.MOD_CTRL=2;OpenLayers.Handler.MOD_ALT=4;OpenLayers.Handler.MOD_META=8;OpenLayers.Handler.Click=OpenLayers.Class(OpenLayers.Handler,{delay:300,single:!0,"double":!1,pixelTolerance:0,dblclickTolerance:13,stopSingle:!1,stopDouble:!1,timerId:null,down:null,last:null,first:null,rightclickTimerId:null,touchstart:function(a){this.startTouch();this.down=this.getEventInfo(a);this.last=this.getEventInfo(a);return!0},touchmove:function(a){this.last=this.getEventInfo(a);return!0},touchend:function(a){this.down&&(a.xy=this.last.xy,a.lastTouches=this.last.touches,this.handleSingle(a),
1875 this.down=null);return!0},mousedown:function(a){this.down=this.getEventInfo(a);this.last=this.getEventInfo(a);return!0},mouseup:function(a){var b=!0;this.checkModifiers(a)&&(this.control.handleRightClicks&&OpenLayers.Event.isRightClick(a))&&(b=this.rightclick(a));return b},rightclick:function(a){if(this.passesTolerance(a)){if(null!=this.rightclickTimerId)return this.clearTimer(),this.callback("dblrightclick",[a]),!this.stopDouble;a=this["double"]?OpenLayers.Util.extend({},a):this.callback("rightclick",
1876 [a]);a=OpenLayers.Function.bind(this.delayedRightCall,this,a);this.rightclickTimerId=window.setTimeout(a,this.delay)}return!this.stopSingle},delayedRightCall:function(a){this.rightclickTimerId=null;a&&this.callback("rightclick",[a])},click:function(a){this.last||(this.last=this.getEventInfo(a));this.handleSingle(a);return!this.stopSingle},dblclick:function(a){this.handleDouble(a);return!this.stopDouble},handleDouble:function(a){this.passesDblclickTolerance(a)&&(this["double"]&&this.callback("dblclick",
1877 [a]),this.clearTimer())},handleSingle:function(a){this.passesTolerance(a)&&(null!=this.timerId?(this.last.touches&&1===this.last.touches.length&&(this["double"]&&OpenLayers.Event.preventDefault(a),this.handleDouble(a)),this.last.touches&&2===this.last.touches.length||this.clearTimer()):(this.first=this.getEventInfo(a),a=this.single?OpenLayers.Util.extend({},a):null,this.queuePotentialClick(a)))},queuePotentialClick:function(a){this.timerId=window.setTimeout(OpenLayers.Function.bind(this.delayedCall,
1878 this,a),this.delay)},passesTolerance:function(a){var b=!0;if(null!=this.pixelTolerance&&this.down&&this.down.xy&&(b=this.pixelTolerance>=this.down.xy.distanceTo(a.xy))&&this.touch&&this.down.touches.length===this.last.touches.length){a=0;for(var c=this.down.touches.length;a<c;++a)if(this.getTouchDistance(this.down.touches[a],this.last.touches[a])>this.pixelTolerance){b=!1;break}}return b},getTouchDistance:function(a,b){return Math.sqrt(Math.pow(a.clientX-b.clientX,2)+Math.pow(a.clientY-b.clientY,
1879 2))},passesDblclickTolerance:function(a){a=!0;this.down&&this.first&&(a=this.down.xy.distanceTo(this.first.xy)<=this.dblclickTolerance);return a},clearTimer:function(){null!=this.timerId&&(window.clearTimeout(this.timerId),this.timerId=null);null!=this.rightclickTimerId&&(window.clearTimeout(this.rightclickTimerId),this.rightclickTimerId=null)},delayedCall:function(a){this.timerId=null;a&&this.callback("click",[a])},getEventInfo:function(a){var b;if(a.touches){var c=a.touches.length;b=Array(c);for(var d,
1880 e=0;e<c;e++)d=a.touches[e],b[e]={clientX:d.olClientX,clientY:d.olClientY}}return{xy:a.xy,touches:b}},deactivate:function(){var a=!1;OpenLayers.Handler.prototype.deactivate.apply(this,arguments)&&(this.clearTimer(),this.last=this.first=this.down=null,a=!0);return a},CLASS_NAME:"OpenLayers.Handler.Click"});OpenLayers.Handler.Drag=OpenLayers.Class(OpenLayers.Handler,{started:!1,stopDown:!0,dragging:!1,last:null,start:null,lastMoveEvt:null,oldOnselectstart:null,interval:0,timeoutId:null,documentDrag:!1,documentEvents:null,initialize:function(a,b,c){OpenLayers.Handler.prototype.initialize.apply(this,arguments);if(!0===this.documentDrag){var d=this;this._docMove=function(a){d.mousemove({xy:{x:a.clientX,y:a.clientY},element:document})};this._docUp=function(a){d.mouseup({xy:{x:a.clientX,y:a.clientY}})}}},
1881 dragstart:function(a){var b=!0;this.dragging=!1;this.checkModifiers(a)&&(OpenLayers.Event.isLeftClick(a)||OpenLayers.Event.isSingleTouch(a))?(this.started=!0,this.last=this.start=a.xy,OpenLayers.Element.addClass(this.map.viewPortDiv,"olDragDown"),this.down(a),this.callback("down",[a.xy]),OpenLayers.Event.preventDefault(a),this.oldOnselectstart||(this.oldOnselectstart=document.onselectstart?document.onselectstart:OpenLayers.Function.True),document.onselectstart=OpenLayers.Function.False,b=!this.stopDown):
1882 (this.started=!1,this.last=this.start=null);return b},dragmove:function(a){this.lastMoveEvt=a;!this.started||(this.timeoutId||a.xy.x==this.last.x&&a.xy.y==this.last.y)||(!0===this.documentDrag&&this.documentEvents&&(a.element===document?(this.adjustXY(a),this.setEvent(a)):this.removeDocumentEvents()),0<this.interval&&(this.timeoutId=setTimeout(OpenLayers.Function.bind(this.removeTimeout,this),this.interval)),this.dragging=!0,this.move(a),this.callback("move",[a.xy]),this.oldOnselectstart||(this.oldOnselectstart=
1883 document.onselectstart,document.onselectstart=OpenLayers.Function.False),this.last=a.xy);return!0},dragend:function(a){if(this.started){!0===this.documentDrag&&this.documentEvents&&(this.adjustXY(a),this.removeDocumentEvents());var b=this.start!=this.last;this.dragging=this.started=!1;OpenLayers.Element.removeClass(this.map.viewPortDiv,"olDragDown");this.up(a);this.callback("up",[a.xy]);b&&this.callback("done",[a.xy]);document.onselectstart=this.oldOnselectstart}return!0},down:function(a){},move:function(a){},
1884 up:function(a){},out:function(a){},mousedown:function(a){return this.dragstart(a)},touchstart:function(a){this.startTouch();return this.dragstart(a)},mousemove:function(a){return this.dragmove(a)},touchmove:function(a){return this.dragmove(a)},removeTimeout:function(){this.timeoutId=null;this.dragging&&this.mousemove(this.lastMoveEvt)},mouseup:function(a){return this.dragend(a)},touchend:function(a){a.xy=this.last;return this.dragend(a)},mouseout:function(a){if(this.started&&OpenLayers.Util.mouseLeft(a,
1885 this.map.viewPortDiv))if(!0===this.documentDrag)this.addDocumentEvents();else{var b=this.start!=this.last;this.dragging=this.started=!1;OpenLayers.Element.removeClass(this.map.viewPortDiv,"olDragDown");this.out(a);this.callback("out",[]);b&&this.callback("done",[a.xy]);document.onselectstart&&(document.onselectstart=this.oldOnselectstart)}return!0},click:function(a){return this.start==this.last},activate:function(){var a=!1;OpenLayers.Handler.prototype.activate.apply(this,arguments)&&(this.dragging=
1886 !1,a=!0);return a},deactivate:function(){var a=!1;OpenLayers.Handler.prototype.deactivate.apply(this,arguments)&&(this.dragging=this.started=!1,this.last=this.start=null,a=!0,OpenLayers.Element.removeClass(this.map.viewPortDiv,"olDragDown"));return a},adjustXY:function(a){var b=OpenLayers.Util.pagePosition(this.map.viewPortDiv);a.xy.x-=b[0];a.xy.y-=b[1]},addDocumentEvents:function(){OpenLayers.Element.addClass(document.body,"olDragDown");this.documentEvents=!0;OpenLayers.Event.observe(document,"mousemove",
1887 this._docMove);OpenLayers.Event.observe(document,"mouseup",this._docUp)},removeDocumentEvents:function(){OpenLayers.Element.removeClass(document.body,"olDragDown");this.documentEvents=!1;OpenLayers.Event.stopObserving(document,"mousemove",this._docMove);OpenLayers.Event.stopObserving(document,"mouseup",this._docUp)},CLASS_NAME:"OpenLayers.Handler.Drag"});OpenLayers.Control.OverviewMap=OpenLayers.Class(OpenLayers.Control,{element:null,ovmap:null,size:{w:180,h:90},layers:null,minRectSize:15,minRectDisplayClass:"RectReplacement",minRatio:8,maxRatio:32,mapOptions:null,autoPan:!1,handlers:null,resolutionFactor:1,maximized:!1,maximizeTitle:"",minimizeTitle:"",initialize:function(a){this.layers=[];this.handlers={};OpenLayers.Control.prototype.initialize.apply(this,[a])},destroy:function(){this.mapDiv&&(this.handlers.click&&this.handlers.click.destroy(),
1888 this.handlers.drag&&this.handlers.drag.destroy(),this.ovmap&&this.ovmap.viewPortDiv.removeChild(this.extentRectangle),this.extentRectangle=null,this.rectEvents&&(this.rectEvents.destroy(),this.rectEvents=null),this.ovmap&&(this.ovmap.destroy(),this.ovmap=null),this.element.removeChild(this.mapDiv),this.mapDiv=null,this.div.removeChild(this.element),this.element=null,this.maximizeDiv&&(this.div.removeChild(this.maximizeDiv),this.maximizeDiv=null),this.minimizeDiv&&(this.div.removeChild(this.minimizeDiv),
1889 this.minimizeDiv=null),this.map.events.un({buttonclick:this.onButtonClick,moveend:this.update,changebaselayer:this.baseLayerDraw,scope:this}),OpenLayers.Control.prototype.destroy.apply(this,arguments))},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);if(0===this.layers.length)if(this.map.baseLayer)this.layers=[this.map.baseLayer.clone()];else return this.map.events.register("changebaselayer",this,this.baseLayerDraw),this.div;this.element=document.createElement("div");this.element.className=
1890 this.displayClass+"Element";this.element.style.display="none";this.mapDiv=document.createElement("div");this.mapDiv.style.width=this.size.w+"px";this.mapDiv.style.height=this.size.h+"px";this.mapDiv.style.position="relative";this.mapDiv.style.overflow="hidden";this.mapDiv.id=OpenLayers.Util.createUniqueID("overviewMap");this.extentRectangle=document.createElement("div");this.extentRectangle.style.position="absolute";this.extentRectangle.style.zIndex=1E3;this.extentRectangle.className=this.displayClass+
1891 "ExtentRectangle";this.element.appendChild(this.mapDiv);this.div.appendChild(this.element);if(this.outsideViewport)this.element.style.display="";else{this.div.className+=" "+this.displayClass+"Container";var a=OpenLayers.Util.getImageLocation("layer-switcher-maximize.png");this.maximizeDiv=OpenLayers.Util.createAlphaImageDiv(this.displayClass+"MaximizeButton",null,null,a,"absolute");this.maximizeDiv.style.display="none";this.maximizeDiv.className=this.displayClass+"MaximizeButton olButton";this.maximizeTitle&&
1892 (this.maximizeDiv.title=this.maximizeTitle);this.div.appendChild(this.maximizeDiv);a=OpenLayers.Util.getImageLocation("layer-switcher-minimize.png");this.minimizeDiv=OpenLayers.Util.createAlphaImageDiv("OpenLayers_Control_minimizeDiv",null,null,a,"absolute");this.minimizeDiv.style.display="none";this.minimizeDiv.className=this.displayClass+"MinimizeButton olButton";this.minimizeTitle&&(this.minimizeDiv.title=this.minimizeTitle);this.div.appendChild(this.minimizeDiv);this.minimizeControl()}this.map.getExtent()&&
1893 this.update();this.map.events.on({buttonclick:this.onButtonClick,moveend:this.update,scope:this});this.maximized&&this.maximizeControl();return this.div},baseLayerDraw:function(){this.draw();this.map.events.unregister("changebaselayer",this,this.baseLayerDraw)},rectDrag:function(a){var b=this.handlers.drag.last.x-a.x,c=this.handlers.drag.last.y-a.y;if(0!=b||0!=c){var d=this.rectPxBounds.top,e=this.rectPxBounds.left;a=Math.abs(this.rectPxBounds.getHeight());var f=this.rectPxBounds.getWidth(),c=Math.max(0,
1894 d-c),c=Math.min(c,this.ovmap.size.h-this.hComp-a),b=Math.max(0,e-b),b=Math.min(b,this.ovmap.size.w-this.wComp-f);this.setRectPxBounds(new OpenLayers.Bounds(b,c+a,b+f,c))}},mapDivClick:function(a){var b=this.rectPxBounds.getCenterPixel(),c=a.xy.x-b.x,d=a.xy.y-b.y,e=this.rectPxBounds.top,f=this.rectPxBounds.left;a=Math.abs(this.rectPxBounds.getHeight());b=this.rectPxBounds.getWidth();d=Math.max(0,e+d);d=Math.min(d,this.ovmap.size.h-a);c=Math.max(0,f+c);c=Math.min(c,this.ovmap.size.w-b);this.setRectPxBounds(new OpenLayers.Bounds(c,
1895 d+a,c+b,d));this.updateMapToRect()},onButtonClick:function(a){a.buttonElement===this.minimizeDiv?this.minimizeControl():a.buttonElement===this.maximizeDiv&&this.maximizeControl()},maximizeControl:function(a){this.element.style.display="";this.showToggle(!1);null!=a&&OpenLayers.Event.stop(a)},minimizeControl:function(a){this.element.style.display="none";this.showToggle(!0);null!=a&&OpenLayers.Event.stop(a)},showToggle:function(a){this.maximizeDiv&&(this.maximizeDiv.style.display=a?"":"none");this.minimizeDiv&&
1896 (this.minimizeDiv.style.display=a?"none":"")},update:function(){null==this.ovmap&&this.createMap();!this.autoPan&&this.isSuitableOverview()||this.updateOverview();this.updateRectToMap()},isSuitableOverview:function(){var a=this.map.getExtent(),b=this.map.getMaxExtent(),a=new OpenLayers.Bounds(Math.max(a.left,b.left),Math.max(a.bottom,b.bottom),Math.min(a.right,b.right),Math.min(a.top,b.top));this.ovmap.getProjection()!=this.map.getProjection()&&(a=a.transform(this.map.getProjectionObject(),this.ovmap.getProjectionObject()));
1897 b=this.ovmap.getResolution()/this.map.getResolution();return b>this.minRatio&&b<=this.maxRatio&&this.ovmap.getExtent().containsBounds(a)},updateOverview:function(){var a=this.map.getResolution(),b=this.ovmap.getResolution(),c=b/a;c>this.maxRatio?b=this.minRatio*a:c<=this.minRatio&&(b=this.maxRatio*a);this.ovmap.getProjection()!=this.map.getProjection()?(a=this.map.center.clone(),a.transform(this.map.getProjectionObject(),this.ovmap.getProjectionObject())):a=this.map.center;this.ovmap.setCenter(a,
1898 this.ovmap.getZoomForResolution(b*this.resolutionFactor));this.updateRectToMap()},createMap:function(){var a=OpenLayers.Util.extend({controls:[],maxResolution:"auto",fallThrough:!1},this.mapOptions);this.ovmap=new OpenLayers.Map(this.mapDiv,a);this.ovmap.viewPortDiv.appendChild(this.extentRectangle);OpenLayers.Event.stopObserving(window,"unload",this.ovmap.unloadDestroy);this.ovmap.addLayers(this.layers);this.ovmap.zoomToMaxExtent();this.wComp=(this.wComp=parseInt(OpenLayers.Element.getStyle(this.extentRectangle,
1899 "border-left-width"))+parseInt(OpenLayers.Element.getStyle(this.extentRectangle,"border-right-width")))?this.wComp:2;this.hComp=(this.hComp=parseInt(OpenLayers.Element.getStyle(this.extentRectangle,"border-top-width"))+parseInt(OpenLayers.Element.getStyle(this.extentRectangle,"border-bottom-width")))?this.hComp:2;this.handlers.drag=new OpenLayers.Handler.Drag(this,{move:this.rectDrag,done:this.updateMapToRect},{map:this.ovmap});this.handlers.click=new OpenLayers.Handler.Click(this,{click:this.mapDivClick},
1900 {single:!0,"double":!1,stopSingle:!0,stopDouble:!0,pixelTolerance:1,map:this.ovmap});this.handlers.click.activate();this.rectEvents=new OpenLayers.Events(this,this.extentRectangle,null,!0);this.rectEvents.register("mouseover",this,function(a){this.handlers.drag.active||this.map.dragging||this.handlers.drag.activate()});this.rectEvents.register("mouseout",this,function(a){this.handlers.drag.dragging||this.handlers.drag.deactivate()});if(this.ovmap.getProjection()!=this.map.getProjection()){var a=this.map.getProjectionObject().getUnits()||
1901 this.map.units||this.map.baseLayer.units,b=this.ovmap.getProjectionObject().getUnits()||this.ovmap.units||this.ovmap.baseLayer.units;this.resolutionFactor=a&&b?OpenLayers.INCHES_PER_UNIT[a]/OpenLayers.INCHES_PER_UNIT[b]:1}},updateRectToMap:function(){var a;a=this.ovmap.getProjection()!=this.map.getProjection()?this.map.getExtent().transform(this.map.getProjectionObject(),this.ovmap.getProjectionObject()):this.map.getExtent();(a=this.getRectBoundsFromMapBounds(a))&&this.setRectPxBounds(a)},updateMapToRect:function(){var a=
1902 this.getMapBoundsFromRectBounds(this.rectPxBounds);this.ovmap.getProjection()!=this.map.getProjection()&&(a=a.transform(this.ovmap.getProjectionObject(),this.map.getProjectionObject()));this.map.panTo(a.getCenterLonLat())},setRectPxBounds:function(a){var b=Math.max(a.top,0),c=Math.max(a.left,0),d=Math.min(a.top+Math.abs(a.getHeight()),this.ovmap.size.h-this.hComp);a=Math.min(a.left+a.getWidth(),this.ovmap.size.w-this.wComp);var e=Math.max(a-c,0),f=Math.max(d-b,0);e<this.minRectSize||f<this.minRectSize?
1903 (this.extentRectangle.className=this.displayClass+this.minRectDisplayClass,e=c+e/2-this.minRectSize/2,this.extentRectangle.style.top=Math.round(b+f/2-this.minRectSize/2)+"px",this.extentRectangle.style.left=Math.round(e)+"px",this.extentRectangle.style.height=this.minRectSize+"px",this.extentRectangle.style.width=this.minRectSize+"px"):(this.extentRectangle.className=this.displayClass+"ExtentRectangle",this.extentRectangle.style.top=Math.round(b)+"px",this.extentRectangle.style.left=Math.round(c)+
1904 "px",this.extentRectangle.style.height=Math.round(f)+"px",this.extentRectangle.style.width=Math.round(e)+"px");this.rectPxBounds=new OpenLayers.Bounds(Math.round(c),Math.round(d),Math.round(a),Math.round(b))},getRectBoundsFromMapBounds:function(a){var b=this.getOverviewPxFromLonLat({lon:a.left,lat:a.bottom});a=this.getOverviewPxFromLonLat({lon:a.right,lat:a.top});var c=null;b&&a&&(c=new OpenLayers.Bounds(b.x,b.y,a.x,a.y));return c},getMapBoundsFromRectBounds:function(a){var b=this.getLonLatFromOverviewPx({x:a.left,
1905 y:a.bottom});a=this.getLonLatFromOverviewPx({x:a.right,y:a.top});return new OpenLayers.Bounds(b.lon,b.lat,a.lon,a.lat)},getLonLatFromOverviewPx:function(a){var b=this.ovmap.size,c=this.ovmap.getResolution(),d=this.ovmap.getExtent().getCenterLonLat();return{lon:d.lon+(a.x-b.w/2)*c,lat:d.lat-(a.y-b.h/2)*c}},getOverviewPxFromLonLat:function(a){var b=this.ovmap.getResolution(),c=this.ovmap.getExtent();if(c)return{x:Math.round(1/b*(a.lon-c.left)),y:Math.round(1/b*(c.top-a.lat))}},CLASS_NAME:"OpenLayers.Control.OverviewMap"});OpenLayers.Layer=OpenLayers.Class({id:null,name:null,div:null,opacity:1,alwaysInRange:null,RESOLUTION_PROPERTIES:"scales resolutions maxScale minScale maxResolution minResolution numZoomLevels maxZoomLevel".split(" "),events:null,map:null,isBaseLayer:!1,alpha:!1,displayInLayerSwitcher:!0,visibility:!0,attribution:null,inRange:!1,imageSize:null,options:null,eventListeners:null,gutter:0,projection:null,units:null,scales:null,resolutions:null,maxExtent:null,minExtent:null,maxResolution:null,minResolution:null,
1906 numZoomLevels:null,minScale:null,maxScale:null,displayOutsideMaxExtent:!1,wrapDateLine:!1,metadata:null,initialize:function(a,b){this.metadata={};b=OpenLayers.Util.extend({},b);null!=this.alwaysInRange&&(b.alwaysInRange=this.alwaysInRange);this.addOptions(b);this.name=a;if(null==this.id&&(this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_"),this.div=OpenLayers.Util.createDiv(this.id),this.div.style.width="100%",this.div.style.height="100%",this.div.dir="ltr",this.events=new OpenLayers.Events(this,
1907 this.div),this.eventListeners instanceof Object))this.events.on(this.eventListeners)},destroy:function(a){null==a&&(a=!0);null!=this.map&&this.map.removeLayer(this,a);this.options=this.div=this.name=this.map=this.projection=null;this.events&&(this.eventListeners&&this.events.un(this.eventListeners),this.events.destroy());this.events=this.eventListeners=null},clone:function(a){null==a&&(a=new OpenLayers.Layer(this.name,this.getOptions()));OpenLayers.Util.applyDefaults(a,this);a.map=null;return a},
1908 getOptions:function(){var a={},b;for(b in this.options)a[b]=this[b];return a},setName:function(a){a!=this.name&&(this.name=a,null!=this.map&&this.map.events.triggerEvent("changelayer",{layer:this,property:"name"}))},addOptions:function(a,b){null==this.options&&(this.options={});a&&("string"==typeof a.projection&&(a.projection=new OpenLayers.Projection(a.projection)),a.projection&&OpenLayers.Util.applyDefaults(a,OpenLayers.Projection.defaults[a.projection.getCode()]),!a.maxExtent||a.maxExtent instanceof
1909 OpenLayers.Bounds||(a.maxExtent=new OpenLayers.Bounds(a.maxExtent)),!a.minExtent||a.minExtent instanceof OpenLayers.Bounds||(a.minExtent=new OpenLayers.Bounds(a.minExtent)));OpenLayers.Util.extend(this.options,a);OpenLayers.Util.extend(this,a);this.projection&&this.projection.getUnits()&&(this.units=this.projection.getUnits());if(this.map){var c=this.map.getResolution(),d=this.RESOLUTION_PROPERTIES.concat(["projection","units","minExtent","maxExtent"]),e;for(e in a)if(a.hasOwnProperty(e)&&0<=OpenLayers.Util.indexOf(d,
1910 e)){this.initResolutions();b&&this.map.baseLayer===this&&(this.map.setCenter(this.map.getCenter(),this.map.getZoomForResolution(c),!1,!0),this.map.events.triggerEvent("changebaselayer",{layer:this}));break}}},onMapResize:function(){},redraw:function(){var a=!1;if(this.map){this.inRange=this.calculateInRange();var b=this.getExtent();b&&(this.inRange&&this.visibility)&&(this.moveTo(b,!0,!1),this.events.triggerEvent("moveend",{zoomChanged:!0}),a=!0)}return a},moveTo:function(a,b,c){a=this.visibility;
1911 this.isBaseLayer||(a=a&&this.inRange);this.display(a)},moveByPx:function(a,b){},setMap:function(a){null==this.map&&(this.map=a,this.maxExtent=this.maxExtent||this.map.maxExtent,this.minExtent=this.minExtent||this.map.minExtent,this.projection=this.projection||this.map.projection,"string"==typeof this.projection&&(this.projection=new OpenLayers.Projection(this.projection)),this.units=this.projection.getUnits()||this.units||this.map.units,this.initResolutions(),this.isBaseLayer||(this.inRange=this.calculateInRange(),
1912 this.div.style.display=this.visibility&&this.inRange?"":"none"),this.setTileSize())},afterAdd:function(){},removeMap:function(a){},getImageSize:function(a){return this.imageSize||this.tileSize},setTileSize:function(a){this.tileSize=a=a?a:this.tileSize?this.tileSize:this.map.getTileSize();this.gutter&&(this.imageSize=new OpenLayers.Size(a.w+2*this.gutter,a.h+2*this.gutter))},getVisibility:function(){return this.visibility},setVisibility:function(a){a!=this.visibility&&(this.visibility=a,this.display(a),
1913 this.redraw(),null!=this.map&&this.map.events.triggerEvent("changelayer",{layer:this,property:"visibility"}),this.events.triggerEvent("visibilitychanged"))},display:function(a){a!=("none"!=this.div.style.display)&&(this.div.style.display=a&&this.calculateInRange()?"block":"none")},calculateInRange:function(){var a=!1;this.alwaysInRange?a=!0:this.map&&(a=this.map.getResolution(),a=a>=this.minResolution&&a<=this.maxResolution);return a},setIsBaseLayer:function(a){a!=this.isBaseLayer&&(this.isBaseLayer=
1914 a,null!=this.map&&this.map.events.triggerEvent("changebaselayer",{layer:this}))},initResolutions:function(){var a,b,c,d={},e=!0;a=0;for(b=this.RESOLUTION_PROPERTIES.length;a<b;a++)c=this.RESOLUTION_PROPERTIES[a],d[c]=this.options[c],e&&this.options[c]&&(e=!1);null==this.options.alwaysInRange&&(this.alwaysInRange=e);null==d.resolutions&&(d.resolutions=this.resolutionsFromScales(d.scales));null==d.resolutions&&(d.resolutions=this.calculateResolutions(d));if(null==d.resolutions){a=0;for(b=this.RESOLUTION_PROPERTIES.length;a<
1915 b;a++)c=this.RESOLUTION_PROPERTIES[a],d[c]=null!=this.options[c]?this.options[c]:this.map[c];null==d.resolutions&&(d.resolutions=this.resolutionsFromScales(d.scales));null==d.resolutions&&(d.resolutions=this.calculateResolutions(d))}var f;this.options.maxResolution&&"auto"!==this.options.maxResolution&&(f=this.options.maxResolution);this.options.minScale&&(f=OpenLayers.Util.getResolutionFromScale(this.options.minScale,this.units));var g;this.options.minResolution&&"auto"!==this.options.minResolution&&
1916 (g=this.options.minResolution);this.options.maxScale&&(g=OpenLayers.Util.getResolutionFromScale(this.options.maxScale,this.units));d.resolutions&&(d.resolutions.sort(function(a,b){return b-a}),f||(f=d.resolutions[0]),g||(g=d.resolutions[d.resolutions.length-1]));if(this.resolutions=d.resolutions){b=this.resolutions.length;this.scales=Array(b);for(a=0;a<b;a++)this.scales[a]=OpenLayers.Util.getScaleFromResolution(this.resolutions[a],this.units);this.numZoomLevels=b}if(this.minResolution=g)this.maxScale=
1917 OpenLayers.Util.getScaleFromResolution(g,this.units);if(this.maxResolution=f)this.minScale=OpenLayers.Util.getScaleFromResolution(f,this.units)},resolutionsFromScales:function(a){if(null!=a){var b,c,d;d=a.length;b=Array(d);for(c=0;c<d;c++)b[c]=OpenLayers.Util.getResolutionFromScale(a[c],this.units);return b}},calculateResolutions:function(a){var b,c,d=a.maxResolution;null!=a.minScale?d=OpenLayers.Util.getResolutionFromScale(a.minScale,this.units):"auto"==d&&null!=this.maxExtent&&(b=this.map.getSize(),
1918 c=this.maxExtent.getWidth()/b.w,b=this.maxExtent.getHeight()/b.h,d=Math.max(c,b));c=a.minResolution;null!=a.maxScale?c=OpenLayers.Util.getResolutionFromScale(a.maxScale,this.units):"auto"==a.minResolution&&null!=this.minExtent&&(b=this.map.getSize(),c=this.minExtent.getWidth()/b.w,b=this.minExtent.getHeight()/b.h,c=Math.max(c,b));"number"!==typeof d&&("number"!==typeof c&&null!=this.maxExtent)&&(d=this.map.getTileSize(),d=Math.max(this.maxExtent.getWidth()/d.w,this.maxExtent.getHeight()/d.h));b=a.maxZoomLevel;
1919 a=a.numZoomLevels;"number"===typeof c&&"number"===typeof d&&void 0===a?a=Math.floor(Math.log(d/c)/Math.log(2))+1:void 0===a&&null!=b&&(a=b+1);if(!("number"!==typeof a||0>=a||"number"!==typeof d&&"number"!==typeof c)){b=Array(a);var e=2;"number"==typeof c&&"number"==typeof d&&(e=Math.pow(d/c,1/(a-1)));var f;if("number"===typeof d)for(f=0;f<a;f++)b[f]=d/Math.pow(e,f);else for(f=0;f<a;f++)b[a-1-f]=c*Math.pow(e,f);return b}},getResolution:function(){var a=this.map.getZoom();return this.getResolutionForZoom(a)},
1920 getExtent:function(){return this.map.calculateBounds()},getZoomForExtent:function(a,b){var c=this.map.getSize(),c=Math.max(a.getWidth()/c.w,a.getHeight()/c.h);return this.getZoomForResolution(c,b)},getDataExtent:function(){},getResolutionForZoom:function(a){a=Math.max(0,Math.min(a,this.resolutions.length-1));if(this.map.fractionalZoom){var b=Math.floor(a),c=Math.ceil(a);a=this.resolutions[b]-(a-b)*(this.resolutions[b]-this.resolutions[c])}else a=this.resolutions[Math.round(a)];return a},getZoomForResolution:function(a,
1921 b){var c,d;if(this.map.fractionalZoom){var e=0,f=this.resolutions[e],g=this.resolutions[this.resolutions.length-1],h;c=0;for(d=this.resolutions.length;c<d;++c)if(h=this.resolutions[c],h>=a&&(f=h,e=c),h<=a){g=h;break}c=f-g;c=0<c?e+(f-a)/c:e}else{f=Number.POSITIVE_INFINITY;c=0;for(d=this.resolutions.length;c<d;c++)if(b){e=Math.abs(this.resolutions[c]-a);if(e>f)break;f=e}else if(this.resolutions[c]<a)break;c=Math.max(0,c-1)}return c},getLonLatFromViewPortPx:function(a){var b=null,c=this.map;if(null!=
1922 a&&c.minPx){var b=c.getResolution(),d=c.getMaxExtent({restricted:!0}),b=new OpenLayers.LonLat((a.x-c.minPx.x)*b+d.left,(c.minPx.y-a.y)*b+d.top);this.wrapDateLine&&(b=b.wrapDateLine(this.maxExtent))}return b},getViewPortPxFromLonLat:function(a,b){var c=null;null!=a&&(b=b||this.map.getResolution(),c=this.map.calculateBounds(null,b),c=new OpenLayers.Pixel(1/b*(a.lon-c.left),1/b*(c.top-a.lat)));return c},setOpacity:function(a){if(a!=this.opacity){this.opacity=a;for(var b=this.div.childNodes,c=0,d=b.length;c<
1923 d;++c){var e=b[c].firstChild||b[c],f=b[c].lastChild;f&&"iframe"===f.nodeName.toLowerCase()&&(e=f.parentNode);OpenLayers.Util.modifyDOMElement(e,null,null,null,null,null,null,a)}null!=this.map&&this.map.events.triggerEvent("changelayer",{layer:this,property:"opacity"})}},getZIndex:function(){return this.div.style.zIndex},setZIndex:function(a){this.div.style.zIndex=a},adjustBounds:function(a){if(this.gutter){var b=this.gutter*this.map.getResolution();a=new OpenLayers.Bounds(a.left-b,a.bottom-b,a.right+
1924 b,a.top+b)}this.wrapDateLine&&(b={rightTolerance:this.getResolution(),leftTolerance:this.getResolution()},a=a.wrapDateLine(this.maxExtent,b));return a},CLASS_NAME:"OpenLayers.Layer"});OpenLayers.Layer.SphericalMercator={getExtent:function(){var a=null;return a=this.sphericalMercator?this.map.calculateBounds():OpenLayers.Layer.FixedZoomLevels.prototype.getExtent.apply(this)},getLonLatFromViewPortPx:function(a){return OpenLayers.Layer.prototype.getLonLatFromViewPortPx.apply(this,arguments)},getViewPortPxFromLonLat:function(a){return OpenLayers.Layer.prototype.getViewPortPxFromLonLat.apply(this,arguments)},initMercatorParameters:function(){this.RESOLUTIONS=[];for(var a=0;a<=this.MAX_ZOOM_LEVEL;++a)this.RESOLUTIONS[a]=
1925 156543.03390625/Math.pow(2,a);this.units="m";this.projection=this.projection||"EPSG:900913"},forwardMercator:function(){var a=new OpenLayers.Projection("EPSG:4326"),b=new OpenLayers.Projection("EPSG:900913");return function(c,d){var e=OpenLayers.Projection.transform({x:c,y:d},a,b);return new OpenLayers.LonLat(e.x,e.y)}}(),inverseMercator:function(){var a=new OpenLayers.Projection("EPSG:4326"),b=new OpenLayers.Projection("EPSG:900913");return function(c,d){var e=OpenLayers.Projection.transform({x:c,
1926 y:d},b,a);return new OpenLayers.LonLat(e.x,e.y)}}()};OpenLayers.Layer.EventPane=OpenLayers.Class(OpenLayers.Layer,{smoothDragPan:!0,isBaseLayer:!0,isFixed:!0,pane:null,mapObject:null,initialize:function(a,b){OpenLayers.Layer.prototype.initialize.apply(this,arguments);null==this.pane&&(this.pane=OpenLayers.Util.createDiv(this.div.id+"_EventPane"))},destroy:function(){this.pane=this.mapObject=null;OpenLayers.Layer.prototype.destroy.apply(this,arguments)},setMap:function(a){OpenLayers.Layer.prototype.setMap.apply(this,arguments);this.pane.style.zIndex=
1927 parseInt(this.div.style.zIndex)+1;this.pane.style.display=this.div.style.display;this.pane.style.width="100%";this.pane.style.height="100%";"msie"==OpenLayers.BROWSER_NAME&&(this.pane.style.background="url("+OpenLayers.Util.getImageLocation("blank.gif")+")");this.isFixed?this.map.viewPortDiv.appendChild(this.pane):this.map.layerContainerDiv.appendChild(this.pane);this.loadMapObject();null==this.mapObject&&this.loadWarningMessage()},removeMap:function(a){this.pane&&this.pane.parentNode&&this.pane.parentNode.removeChild(this.pane);
1928 OpenLayers.Layer.prototype.removeMap.apply(this,arguments)},loadWarningMessage:function(){this.div.style.backgroundColor="darkblue";var a=this.map.getSize(),b=Math.min(a.w,300),c=Math.min(a.h,200),b=new OpenLayers.Size(b,c),a=(new OpenLayers.Pixel(a.w/2,a.h/2)).add(-b.w/2,-b.h/2),a=OpenLayers.Util.createDiv(this.name+"_warning",a,b,null,null,null,"auto");a.style.padding="7px";a.style.backgroundColor="yellow";a.innerHTML=this.getWarningHTML();this.div.appendChild(a)},getWarningHTML:function(){return""},
1929 display:function(a){OpenLayers.Layer.prototype.display.apply(this,arguments);this.pane.style.display=this.div.style.display},setZIndex:function(a){OpenLayers.Layer.prototype.setZIndex.apply(this,arguments);this.pane.style.zIndex=parseInt(this.div.style.zIndex)+1},moveByPx:function(a,b){OpenLayers.Layer.prototype.moveByPx.apply(this,arguments);this.dragPanMapObject?this.dragPanMapObject(a,-b):this.moveTo(this.map.getCachedCenter())},moveTo:function(a,b,c){OpenLayers.Layer.prototype.moveTo.apply(this,
1930 arguments);if(null!=this.mapObject){var d=this.map.getCenter(),e=this.map.getZoom();if(null!=d){var f=this.getMapObjectCenter(),f=this.getOLLonLatFromMapObjectLonLat(f),g=this.getMapObjectZoom(),g=this.getOLZoomFromMapObjectZoom(g);d.equals(f)&&e==g||(!b&&f&&this.dragPanMapObject&&this.smoothDragPan?(e=this.map.getViewPortPxFromLonLat(f),d=this.map.getViewPortPxFromLonLat(d),this.dragPanMapObject(d.x-e.x,e.y-d.y)):(d=this.getMapObjectLonLatFromOLLonLat(d),e=this.getMapObjectZoomFromOLZoom(e),this.setMapObjectCenter(d,
1931 e,c)))}}},getLonLatFromViewPortPx:function(a){var b=null;null!=this.mapObject&&null!=this.getMapObjectCenter()&&(a=this.getMapObjectPixelFromOLPixel(a),a=this.getMapObjectLonLatFromMapObjectPixel(a),b=this.getOLLonLatFromMapObjectLonLat(a));return b},getViewPortPxFromLonLat:function(a){var b=null;null!=this.mapObject&&null!=this.getMapObjectCenter()&&(a=this.getMapObjectLonLatFromOLLonLat(a),a=this.getMapObjectPixelFromMapObjectLonLat(a),b=this.getOLPixelFromMapObjectPixel(a));return b},getOLLonLatFromMapObjectLonLat:function(a){var b=
1932 null;null!=a&&(b=this.getLongitudeFromMapObjectLonLat(a),a=this.getLatitudeFromMapObjectLonLat(a),b=new OpenLayers.LonLat(b,a));return b},getMapObjectLonLatFromOLLonLat:function(a){var b=null;null!=a&&(b=this.getMapObjectLonLatFromLonLat(a.lon,a.lat));return b},getOLPixelFromMapObjectPixel:function(a){var b=null;null!=a&&(b=this.getXFromMapObjectPixel(a),a=this.getYFromMapObjectPixel(a),b=new OpenLayers.Pixel(b,a));return b},getMapObjectPixelFromOLPixel:function(a){var b=null;null!=a&&(b=this.getMapObjectPixelFromXY(a.x,
1933 a.y));return b},CLASS_NAME:"OpenLayers.Layer.EventPane"});OpenLayers.Layer.FixedZoomLevels=OpenLayers.Class({initialize:function(){},initResolutions:function(){for(var a=["minZoomLevel","maxZoomLevel","numZoomLevels"],b=0,c=a.length;b<c;b++){var d=a[b];this[d]=null!=this.options[d]?this.options[d]:this.map[d]}if(null==this.minZoomLevel||this.minZoomLevel<this.MIN_ZOOM_LEVEL)this.minZoomLevel=this.MIN_ZOOM_LEVEL;a=this.MAX_ZOOM_LEVEL-this.minZoomLevel+1;b=null==this.options.numZoomLevels&&null!=this.options.maxZoomLevel||null==this.numZoomLevels&&null!=this.maxZoomLevel?
1934 this.maxZoomLevel-this.minZoomLevel+1:this.numZoomLevels;this.numZoomLevels=null!=b?Math.min(b,a):a;this.maxZoomLevel=this.minZoomLevel+this.numZoomLevels-1;if(null!=this.RESOLUTIONS){a=0;this.resolutions=[];for(b=this.minZoomLevel;b<=this.maxZoomLevel;b++)this.resolutions[a++]=this.RESOLUTIONS[b];this.maxResolution=this.resolutions[0];this.minResolution=this.resolutions[this.resolutions.length-1]}},getResolution:function(){if(null!=this.resolutions)return OpenLayers.Layer.prototype.getResolution.apply(this,
1935 arguments);var a=null,b=this.map.getSize(),c=this.getExtent();null!=b&&null!=c&&(a=Math.max(c.getWidth()/b.w,c.getHeight()/b.h));return a},getExtent:function(){var a=this.map.getSize(),b=this.getLonLatFromViewPortPx({x:0,y:0}),a=this.getLonLatFromViewPortPx({x:a.w,y:a.h});return null!=b&&null!=a?new OpenLayers.Bounds(b.lon,a.lat,a.lon,b.lat):null},getZoomForResolution:function(a){if(null!=this.resolutions)return OpenLayers.Layer.prototype.getZoomForResolution.apply(this,arguments);var b=OpenLayers.Layer.prototype.getExtent.apply(this,
1936 []);return this.getZoomForExtent(b)},getOLZoomFromMapObjectZoom:function(a){var b=null;null!=a&&(b=a-this.minZoomLevel,this.map.baseLayer!==this&&(b=this.map.baseLayer.getZoomForResolution(this.getResolutionForZoom(b))));return b},getMapObjectZoomFromOLZoom:function(a){var b=null;null!=a&&(b=a+this.minZoomLevel,this.map.baseLayer!==this&&(b=this.getZoomForResolution(this.map.baseLayer.getResolutionForZoom(b))));return b},CLASS_NAME:"OpenLayers.Layer.FixedZoomLevels"});OpenLayers.Layer.Google=OpenLayers.Class(OpenLayers.Layer.EventPane,OpenLayers.Layer.FixedZoomLevels,{MIN_ZOOM_LEVEL:0,MAX_ZOOM_LEVEL:21,RESOLUTIONS:[1.40625,0.703125,0.3515625,0.17578125,0.087890625,0.0439453125,0.02197265625,0.010986328125,0.0054931640625,0.00274658203125,0.001373291015625,6.866455078125E-4,3.4332275390625E-4,1.71661376953125E-4,8.58306884765625E-5,4.291534423828125E-5,2.145767211914062E-5,1.072883605957031E-5,5.36441802978515E-6,2.68220901489257E-6,1.341104507446289E-6,6.705522537231445E-7],
1937 type:null,wrapDateLine:!0,sphericalMercator:!1,version:null,initialize:function(a,b){b=b||{};b.version||(b.version="function"===typeof GMap2?"2":"3");var c=OpenLayers.Layer.Google["v"+b.version.replace(/\./g,"_")];if(c)OpenLayers.Util.applyDefaults(b,c);else throw"Unsupported Google Maps API version: "+b.version;OpenLayers.Util.applyDefaults(b,c.DEFAULTS);b.maxExtent&&(b.maxExtent=b.maxExtent.clone());OpenLayers.Layer.EventPane.prototype.initialize.apply(this,[a,b]);OpenLayers.Layer.FixedZoomLevels.prototype.initialize.apply(this,
1938 [a,b]);this.sphericalMercator&&(OpenLayers.Util.extend(this,OpenLayers.Layer.SphericalMercator),this.initMercatorParameters())},clone:function(){return new OpenLayers.Layer.Google(this.name,this.getOptions())},setVisibility:function(a){var b=null==this.opacity?1:this.opacity;OpenLayers.Layer.EventPane.prototype.setVisibility.apply(this,arguments);this.setOpacity(b)},display:function(a){this._dragging||this.setGMapVisibility(a);OpenLayers.Layer.EventPane.prototype.display.apply(this,arguments)},moveTo:function(a,
1939 b,c){this._dragging=c;OpenLayers.Layer.EventPane.prototype.moveTo.apply(this,arguments);delete this._dragging},setOpacity:function(a){a!==this.opacity&&(null!=this.map&&this.map.events.triggerEvent("changelayer",{layer:this,property:"opacity"}),this.opacity=a);if(this.getVisibility()){var b=this.getMapContainer();OpenLayers.Util.modifyDOMElement(b,null,null,null,null,null,null,a)}},destroy:function(){if(this.map){this.setGMapVisibility(!1);var a=OpenLayers.Layer.Google.cache[this.map.id];a&&1>=a.count&&
1940 this.removeGMapElements()}OpenLayers.Layer.EventPane.prototype.destroy.apply(this,arguments)},removeGMapElements:function(){var a=OpenLayers.Layer.Google.cache[this.map.id];if(a){var b=this.mapObject&&this.getMapContainer();b&&b.parentNode&&b.parentNode.removeChild(b);(b=a.termsOfUse)&&b.parentNode&&b.parentNode.removeChild(b);(a=a.poweredBy)&&a.parentNode&&a.parentNode.removeChild(a);this.mapObject&&(window.google&&google.maps&&google.maps.event&&google.maps.event.clearListeners)&&google.maps.event.clearListeners(this.mapObject,
1941 "tilesloaded")}},removeMap:function(a){this.visibility&&this.mapObject&&this.setGMapVisibility(!1);var b=OpenLayers.Layer.Google.cache[a.id];b&&(1>=b.count?(this.removeGMapElements(),delete OpenLayers.Layer.Google.cache[a.id]):--b.count);delete this.termsOfUse;delete this.poweredBy;delete this.mapObject;delete this.dragObject;OpenLayers.Layer.EventPane.prototype.removeMap.apply(this,arguments)},getOLBoundsFromMapObjectBounds:function(a){var b=null;null!=a&&(b=a.getSouthWest(),a=a.getNorthEast(),this.sphericalMercator?
1942 (b=this.forwardMercator(b.lng(),b.lat()),a=this.forwardMercator(a.lng(),a.lat())):(b=new OpenLayers.LonLat(b.lng(),b.lat()),a=new OpenLayers.LonLat(a.lng(),a.lat())),b=new OpenLayers.Bounds(b.lon,b.lat,a.lon,a.lat));return b},getWarningHTML:function(){return OpenLayers.i18n("googleWarning")},getMapObjectCenter:function(){return this.mapObject.getCenter()},getMapObjectZoom:function(){return this.mapObject.getZoom()},getLongitudeFromMapObjectLonLat:function(a){return this.sphericalMercator?this.forwardMercator(a.lng(),
1943 a.lat()).lon:a.lng()},getLatitudeFromMapObjectLonLat:function(a){return this.sphericalMercator?this.forwardMercator(a.lng(),a.lat()).lat:a.lat()},getXFromMapObjectPixel:function(a){return a.x},getYFromMapObjectPixel:function(a){return a.y},CLASS_NAME:"OpenLayers.Layer.Google"});OpenLayers.Layer.Google.cache={};
1944 OpenLayers.Layer.Google.v2={termsOfUse:null,poweredBy:null,dragObject:null,loadMapObject:function(){this.type||(this.type=G_NORMAL_MAP);var a,b,c,d=OpenLayers.Layer.Google.cache[this.map.id];if(d)a=d.mapObject,b=d.termsOfUse,c=d.poweredBy,++d.count;else{var d=this.map.viewPortDiv,e=document.createElement("div");e.id=this.map.id+"_GMap2Container";e.style.position="absolute";e.style.width="100%";e.style.height="100%";d.appendChild(e);try{a=new GMap2(e),b=e.lastChild,d.appendChild(b),b.style.zIndex=
1945 "1100",b.style.right="",b.style.bottom="",b.className="olLayerGoogleCopyright",c=e.lastChild,d.appendChild(c),c.style.zIndex="1100",c.style.right="",c.style.bottom="",c.className="olLayerGooglePoweredBy gmnoprint"}catch(f){throw f;}OpenLayers.Layer.Google.cache[this.map.id]={mapObject:a,termsOfUse:b,poweredBy:c,count:1}}this.mapObject=a;this.termsOfUse=b;this.poweredBy=c;-1===OpenLayers.Util.indexOf(this.mapObject.getMapTypes(),this.type)&&this.mapObject.addMapType(this.type);"function"==typeof a.getDragObject?
1946 this.dragObject=a.getDragObject():this.dragPanMapObject=null;!1===this.isBaseLayer&&this.setGMapVisibility("none"!==this.div.style.display)},onMapResize:function(){if(this.visibility&&this.mapObject.isLoaded())this.mapObject.checkResize();else{if(!this._resized)var a=this,b=GEvent.addListener(this.mapObject,"load",function(){GEvent.removeListener(b);delete a._resized;a.mapObject.checkResize();a.moveTo(a.map.getCenter(),a.map.getZoom())});this._resized=!0}},setGMapVisibility:function(a){var b=OpenLayers.Layer.Google.cache[this.map.id];
1947 if(b){var c=this.mapObject.getContainer();!0===a?(this.mapObject.setMapType(this.type),c.style.display="",this.termsOfUse.style.left="",this.termsOfUse.style.display="",this.poweredBy.style.display="",b.displayed=this.id):(b.displayed===this.id&&delete b.displayed,b.displayed||(c.style.display="none",this.termsOfUse.style.display="none",this.termsOfUse.style.left="-9999px",this.poweredBy.style.display="none"))}},getMapContainer:function(){return this.mapObject.getContainer()},getMapObjectBoundsFromOLBounds:function(a){var b=
1948 null;null!=a&&(b=this.sphericalMercator?this.inverseMercator(a.bottom,a.left):new OpenLayers.LonLat(a.bottom,a.left),a=this.sphericalMercator?this.inverseMercator(a.top,a.right):new OpenLayers.LonLat(a.top,a.right),b=new GLatLngBounds(new GLatLng(b.lat,b.lon),new GLatLng(a.lat,a.lon)));return b},setMapObjectCenter:function(a,b){this.mapObject.setCenter(a,b)},dragPanMapObject:function(a,b){this.dragObject.moveBy(new GSize(-a,b))},getMapObjectLonLatFromMapObjectPixel:function(a){return this.mapObject.fromContainerPixelToLatLng(a)},
1949 getMapObjectPixelFromMapObjectLonLat:function(a){return this.mapObject.fromLatLngToContainerPixel(a)},getMapObjectZoomFromMapObjectBounds:function(a){return this.mapObject.getBoundsZoomLevel(a)},getMapObjectLonLatFromLonLat:function(a,b){var c;this.sphericalMercator?(c=this.inverseMercator(a,b),c=new GLatLng(c.lat,c.lon)):c=new GLatLng(b,a);return c},getMapObjectPixelFromXY:function(a,b){return new GPoint(a,b)}};OpenLayers.Format.XML=OpenLayers.Class(OpenLayers.Format,{namespaces:null,namespaceAlias:null,defaultPrefix:null,readers:{},writers:{},xmldom:null,initialize:function(a){window.ActiveXObject&&(this.xmldom=new ActiveXObject("Microsoft.XMLDOM"));OpenLayers.Format.prototype.initialize.apply(this,[a]);this.namespaces=OpenLayers.Util.extend({},this.namespaces);this.namespaceAlias={};for(var b in this.namespaces)this.namespaceAlias[this.namespaces[b]]=b},destroy:function(){this.xmldom=null;OpenLayers.Format.prototype.destroy.apply(this,
1950 arguments)},setNamespace:function(a,b){this.namespaces[a]=b;this.namespaceAlias[b]=a},read:function(a){var b=a.indexOf("<");0<b&&(a=a.substring(b));b=OpenLayers.Util.Try(OpenLayers.Function.bind(function(){var b;b=window.ActiveXObject&&!this.xmldom?new ActiveXObject("Microsoft.XMLDOM"):this.xmldom;b.loadXML(a);return b},this),function(){return(new DOMParser).parseFromString(a,"text/xml")},function(){var b=new XMLHttpRequest;b.open("GET","data:text/xml;charset=utf-8,"+encodeURIComponent(a),!1);b.overrideMimeType&&
1951 b.overrideMimeType("text/xml");b.send(null);return b.responseXML});this.keepData&&(this.data=b);return b},write:function(a){if(this.xmldom)a=a.xml;else{var b=new XMLSerializer;if(1==a.nodeType){var c=document.implementation.createDocument("","",null);c.importNode&&(a=c.importNode(a,!0));c.appendChild(a);a=b.serializeToString(c)}else a=b.serializeToString(a)}return a},createElementNS:function(a,b){return this.xmldom?"string"==typeof a?this.xmldom.createNode(1,b,a):this.xmldom.createNode(1,b,""):document.createElementNS(a,
1952 b)},createDocumentFragment:function(){return this.xmldom?this.xmldom.createDocumentFragment():document.createDocumentFragment()},createTextNode:function(a){"string"!==typeof a&&(a=String(a));return this.xmldom?this.xmldom.createTextNode(a):document.createTextNode(a)},getElementsByTagNameNS:function(a,b,c){var d=[];if(a.getElementsByTagNameNS)d=a.getElementsByTagNameNS(b,c);else{a=a.getElementsByTagName("*");for(var e,f,g=0,h=a.length;g<h;++g)if(e=a[g],f=e.prefix?e.prefix+":"+c:c,"*"==c||f==e.nodeName)"*"!=
1953 b&&b!=e.namespaceURI||d.push(e)}return d},getAttributeNodeNS:function(a,b,c){var d=null;if(a.getAttributeNodeNS)d=a.getAttributeNodeNS(b,c);else{a=a.attributes;for(var e,f,g=0,h=a.length;g<h;++g)if(e=a[g],e.namespaceURI==b&&(f=e.prefix?e.prefix+":"+c:c,f==e.nodeName)){d=e;break}}return d},getAttributeNS:function(a,b,c){var d="";if(a.getAttributeNS)d=a.getAttributeNS(b,c)||"";else if(a=this.getAttributeNodeNS(a,b,c))d=a.nodeValue;return d},getChildValue:function(a,b){var c=b||"";if(a)for(var d=a.firstChild;d;d=
1954 d.nextSibling)switch(d.nodeType){case 3:case 4:c+=d.nodeValue}return c},isSimpleContent:function(a){var b=!0;for(a=a.firstChild;a;a=a.nextSibling)if(1===a.nodeType){b=!1;break}return b},contentType:function(a){var b=!1,c=!1,d=OpenLayers.Format.XML.CONTENT_TYPE.EMPTY;for(a=a.firstChild;a;a=a.nextSibling){switch(a.nodeType){case 1:c=!0;break;case 8:break;default:b=!0}if(c&&b)break}if(c&&b)d=OpenLayers.Format.XML.CONTENT_TYPE.MIXED;else{if(c)return OpenLayers.Format.XML.CONTENT_TYPE.COMPLEX;if(b)return OpenLayers.Format.XML.CONTENT_TYPE.SIMPLE}return d},
1955 hasAttributeNS:function(a,b,c){var d=!1;return d=a.hasAttributeNS?a.hasAttributeNS(b,c):!!this.getAttributeNodeNS(a,b,c)},setAttributeNS:function(a,b,c,d){if(a.setAttributeNS)a.setAttributeNS(b,c,d);else if(this.xmldom)b?(b=a.ownerDocument.createNode(2,c,b),b.nodeValue=d,a.setAttributeNode(b)):a.setAttribute(c,d);else throw"setAttributeNS not implemented";},createElementNSPlus:function(a,b){b=b||{};var c=b.uri||this.namespaces[b.prefix];c||(c=a.indexOf(":"),c=this.namespaces[a.substring(0,c)]);c||
1956 (c=this.namespaces[this.defaultPrefix]);c=this.createElementNS(c,a);b.attributes&&this.setAttributes(c,b.attributes);var d=b.value;null!=d&&c.appendChild(this.createTextNode(d));return c},setAttributes:function(a,b){var c,d,e;for(e in b)null!=b[e]&&b[e].toString&&(c=b[e].toString(),d=this.namespaces[e.substring(0,e.indexOf(":"))]||null,this.setAttributeNS(a,d,e,c))},readNode:function(a,b){b||(b={});var c=this.readers[a.namespaceURI?this.namespaceAlias[a.namespaceURI]:this.defaultPrefix];if(c){var d=
1957 a.localName||a.nodeName.split(":").pop();(c=c[d]||c["*"])&&c.apply(this,[a,b])}return b},readChildNodes:function(a,b){b||(b={});for(var c=a.childNodes,d,e=0,f=c.length;e<f;++e)d=c[e],1==d.nodeType&&this.readNode(d,b);return b},writeNode:function(a,b,c){var d,e=a.indexOf(":");0<e?(d=a.substring(0,e),a=a.substring(e+1)):d=c?this.namespaceAlias[c.namespaceURI]:this.defaultPrefix;b=this.writers[d][a].apply(this,[b]);c&&c.appendChild(b);return b},getChildEl:function(a,b,c){return a&&this.getThisOrNextEl(a.firstChild,
1958 b,c)},getNextEl:function(a,b,c){return a&&this.getThisOrNextEl(a.nextSibling,b,c)},getThisOrNextEl:function(a,b,c){a:for(;a;a=a.nextSibling)switch(a.nodeType){case 1:if(!(b&&b!==(a.localName||a.nodeName.split(":").pop())||c&&c!==a.namespaceURI))break a;a=null;break a;case 3:if(/^\s*$/.test(a.nodeValue))break;case 4:case 6:case 12:case 10:case 11:a=null;break a}return a||null},lookupNamespaceURI:function(a,b){var c=null;if(a)if(a.lookupNamespaceURI)c=a.lookupNamespaceURI(b);else a:switch(a.nodeType){case 1:if(null!==
1959 a.namespaceURI&&a.prefix===b){c=a.namespaceURI;break a}if(c=a.attributes.length)for(var d,e=0;e<c;++e)if(d=a.attributes[e],"xmlns"===d.prefix&&d.name==="xmlns:"+b){c=d.value||null;break a}else if("xmlns"===d.name&&null===b){c=d.value||null;break a}c=this.lookupNamespaceURI(a.parentNode,b);break a;case 2:c=this.lookupNamespaceURI(a.ownerElement,b);break a;case 9:c=this.lookupNamespaceURI(a.documentElement,b);break a;case 6:case 12:case 10:case 11:break a;default:c=this.lookupNamespaceURI(a.parentNode,
1960 b)}return c},getXMLDoc:function(){OpenLayers.Format.XML.document||this.xmldom||(document.implementation&&document.implementation.createDocument?OpenLayers.Format.XML.document=document.implementation.createDocument("","",null):!this.xmldom&&window.ActiveXObject&&(this.xmldom=new ActiveXObject("Microsoft.XMLDOM")));return OpenLayers.Format.XML.document||this.xmldom},CLASS_NAME:"OpenLayers.Format.XML"});OpenLayers.Format.XML.CONTENT_TYPE={EMPTY:0,SIMPLE:1,COMPLEX:2,MIXED:3};
1961 OpenLayers.Format.XML.lookupNamespaceURI=OpenLayers.Function.bind(OpenLayers.Format.XML.prototype.lookupNamespaceURI,OpenLayers.Format.XML.prototype);OpenLayers.Format.XML.document=null;OpenLayers.Format.WFST=function(a){a=OpenLayers.Util.applyDefaults(a,OpenLayers.Format.WFST.DEFAULTS);var b=OpenLayers.Format.WFST["v"+a.version.replace(/\./g,"_")];if(!b)throw"Unsupported WFST version: "+a.version;return new b(a)};OpenLayers.Format.WFST.DEFAULTS={version:"1.0.0"};OpenLayers.Feature=OpenLayers.Class({layer:null,id:null,lonlat:null,data:null,marker:null,popupClass:null,popup:null,initialize:function(a,b,c){this.layer=a;this.lonlat=b;this.data=null!=c?c:{};this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_")},destroy:function(){null!=this.layer&&null!=this.layer.map&&null!=this.popup&&this.layer.map.removePopup(this.popup);null!=this.layer&&null!=this.marker&&this.layer.removeMarker(this.marker);this.data=this.lonlat=this.id=this.layer=null;null!=this.marker&&
1962 (this.destroyMarker(this.marker),this.marker=null);null!=this.popup&&(this.destroyPopup(this.popup),this.popup=null)},onScreen:function(){var a=!1;null!=this.layer&&null!=this.layer.map&&(a=this.layer.map.getExtent().containsLonLat(this.lonlat));return a},createMarker:function(){null!=this.lonlat&&(this.marker=new OpenLayers.Marker(this.lonlat,this.data.icon));return this.marker},destroyMarker:function(){this.marker.destroy()},createPopup:function(a){null!=this.lonlat&&(this.popup||(this.popup=new (this.popupClass?
1963 this.popupClass:OpenLayers.Popup.Anchored)(this.id+"_popup",this.lonlat,this.data.popupSize,this.data.popupContentHTML,this.marker?this.marker.icon:null,a)),null!=this.data.overflow&&(this.popup.contentDiv.style.overflow=this.data.overflow),this.popup.feature=this);return this.popup},destroyPopup:function(){this.popup&&(this.popup.feature=null,this.popup.destroy(),this.popup=null)},CLASS_NAME:"OpenLayers.Feature"});OpenLayers.State={UNKNOWN:"Unknown",INSERT:"Insert",UPDATE:"Update",DELETE:"Delete"};
1964 OpenLayers.Feature.Vector=OpenLayers.Class(OpenLayers.Feature,{fid:null,geometry:null,attributes:null,bounds:null,state:null,style:null,url:null,renderIntent:"default",modified:null,initialize:function(a,b,c){OpenLayers.Feature.prototype.initialize.apply(this,[null,null,b]);this.lonlat=null;this.geometry=a?a:null;this.state=null;this.attributes={};b&&(this.attributes=OpenLayers.Util.extend(this.attributes,b));this.style=c?c:null},destroy:function(){this.layer&&(this.layer.removeFeatures(this),this.layer=
1965 null);this.modified=this.geometry=null;OpenLayers.Feature.prototype.destroy.apply(this,arguments)},clone:function(){return new OpenLayers.Feature.Vector(this.geometry?this.geometry.clone():null,this.attributes,this.style)},onScreen:function(a){var b=!1;this.layer&&this.layer.map&&(b=this.layer.map.getExtent(),a?(a=this.geometry.getBounds(),b=b.intersectsBounds(a)):b=b.toGeometry().intersects(this.geometry));return b},getVisibility:function(){return!(this.style&&"none"==this.style.display||!this.layer||
1966 this.layer&&this.layer.styleMap&&"none"==this.layer.styleMap.createSymbolizer(this,this.renderIntent).display||this.layer&&!this.layer.getVisibility())},createMarker:function(){return null},destroyMarker:function(){},createPopup:function(){return null},atPoint:function(a,b,c){var d=!1;this.geometry&&(d=this.geometry.atPoint(a,b,c));return d},destroyPopup:function(){},move:function(a){if(this.layer&&this.geometry.move){a="OpenLayers.LonLat"==a.CLASS_NAME?this.layer.getViewPortPxFromLonLat(a):a;var b=
1967 this.layer.getViewPortPxFromLonLat(this.geometry.getBounds().getCenterLonLat()),c=this.layer.map.getResolution();this.geometry.move(c*(a.x-b.x),c*(b.y-a.y));this.layer.drawFeature(this);return b}},toState:function(a){if(a==OpenLayers.State.UPDATE)switch(this.state){case OpenLayers.State.UNKNOWN:case OpenLayers.State.DELETE:this.state=a}else if(a==OpenLayers.State.INSERT)switch(this.state){case OpenLayers.State.UNKNOWN:break;default:this.state=a}else if(a==OpenLayers.State.DELETE)switch(this.state){case OpenLayers.State.UNKNOWN:case OpenLayers.State.UPDATE:this.state=
1968 a}else a==OpenLayers.State.UNKNOWN&&(this.state=a)},CLASS_NAME:"OpenLayers.Feature.Vector"});
1969 OpenLayers.Feature.Vector.style={"default":{fillColor:"#ee9900",fillOpacity:0.4,hoverFillColor:"white",hoverFillOpacity:0.8,strokeColor:"#ee9900",strokeOpacity:1,strokeWidth:1,strokeLinecap:"round",strokeDashstyle:"solid",hoverStrokeColor:"red",hoverStrokeOpacity:1,hoverStrokeWidth:0.2,pointRadius:6,hoverPointRadius:1,hoverPointUnit:"%",pointerEvents:"visiblePainted",cursor:"inherit",fontColor:"#000000",labelAlign:"cm",labelOutlineColor:"white",labelOutlineWidth:3},select:{fillColor:"blue",fillOpacity:0.4,
1970 hoverFillColor:"white",hoverFillOpacity:0.8,strokeColor:"blue",strokeOpacity:1,strokeWidth:2,strokeLinecap:"round",strokeDashstyle:"solid",hoverStrokeColor:"red",hoverStrokeOpacity:1,hoverStrokeWidth:0.2,pointRadius:6,hoverPointRadius:1,hoverPointUnit:"%",pointerEvents:"visiblePainted",cursor:"pointer",fontColor:"#000000",labelAlign:"cm",labelOutlineColor:"white",labelOutlineWidth:3},temporary:{fillColor:"#66cccc",fillOpacity:0.2,hoverFillColor:"white",hoverFillOpacity:0.8,strokeColor:"#66cccc",strokeOpacity:1,
1971 strokeLinecap:"round",strokeWidth:2,strokeDashstyle:"solid",hoverStrokeColor:"red",hoverStrokeOpacity:1,hoverStrokeWidth:0.2,pointRadius:6,hoverPointRadius:1,hoverPointUnit:"%",pointerEvents:"visiblePainted",cursor:"inherit",fontColor:"#000000",labelAlign:"cm",labelOutlineColor:"white",labelOutlineWidth:3},"delete":{display:"none"}};OpenLayers.Style=OpenLayers.Class({id:null,name:null,title:null,description:null,layerName:null,isDefault:!1,rules:null,context:null,defaultStyle:null,defaultsPerSymbolizer:!1,propertyStyles:null,initialize:function(a,b){OpenLayers.Util.extend(this,b);this.rules=[];b&&b.rules&&this.addRules(b.rules);this.setDefaultStyle(a||OpenLayers.Feature.Vector.style["default"]);this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_")},destroy:function(){for(var a=0,b=this.rules.length;a<b;a++)this.rules[a].destroy(),
1972 this.rules[a]=null;this.defaultStyle=this.rules=null},createSymbolizer:function(a){for(var b=this.defaultsPerSymbolizer?{}:this.createLiterals(OpenLayers.Util.extend({},this.defaultStyle),a),c=this.rules,d,e=[],f=!1,g=0,h=c.length;g<h;g++)d=c[g],d.evaluate(a)&&(d instanceof OpenLayers.Rule&&d.elseFilter?e.push(d):(f=!0,this.applySymbolizer(d,b,a)));if(!1==f&&0<e.length)for(f=!0,g=0,h=e.length;g<h;g++)this.applySymbolizer(e[g],b,a);0<c.length&&!1==f&&(b.display="none");null!=b.label&&"string"!==typeof b.label&&
1973 (b.label=String(b.label));return b},applySymbolizer:function(a,b,c){var d=c.geometry?this.getSymbolizerPrefix(c.geometry):OpenLayers.Style.SYMBOLIZER_PREFIXES[0];a=a.symbolizer[d]||a.symbolizer;!0===this.defaultsPerSymbolizer&&(d=this.defaultStyle,OpenLayers.Util.applyDefaults(a,{pointRadius:d.pointRadius}),!0!==a.stroke&&!0!==a.graphic||OpenLayers.Util.applyDefaults(a,{strokeWidth:d.strokeWidth,strokeColor:d.strokeColor,strokeOpacity:d.strokeOpacity,strokeDashstyle:d.strokeDashstyle,strokeLinecap:d.strokeLinecap}),
1974 !0!==a.fill&&!0!==a.graphic||OpenLayers.Util.applyDefaults(a,{fillColor:d.fillColor,fillOpacity:d.fillOpacity}),!0===a.graphic&&OpenLayers.Util.applyDefaults(a,{pointRadius:this.defaultStyle.pointRadius,externalGraphic:this.defaultStyle.externalGraphic,graphicName:this.defaultStyle.graphicName,graphicOpacity:this.defaultStyle.graphicOpacity,graphicWidth:this.defaultStyle.graphicWidth,graphicHeight:this.defaultStyle.graphicHeight,graphicXOffset:this.defaultStyle.graphicXOffset,graphicYOffset:this.defaultStyle.graphicYOffset}));
1975 return this.createLiterals(OpenLayers.Util.extend(b,a),c)},createLiterals:function(a,b){var c=OpenLayers.Util.extend({},b.attributes||b.data);OpenLayers.Util.extend(c,this.context);for(var d in this.propertyStyles)a[d]=OpenLayers.Style.createLiteral(a[d],c,b,d);return a},findPropertyStyles:function(){var a={};this.addPropertyStyles(a,this.defaultStyle);for(var b=this.rules,c,d,e=0,f=b.length;e<f;e++){c=b[e].symbolizer;for(var g in c)if(d=c[g],"object"==typeof d)this.addPropertyStyles(a,d);else{this.addPropertyStyles(a,
1976 c);break}}return a},addPropertyStyles:function(a,b){var c,d;for(d in b)c=b[d],"string"==typeof c&&c.match(/\$\{\w+\}/)&&(a[d]=!0);return a},addRules:function(a){Array.prototype.push.apply(this.rules,a);this.propertyStyles=this.findPropertyStyles()},setDefaultStyle:function(a){this.defaultStyle=a;this.propertyStyles=this.findPropertyStyles()},getSymbolizerPrefix:function(a){for(var b=OpenLayers.Style.SYMBOLIZER_PREFIXES,c=0,d=b.length;c<d;c++)if(-1!=a.CLASS_NAME.indexOf(b[c]))return b[c]},clone:function(){var a=
1977 OpenLayers.Util.extend({},this);if(this.rules){a.rules=[];for(var b=0,c=this.rules.length;b<c;++b)a.rules.push(this.rules[b].clone())}a.context=this.context&&OpenLayers.Util.extend({},this.context);b=OpenLayers.Util.extend({},this.defaultStyle);return new OpenLayers.Style(b,a)},CLASS_NAME:"OpenLayers.Style"});OpenLayers.Style.createLiteral=function(a,b,c,d){"string"==typeof a&&-1!=a.indexOf("${")&&(a=OpenLayers.String.format(a,b,[c,d]),a=isNaN(a)||!a?a:parseFloat(a));return a};
1978 OpenLayers.Style.SYMBOLIZER_PREFIXES=["Point","Line","Polygon","Text","Raster"];OpenLayers.Filter=OpenLayers.Class({initialize:function(a){OpenLayers.Util.extend(this,a)},destroy:function(){},evaluate:function(a){return!0},clone:function(){return null},toString:function(){return OpenLayers.Format&&OpenLayers.Format.CQL?OpenLayers.Format.CQL.prototype.write(this):Object.prototype.toString.call(this)},CLASS_NAME:"OpenLayers.Filter"});OpenLayers.Filter.Spatial=OpenLayers.Class(OpenLayers.Filter,{type:null,property:null,value:null,distance:null,distanceUnits:null,evaluate:function(a){var b=!1;switch(this.type){case OpenLayers.Filter.Spatial.BBOX:case OpenLayers.Filter.Spatial.INTERSECTS:if(a.geometry){var c=this.value;"OpenLayers.Bounds"==this.value.CLASS_NAME&&(c=this.value.toGeometry());a.geometry.intersects(c)&&(b=!0)}break;default:throw Error("evaluate is not implemented for this filter type.");}return b},clone:function(){var a=
1979 OpenLayers.Util.applyDefaults({value:this.value&&this.value.clone&&this.value.clone()},this);return new OpenLayers.Filter.Spatial(a)},CLASS_NAME:"OpenLayers.Filter.Spatial"});OpenLayers.Filter.Spatial.BBOX="BBOX";OpenLayers.Filter.Spatial.INTERSECTS="INTERSECTS";OpenLayers.Filter.Spatial.DWITHIN="DWITHIN";OpenLayers.Filter.Spatial.WITHIN="WITHIN";OpenLayers.Filter.Spatial.CONTAINS="CONTAINS";OpenLayers.Filter.FeatureId=OpenLayers.Class(OpenLayers.Filter,{fids:null,type:"FID",initialize:function(a){this.fids=[];OpenLayers.Filter.prototype.initialize.apply(this,[a])},evaluate:function(a){for(var b=0,c=this.fids.length;b<c;b++)if((a.fid||a.id)==this.fids[b])return!0;return!1},clone:function(){var a=new OpenLayers.Filter.FeatureId;OpenLayers.Util.extend(a,this);a.fids=this.fids.slice();return a},CLASS_NAME:"OpenLayers.Filter.FeatureId"});OpenLayers.Format.WFST.v1=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance",wfs:"http://www.opengis.net/wfs",gml:"http://www.opengis.net/gml",ogc:"http://www.opengis.net/ogc",ows:"http://www.opengis.net/ows"},defaultPrefix:"wfs",version:null,schemaLocations:null,srsName:null,extractAttributes:!0,xy:!0,stateName:null,initialize:function(a){this.stateName={};this.stateName[OpenLayers.State.INSERT]="wfs:Insert";this.stateName[OpenLayers.State.UPDATE]=
1980 "wfs:Update";this.stateName[OpenLayers.State.DELETE]="wfs:Delete";OpenLayers.Format.XML.prototype.initialize.apply(this,[a])},getSrsName:function(a,b){var c=b&&b.srsName;c||(c=a&&a.layer?a.layer.projection.getCode():this.srsName);return c},read:function(a,b){b=b||{};OpenLayers.Util.applyDefaults(b,{output:"features"});"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));a&&9==a.nodeType&&(a=a.documentElement);var c={};a&&this.readNode(a,c,!0);c.features&&"features"===b.output&&
1981 (c=c.features);return c},readers:{wfs:{FeatureCollection:function(a,b){b.features=[];this.readChildNodes(a,b)}}},write:function(a,b){var c=this.writeNode("wfs:Transaction",{features:a,options:b}),d=this.schemaLocationAttr();d&&this.setAttributeNS(c,this.namespaces.xsi,"xsi:schemaLocation",d);return OpenLayers.Format.XML.prototype.write.apply(this,[c])},writers:{wfs:{GetFeature:function(a){var b=this.createElementNSPlus("wfs:GetFeature",{attributes:{service:"WFS",version:this.version,handle:a&&a.handle,
1982 outputFormat:a&&a.outputFormat,maxFeatures:a&&a.maxFeatures,"xsi:schemaLocation":this.schemaLocationAttr(a)}});if("string"==typeof this.featureType)this.writeNode("Query",a,b);else for(var c=0,d=this.featureType.length;c<d;c++)a.featureType=this.featureType[c],this.writeNode("Query",a,b);return b},Transaction:function(a){a=a||{};var b=a.options||{},c=this.createElementNSPlus("wfs:Transaction",{attributes:{service:"WFS",version:this.version,handle:b.handle}}),d,e=a.features;if(e){!0===b.multi&&OpenLayers.Util.extend(this.geometryTypes,
1983 {"OpenLayers.Geometry.Point":"MultiPoint","OpenLayers.Geometry.LineString":!0===this.multiCurve?"MultiCurve":"MultiLineString","OpenLayers.Geometry.Polygon":!0===this.multiSurface?"MultiSurface":"MultiPolygon"});var f,g;a=0;for(d=e.length;a<d;++a)g=e[a],(f=this.stateName[g.state])&&this.writeNode(f,{feature:g,options:b},c);!0===b.multi&&this.setGeometryTypes()}if(b.nativeElements)for(a=0,d=b.nativeElements.length;a<d;++a)this.writeNode("wfs:Native",b.nativeElements[a],c);return c},Native:function(a){return this.createElementNSPlus("wfs:Native",
1984 {attributes:{vendorId:a.vendorId,safeToIgnore:a.safeToIgnore},value:a.value})},Insert:function(a){var b=a.feature;a=a.options;a=this.createElementNSPlus("wfs:Insert",{attributes:{handle:a&&a.handle}});this.srsName=this.getSrsName(b);this.writeNode("feature:_typeName",b,a);return a},Update:function(a){var b=a.feature;a=a.options;a=this.createElementNSPlus("wfs:Update",{attributes:{handle:a&&a.handle,typeName:(this.featureNS?this.featurePrefix+":":"")+this.featureType}});this.featureNS&&a.setAttribute("xmlns:"+
1985 this.featurePrefix,this.featureNS);var c=b.modified;null===this.geometryName||c&&void 0===c.geometry||(this.srsName=this.getSrsName(b),this.writeNode("Property",{name:this.geometryName,value:b.geometry},a));for(var d in b.attributes)void 0===b.attributes[d]||c&&c.attributes&&(!c.attributes||void 0===c.attributes[d])||this.writeNode("Property",{name:d,value:b.attributes[d]},a);this.writeNode("ogc:Filter",new OpenLayers.Filter.FeatureId({fids:[b.fid]}),a);return a},Property:function(a){var b=this.createElementNSPlus("wfs:Property");
1986 this.writeNode("Name",a.name,b);null!==a.value&&this.writeNode("Value",a.value,b);return b},Name:function(a){return this.createElementNSPlus("wfs:Name",{value:a})},Value:function(a){var b;a instanceof OpenLayers.Geometry?(b=this.createElementNSPlus("wfs:Value"),a=this.writeNode("feature:_geometry",a).firstChild,b.appendChild(a)):b=this.createElementNSPlus("wfs:Value",{value:a});return b},Delete:function(a){var b=a.feature;a=a.options;a=this.createElementNSPlus("wfs:Delete",{attributes:{handle:a&&
1987 a.handle,typeName:(this.featureNS?this.featurePrefix+":":"")+this.featureType}});this.featureNS&&a.setAttribute("xmlns:"+this.featurePrefix,this.featureNS);this.writeNode("ogc:Filter",new OpenLayers.Filter.FeatureId({fids:[b.fid]}),a);return a}}},schemaLocationAttr:function(a){a=OpenLayers.Util.extend({featurePrefix:this.featurePrefix,schema:this.schema},a);var b=OpenLayers.Util.extend({},this.schemaLocations);a.schema&&(b[a.featurePrefix]=a.schema);a=[];var c,d;for(d in b)(c=this.namespaces[d])&&
1988 a.push(c+" "+b[d]);return a.join(" ")||void 0},setFilterProperty:function(a){if(a.filters)for(var b=0,c=a.filters.length;b<c;++b)OpenLayers.Format.WFST.v1.prototype.setFilterProperty.call(this,a.filters[b]);else a instanceof OpenLayers.Filter.Spatial&&!a.property&&(a.property=this.geometryName)},CLASS_NAME:"OpenLayers.Format.WFST.v1"});OpenLayers.Format.OGCExceptionReport=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{ogc:"http://www.opengis.net/ogc"},regExes:{trimSpace:/^\s*|\s*$/g,removeSpace:/\s*/g,splitSpace:/\s+/,trimComma:/\s*,\s*/g},defaultPrefix:"ogc",read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));var b={exceptionReport:null};a.documentElement&&(this.readChildNodes(a,b),null===b.exceptionReport&&(b=(new OpenLayers.Format.OWSCommon).read(a)));return b},readers:{ogc:{ServiceExceptionReport:function(a,
1989 b){b.exceptionReport={exceptions:[]};this.readChildNodes(a,b.exceptionReport)},ServiceException:function(a,b){var c={code:a.getAttribute("code"),locator:a.getAttribute("locator"),text:this.getChildValue(a)};b.exceptions.push(c)}}},CLASS_NAME:"OpenLayers.Format.OGCExceptionReport"});OpenLayers.Format.XML.VersionedOGC=OpenLayers.Class(OpenLayers.Format.XML,{defaultVersion:null,version:null,profile:null,allowFallback:!1,name:null,stringifyOutput:!1,parser:null,initialize:function(a){OpenLayers.Format.XML.prototype.initialize.apply(this,[a]);a=this.CLASS_NAME;this.name=a.substring(a.lastIndexOf(".")+1)},getVersion:function(a,b){var c;a?(c=this.version,c||(c=a.getAttribute("version"),c||(c=this.defaultVersion))):c=b&&b.version||this.version||this.defaultVersion;return c},getParser:function(a){a=
1990 a||this.defaultVersion;var b=this.profile?"_"+this.profile:"";if(!this.parser||this.parser.VERSION!=a){var c=OpenLayers.Format[this.name]["v"+a.replace(/\./g,"_")+b];if(!c&&(""!==b&&this.allowFallback&&(b="",c=OpenLayers.Format[this.name]["v"+a.replace(/\./g,"_")]),!c))throw"Can't find a "+this.name+" parser for version "+a+b;this.parser=new c(this.options)}return this.parser},write:function(a,b){var c=this.getVersion(null,b);this.parser=this.getParser(c);c=this.parser.write(a,b);return!1===this.stringifyOutput?
1991 c:OpenLayers.Format.XML.prototype.write.apply(this,[c])},read:function(a,b){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));var c=this.getVersion(a.documentElement);this.parser=this.getParser(c);var d=this.parser.read(a,b),e=this.parser.errorProperty||null;null!==e&&void 0===d[e]&&(e=new OpenLayers.Format.OGCExceptionReport,d.error=e.read(a));d.version=c;return d},CLASS_NAME:"OpenLayers.Format.XML.VersionedOGC"});OpenLayers.Filter.Logical=OpenLayers.Class(OpenLayers.Filter,{filters:null,type:null,initialize:function(a){this.filters=[];OpenLayers.Filter.prototype.initialize.apply(this,[a])},destroy:function(){this.filters=null;OpenLayers.Filter.prototype.destroy.apply(this)},evaluate:function(a){var b,c;switch(this.type){case OpenLayers.Filter.Logical.AND:b=0;for(c=this.filters.length;b<c;b++)if(!1==this.filters[b].evaluate(a))return!1;return!0;case OpenLayers.Filter.Logical.OR:b=0;for(c=this.filters.length;b<
1992 c;b++)if(!0==this.filters[b].evaluate(a))return!0;return!1;case OpenLayers.Filter.Logical.NOT:return!this.filters[0].evaluate(a)}},clone:function(){for(var a=[],b=0,c=this.filters.length;b<c;++b)a.push(this.filters[b].clone());return new OpenLayers.Filter.Logical({type:this.type,filters:a})},CLASS_NAME:"OpenLayers.Filter.Logical"});OpenLayers.Filter.Logical.AND="&&";OpenLayers.Filter.Logical.OR="||";OpenLayers.Filter.Logical.NOT="!";OpenLayers.Filter.Comparison=OpenLayers.Class(OpenLayers.Filter,{type:null,property:null,value:null,matchCase:!0,lowerBoundary:null,upperBoundary:null,initialize:function(a){OpenLayers.Filter.prototype.initialize.apply(this,[a]);this.type===OpenLayers.Filter.Comparison.LIKE&&void 0===a.matchCase&&(this.matchCase=null)},evaluate:function(a){a instanceof OpenLayers.Feature.Vector&&(a=a.attributes);var b=!1;a=a[this.property];switch(this.type){case OpenLayers.Filter.Comparison.EQUAL_TO:b=this.value;
1993 b=this.matchCase||"string"!=typeof a||"string"!=typeof b?a==b:a.toUpperCase()==b.toUpperCase();break;case OpenLayers.Filter.Comparison.NOT_EQUAL_TO:b=this.value;b=this.matchCase||"string"!=typeof a||"string"!=typeof b?a!=b:a.toUpperCase()!=b.toUpperCase();break;case OpenLayers.Filter.Comparison.LESS_THAN:b=a<this.value;break;case OpenLayers.Filter.Comparison.GREATER_THAN:b=a>this.value;break;case OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO:b=a<=this.value;break;case OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO:b=
1994 a>=this.value;break;case OpenLayers.Filter.Comparison.BETWEEN:b=a>=this.lowerBoundary&&a<=this.upperBoundary;break;case OpenLayers.Filter.Comparison.LIKE:b=RegExp(this.value,"gi").test(a);break;case OpenLayers.Filter.Comparison.IS_NULL:b=null===a}return b},value2regex:function(a,b,c){if("."==a)throw Error("'.' is an unsupported wildCard character for OpenLayers.Filter.Comparison");a=a?a:"*";b=b?b:".";this.value=this.value.replace(RegExp("\\"+(c?c:"!")+"(.|$)","g"),"\\$1");this.value=this.value.replace(RegExp("\\"+
1995 b,"g"),".");this.value=this.value.replace(RegExp("\\"+a,"g"),".*");this.value=this.value.replace(RegExp("\\\\.\\*","g"),"\\"+a);return this.value=this.value.replace(RegExp("\\\\\\.","g"),"\\"+b)},regex2value:function(){var a=this.value,a=a.replace(/!/g,"!!"),a=a.replace(/(\\)?\\\./g,function(a,c){return c?a:"!."}),a=a.replace(/(\\)?\\\*/g,function(a,c){return c?a:"!*"}),a=a.replace(/\\\\/g,"\\");return a=a.replace(/\.\*/g,"*")},clone:function(){return OpenLayers.Util.extend(new OpenLayers.Filter.Comparison,
1996 this)},CLASS_NAME:"OpenLayers.Filter.Comparison"});OpenLayers.Filter.Comparison.EQUAL_TO="==";OpenLayers.Filter.Comparison.NOT_EQUAL_TO="!=";OpenLayers.Filter.Comparison.LESS_THAN="<";OpenLayers.Filter.Comparison.GREATER_THAN=">";OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO="<=";OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO=">=";OpenLayers.Filter.Comparison.BETWEEN="..";OpenLayers.Filter.Comparison.LIKE="~";OpenLayers.Filter.Comparison.IS_NULL="NULL";OpenLayers.Format.Filter=OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC,{defaultVersion:"1.0.0",CLASS_NAME:"OpenLayers.Format.Filter"});OpenLayers.Filter.Function=OpenLayers.Class(OpenLayers.Filter,{name:null,params:null,CLASS_NAME:"OpenLayers.Filter.Function"});OpenLayers.Date={dateRegEx:/^(?:(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?)?(?:(?:T(\d{1,2}):(\d{2}):(\d{2}(?:\.\d+)?)(Z|(?:[+-]\d{1,2}(?::(\d{2}))?)))|Z)?$/,toISOString:function(){return"toISOString"in Date.prototype?function(a){return a.toISOString()}:function(a){return isNaN(a.getTime())?"Invalid Date":a.getUTCFullYear()+"-"+OpenLayers.Number.zeroPad(a.getUTCMonth()+1,2)+"-"+OpenLayers.Number.zeroPad(a.getUTCDate(),2)+"T"+OpenLayers.Number.zeroPad(a.getUTCHours(),2)+":"+OpenLayers.Number.zeroPad(a.getUTCMinutes(),
1997 2)+":"+OpenLayers.Number.zeroPad(a.getUTCSeconds(),2)+"."+OpenLayers.Number.zeroPad(a.getUTCMilliseconds(),3)+"Z"}}(),parse:function(a){var b;if((a=a.match(this.dateRegEx))&&(a[1]||a[7])){b=parseInt(a[1],10)||0;var c=parseInt(a[2],10)-1||0,d=parseInt(a[3],10)||1;b=new Date(Date.UTC(b,c,d));if(c=a[7]){var d=parseInt(a[4],10),e=parseInt(a[5],10),f=parseFloat(a[6]),g=f|0,f=Math.round(1E3*(f-g));b.setUTCHours(d,e,g,f);"Z"!==c&&(c=parseInt(c,10),a=parseInt(a[8],10)||0,a=-1E3*(60*60*c+60*a),b=new Date(b.getTime()+
1998 a))}}else b=new Date("invalid");return b}};OpenLayers.Format.Filter.v1=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{ogc:"http://www.opengis.net/ogc",gml:"http://www.opengis.net/gml",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance"},defaultPrefix:"ogc",schemaLocation:null,initialize:function(a){OpenLayers.Format.XML.prototype.initialize.apply(this,[a])},read:function(a){var b={};this.readers.ogc.Filter.apply(this,[a,b]);return b.filter},readers:{ogc:{_expression:function(a){for(var b="",c=a.firstChild;c;c=
1999 c.nextSibling)switch(c.nodeType){case 1:a=this.readNode(c);a.property?b+="${"+a.property+"}":void 0!==a.value&&(b+=a.value);break;case 3:case 4:b+=c.nodeValue}return b},Filter:function(a,b){var c={fids:[],filters:[]};this.readChildNodes(a,c);0<c.fids.length?b.filter=new OpenLayers.Filter.FeatureId({fids:c.fids}):0<c.filters.length&&(b.filter=c.filters[0])},FeatureId:function(a,b){var c=a.getAttribute("fid");c&&b.fids.push(c)},And:function(a,b){var c=new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.AND});
2000 this.readChildNodes(a,c);b.filters.push(c)},Or:function(a,b){var c=new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.OR});this.readChildNodes(a,c);b.filters.push(c)},Not:function(a,b){var c=new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.NOT});this.readChildNodes(a,c);b.filters.push(c)},PropertyIsLessThan:function(a,b){var c=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.LESS_THAN});this.readChildNodes(a,c);b.filters.push(c)},PropertyIsGreaterThan:function(a,
2001 b){var c=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.GREATER_THAN});this.readChildNodes(a,c);b.filters.push(c)},PropertyIsLessThanOrEqualTo:function(a,b){var c=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO});this.readChildNodes(a,c);b.filters.push(c)},PropertyIsGreaterThanOrEqualTo:function(a,b){var c=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO});this.readChildNodes(a,c);b.filters.push(c)},
2002 PropertyIsBetween:function(a,b){var c=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.BETWEEN});this.readChildNodes(a,c);b.filters.push(c)},Literal:function(a,b){b.value=OpenLayers.String.numericIf(this.getChildValue(a),!0)},PropertyName:function(a,b){b.property=this.getChildValue(a)},LowerBoundary:function(a,b){b.lowerBoundary=OpenLayers.String.numericIf(this.readers.ogc._expression.call(this,a),!0)},UpperBoundary:function(a,b){b.upperBoundary=OpenLayers.String.numericIf(this.readers.ogc._expression.call(this,
2003 a),!0)},Intersects:function(a,b){this.readSpatial(a,b,OpenLayers.Filter.Spatial.INTERSECTS)},Within:function(a,b){this.readSpatial(a,b,OpenLayers.Filter.Spatial.WITHIN)},Contains:function(a,b){this.readSpatial(a,b,OpenLayers.Filter.Spatial.CONTAINS)},DWithin:function(a,b){this.readSpatial(a,b,OpenLayers.Filter.Spatial.DWITHIN)},Distance:function(a,b){b.distance=parseInt(this.getChildValue(a));b.distanceUnits=a.getAttribute("units")},Function:function(a,b){},PropertyIsNull:function(a,b){var c=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.IS_NULL});
2004 this.readChildNodes(a,c);b.filters.push(c)}}},readSpatial:function(a,b,c){c=new OpenLayers.Filter.Spatial({type:c});this.readChildNodes(a,c);c.value=c.components[0];delete c.components;b.filters.push(c)},encodeLiteral:function(a){a instanceof Date&&(a=OpenLayers.Date.toISOString(a));return a},writeOgcExpression:function(a,b){a instanceof OpenLayers.Filter.Function?this.writeNode("Function",a,b):this.writeNode("Literal",a,b);return b},write:function(a){return this.writers.ogc.Filter.apply(this,[a])},
2005 writers:{ogc:{Filter:function(a){var b=this.createElementNSPlus("ogc:Filter");this.writeNode(this.getFilterType(a),a,b);return b},_featureIds:function(a){for(var b=this.createDocumentFragment(),c=0,d=a.fids.length;c<d;++c)this.writeNode("ogc:FeatureId",a.fids[c],b);return b},FeatureId:function(a){return this.createElementNSPlus("ogc:FeatureId",{attributes:{fid:a}})},And:function(a){for(var b=this.createElementNSPlus("ogc:And"),c,d=0,e=a.filters.length;d<e;++d)c=a.filters[d],this.writeNode(this.getFilterType(c),
2006 c,b);return b},Or:function(a){for(var b=this.createElementNSPlus("ogc:Or"),c,d=0,e=a.filters.length;d<e;++d)c=a.filters[d],this.writeNode(this.getFilterType(c),c,b);return b},Not:function(a){var b=this.createElementNSPlus("ogc:Not");a=a.filters[0];this.writeNode(this.getFilterType(a),a,b);return b},PropertyIsLessThan:function(a){var b=this.createElementNSPlus("ogc:PropertyIsLessThan");this.writeNode("PropertyName",a,b);this.writeOgcExpression(a.value,b);return b},PropertyIsGreaterThan:function(a){var b=
2007 this.createElementNSPlus("ogc:PropertyIsGreaterThan");this.writeNode("PropertyName",a,b);this.writeOgcExpression(a.value,b);return b},PropertyIsLessThanOrEqualTo:function(a){var b=this.createElementNSPlus("ogc:PropertyIsLessThanOrEqualTo");this.writeNode("PropertyName",a,b);this.writeOgcExpression(a.value,b);return b},PropertyIsGreaterThanOrEqualTo:function(a){var b=this.createElementNSPlus("ogc:PropertyIsGreaterThanOrEqualTo");this.writeNode("PropertyName",a,b);this.writeOgcExpression(a.value,b);
2008 return b},PropertyIsBetween:function(a){var b=this.createElementNSPlus("ogc:PropertyIsBetween");this.writeNode("PropertyName",a,b);this.writeNode("LowerBoundary",a,b);this.writeNode("UpperBoundary",a,b);return b},PropertyName:function(a){return this.createElementNSPlus("ogc:PropertyName",{value:a.property})},Literal:function(a){return this.createElementNSPlus("ogc:Literal",{value:(this.encodeLiteral||OpenLayers.Format.Filter.v1.prototype.encodeLiteral)(a)})},LowerBoundary:function(a){var b=this.createElementNSPlus("ogc:LowerBoundary");
2009 this.writeOgcExpression(a.lowerBoundary,b);return b},UpperBoundary:function(a){var b=this.createElementNSPlus("ogc:UpperBoundary");this.writeNode("Literal",a.upperBoundary,b);return b},INTERSECTS:function(a){return this.writeSpatial(a,"Intersects")},WITHIN:function(a){return this.writeSpatial(a,"Within")},CONTAINS:function(a){return this.writeSpatial(a,"Contains")},DWITHIN:function(a){var b=this.writeSpatial(a,"DWithin");this.writeNode("Distance",a,b);return b},Distance:function(a){return this.createElementNSPlus("ogc:Distance",
2010 {attributes:{units:a.distanceUnits},value:a.distance})},Function:function(a){var b=this.createElementNSPlus("ogc:Function",{attributes:{name:a.name}});a=a.params;for(var c=0,d=a.length;c<d;c++)this.writeOgcExpression(a[c],b);return b},PropertyIsNull:function(a){var b=this.createElementNSPlus("ogc:PropertyIsNull");this.writeNode("PropertyName",a,b);return b}}},getFilterType:function(a){var b=this.filterMap[a.type];if(!b)throw"Filter writing not supported for rule type: "+a.type;return b},filterMap:{"&&":"And",
2011 "||":"Or","!":"Not","==":"PropertyIsEqualTo","!=":"PropertyIsNotEqualTo","<":"PropertyIsLessThan",">":"PropertyIsGreaterThan","<=":"PropertyIsLessThanOrEqualTo",">=":"PropertyIsGreaterThanOrEqualTo","..":"PropertyIsBetween","~":"PropertyIsLike",NULL:"PropertyIsNull",BBOX:"BBOX",DWITHIN:"DWITHIN",WITHIN:"WITHIN",CONTAINS:"CONTAINS",INTERSECTS:"INTERSECTS",FID:"_featureIds"},CLASS_NAME:"OpenLayers.Format.Filter.v1"});OpenLayers.Geometry=OpenLayers.Class({id:null,parent:null,bounds:null,initialize:function(){this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_")},destroy:function(){this.bounds=this.id=null},clone:function(){return new OpenLayers.Geometry},setBounds:function(a){a&&(this.bounds=a.clone())},clearBounds:function(){this.bounds=null;this.parent&&this.parent.clearBounds()},extendBounds:function(a){this.getBounds()?this.bounds.extend(a):this.setBounds(a)},getBounds:function(){null==this.bounds&&this.calculateBounds();
2012 return this.bounds},calculateBounds:function(){},distanceTo:function(a,b){},getVertices:function(a){},atPoint:function(a,b,c){var d=!1;null!=this.getBounds()&&null!=a&&(b=null!=b?b:0,c=null!=c?c:0,d=(new OpenLayers.Bounds(this.bounds.left-b,this.bounds.bottom-c,this.bounds.right+b,this.bounds.top+c)).containsLonLat(a));return d},getLength:function(){return 0},getArea:function(){return 0},getCentroid:function(){return null},toString:function(){return OpenLayers.Format&&OpenLayers.Format.WKT?OpenLayers.Format.WKT.prototype.write(new OpenLayers.Feature.Vector(this)):
2013 Object.prototype.toString.call(this)},CLASS_NAME:"OpenLayers.Geometry"});OpenLayers.Geometry.fromWKT=function(a){var b;if(OpenLayers.Format&&OpenLayers.Format.WKT){var c=OpenLayers.Geometry.fromWKT.format;c||(c=new OpenLayers.Format.WKT,OpenLayers.Geometry.fromWKT.format=c);a=c.read(a);if(a instanceof OpenLayers.Feature.Vector)b=a.geometry;else if(OpenLayers.Util.isArray(a)){b=a.length;for(var c=Array(b),d=0;d<b;++d)c[d]=a[d].geometry;b=new OpenLayers.Geometry.Collection(c)}}return b};
2014 OpenLayers.Geometry.segmentsIntersect=function(a,b,c){var d=c&&c.point;c=c&&c.tolerance;var e=!1,f=a.x1-b.x1,g=a.y1-b.y1,h=a.x2-a.x1,k=a.y2-a.y1,l=b.y2-b.y1,m=b.x2-b.x1,n=l*h-m*k,l=m*g-l*f,g=h*g-k*f;0==n?0==l&&0==g&&(e=!0):(f=l/n,n=g/n,0<=f&&(1>=f&&0<=n&&1>=n)&&(d?(h=a.x1+f*h,n=a.y1+f*k,e=new OpenLayers.Geometry.Point(h,n)):e=!0));if(c)if(e){if(d)a:for(a=[a,b],b=0;2>b;++b)for(f=a[b],k=1;3>k;++k)if(h=f["x"+k],n=f["y"+k],d=Math.sqrt(Math.pow(h-e.x,2)+Math.pow(n-e.y,2)),d<c){e.x=h;e.y=n;break a}}else a:for(a=
2015 [a,b],b=0;2>b;++b)for(h=a[b],n=a[(b+1)%2],k=1;3>k;++k)if(f={x:h["x"+k],y:h["y"+k]},g=OpenLayers.Geometry.distanceToSegment(f,n),g.distance<c){e=d?new OpenLayers.Geometry.Point(f.x,f.y):!0;break a}return e};OpenLayers.Geometry.distanceToSegment=function(a,b){var c=OpenLayers.Geometry.distanceSquaredToSegment(a,b);c.distance=Math.sqrt(c.distance);return c};
2016 OpenLayers.Geometry.distanceSquaredToSegment=function(a,b){var c=a.x,d=a.y,e=b.x1,f=b.y1,g=b.x2,h=b.y2,k=g-e,l=h-f,m=(k*(c-e)+l*(d-f))/(Math.pow(k,2)+Math.pow(l,2));0>=m||(1<=m?(e=g,f=h):(e+=m*k,f+=m*l));return{distance:Math.pow(e-c,2)+Math.pow(f-d,2),x:e,y:f,along:m}};OpenLayers.Geometry.Point=OpenLayers.Class(OpenLayers.Geometry,{x:null,y:null,initialize:function(a,b){OpenLayers.Geometry.prototype.initialize.apply(this,arguments);this.x=parseFloat(a);this.y=parseFloat(b)},clone:function(a){null==a&&(a=new OpenLayers.Geometry.Point(this.x,this.y));OpenLayers.Util.applyDefaults(a,this);return a},calculateBounds:function(){this.bounds=new OpenLayers.Bounds(this.x,this.y,this.x,this.y)},distanceTo:function(a,b){var c=!(b&&!1===b.edge)&&b&&b.details,d,e,f,g,h;a instanceof
2017 OpenLayers.Geometry.Point?(e=this.x,f=this.y,g=a.x,h=a.y,d=Math.sqrt(Math.pow(e-g,2)+Math.pow(f-h,2)),d=c?{x0:e,y0:f,x1:g,y1:h,distance:d}:d):(d=a.distanceTo(this,b),c&&(d={x0:d.x1,y0:d.y1,x1:d.x0,y1:d.y0,distance:d.distance}));return d},equals:function(a){var b=!1;null!=a&&(b=this.x==a.x&&this.y==a.y||isNaN(this.x)&&isNaN(this.y)&&isNaN(a.x)&&isNaN(a.y));return b},toShortString:function(){return this.x+", "+this.y},move:function(a,b){this.x+=a;this.y+=b;this.clearBounds()},rotate:function(a,b){a*=
2018 Math.PI/180;var c=this.distanceTo(b),d=a+Math.atan2(this.y-b.y,this.x-b.x);this.x=b.x+c*Math.cos(d);this.y=b.y+c*Math.sin(d);this.clearBounds()},getCentroid:function(){return new OpenLayers.Geometry.Point(this.x,this.y)},resize:function(a,b,c){this.x=b.x+a*(void 0==c?1:c)*(this.x-b.x);this.y=b.y+a*(this.y-b.y);this.clearBounds();return this},intersects:function(a){var b=!1;return b="OpenLayers.Geometry.Point"==a.CLASS_NAME?this.equals(a):a.intersects(this)},transform:function(a,b){a&&b&&(OpenLayers.Projection.transform(this,
2019 a,b),this.bounds=null);return this},getVertices:function(a){return[this]},CLASS_NAME:"OpenLayers.Geometry.Point"});OpenLayers.Geometry.Collection=OpenLayers.Class(OpenLayers.Geometry,{components:null,componentTypes:null,initialize:function(a){OpenLayers.Geometry.prototype.initialize.apply(this,arguments);this.components=[];null!=a&&this.addComponents(a)},destroy:function(){this.components.length=0;this.components=null;OpenLayers.Geometry.prototype.destroy.apply(this,arguments)},clone:function(){for(var a=eval("new "+this.CLASS_NAME+"()"),b=0,c=this.components.length;b<c;b++)a.addComponent(this.components[b].clone());
2020 OpenLayers.Util.applyDefaults(a,this);return a},getComponentsString:function(){for(var a=[],b=0,c=this.components.length;b<c;b++)a.push(this.components[b].toShortString());return a.join(",")},calculateBounds:function(){this.bounds=null;var a=new OpenLayers.Bounds,b=this.components;if(b)for(var c=0,d=b.length;c<d;c++)a.extend(b[c].getBounds());null!=a.left&&(null!=a.bottom&&null!=a.right&&null!=a.top)&&this.setBounds(a)},addComponents:function(a){OpenLayers.Util.isArray(a)||(a=[a]);for(var b=0,c=a.length;b<
2021 c;b++)this.addComponent(a[b])},addComponent:function(a,b){var c=!1;if(a&&(null==this.componentTypes||-1<OpenLayers.Util.indexOf(this.componentTypes,a.CLASS_NAME))){if(null!=b&&b<this.components.length){var c=this.components.slice(0,b),d=this.components.slice(b,this.components.length);c.push(a);this.components=c.concat(d)}else this.components.push(a);a.parent=this;this.clearBounds();c=!0}return c},removeComponents:function(a){var b=!1;OpenLayers.Util.isArray(a)||(a=[a]);for(var c=a.length-1;0<=c;--c)b=
2022 this.removeComponent(a[c])||b;return b},removeComponent:function(a){OpenLayers.Util.removeItem(this.components,a);this.clearBounds();return!0},getLength:function(){for(var a=0,b=0,c=this.components.length;b<c;b++)a+=this.components[b].getLength();return a},getArea:function(){for(var a=0,b=0,c=this.components.length;b<c;b++)a+=this.components[b].getArea();return a},getGeodesicArea:function(a){for(var b=0,c=0,d=this.components.length;c<d;c++)b+=this.components[c].getGeodesicArea(a);return b},getCentroid:function(a){if(!a)return this.components.length&&
2023 this.components[0].getCentroid();a=this.components.length;if(!a)return!1;for(var b=[],c=[],d=0,e=Number.MAX_VALUE,f,g=0;g<a;++g){f=this.components[g];var h=f.getArea();f=f.getCentroid(!0);isNaN(h)||(isNaN(f.x)||isNaN(f.y))||(b.push(h),d+=h,e=h<e&&0<h?h:e,c.push(f))}a=b.length;if(0===d){for(g=0;g<a;++g)b[g]=1;d=b.length}else{for(g=0;g<a;++g)b[g]/=e;d/=e}for(var k=e=0,g=0;g<a;++g)f=c[g],h=b[g],e+=f.x*h,k+=f.y*h;return new OpenLayers.Geometry.Point(e/d,k/d)},getGeodesicLength:function(a){for(var b=0,
2024 c=0,d=this.components.length;c<d;c++)b+=this.components[c].getGeodesicLength(a);return b},move:function(a,b){for(var c=0,d=this.components.length;c<d;c++)this.components[c].move(a,b)},rotate:function(a,b){for(var c=0,d=this.components.length;c<d;++c)this.components[c].rotate(a,b)},resize:function(a,b,c){for(var d=0;d<this.components.length;++d)this.components[d].resize(a,b,c);return this},distanceTo:function(a,b){for(var c=!(b&&!1===b.edge)&&b&&b.details,d,e,f,g=Number.POSITIVE_INFINITY,h=0,k=this.components.length;h<
2025 k&&!(d=this.components[h].distanceTo(a,b),f=c?d.distance:d,f<g&&(g=f,e=d,0==g));++h);return e},equals:function(a){var b=!0;if(a&&a.CLASS_NAME&&this.CLASS_NAME==a.CLASS_NAME)if(OpenLayers.Util.isArray(a.components)&&a.components.length==this.components.length)for(var c=0,d=this.components.length;c<d;++c){if(!this.components[c].equals(a.components[c])){b=!1;break}}else b=!1;else b=!1;return b},transform:function(a,b){if(a&&b){for(var c=0,d=this.components.length;c<d;c++)this.components[c].transform(a,
2026 b);this.bounds=null}return this},intersects:function(a){for(var b=!1,c=0,d=this.components.length;c<d&&!(b=a.intersects(this.components[c]));++c);return b},getVertices:function(a){for(var b=[],c=0,d=this.components.length;c<d;++c)Array.prototype.push.apply(b,this.components[c].getVertices(a));return b},CLASS_NAME:"OpenLayers.Geometry.Collection"});OpenLayers.Geometry.MultiPoint=OpenLayers.Class(OpenLayers.Geometry.Collection,{componentTypes:["OpenLayers.Geometry.Point"],addPoint:function(a,b){this.addComponent(a,b)},removePoint:function(a){this.removeComponent(a)},CLASS_NAME:"OpenLayers.Geometry.MultiPoint"});OpenLayers.Geometry.Curve=OpenLayers.Class(OpenLayers.Geometry.MultiPoint,{componentTypes:["OpenLayers.Geometry.Point"],getLength:function(){var a=0;if(this.components&&1<this.components.length)for(var b=1,c=this.components.length;b<c;b++)a+=this.components[b-1].distanceTo(this.components[b]);return a},getGeodesicLength:function(a){var b=this;if(a){var c=new OpenLayers.Projection("EPSG:4326");c.equals(a)||(b=this.clone().transform(a,c))}a=0;if(b.components&&1<b.components.length)for(var d,e=1,f=b.components.length;e<
2027 f;e++)c=b.components[e-1],d=b.components[e],a+=OpenLayers.Util.distVincenty({lon:c.x,lat:c.y},{lon:d.x,lat:d.y});return 1E3*a},CLASS_NAME:"OpenLayers.Geometry.Curve"});OpenLayers.Geometry.LineString=OpenLayers.Class(OpenLayers.Geometry.Curve,{removeComponent:function(a){var b=this.components&&2<this.components.length;b&&OpenLayers.Geometry.Collection.prototype.removeComponent.apply(this,arguments);return b},intersects:function(a){var b=!1,c=a.CLASS_NAME;if("OpenLayers.Geometry.LineString"==c||"OpenLayers.Geometry.LinearRing"==c||"OpenLayers.Geometry.Point"==c){var d=this.getSortedSegments();a="OpenLayers.Geometry.Point"==c?[{x1:a.x,y1:a.y,x2:a.x,y2:a.y}]:a.getSortedSegments();
2028 var e,f,g,h,k,l,m,n=0,p=d.length;a:for(;n<p;++n){c=d[n];e=c.x1;f=c.x2;g=c.y1;h=c.y2;var q=0,r=a.length;for(;q<r;++q){k=a[q];if(k.x1>f)break;if(!(k.x2<e||(l=k.y1,m=k.y2,Math.min(l,m)>Math.max(g,h)||Math.max(l,m)<Math.min(g,h)||!OpenLayers.Geometry.segmentsIntersect(c,k)))){b=!0;break a}}}}else b=a.intersects(this);return b},getSortedSegments:function(){for(var a=this.components.length-1,b=Array(a),c,d,e=0;e<a;++e)c=this.components[e],d=this.components[e+1],b[e]=c.x<d.x?{x1:c.x,y1:c.y,x2:d.x,y2:d.y}:
2029 {x1:d.x,y1:d.y,x2:c.x,y2:c.y};return b.sort(function(a,b){return a.x1-b.x1})},splitWithSegment:function(a,b){for(var c=!(b&&!1===b.edge),d=b&&b.tolerance,e=[],f=this.getVertices(),g=[],h=[],k=!1,l,m,n,p={point:!0,tolerance:d},q=null,r=0,s=f.length-2;r<=s;++r)if(d=f[r],g.push(d.clone()),l=f[r+1],m={x1:d.x,y1:d.y,x2:l.x,y2:l.y},m=OpenLayers.Geometry.segmentsIntersect(a,m,p),m instanceof OpenLayers.Geometry.Point&&((n=m.x===a.x1&&m.y===a.y1||m.x===a.x2&&m.y===a.y2||m.equals(d)||m.equals(l)?!0:!1)||c))m.equals(h[h.length-
2030 1])||h.push(m.clone()),0===r&&m.equals(d)||m.equals(l)||(k=!0,m.equals(d)||g.push(m),e.push(new OpenLayers.Geometry.LineString(g)),g=[m.clone()]);k&&(g.push(l.clone()),e.push(new OpenLayers.Geometry.LineString(g)));if(0<h.length)var t=a.x1<a.x2?1:-1,u=a.y1<a.y2?1:-1,q={lines:e,points:h.sort(function(a,b){return t*a.x-t*b.x||u*a.y-u*b.y})};return q},split:function(a,b){var c=null,d=b&&b.mutual,e,f,g,h;if(a instanceof OpenLayers.Geometry.LineString){var k=this.getVertices(),l,m,n,p,q,r=[];g=[];for(var s=
2031 0,t=k.length-2;s<=t;++s){l=k[s];m=k[s+1];n={x1:l.x,y1:l.y,x2:m.x,y2:m.y};h=h||[a];d&&r.push(l.clone());for(var u=0;u<h.length;++u)if(p=h[u].splitWithSegment(n,b))if(q=p.lines,0<q.length&&(q.unshift(u,1),Array.prototype.splice.apply(h,q),u+=q.length-2),d)for(var v=0,w=p.points.length;v<w;++v)q=p.points[v],q.equals(l)||(r.push(q),g.push(new OpenLayers.Geometry.LineString(r)),r=q.equals(m)?[]:[q.clone()])}d&&(0<g.length&&0<r.length)&&(r.push(m.clone()),g.push(new OpenLayers.Geometry.LineString(r)))}else c=
2032 a.splitWith(this,b);h&&1<h.length?f=!0:h=[];g&&1<g.length?e=!0:g=[];if(f||e)c=d?[g,h]:h;return c},splitWith:function(a,b){return a.split(this,b)},getVertices:function(a){return!0===a?[this.components[0],this.components[this.components.length-1]]:!1===a?this.components.slice(1,this.components.length-1):this.components.slice()},distanceTo:function(a,b){var c=!(b&&!1===b.edge)&&b&&b.details,d,e={},f=Number.POSITIVE_INFINITY;if(a instanceof OpenLayers.Geometry.Point){for(var g=this.getSortedSegments(),
2033 h=a.x,k=a.y,l,m=0,n=g.length;m<n;++m)if(l=g[m],d=OpenLayers.Geometry.distanceToSegment(a,l),d.distance<f){if(f=d.distance,e=d,0===f)break}else if(l.x2>h&&(k>l.y1&&k<l.y2||k<l.y1&&k>l.y2))break;e=c?{distance:e.distance,x0:e.x,y0:e.y,x1:h,y1:k}:e.distance}else if(a instanceof OpenLayers.Geometry.LineString){var g=this.getSortedSegments(),h=a.getSortedSegments(),p,q,r=h.length,s={point:!0},m=0,n=g.length;a:for(;m<n;++m){k=g[m];l=k.x1;q=k.y1;for(var t=0;t<r;++t)if(d=h[t],p=OpenLayers.Geometry.segmentsIntersect(k,
2034 d,s)){f=0;e={distance:0,x0:p.x,y0:p.y,x1:p.x,y1:p.y};break a}else d=OpenLayers.Geometry.distanceToSegment({x:l,y:q},d),d.distance<f&&(f=d.distance,e={distance:f,x0:l,y0:q,x1:d.x,y1:d.y})}c||(e=e.distance);0!==f&&k&&(d=a.distanceTo(new OpenLayers.Geometry.Point(k.x2,k.y2),b),m=c?d.distance:d,m<f&&(e=c?{distance:f,x0:d.x1,y0:d.y1,x1:d.x0,y1:d.y0}:m))}else e=a.distanceTo(this,b),c&&(e={distance:e.distance,x0:e.x1,y0:e.y1,x1:e.x0,y1:e.y0});return e},simplify:function(a){if(this&&null!==this){var b=this.getVertices();
2035 if(3>b.length)return this;var c=function(a,b,d,k){for(var l=0,m=0,n=b,p;n<d;n++){p=a[b];var q=a[d],r=a[n],r=Math.abs(0.5*(p.x*q.y+q.x*r.y+r.x*p.y-q.x*p.y-r.x*q.y-p.x*r.y));p=Math.sqrt(Math.pow(p.x-q.x,2)+Math.pow(p.y-q.y,2));p=2*(r/p);p>l&&(l=p,m=n)}l>k&&m!=b&&(e.push(m),c(a,b,m,k),c(a,m,d,k))},d=b.length-1,e=[];e.push(0);for(e.push(d);b[0].equals(b[d]);)d--,e.push(d);c(b,0,d,a);a=[];e.sort(function(a,b){return a-b});for(d=0;d<e.length;d++)a.push(b[e[d]]);return new OpenLayers.Geometry.LineString(a)}return this},
2036 CLASS_NAME:"OpenLayers.Geometry.LineString"});OpenLayers.Geometry.MultiLineString=OpenLayers.Class(OpenLayers.Geometry.Collection,{componentTypes:["OpenLayers.Geometry.LineString"],split:function(a,b){for(var c=null,d=b&&b.mutual,e,f,g,h,k=[],l=[a],m=0,n=this.components.length;m<n;++m){f=this.components[m];g=!1;for(var p=0;p<l.length;++p)if(e=f.split(l[p],b)){if(d){g=e[0];for(var q=0,r=g.length;q<r;++q)0===q&&k.length?k[k.length-1].addComponent(g[q]):k.push(new OpenLayers.Geometry.MultiLineString([g[q]]));g=!0;e=e[1]}if(e.length){e.unshift(p,
2037 1);Array.prototype.splice.apply(l,e);break}}g||(k.length?k[k.length-1].addComponent(f.clone()):k=[new OpenLayers.Geometry.MultiLineString(f.clone())])}k&&1<k.length?g=!0:k=[];l&&1<l.length?h=!0:l=[];if(g||h)c=d?[k,l]:l;return c},splitWith:function(a,b){var c=null,d=b&&b.mutual,e,f,g,h,k,l;if(a instanceof OpenLayers.Geometry.LineString){l=[];k=[a];for(var m=0,n=this.components.length;m<n;++m){g=!1;f=this.components[m];for(var p=0;p<k.length;++p)if(e=k[p].split(f,b)){d&&(g=e[0],g.length&&(g.unshift(p,
2038 1),Array.prototype.splice.apply(k,g),p+=g.length-2),e=e[1],0===e.length&&(e=[f.clone()]));g=0;for(var q=e.length;g<q;++g)0===g&&l.length?l[l.length-1].addComponent(e[g]):l.push(new OpenLayers.Geometry.MultiLineString([e[g]]));g=!0}g||(l.length?l[l.length-1].addComponent(f.clone()):l=[new OpenLayers.Geometry.MultiLineString([f.clone()])])}}else c=a.split(this);k&&1<k.length?h=!0:k=[];l&&1<l.length?g=!0:l=[];if(h||g)c=d?[k,l]:l;return c},CLASS_NAME:"OpenLayers.Geometry.MultiLineString"});OpenLayers.Geometry.LinearRing=OpenLayers.Class(OpenLayers.Geometry.LineString,{componentTypes:["OpenLayers.Geometry.Point"],addComponent:function(a,b){var c=!1,d=this.components.pop();null==b&&a.equals(d)||(c=OpenLayers.Geometry.Collection.prototype.addComponent.apply(this,arguments));OpenLayers.Geometry.Collection.prototype.addComponent.apply(this,[this.components[0]]);return c},removeComponent:function(a){var b=this.components&&3<this.components.length;b&&(this.components.pop(),OpenLayers.Geometry.Collection.prototype.removeComponent.apply(this,
2039 arguments),OpenLayers.Geometry.Collection.prototype.addComponent.apply(this,[this.components[0]]));return b},move:function(a,b){for(var c=0,d=this.components.length;c<d-1;c++)this.components[c].move(a,b)},rotate:function(a,b){for(var c=0,d=this.components.length;c<d-1;++c)this.components[c].rotate(a,b)},resize:function(a,b,c){for(var d=0,e=this.components.length;d<e-1;++d)this.components[d].resize(a,b,c);return this},transform:function(a,b){if(a&&b){for(var c=0,d=this.components.length;c<d-1;c++)this.components[c].transform(a,
2040 b);this.bounds=null}return this},getCentroid:function(){if(this.components){var a=this.components.length;if(0<a&&2>=a)return this.components[0].clone();if(2<a){var b=0,c=0,d=this.components[0].x,e=this.components[0].y,f=-1*this.getArea();if(0!=f){for(var g=0;g<a-1;g++)var h=this.components[g],k=this.components[g+1],b=b+(h.x+k.x-2*d)*((h.x-d)*(k.y-e)-(k.x-d)*(h.y-e)),c=c+(h.y+k.y-2*e)*((h.x-d)*(k.y-e)-(k.x-d)*(h.y-e));b=d+b/(6*f);a=e+c/(6*f)}else{for(g=0;g<a-1;g++)b+=this.components[g].x,c+=this.components[g].y;
2041 b/=a-1;a=c/(a-1)}return new OpenLayers.Geometry.Point(b,a)}return null}},getArea:function(){var a=0;if(this.components&&2<this.components.length){for(var b=a=0,c=this.components.length;b<c-1;b++)var d=this.components[b],e=this.components[b+1],a=a+(d.x+e.x)*(e.y-d.y);a=-a/2}return a},getGeodesicArea:function(a){var b=this;if(a){var c=new OpenLayers.Projection("EPSG:4326");c.equals(a)||(b=this.clone().transform(a,c))}a=0;c=b.components&&b.components.length;if(2<c){for(var d,e,f=0;f<c-1;f++)d=b.components[f],
2042 e=b.components[f+1],a+=OpenLayers.Util.rad(e.x-d.x)*(2+Math.sin(OpenLayers.Util.rad(d.y))+Math.sin(OpenLayers.Util.rad(e.y)));a=40680631590769*a/2}return a},containsPoint:function(a){var b=OpenLayers.Number.limitSigDigs,c=b(a.x,14);a=b(a.y,14);for(var d=this.components.length-1,e,f,g,h,k,l=0,m=0;m<d;++m)if(e=this.components[m],g=b(e.x,14),e=b(e.y,14),f=this.components[m+1],h=b(f.x,14),f=b(f.y,14),e==f){if(a==e&&(g<=h&&c>=g&&c<=h||g>=h&&c<=g&&c>=h)){l=-1;break}}else{k=b((a-f)*((h-g)/(f-e))+h,14);if(k==
2043 c&&(e<f&&a>=e&&a<=f||e>f&&a<=e&&a>=f)){l=-1;break}k<=c||g!=h&&(k<Math.min(g,h)||k>Math.max(g,h))||(e<f&&a>=e&&a<f||e>f&&a<e&&a>=f)&&++l}return-1==l?1:!!(l&1)},intersects:function(a){var b=!1;if("OpenLayers.Geometry.Point"==a.CLASS_NAME)b=this.containsPoint(a);else if("OpenLayers.Geometry.LineString"==a.CLASS_NAME)b=a.intersects(this);else if("OpenLayers.Geometry.LinearRing"==a.CLASS_NAME)b=OpenLayers.Geometry.LineString.prototype.intersects.apply(this,[a]);else for(var c=0,d=a.components.length;c<
2044 d&&!(b=a.components[c].intersects(this));++c);return b},getVertices:function(a){return!0===a?[]:this.components.slice(0,this.components.length-1)},CLASS_NAME:"OpenLayers.Geometry.LinearRing"});OpenLayers.Geometry.Polygon=OpenLayers.Class(OpenLayers.Geometry.Collection,{componentTypes:["OpenLayers.Geometry.LinearRing"],getArea:function(){var a=0;if(this.components&&0<this.components.length)for(var a=a+Math.abs(this.components[0].getArea()),b=1,c=this.components.length;b<c;b++)a-=Math.abs(this.components[b].getArea());return a},getGeodesicArea:function(a){var b=0;if(this.components&&0<this.components.length)for(var b=b+Math.abs(this.components[0].getGeodesicArea(a)),c=1,d=this.components.length;c<
2045 d;c++)b-=Math.abs(this.components[c].getGeodesicArea(a));return b},containsPoint:function(a){var b=this.components.length,c=!1;if(0<b&&(c=this.components[0].containsPoint(a),1!==c&&c&&1<b))for(var d,e=1;e<b;++e)if(d=this.components[e].containsPoint(a)){c=1===d?1:!1;break}return c},intersects:function(a){var b=!1,c,d;if("OpenLayers.Geometry.Point"==a.CLASS_NAME)b=this.containsPoint(a);else if("OpenLayers.Geometry.LineString"==a.CLASS_NAME||"OpenLayers.Geometry.LinearRing"==a.CLASS_NAME){c=0;for(d=
2046 this.components.length;c<d&&!(b=a.intersects(this.components[c]));++c);if(!b)for(c=0,d=a.components.length;c<d&&!(b=this.containsPoint(a.components[c]));++c);}else for(c=0,d=a.components.length;c<d&&!(b=this.intersects(a.components[c]));++c);if(!b&&"OpenLayers.Geometry.Polygon"==a.CLASS_NAME){var e=this.components[0];c=0;for(d=e.components.length;c<d&&!(b=a.containsPoint(e.components[c]));++c);}return b},distanceTo:function(a,b){return b&&!1===b.edge&&this.intersects(a)?0:OpenLayers.Geometry.Collection.prototype.distanceTo.apply(this,
2047 [a,b])},CLASS_NAME:"OpenLayers.Geometry.Polygon"});OpenLayers.Geometry.Polygon.createRegularPolygon=function(a,b,c,d){var e=Math.PI*(1/c-0.5);d&&(e+=d/180*Math.PI);for(var f,g=[],h=0;h<c;++h)f=e+2*h*Math.PI/c,d=a.x+b*Math.cos(f),f=a.y+b*Math.sin(f),g.push(new OpenLayers.Geometry.Point(d,f));a=new OpenLayers.Geometry.LinearRing(g);return new OpenLayers.Geometry.Polygon([a])};OpenLayers.Geometry.MultiPolygon=OpenLayers.Class(OpenLayers.Geometry.Collection,{componentTypes:["OpenLayers.Geometry.Polygon"],CLASS_NAME:"OpenLayers.Geometry.MultiPolygon"});OpenLayers.Format.GML=OpenLayers.Class(OpenLayers.Format.XML,{featureNS:"http://mapserver.gis.umn.edu/mapserver",featurePrefix:"feature",featureName:"featureMember",layerName:"features",geometryName:"geometry",collectionName:"FeatureCollection",gmlns:"http://www.opengis.net/gml",extractAttributes:!0,xy:!0,initialize:function(a){this.regExes={trimSpace:/^\s*|\s*$/g,removeSpace:/\s*/g,splitSpace:/\s+/,trimComma:/\s*,\s*/g};OpenLayers.Format.XML.prototype.initialize.apply(this,[a])},read:function(a){"string"==
2048 typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));a=this.getElementsByTagNameNS(a.documentElement,this.gmlns,this.featureName);for(var b=[],c=0;c<a.length;c++){var d=this.parseFeature(a[c]);d&&b.push(d)}return b},parseFeature:function(a){for(var b="MultiPolygon Polygon MultiLineString LineString MultiPoint Point Envelope".split(" "),c,d,e,f=0;f<b.length;++f)if(c=b[f],d=this.getElementsByTagNameNS(a,this.gmlns,c),0<d.length){if(e=this.parseGeometry[c.toLowerCase()])e=e.apply(this,
2049 [d[0]]),this.internalProjection&&this.externalProjection&&e.transform(this.externalProjection,this.internalProjection);else throw new TypeError("Unsupported geometry type: "+c);break}var g;c=this.getElementsByTagNameNS(a,this.gmlns,"Box");for(f=0;f<c.length;++f)b=c[f],d=this.parseGeometry.box.apply(this,[b]),b=b.parentNode,"boundedBy"===(b.localName||b.nodeName.split(":").pop())?g=d:e=d.toGeometry();var h;this.extractAttributes&&(h=this.parseAttributes(a));h=new OpenLayers.Feature.Vector(e,h);h.bounds=
2050 g;h.gml={featureType:a.firstChild.nodeName.split(":")[1],featureNS:a.firstChild.namespaceURI,featureNSPrefix:a.firstChild.prefix};a=a.firstChild;for(var k;a&&(1!=a.nodeType||!(k=a.getAttribute("fid")||a.getAttribute("id")));)a=a.nextSibling;h.fid=k;return h},parseGeometry:{point:function(a){var b,c;c=[];b=this.getElementsByTagNameNS(a,this.gmlns,"pos");0<b.length&&(c=b[0].firstChild.nodeValue,c=c.replace(this.regExes.trimSpace,""),c=c.split(this.regExes.splitSpace));0==c.length&&(b=this.getElementsByTagNameNS(a,
2051 this.gmlns,"coordinates"),0<b.length&&(c=b[0].firstChild.nodeValue,c=c.replace(this.regExes.removeSpace,""),c=c.split(",")));0==c.length&&(b=this.getElementsByTagNameNS(a,this.gmlns,"coord"),0<b.length&&(a=this.getElementsByTagNameNS(b[0],this.gmlns,"X"),b=this.getElementsByTagNameNS(b[0],this.gmlns,"Y"),0<a.length&&0<b.length&&(c=[a[0].firstChild.nodeValue,b[0].firstChild.nodeValue])));2==c.length&&(c[2]=null);return this.xy?new OpenLayers.Geometry.Point(c[0],c[1],c[2]):new OpenLayers.Geometry.Point(c[1],
2052 c[0],c[2])},multipoint:function(a){a=this.getElementsByTagNameNS(a,this.gmlns,"Point");var b=[];if(0<a.length)for(var c,d=0;d<a.length;++d)(c=this.parseGeometry.point.apply(this,[a[d]]))&&b.push(c);return new OpenLayers.Geometry.MultiPoint(b)},linestring:function(a,b){var c,d;d=[];var e=[];c=this.getElementsByTagNameNS(a,this.gmlns,"posList");if(0<c.length){d=this.getChildValue(c[0]);d=d.replace(this.regExes.trimSpace,"");d=d.split(this.regExes.splitSpace);var f=parseInt(c[0].getAttribute("dimension")),
2053 g,h,k;for(c=0;c<d.length/f;++c)g=c*f,h=d[g],k=d[g+1],g=2==f?null:d[g+2],this.xy?e.push(new OpenLayers.Geometry.Point(h,k,g)):e.push(new OpenLayers.Geometry.Point(k,h,g))}if(0==d.length&&(c=this.getElementsByTagNameNS(a,this.gmlns,"coordinates"),0<c.length))for(d=this.getChildValue(c[0]),d=d.replace(this.regExes.trimSpace,""),d=d.replace(this.regExes.trimComma,","),f=d.split(this.regExes.splitSpace),c=0;c<f.length;++c)d=f[c].split(","),2==d.length&&(d[2]=null),this.xy?e.push(new OpenLayers.Geometry.Point(d[0],
2054 d[1],d[2])):e.push(new OpenLayers.Geometry.Point(d[1],d[0],d[2]));d=null;0!=e.length&&(d=b?new OpenLayers.Geometry.LinearRing(e):new OpenLayers.Geometry.LineString(e));return d},multilinestring:function(a){a=this.getElementsByTagNameNS(a,this.gmlns,"LineString");var b=[];if(0<a.length)for(var c,d=0;d<a.length;++d)(c=this.parseGeometry.linestring.apply(this,[a[d]]))&&b.push(c);return new OpenLayers.Geometry.MultiLineString(b)},polygon:function(a){a=this.getElementsByTagNameNS(a,this.gmlns,"LinearRing");
2055 var b=[];if(0<a.length)for(var c,d=0;d<a.length;++d)(c=this.parseGeometry.linestring.apply(this,[a[d],!0]))&&b.push(c);return new OpenLayers.Geometry.Polygon(b)},multipolygon:function(a){a=this.getElementsByTagNameNS(a,this.gmlns,"Polygon");var b=[];if(0<a.length)for(var c,d=0;d<a.length;++d)(c=this.parseGeometry.polygon.apply(this,[a[d]]))&&b.push(c);return new OpenLayers.Geometry.MultiPolygon(b)},envelope:function(a){var b=[],c,d,e=this.getElementsByTagNameNS(a,this.gmlns,"lowerCorner");if(0<e.length){c=
2056 [];0<e.length&&(c=e[0].firstChild.nodeValue,c=c.replace(this.regExes.trimSpace,""),c=c.split(this.regExes.splitSpace));2==c.length&&(c[2]=null);var f=this.xy?new OpenLayers.Geometry.Point(c[0],c[1],c[2]):new OpenLayers.Geometry.Point(c[1],c[0],c[2])}a=this.getElementsByTagNameNS(a,this.gmlns,"upperCorner");if(0<a.length){c=[];0<a.length&&(c=a[0].firstChild.nodeValue,c=c.replace(this.regExes.trimSpace,""),c=c.split(this.regExes.splitSpace));2==c.length&&(c[2]=null);var g=this.xy?new OpenLayers.Geometry.Point(c[0],
2057 c[1],c[2]):new OpenLayers.Geometry.Point(c[1],c[0],c[2])}f&&g&&(b.push(new OpenLayers.Geometry.Point(f.x,f.y)),b.push(new OpenLayers.Geometry.Point(g.x,f.y)),b.push(new OpenLayers.Geometry.Point(g.x,g.y)),b.push(new OpenLayers.Geometry.Point(f.x,g.y)),b.push(new OpenLayers.Geometry.Point(f.x,f.y)),b=new OpenLayers.Geometry.LinearRing(b),d=new OpenLayers.Geometry.Polygon([b]));return d},box:function(a){var b=this.getElementsByTagNameNS(a,this.gmlns,"coordinates"),c=a=null;0<b.length&&(b=b[0].firstChild.nodeValue,
2058 b=b.split(" "),2==b.length&&(a=b[0].split(","),c=b[1].split(",")));if(null!==a&&null!==c)return new OpenLayers.Bounds(parseFloat(a[0]),parseFloat(a[1]),parseFloat(c[0]),parseFloat(c[1]))}},parseAttributes:function(a){var b={};a=a.firstChild;for(var c,d,e;a;){if(1==a.nodeType){a=a.childNodes;for(c=0;c<a.length;++c)if(d=a[c],1==d.nodeType)if(e=d.childNodes,1==e.length){if(e=e[0],3==e.nodeType||4==e.nodeType)d=d.prefix?d.nodeName.split(":")[1]:d.nodeName,e=e.nodeValue.replace(this.regExes.trimSpace,
2059 ""),b[d]=e}else b[d.nodeName.split(":").pop()]=null;break}a=a.nextSibling}return b},write:function(a){OpenLayers.Util.isArray(a)||(a=[a]);for(var b=this.createElementNS("http://www.opengis.net/wfs","wfs:"+this.collectionName),c=0;c<a.length;c++)b.appendChild(this.createFeatureXML(a[c]));return OpenLayers.Format.XML.prototype.write.apply(this,[b])},createFeatureXML:function(a){var b=this.buildGeometryNode(a.geometry),c=this.createElementNS(this.featureNS,this.featurePrefix+":"+this.geometryName);c.appendChild(b);
2060 var b=this.createElementNS(this.gmlns,"gml:"+this.featureName),d=this.createElementNS(this.featureNS,this.featurePrefix+":"+this.layerName);d.setAttribute("fid",a.fid||a.id);d.appendChild(c);for(var e in a.attributes){var c=this.createTextNode(a.attributes[e]),f=e.substring(e.lastIndexOf(":")+1),f=this.createElementNS(this.featureNS,this.featurePrefix+":"+f);f.appendChild(c);d.appendChild(f)}b.appendChild(d);return b},buildGeometryNode:function(a){this.externalProjection&&this.internalProjection&&
2061 (a=a.clone(),a.transform(this.internalProjection,this.externalProjection));var b=a.CLASS_NAME,b=b.substring(b.lastIndexOf(".")+1);return this.buildGeometry[b.toLowerCase()].apply(this,[a])},buildGeometry:{point:function(a){var b=this.createElementNS(this.gmlns,"gml:Point");b.appendChild(this.buildCoordinatesNode(a));return b},multipoint:function(a){var b=this.createElementNS(this.gmlns,"gml:MultiPoint");a=a.components;for(var c,d,e=0;e<a.length;e++)c=this.createElementNS(this.gmlns,"gml:pointMember"),
2062 d=this.buildGeometry.point.apply(this,[a[e]]),c.appendChild(d),b.appendChild(c);return b},linestring:function(a){var b=this.createElementNS(this.gmlns,"gml:LineString");b.appendChild(this.buildCoordinatesNode(a));return b},multilinestring:function(a){var b=this.createElementNS(this.gmlns,"gml:MultiLineString");a=a.components;for(var c,d,e=0;e<a.length;++e)c=this.createElementNS(this.gmlns,"gml:lineStringMember"),d=this.buildGeometry.linestring.apply(this,[a[e]]),c.appendChild(d),b.appendChild(c);
2063 return b},linearring:function(a){var b=this.createElementNS(this.gmlns,"gml:LinearRing");b.appendChild(this.buildCoordinatesNode(a));return b},polygon:function(a){var b=this.createElementNS(this.gmlns,"gml:Polygon");a=a.components;for(var c,d,e=0;e<a.length;++e)c=0==e?"outerBoundaryIs":"innerBoundaryIs",c=this.createElementNS(this.gmlns,"gml:"+c),d=this.buildGeometry.linearring.apply(this,[a[e]]),c.appendChild(d),b.appendChild(c);return b},multipolygon:function(a){var b=this.createElementNS(this.gmlns,
2064 "gml:MultiPolygon");a=a.components;for(var c,d,e=0;e<a.length;++e)c=this.createElementNS(this.gmlns,"gml:polygonMember"),d=this.buildGeometry.polygon.apply(this,[a[e]]),c.appendChild(d),b.appendChild(c);return b},bounds:function(a){var b=this.createElementNS(this.gmlns,"gml:Box");b.appendChild(this.buildCoordinatesNode(a));return b}},buildCoordinatesNode:function(a){var b=this.createElementNS(this.gmlns,"gml:coordinates");b.setAttribute("decimal",".");b.setAttribute("cs",",");b.setAttribute("ts",
2065 " ");var c=[];if(a instanceof OpenLayers.Bounds)c.push(a.left+","+a.bottom),c.push(a.right+","+a.top);else{a=a.components?a.components:[a];for(var d=0;d<a.length;d++)c.push(a[d].x+","+a[d].y)}c=this.createTextNode(c.join(" "));b.appendChild(c);return b},CLASS_NAME:"OpenLayers.Format.GML"});OpenLayers.Format.GML||(OpenLayers.Format.GML={});
2066 OpenLayers.Format.GML.Base=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{gml:"http://www.opengis.net/gml",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance",wfs:"http://www.opengis.net/wfs"},defaultPrefix:"gml",schemaLocation:null,featureType:null,featureNS:null,geometryName:"geometry",extractAttributes:!0,srsName:null,xy:!0,geometryTypes:null,singleFeatureType:null,regExes:{trimSpace:/^\s*|\s*$/g,removeSpace:/\s*/g,splitSpace:/\s+/,trimComma:/\s*,\s*/g,featureMember:/^(.*:)?featureMembers?$/},
2067 initialize:function(a){OpenLayers.Format.XML.prototype.initialize.apply(this,[a]);this.setGeometryTypes();a&&a.featureNS&&this.setNamespace("feature",a.featureNS);this.singleFeatureType=!a||"string"===typeof a.featureType},read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));a&&9==a.nodeType&&(a=a.documentElement);var b=[];this.readNode(a,{features:b},!0);if(0==b.length){var c=this.getElementsByTagNameNS(a,this.namespaces.gml,"featureMember");if(c.length){a=
2068 0;for(var d=c.length;a<d;++a)this.readNode(c[a],{features:b},!0)}else c=this.getElementsByTagNameNS(a,this.namespaces.gml,"featureMembers"),c.length&&this.readNode(c[0],{features:b},!0)}return b},readNode:function(a,b,c){!0===c&&!0===this.autoConfig&&(this.featureType=null,delete this.namespaceAlias[this.featureNS],delete this.namespaces.feature,this.featureNS=null);this.featureNS||(a.prefix in this.namespaces||a.parentNode.namespaceURI!=this.namespaces.gml||!this.regExes.featureMember.test(a.parentNode.nodeName))||
2069 (this.featureType=a.nodeName.split(":").pop(),this.setNamespace("feature",a.namespaceURI),this.featureNS=a.namespaceURI,this.autoConfig=!0);return OpenLayers.Format.XML.prototype.readNode.apply(this,[a,b])},readers:{gml:{_inherit:function(a,b,c){},featureMember:function(a,b){this.readChildNodes(a,b)},featureMembers:function(a,b){this.readChildNodes(a,b)},name:function(a,b){b.name=this.getChildValue(a)},boundedBy:function(a,b){var c={};this.readChildNodes(a,c);c.components&&0<c.components.length&&
2070 (b.bounds=c.components[0])},Point:function(a,b){var c={points:[]};this.readChildNodes(a,c);b.components||(b.components=[]);b.components.push(c.points[0])},coordinates:function(a,b){for(var c=this.getChildValue(a).replace(this.regExes.trimSpace,""),c=c.replace(this.regExes.trimComma,","),c=c.split(this.regExes.splitSpace),d,e=c.length,f=Array(e),g=0;g<e;++g)d=c[g].split(","),f[g]=this.xy?new OpenLayers.Geometry.Point(d[0],d[1],d[2]):new OpenLayers.Geometry.Point(d[1],d[0],d[2]);b.points=f},coord:function(a,
2071 b){var c={};this.readChildNodes(a,c);b.points||(b.points=[]);b.points.push(new OpenLayers.Geometry.Point(c.x,c.y,c.z))},X:function(a,b){b.x=this.getChildValue(a)},Y:function(a,b){b.y=this.getChildValue(a)},Z:function(a,b){b.z=this.getChildValue(a)},MultiPoint:function(a,b){var c={components:[]};this.readers.gml._inherit.apply(this,[a,c,b]);this.readChildNodes(a,c);b.components=[new OpenLayers.Geometry.MultiPoint(c.components)]},pointMember:function(a,b){this.readChildNodes(a,b)},LineString:function(a,
2072 b){var c={};this.readers.gml._inherit.apply(this,[a,c,b]);this.readChildNodes(a,c);b.components||(b.components=[]);b.components.push(new OpenLayers.Geometry.LineString(c.points))},MultiLineString:function(a,b){var c={components:[]};this.readers.gml._inherit.apply(this,[a,c,b]);this.readChildNodes(a,c);b.components=[new OpenLayers.Geometry.MultiLineString(c.components)]},lineStringMember:function(a,b){this.readChildNodes(a,b)},Polygon:function(a,b){var c={outer:null,inner:[]};this.readers.gml._inherit.apply(this,
2073 [a,c,b]);this.readChildNodes(a,c);c.inner.unshift(c.outer);b.components||(b.components=[]);b.components.push(new OpenLayers.Geometry.Polygon(c.inner))},LinearRing:function(a,b){var c={};this.readers.gml._inherit.apply(this,[a,c]);this.readChildNodes(a,c);b.components=[new OpenLayers.Geometry.LinearRing(c.points)]},MultiPolygon:function(a,b){var c={components:[]};this.readers.gml._inherit.apply(this,[a,c,b]);this.readChildNodes(a,c);b.components=[new OpenLayers.Geometry.MultiPolygon(c.components)]},
2074 polygonMember:function(a,b){this.readChildNodes(a,b)},GeometryCollection:function(a,b){var c={components:[]};this.readers.gml._inherit.apply(this,[a,c,b]);this.readChildNodes(a,c);b.components=[new OpenLayers.Geometry.Collection(c.components)]},geometryMember:function(a,b){this.readChildNodes(a,b)}},feature:{"*":function(a,b){var c,d=a.localName||a.nodeName.split(":").pop();b.features?this.singleFeatureType||-1===OpenLayers.Util.indexOf(this.featureType,d)?d===this.featureType&&(c="_typeName"):c=
2075 "_typeName":0==a.childNodes.length||1==a.childNodes.length&&3==a.firstChild.nodeType?this.extractAttributes&&(c="_attribute"):c="_geometry";c&&this.readers.feature[c].apply(this,[a,b])},_typeName:function(a,b){var c={components:[],attributes:{}};this.readChildNodes(a,c);c.name&&(c.attributes.name=c.name);var d=new OpenLayers.Feature.Vector(c.components[0],c.attributes);this.singleFeatureType||(d.type=a.nodeName.split(":").pop(),d.namespace=a.namespaceURI);var e=a.getAttribute("fid")||this.getAttributeNS(a,
2076 this.namespaces.gml,"id");e&&(d.fid=e);this.internalProjection&&(this.externalProjection&&d.geometry)&&d.geometry.transform(this.externalProjection,this.internalProjection);c.bounds&&(d.bounds=c.bounds);b.features.push(d)},_geometry:function(a,b){this.geometryName||(this.geometryName=a.nodeName.split(":").pop());this.readChildNodes(a,b)},_attribute:function(a,b){var c=a.localName||a.nodeName.split(":").pop(),d=this.getChildValue(a);b.attributes[c]=d}},wfs:{FeatureCollection:function(a,b){this.readChildNodes(a,
2077 b)}}},write:function(a){var b;b=OpenLayers.Util.isArray(a)?"featureMembers":"featureMember";a=this.writeNode("gml:"+b,a);this.setAttributeNS(a,this.namespaces.xsi,"xsi:schemaLocation",this.schemaLocation);return OpenLayers.Format.XML.prototype.write.apply(this,[a])},writers:{gml:{featureMember:function(a){var b=this.createElementNSPlus("gml:featureMember");this.writeNode("feature:_typeName",a,b);return b},MultiPoint:function(a){var b=this.createElementNSPlus("gml:MultiPoint");a=a.components||[a];
2078 for(var c=0,d=a.length;c<d;++c)this.writeNode("pointMember",a[c],b);return b},pointMember:function(a){var b=this.createElementNSPlus("gml:pointMember");this.writeNode("Point",a,b);return b},MultiLineString:function(a){var b=this.createElementNSPlus("gml:MultiLineString");a=a.components||[a];for(var c=0,d=a.length;c<d;++c)this.writeNode("lineStringMember",a[c],b);return b},lineStringMember:function(a){var b=this.createElementNSPlus("gml:lineStringMember");this.writeNode("LineString",a,b);return b},
2079 MultiPolygon:function(a){var b=this.createElementNSPlus("gml:MultiPolygon");a=a.components||[a];for(var c=0,d=a.length;c<d;++c)this.writeNode("polygonMember",a[c],b);return b},polygonMember:function(a){var b=this.createElementNSPlus("gml:polygonMember");this.writeNode("Polygon",a,b);return b},GeometryCollection:function(a){for(var b=this.createElementNSPlus("gml:GeometryCollection"),c=0,d=a.components.length;c<d;++c)this.writeNode("geometryMember",a.components[c],b);return b},geometryMember:function(a){var b=
2080 this.createElementNSPlus("gml:geometryMember");a=this.writeNode("feature:_geometry",a);b.appendChild(a.firstChild);return b}},feature:{_typeName:function(a){var b=this.createElementNSPlus("feature:"+this.featureType,{attributes:{fid:a.fid}});a.geometry&&this.writeNode("feature:_geometry",a.geometry,b);for(var c in a.attributes){var d=a.attributes[c];null!=d&&this.writeNode("feature:_attribute",{name:c,value:d},b)}return b},_geometry:function(a){this.externalProjection&&this.internalProjection&&(a=
2081 a.clone().transform(this.internalProjection,this.externalProjection));var b=this.createElementNSPlus("feature:"+this.geometryName);a=this.writeNode("gml:"+this.geometryTypes[a.CLASS_NAME],a,b);this.srsName&&a.setAttribute("srsName",this.srsName);return b},_attribute:function(a){return this.createElementNSPlus("feature:"+a.name,{value:a.value})}},wfs:{FeatureCollection:function(a){for(var b=this.createElementNSPlus("wfs:FeatureCollection"),c=0,d=a.length;c<d;++c)this.writeNode("gml:featureMember",
2082 a[c],b);return b}}},setGeometryTypes:function(){this.geometryTypes={"OpenLayers.Geometry.Point":"Point","OpenLayers.Geometry.MultiPoint":"MultiPoint","OpenLayers.Geometry.LineString":"LineString","OpenLayers.Geometry.MultiLineString":"MultiLineString","OpenLayers.Geometry.Polygon":"Polygon","OpenLayers.Geometry.MultiPolygon":"MultiPolygon","OpenLayers.Geometry.Collection":"GeometryCollection"}},CLASS_NAME:"OpenLayers.Format.GML.Base"});OpenLayers.Format.GML.v3=OpenLayers.Class(OpenLayers.Format.GML.Base,{schemaLocation:"http://www.opengis.net/gml http://schemas.opengis.net/gml/3.1.1/profiles/gmlsfProfile/1.0.0/gmlsf.xsd",curve:!1,multiCurve:!0,surface:!1,multiSurface:!0,initialize:function(a){OpenLayers.Format.GML.Base.prototype.initialize.apply(this,[a])},readers:{gml:OpenLayers.Util.applyDefaults({_inherit:function(a,b,c){if(a=parseInt(a.getAttribute("srsDimension"),10)||c&&c.srsDimension)b.srsDimension=a},featureMembers:function(a,
2083 b){this.readChildNodes(a,b)},Curve:function(a,b){var c={points:[]};this.readers.gml._inherit.apply(this,[a,c,b]);this.readChildNodes(a,c);b.components||(b.components=[]);b.components.push(new OpenLayers.Geometry.LineString(c.points))},segments:function(a,b){this.readChildNodes(a,b)},LineStringSegment:function(a,b){var c={};this.readChildNodes(a,c);c.points&&Array.prototype.push.apply(b.points,c.points)},pos:function(a,b){var c=this.getChildValue(a).replace(this.regExes.trimSpace,"").split(this.regExes.splitSpace),
2084 c=this.xy?new OpenLayers.Geometry.Point(c[0],c[1],c[2]):new OpenLayers.Geometry.Point(c[1],c[0],c[2]);b.points=[c]},posList:function(a,b){for(var c=this.getChildValue(a).replace(this.regExes.trimSpace,"").split(this.regExes.splitSpace),d=b.srsDimension||parseInt(a.getAttribute("srsDimension")||a.getAttribute("dimension"),10)||2,e,f,g,h=Array(c.length/d),k=0,l=c.length;k<l;k+=d)e=c[k],f=c[k+1],g=2==d?void 0:c[k+2],h[k/d]=this.xy?new OpenLayers.Geometry.Point(e,f,g):new OpenLayers.Geometry.Point(f,
2085 e,g);b.points=h},Surface:function(a,b){this.readChildNodes(a,b)},patches:function(a,b){this.readChildNodes(a,b)},PolygonPatch:function(a,b){this.readers.gml.Polygon.apply(this,[a,b])},exterior:function(a,b){var c={};this.readChildNodes(a,c);b.outer=c.components[0]},interior:function(a,b){var c={};this.readChildNodes(a,c);b.inner.push(c.components[0])},MultiCurve:function(a,b){var c={components:[]};this.readers.gml._inherit.apply(this,[a,c,b]);this.readChildNodes(a,c);0<c.components.length&&(b.components=
2086 [new OpenLayers.Geometry.MultiLineString(c.components)])},curveMember:function(a,b){this.readChildNodes(a,b)},MultiSurface:function(a,b){var c={components:[]};this.readers.gml._inherit.apply(this,[a,c,b]);this.readChildNodes(a,c);0<c.components.length&&(b.components=[new OpenLayers.Geometry.MultiPolygon(c.components)])},surfaceMember:function(a,b){this.readChildNodes(a,b)},surfaceMembers:function(a,b){this.readChildNodes(a,b)},pointMembers:function(a,b){this.readChildNodes(a,b)},lineStringMembers:function(a,
2087 b){this.readChildNodes(a,b)},polygonMembers:function(a,b){this.readChildNodes(a,b)},geometryMembers:function(a,b){this.readChildNodes(a,b)},Envelope:function(a,b){var c={points:Array(2)};this.readChildNodes(a,c);b.components||(b.components=[]);var d=c.points[0],c=c.points[1];b.components.push(new OpenLayers.Bounds(d.x,d.y,c.x,c.y))},lowerCorner:function(a,b){var c={};this.readers.gml.pos.apply(this,[a,c]);b.points[0]=c.points[0]},upperCorner:function(a,b){var c={};this.readers.gml.pos.apply(this,
2088 [a,c]);b.points[1]=c.points[0]}},OpenLayers.Format.GML.Base.prototype.readers.gml),feature:OpenLayers.Format.GML.Base.prototype.readers.feature,wfs:OpenLayers.Format.GML.Base.prototype.readers.wfs},write:function(a){var b;b=OpenLayers.Util.isArray(a)?"featureMembers":"featureMember";a=this.writeNode("gml:"+b,a);this.setAttributeNS(a,this.namespaces.xsi,"xsi:schemaLocation",this.schemaLocation);return OpenLayers.Format.XML.prototype.write.apply(this,[a])},writers:{gml:OpenLayers.Util.applyDefaults({featureMembers:function(a){for(var b=
2089 this.createElementNSPlus("gml:featureMembers"),c=0,d=a.length;c<d;++c)this.writeNode("feature:_typeName",a[c],b);return b},Point:function(a){var b=this.createElementNSPlus("gml:Point");this.writeNode("pos",a,b);return b},pos:function(a){return this.createElementNSPlus("gml:pos",{value:this.xy?a.x+" "+a.y:a.y+" "+a.x})},LineString:function(a){var b=this.createElementNSPlus("gml:LineString");this.writeNode("posList",a.components,b);return b},Curve:function(a){var b=this.createElementNSPlus("gml:Curve");
2090 this.writeNode("segments",a,b);return b},segments:function(a){var b=this.createElementNSPlus("gml:segments");this.writeNode("LineStringSegment",a,b);return b},LineStringSegment:function(a){var b=this.createElementNSPlus("gml:LineStringSegment");this.writeNode("posList",a.components,b);return b},posList:function(a){for(var b=a.length,c=Array(b),d,e=0;e<b;++e)d=a[e],c[e]=this.xy?d.x+" "+d.y:d.y+" "+d.x;return this.createElementNSPlus("gml:posList",{value:c.join(" ")})},Surface:function(a){var b=this.createElementNSPlus("gml:Surface");
2091 this.writeNode("patches",a,b);return b},patches:function(a){var b=this.createElementNSPlus("gml:patches");this.writeNode("PolygonPatch",a,b);return b},PolygonPatch:function(a){var b=this.createElementNSPlus("gml:PolygonPatch",{attributes:{interpolation:"planar"}});this.writeNode("exterior",a.components[0],b);for(var c=1,d=a.components.length;c<d;++c)this.writeNode("interior",a.components[c],b);return b},Polygon:function(a){var b=this.createElementNSPlus("gml:Polygon");this.writeNode("exterior",a.components[0],
2092 b);for(var c=1,d=a.components.length;c<d;++c)this.writeNode("interior",a.components[c],b);return b},exterior:function(a){var b=this.createElementNSPlus("gml:exterior");this.writeNode("LinearRing",a,b);return b},interior:function(a){var b=this.createElementNSPlus("gml:interior");this.writeNode("LinearRing",a,b);return b},LinearRing:function(a){var b=this.createElementNSPlus("gml:LinearRing");this.writeNode("posList",a.components,b);return b},MultiCurve:function(a){var b=this.createElementNSPlus("gml:MultiCurve");
2093 a=a.components||[a];for(var c=0,d=a.length;c<d;++c)this.writeNode("curveMember",a[c],b);return b},curveMember:function(a){var b=this.createElementNSPlus("gml:curveMember");this.curve?this.writeNode("Curve",a,b):this.writeNode("LineString",a,b);return b},MultiSurface:function(a){var b=this.createElementNSPlus("gml:MultiSurface");a=a.components||[a];for(var c=0,d=a.length;c<d;++c)this.writeNode("surfaceMember",a[c],b);return b},surfaceMember:function(a){var b=this.createElementNSPlus("gml:surfaceMember");
2094 this.surface?this.writeNode("Surface",a,b):this.writeNode("Polygon",a,b);return b},Envelope:function(a){var b=this.createElementNSPlus("gml:Envelope");this.writeNode("lowerCorner",a,b);this.writeNode("upperCorner",a,b);this.srsName&&b.setAttribute("srsName",this.srsName);return b},lowerCorner:function(a){return this.createElementNSPlus("gml:lowerCorner",{value:this.xy?a.left+" "+a.bottom:a.bottom+" "+a.left})},upperCorner:function(a){return this.createElementNSPlus("gml:upperCorner",{value:this.xy?
2095 a.right+" "+a.top:a.top+" "+a.right})}},OpenLayers.Format.GML.Base.prototype.writers.gml),feature:OpenLayers.Format.GML.Base.prototype.writers.feature,wfs:OpenLayers.Format.GML.Base.prototype.writers.wfs},setGeometryTypes:function(){this.geometryTypes={"OpenLayers.Geometry.Point":"Point","OpenLayers.Geometry.MultiPoint":"MultiPoint","OpenLayers.Geometry.LineString":!0===this.curve?"Curve":"LineString","OpenLayers.Geometry.MultiLineString":!1===this.multiCurve?"MultiLineString":"MultiCurve","OpenLayers.Geometry.Polygon":!0===
2096 this.surface?"Surface":"Polygon","OpenLayers.Geometry.MultiPolygon":!1===this.multiSurface?"MultiPolygon":"MultiSurface","OpenLayers.Geometry.Collection":"GeometryCollection"}},CLASS_NAME:"OpenLayers.Format.GML.v3"});OpenLayers.Format.Filter.v1_1_0=OpenLayers.Class(OpenLayers.Format.GML.v3,OpenLayers.Format.Filter.v1,{VERSION:"1.1.0",schemaLocation:"http://www.opengis.net/ogc/filter/1.1.0/filter.xsd",initialize:function(a){OpenLayers.Format.GML.v3.prototype.initialize.apply(this,[a])},readers:{ogc:OpenLayers.Util.applyDefaults({PropertyIsEqualTo:function(a,b){var c=a.getAttribute("matchCase"),c=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.EQUAL_TO,matchCase:!("false"===c||"0"===c)});this.readChildNodes(a,
2097 c);b.filters.push(c)},PropertyIsNotEqualTo:function(a,b){var c=a.getAttribute("matchCase"),c=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.NOT_EQUAL_TO,matchCase:!("false"===c||"0"===c)});this.readChildNodes(a,c);b.filters.push(c)},PropertyIsLike:function(a,b){var c=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.LIKE});this.readChildNodes(a,c);var d=a.getAttribute("wildCard"),e=a.getAttribute("singleChar"),f=a.getAttribute("escapeChar");c.value2regex(d,e,
2098 f);b.filters.push(c)}},OpenLayers.Format.Filter.v1.prototype.readers.ogc),gml:OpenLayers.Format.GML.v3.prototype.readers.gml,feature:OpenLayers.Format.GML.v3.prototype.readers.feature},writers:{ogc:OpenLayers.Util.applyDefaults({PropertyIsEqualTo:function(a){var b=this.createElementNSPlus("ogc:PropertyIsEqualTo",{attributes:{matchCase:a.matchCase}});this.writeNode("PropertyName",a,b);this.writeOgcExpression(a.value,b);return b},PropertyIsNotEqualTo:function(a){var b=this.createElementNSPlus("ogc:PropertyIsNotEqualTo",
2099 {attributes:{matchCase:a.matchCase}});this.writeNode("PropertyName",a,b);this.writeOgcExpression(a.value,b);return b},PropertyIsLike:function(a){var b=this.createElementNSPlus("ogc:PropertyIsLike",{attributes:{matchCase:a.matchCase,wildCard:"*",singleChar:".",escapeChar:"!"}});this.writeNode("PropertyName",a,b);this.writeNode("Literal",a.regex2value(),b);return b},BBOX:function(a){var b=this.createElementNSPlus("ogc:BBOX");a.property&&this.writeNode("PropertyName",a,b);var c=this.writeNode("gml:Envelope",
2100 a.value);a.projection&&c.setAttribute("srsName",a.projection);b.appendChild(c);return b},SortBy:function(a){for(var b=this.createElementNSPlus("ogc:SortBy"),c=0,d=a.length;c<d;c++)this.writeNode("ogc:SortProperty",a[c],b);return b},SortProperty:function(a){var b=this.createElementNSPlus("ogc:SortProperty");this.writeNode("ogc:PropertyName",a,b);this.writeNode("ogc:SortOrder","DESC"==a.order?"DESC":"ASC",b);return b},SortOrder:function(a){return this.createElementNSPlus("ogc:SortOrder",{value:a})}},
2101 OpenLayers.Format.Filter.v1.prototype.writers.ogc),gml:OpenLayers.Format.GML.v3.prototype.writers.gml,feature:OpenLayers.Format.GML.v3.prototype.writers.feature},writeSpatial:function(a,b){var c=this.createElementNSPlus("ogc:"+b);this.writeNode("PropertyName",a,c);if(a.value instanceof OpenLayers.Filter.Function)this.writeNode("Function",a.value,c);else{var d;d=a.value instanceof OpenLayers.Geometry?this.writeNode("feature:_geometry",a.value).firstChild:this.writeNode("gml:Envelope",a.value);a.projection&&
2102 d.setAttribute("srsName",a.projection);c.appendChild(d)}return c},CLASS_NAME:"OpenLayers.Format.Filter.v1_1_0"});OpenLayers.Format.OWSCommon=OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC,{defaultVersion:"1.0.0",getVersion:function(a,b){var c=this.version;if(!c){var d=a.getAttribute("xmlns:ows");d&&"1.1"===d.substring(d.lastIndexOf("/")+1)&&(c="1.1.0");c||(c=this.defaultVersion)}return c},CLASS_NAME:"OpenLayers.Format.OWSCommon"});OpenLayers.Format.OWSCommon.v1=OpenLayers.Class(OpenLayers.Format.XML,{regExes:{trimSpace:/^\s*|\s*$/g,removeSpace:/\s*/g,splitSpace:/\s+/,trimComma:/\s*,\s*/g},read:function(a,b){OpenLayers.Util.applyDefaults(b,this.options);var c={};this.readChildNodes(a,c);return c},readers:{ows:{Exception:function(a,b){var c={code:a.getAttribute("exceptionCode"),locator:a.getAttribute("locator"),texts:[]};b.exceptions.push(c);this.readChildNodes(a,c)},ExceptionText:function(a,b){var c=this.getChildValue(a);b.texts.push(c)},
2103 ServiceIdentification:function(a,b){b.serviceIdentification={};this.readChildNodes(a,b.serviceIdentification)},Title:function(a,b){b.title=this.getChildValue(a)},Abstract:function(a,b){b["abstract"]=this.getChildValue(a)},Keywords:function(a,b){b.keywords={};this.readChildNodes(a,b.keywords)},Keyword:function(a,b){b[this.getChildValue(a)]=!0},ServiceType:function(a,b){b.serviceType={codeSpace:a.getAttribute("codeSpace"),value:this.getChildValue(a)}},ServiceTypeVersion:function(a,b){b.serviceTypeVersion=
2104 this.getChildValue(a)},Fees:function(a,b){b.fees=this.getChildValue(a)},AccessConstraints:function(a,b){b.accessConstraints=this.getChildValue(a)},ServiceProvider:function(a,b){b.serviceProvider={};this.readChildNodes(a,b.serviceProvider)},ProviderName:function(a,b){b.providerName=this.getChildValue(a)},ProviderSite:function(a,b){b.providerSite=this.getAttributeNS(a,this.namespaces.xlink,"href")},ServiceContact:function(a,b){b.serviceContact={};this.readChildNodes(a,b.serviceContact)},IndividualName:function(a,
2105 b){b.individualName=this.getChildValue(a)},PositionName:function(a,b){b.positionName=this.getChildValue(a)},ContactInfo:function(a,b){b.contactInfo={};this.readChildNodes(a,b.contactInfo)},Phone:function(a,b){b.phone={};this.readChildNodes(a,b.phone)},Voice:function(a,b){b.voice=this.getChildValue(a)},Address:function(a,b){b.address={};this.readChildNodes(a,b.address)},DeliveryPoint:function(a,b){b.deliveryPoint=this.getChildValue(a)},City:function(a,b){b.city=this.getChildValue(a)},AdministrativeArea:function(a,
2106 b){b.administrativeArea=this.getChildValue(a)},PostalCode:function(a,b){b.postalCode=this.getChildValue(a)},Country:function(a,b){b.country=this.getChildValue(a)},ElectronicMailAddress:function(a,b){b.electronicMailAddress=this.getChildValue(a)},Role:function(a,b){b.role=this.getChildValue(a)},OperationsMetadata:function(a,b){b.operationsMetadata={};this.readChildNodes(a,b.operationsMetadata)},Operation:function(a,b){var c=a.getAttribute("name");b[c]={};this.readChildNodes(a,b[c])},DCP:function(a,
2107 b){b.dcp={};this.readChildNodes(a,b.dcp)},HTTP:function(a,b){b.http={};this.readChildNodes(a,b.http)},Get:function(a,b){b.get||(b.get=[]);var c={url:this.getAttributeNS(a,this.namespaces.xlink,"href")};this.readChildNodes(a,c);b.get.push(c)},Post:function(a,b){b.post||(b.post=[]);var c={url:this.getAttributeNS(a,this.namespaces.xlink,"href")};this.readChildNodes(a,c);b.post.push(c)},Parameter:function(a,b){b.parameters||(b.parameters={});var c=a.getAttribute("name");b.parameters[c]={};this.readChildNodes(a,
2108 b.parameters[c])},Constraint:function(a,b){b.constraints||(b.constraints={});var c=a.getAttribute("name");b.constraints[c]={};this.readChildNodes(a,b.constraints[c])},Value:function(a,b){b[this.getChildValue(a)]=!0},OutputFormat:function(a,b){b.formats.push({value:this.getChildValue(a)});this.readChildNodes(a,b)},WGS84BoundingBox:function(a,b){var c={};c.crs=a.getAttribute("crs");b.BoundingBox?b.BoundingBox.push(c):(b.projection=c.crs,c=b);this.readChildNodes(a,c)},BoundingBox:function(a,b){this.readers.ows.WGS84BoundingBox.apply(this,
2109 [a,b])},LowerCorner:function(a,b){var c=this.getChildValue(a).replace(this.regExes.trimSpace,""),c=c.replace(this.regExes.trimComma,","),c=c.split(this.regExes.splitSpace);b.left=c[0];b.bottom=c[1]},UpperCorner:function(a,b){var c=this.getChildValue(a).replace(this.regExes.trimSpace,""),c=c.replace(this.regExes.trimComma,","),c=c.split(this.regExes.splitSpace);b.right=c[0];b.top=c[1];b.bounds=new OpenLayers.Bounds(b.left,b.bottom,b.right,b.top);delete b.left;delete b.bottom;delete b.right;delete b.top},
2110 Language:function(a,b){b.language=this.getChildValue(a)}}},writers:{ows:{BoundingBox:function(a,b){var c=this.createElementNSPlus(b||"ows:BoundingBox",{attributes:{crs:a.projection}});this.writeNode("ows:LowerCorner",a,c);this.writeNode("ows:UpperCorner",a,c);return c},LowerCorner:function(a){return this.createElementNSPlus("ows:LowerCorner",{value:a.bounds.left+" "+a.bounds.bottom})},UpperCorner:function(a){return this.createElementNSPlus("ows:UpperCorner",{value:a.bounds.right+" "+a.bounds.top})},
2111 Identifier:function(a){return this.createElementNSPlus("ows:Identifier",{value:a})},Title:function(a){return this.createElementNSPlus("ows:Title",{value:a})},Abstract:function(a){return this.createElementNSPlus("ows:Abstract",{value:a})},OutputFormat:function(a){return this.createElementNSPlus("ows:OutputFormat",{value:a})}}},CLASS_NAME:"OpenLayers.Format.OWSCommon.v1"});OpenLayers.Format.OWSCommon.v1_0_0=OpenLayers.Class(OpenLayers.Format.OWSCommon.v1,{namespaces:{ows:"http://www.opengis.net/ows",xlink:"http://www.w3.org/1999/xlink"},readers:{ows:OpenLayers.Util.applyDefaults({ExceptionReport:function(a,b){b.success=!1;b.exceptionReport={version:a.getAttribute("version"),language:a.getAttribute("language"),exceptions:[]};this.readChildNodes(a,b.exceptionReport)}},OpenLayers.Format.OWSCommon.v1.prototype.readers.ows)},writers:{ows:OpenLayers.Format.OWSCommon.v1.prototype.writers.ows},
2112 CLASS_NAME:"OpenLayers.Format.OWSCommon.v1_0_0"});OpenLayers.Format.WFST.v1_1_0=OpenLayers.Class(OpenLayers.Format.Filter.v1_1_0,OpenLayers.Format.WFST.v1,{version:"1.1.0",schemaLocations:{wfs:"http://schemas.opengis.net/wfs/1.1.0/wfs.xsd"},initialize:function(a){OpenLayers.Format.Filter.v1_1_0.prototype.initialize.apply(this,[a]);OpenLayers.Format.WFST.v1.prototype.initialize.apply(this,[a])},readNode:function(a,b,c){return OpenLayers.Format.GML.v3.prototype.readNode.apply(this,arguments)},readers:{wfs:OpenLayers.Util.applyDefaults({FeatureCollection:function(a,
2113 b){b.numberOfFeatures=parseInt(a.getAttribute("numberOfFeatures"));OpenLayers.Format.WFST.v1.prototype.readers.wfs.FeatureCollection.apply(this,arguments)},TransactionResponse:function(a,b){b.insertIds=[];b.success=!1;this.readChildNodes(a,b)},TransactionSummary:function(a,b){b.success=!0},InsertResults:function(a,b){this.readChildNodes(a,b)},Feature:function(a,b){var c={fids:[]};this.readChildNodes(a,c);b.insertIds.push(c.fids[0])}},OpenLayers.Format.WFST.v1.prototype.readers.wfs),gml:OpenLayers.Format.GML.v3.prototype.readers.gml,
2114 feature:OpenLayers.Format.GML.v3.prototype.readers.feature,ogc:OpenLayers.Format.Filter.v1_1_0.prototype.readers.ogc,ows:OpenLayers.Format.OWSCommon.v1_0_0.prototype.readers.ows},writers:{wfs:OpenLayers.Util.applyDefaults({GetFeature:function(a){var b=OpenLayers.Format.WFST.v1.prototype.writers.wfs.GetFeature.apply(this,arguments);a&&this.setAttributes(b,{resultType:a.resultType,startIndex:a.startIndex,count:a.count});return b},Query:function(a){a=OpenLayers.Util.extend({featureNS:this.featureNS,
2115 featurePrefix:this.featurePrefix,featureType:this.featureType,srsName:this.srsName},a);var b=a.featurePrefix,c=this.createElementNSPlus("wfs:Query",{attributes:{typeName:(b?b+":":"")+a.featureType,srsName:a.srsName}});a.featureNS&&c.setAttribute("xmlns:"+b,a.featureNS);if(a.propertyNames)for(var b=0,d=a.propertyNames.length;b<d;b++)this.writeNode("wfs:PropertyName",{property:a.propertyNames[b]},c);a.filter&&(OpenLayers.Format.WFST.v1_1_0.prototype.setFilterProperty.call(this,a.filter),this.writeNode("ogc:Filter",
2116 a.filter,c));return c},PropertyName:function(a){return this.createElementNSPlus("wfs:PropertyName",{value:a.property})}},OpenLayers.Format.WFST.v1.prototype.writers.wfs),gml:OpenLayers.Format.GML.v3.prototype.writers.gml,feature:OpenLayers.Format.GML.v3.prototype.writers.feature,ogc:OpenLayers.Format.Filter.v1_1_0.prototype.writers.ogc},CLASS_NAME:"OpenLayers.Format.WFST.v1_1_0"});OpenLayers.Protocol=OpenLayers.Class({format:null,options:null,autoDestroy:!0,defaultFilter:null,initialize:function(a){a=a||{};OpenLayers.Util.extend(this,a);this.options=a},mergeWithDefaultFilter:function(a){return a&&this.defaultFilter?new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.AND,filters:[this.defaultFilter,a]}):a||this.defaultFilter||void 0},destroy:function(){this.format=this.options=null},read:function(a){a=a||{};a.filter=this.mergeWithDefaultFilter(a.filter)},create:function(){},
2117 update:function(){},"delete":function(){},commit:function(){},abort:function(a){},createCallback:function(a,b,c){return OpenLayers.Function.bind(function(){a.apply(this,[b,c])},this)},CLASS_NAME:"OpenLayers.Protocol"});OpenLayers.Protocol.Response=OpenLayers.Class({code:null,requestType:null,last:!0,features:null,data:null,reqFeatures:null,priv:null,error:null,initialize:function(a){OpenLayers.Util.extend(this,a)},success:function(){return 0<this.code},CLASS_NAME:"OpenLayers.Protocol.Response"});
2118 OpenLayers.Protocol.Response.SUCCESS=1;OpenLayers.Protocol.Response.FAILURE=0;OpenLayers.Format.JSON=OpenLayers.Class(OpenLayers.Format,{indent:" ",space:" ",newline:"\n",level:0,pretty:!1,nativeJSON:function(){return!(!window.JSON||"function"!=typeof JSON.parse||"function"!=typeof JSON.stringify)}(),read:function(a,b){var c;if(this.nativeJSON)c=JSON.parse(a,b);else try{if(/^[\],:{}\s]*$/.test(a.replace(/\\["\\\/bfnrtu]/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))&&(c=eval("("+a+")"),"function"===
2119 typeof b)){var d=function(a,c){if(c&&"object"===typeof c)for(var e in c)c.hasOwnProperty(e)&&(c[e]=d(e,c[e]));return b(a,c)};c=d("",c)}}catch(e){}this.keepData&&(this.data=c);return c},write:function(a,b){this.pretty=!!b;var c=null,d=typeof a;if(this.serialize[d])try{c=!this.pretty&&this.nativeJSON?JSON.stringify(a):this.serialize[d].apply(this,[a])}catch(e){OpenLayers.Console.error("Trouble serializing: "+e)}return c},writeIndent:function(){var a=[];if(this.pretty)for(var b=0;b<this.level;++b)a.push(this.indent);
2120 return a.join("")},writeNewline:function(){return this.pretty?this.newline:""},writeSpace:function(){return this.pretty?this.space:""},serialize:{object:function(a){if(null==a)return"null";if(a.constructor==Date)return this.serialize.date.apply(this,[a]);if(a.constructor==Array)return this.serialize.array.apply(this,[a]);var b=["{"];this.level+=1;var c,d,e,f=!1;for(c in a)a.hasOwnProperty(c)&&(d=OpenLayers.Format.JSON.prototype.write.apply(this,[c,this.pretty]),e=OpenLayers.Format.JSON.prototype.write.apply(this,
2121 [a[c],this.pretty]),null!=d&&null!=e&&(f&&b.push(","),b.push(this.writeNewline(),this.writeIndent(),d,":",this.writeSpace(),e),f=!0));this.level-=1;b.push(this.writeNewline(),this.writeIndent(),"}");return b.join("")},array:function(a){var b,c=["["];this.level+=1;for(var d=0,e=a.length;d<e;++d)b=OpenLayers.Format.JSON.prototype.write.apply(this,[a[d],this.pretty]),null!=b&&(0<d&&c.push(","),c.push(this.writeNewline(),this.writeIndent(),b));this.level-=1;c.push(this.writeNewline(),this.writeIndent(),
2122 "]");return c.join("")},string:function(a){var b={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};return/["\\\x00-\x1f]/.test(a)?'"'+a.replace(/([\x00-\x1f\\"])/g,function(a,d){var e=b[d];if(e)return e;e=d.charCodeAt();return"\\u00"+Math.floor(e/16).toString(16)+(e%16).toString(16)})+'"':'"'+a+'"'},number:function(a){return isFinite(a)?String(a):"null"},"boolean":function(a){return String(a)},date:function(a){function b(a){return 10>a?"0"+a:a}return'"'+a.getFullYear()+
2123 "-"+b(a.getMonth()+1)+"-"+b(a.getDate())+"T"+b(a.getHours())+":"+b(a.getMinutes())+":"+b(a.getSeconds())+'"'}},CLASS_NAME:"OpenLayers.Format.JSON"});OpenLayers.Format.GeoJSON=OpenLayers.Class(OpenLayers.Format.JSON,{ignoreExtraDims:!1,read:function(a,b,c){b=b?b:"FeatureCollection";var d=null,e=null,e="string"==typeof a?OpenLayers.Format.JSON.prototype.read.apply(this,[a,c]):a;if(!e)OpenLayers.Console.error("Bad JSON: "+a);else if("string"!=typeof e.type)OpenLayers.Console.error("Bad GeoJSON - no type: "+a);else if(this.isValidType(e,b))switch(b){case "Geometry":try{d=this.parseGeometry(e)}catch(f){OpenLayers.Console.error(f)}break;case "Feature":try{d=
2124 this.parseFeature(e),d.type="Feature"}catch(g){OpenLayers.Console.error(g)}break;case "FeatureCollection":switch(d=[],e.type){case "Feature":try{d.push(this.parseFeature(e))}catch(h){d=null,OpenLayers.Console.error(h)}break;case "FeatureCollection":a=0;for(b=e.features.length;a<b;++a)try{d.push(this.parseFeature(e.features[a]))}catch(k){d=null,OpenLayers.Console.error(k)}break;default:try{var l=this.parseGeometry(e);d.push(new OpenLayers.Feature.Vector(l))}catch(m){d=null,OpenLayers.Console.error(m)}}}return d},
2125 isValidType:function(a,b){var c=!1;switch(b){case "Geometry":-1==OpenLayers.Util.indexOf("Point MultiPoint LineString MultiLineString Polygon MultiPolygon Box GeometryCollection".split(" "),a.type)?OpenLayers.Console.error("Unsupported geometry type: "+a.type):c=!0;break;case "FeatureCollection":c=!0;break;default:a.type==b?c=!0:OpenLayers.Console.error("Cannot convert types from "+a.type+" to "+b)}return c},parseFeature:function(a){var b,c,d;c=a.properties?a.properties:{};d=a.geometry&&a.geometry.bbox||
2126 a.bbox;try{b=this.parseGeometry(a.geometry)}catch(e){throw e;}b=new OpenLayers.Feature.Vector(b,c);d&&(b.bounds=OpenLayers.Bounds.fromArray(d));a.id&&(b.fid=a.id);return b},parseGeometry:function(a){if(null==a)return null;var b,c=!1;if("GeometryCollection"==a.type){if(!OpenLayers.Util.isArray(a.geometries))throw"GeometryCollection must have geometries array: "+a;b=a.geometries.length;for(var c=Array(b),d=0;d<b;++d)c[d]=this.parseGeometry.apply(this,[a.geometries[d]]);b=new OpenLayers.Geometry.Collection(c);
2127 c=!0}else{if(!OpenLayers.Util.isArray(a.coordinates))throw"Geometry must have coordinates array: "+a;if(!this.parseCoords[a.type.toLowerCase()])throw"Unsupported geometry type: "+a.type;try{b=this.parseCoords[a.type.toLowerCase()].apply(this,[a.coordinates])}catch(e){throw e;}}this.internalProjection&&(this.externalProjection&&!c)&&b.transform(this.externalProjection,this.internalProjection);return b},parseCoords:{point:function(a){if(!1==this.ignoreExtraDims&&2!=a.length)throw"Only 2D points are supported: "+
2128 a;return new OpenLayers.Geometry.Point(a[0],a[1])},multipoint:function(a){for(var b=[],c=null,d=0,e=a.length;d<e;++d){try{c=this.parseCoords.point.apply(this,[a[d]])}catch(f){throw f;}b.push(c)}return new OpenLayers.Geometry.MultiPoint(b)},linestring:function(a){for(var b=[],c=null,d=0,e=a.length;d<e;++d){try{c=this.parseCoords.point.apply(this,[a[d]])}catch(f){throw f;}b.push(c)}return new OpenLayers.Geometry.LineString(b)},multilinestring:function(a){for(var b=[],c=null,d=0,e=a.length;d<e;++d){try{c=
2129 this.parseCoords.linestring.apply(this,[a[d]])}catch(f){throw f;}b.push(c)}return new OpenLayers.Geometry.MultiLineString(b)},polygon:function(a){for(var b=[],c,d,e=0,f=a.length;e<f;++e){try{d=this.parseCoords.linestring.apply(this,[a[e]])}catch(g){throw g;}c=new OpenLayers.Geometry.LinearRing(d.components);b.push(c)}return new OpenLayers.Geometry.Polygon(b)},multipolygon:function(a){for(var b=[],c=null,d=0,e=a.length;d<e;++d){try{c=this.parseCoords.polygon.apply(this,[a[d]])}catch(f){throw f;}b.push(c)}return new OpenLayers.Geometry.MultiPolygon(b)},
2130 box:function(a){if(2!=a.length)throw"GeoJSON box coordinates must have 2 elements";return new OpenLayers.Geometry.Polygon([new OpenLayers.Geometry.LinearRing([new OpenLayers.Geometry.Point(a[0][0],a[0][1]),new OpenLayers.Geometry.Point(a[1][0],a[0][1]),new OpenLayers.Geometry.Point(a[1][0],a[1][1]),new OpenLayers.Geometry.Point(a[0][0],a[1][1]),new OpenLayers.Geometry.Point(a[0][0],a[0][1])])])}},write:function(a,b){var c={type:null};if(OpenLayers.Util.isArray(a)){c.type="FeatureCollection";var d=
2131 a.length;c.features=Array(d);for(var e=0;e<d;++e){var f=a[e];if(!f instanceof OpenLayers.Feature.Vector)throw"FeatureCollection only supports collections of features: "+f;c.features[e]=this.extract.feature.apply(this,[f])}}else 0==a.CLASS_NAME.indexOf("OpenLayers.Geometry")?c=this.extract.geometry.apply(this,[a]):a instanceof OpenLayers.Feature.Vector&&(c=this.extract.feature.apply(this,[a]),a.layer&&a.layer.projection&&(c.crs=this.createCRSObject(a)));return OpenLayers.Format.JSON.prototype.write.apply(this,
2132 [c,b])},createCRSObject:function(a){a=a.layer.projection.toString();var b={};a.match(/epsg:/i)&&(a=parseInt(a.substring(a.indexOf(":")+1)),b=4326==a?{type:"name",properties:{name:"urn:ogc:def:crs:OGC:1.3:CRS84"}}:{type:"name",properties:{name:"EPSG:"+a}});return b},extract:{feature:function(a){var b=this.extract.geometry.apply(this,[a.geometry]),b={type:"Feature",properties:a.attributes,geometry:b};null!=a.fid&&(b.id=a.fid);return b},geometry:function(a){if(null==a)return null;this.internalProjection&&
2133 this.externalProjection&&(a=a.clone(),a.transform(this.internalProjection,this.externalProjection));var b=a.CLASS_NAME.split(".")[2];a=this.extract[b.toLowerCase()].apply(this,[a]);return"Collection"==b?{type:"GeometryCollection",geometries:a}:{type:b,coordinates:a}},point:function(a){return[a.x,a.y]},multipoint:function(a){for(var b=[],c=0,d=a.components.length;c<d;++c)b.push(this.extract.point.apply(this,[a.components[c]]));return b},linestring:function(a){for(var b=[],c=0,d=a.components.length;c<
2134 d;++c)b.push(this.extract.point.apply(this,[a.components[c]]));return b},multilinestring:function(a){for(var b=[],c=0,d=a.components.length;c<d;++c)b.push(this.extract.linestring.apply(this,[a.components[c]]));return b},polygon:function(a){for(var b=[],c=0,d=a.components.length;c<d;++c)b.push(this.extract.linestring.apply(this,[a.components[c]]));return b},multipolygon:function(a){for(var b=[],c=0,d=a.components.length;c<d;++c)b.push(this.extract.polygon.apply(this,[a.components[c]]));return b},collection:function(a){for(var b=
2135 a.components.length,c=Array(b),d=0;d<b;++d)c[d]=this.extract.geometry.apply(this,[a.components[d]]);return c}},CLASS_NAME:"OpenLayers.Format.GeoJSON"});OpenLayers.Protocol.Script=OpenLayers.Class(OpenLayers.Protocol,{url:null,params:null,callback:null,callbackTemplate:"OpenLayers.Protocol.Script.registry.${id}",callbackKey:"callback",callbackPrefix:"",scope:null,format:null,pendingRequests:null,srsInBBOX:!1,initialize:function(a){a=a||{};this.params={};this.pendingRequests={};OpenLayers.Protocol.prototype.initialize.apply(this,arguments);this.format||(this.format=new OpenLayers.Format.GeoJSON);if(!this.filterToParams&&OpenLayers.Format.QueryStringFilter){var b=
2136 new OpenLayers.Format.QueryStringFilter({srsInBBOX:this.srsInBBOX});this.filterToParams=function(a,d){return b.write(a,d)}}},read:function(a){OpenLayers.Protocol.prototype.read.apply(this,arguments);a=OpenLayers.Util.applyDefaults(a,this.options);a.params=OpenLayers.Util.applyDefaults(a.params,this.options.params);a.filter&&this.filterToParams&&(a.params=this.filterToParams(a.filter,a.params));var b=new OpenLayers.Protocol.Response({requestType:"read"}),c=this.createRequest(a.url,a.params,OpenLayers.Function.bind(function(c){b.data=
2137 c;this.handleRead(b,a)},this));b.priv=c;return b},createRequest:function(a,b,c){c=OpenLayers.Protocol.Script.register(c);var d=OpenLayers.String.format(this.callbackTemplate,{id:c});b=OpenLayers.Util.extend({},b);b[this.callbackKey]=this.callbackPrefix+d;a=OpenLayers.Util.urlAppend(a,OpenLayers.Util.getParameterString(b));b=document.createElement("script");b.type="text/javascript";b.src=a;b.id="OpenLayers_Protocol_Script_"+c;this.pendingRequests[b.id]=b;document.getElementsByTagName("head")[0].appendChild(b);
2138 return b},destroyRequest:function(a){OpenLayers.Protocol.Script.unregister(a.id.split("_").pop());delete this.pendingRequests[a.id];a.parentNode&&a.parentNode.removeChild(a)},handleRead:function(a,b){this.handleResponse(a,b)},handleResponse:function(a,b){b.callback&&(a.data?(a.features=this.parseFeatures(a.data),a.code=OpenLayers.Protocol.Response.SUCCESS):a.code=OpenLayers.Protocol.Response.FAILURE,this.destroyRequest(a.priv),b.callback.call(b.scope,a))},parseFeatures:function(a){return this.format.read(a)},
2139 abort:function(a){if(a)this.destroyRequest(a.priv);else for(var b in this.pendingRequests)this.destroyRequest(this.pendingRequests[b])},destroy:function(){this.abort();delete this.params;delete this.format;OpenLayers.Protocol.prototype.destroy.apply(this)},CLASS_NAME:"OpenLayers.Protocol.Script"});(function(){var a=OpenLayers.Protocol.Script,b=0;a.registry={};a.register=function(c){var d="c"+ ++b;a.registry[d]=function(){c.apply(this,arguments)};return d};a.unregister=function(b){delete a.registry[b]}})();OpenLayers.Format.EncodedPolyline=OpenLayers.Class(OpenLayers.Format,{geometryType:"linestring",initialize:function(a){OpenLayers.Format.prototype.initialize.apply(this,[a])},read:function(a){var b;if("linestring"==this.geometryType)b=OpenLayers.Geometry.LineString;else if("linearring"==this.geometryType)b=OpenLayers.Geometry.LinearRing;else if("multipoint"==this.geometryType)b=OpenLayers.Geometry.MultiPoint;else if("point"!=this.geometryType&&"polygon"!=this.geometryType)return null;a=this.decodeDeltas(a,
2140 2);for(var c=a.length,d=[],e=0;e+1<c;){var f=a[e++],g=a[e++];d.push(new OpenLayers.Geometry.Point(g,f))}return"point"==this.geometryType?new OpenLayers.Feature.Vector(d[0]):"polygon"==this.geometryType?new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([new OpenLayers.Geometry.LinearRing(d)])):new OpenLayers.Feature.Vector(new b(d))},decode:function(a,b,c){a=this.decodeDeltas(a,b,c||1E5);c=a.length;for(var d=[],e=0;e+(b-1)<c;){for(var f=[],g=0;g<b;++g)f.push(a[e++]);d.push(f)}return d},
2141 write:function(a){a=(a.constructor==Array?a[0]:a).geometry;var b=a.CLASS_NAME.split(".")[2].toLowerCase();if("point"==b)a=Array(a);else if("linestring"==b||"linearring"==b||"multipoint"==b)a=a.components;else if("polygon"==b)a=a.components[0].components;else return null;for(var b=[],c=a.length,d=0;d<c;++d){var e=a[d];b.push(e.y);b.push(e.x)}return this.encodeDeltas(b,2)},encode:function(a,b,c){c=c||1E5;for(var d=[],e=a.length,f=0;f<e;++f)for(var g=a[f],h=0;h<b;++h)d.push(g[h]);return this.encodeDeltas(d,
2142 b,c)},encodeDeltas:function(a,b,c){var d,e=Array(b);for(d=0;d<b;++d)e[d]=0;for(var f=a.length,g=0;g<f;)for(d=0;d<b;++d,++g){var h=a[g],k=h-e[d];e[d]=h;a[g]=k}return this.encodeFloats(a,c||1E5)},decodeDeltas:function(a,b,c){var d,e=Array(b);for(d=0;d<b;++d)e[d]=0;a=this.decodeFloats(a,c||1E5);c=a.length;for(var f=0;f<c;)for(d=0;d<b;++d,++f)e[d]+=a[f],a[f]=e[d];return a},encodeFloats:function(a,b){for(var c=b||1E5,d=a.length,e=0;e<d;++e)a[e]=Math.round(a[e]*c);return this.encodeSignedIntegers(a)},decodeFloats:function(a,
2143 b){for(var c=b||1E5,d=this.decodeSignedIntegers(a),e=d.length,f=0;f<e;++f)d[f]/=c;return d},encodeSignedIntegers:function(a){for(var b=a.length,c=0;c<b;++c){var d=a[c],e=d<<1;0>d&&(e=~e);a[c]=e}return this.encodeUnsignedIntegers(a)},decodeSignedIntegers:function(a){a=this.decodeUnsignedIntegers(a);for(var b=a.length,c=0;c<b;++c){var d=a[c];a[c]=d&1?~(d>>1):d>>1}return a},encodeUnsignedIntegers:function(a){for(var b="",c=a.length,d=0;d<c;++d)b+=this.encodeUnsignedInteger(a[d]);return b},decodeUnsignedIntegers:function(a){for(var b=
2144 [],c=0,d=0,e=a.length,f=0;f<e;++f){var g=a.charCodeAt(f)-63,c=c|(g&31)<<d;32>g?(b.push(c),d=c=0):d+=5}return b},encodeFloat:function(a,b){a=Math.round(a*(b||1E5));return this.encodeSignedInteger(a)},decodeFloat:function(a,b){return this.decodeSignedInteger(a)/(b||1E5)},encodeSignedInteger:function(a){var b=a<<1;0>a&&(b=~b);return this.encodeUnsignedInteger(b)},decodeSignedInteger:function(a){a=this.decodeUnsignedInteger(a);return a&1?~(a>>1):a>>1},encodeUnsignedInteger:function(a){for(var b,c="";32<=
2145 a;)b=(32|a&31)+63,c+=String.fromCharCode(b),a>>=5;return c+=String.fromCharCode(a+63)},decodeUnsignedInteger:function(a){for(var b=0,c=0,d=a.length,e=0;e<d;++e){var f=a.charCodeAt(e)-63,b=b|(f&31)<<c;if(32>f)break;c+=5}return b},CLASS_NAME:"OpenLayers.Format.EncodedPolyline"});OpenLayers.Control.Panel=OpenLayers.Class(OpenLayers.Control,{controls:null,autoActivate:!0,defaultControl:null,saveState:!1,allowDepress:!1,activeState:null,initialize:function(a){OpenLayers.Control.prototype.initialize.apply(this,[a]);this.controls=[];this.activeState={}},destroy:function(){this.map&&this.map.events.unregister("buttonclick",this,this.onButtonClick);OpenLayers.Control.prototype.destroy.apply(this,arguments);for(var a,b=this.controls.length-1;0<=b;b--)a=this.controls[b],a.events&&
2146 a.events.un({activate:this.iconOn,deactivate:this.iconOff}),a.panel_div=null;this.activeState=null},activate:function(){if(OpenLayers.Control.prototype.activate.apply(this,arguments)){for(var a,b=0,c=this.controls.length;b<c;b++)a=this.controls[b],(a===this.defaultControl||this.saveState&&this.activeState[a.id])&&a.activate();!0===this.saveState&&(this.defaultControl=null);this.redraw();return!0}return!1},deactivate:function(){if(OpenLayers.Control.prototype.deactivate.apply(this,arguments)){for(var a,
2147 b=0,c=this.controls.length;b<c;b++)a=this.controls[b],this.activeState[a.id]=a.deactivate();this.redraw();return!0}return!1},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);this.outsideViewport?(this.events.attachToElement(this.div),this.events.register("buttonclick",this,this.onButtonClick)):this.map.events.register("buttonclick",this,this.onButtonClick);this.addControlsToMap(this.controls);return this.div},redraw:function(){for(var a=this.div.childNodes.length-1;0<=a;a--)this.div.removeChild(this.div.childNodes[a]);
2148 this.div.innerHTML="";if(this.active)for(var a=0,b=this.controls.length;a<b;a++)this.div.appendChild(this.controls[a].panel_div)},activateControl:function(a){if(!this.active)return!1;if(a.type==OpenLayers.Control.TYPE_BUTTON)a.trigger();else if(a.type==OpenLayers.Control.TYPE_TOGGLE)a.active?a.deactivate():a.activate();else if(this.allowDepress&&a.active)a.deactivate();else{for(var b,c=0,d=this.controls.length;c<d;c++)b=this.controls[c],b==a||b.type!==OpenLayers.Control.TYPE_TOOL&&null!=b.type||b.deactivate();
2149 a.activate()}},addControls:function(a){OpenLayers.Util.isArray(a)||(a=[a]);this.controls=this.controls.concat(a);for(var b=0,c=a.length;b<c;b++){var d=a[b],e=this.createControlMarkup(d);OpenLayers.Element.addClass(e,d.displayClass+"ItemInactive");OpenLayers.Element.addClass(e,"olButton");""==d.title||e.title||(e.title=d.title);d.panel_div=e}this.map&&(this.addControlsToMap(a),this.redraw())},createControlMarkup:function(a){return document.createElement("div")},addControlsToMap:function(a){for(var b,
2150 c=0,d=a.length;c<d;c++)b=a[c],!0===b.autoActivate?(b.autoActivate=!1,this.map.addControl(b),b.autoActivate=!0):(this.map.addControl(b),b.deactivate()),b.events.on({activate:this.iconOn,deactivate:this.iconOff})},iconOn:function(){var a=this.panel_div;a.className=a.className.replace(RegExp("\\b("+this.displayClass+"Item)Inactive\\b"),"$1Active")},iconOff:function(){var a=this.panel_div;a.className=a.className.replace(RegExp("\\b("+this.displayClass+"Item)Active\\b"),"$1Inactive")},onButtonClick:function(a){var b=
2151 this.controls;a=a.buttonElement;for(var c=b.length-1;0<=c;--c)if(b[c].panel_div===a){this.activateControl(b[c]);break}},getControlsBy:function(a,b){var c="function"==typeof b.test;return OpenLayers.Array.filter(this.controls,function(d){return d[a]==b||c&&b.test(d[a])})},getControlsByName:function(a){return this.getControlsBy("name",a)},getControlsByClass:function(a){return this.getControlsBy("CLASS_NAME",a)},CLASS_NAME:"OpenLayers.Control.Panel"});OpenLayers.Control.Button=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_BUTTON,trigger:function(){},CLASS_NAME:"OpenLayers.Control.Button"});OpenLayers.Control.ZoomIn=OpenLayers.Class(OpenLayers.Control.Button,{trigger:function(){this.map&&this.map.zoomIn()},CLASS_NAME:"OpenLayers.Control.ZoomIn"});OpenLayers.Control.ZoomOut=OpenLayers.Class(OpenLayers.Control.Button,{trigger:function(){this.map&&this.map.zoomOut()},CLASS_NAME:"OpenLayers.Control.ZoomOut"});OpenLayers.Control.ZoomToMaxExtent=OpenLayers.Class(OpenLayers.Control.Button,{trigger:function(){this.map&&this.map.zoomToMaxExtent()},CLASS_NAME:"OpenLayers.Control.ZoomToMaxExtent"});OpenLayers.Control.ZoomPanel=OpenLayers.Class(OpenLayers.Control.Panel,{initialize:function(a){OpenLayers.Control.Panel.prototype.initialize.apply(this,[a]);this.addControls([new OpenLayers.Control.ZoomIn,new OpenLayers.Control.ZoomToMaxExtent,new OpenLayers.Control.ZoomOut])},CLASS_NAME:"OpenLayers.Control.ZoomPanel"});OpenLayers.Layer.HTTPRequest=OpenLayers.Class(OpenLayers.Layer,{URL_HASH_FACTOR:(Math.sqrt(5)-1)/2,url:null,params:null,reproject:!1,initialize:function(a,b,c,d){OpenLayers.Layer.prototype.initialize.apply(this,[a,d]);this.url=b;this.params||(this.params=OpenLayers.Util.extend({},c))},destroy:function(){this.params=this.url=null;OpenLayers.Layer.prototype.destroy.apply(this,arguments)},clone:function(a){null==a&&(a=new OpenLayers.Layer.HTTPRequest(this.name,this.url,this.params,this.getOptions()));
2152 return a=OpenLayers.Layer.prototype.clone.apply(this,[a])},setUrl:function(a){this.url=a},mergeNewParams:function(a){this.params=OpenLayers.Util.extend(this.params,a);a=this.redraw();null!=this.map&&this.map.events.triggerEvent("changelayer",{layer:this,property:"params"});return a},redraw:function(a){return a?this.mergeNewParams({_olSalt:Math.random()}):OpenLayers.Layer.prototype.redraw.apply(this,[])},selectUrl:function(a,b){for(var c=1,d=0,e=a.length;d<e;d++)c*=a.charCodeAt(d)*this.URL_HASH_FACTOR,
2153 c-=Math.floor(c);return b[Math.floor(c*b.length)]},getFullRequestString:function(a,b){var c=b||this.url,d=OpenLayers.Util.extend({},this.params),d=OpenLayers.Util.extend(d,a),e=OpenLayers.Util.getParameterString(d);OpenLayers.Util.isArray(c)&&(c=this.selectUrl(e,c));var e=OpenLayers.Util.upperCaseObject(OpenLayers.Util.getParameters(c)),f;for(f in d)f.toUpperCase()in e&&delete d[f];e=OpenLayers.Util.getParameterString(d);return OpenLayers.Util.urlAppend(c,e)},CLASS_NAME:"OpenLayers.Layer.HTTPRequest"});OpenLayers.Tile=OpenLayers.Class({events:null,eventListeners:null,id:null,layer:null,url:null,bounds:null,size:null,position:null,isLoading:!1,initialize:function(a,b,c,d,e,f){this.layer=a;this.position=b.clone();this.setBounds(c);this.url=d;e&&(this.size=e.clone());this.id=OpenLayers.Util.createUniqueID("Tile_");OpenLayers.Util.extend(this,f);this.events=new OpenLayers.Events(this);if(this.eventListeners instanceof Object)this.events.on(this.eventListeners)},unload:function(){this.isLoading&&(this.isLoading=
2154 !1,this.events.triggerEvent("unload"))},destroy:function(){this.position=this.size=this.bounds=this.layer=null;this.eventListeners&&this.events.un(this.eventListeners);this.events.destroy();this.events=this.eventListeners=null},draw:function(a){a||this.clear();var b=this.shouldDraw();b&&(!a&&!1===this.events.triggerEvent("beforedraw"))&&(b=null);return b},shouldDraw:function(){var a=!1,b=this.layer.maxExtent;if(b){var c=this.layer.map,c=c.baseLayer.wrapDateLine&&c.getMaxExtent();this.bounds.intersectsBounds(b,
2155 {inclusive:!1,worldBounds:c})&&(a=!0)}return a||this.layer.displayOutsideMaxExtent},setBounds:function(a){a=a.clone();if(this.layer.map.baseLayer.wrapDateLine){var b=this.layer.map.getMaxExtent(),c=this.layer.map.getResolution();a=a.wrapDateLine(b,{leftTolerance:c,rightTolerance:c})}this.bounds=a},moveTo:function(a,b,c){null==c&&(c=!0);this.setBounds(a);this.position=b.clone();c&&this.draw()},clear:function(a){},CLASS_NAME:"OpenLayers.Tile"});OpenLayers.Tile.Image=OpenLayers.Class(OpenLayers.Tile,{url:null,imgDiv:null,frame:null,imageReloadAttempts:null,layerAlphaHack:null,asyncRequestId:null,maxGetUrlLength:null,canvasContext:null,crossOriginKeyword:null,initialize:function(a,b,c,d,e,f){OpenLayers.Tile.prototype.initialize.apply(this,arguments);this.url=d;this.layerAlphaHack=this.layer.alpha&&OpenLayers.Util.alphaHack();if(null!=this.maxGetUrlLength||this.layer.gutter||this.layerAlphaHack)this.frame=document.createElement("div"),this.frame.style.position=
2156 "absolute",this.frame.style.overflow="hidden";null!=this.maxGetUrlLength&&OpenLayers.Util.extend(this,OpenLayers.Tile.Image.IFrame)},destroy:function(){this.imgDiv&&(this.clear(),this.frame=this.imgDiv=null);this.asyncRequestId=null;OpenLayers.Tile.prototype.destroy.apply(this,arguments)},draw:function(){var a=OpenLayers.Tile.prototype.draw.apply(this,arguments);a?(this.layer!=this.layer.map.baseLayer&&this.layer.reproject&&(this.bounds=this.getBoundsFromBaseLayer(this.position)),this.isLoading?this._loadEvent=
2157 "reload":(this.isLoading=!0,this._loadEvent="loadstart"),this.renderTile(),this.positionTile()):!1===a&&this.unload();return a},renderTile:function(){if(this.layer.async){var a=this.asyncRequestId=(this.asyncRequestId||0)+1;this.layer.getURLasync(this.bounds,function(b){a==this.asyncRequestId&&(this.url=b,this.initImage())},this)}else this.url=this.layer.getURL(this.bounds),this.initImage()},positionTile:function(){var a=this.getTile().style,b=this.frame?this.size:this.layer.getImageSize(this.bounds),
2158 c=1;this.layer instanceof OpenLayers.Layer.Grid&&(c=this.layer.getServerResolution()/this.layer.map.getResolution());a.left=this.position.x+"px";a.top=this.position.y+"px";a.width=Math.round(c*b.w)+"px";a.height=Math.round(c*b.h)+"px"},clear:function(){OpenLayers.Tile.prototype.clear.apply(this,arguments);var a=this.imgDiv;if(a){var b=this.getTile();b.parentNode===this.layer.div&&this.layer.div.removeChild(b);this.setImgSrc();!0===this.layerAlphaHack&&(a.style.filter="");OpenLayers.Element.removeClass(a,
2159 "olImageLoadError")}this.canvasContext=null},getImage:function(){if(!this.imgDiv){this.imgDiv=OpenLayers.Tile.Image.IMAGE.cloneNode(!1);var a=this.imgDiv.style;if(this.frame){var b=0,c=0;this.layer.gutter&&(b=100*(this.layer.gutter/this.layer.tileSize.w),c=100*(this.layer.gutter/this.layer.tileSize.h));a.left=-b+"%";a.top=-c+"%";a.width=2*b+100+"%";a.height=2*c+100+"%"}a.visibility="hidden";a.opacity=0;1>this.layer.opacity&&(a.filter="alpha(opacity="+100*this.layer.opacity+")");a.position="absolute";
2160 this.layerAlphaHack&&(a.paddingTop=a.height,a.height="0",a.width="100%");this.frame&&this.frame.appendChild(this.imgDiv)}return this.imgDiv},setImage:function(a){this.imgDiv=a},initImage:function(){if(this.url||this.imgDiv){this.events.triggerEvent("beforeload");this.layer.div.appendChild(this.getTile());this.events.triggerEvent(this._loadEvent);var a=this.getImage(),b=a.getAttribute("src")||"";this.url&&OpenLayers.Util.isEquivalentUrl(b,this.url)?this._loadTimeout=window.setTimeout(OpenLayers.Function.bind(this.onImageLoad,
2161 this),0):(this.stopLoading(),this.crossOriginKeyword&&a.removeAttribute("crossorigin"),OpenLayers.Event.observe(a,"load",OpenLayers.Function.bind(this.onImageLoad,this)),OpenLayers.Event.observe(a,"error",OpenLayers.Function.bind(this.onImageError,this)),this.imageReloadAttempts=0,this.setImgSrc(this.url))}else this.isLoading=!1},setImgSrc:function(a){var b=this.imgDiv;a?(b.style.visibility="hidden",b.style.opacity=0,this.crossOriginKeyword&&("data:"!==a.substr(0,5)?b.setAttribute("crossorigin",this.crossOriginKeyword):
2162 b.removeAttribute("crossorigin")),b.src=a):(this.stopLoading(),this.imgDiv=null,b.parentNode&&b.parentNode.removeChild(b))},getTile:function(){return this.frame?this.frame:this.getImage()},createBackBuffer:function(){if(this.imgDiv&&!this.isLoading){var a;this.frame?(a=this.frame.cloneNode(!1),a.appendChild(this.imgDiv)):a=this.imgDiv;this.imgDiv=null;return a}},onImageLoad:function(){var a=this.imgDiv;this.stopLoading();a.style.visibility="inherit";a.style.opacity=this.layer.opacity;this.isLoading=
2163 !1;this.canvasContext=null;this.events.triggerEvent("loadend");!0===this.layerAlphaHack&&(a.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+a.src+"', sizingMethod='scale')")},onImageError:function(){var a=this.imgDiv;null!=a.src&&(this.imageReloadAttempts++,this.imageReloadAttempts<=OpenLayers.IMAGE_RELOAD_ATTEMPTS?this.setImgSrc(this.layer.getURL(this.bounds)):(OpenLayers.Element.addClass(a,"olImageLoadError"),this.events.triggerEvent("loaderror"),this.onImageLoad()))},stopLoading:function(){OpenLayers.Event.stopObservingElement(this.imgDiv);
2164 window.clearTimeout(this._loadTimeout);delete this._loadTimeout},getCanvasContext:function(){if(OpenLayers.CANVAS_SUPPORTED&&this.imgDiv&&!this.isLoading){if(!this.canvasContext){var a=document.createElement("canvas");a.width=this.size.w;a.height=this.size.h;this.canvasContext=a.getContext("2d");this.canvasContext.drawImage(this.imgDiv,0,0)}return this.canvasContext}},CLASS_NAME:"OpenLayers.Tile.Image"});
2165 OpenLayers.Tile.Image.IMAGE=function(){var a=new Image;a.className="olTileImage";a.galleryImg="no";return a}();OpenLayers.Layer.Grid=OpenLayers.Class(OpenLayers.Layer.HTTPRequest,{tileSize:null,tileOriginCorner:"bl",tileOrigin:null,tileOptions:null,tileClass:OpenLayers.Tile.Image,grid:null,singleTile:!1,ratio:1.5,buffer:0,transitionEffect:"resize",numLoadingTiles:0,serverResolutions:null,loading:!1,backBuffer:null,gridResolution:null,backBufferResolution:null,backBufferLonLat:null,backBufferTimerId:null,removeBackBufferDelay:null,className:null,gridLayout:null,rowSign:null,transitionendEvents:["transitionend",
2166 "webkitTransitionEnd","otransitionend","oTransitionEnd"],initialize:function(a,b,c,d){OpenLayers.Layer.HTTPRequest.prototype.initialize.apply(this,arguments);this.grid=[];this._removeBackBuffer=OpenLayers.Function.bind(this.removeBackBuffer,this);this.initProperties();this.rowSign="t"===this.tileOriginCorner.substr(0,1)?1:-1},initProperties:function(){void 0===this.options.removeBackBufferDelay&&(this.removeBackBufferDelay=this.singleTile?0:2500);void 0===this.options.className&&(this.className=this.singleTile?
2167 "olLayerGridSingleTile":"olLayerGrid")},setMap:function(a){OpenLayers.Layer.HTTPRequest.prototype.setMap.call(this,a);OpenLayers.Element.addClass(this.div,this.className)},removeMap:function(a){this.removeBackBuffer()},destroy:function(){this.removeBackBuffer();this.clearGrid();this.tileSize=this.grid=null;OpenLayers.Layer.HTTPRequest.prototype.destroy.apply(this,arguments)},clearGrid:function(){if(this.grid){for(var a=0,b=this.grid.length;a<b;a++)for(var c=this.grid[a],d=0,e=c.length;d<e;d++)this.destroyTile(c[d]);
2168 this.grid=[];this.gridLayout=this.gridResolution=null}},addOptions:function(a,b){var c=void 0!==a.singleTile&&a.singleTile!==this.singleTile;OpenLayers.Layer.HTTPRequest.prototype.addOptions.apply(this,arguments);this.map&&c&&(this.initProperties(),this.clearGrid(),this.tileSize=this.options.tileSize,this.setTileSize(),this.moveTo(null,!0))},clone:function(a){null==a&&(a=new OpenLayers.Layer.Grid(this.name,this.url,this.params,this.getOptions()));a=OpenLayers.Layer.HTTPRequest.prototype.clone.apply(this,
2169 [a]);null!=this.tileSize&&(a.tileSize=this.tileSize.clone());a.grid=[];a.gridResolution=null;a.backBuffer=null;a.backBufferTimerId=null;a.loading=!1;a.numLoadingTiles=0;return a},moveTo:function(a,b,c){OpenLayers.Layer.HTTPRequest.prototype.moveTo.apply(this,arguments);a=a||this.map.getExtent();if(null!=a){var d=!this.grid.length||b,e=this.getTilesBounds(),f=this.map.getResolution();this.getServerResolution(f);if(this.singleTile){if(d||!c&&!e.containsBounds(a))b&&"resize"!==this.transitionEffect&&
2170 this.removeBackBuffer(),b&&"resize"!==this.transitionEffect||this.applyBackBuffer(f),this.initSingleTile(a)}else(d=d||!e.intersectsBounds(a,{worldBounds:this.map.baseLayer.wrapDateLine&&this.map.getMaxExtent()}))?(!b||"resize"!==this.transitionEffect&&this.gridResolution!==f||this.applyBackBuffer(f),this.initGriddedTiles(a)):this.moveGriddedTiles()}},getTileData:function(a){var b=null,c=a.lon,d=a.lat,e=this.grid.length;if(this.map&&e){var f=this.map.getResolution();a=this.tileSize.w;var g=this.tileSize.h,
2171 h=this.grid[0][0].bounds,k=h.left,h=h.top;if(c<k&&this.map.baseLayer.wrapDateLine)var l=this.map.getMaxExtent().getWidth(),m=Math.ceil((k-c)/l),c=c+l*m;c=(c-k)/(f*a);d=(h-d)/(f*g);f=Math.floor(c);k=Math.floor(d);0<=k&&k<e&&(e=this.grid[k][f])&&(b={tile:e,i:Math.floor((c-f)*a),j:Math.floor((d-k)*g)})}return b},destroyTile:function(a){this.removeTileMonitoringHooks(a);a.destroy()},getServerResolution:function(a){var b=Number.POSITIVE_INFINITY;a=a||this.map.getResolution();if(this.serverResolutions&&
2172 -1===OpenLayers.Util.indexOf(this.serverResolutions,a)){var c,d,e,f;for(c=this.serverResolutions.length-1;0<=c;c--){e=this.serverResolutions[c];d=Math.abs(e-a);if(d>b)break;b=d;f=e}a=f}return a},getServerZoom:function(){var a=this.getServerResolution();return this.serverResolutions?OpenLayers.Util.indexOf(this.serverResolutions,a):this.map.getZoomForResolution(a)+(this.zoomOffset||0)},applyBackBuffer:function(a){null!==this.backBufferTimerId&&this.removeBackBuffer();var b=this.backBuffer;if(!b){b=
2173 this.createBackBuffer();if(!b)return;a===this.gridResolution?this.div.insertBefore(b,this.div.firstChild):this.map.baseLayer.div.parentNode.insertBefore(b,this.map.baseLayer.div);this.backBuffer=b;var c=this.grid[0][0].bounds;this.backBufferLonLat={lon:c.left,lat:c.top};this.backBufferResolution=this.gridResolution}for(var c=this.backBufferResolution/a,d=b.childNodes,e,f=d.length-1;0<=f;--f)e=d[f],e.style.top=(c*e._i*e._h|0)+"px",e.style.left=(c*e._j*e._w|0)+"px",e.style.width=Math.round(c*e._w)+
2174 "px",e.style.height=Math.round(c*e._h)+"px";a=this.getViewPortPxFromLonLat(this.backBufferLonLat,a);c=this.map.layerContainerOriginPx.y;b.style.left=Math.round(a.x-this.map.layerContainerOriginPx.x)+"px";b.style.top=Math.round(a.y-c)+"px"},createBackBuffer:function(){var a;if(0<this.grid.length){a=document.createElement("div");a.id=this.div.id+"_bb";a.className="olBackBuffer";a.style.position="absolute";var b=this.map;a.style.zIndex="resize"===this.transitionEffect?this.getZIndex()-1:b.Z_INDEX_BASE.BaseLayer-
2175 (b.getNumLayers()-b.getLayerIndex(this));for(var b=0,c=this.grid.length;b<c;b++)for(var d=0,e=this.grid[b].length;d<e;d++){var f=this.grid[b][d],g=this.grid[b][d].createBackBuffer();g&&(g._i=b,g._j=d,g._w=f.size.w,g._h=f.size.h,g.id=f.id+"_bb",a.appendChild(g))}}return a},removeBackBuffer:function(){if(this._transitionElement){for(var a=this.transitionendEvents.length-1;0<=a;--a)OpenLayers.Event.stopObserving(this._transitionElement,this.transitionendEvents[a],this._removeBackBuffer);delete this._transitionElement}this.backBuffer&&
2176 (this.backBuffer.parentNode&&this.backBuffer.parentNode.removeChild(this.backBuffer),this.backBufferResolution=this.backBuffer=null,null!==this.backBufferTimerId&&(window.clearTimeout(this.backBufferTimerId),this.backBufferTimerId=null))},moveByPx:function(a,b){this.singleTile||this.moveGriddedTiles()},setTileSize:function(a){this.singleTile&&(a=this.map.getSize(),a.h=parseInt(a.h*this.ratio,10),a.w=parseInt(a.w*this.ratio,10));OpenLayers.Layer.HTTPRequest.prototype.setTileSize.apply(this,[a])},getTilesBounds:function(){var a=
2177 null,b=this.grid.length;if(b)var a=this.grid[b-1][0].bounds,b=this.grid[0].length*a.getWidth(),c=this.grid.length*a.getHeight(),a=new OpenLayers.Bounds(a.left,a.bottom,a.left+b,a.bottom+c);return a},initSingleTile:function(a){this.events.triggerEvent("retile");var b=a.getCenterLonLat(),c=a.getWidth()*this.ratio;a=a.getHeight()*this.ratio;b=new OpenLayers.Bounds(b.lon-c/2,b.lat-a/2,b.lon+c/2,b.lat+a/2);c=this.map.getLayerPxFromLonLat({lon:b.left,lat:b.top});this.grid.length||(this.grid[0]=[]);(a=this.grid[0][0])?
2178 a.moveTo(b,c):(a=this.addTile(b,c),this.addTileMonitoringHooks(a),a.draw(),this.grid[0][0]=a);this.removeExcessTiles(1,1);this.gridResolution=this.getServerResolution()},calculateGridLayout:function(a,b,c){var d=c*this.tileSize.w;c*=this.tileSize.h;var e=Math.floor((a.left-b.lon)/d)-this.buffer,f=this.rowSign;a=Math[~f?"floor":"ceil"](f*(b.lat-a.top+c)/c)-this.buffer*f;return{tilelon:d,tilelat:c,startcol:e,startrow:a}},getTileOrigin:function(){var a=this.tileOrigin;if(!a)var a=this.getMaxExtent(),
2179 b={tl:["left","top"],tr:["right","top"],bl:["left","bottom"],br:["right","bottom"]}[this.tileOriginCorner],a=new OpenLayers.LonLat(a[b[0]],a[b[1]]);return a},getTileBoundsForGridIndex:function(a,b){var c=this.getTileOrigin(),d=this.gridLayout,e=d.tilelon,f=d.tilelat,g=d.startcol,d=d.startrow,h=this.rowSign;return new OpenLayers.Bounds(c.lon+(g+b)*e,c.lat-(d+a*h)*f*h,c.lon+(g+b+1)*e,c.lat-(d+(a-1)*h)*f*h)},initGriddedTiles:function(a){this.events.triggerEvent("retile");var b=this.map.getSize(),c=this.getTileOrigin(),
2180 d=this.map.getResolution(),e=this.getServerResolution(),f=d/e,d=this.tileSize.w/f,f=this.tileSize.h/f,g=Math.ceil(b.h/f)+2*this.buffer+1,b=Math.ceil(b.w/d)+2*this.buffer+1;this.gridLayout=e=this.calculateGridLayout(a,c,e);var c=e.tilelon,h=e.tilelat,e=this.map.layerContainerOriginPx.x,k=this.map.layerContainerOriginPx.y,l=this.getTileBoundsForGridIndex(0,0),m=this.map.getViewPortPxFromLonLat(new OpenLayers.LonLat(l.left,l.top));m.x=Math.round(m.x)-e;m.y=Math.round(m.y)-k;var e=[],k=this.map.getCenter(),
2181 n=0;do{var p=this.grid[n];p||(p=[],this.grid.push(p));var q=0;do{var l=this.getTileBoundsForGridIndex(n,q),r=m.clone();r.x+=q*Math.round(d);r.y+=n*Math.round(f);var s=p[q];s?s.moveTo(l,r,!1):(s=this.addTile(l,r),this.addTileMonitoringHooks(s),p.push(s));r=l.getCenterLonLat();e.push({tile:s,distance:Math.pow(r.lon-k.lon,2)+Math.pow(r.lat-k.lat,2)});q+=1}while(l.right<=a.right+c*this.buffer||q<b);n+=1}while(l.bottom>=a.bottom-h*this.buffer||n<g);this.removeExcessTiles(n,q);this.gridResolution=d=this.getServerResolution();
2182 e.sort(function(a,b){return a.distance-b.distance});a=0;for(d=e.length;a<d;++a)e[a].tile.draw()},getMaxExtent:function(){return this.maxExtent},addTile:function(a,b){var c=new this.tileClass(this,b,a,null,this.tileSize,this.tileOptions);this.events.triggerEvent("addtile",{tile:c});return c},addTileMonitoringHooks:function(a){a.onLoadStart=function(){!1===this.loading&&(this.loading=!0,this.events.triggerEvent("loadstart"));this.events.triggerEvent("tileloadstart",{tile:a});this.numLoadingTiles++;
2183 !this.singleTile&&(this.backBuffer&&this.gridResolution===this.backBufferResolution)&&OpenLayers.Element.addClass(a.getTile(),"olTileReplacing")};a.onLoadEnd=function(b){this.numLoadingTiles--;b="unload"===b.type;this.events.triggerEvent("tileloaded",{tile:a,aborted:b});if(!this.singleTile&&!b&&this.backBuffer&&this.gridResolution===this.backBufferResolution){var c=a.getTile();if("none"===OpenLayers.Element.getStyle(c,"display")){var d=document.getElementById(a.id+"_bb");d&&d.parentNode.removeChild(d)}OpenLayers.Element.removeClass(c,
2184 "olTileReplacing")}if(0===this.numLoadingTiles){if(this.backBuffer)if(0===this.backBuffer.childNodes.length)this.removeBackBuffer();else{this._transitionElement=b?this.div.lastChild:a.imgDiv;b=this.transitionendEvents;for(c=b.length-1;0<=c;--c)OpenLayers.Event.observe(this._transitionElement,b[c],this._removeBackBuffer);this.backBufferTimerId=window.setTimeout(this._removeBackBuffer,this.removeBackBufferDelay)}this.loading=!1;this.events.triggerEvent("loadend")}};a.onLoadError=function(){this.events.triggerEvent("tileerror",
2185 {tile:a})};a.events.on({loadstart:a.onLoadStart,loadend:a.onLoadEnd,unload:a.onLoadEnd,loaderror:a.onLoadError,scope:this})},removeTileMonitoringHooks:function(a){a.unload();a.events.un({loadstart:a.onLoadStart,loadend:a.onLoadEnd,unload:a.onLoadEnd,loaderror:a.onLoadError,scope:this})},moveGriddedTiles:function(){for(var a=this.buffer+1;;){var b=this.grid[0][0],c=b.position.x+this.map.layerContainerOriginPx.x,b=b.position.y+this.map.layerContainerOriginPx.y,d=this.getServerResolution()/this.map.getResolution(),
2186 d={w:Math.round(this.tileSize.w*d),h:Math.round(this.tileSize.h*d)};if(c>-d.w*(a-1))this.shiftColumn(!0,d);else if(c<-d.w*a)this.shiftColumn(!1,d);else if(b>-d.h*(a-1))this.shiftRow(!0,d);else if(b<-d.h*a)this.shiftRow(!1,d);else break}},shiftRow:function(a,b){var c=this.grid,d=a?0:c.length-1,e=a?-1:1;this.gridLayout.startrow+=e*this.rowSign;for(var f=c[d],g=c[a?"pop":"shift"](),h=0,k=g.length;h<k;h++){var l=g[h],m=f[h].position.clone();m.y+=b.h*e;l.moveTo(this.getTileBoundsForGridIndex(d,h),m)}c[a?
2187 "unshift":"push"](g)},shiftColumn:function(a,b){var c=this.grid,d=a?0:c[0].length-1,e=a?-1:1;this.gridLayout.startcol+=e;for(var f=0,g=c.length;f<g;f++){var h=c[f],k=h[d].position.clone(),l=h[a?"pop":"shift"]();k.x+=b.w*e;l.moveTo(this.getTileBoundsForGridIndex(f,d),k);h[a?"unshift":"push"](l)}},removeExcessTiles:function(a,b){for(var c,d;this.grid.length>a;){var e=this.grid.pop();c=0;for(d=e.length;c<d;c++){var f=e[c];this.destroyTile(f)}}c=0;for(d=this.grid.length;c<d;c++)for(;this.grid[c].length>
2188 b;)e=this.grid[c],f=e.pop(),this.destroyTile(f)},onMapResize:function(){this.singleTile&&(this.clearGrid(),this.setTileSize())},getTileBounds:function(a){var b=this.maxExtent,c=this.getResolution(),d=c*this.tileSize.w,c=c*this.tileSize.h,e=this.getLonLatFromViewPortPx(a);a=b.left+d*Math.floor((e.lon-b.left)/d);b=b.bottom+c*Math.floor((e.lat-b.bottom)/c);return new OpenLayers.Bounds(a,b,a+d,b+c)},CLASS_NAME:"OpenLayers.Layer.Grid"});OpenLayers.Format.ArcXML=OpenLayers.Class(OpenLayers.Format.XML,{fontStyleKeys:"antialiasing blockout font fontcolor fontsize fontstyle glowing interval outline printmode shadow transparency".split(" "),request:null,response:null,initialize:function(a){this.request=new OpenLayers.Format.ArcXML.Request;this.response=new OpenLayers.Format.ArcXML.Response;if(a)if("feature"==a.requesttype){this.request.get_image=null;var b=this.request.get_feature.query;this.addCoordSys(b.featurecoordsys,a.featureCoordSys);
2189 this.addCoordSys(b.filtercoordsys,a.filterCoordSys);a.polygon?(b.isspatial=!0,b.spatialfilter.polygon=a.polygon):a.envelope&&(b.isspatial=!0,b.spatialfilter.envelope={minx:0,miny:0,maxx:0,maxy:0},this.parseEnvelope(b.spatialfilter.envelope,a.envelope))}else"image"==a.requesttype?(this.request.get_feature=null,b=this.request.get_image.properties,this.parseEnvelope(b.envelope,a.envelope),this.addLayers(b.layerlist,a.layers),this.addImageSize(b.imagesize,a.tileSize),this.addCoordSys(b.featurecoordsys,
2190 a.featureCoordSys),this.addCoordSys(b.filtercoordsys,a.filterCoordSys)):this.request=null;OpenLayers.Format.XML.prototype.initialize.apply(this,[a])},parseEnvelope:function(a,b){b&&4==b.length&&(a.minx=b[0],a.miny=b[1],a.maxx=b[2],a.maxy=b[3])},addLayers:function(a,b){for(var c=0,d=b.length;c<d;c++)a.push(b[c])},addImageSize:function(a,b){null!==b&&(a.width=b.w,a.height=b.h,a.printwidth=b.w,a.printheight=b.h)},addCoordSys:function(a,b){"string"==typeof b?(a.id=parseInt(b),a.string=b):"object"==typeof b&&
2191 null!==b.proj&&(a.id=b.proj.srsProjNumber,a.string=b.proj.srsCode)},iserror:function(a){var b=null;a?(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]),a=a.documentElement.getElementsByTagName("ERROR"),b=null!==a&&0<a.length):b=""!==this.response.error;return b},read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));var b=null;a&&a.documentElement&&(b="ARCXML"==a.documentElement.nodeName?a.documentElement:a.documentElement.getElementsByTagName("ARCXML")[0]);
2192 if(!b||"parsererror"===b.firstChild.nodeName){var c,d;try{c=a.firstChild.nodeValue,d=a.firstChild.childNodes[1].firstChild.nodeValue}catch(e){}throw{message:"Error parsing the ArcXML request",error:c,source:d};}return this.parseResponse(b)},write:function(a){a||(a=this.request);var b=this.createElementNS("","ARCXML");b.setAttribute("version","1.1");var c=this.createElementNS("","REQUEST");if(null!=a.get_image){var d=this.createElementNS("","GET_IMAGE");c.appendChild(d);var e=this.createElementNS("",
2193 "PROPERTIES");d.appendChild(e);a=a.get_image.properties;null!=a.featurecoordsys&&(d=this.createElementNS("","FEATURECOORDSYS"),e.appendChild(d),0===a.featurecoordsys.id?d.setAttribute("string",a.featurecoordsys.string):d.setAttribute("id",a.featurecoordsys.id));null!=a.filtercoordsys&&(d=this.createElementNS("","FILTERCOORDSYS"),e.appendChild(d),0===a.filtercoordsys.id?d.setAttribute("string",a.filtercoordsys.string):d.setAttribute("id",a.filtercoordsys.id));null!=a.envelope&&(d=this.createElementNS("",
2194 "ENVELOPE"),e.appendChild(d),d.setAttribute("minx",a.envelope.minx),d.setAttribute("miny",a.envelope.miny),d.setAttribute("maxx",a.envelope.maxx),d.setAttribute("maxy",a.envelope.maxy));d=this.createElementNS("","IMAGESIZE");e.appendChild(d);d.setAttribute("height",a.imagesize.height);d.setAttribute("width",a.imagesize.width);if(a.imagesize.height!=a.imagesize.printheight||a.imagesize.width!=a.imagesize.printwidth)d.setAttribute("printheight",a.imagesize.printheight),d.setArrtibute("printwidth",a.imagesize.printwidth);
2195 null!=a.background&&(d=this.createElementNS("","BACKGROUND"),e.appendChild(d),d.setAttribute("color",a.background.color.r+","+a.background.color.g+","+a.background.color.b),null!==a.background.transcolor&&d.setAttribute("transcolor",a.background.transcolor.r+","+a.background.transcolor.g+","+a.background.transcolor.b));if(null!=a.layerlist&&0<a.layerlist.length)for(d=this.createElementNS("","LAYERLIST"),e.appendChild(d),e=0;e<a.layerlist.length;e++){var f=this.createElementNS("","LAYERDEF");d.appendChild(f);
2196 f.setAttribute("id",a.layerlist[e].id);f.setAttribute("visible",a.layerlist[e].visible);if("object"==typeof a.layerlist[e].query){var g=a.layerlist[e].query;if(0>g.where.length)continue;var h=null,h="boolean"==typeof g.spatialfilter&&g.spatialfilter?this.createElementNS("","SPATIALQUERY"):this.createElementNS("","QUERY");h.setAttribute("where",g.where);"number"==typeof g.accuracy&&0<g.accuracy&&h.setAttribute("accuracy",g.accuracy);"number"==typeof g.featurelimit&&2E3>g.featurelimit&&h.setAttribute("featurelimit",
2197 g.featurelimit);"string"==typeof g.subfields&&"#ALL#"!=g.subfields&&h.setAttribute("subfields",g.subfields);"string"==typeof g.joinexpression&&0<g.joinexpression.length&&h.setAttribute("joinexpression",g.joinexpression);"string"==typeof g.jointables&&0<g.jointables.length&&h.setAttribute("jointables",g.jointables);f.appendChild(h)}"object"==typeof a.layerlist[e].renderer&&this.addRenderer(f,a.layerlist[e].renderer)}}else null!=a.get_feature&&(d=this.createElementNS("","GET_FEATURES"),d.setAttribute("outputmode",
2198 "newxml"),d.setAttribute("checkesc","true"),a.get_feature.geometry?d.setAttribute("geometry",a.get_feature.geometry):d.setAttribute("geometry","false"),a.get_feature.compact&&d.setAttribute("compact",a.get_feature.compact),"number"==a.get_feature.featurelimit&&d.setAttribute("featurelimit",a.get_feature.featurelimit),d.setAttribute("globalenvelope","true"),c.appendChild(d),null!=a.get_feature.layer&&0<a.get_feature.layer.length&&(e=this.createElementNS("","LAYER"),e.setAttribute("id",a.get_feature.layer),
2199 d.appendChild(e)),a=a.get_feature.query,null!=a&&(e=null,e=a.isspatial?this.createElementNS("","SPATIALQUERY"):this.createElementNS("","QUERY"),d.appendChild(e),"number"==typeof a.accuracy&&e.setAttribute("accuracy",a.accuracy),null!=a.featurecoordsys&&(d=this.createElementNS("","FEATURECOORDSYS"),0==a.featurecoordsys.id?d.setAttribute("string",a.featurecoordsys.string):d.setAttribute("id",a.featurecoordsys.id),e.appendChild(d)),null!=a.filtercoordsys&&(d=this.createElementNS("","FILTERCOORDSYS"),
2200 0===a.filtercoordsys.id?d.setAttribute("string",a.filtercoordsys.string):d.setAttribute("id",a.filtercoordsys.id),e.appendChild(d)),0<a.buffer&&(d=this.createElementNS("","BUFFER"),d.setAttribute("distance",a.buffer),e.appendChild(d)),a.isspatial&&(d=this.createElementNS("","SPATIALFILTER"),d.setAttribute("relation",a.spatialfilter.relation),e.appendChild(d),a.spatialfilter.envelope?(f=this.createElementNS("","ENVELOPE"),f.setAttribute("minx",a.spatialfilter.envelope.minx),f.setAttribute("miny",a.spatialfilter.envelope.miny),
2201 f.setAttribute("maxx",a.spatialfilter.envelope.maxx),f.setAttribute("maxy",a.spatialfilter.envelope.maxy),d.appendChild(f)):"object"==typeof a.spatialfilter.polygon&&d.appendChild(this.writePolygonGeometry(a.spatialfilter.polygon))),null!=a.where&&0<a.where.length&&e.setAttribute("where",a.where)));b.appendChild(c);return OpenLayers.Format.XML.prototype.write.apply(this,[b])},addGroupRenderer:function(a,b){var c=this.createElementNS("","GROUPRENDERER");a.appendChild(c);for(var d=0;d<b.length;d++)this.addRenderer(c,
2202 b[d])},addRenderer:function(a,b){if(OpenLayers.Util.isArray(b))this.addGroupRenderer(a,b);else{var c=this.createElementNS("",b.type.toUpperCase()+"RENDERER");a.appendChild(c);"VALUEMAPRENDERER"==c.tagName?this.addValueMapRenderer(c,b):"VALUEMAPLABELRENDERER"==c.tagName?this.addValueMapLabelRenderer(c,b):"SIMPLELABELRENDERER"==c.tagName?this.addSimpleLabelRenderer(c,b):"SCALEDEPENDENTRENDERER"==c.tagName&&this.addScaleDependentRenderer(c,b)}},addScaleDependentRenderer:function(a,b){"string"!=typeof b.lower&&
2203 "number"!=typeof b.lower||a.setAttribute("lower",b.lower);"string"!=typeof b.upper&&"number"!=typeof b.upper||a.setAttribute("upper",b.upper);this.addRenderer(a,b.renderer)},addValueMapLabelRenderer:function(a,b){a.setAttribute("lookupfield",b.lookupfield);a.setAttribute("labelfield",b.labelfield);if("object"==typeof b.exacts)for(var c=0,d=b.exacts.length;c<d;c++){var e=b.exacts[c],f=this.createElementNS("","EXACT");"string"==typeof e.value&&f.setAttribute("value",e.value);"string"==typeof e.label&&
2204 f.setAttribute("label",e.label);"string"==typeof e.method&&f.setAttribute("method",e.method);a.appendChild(f);if("object"==typeof e.symbol){var g=null;"text"==e.symbol.type&&(g=this.createElementNS("","TEXTSYMBOL"));if(null!=g){for(var h=this.fontStyleKeys,k=0,l=h.length;k<l;k++){var m=h[k];e.symbol[m]&&g.setAttribute(m,e.symbol[m])}f.appendChild(g)}}}},addValueMapRenderer:function(a,b){a.setAttribute("lookupfield",b.lookupfield);if("object"==typeof b.ranges)for(var c=0,d=b.ranges.length;c<d;c++){var e=
2205 b.ranges[c],f=this.createElementNS("","RANGE");f.setAttribute("lower",e.lower);f.setAttribute("upper",e.upper);a.appendChild(f);if("object"==typeof e.symbol){var g=null;"simplepolygon"==e.symbol.type&&(g=this.createElementNS("","SIMPLEPOLYGONSYMBOL"));null!=g&&("string"==typeof e.symbol.boundarycolor&&g.setAttribute("boundarycolor",e.symbol.boundarycolor),"string"==typeof e.symbol.fillcolor&&g.setAttribute("fillcolor",e.symbol.fillcolor),"number"==typeof e.symbol.filltransparency&&g.setAttribute("filltransparency",
2206 e.symbol.filltransparency),f.appendChild(g))}}else if("object"==typeof b.exacts)for(c=0,d=b.exacts.length;c<d;c++)e=b.exacts[c],f=this.createElementNS("","EXACT"),"string"==typeof e.value&&f.setAttribute("value",e.value),"string"==typeof e.label&&f.setAttribute("label",e.label),"string"==typeof e.method&&f.setAttribute("method",e.method),a.appendChild(f),"object"==typeof e.symbol&&(g=null,"simplemarker"==e.symbol.type&&(g=this.createElementNS("","SIMPLEMARKERSYMBOL")),null!=g&&("string"==typeof e.symbol.antialiasing&&
2207 g.setAttribute("antialiasing",e.symbol.antialiasing),"string"==typeof e.symbol.color&&g.setAttribute("color",e.symbol.color),"string"==typeof e.symbol.outline&&g.setAttribute("outline",e.symbol.outline),"string"==typeof e.symbol.overlap&&g.setAttribute("overlap",e.symbol.overlap),"string"==typeof e.symbol.shadow&&g.setAttribute("shadow",e.symbol.shadow),"number"==typeof e.symbol.transparency&&g.setAttribute("transparency",e.symbol.transparency),"string"==typeof e.symbol.usecentroid&&g.setAttribute("usecentroid",
2208 e.symbol.usecentroid),"number"==typeof e.symbol.width&&g.setAttribute("width",e.symbol.width),f.appendChild(g)))},addSimpleLabelRenderer:function(a,b){a.setAttribute("field",b.field);for(var c="featureweight howmanylabels labelbufferratio labelpriorities labelweight linelabelposition rotationalangles".split(" "),d=0,e=c.length;d<e;d++){var f=c[d];b[f]&&a.setAttribute(f,b[f])}if("text"==b.symbol.type){var g=b.symbol,h=this.createElementNS("","TEXTSYMBOL");a.appendChild(h);c=this.fontStyleKeys;d=0;
2209 for(e=c.length;d<e;d++)f=c[d],g[f]&&h.setAttribute(f,b[f])}},writePolygonGeometry:function(a){if(!(a instanceof OpenLayers.Geometry.Polygon))throw{message:"Cannot write polygon geometry to ArcXML with an "+a.CLASS_NAME+" object.",geometry:a};for(var b=this.createElementNS("","POLYGON"),c=0,d=a.components.length;c<d;c++){for(var e=a.components[c],f=this.createElementNS("","RING"),g=0,h=e.components.length;g<h;g++){var k=e.components[g],l=this.createElementNS("","POINT");l.setAttribute("x",k.x);l.setAttribute("y",
2210 k.y);f.appendChild(l)}b.appendChild(f)}return b},parseResponse:function(a){"string"==typeof a&&(a=(new OpenLayers.Format.XML).read(a));var b=new OpenLayers.Format.ArcXML.Response,c=a.getElementsByTagName("ERROR");if(null!=c&&0<c.length)b.error=this.getChildValue(c,"Unknown error.");else{c=a.getElementsByTagName("RESPONSE");if(null==c||0==c.length)return b.error="No RESPONSE tag found in ArcXML response.",b;var d=c[0].firstChild.nodeName;"#text"==d&&(d=c[0].firstChild.nextSibling.nodeName);if("IMAGE"==
2211 d)c=a.getElementsByTagName("ENVELOPE"),a=a.getElementsByTagName("OUTPUT"),null==c||0==c.length?b.error="No ENVELOPE tag found in ArcXML response.":null==a||0==a.length?b.error="No OUTPUT tag found in ArcXML response.":(c=this.parseAttributes(c[0]),d=this.parseAttributes(a[0]),b.image="string"==typeof d.type?{envelope:c,output:{type:d.type,data:this.getChildValue(a[0])}}:{envelope:c,output:d});else if("FEATURES"==d){if(a=c[0].getElementsByTagName("FEATURES"),c=a[0].getElementsByTagName("FEATURECOUNT"),
2212 b.features.featurecount=c[0].getAttribute("count"),0<b.features.featurecount)for(c=a[0].getElementsByTagName("ENVELOPE"),b.features.envelope=this.parseAttributes(c[0],"number"),a=a[0].getElementsByTagName("FEATURE"),c=0;c<a.length;c++){for(var d=new OpenLayers.Feature.Vector,e=a[c].getElementsByTagName("FIELD"),f=0;f<e.length;f++){var g=e[f].getAttribute("name"),h=e[f].getAttribute("value");d.attributes[g]=h}e=a[c].getElementsByTagName("POLYGON");if(0<e.length){e=e[0].getElementsByTagName("RING");
2213 f=[];for(g=0;g<e.length;g++){h=[];h.push(this.parsePointGeometry(e[g]));for(var k=e[g].getElementsByTagName("HOLE"),l=0;l<k.length;l++)h.push(this.parsePointGeometry(k[l]));f.push(new OpenLayers.Geometry.Polygon(h))}d.geometry=1==f.length?f[0]:new OpenLayers.Geometry.MultiPolygon(f)}b.features.feature.push(d)}}else b.error="Unidentified response type."}return b},parseAttributes:function(a,b){for(var c={},d=0;d<a.attributes.length;d++)c[a.attributes[d].nodeName]="number"==b?parseFloat(a.attributes[d].nodeValue):
2214 a.attributes[d].nodeValue;return c},parsePointGeometry:function(a){var b=[],c=a.getElementsByTagName("COORDS");if(0<c.length)for(a=this.getChildValue(c[0]),a=a.split(/;/),c=0;c<a.length;c++){var d=a[c].split(/ /);b.push(new OpenLayers.Geometry.Point(d[0],d[1]))}else if(a=a.getElementsByTagName("POINT"),0<a.length)for(c=0;c<a.length;c++)b.push(new OpenLayers.Geometry.Point(parseFloat(a[c].getAttribute("x")),parseFloat(a[c].getAttribute("y"))));return new OpenLayers.Geometry.LinearRing(b)},CLASS_NAME:"OpenLayers.Format.ArcXML"});
2215 OpenLayers.Format.ArcXML.Request=OpenLayers.Class({initialize:function(a){return OpenLayers.Util.extend(this,{get_image:{properties:{background:null,draw:!0,envelope:{minx:0,miny:0,maxx:0,maxy:0},featurecoordsys:{id:0,string:"",datumtransformid:0,datumtransformstring:""},filtercoordsys:{id:0,string:"",datumtransformid:0,datumtransformstring:""},imagesize:{height:0,width:0,dpi:96,printheight:0,printwidth:0,scalesymbols:!1},layerlist:[],output:{baseurl:"",legendbaseurl:"",legendname:"",legendpath:"",
2216 legendurl:"",name:"",path:"",type:"jpg",url:""}}},get_feature:{layer:"",query:{isspatial:!1,featurecoordsys:{id:0,string:"",datumtransformid:0,datumtransformstring:""},filtercoordsys:{id:0,string:"",datumtransformid:0,datumtransformstring:""},buffer:0,where:"",spatialfilter:{relation:"envelope_intersection",envelope:null}}},environment:{separators:{cs:" ",ts:";"}},layer:[],workspaces:[]})},CLASS_NAME:"OpenLayers.Format.ArcXML.Request"});
2217 OpenLayers.Format.ArcXML.Response=OpenLayers.Class({initialize:function(a){return OpenLayers.Util.extend(this,{image:{envelope:null,output:""},features:{featurecount:0,envelope:null,feature:[]},error:""})},CLASS_NAME:"OpenLayers.Format.ArcXML.Response"});(function(){function a(){this._object=f&&!k?new f:new window.ActiveXObject("Microsoft.XMLHTTP");this._listeners=[]}function b(){return new a}function c(a){b.onreadystatechange&&b.onreadystatechange.apply(a);a.dispatchEvent({type:"readystatechange",bubbles:!1,cancelable:!1,timeStamp:new Date+0})}function d(a){try{a.responseText=a._object.responseText}catch(b){}try{var c;var d=a._object,e=d.responseXML,f=d.responseText;h&&(f&&e&&!e.documentElement&&d.getResponseHeader("Content-Type").match(/[^\/]+\/[^\+]+\+xml/))&&
2218 (e=new window.ActiveXObject("Microsoft.XMLDOM"),e.async=!1,e.validateOnParse=!1,e.loadXML(f));c=e&&(h&&0!=e.parseError||!e.documentElement||e.documentElement&&"parsererror"==e.documentElement.tagName)?null:e;a.responseXML=c}catch(g){}try{a.status=a._object.status}catch(k){}try{a.statusText=a._object.statusText}catch(u){}}function e(a){a._object.onreadystatechange=new window.Function}var f=window.XMLHttpRequest,g=!!window.controllers,h=window.document.all&&!window.opera,k=h&&window.navigator.userAgent.match(/MSIE 7.0/);
2219 b.prototype=a.prototype;g&&f.wrapped&&(b.wrapped=f.wrapped);b.UNSENT=0;b.OPENED=1;b.HEADERS_RECEIVED=2;b.LOADING=3;b.DONE=4;b.prototype.readyState=b.UNSENT;b.prototype.responseText="";b.prototype.responseXML=null;b.prototype.status=0;b.prototype.statusText="";b.prototype.priority="NORMAL";b.prototype.onreadystatechange=null;b.onreadystatechange=null;b.onopen=null;b.onsend=null;b.onabort=null;b.prototype.open=function(a,f,k,p,q){delete this._headers;3>arguments.length&&(k=!0);this._async=k;var r=this,
2220 s=this.readyState,t;h&&k&&(t=function(){s!=b.DONE&&(e(r),r.abort())},window.attachEvent("onunload",t));b.onopen&&b.onopen.apply(this,arguments);4<arguments.length?this._object.open(a,f,k,p,q):3<arguments.length?this._object.open(a,f,k,p):this._object.open(a,f,k);this.readyState=b.OPENED;c(this);this._object.onreadystatechange=function(){if(!g||k)r.readyState=r._object.readyState,d(r),r._aborted?r.readyState=b.UNSENT:(r.readyState==b.DONE&&(delete r._data,e(r),h&&k&&window.detachEvent("onunload",t)),
2221 s!=r.readyState&&c(r),s=r.readyState)}};b.prototype.send=function(a){b.onsend&&b.onsend.apply(this,arguments);arguments.length||(a=null);a&&a.nodeType&&(a=window.XMLSerializer?(new window.XMLSerializer).serializeToString(a):a.xml,this._headers["Content-Type"]||this._object.setRequestHeader("Content-Type","application/xml"));this._data=a;a:if(this._object.send(this._data),g&&!this._async)for(this.readyState=b.OPENED,d(this);this.readyState<b.DONE;)if(this.readyState++,c(this),this._aborted)break a};
2222 b.prototype.abort=function(){b.onabort&&b.onabort.apply(this,arguments);this.readyState>b.UNSENT&&(this._aborted=!0);this._object.abort();e(this);this.readyState=b.UNSENT;delete this._data};b.prototype.getAllResponseHeaders=function(){return this._object.getAllResponseHeaders()};b.prototype.getResponseHeader=function(a){return this._object.getResponseHeader(a)};b.prototype.setRequestHeader=function(a,b){this._headers||(this._headers={});this._headers[a]=b;return this._object.setRequestHeader(a,b)};
2223 b.prototype.addEventListener=function(a,b,c){for(var d=0,e;e=this._listeners[d];d++)if(e[0]==a&&e[1]==b&&e[2]==c)return;this._listeners.push([a,b,c])};b.prototype.removeEventListener=function(a,b,c){for(var d=0,e;(e=this._listeners[d])&&(e[0]!=a||e[1]!=b||e[2]!=c);d++);e&&this._listeners.splice(d,1)};b.prototype.dispatchEvent=function(a){a={type:a.type,target:this,currentTarget:this,eventPhase:2,bubbles:a.bubbles,cancelable:a.cancelable,timeStamp:a.timeStamp,stopPropagation:function(){},preventDefault:function(){},
2224 initEvent:function(){}};"readystatechange"==a.type&&this.onreadystatechange&&(this.onreadystatechange.handleEvent||this.onreadystatechange).apply(this,[a]);for(var b=0,c;c=this._listeners[b];b++)c[0]!=a.type||c[2]||(c[1].handleEvent||c[1]).apply(this,[a])};b.prototype.toString=function(){return"[object XMLHttpRequest]"};b.toString=function(){return"[XMLHttpRequest]"};window.Function.prototype.apply||(window.Function.prototype.apply=function(a,b){b||(b=[]);a.__func=this;a.__func(b[0],b[1],b[2],b[3],
2225 b[4]);delete a.__func});OpenLayers.Request||(OpenLayers.Request={});OpenLayers.Request.XMLHttpRequest=b})();OpenLayers.ProxyHost="";OpenLayers.Request||(OpenLayers.Request={});
2226 OpenLayers.Util.extend(OpenLayers.Request,{DEFAULT_CONFIG:{method:"GET",url:window.location.href,async:!0,user:void 0,password:void 0,params:null,proxy:OpenLayers.ProxyHost,headers:{},data:null,callback:function(){},success:null,failure:null,scope:null},URL_SPLIT_REGEX:/([^:]*:)\/\/([^:]*:?[^@]*@)?([^:\/\?]*):?([^\/\?]*)/,events:new OpenLayers.Events(this),makeSameOrigin:function(a,b){var c=0!==a.indexOf("http"),d=!c&&a.match(this.URL_SPLIT_REGEX);if(d){var e=window.location,c=d[1]==e.protocol&&d[3]==
2227 e.hostname,d=d[4],e=e.port;if(80!=d&&""!=d||"80"!=e&&""!=e)c=c&&d==e}c||b&&(a="function"==typeof b?b(a):b+encodeURIComponent(a));return a},issue:function(a){var b=OpenLayers.Util.extend(this.DEFAULT_CONFIG,{proxy:OpenLayers.ProxyHost});a=a||{};a.headers=a.headers||{};a=OpenLayers.Util.applyDefaults(a,b);a.headers=OpenLayers.Util.applyDefaults(a.headers,b.headers);var b=!1,c;for(c in a.headers)a.headers.hasOwnProperty(c)&&"x-requested-with"===c.toLowerCase()&&(b=!0);!1===b&&(a.headers["X-Requested-With"]=
2228 "XMLHttpRequest");var d=new OpenLayers.Request.XMLHttpRequest,e=OpenLayers.Util.urlAppend(a.url,OpenLayers.Util.getParameterString(a.params||{})),e=OpenLayers.Request.makeSameOrigin(e,a.proxy);d.open(a.method,e,a.async,a.user,a.password);for(var f in a.headers)d.setRequestHeader(f,a.headers[f]);var g=this.events,h=this;d.onreadystatechange=function(){d.readyState==OpenLayers.Request.XMLHttpRequest.DONE&&!1!==g.triggerEvent("complete",{request:d,config:a,requestUrl:e})&&h.runCallbacks({request:d,config:a,
2229 requestUrl:e})};!1===a.async?d.send(a.data):window.setTimeout(function(){0!==d.readyState&&d.send(a.data)},0);return d},runCallbacks:function(a){var b=a.request,c=a.config,d=c.scope?OpenLayers.Function.bind(c.callback,c.scope):c.callback,e;c.success&&(e=c.scope?OpenLayers.Function.bind(c.success,c.scope):c.success);var f;c.failure&&(f=c.scope?OpenLayers.Function.bind(c.failure,c.scope):c.failure);"file:"==OpenLayers.Util.createUrlObject(c.url).protocol&&b.responseText&&(b.status=200);d(b);if(!b.status||
2230 200<=b.status&&300>b.status)this.events.triggerEvent("success",a),e&&e(b);b.status&&(200>b.status||300<=b.status)&&(this.events.triggerEvent("failure",a),f&&f(b))},GET:function(a){a=OpenLayers.Util.extend(a,{method:"GET"});return OpenLayers.Request.issue(a)},POST:function(a){a=OpenLayers.Util.extend(a,{method:"POST"});a.headers=a.headers?a.headers:{};"CONTENT-TYPE"in OpenLayers.Util.upperCaseObject(a.headers)||(a.headers["Content-Type"]="application/xml");return OpenLayers.Request.issue(a)},PUT:function(a){a=
2231 OpenLayers.Util.extend(a,{method:"PUT"});a.headers=a.headers?a.headers:{};"CONTENT-TYPE"in OpenLayers.Util.upperCaseObject(a.headers)||(a.headers["Content-Type"]="application/xml");return OpenLayers.Request.issue(a)},DELETE:function(a){a=OpenLayers.Util.extend(a,{method:"DELETE"});return OpenLayers.Request.issue(a)},HEAD:function(a){a=OpenLayers.Util.extend(a,{method:"HEAD"});return OpenLayers.Request.issue(a)},OPTIONS:function(a){a=OpenLayers.Util.extend(a,{method:"OPTIONS"});return OpenLayers.Request.issue(a)}});OpenLayers.Layer.ArcIMS=OpenLayers.Class(OpenLayers.Layer.Grid,{DEFAULT_PARAMS:{ClientVersion:"9.2",ServiceName:""},featureCoordSys:"4326",filterCoordSys:"4326",layers:null,async:!0,name:"ArcIMS",isBaseLayer:!0,DEFAULT_OPTIONS:{tileSize:new OpenLayers.Size(512,512),featureCoordSys:"4326",filterCoordSys:"4326",layers:null,isBaseLayer:!0,async:!0,name:"ArcIMS"},initialize:function(a,b,c){this.tileSize=new OpenLayers.Size(512,512);this.params=OpenLayers.Util.applyDefaults({ServiceName:c.serviceName},
2232 this.DEFAULT_PARAMS);this.options=OpenLayers.Util.applyDefaults(c,this.DEFAULT_OPTIONS);OpenLayers.Layer.Grid.prototype.initialize.apply(this,[a,b,this.params,c]);this.transparent&&(this.isBaseLayer||(this.isBaseLayer=!1),"image/jpeg"==this.format&&(this.format=OpenLayers.Util.alphaHack()?"image/gif":"image/png"));null===this.options.layers&&(this.options.layers=[])},getURL:function(a){var b="";a=this.adjustBounds(a);a=new OpenLayers.Format.ArcXML(OpenLayers.Util.extend(this.options,{requesttype:"image",
2233 envelope:a.toArray(),tileSize:this.tileSize}));a=new OpenLayers.Request.POST({url:this.getFullRequestString(),data:a.write(),async:!1});null!=a&&(b=a.responseXML,b&&b.documentElement||(b=a.responseText),b=(new OpenLayers.Format.ArcXML).read(b),b=this.getUrlOrImage(b.image.output));return b},getURLasync:function(a,b,c){a=this.adjustBounds(a);a=new OpenLayers.Format.ArcXML(OpenLayers.Util.extend(this.options,{requesttype:"image",envelope:a.toArray(),tileSize:this.tileSize}));OpenLayers.Request.POST({url:this.getFullRequestString(),
2234 async:!0,data:a.write(),callback:function(a){var e=a.responseXML;e&&e.documentElement||(e=a.responseText);a=(new OpenLayers.Format.ArcXML).read(e);b.call(c,this.getUrlOrImage(a.image.output))},scope:this})},getUrlOrImage:function(a){var b="";a.url?b=a.url:a.data&&(b="data:image/"+a.type+";base64,"+a.data);return b},setLayerQuery:function(a,b){for(var c=0;c<this.options.layers.length;c++)if(a==this.options.layers[c].id){this.options.layers[c].query=b;return}this.options.layers.push({id:a,visible:!0,
2235 query:b})},getFeatureInfo:function(a,b,c){var d=c.buffer||1,e=c.callback||function(){},f=c.scope||window,g={};OpenLayers.Util.extend(g,this.options);g.requesttype="feature";a instanceof OpenLayers.LonLat?(g.polygon=null,g.envelope=[a.lon-d,a.lat-d,a.lon+d,a.lat+d]):a instanceof OpenLayers.Geometry.Polygon&&(g.envelope=null,g.polygon=a);var h=new OpenLayers.Format.ArcXML(g);OpenLayers.Util.extend(h.request.get_feature,c);h.request.get_feature.layer=b.id;"number"==typeof b.query.accuracy?h.request.get_feature.query.accuracy=
2236 b.query.accuracy:(a=this.map.getCenter(),c=this.map.getViewPortPxFromLonLat(a),c.x++,c=this.map.getLonLatFromPixel(c),h.request.get_feature.query.accuracy=c.lon-a.lon);h.request.get_feature.query.where=b.query.where;h.request.get_feature.query.spatialfilter.relation="area_intersection";OpenLayers.Request.POST({url:this.getFullRequestString({CustomService:"Query"}),data:h.write(),callback:function(a){a=h.parseResponse(a.responseText);h.iserror()?e.call(f,null):e.call(f,a.features)}})},clone:function(a){null==
2237 a&&(a=new OpenLayers.Layer.ArcIMS(this.name,this.url,this.getOptions()));return a=OpenLayers.Layer.Grid.prototype.clone.apply(this,[a])},CLASS_NAME:"OpenLayers.Layer.ArcIMS"});OpenLayers.Control.PanZoom=OpenLayers.Class(OpenLayers.Control,{slideFactor:50,slideRatio:null,buttons:null,position:null,initialize:function(a){this.position=new OpenLayers.Pixel(OpenLayers.Control.PanZoom.X,OpenLayers.Control.PanZoom.Y);OpenLayers.Control.prototype.initialize.apply(this,arguments)},destroy:function(){this.map&&this.map.events.unregister("buttonclick",this,this.onButtonClick);this.removeButtons();this.position=this.buttons=null;OpenLayers.Control.prototype.destroy.apply(this,arguments)},
2238 setMap:function(a){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.map.events.register("buttonclick",this,this.onButtonClick)},draw:function(a){OpenLayers.Control.prototype.draw.apply(this,arguments);a=this.position;this.buttons=[];var b={w:18,h:18},c=new OpenLayers.Pixel(a.x+b.w/2,a.y);this._addButton("panup","north-mini.png",c,b);a.y=c.y+b.h;this._addButton("panleft","west-mini.png",a,b);this._addButton("panright","east-mini.png",a.add(b.w,0),b);this._addButton("pandown","south-mini.png",
2239 c.add(0,2*b.h),b);this._addButton("zoomin","zoom-plus-mini.png",c.add(0,3*b.h+5),b);this._addButton("zoomworld","zoom-world-mini.png",c.add(0,4*b.h+5),b);this._addButton("zoomout","zoom-minus-mini.png",c.add(0,5*b.h+5),b);return this.div},_addButton:function(a,b,c,d){b=OpenLayers.Util.getImageLocation(b);c=OpenLayers.Util.createAlphaImageDiv(this.id+"_"+a,c,d,b,"absolute");c.style.cursor="pointer";this.div.appendChild(c);c.action=a;c.className="olButton";this.buttons.push(c);return c},_removeButton:function(a){this.div.removeChild(a);
2240 OpenLayers.Util.removeItem(this.buttons,a)},removeButtons:function(){for(var a=this.buttons.length-1;0<=a;--a)this._removeButton(this.buttons[a])},onButtonClick:function(a){switch(a.buttonElement.action){case "panup":this.map.pan(0,-this.getSlideFactor("h"));break;case "pandown":this.map.pan(0,this.getSlideFactor("h"));break;case "panleft":this.map.pan(-this.getSlideFactor("w"),0);break;case "panright":this.map.pan(this.getSlideFactor("w"),0);break;case "zoomin":this.map.zoomIn();break;case "zoomout":this.map.zoomOut();
2241 break;case "zoomworld":this.map.zoomToMaxExtent()}},getSlideFactor:function(a){return this.slideRatio?this.map.getSize()[a]*this.slideRatio:this.slideFactor},CLASS_NAME:"OpenLayers.Control.PanZoom"});OpenLayers.Control.PanZoom.X=4;OpenLayers.Control.PanZoom.Y=4;OpenLayers.Control.PanZoomBar=OpenLayers.Class(OpenLayers.Control.PanZoom,{zoomStopWidth:18,zoomStopHeight:11,slider:null,sliderEvents:null,zoombarDiv:null,zoomWorldIcon:!1,panIcons:!0,forceFixedZoomLevel:!1,mouseDragStart:null,deltaY:null,zoomStart:null,destroy:function(){this._removeZoomBar();this.map.events.un({changebaselayer:this.redraw,updatesize:this.redraw,scope:this});OpenLayers.Control.PanZoom.prototype.destroy.apply(this,arguments);delete this.mouseDragStart;delete this.zoomStart},setMap:function(a){OpenLayers.Control.PanZoom.prototype.setMap.apply(this,
2242 arguments);this.map.events.on({changebaselayer:this.redraw,updatesize:this.redraw,scope:this})},redraw:function(){null!=this.div&&(this.removeButtons(),this._removeZoomBar());this.draw()},draw:function(a){OpenLayers.Control.prototype.draw.apply(this,arguments);a=this.position.clone();this.buttons=[];var b={w:18,h:18};if(this.panIcons){var c=new OpenLayers.Pixel(a.x+b.w/2,a.y),d=b.w;this.zoomWorldIcon&&(c=new OpenLayers.Pixel(a.x+b.w,a.y));this._addButton("panup","north-mini.png",c,b);a.y=c.y+b.h;
2243 this._addButton("panleft","west-mini.png",a,b);this.zoomWorldIcon&&(this._addButton("zoomworld","zoom-world-mini.png",a.add(b.w,0),b),d*=2);this._addButton("panright","east-mini.png",a.add(d,0),b);this._addButton("pandown","south-mini.png",c.add(0,2*b.h),b);this._addButton("zoomin","zoom-plus-mini.png",c.add(0,3*b.h+5),b);c=this._addZoomBar(c.add(0,4*b.h+5));this._addButton("zoomout","zoom-minus-mini.png",c,b)}else this._addButton("zoomin","zoom-plus-mini.png",a,b),c=this._addZoomBar(a.add(0,b.h)),
2244 this._addButton("zoomout","zoom-minus-mini.png",c,b),this.zoomWorldIcon&&(c=c.add(0,b.h+3),this._addButton("zoomworld","zoom-world-mini.png",c,b));return this.div},_addZoomBar:function(a){var b=OpenLayers.Util.getImageLocation("slider.png"),c=this.id+"_"+this.map.id,d=this.map.getMinZoom(),e=this.map.getNumZoomLevels()-1-this.map.getZoom(),e=OpenLayers.Util.createAlphaImageDiv(c,a.add(-1,e*this.zoomStopHeight),{w:20,h:9},b,"absolute");e.style.cursor="move";this.slider=e;this.sliderEvents=new OpenLayers.Events(this,
2245 e,null,!0,{includeXY:!0});this.sliderEvents.on({touchstart:this.zoomBarDown,touchmove:this.zoomBarDrag,touchend:this.zoomBarUp,mousedown:this.zoomBarDown,mousemove:this.zoomBarDrag,mouseup:this.zoomBarUp});var f={w:this.zoomStopWidth,h:this.zoomStopHeight*(this.map.getNumZoomLevels()-d)},b=OpenLayers.Util.getImageLocation("zoombar.png"),c=null;OpenLayers.Util.alphaHack()?(c=this.id+"_"+this.map.id,c=OpenLayers.Util.createAlphaImageDiv(c,a,{w:f.w,h:this.zoomStopHeight},b,"absolute",null,"crop"),c.style.height=
2246 f.h+"px"):c=OpenLayers.Util.createDiv("OpenLayers_Control_PanZoomBar_Zoombar"+this.map.id,a,f,b);c.style.cursor="pointer";c.className="olButton";this.zoombarDiv=c;this.div.appendChild(c);this.startTop=parseInt(c.style.top);this.div.appendChild(e);this.map.events.register("zoomend",this,this.moveZoomBar);return a=a.add(0,this.zoomStopHeight*(this.map.getNumZoomLevels()-d))},_removeZoomBar:function(){this.sliderEvents.un({touchstart:this.zoomBarDown,touchmove:this.zoomBarDrag,touchend:this.zoomBarUp,
2247 mousedown:this.zoomBarDown,mousemove:this.zoomBarDrag,mouseup:this.zoomBarUp});this.sliderEvents.destroy();this.div.removeChild(this.zoombarDiv);this.zoombarDiv=null;this.div.removeChild(this.slider);this.slider=null;this.map.events.unregister("zoomend",this,this.moveZoomBar)},onButtonClick:function(a){OpenLayers.Control.PanZoom.prototype.onButtonClick.apply(this,arguments);if(a.buttonElement===this.zoombarDiv){var b=a.buttonXY.y/this.zoomStopHeight;if(this.forceFixedZoomLevel||!this.map.fractionalZoom)b=
2248 Math.floor(b);b=this.map.getNumZoomLevels()-1-b;b=Math.min(Math.max(b,0),this.map.getNumZoomLevels()-1);this.map.zoomTo(b)}},passEventToSlider:function(a){this.sliderEvents.handleBrowserEvent(a)},zoomBarDown:function(a){if(OpenLayers.Event.isLeftClick(a)||OpenLayers.Event.isSingleTouch(a))this.map.events.on({touchmove:this.passEventToSlider,mousemove:this.passEventToSlider,mouseup:this.passEventToSlider,scope:this}),this.mouseDragStart=a.xy.clone(),this.zoomStart=a.xy.clone(),this.div.style.cursor=
2249 "move",this.zoombarDiv.offsets=null,OpenLayers.Event.stop(a)},zoomBarDrag:function(a){if(null!=this.mouseDragStart){var b=this.mouseDragStart.y-a.xy.y,c=OpenLayers.Util.pagePosition(this.zoombarDiv);0<a.clientY-c[1]&&a.clientY-c[1]<parseInt(this.zoombarDiv.style.height)-2&&(b=parseInt(this.slider.style.top)-b,this.slider.style.top=b+"px",this.mouseDragStart=a.xy.clone());this.deltaY=this.zoomStart.y-a.xy.y;OpenLayers.Event.stop(a)}},zoomBarUp:function(a){if((OpenLayers.Event.isLeftClick(a)||"touchend"===
2250 a.type)&&this.mouseDragStart){this.div.style.cursor="";this.map.events.un({touchmove:this.passEventToSlider,mouseup:this.passEventToSlider,mousemove:this.passEventToSlider,scope:this});var b=this.map.zoom;!this.forceFixedZoomLevel&&this.map.fractionalZoom?(b+=this.deltaY/this.zoomStopHeight,b=Math.min(Math.max(b,0),this.map.getNumZoomLevels()-1)):(b+=this.deltaY/this.zoomStopHeight,b=Math.max(Math.round(b),0));this.map.zoomTo(b);this.zoomStart=this.mouseDragStart=null;this.deltaY=0;OpenLayers.Event.stop(a)}},
2251 moveZoomBar:function(){var a=(this.map.getNumZoomLevels()-1-this.map.getZoom())*this.zoomStopHeight+this.startTop+1;this.slider.style.top=a+"px"},CLASS_NAME:"OpenLayers.Control.PanZoomBar"});OpenLayers.Format.WFSCapabilities=OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC,{defaultVersion:"1.1.0",CLASS_NAME:"OpenLayers.Format.WFSCapabilities"});OpenLayers.Format.WFSCapabilities.v1=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{wfs:"http://www.opengis.net/wfs",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance",ows:"http://www.opengis.net/ows"},errorProperty:"featureTypeList",defaultPrefix:"wfs",read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));a&&9==a.nodeType&&(a=a.documentElement);var b={};this.readNode(a,b);return b},readers:{wfs:{WFS_Capabilities:function(a,
2252 b){this.readChildNodes(a,b)},FeatureTypeList:function(a,b){b.featureTypeList={featureTypes:[]};this.readChildNodes(a,b.featureTypeList)},FeatureType:function(a,b){var c={};this.readChildNodes(a,c);b.featureTypes.push(c)},Name:function(a,b){var c=this.getChildValue(a);c&&(c=c.split(":"),b.name=c.pop(),0<c.length&&(b.featureNS=this.lookupNamespaceURI(a,c[0])))},Title:function(a,b){var c=this.getChildValue(a);c&&(b.title=c)},Abstract:function(a,b){var c=this.getChildValue(a);c&&(b["abstract"]=c)}}},
2253 CLASS_NAME:"OpenLayers.Format.WFSCapabilities.v1"});OpenLayers.Format.WFSCapabilities.v1_1_0=OpenLayers.Class(OpenLayers.Format.WFSCapabilities.v1,{regExes:{trimSpace:/^\s*|\s*$/g,removeSpace:/\s*/g,splitSpace:/\s+/,trimComma:/\s*,\s*/g},readers:{wfs:OpenLayers.Util.applyDefaults({DefaultSRS:function(a,b){var c=this.getChildValue(a);c&&(b.srs=c)}},OpenLayers.Format.WFSCapabilities.v1.prototype.readers.wfs),ows:OpenLayers.Format.OWSCommon.v1.prototype.readers.ows},CLASS_NAME:"OpenLayers.Format.WFSCapabilities.v1_1_0"});OpenLayers.Layer.Image=OpenLayers.Class(OpenLayers.Layer,{isBaseLayer:!0,url:null,extent:null,size:null,tile:null,aspectRatio:null,initialize:function(a,b,c,d,e){this.url=b;this.maxExtent=this.extent=c;this.size=d;OpenLayers.Layer.prototype.initialize.apply(this,[a,e]);this.aspectRatio=this.extent.getHeight()/this.size.h/(this.extent.getWidth()/this.size.w)},destroy:function(){this.tile&&(this.removeTileMonitoringHooks(this.tile),this.tile.destroy(),this.tile=null);OpenLayers.Layer.prototype.destroy.apply(this,
2254 arguments)},clone:function(a){null==a&&(a=new OpenLayers.Layer.Image(this.name,this.url,this.extent,this.size,this.getOptions()));return a=OpenLayers.Layer.prototype.clone.apply(this,[a])},setMap:function(a){null==this.options.maxResolution&&(this.options.maxResolution=this.aspectRatio*this.extent.getWidth()/this.size.w);OpenLayers.Layer.prototype.setMap.apply(this,arguments)},moveTo:function(a,b,c){OpenLayers.Layer.prototype.moveTo.apply(this,arguments);var d=null==this.tile;if(b||d){this.setTileSize();
2255 var e=this.map.getLayerPxFromLonLat({lon:this.extent.left,lat:this.extent.top});d?(this.tile=new OpenLayers.Tile.Image(this,e,this.extent,null,this.tileSize),this.addTileMonitoringHooks(this.tile)):(this.tile.size=this.tileSize.clone(),this.tile.position=e.clone());this.tile.draw()}},setTileSize:function(){var a=this.extent.getWidth()/this.map.getResolution(),b=this.extent.getHeight()/this.map.getResolution();this.tileSize=new OpenLayers.Size(a,b)},addTileMonitoringHooks:function(a){a.onLoadStart=
2256 function(){this.events.triggerEvent("loadstart")};a.events.register("loadstart",this,a.onLoadStart);a.onLoadEnd=function(){this.events.triggerEvent("loadend")};a.events.register("loadend",this,a.onLoadEnd);a.events.register("unload",this,a.onLoadEnd)},removeTileMonitoringHooks:function(a){a.unload();a.events.un({loadstart:a.onLoadStart,loadend:a.onLoadEnd,unload:a.onLoadEnd,scope:this})},setUrl:function(a){this.url=a;this.tile.draw()},getURL:function(a){return this.url},CLASS_NAME:"OpenLayers.Layer.Image"});OpenLayers.Strategy=OpenLayers.Class({layer:null,options:null,active:null,autoActivate:!0,autoDestroy:!0,initialize:function(a){OpenLayers.Util.extend(this,a);this.options=a;this.active=!1},destroy:function(){this.deactivate();this.options=this.layer=null},setLayer:function(a){this.layer=a},activate:function(){return this.active?!1:this.active=!0},deactivate:function(){return this.active?(this.active=!1,!0):!1},CLASS_NAME:"OpenLayers.Strategy"});OpenLayers.Strategy.Save=OpenLayers.Class(OpenLayers.Strategy,{events:null,auto:!1,timer:null,initialize:function(a){OpenLayers.Strategy.prototype.initialize.apply(this,[a]);this.events=new OpenLayers.Events(this)},activate:function(){var a=OpenLayers.Strategy.prototype.activate.call(this);if(a&&this.auto)if("number"===typeof this.auto)this.timer=window.setInterval(OpenLayers.Function.bind(this.save,this),1E3*this.auto);else this.layer.events.on({featureadded:this.triggerSave,afterfeaturemodified:this.triggerSave,
2257 scope:this});return a},deactivate:function(){var a=OpenLayers.Strategy.prototype.deactivate.call(this);a&&this.auto&&("number"===typeof this.auto?window.clearInterval(this.timer):this.layer.events.un({featureadded:this.triggerSave,afterfeaturemodified:this.triggerSave,scope:this}));return a},triggerSave:function(a){var b=a.feature;b.state!==OpenLayers.State.INSERT&&b.state!==OpenLayers.State.UPDATE&&b.state!==OpenLayers.State.DELETE||this.save([a.feature])},save:function(a){a||(a=this.layer.features);
2258 this.events.triggerEvent("start",{features:a});var b=this.layer.projection,c=this.layer.map.getProjectionObject();if(!c.equals(b)){for(var d=a.length,e=Array(d),f,g,h=0;h<d;++h)f=a[h],g=f.clone(),g.fid=f.fid,g.state=f.state,f.url&&(g.url=f.url),g._original=f,g.geometry.transform(c,b),e[h]=g;a=e}this.layer.protocol.commit(a,{callback:this.onCommit,scope:this})},onCommit:function(a){var b={response:a};if(a.success()){for(var c=a.reqFeatures,d,e=[],f=a.insertIds||[],g=0,h=0,k=c.length;h<k;++h)if(d=c[h],
2259 d=d._original||d,a=d.state)a==OpenLayers.State.DELETE?e.push(d):a==OpenLayers.State.INSERT&&(d.fid=f[g],++g),d.state=null;0<e.length&&this.layer.destroyFeatures(e);this.events.triggerEvent("success",b)}else this.events.triggerEvent("fail",b)},CLASS_NAME:"OpenLayers.Strategy.Save"});OpenLayers.Events.featureclick=OpenLayers.Class({cache:null,map:null,provides:["featureclick","nofeatureclick","featureover","featureout"],initialize:function(a){this.target=a;if(a.object instanceof OpenLayers.Map)this.setMap(a.object);else if(a.object instanceof OpenLayers.Layer.Vector)a.object.map?this.setMap(a.object.map):a.object.events.register("added",this,function(b){this.setMap(a.object.map)});else throw"Listeners for '"+this.provides.join("', '")+"' events can only be registered for OpenLayers.Layer.Vector or OpenLayers.Map instances";
2260 for(var b=this.provides.length-1;0<=b;--b)a.extensions[this.provides[b]]=!0},setMap:function(a){this.map=a;this.cache={};a.events.register("mousedown",this,this.start,{extension:!0});a.events.register("mouseup",this,this.onClick,{extension:!0});a.events.register("touchstart",this,this.start,{extension:!0});a.events.register("touchmove",this,this.cancel,{extension:!0});a.events.register("touchend",this,this.onClick,{extension:!0});a.events.register("mousemove",this,this.onMousemove,{extension:!0})},
2261 start:function(a){this.startEvt=a},cancel:function(a){delete this.startEvt},onClick:function(a){if(this.startEvt&&("touchend"===a.type||OpenLayers.Event.isLeftClick(a))){a=this.getFeatures(this.startEvt);delete this.startEvt;for(var b,c,d={},e=0,f=a.length;e<f&&(b=a[e],c=b.layer,d[c.id]=!0,b=this.triggerEvent("featureclick",{feature:b}),!1!==b);++e);e=0;for(f=this.map.layers.length;e<f;++e)c=this.map.layers[e],c instanceof OpenLayers.Layer.Vector&&!d[c.id]&&this.triggerEvent("nofeatureclick",{layer:c})}},
2262 onMousemove:function(a){delete this.startEvt;var b=this.getFeatures(a),c={};a=[];for(var d,e=0,f=b.length;e<f;++e)d=b[e],c[d.id]=d,this.cache[d.id]||a.push(d);var b=[],g;for(g in this.cache)d=this.cache[g],d.layer&&d.layer.map?c[d.id]||b.push(d):delete this.cache[g];e=0;for(f=a.length;e<f&&(d=a[e],this.cache[d.id]=d,g=this.triggerEvent("featureover",{feature:d}),!1!==g);++e);e=0;for(f=b.length;e<f&&(d=b[e],delete this.cache[d.id],g=this.triggerEvent("featureout",{feature:d}),!1!==g);++e);},triggerEvent:function(a,
2263 b){var c=b.feature?b.feature.layer:b.layer,d=this.target.object;if(d instanceof OpenLayers.Map||d===c)return this.target.triggerEvent(a,b)},getFeatures:function(a){var b=a.clientX,c=a.clientY,d=[],e=[],f=[],g,h,k,l;for(l=this.map.layers.length-1;0<=l;--l)if(g=this.map.layers[l],"none"!==g.div.style.display)if(g.renderer instanceof OpenLayers.Renderer.Elements){if(g instanceof OpenLayers.Layer.Vector)for(h=document.elementFromPoint(b,c);h&&h._featureId;)(k=g.getFeatureById(h._featureId))?(d.push(k),
2264 h.style.display="none",e.push(h),h=document.elementFromPoint(b,c)):h=!1;f.push(g);g.div.style.display="none"}else g.renderer instanceof OpenLayers.Renderer.Canvas&&(k=g.renderer.getFeatureIdFromEvent(a))&&(d.push(k),f.push(g));l=0;for(a=e.length;l<a;++l)e[l].style.display="";for(l=f.length-1;0<=l;--l)f[l].div.style.display="block";return d},destroy:function(){for(var a=this.provides.length-1;0<=a;--a)delete this.target.extensions[this.provides[a]];this.map.events.un({mousemove:this.onMousemove,mousedown:this.start,
2265 mouseup:this.onClick,touchstart:this.start,touchmove:this.cancel,touchend:this.onClick,scope:this});delete this.cache;delete this.map;delete this.target}});OpenLayers.Events.nofeatureclick=OpenLayers.Events.featureclick;OpenLayers.Events.featureover=OpenLayers.Events.featureclick;OpenLayers.Events.featureout=OpenLayers.Events.featureclick;OpenLayers.Format.GPX=OpenLayers.Class(OpenLayers.Format.XML,{defaultDesc:"No description available",extractWaypoints:!0,extractTracks:!0,extractRoutes:!0,extractAttributes:!0,namespaces:{gpx:"http://www.topografix.com/GPX/1/1",xsi:"http://www.w3.org/2001/XMLSchema-instance"},schemaLocation:"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd",creator:"OpenLayers",initialize:function(a){this.externalProjection=new OpenLayers.Projection("EPSG:4326");OpenLayers.Format.XML.prototype.initialize.apply(this,
2266 [a])},read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));var b=[];if(this.extractTracks)for(var c=a.getElementsByTagName("trk"),d=0,e=c.length;d<e;d++){var f={};this.extractAttributes&&(f=this.parseAttributes(c[d]));for(var g=this.getElementsByTagNameNS(c[d],c[d].namespaceURI,"trkseg"),h=0,k=g.length;h<k;h++){var l=this.extractSegment(g[h],"trkpt");b.push(new OpenLayers.Feature.Vector(l,f))}}if(this.extractRoutes)for(e=a.getElementsByTagName("rte"),c=0,d=
2267 e.length;c<d;c++)f={},this.extractAttributes&&(f=this.parseAttributes(e[c])),g=this.extractSegment(e[c],"rtept"),b.push(new OpenLayers.Feature.Vector(g,f));if(this.extractWaypoints)for(a=a.getElementsByTagName("wpt"),c=0,e=a.length;c<e;c++)f={},this.extractAttributes&&(f=this.parseAttributes(a[c])),d=new OpenLayers.Geometry.Point(a[c].getAttribute("lon"),a[c].getAttribute("lat")),b.push(new OpenLayers.Feature.Vector(d,f));if(this.internalProjection&&this.externalProjection)for(f=0,a=b.length;f<a;f++)b[f].geometry.transform(this.externalProjection,
2268 this.internalProjection);return b},extractSegment:function(a,b){for(var c=this.getElementsByTagNameNS(a,a.namespaceURI,b),d=[],e=0,f=c.length;e<f;e++)d.push(new OpenLayers.Geometry.Point(c[e].getAttribute("lon"),c[e].getAttribute("lat")));return new OpenLayers.Geometry.LineString(d)},parseAttributes:function(a){var b={};a=a.firstChild;for(var c,d;a;)1==a.nodeType&&a.firstChild&&(c=a.firstChild,3==c.nodeType||4==c.nodeType)&&(d=a.prefix?a.nodeName.split(":")[1]:a.nodeName,"trkseg"!=d&&"rtept"!=d&&
2269 (b[d]=c.nodeValue)),a=a.nextSibling;return b},write:function(a,b){a=OpenLayers.Util.isArray(a)?a:[a];var c=this.createElementNS(this.namespaces.gpx,"gpx");c.setAttribute("version","1.1");c.setAttribute("creator",this.creator);this.setAttributes(c,{"xsi:schemaLocation":this.schemaLocation});b&&"object"==typeof b&&c.appendChild(this.buildMetadataNode(b));for(var d=0,e=a.length;d<e;d++)c.appendChild(this.buildFeatureNode(a[d]));return OpenLayers.Format.XML.prototype.write.apply(this,[c])},buildMetadataNode:function(a){for(var b=
2270 ["name","desc","author"],c=this.createElementNS(this.namespaces.gpx,"metadata"),d=0;d<b.length;d++){var e=b[d];if(a[e]){var f=this.createElementNS(this.namespaces.gpx,e);f.appendChild(this.createTextNode(a[e]));c.appendChild(f)}}return c},buildFeatureNode:function(a){var b=a.geometry,b=b.clone();this.internalProjection&&this.externalProjection&&b.transform(this.internalProjection,this.externalProjection);if("OpenLayers.Geometry.Point"==b.CLASS_NAME){var c=this.buildWptNode(b);this.appendAttributesNode(c,
2271 a);return c}c=this.createElementNS(this.namespaces.gpx,"trk");this.appendAttributesNode(c,a);a=this.buildTrkSegNode(b);a=OpenLayers.Util.isArray(a)?a:[a];for(var b=0,d=a.length;b<d;b++)c.appendChild(a[b]);return c},buildTrkSegNode:function(a){var b,c,d,e;if("OpenLayers.Geometry.LineString"==a.CLASS_NAME||"OpenLayers.Geometry.LinearRing"==a.CLASS_NAME){b=this.createElementNS(this.namespaces.gpx,"trkseg");c=0;for(d=a.components.length;c<d;c++)e=a.components[c],b.appendChild(this.buildTrkPtNode(e));
2272 return b}b=[];c=0;for(d=a.components.length;c<d;c++)b.push(this.buildTrkSegNode(a.components[c]));return b},buildTrkPtNode:function(a){var b=this.createElementNS(this.namespaces.gpx,"trkpt");b.setAttribute("lon",a.x);b.setAttribute("lat",a.y);return b},buildWptNode:function(a){var b=this.createElementNS(this.namespaces.gpx,"wpt");b.setAttribute("lon",a.x);b.setAttribute("lat",a.y);return b},appendAttributesNode:function(a,b){var c=this.createElementNS(this.namespaces.gpx,"name");c.appendChild(this.createTextNode(b.attributes.name||
2273 b.id));a.appendChild(c);c=this.createElementNS(this.namespaces.gpx,"desc");c.appendChild(this.createTextNode(b.attributes.description||this.defaultDesc));a.appendChild(c)},CLASS_NAME:"OpenLayers.Format.GPX"});OpenLayers.Format.WMSDescribeLayer=OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC,{defaultVersion:"1.1.1",CLASS_NAME:"OpenLayers.Format.WMSDescribeLayer"});OpenLayers.Format.WMSDescribeLayer.v1_1_1=OpenLayers.Class(OpenLayers.Format.WMSDescribeLayer,{initialize:function(a){OpenLayers.Format.WMSDescribeLayer.prototype.initialize.apply(this,[a])},read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));for(var b=a.documentElement.childNodes,c={layerDescriptions:[]},d,e,f=0;f<b.length;++f)if(d=b[f],e=d.nodeName,"LayerDescription"==e){e=d.getAttribute("name");var g="",h="",k="";d.getAttribute("owsType")?(g=d.getAttribute("owsType"),
2274 h=d.getAttribute("owsURL")):""!=d.getAttribute("wfs")?(g="WFS",h=d.getAttribute("wfs")):""!=d.getAttribute("wcs")&&(g="WCS",h=d.getAttribute("wcs"));d=d.getElementsByTagName("Query");0<d.length&&((k=d[0].getAttribute("typeName"))||(k=d[0].getAttribute("typename")));d={layerName:e,owsType:g,owsURL:h,typeName:k};c.layerDescriptions.push(d);c.length=c.layerDescriptions.length;c[c.length-1]=d}else if("ServiceException"==e)return{error:(new OpenLayers.Format.OGCExceptionReport).read(a)};return c},CLASS_NAME:"OpenLayers.Format.WMSDescribeLayer.v1_1_1"});
2275 OpenLayers.Format.WMSDescribeLayer.v1_1_0=OpenLayers.Format.WMSDescribeLayer.v1_1_1;OpenLayers.Layer.XYZ=OpenLayers.Class(OpenLayers.Layer.Grid,{isBaseLayer:!0,sphericalMercator:!1,zoomOffset:0,serverResolutions:null,initialize:function(a,b,c){if(c&&c.sphericalMercator||this.sphericalMercator)c=OpenLayers.Util.extend({projection:"EPSG:900913",numZoomLevels:19},c);OpenLayers.Layer.Grid.prototype.initialize.apply(this,[a||this.name,b||this.url,{},c])},clone:function(a){null==a&&(a=new OpenLayers.Layer.XYZ(this.name,this.url,this.getOptions()));return a=OpenLayers.Layer.Grid.prototype.clone.apply(this,
2276 [a])},getURL:function(a){a=this.getXYZ(a);var b=this.url;OpenLayers.Util.isArray(b)&&(b=this.selectUrl(""+a.x+a.y+a.z,b));return OpenLayers.String.format(b,a)},getXYZ:function(a){var b=this.getServerResolution(),c=Math.round((a.left-this.maxExtent.left)/(b*this.tileSize.w));a=Math.round((this.maxExtent.top-a.top)/(b*this.tileSize.h));b=this.getServerZoom();if(this.wrapDateLine)var d=Math.pow(2,b),c=(c%d+d)%d;return{x:c,y:a,z:b}},setMap:function(a){OpenLayers.Layer.Grid.prototype.setMap.apply(this,
2277 arguments);this.tileOrigin||(this.tileOrigin=new OpenLayers.LonLat(this.maxExtent.left,this.maxExtent.bottom))},CLASS_NAME:"OpenLayers.Layer.XYZ"});OpenLayers.Layer.OSM=OpenLayers.Class(OpenLayers.Layer.XYZ,{name:"OpenStreetMap",url:["http://a.tile.openstreetmap.org/${z}/${x}/${y}.png","http://b.tile.openstreetmap.org/${z}/${x}/${y}.png","http://c.tile.openstreetmap.org/${z}/${x}/${y}.png"],attribution:"&copy; <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a> contributors",sphericalMercator:!0,wrapDateLine:!0,tileOptions:null,initialize:function(a,b,c){OpenLayers.Layer.XYZ.prototype.initialize.apply(this,arguments);this.tileOptions=
2278 OpenLayers.Util.extend({crossOriginKeyword:"anonymous"},this.options&&this.options.tileOptions)},clone:function(a){null==a&&(a=new OpenLayers.Layer.OSM(this.name,this.url,this.getOptions()));return a=OpenLayers.Layer.XYZ.prototype.clone.apply(this,[a])},CLASS_NAME:"OpenLayers.Layer.OSM"});OpenLayers.Renderer=OpenLayers.Class({container:null,root:null,extent:null,locked:!1,size:null,resolution:null,map:null,featureDx:0,initialize:function(a,b){this.container=OpenLayers.Util.getElement(a);OpenLayers.Util.extend(this,b)},destroy:function(){this.map=this.resolution=this.size=this.extent=this.container=null},supported:function(){return!1},setExtent:function(a,b){this.extent=a.clone();if(this.map.baseLayer&&this.map.baseLayer.wrapDateLine){var c=a.getWidth()/this.map.getExtent().getWidth();
2279 a=a.scale(1/c);this.extent=a.wrapDateLine(this.map.getMaxExtent()).scale(c)}b&&(this.resolution=null);return!0},setSize:function(a){this.size=a.clone();this.resolution=null},getResolution:function(){return this.resolution=this.resolution||this.map.getResolution()},drawFeature:function(a,b){null==b&&(b=a.style);if(a.geometry){var c=a.geometry.getBounds();if(c){var d;this.map.baseLayer&&this.map.baseLayer.wrapDateLine&&(d=this.map.getMaxExtent());c.intersectsBounds(this.extent,{worldBounds:d})?this.calculateFeatureDx(c,
2280 d):b={display:"none"};c=this.drawGeometry(a.geometry,b,a.id);if("none"!=b.display&&b.label&&!1!==c){d=a.geometry.getCentroid();if(b.labelXOffset||b.labelYOffset){var e=isNaN(b.labelXOffset)?0:b.labelXOffset,f=isNaN(b.labelYOffset)?0:b.labelYOffset,g=this.getResolution();d.move(e*g,f*g)}this.drawText(a.id,b,d)}else this.removeText(a.id);return c}}},calculateFeatureDx:function(a,b){this.featureDx=0;if(b){var c=b.getWidth();this.featureDx=Math.round(((a.left+a.right)/2-(this.extent.left+this.extent.right)/
2281 2)/c)*c}},drawGeometry:function(a,b,c){},drawText:function(a,b,c){},removeText:function(a){},clear:function(){},getFeatureIdFromEvent:function(a){},eraseFeatures:function(a){OpenLayers.Util.isArray(a)||(a=[a]);for(var b=0,c=a.length;b<c;++b){var d=a[b];this.eraseGeometry(d.geometry,d.id);this.removeText(d.id)}},eraseGeometry:function(a,b){},moveRoot:function(a){},getRenderLayerId:function(){return this.container.id},applyDefaultSymbolizer:function(a){var b=OpenLayers.Util.extend({},OpenLayers.Renderer.defaultSymbolizer);
2282 !1===a.stroke&&(delete b.strokeWidth,delete b.strokeColor);!1===a.fill&&delete b.fillColor;OpenLayers.Util.extend(b,a);return b},CLASS_NAME:"OpenLayers.Renderer"});OpenLayers.Renderer.defaultSymbolizer={fillColor:"#000000",strokeColor:"#000000",strokeWidth:2,fillOpacity:1,strokeOpacity:1,pointRadius:0,labelAlign:"cm"};
2283 OpenLayers.Renderer.symbol={star:[350,75,379,161,469,161,397,215,423,301,350,250,277,301,303,215,231,161,321,161,350,75],cross:[4,0,6,0,6,4,10,4,10,6,6,6,6,10,4,10,4,6,0,6,0,4,4,4,4,0],x:[0,0,25,0,50,35,75,0,100,0,65,50,100,100,75,100,50,65,25,100,0,100,35,50,0,0],square:[0,0,0,1,1,1,1,0,0,0],triangle:[0,10,10,10,5,0,0,10]};OpenLayers.Renderer.Canvas=OpenLayers.Class(OpenLayers.Renderer,{hitDetection:!0,hitOverflow:0,canvas:null,features:null,pendingRedraw:!1,cachedSymbolBounds:{},initialize:function(a,b){OpenLayers.Renderer.prototype.initialize.apply(this,arguments);this.root=document.createElement("canvas");this.container.appendChild(this.root);this.canvas=this.root.getContext("2d");this.features={};this.hitDetection&&(this.hitCanvas=document.createElement("canvas"),this.hitContext=this.hitCanvas.getContext("2d"))},
2284 setExtent:function(){OpenLayers.Renderer.prototype.setExtent.apply(this,arguments);return!1},eraseGeometry:function(a,b){this.eraseFeatures(this.features[b][0])},supported:function(){return OpenLayers.CANVAS_SUPPORTED},setSize:function(a){this.size=a.clone();var b=this.root;b.style.width=a.w+"px";b.style.height=a.h+"px";b.width=a.w;b.height=a.h;this.resolution=null;this.hitDetection&&(b=this.hitCanvas,b.style.width=a.w+"px",b.style.height=a.h+"px",b.width=a.w,b.height=a.h)},drawFeature:function(a,
2285 b){var c;if(a.geometry){b=this.applyDefaultSymbolizer(b||a.style);c=a.geometry.getBounds();var d;this.map.baseLayer&&this.map.baseLayer.wrapDateLine&&(d=this.map.getMaxExtent());d=c&&c.intersectsBounds(this.extent,{worldBounds:d});(c="none"!==b.display&&!!c&&d)?this.features[a.id]=[a,b]:delete this.features[a.id];this.pendingRedraw=!0}this.pendingRedraw&&!this.locked&&(this.redraw(),this.pendingRedraw=!1);return c},drawGeometry:function(a,b,c){var d=a.CLASS_NAME;if("OpenLayers.Geometry.Collection"==
2286 d||"OpenLayers.Geometry.MultiPoint"==d||"OpenLayers.Geometry.MultiLineString"==d||"OpenLayers.Geometry.MultiPolygon"==d)for(d=0;d<a.components.length;d++)this.drawGeometry(a.components[d],b,c);else switch(a.CLASS_NAME){case "OpenLayers.Geometry.Point":this.drawPoint(a,b,c);break;case "OpenLayers.Geometry.LineString":this.drawLineString(a,b,c);break;case "OpenLayers.Geometry.LinearRing":this.drawLinearRing(a,b,c);break;case "OpenLayers.Geometry.Polygon":this.drawPolygon(a,b,c)}},drawExternalGraphic:function(a,
2287 b,c){var d=new Image,e=b.title||b.graphicTitle;e&&(d.title=e);var f=b.graphicWidth||b.graphicHeight,g=b.graphicHeight||b.graphicWidth,f=f?f:2*b.pointRadius,g=g?g:2*b.pointRadius,h=void 0!=b.graphicXOffset?b.graphicXOffset:-(0.5*f),k=void 0!=b.graphicYOffset?b.graphicYOffset:-(0.5*g),l=b.graphicOpacity||b.fillOpacity;d.onload=OpenLayers.Function.bind(function(){if(this.features[c]){var b=this.getLocalXY(a),e=b[0],b=b[1];if(!isNaN(e)&&!isNaN(b)){var e=e+h|0,b=b+k|0,p=this.canvas;p.globalAlpha=l;var q=
2288 OpenLayers.Renderer.Canvas.drawImageScaleFactor||(OpenLayers.Renderer.Canvas.drawImageScaleFactor=/android 2.1/.test(navigator.userAgent.toLowerCase())?320/window.screen.width:1);p.drawImage(d,e*q,b*q,f*q,g*q);this.hitDetection&&(this.setHitContextStyle("fill",c),this.hitContext.fillRect(e,b,f,g))}}},this);d.src=b.externalGraphic},drawNamedSymbol:function(a,b,c){var d,e,f,g;f=Math.PI/180;var h=OpenLayers.Renderer.symbol[b.graphicName];if(!h)throw Error(b.graphicName+" is not a valid symbol name");
2289 if(!(!h.length||2>h.length||(a=this.getLocalXY(a),e=a[0],g=a[1],isNaN(e)||isNaN(g)))){this.canvas.lineCap="round";this.canvas.lineJoin="round";this.hitDetection&&(this.hitContext.lineCap="round",this.hitContext.lineJoin="round");if(b.graphicName in this.cachedSymbolBounds)d=this.cachedSymbolBounds[b.graphicName];else{d=new OpenLayers.Bounds;for(a=0;a<h.length;a+=2)d.extend(new OpenLayers.LonLat(h[a],h[a+1]));this.cachedSymbolBounds[b.graphicName]=d}this.canvas.save();this.hitDetection&&this.hitContext.save();
2290 this.canvas.translate(e,g);this.hitDetection&&this.hitContext.translate(e,g);a=f*b.rotation;isNaN(a)||(this.canvas.rotate(a),this.hitDetection&&this.hitContext.rotate(a));f=2*b.pointRadius/Math.max(d.getWidth(),d.getHeight());this.canvas.scale(f,f);this.hitDetection&&this.hitContext.scale(f,f);a=d.getCenterLonLat().lon;d=d.getCenterLonLat().lat;this.canvas.translate(-a,-d);this.hitDetection&&this.hitContext.translate(-a,-d);g=b.strokeWidth;b.strokeWidth=g/f;if(!1!==b.fill){this.setCanvasStyle("fill",
2291 b);this.canvas.beginPath();for(a=0;a<h.length;a+=2)d=h[a],e=h[a+1],0==a&&this.canvas.moveTo(d,e),this.canvas.lineTo(d,e);this.canvas.closePath();this.canvas.fill();if(this.hitDetection){this.setHitContextStyle("fill",c,b);this.hitContext.beginPath();for(a=0;a<h.length;a+=2)d=h[a],e=h[a+1],0==a&&this.canvas.moveTo(d,e),this.hitContext.lineTo(d,e);this.hitContext.closePath();this.hitContext.fill()}}if(!1!==b.stroke){this.setCanvasStyle("stroke",b);this.canvas.beginPath();for(a=0;a<h.length;a+=2)d=h[a],
2292 e=h[a+1],0==a&&this.canvas.moveTo(d,e),this.canvas.lineTo(d,e);this.canvas.closePath();this.canvas.stroke();if(this.hitDetection){this.setHitContextStyle("stroke",c,b,f);this.hitContext.beginPath();for(a=0;a<h.length;a+=2)d=h[a],e=h[a+1],0==a&&this.hitContext.moveTo(d,e),this.hitContext.lineTo(d,e);this.hitContext.closePath();this.hitContext.stroke()}}b.strokeWidth=g;this.canvas.restore();this.hitDetection&&this.hitContext.restore();this.setCanvasStyle("reset")}},setCanvasStyle:function(a,b){"fill"===
2293 a?(this.canvas.globalAlpha=b.fillOpacity,this.canvas.fillStyle=b.fillColor):"stroke"===a?(this.canvas.globalAlpha=b.strokeOpacity,this.canvas.strokeStyle=b.strokeColor,this.canvas.lineWidth=b.strokeWidth):(this.canvas.globalAlpha=0,this.canvas.lineWidth=1)},featureIdToHex:function(a){a=Number(a.split("_").pop())+1;16777216<=a&&(this.hitOverflow=a-16777215,a=a%16777216+1);a="000000"+a.toString(16);var b=a.length;return a="#"+a.substring(b-6,b)},setHitContextStyle:function(a,b,c,d){b=this.featureIdToHex(b);
2294 "fill"==a?(this.hitContext.globalAlpha=1,this.hitContext.fillStyle=b):"stroke"==a?(this.hitContext.globalAlpha=1,this.hitContext.strokeStyle=b,"undefined"===typeof d?this.hitContext.lineWidth=c.strokeWidth+2:isNaN(d)||(this.hitContext.lineWidth=c.strokeWidth+2/d)):(this.hitContext.globalAlpha=0,this.hitContext.lineWidth=1)},drawPoint:function(a,b,c){if(!1!==b.graphic)if(b.externalGraphic)this.drawExternalGraphic(a,b,c);else if(b.graphicName&&"circle"!=b.graphicName)this.drawNamedSymbol(a,b,c);else{var d=
2295 this.getLocalXY(a);a=d[0];d=d[1];if(!isNaN(a)&&!isNaN(d)){var e=2*Math.PI,f=b.pointRadius;!1!==b.fill&&(this.setCanvasStyle("fill",b),this.canvas.beginPath(),this.canvas.arc(a,d,f,0,e,!0),this.canvas.fill(),this.hitDetection&&(this.setHitContextStyle("fill",c,b),this.hitContext.beginPath(),this.hitContext.arc(a,d,f,0,e,!0),this.hitContext.fill()));!1!==b.stroke&&(this.setCanvasStyle("stroke",b),this.canvas.beginPath(),this.canvas.arc(a,d,f,0,e,!0),this.canvas.stroke(),this.hitDetection&&(this.setHitContextStyle("stroke",
2296 c,b),this.hitContext.beginPath(),this.hitContext.arc(a,d,f,0,e,!0),this.hitContext.stroke()),this.setCanvasStyle("reset"))}}},drawLineString:function(a,b,c){b=OpenLayers.Util.applyDefaults({fill:!1},b);this.drawLinearRing(a,b,c)},drawLinearRing:function(a,b,c){!1!==b.fill&&(this.setCanvasStyle("fill",b),this.renderPath(this.canvas,a,b,c,"fill"),this.hitDetection&&(this.setHitContextStyle("fill",c,b),this.renderPath(this.hitContext,a,b,c,"fill")));!1!==b.stroke&&(this.setCanvasStyle("stroke",b),this.renderPath(this.canvas,
2297 a,b,c,"stroke"),this.hitDetection&&(this.setHitContextStyle("stroke",c,b),this.renderPath(this.hitContext,a,b,c,"stroke")));this.setCanvasStyle("reset")},renderPath:function(a,b,c,d,e){b=b.components;c=b.length;a.beginPath();d=this.getLocalXY(b[0]);var f=d[1];if(!isNaN(d[0])&&!isNaN(f)){a.moveTo(d[0],d[1]);for(d=1;d<c;++d)f=this.getLocalXY(b[d]),a.lineTo(f[0],f[1]);"fill"===e?a.fill():a.stroke()}},drawPolygon:function(a,b,c){a=a.components;var d=a.length;this.drawLinearRing(a[0],b,c);for(var e=1;e<
2298 d;++e)this.canvas.globalCompositeOperation="destination-out",this.hitDetection&&(this.hitContext.globalCompositeOperation="destination-out"),this.drawLinearRing(a[e],OpenLayers.Util.applyDefaults({stroke:!1,fillOpacity:1},b),c),this.canvas.globalCompositeOperation="source-over",this.hitDetection&&(this.hitContext.globalCompositeOperation="source-over"),this.drawLinearRing(a[e],OpenLayers.Util.applyDefaults({fill:!1},b),c)},drawText:function(a,b){var c=this.getLocalXY(a);this.setCanvasStyle("reset");
2299 this.canvas.fillStyle=b.fontColor;this.canvas.globalAlpha=b.fontOpacity||1;var d=[b.fontStyle?b.fontStyle:"normal","normal",b.fontWeight?b.fontWeight:"normal",b.fontSize?b.fontSize:"1em",b.fontFamily?b.fontFamily:"sans-serif"].join(" "),e=b.label.split("\n"),f=e.length;if(this.canvas.fillText){this.canvas.font=d;this.canvas.textAlign=OpenLayers.Renderer.Canvas.LABEL_ALIGN[b.labelAlign[0]]||"center";this.canvas.textBaseline=OpenLayers.Renderer.Canvas.LABEL_ALIGN[b.labelAlign[1]]||"middle";var g=OpenLayers.Renderer.Canvas.LABEL_FACTOR[b.labelAlign[1]];
2300 null==g&&(g=-0.5);d=this.canvas.measureText("Mg").height||this.canvas.measureText("xx").width;c[1]+=d*g*(f-1);for(g=0;g<f;g++)b.labelOutlineWidth&&(this.canvas.save(),this.canvas.globalAlpha=b.labelOutlineOpacity||b.fontOpacity||1,this.canvas.strokeStyle=b.labelOutlineColor,this.canvas.lineWidth=b.labelOutlineWidth,this.canvas.strokeText(e[g],c[0],c[1]+d*g+1),this.canvas.restore()),this.canvas.fillText(e[g],c[0],c[1]+d*g)}else if(this.canvas.mozDrawText){this.canvas.mozTextStyle=d;var h=OpenLayers.Renderer.Canvas.LABEL_FACTOR[b.labelAlign[0]];
2301 null==h&&(h=-0.5);g=OpenLayers.Renderer.Canvas.LABEL_FACTOR[b.labelAlign[1]];null==g&&(g=-0.5);d=this.canvas.mozMeasureText("xx");c[1]+=d*(1+g*f);for(g=0;g<f;g++){var k=c[0]+h*this.canvas.mozMeasureText(e[g]),l=c[1]+g*d;this.canvas.translate(k,l);this.canvas.mozDrawText(e[g]);this.canvas.translate(-k,-l)}}this.setCanvasStyle("reset")},getLocalXY:function(a){var b=this.getResolution(),c=this.extent;return[(a.x-this.featureDx)/b+-c.left/b,c.top/b-a.y/b]},clear:function(){var a=this.root.height,b=this.root.width;
2302 this.canvas.clearRect(0,0,b,a);this.features={};this.hitDetection&&this.hitContext.clearRect(0,0,b,a)},getFeatureIdFromEvent:function(a){var b;if(this.hitDetection&&"none"!==this.root.style.display&&!this.map.dragging&&(a=a.xy,a=this.hitContext.getImageData(a.x|0,a.y|0,1,1).data,255===a[3]&&(a=a[2]+256*(a[1]+256*a[0])))){a="OpenLayers_Feature_Vector_"+(a-1+this.hitOverflow);try{b=this.features[a][0]}catch(c){}}return b},eraseFeatures:function(a){OpenLayers.Util.isArray(a)||(a=[a]);for(var b=0;b<a.length;++b)delete this.features[a[b].id];
2303 this.redraw()},redraw:function(){if(!this.locked){var a=this.root.height,b=this.root.width;this.canvas.clearRect(0,0,b,a);this.hitDetection&&this.hitContext.clearRect(0,0,b,a);var a=[],c,d,e=this.map.baseLayer&&this.map.baseLayer.wrapDateLine&&this.map.getMaxExtent(),f;for(f in this.features)this.features.hasOwnProperty(f)&&(b=this.features[f][0],c=b.geometry,this.calculateFeatureDx(c.getBounds(),e),d=this.features[f][1],this.drawGeometry(c,d,b.id),d.label&&a.push([b,d]));b=0;for(c=a.length;b<c;++b)f=
2304 a[b],this.drawText(f[0].geometry.getCentroid(),f[1])}},CLASS_NAME:"OpenLayers.Renderer.Canvas"});OpenLayers.Renderer.Canvas.LABEL_ALIGN={l:"left",r:"right",t:"top",b:"bottom"};OpenLayers.Renderer.Canvas.LABEL_FACTOR={l:0,r:-1,t:0,b:-1};OpenLayers.Renderer.Canvas.drawImageScaleFactor=null;OpenLayers.Format.OSM=OpenLayers.Class(OpenLayers.Format.XML,{checkTags:!1,interestingTagsExclude:null,areaTags:null,initialize:function(a){var b={interestingTagsExclude:"source source_ref source:ref history attribution created_by".split(" "),areaTags:"area building leisure tourism ruins historic landuse military natural sport".split(" ")},b=OpenLayers.Util.extend(b,a),c={};for(a=0;a<b.interestingTagsExclude.length;a++)c[b.interestingTagsExclude[a]]=!0;b.interestingTagsExclude=c;c={};for(a=0;a<b.areaTags.length;a++)c[b.areaTags[a]]=
2305 !0;b.areaTags=c;this.externalProjection=new OpenLayers.Projection("EPSG:4326");OpenLayers.Format.XML.prototype.initialize.apply(this,[b])},read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));var b=this.getNodes(a),c=this.getWays(a);a=Array(c.length);for(var d=0;d<c.length;d++){for(var e=Array(c[d].nodes.length),f=this.isWayArea(c[d])?1:0,g=0;g<c[d].nodes.length;g++){var h=b[c[d].nodes[g]],k=new OpenLayers.Geometry.Point(h.lon,h.lat);k.osm_id=parseInt(c[d].nodes[g]);
2306 e[g]=k;h.used=!0}h=null;h=f?new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(e)):new OpenLayers.Geometry.LineString(e);this.internalProjection&&this.externalProjection&&h.transform(this.externalProjection,this.internalProjection);e=new OpenLayers.Feature.Vector(h,c[d].tags);e.osm_id=parseInt(c[d].id);e.fid="way."+e.osm_id;a[d]=e}for(var l in b){h=b[l];if(!h.used||this.checkTags){c=null;if(this.checkTags){c=this.getTags(h.node,!0);if(h.used&&!c[1])continue;c=c[0]}else c=this.getTags(h.node);
2307 e=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(h.lon,h.lat),c);this.internalProjection&&this.externalProjection&&e.geometry.transform(this.externalProjection,this.internalProjection);e.osm_id=parseInt(l);e.fid="node."+e.osm_id;a.push(e)}h.node=null}return a},getNodes:function(a){a=a.getElementsByTagName("node");for(var b={},c=0;c<a.length;c++){var d=a[c],e=d.getAttribute("id");b[e]={lat:d.getAttribute("lat"),lon:d.getAttribute("lon"),node:d}}return b},getWays:function(a){a=a.getElementsByTagName("way");
2308 for(var b=[],c=0;c<a.length;c++){var d=a[c],e={id:d.getAttribute("id")};e.tags=this.getTags(d);d=d.getElementsByTagName("nd");e.nodes=Array(d.length);for(var f=0;f<d.length;f++)e.nodes[f]=d[f].getAttribute("ref");b.push(e)}return b},getTags:function(a,b){for(var c=a.getElementsByTagName("tag"),d={},e=!1,f=0;f<c.length;f++){var g=c[f].getAttribute("k");d[g]=c[f].getAttribute("v");b&&(this.interestingTagsExclude[g]||(e=!0))}return b?[d,e]:d},isWayArea:function(a){var b=!1,c=!1;a.nodes[0]==a.nodes[a.nodes.length-
2309 1]&&(b=!0);if(this.checkTags)for(var d in a.tags)if(this.areaTags[d]){c=!0;break}return b&&(this.checkTags?c:!0)},write:function(a){OpenLayers.Util.isArray(a)||(a=[a]);this.osm_id=1;this.created_nodes={};var b=this.createElementNS(null,"osm");b.setAttribute("version","0.5");b.setAttribute("generator","OpenLayers "+OpenLayers.VERSION_NUMBER);for(var c=a.length-1;0<=c;c--)for(var d=this.createFeatureNodes(a[c]),e=0;e<d.length;e++)b.appendChild(d[e]);return OpenLayers.Format.XML.prototype.write.apply(this,
2310 [b])},createFeatureNodes:function(a){var b=[],c=a.geometry.CLASS_NAME,c=c.substring(c.lastIndexOf(".")+1),c=c.toLowerCase();(c=this.createXML[c])&&(b=c.apply(this,[a]));return b},createXML:{point:function(a){var b=null,c=a.geometry?a.geometry:a;this.internalProjection&&this.externalProjection&&(c=c.clone(),c.transform(this.internalProjection,this.externalProjection));var d=!1;a.osm_id?(b=a.osm_id,this.created_nodes[b]&&(d=!0)):(b=-this.osm_id,this.osm_id++);var e=d?this.created_nodes[b]:this.createElementNS(null,
2311 "node");this.created_nodes[b]=e;e.setAttribute("id",b);e.setAttribute("lon",c.x);e.setAttribute("lat",c.y);a.attributes&&this.serializeTags(a,e);this.setState(a,e);return d?[]:[e]},linestring:function(a){var b,c=[],d=a.geometry;a.osm_id?b=a.osm_id:(b=-this.osm_id,this.osm_id++);var e=this.createElementNS(null,"way");e.setAttribute("id",b);for(b=0;b<d.components.length;b++){var f=this.createXML.point.apply(this,[d.components[b]]);if(f.length){var f=f[0],g=f.getAttribute("id");c.push(f)}else g=d.components[b].osm_id,
2312 f=this.created_nodes[g];this.setState(a,f);f=this.createElementNS(null,"nd");f.setAttribute("ref",g);e.appendChild(f)}this.serializeTags(a,e);c.push(e);return c},polygon:function(a){var b=OpenLayers.Util.extend({area:"yes"},a.attributes),b=new OpenLayers.Feature.Vector(a.geometry.components[0],b);b.osm_id=a.osm_id;return this.createXML.linestring.apply(this,[b])}},serializeTags:function(a,b){for(var c in a.attributes){var d=this.createElementNS(null,"tag");d.setAttribute("k",c);d.setAttribute("v",
2313 a.attributes[c]);b.appendChild(d)}},setState:function(a,b){if(a.state){var c=null;switch(a.state){case OpenLayers.State.UPDATE:case OpenLayers.State.DELETE:c="delete"}c&&b.setAttribute("action",c)}},CLASS_NAME:"OpenLayers.Format.OSM"});OpenLayers.Handler.Keyboard=OpenLayers.Class(OpenLayers.Handler,{KEY_EVENTS:["keydown","keyup"],eventListener:null,observeElement:null,initialize:function(a,b,c){OpenLayers.Handler.prototype.initialize.apply(this,arguments);this.eventListener=OpenLayers.Function.bindAsEventListener(this.handleKeyEvent,this)},destroy:function(){this.deactivate();this.eventListener=null;OpenLayers.Handler.prototype.destroy.apply(this,arguments)},activate:function(){if(OpenLayers.Handler.prototype.activate.apply(this,
2314 arguments)){this.observeElement=this.observeElement||document;for(var a=0,b=this.KEY_EVENTS.length;a<b;a++)OpenLayers.Event.observe(this.observeElement,this.KEY_EVENTS[a],this.eventListener);return!0}return!1},deactivate:function(){var a=!1;if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){for(var a=0,b=this.KEY_EVENTS.length;a<b;a++)OpenLayers.Event.stopObserving(this.observeElement,this.KEY_EVENTS[a],this.eventListener);a=!0}return a},handleKeyEvent:function(a){this.checkModifiers(a)&&
2315 this.callback(a.type,[a])},CLASS_NAME:"OpenLayers.Handler.Keyboard"});OpenLayers.Control.ModifyFeature=OpenLayers.Class(OpenLayers.Control,{documentDrag:!1,geometryTypes:null,clickout:!0,toggle:!0,standalone:!1,layer:null,feature:null,vertex:null,vertices:null,virtualVertices:null,handlers:null,deleteCodes:null,virtualStyle:null,vertexRenderIntent:null,mode:null,createVertices:!0,modified:!1,radiusHandle:null,dragHandle:null,onModificationStart:function(){},onModification:function(){},onModificationEnd:function(){},initialize:function(a,b){b=b||{};this.layer=a;this.vertices=
2316 [];this.virtualVertices=[];this.virtualStyle=OpenLayers.Util.extend({},this.layer.style||this.layer.styleMap.createSymbolizer(null,b.vertexRenderIntent));this.virtualStyle.fillOpacity=0.3;this.virtualStyle.strokeOpacity=0.3;this.deleteCodes=[46,68];this.mode=OpenLayers.Control.ModifyFeature.RESHAPE;OpenLayers.Control.prototype.initialize.apply(this,[b]);OpenLayers.Util.isArray(this.deleteCodes)||(this.deleteCodes=[this.deleteCodes]);var c={documentDrag:this.documentDrag,stopDown:!1};this.handlers=
2317 {keyboard:new OpenLayers.Handler.Keyboard(this,{keydown:this.handleKeypress}),drag:new OpenLayers.Handler.Drag(this,{down:function(a){this.vertex=null;(a=this.layer.getFeatureFromEvent(this.handlers.drag.evt))?this.dragStart(a):this.clickout&&(this._unselect=this.feature)},move:function(a){delete this._unselect;this.vertex&&this.dragVertex(this.vertex,a)},up:function(){this.handlers.drag.stopDown=!1;this._unselect&&(this.unselectFeature(this._unselect),delete this._unselect)},done:function(a){this.vertex&&
2318 this.dragComplete(this.vertex)}},c)}},destroy:function(){this.map&&this.map.events.un({removelayer:this.handleMapEvents,changelayer:this.handleMapEvents,scope:this});this.layer=null;OpenLayers.Control.prototype.destroy.apply(this,[])},activate:function(){this.moveLayerToTop();this.map.events.on({removelayer:this.handleMapEvents,changelayer:this.handleMapEvents,scope:this});return this.handlers.keyboard.activate()&&this.handlers.drag.activate()&&OpenLayers.Control.prototype.activate.apply(this,arguments)},
2319 deactivate:function(){var a=!1;OpenLayers.Control.prototype.deactivate.apply(this,arguments)&&(this.moveLayerBack(),this.map.events.un({removelayer:this.handleMapEvents,changelayer:this.handleMapEvents,scope:this}),this.layer.removeFeatures(this.vertices,{silent:!0}),this.layer.removeFeatures(this.virtualVertices,{silent:!0}),this.vertices=[],this.handlers.drag.deactivate(),this.handlers.keyboard.deactivate(),(a=this.feature)&&(a.geometry&&a.layer)&&this.unselectFeature(a),a=!0);return a},beforeSelectFeature:function(a){return this.layer.events.triggerEvent("beforefeaturemodified",
2320 {feature:a})},selectFeature:function(a){if(!(this.feature===a||this.geometryTypes&&-1==OpenLayers.Util.indexOf(this.geometryTypes,a.geometry.CLASS_NAME))){!1!==this.beforeSelectFeature(a)&&(this.feature&&this.unselectFeature(this.feature),this.feature=a,this.layer.selectedFeatures.push(a),this.layer.drawFeature(a,"select"),this.modified=!1,this.resetVertices(),this.onModificationStart(this.feature));var b=a.modified;!a.geometry||b&&b.geometry||(this._originalGeometry=a.geometry.clone())}},unselectFeature:function(a){this.layer.removeFeatures(this.vertices,
2321 {silent:!0});this.vertices=[];this.layer.destroyFeatures(this.virtualVertices,{silent:!0});this.virtualVertices=[];this.dragHandle&&(this.layer.destroyFeatures([this.dragHandle],{silent:!0}),delete this.dragHandle);this.radiusHandle&&(this.layer.destroyFeatures([this.radiusHandle],{silent:!0}),delete this.radiusHandle);this.layer.drawFeature(this.feature,"default");this.feature=null;OpenLayers.Util.removeItem(this.layer.selectedFeatures,a);this.onModificationEnd(a);this.layer.events.triggerEvent("afterfeaturemodified",
2322 {feature:a,modified:this.modified});this.modified=!1},dragStart:function(a){var b="OpenLayers.Geometry.Point"==a.geometry.CLASS_NAME;this.standalone||(a._sketch||!b)&&a._sketch||(this.toggle&&this.feature===a&&(this._unselect=a),this.selectFeature(a));if(a._sketch||b)this.vertex=a,this.handlers.drag.stopDown=!0},dragVertex:function(a,b){var c=this.map.getLonLatFromViewPortPx(b),d=a.geometry;d.move(c.lon-d.x,c.lat-d.y);this.modified=!0;"OpenLayers.Geometry.Point"==this.feature.geometry.CLASS_NAME?
2323 this.layer.events.triggerEvent("vertexmodified",{vertex:a.geometry,feature:this.feature,pixel:b}):(a._index?(a.geometry.parent.addComponent(a.geometry,a._index),delete a._index,OpenLayers.Util.removeItem(this.virtualVertices,a),this.vertices.push(a)):a==this.dragHandle?(this.layer.removeFeatures(this.vertices,{silent:!0}),this.vertices=[],this.radiusHandle&&(this.layer.destroyFeatures([this.radiusHandle],{silent:!0}),this.radiusHandle=null)):a!==this.radiusHandle&&this.layer.events.triggerEvent("vertexmodified",
2324 {vertex:a.geometry,feature:this.feature,pixel:b}),0<this.virtualVertices.length&&(this.layer.destroyFeatures(this.virtualVertices,{silent:!0}),this.virtualVertices=[]),this.layer.drawFeature(this.feature,this.standalone?void 0:"select"));this.layer.drawFeature(a)},dragComplete:function(a){this.resetVertices();this.setFeatureState();this.onModification(this.feature);this.layer.events.triggerEvent("featuremodified",{feature:this.feature})},setFeatureState:function(){if(this.feature.state!=OpenLayers.State.INSERT&&
2325 this.feature.state!=OpenLayers.State.DELETE&&(this.feature.state=OpenLayers.State.UPDATE,this.modified&&this._originalGeometry)){var a=this.feature;a.modified=OpenLayers.Util.extend(a.modified,{geometry:this._originalGeometry});delete this._originalGeometry}},resetVertices:function(){0<this.vertices.length&&(this.layer.removeFeatures(this.vertices,{silent:!0}),this.vertices=[]);0<this.virtualVertices.length&&(this.layer.removeFeatures(this.virtualVertices,{silent:!0}),this.virtualVertices=[]);this.dragHandle&&
2326 (this.layer.destroyFeatures([this.dragHandle],{silent:!0}),this.dragHandle=null);this.radiusHandle&&(this.layer.destroyFeatures([this.radiusHandle],{silent:!0}),this.radiusHandle=null);this.feature&&"OpenLayers.Geometry.Point"!=this.feature.geometry.CLASS_NAME&&(this.mode&OpenLayers.Control.ModifyFeature.DRAG&&this.collectDragHandle(),this.mode&(OpenLayers.Control.ModifyFeature.ROTATE|OpenLayers.Control.ModifyFeature.RESIZE)&&this.collectRadiusHandle(),this.mode&OpenLayers.Control.ModifyFeature.RESHAPE&&
2327 (this.mode&OpenLayers.Control.ModifyFeature.RESIZE||this.collectVertices()))},handleKeypress:function(a){var b=a.keyCode;this.feature&&-1!=OpenLayers.Util.indexOf(this.deleteCodes,b)&&(b=this.layer.getFeatureFromEvent(this.handlers.drag.evt))&&(-1!=OpenLayers.Util.indexOf(this.vertices,b)&&!this.handlers.drag.dragging&&b.geometry.parent)&&(b.geometry.parent.removeComponent(b.geometry),this.layer.events.triggerEvent("vertexremoved",{vertex:b.geometry,feature:this.feature,pixel:a.xy}),this.layer.drawFeature(this.feature,
2328 this.standalone?void 0:"select"),this.modified=!0,this.resetVertices(),this.setFeatureState(),this.onModification(this.feature),this.layer.events.triggerEvent("featuremodified",{feature:this.feature}))},collectVertices:function(){function a(c){var d,e,f;if("OpenLayers.Geometry.Point"==c.CLASS_NAME)e=new OpenLayers.Feature.Vector(c),e._sketch=!0,e.renderIntent=b.vertexRenderIntent,b.vertices.push(e);else{f=c.components.length;"OpenLayers.Geometry.LinearRing"==c.CLASS_NAME&&(f-=1);for(d=0;d<f;++d)e=
2329 c.components[d],"OpenLayers.Geometry.Point"==e.CLASS_NAME?(e=new OpenLayers.Feature.Vector(e),e._sketch=!0,e.renderIntent=b.vertexRenderIntent,b.vertices.push(e)):a(e);if(b.createVertices&&"OpenLayers.Geometry.MultiPoint"!=c.CLASS_NAME)for(d=0,f=c.components.length;d<f-1;++d){e=c.components[d];var g=c.components[d+1];"OpenLayers.Geometry.Point"==e.CLASS_NAME&&"OpenLayers.Geometry.Point"==g.CLASS_NAME&&(e=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point((e.x+g.x)/2,(e.y+g.y)/2),null,b.virtualStyle),
2330 e.geometry.parent=c,e._index=d+1,e._sketch=!0,b.virtualVertices.push(e))}}}this.vertices=[];this.virtualVertices=[];var b=this;a.call(this,this.feature.geometry);this.layer.addFeatures(this.virtualVertices,{silent:!0});this.layer.addFeatures(this.vertices,{silent:!0})},collectDragHandle:function(){var a=this.feature.geometry,b=a.getBounds().getCenterLonLat(),b=new OpenLayers.Geometry.Point(b.lon,b.lat),c=new OpenLayers.Feature.Vector(b);b.move=function(b,c){OpenLayers.Geometry.Point.prototype.move.call(this,
2331 b,c);a.move(b,c)};c._sketch=!0;this.dragHandle=c;this.dragHandle.renderIntent=this.vertexRenderIntent;this.layer.addFeatures([this.dragHandle],{silent:!0})},collectRadiusHandle:function(){var a=this.feature.geometry,b=a.getBounds(),c=b.getCenterLonLat(),d=new OpenLayers.Geometry.Point(c.lon,c.lat),b=new OpenLayers.Geometry.Point(b.right,b.bottom),c=new OpenLayers.Feature.Vector(b),e=this.mode&OpenLayers.Control.ModifyFeature.RESIZE,f=this.mode&OpenLayers.Control.ModifyFeature.RESHAPE,g=this.mode&
2332 OpenLayers.Control.ModifyFeature.ROTATE;b.move=function(b,c){OpenLayers.Geometry.Point.prototype.move.call(this,b,c);var l=this.x-d.x,m=this.y-d.y,n=l-b,p=m-c;if(g){var q=Math.atan2(p,n),q=Math.atan2(m,l)-q,q=q*(180/Math.PI);a.rotate(q,d)}if(e){var r;f?(m/=p,r=l/n/m):(n=Math.sqrt(n*n+p*p),m=Math.sqrt(l*l+m*m)/n);a.resize(m,d,r)}};c._sketch=!0;this.radiusHandle=c;this.radiusHandle.renderIntent=this.vertexRenderIntent;this.layer.addFeatures([this.radiusHandle],{silent:!0})},setMap:function(a){this.handlers.drag.setMap(a);
2333 OpenLayers.Control.prototype.setMap.apply(this,arguments)},handleMapEvents:function(a){"removelayer"!=a.type&&"order"!=a.property||this.moveLayerToTop()},moveLayerToTop:function(){var a=Math.max(this.map.Z_INDEX_BASE.Feature-1,this.layer.getZIndex())+1;this.layer.setZIndex(a)},moveLayerBack:function(){var a=this.layer.getZIndex()-1;a>=this.map.Z_INDEX_BASE.Feature?this.layer.setZIndex(a):this.map.setLayerZIndex(this.layer,this.map.getLayerIndex(this.layer))},CLASS_NAME:"OpenLayers.Control.ModifyFeature"});
2334 OpenLayers.Control.ModifyFeature.RESHAPE=1;OpenLayers.Control.ModifyFeature.RESIZE=2;OpenLayers.Control.ModifyFeature.ROTATE=4;OpenLayers.Control.ModifyFeature.DRAG=8;OpenLayers.Layer.Bing=OpenLayers.Class(OpenLayers.Layer.XYZ,{key:null,serverResolutions:[156543.03390625,78271.516953125,39135.7584765625,19567.87923828125,9783.939619140625,4891.9698095703125,2445.9849047851562,1222.9924523925781,611.4962261962891,305.74811309814453,152.87405654907226,76.43702827453613,38.218514137268066,19.109257068634033,9.554628534317017,4.777314267158508,2.388657133579254,1.194328566789627,0.5971642833948135,0.29858214169740677,0.14929107084870338,0.07464553542435169],attributionTemplate:'<span class="olBingAttribution ${type}"><div><a target="_blank" href="http://www.bing.com/maps/"><img src="${logo}" /></a></div>${copyrights}<a style="white-space: nowrap" target="_blank" href="http://www.microsoft.com/maps/product/terms.html">Terms of Use</a></span>',
2335 metadata:null,protocolRegex:/^http:/i,type:"Road",culture:"en-US",metadataParams:null,tileOptions:null,protocol:~window.location.href.indexOf("http")?"":"http:",initialize:function(a){a=OpenLayers.Util.applyDefaults({sphericalMercator:!0},a);OpenLayers.Layer.XYZ.prototype.initialize.apply(this,[a.name||"Bing "+(a.type||this.type),null,a]);this.tileOptions=OpenLayers.Util.extend({crossOriginKeyword:"anonymous"},this.options.tileOptions);this.loadMetadata()},loadMetadata:function(){this._callbackId=
2336 "_callback_"+this.id.replace(/\./g,"_");window[this._callbackId]=OpenLayers.Function.bind(OpenLayers.Layer.Bing.processMetadata,this);var a=OpenLayers.Util.applyDefaults({key:this.key,jsonp:this._callbackId,include:"ImageryProviders"},this.metadataParams),a=this.protocol+"//dev.virtualearth.net/REST/v1/Imagery/Metadata/"+this.type+"?"+OpenLayers.Util.getParameterString(a),b=document.createElement("script");b.type="text/javascript";b.src=a;b.id=this._callbackId;document.getElementsByTagName("head")[0].appendChild(b)},
2337 initLayer:function(){var a=this.metadata.resourceSets[0].resources[0],b=a.imageUrl.replace("{quadkey}","${quadkey}"),b=b.replace("{culture}",this.culture),b=b.replace(this.protocolRegex,this.protocol);this.url=[];for(var c=0;c<a.imageUrlSubdomains.length;++c)this.url.push(b.replace("{subdomain}",a.imageUrlSubdomains[c]));this.addOptions({maxResolution:Math.min(this.serverResolutions[a.zoomMin],this.maxResolution||Number.POSITIVE_INFINITY),numZoomLevels:Math.min(a.zoomMax+1-a.zoomMin,this.numZoomLevels)},
2338 !0);this.isBaseLayer||this.redraw();this.updateAttribution()},getURL:function(a){if(this.url){var b=this.getXYZ(a);a=b.x;for(var c=b.y,b=b.z,d=[],e=b;0<e;--e){var f="0",g=1<<e-1;0!=(a&g)&&f++;0!=(c&g)&&(f++,f++);d.push(f)}d=d.join("");a=this.selectUrl(""+a+c+b,this.url);return OpenLayers.String.format(a,{quadkey:d})}},updateAttribution:function(){var a=this.metadata;if(a.resourceSets&&this.map&&this.map.center){var b=a.resourceSets[0].resources[0],c=this.map.getExtent().transform(this.map.getProjectionObject(),
2339 new OpenLayers.Projection("EPSG:4326")),d=b.imageryProviders||[],e=OpenLayers.Util.indexOf(this.serverResolutions,this.getServerResolution()),b="",f,g,h,k,l,m,n;g=0;for(h=d.length;g<h;++g)for(f=d[g],k=0,l=f.coverageAreas.length;k<l;++k)n=f.coverageAreas[k],m=OpenLayers.Bounds.fromArray(n.bbox,!0),c.intersectsBounds(m)&&(e<=n.zoomMax&&e>=n.zoomMin)&&(b+=f.attribution+" ");a=a.brandLogoUri.replace(this.protocolRegex,this.protocol);this.attribution=OpenLayers.String.format(this.attributionTemplate,{type:this.type.toLowerCase(),
2340 logo:a,copyrights:b});this.map&&this.map.events.triggerEvent("changelayer",{layer:this,property:"attribution"})}},setMap:function(){OpenLayers.Layer.XYZ.prototype.setMap.apply(this,arguments);this.map.events.register("moveend",this,this.updateAttribution)},clone:function(a){null==a&&(a=new OpenLayers.Layer.Bing(this.options));return a=OpenLayers.Layer.XYZ.prototype.clone.apply(this,[a])},destroy:function(){this.map&&this.map.events.unregister("moveend",this,this.updateAttribution);OpenLayers.Layer.XYZ.prototype.destroy.apply(this,
2341 arguments)},CLASS_NAME:"OpenLayers.Layer.Bing"});OpenLayers.Layer.Bing.processMetadata=function(a){this.metadata=a;this.initLayer();a=document.getElementById(this._callbackId);a.parentNode.removeChild(a);window[this._callbackId]=void 0;delete this._callbackId};OpenLayers.StyleMap=OpenLayers.Class({styles:null,extendDefault:!0,initialize:function(a,b){this.styles={"default":new OpenLayers.Style(OpenLayers.Feature.Vector.style["default"]),select:new OpenLayers.Style(OpenLayers.Feature.Vector.style.select),temporary:new OpenLayers.Style(OpenLayers.Feature.Vector.style.temporary),"delete":new OpenLayers.Style(OpenLayers.Feature.Vector.style["delete"])};if(a instanceof OpenLayers.Style)this.styles["default"]=a,this.styles.select=a,this.styles.temporary=a,this.styles["delete"]=
2342 a;else if("object"==typeof a)for(var c in a)if(a[c]instanceof OpenLayers.Style)this.styles[c]=a[c];else if("object"==typeof a[c])this.styles[c]=new OpenLayers.Style(a[c]);else{this.styles["default"]=new OpenLayers.Style(a);this.styles.select=new OpenLayers.Style(a);this.styles.temporary=new OpenLayers.Style(a);this.styles["delete"]=new OpenLayers.Style(a);break}OpenLayers.Util.extend(this,b)},destroy:function(){for(var a in this.styles)this.styles[a].destroy();this.styles=null},createSymbolizer:function(a,
2343 b){a||(a=new OpenLayers.Feature.Vector);this.styles[b]||(b="default");a.renderIntent=b;var c={};this.extendDefault&&"default"!=b&&(c=this.styles["default"].createSymbolizer(a));return OpenLayers.Util.extend(c,this.styles[b].createSymbolizer(a))},addUniqueValueRules:function(a,b,c,d){var e=[],f;for(f in c)e.push(new OpenLayers.Rule({symbolizer:c[f],context:d,filter:new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.EQUAL_TO,property:b,value:f})}));this.styles[a].addRules(e)},CLASS_NAME:"OpenLayers.StyleMap"});OpenLayers.Layer.Vector=OpenLayers.Class(OpenLayers.Layer,{isBaseLayer:!1,isFixed:!1,features:null,filter:null,selectedFeatures:null,unrenderedFeatures:null,reportError:!0,style:null,styleMap:null,strategies:null,protocol:null,renderers:["SVG","VML","Canvas"],renderer:null,rendererOptions:null,geometryType:null,drawn:!1,ratio:1,initialize:function(a,b){OpenLayers.Layer.prototype.initialize.apply(this,arguments);this.renderer&&this.renderer.supported()||this.assignRenderer();this.renderer&&this.renderer.supported()||
2344 (this.renderer=null,this.displayError());this.styleMap||(this.styleMap=new OpenLayers.StyleMap);this.features=[];this.selectedFeatures=[];this.unrenderedFeatures={};if(this.strategies)for(var c=0,d=this.strategies.length;c<d;c++)this.strategies[c].setLayer(this)},destroy:function(){if(this.strategies){var a,b,c;b=0;for(c=this.strategies.length;b<c;b++)a=this.strategies[b],a.autoDestroy&&a.destroy();this.strategies=null}this.protocol&&(this.protocol.autoDestroy&&this.protocol.destroy(),this.protocol=
2345 null);this.destroyFeatures();this.unrenderedFeatures=this.selectedFeatures=this.features=null;this.renderer&&this.renderer.destroy();this.drawn=this.geometryType=this.renderer=null;OpenLayers.Layer.prototype.destroy.apply(this,arguments)},clone:function(a){null==a&&(a=new OpenLayers.Layer.Vector(this.name,this.getOptions()));a=OpenLayers.Layer.prototype.clone.apply(this,[a]);for(var b=this.features,c=b.length,d=Array(c),e=0;e<c;++e)d[e]=b[e].clone();a.features=d;return a},refresh:function(a){this.calculateInRange()&&
2346 this.visibility&&this.events.triggerEvent("refresh",a)},assignRenderer:function(){for(var a=0,b=this.renderers.length;a<b;a++){var c=this.renderers[a];if((c="function"==typeof c?c:OpenLayers.Renderer[c])&&c.prototype.supported()){this.renderer=new c(this.div,this.rendererOptions);break}}},displayError:function(){this.reportError&&OpenLayers.Console.userError(OpenLayers.i18n("browserNotSupported",{renderers:this.renderers.join("\n")}))},setMap:function(a){OpenLayers.Layer.prototype.setMap.apply(this,
2347 arguments);if(this.renderer){this.renderer.map=this.map;var b=this.map.getSize();b.w*=this.ratio;b.h*=this.ratio;this.renderer.setSize(b)}else this.map.removeLayer(this)},afterAdd:function(){if(this.strategies){var a,b,c;b=0;for(c=this.strategies.length;b<c;b++)a=this.strategies[b],a.autoActivate&&a.activate()}},removeMap:function(a){this.drawn=!1;if(this.strategies){var b,c;b=0;for(c=this.strategies.length;b<c;b++)a=this.strategies[b],a.autoActivate&&a.deactivate()}},onMapResize:function(){OpenLayers.Layer.prototype.onMapResize.apply(this,
2348 arguments);var a=this.map.getSize();a.w*=this.ratio;a.h*=this.ratio;this.renderer.setSize(a)},moveTo:function(a,b,c){OpenLayers.Layer.prototype.moveTo.apply(this,arguments);var d=!0;if(!c){this.renderer.root.style.visibility="hidden";var d=this.map.getSize(),e=d.w,d=d.h,e=e/2*this.ratio-e/2,d=d/2*this.ratio-d/2,e=e+this.map.layerContainerOriginPx.x,e=-Math.round(e),d=d+this.map.layerContainerOriginPx.y,d=-Math.round(d);this.div.style.left=e+"px";this.div.style.top=d+"px";e=this.map.getExtent().scale(this.ratio);
2349 d=this.renderer.setExtent(e,b);this.renderer.root.style.visibility="visible";!0===OpenLayers.IS_GECKO&&(this.div.scrollLeft=this.div.scrollLeft);if(!b&&d)for(var f in this.unrenderedFeatures)e=this.unrenderedFeatures[f],this.drawFeature(e)}if(!this.drawn||b||!d)for(this.drawn=!0,f=0,d=this.features.length;f<d;f++)this.renderer.locked=f!==d-1,e=this.features[f],this.drawFeature(e)},display:function(a){OpenLayers.Layer.prototype.display.apply(this,arguments);var b=this.div.style.display;b!=this.renderer.root.style.display&&
2350 (this.renderer.root.style.display=b)},addFeatures:function(a,b){OpenLayers.Util.isArray(a)||(a=[a]);var c=!b||!b.silent;if(c){var d={features:a};if(!1===this.events.triggerEvent("beforefeaturesadded",d))return;a=d.features}for(var d=[],e=0,f=a.length;e<f;e++){this.renderer.locked=e!=a.length-1?!0:!1;var g=a[e];if(this.geometryType&&!(g.geometry instanceof this.geometryType))throw new TypeError("addFeatures: component should be an "+this.geometryType.prototype.CLASS_NAME);g.layer=this;!g.style&&this.style&&
2351 (g.style=OpenLayers.Util.extend({},this.style));if(c){if(!1===this.events.triggerEvent("beforefeatureadded",{feature:g}))continue;this.preFeatureInsert(g)}d.push(g);this.features.push(g);this.drawFeature(g);c&&(this.events.triggerEvent("featureadded",{feature:g}),this.onFeatureInsert(g))}c&&this.events.triggerEvent("featuresadded",{features:d})},removeFeatures:function(a,b){if(a&&0!==a.length){if(a===this.features)return this.removeAllFeatures(b);OpenLayers.Util.isArray(a)||(a=[a]);a===this.selectedFeatures&&
2352 (a=a.slice());var c=!b||!b.silent;c&&this.events.triggerEvent("beforefeaturesremoved",{features:a});for(var d=a.length-1;0<=d;d--){this.renderer.locked=0!=d&&a[d-1].geometry?!0:!1;var e=a[d];delete this.unrenderedFeatures[e.id];c&&this.events.triggerEvent("beforefeatureremoved",{feature:e});this.features=OpenLayers.Util.removeItem(this.features,e);e.layer=null;e.geometry&&this.renderer.eraseFeatures(e);-1!=OpenLayers.Util.indexOf(this.selectedFeatures,e)&&OpenLayers.Util.removeItem(this.selectedFeatures,
2353 e);c&&this.events.triggerEvent("featureremoved",{feature:e})}c&&this.events.triggerEvent("featuresremoved",{features:a})}},removeAllFeatures:function(a){a=!a||!a.silent;var b=this.features;a&&this.events.triggerEvent("beforefeaturesremoved",{features:b});for(var c,d=b.length-1;0<=d;d--)c=b[d],a&&this.events.triggerEvent("beforefeatureremoved",{feature:c}),c.layer=null,a&&this.events.triggerEvent("featureremoved",{feature:c});this.renderer.clear();this.features=[];this.unrenderedFeatures={};this.selectedFeatures=
2354 [];a&&this.events.triggerEvent("featuresremoved",{features:b})},destroyFeatures:function(a,b){void 0==a&&(a=this.features);if(a){this.removeFeatures(a,b);for(var c=a.length-1;0<=c;c--)a[c].destroy()}},drawFeature:function(a,b){if(this.drawn){if("object"!=typeof b){b||a.state!==OpenLayers.State.DELETE||(b="delete");var c=b||a.renderIntent;(b=a.style||this.style)||(b=this.styleMap.createSymbolizer(a,c))}c=this.renderer.drawFeature(a,b);!1===c||null===c?this.unrenderedFeatures[a.id]=a:delete this.unrenderedFeatures[a.id]}},
2355 eraseFeatures:function(a){this.renderer.eraseFeatures(a)},getFeatureFromEvent:function(a){if(!this.renderer)throw Error("getFeatureFromEvent called on layer with no renderer. This usually means you destroyed a layer, but not some handler which is associated with it.");var b=null;(a=this.renderer.getFeatureIdFromEvent(a))&&(b="string"===typeof a?this.getFeatureById(a):a);return b},getFeatureBy:function(a,b){for(var c=null,d=0,e=this.features.length;d<e;++d)if(this.features[d][a]==b){c=this.features[d];
2356 break}return c},getFeatureById:function(a){return this.getFeatureBy("id",a)},getFeatureByFid:function(a){return this.getFeatureBy("fid",a)},getFeaturesByAttribute:function(a,b){var c,d,e=this.features.length,f=[];for(c=0;c<e;c++)(d=this.features[c])&&d.attributes&&d.attributes[a]===b&&f.push(d);return f},onFeatureInsert:function(a){},preFeatureInsert:function(a){},getDataExtent:function(){var a=null,b=this.features;if(b&&0<b.length)for(var c=null,d=0,e=b.length;d<e;d++)if(c=b[d].geometry)null===a&&
2357 (a=new OpenLayers.Bounds),a.extend(c.getBounds());return a},CLASS_NAME:"OpenLayers.Layer.Vector"});OpenLayers.Layer.PointGrid=OpenLayers.Class(OpenLayers.Layer.Vector,{dx:null,dy:null,ratio:1.5,maxFeatures:250,rotation:0,origin:null,gridBounds:null,initialize:function(a){a=a||{};OpenLayers.Layer.Vector.prototype.initialize.apply(this,[a.name,a])},setMap:function(a){OpenLayers.Layer.Vector.prototype.setMap.apply(this,arguments);a.events.register("moveend",this,this.onMoveEnd)},removeMap:function(a){a.events.unregister("moveend",this,this.onMoveEnd);OpenLayers.Layer.Vector.prototype.removeMap.apply(this,
2358 arguments)},setRatio:function(a){this.ratio=a;this.updateGrid(!0)},setMaxFeatures:function(a){this.maxFeatures=a;this.updateGrid(!0)},setSpacing:function(a,b){this.dx=a;this.dy=b||a;this.updateGrid(!0)},setOrigin:function(a){this.origin=a;this.updateGrid(!0)},getOrigin:function(){this.origin||(this.origin=this.map.getExtent().getCenterLonLat());return this.origin},setRotation:function(a){this.rotation=a;this.updateGrid(!0)},onMoveEnd:function(){this.updateGrid()},getViewBounds:function(){var a=this.map.getExtent();
2359 if(this.rotation){var b=this.getOrigin(),b=new OpenLayers.Geometry.Point(b.lon,b.lat),a=a.toGeometry();a.rotate(-this.rotation,b);a=a.getBounds()}return a},updateGrid:function(a){if(a||this.invalidBounds()){var b=this.getViewBounds(),c=this.getOrigin();a=new OpenLayers.Geometry.Point(c.lon,c.lat);var d=b.getWidth(),e=b.getHeight(),f=d/e,g=Math.sqrt(this.dx*this.dy*this.maxFeatures/f),d=Math.min(d*this.ratio,g*f),e=Math.min(e*this.ratio,g),b=b.getCenterLonLat();this.gridBounds=new OpenLayers.Bounds(b.lon-
2360 d/2,b.lat-e/2,b.lon+d/2,b.lat+e/2);for(var b=Math.floor(e/this.dy),d=Math.floor(d/this.dx),e=c.lon+this.dx*Math.ceil((this.gridBounds.left-c.lon)/this.dx),c=c.lat+this.dy*Math.ceil((this.gridBounds.bottom-c.lat)/this.dy),g=Array(b*d),h,k=0;k<d;++k)for(var f=e+k*this.dx,l=0;l<b;++l)h=c+l*this.dy,h=new OpenLayers.Geometry.Point(f,h),this.rotation&&h.rotate(this.rotation,a),g[k*b+l]=new OpenLayers.Feature.Vector(h);this.destroyFeatures(this.features,{silent:!0});this.addFeatures(g,{silent:!0})}},invalidBounds:function(){return!this.gridBounds||
2361 !this.gridBounds.containsBounds(this.getViewBounds())},CLASS_NAME:"OpenLayers.Layer.PointGrid"});OpenLayers.Handler.MouseWheel=OpenLayers.Class(OpenLayers.Handler,{wheelListener:null,interval:0,maxDelta:Number.POSITIVE_INFINITY,delta:0,cumulative:!0,initialize:function(a,b,c){OpenLayers.Handler.prototype.initialize.apply(this,arguments);this.wheelListener=OpenLayers.Function.bindAsEventListener(this.onWheelEvent,this)},destroy:function(){OpenLayers.Handler.prototype.destroy.apply(this,arguments);this.wheelListener=null},onWheelEvent:function(a){if(this.map&&this.checkModifiers(a)){for(var b=
2362 !1,c=!1,d=!1,e=OpenLayers.Event.element(a);null!=e&&!d&&!b;){if(!b)try{var f,b=(f=e.currentStyle?e.currentStyle.overflow:document.defaultView.getComputedStyle(e,null).getPropertyValue("overflow"))&&"auto"==f||"scroll"==f}catch(g){}if(!c&&(c=OpenLayers.Element.hasClass(e,"olScrollable"),!c))for(var d=0,h=this.map.layers.length;d<h;d++){var k=this.map.layers[d];if(e==k.div||e==k.pane){c=!0;break}}d=e==this.map.div;e=e.parentNode}if(!b&&d){if(c)if(b=0,a.wheelDelta?(b=a.wheelDelta,0===b%160&&(b*=0.75),
2363 b/=120):a.detail&&(b=-(a.detail/Math.abs(a.detail))),this.delta+=b,window.clearTimeout(this._timeoutId),this.interval&&Math.abs(this.delta)<this.maxDelta){var l=OpenLayers.Util.extend({},a);this._timeoutId=window.setTimeout(OpenLayers.Function.bind(function(){this.wheelZoom(l)},this),this.interval)}else this.wheelZoom(a);OpenLayers.Event.stop(a)}}},wheelZoom:function(a){var b=this.delta;this.delta=0;b&&(a.xy=this.map.events.getMousePosition(a),0>b?this.callback("down",[a,this.cumulative?Math.max(-this.maxDelta,
2364 b):-1]):this.callback("up",[a,this.cumulative?Math.min(this.maxDelta,b):1]))},activate:function(a){if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){var b=this.wheelListener;OpenLayers.Event.observe(window,"DOMMouseScroll",b);OpenLayers.Event.observe(window,"mousewheel",b);OpenLayers.Event.observe(document,"mousewheel",b);return!0}return!1},deactivate:function(a){if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){var b=this.wheelListener;OpenLayers.Event.stopObserving(window,
2365 "DOMMouseScroll",b);OpenLayers.Event.stopObserving(window,"mousewheel",b);OpenLayers.Event.stopObserving(document,"mousewheel",b);return!0}return!1},CLASS_NAME:"OpenLayers.Handler.MouseWheel"});OpenLayers.Symbolizer=OpenLayers.Class({zIndex:0,initialize:function(a){OpenLayers.Util.extend(this,a)},clone:function(){return new (eval(this.CLASS_NAME))(OpenLayers.Util.extend({},this))},CLASS_NAME:"OpenLayers.Symbolizer"});OpenLayers.Symbolizer.Raster=OpenLayers.Class(OpenLayers.Symbolizer,{initialize:function(a){OpenLayers.Symbolizer.prototype.initialize.apply(this,arguments)},CLASS_NAME:"OpenLayers.Symbolizer.Raster"});OpenLayers.Rule=OpenLayers.Class({id:null,name:null,title:null,description:null,context:null,filter:null,elseFilter:!1,symbolizer:null,symbolizers:null,minScaleDenominator:null,maxScaleDenominator:null,initialize:function(a){this.symbolizer={};OpenLayers.Util.extend(this,a);this.symbolizers&&delete this.symbolizer;this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_")},destroy:function(){for(var a in this.symbolizer)this.symbolizer[a]=null;this.symbolizer=null;delete this.symbolizers},evaluate:function(a){var b=
2366 this.getContext(a),c=!0;if(this.minScaleDenominator||this.maxScaleDenominator)var d=a.layer.map.getScale();this.minScaleDenominator&&(c=d>=OpenLayers.Style.createLiteral(this.minScaleDenominator,b));c&&this.maxScaleDenominator&&(c=d<OpenLayers.Style.createLiteral(this.maxScaleDenominator,b));c&&this.filter&&(c="OpenLayers.Filter.FeatureId"==this.filter.CLASS_NAME?this.filter.evaluate(a):this.filter.evaluate(b));return c},getContext:function(a){var b=this.context;b||(b=a.attributes||a.data);"function"==
2367 typeof this.context&&(b=this.context(a));return b},clone:function(){var a=OpenLayers.Util.extend({},this);if(this.symbolizers){var b=this.symbolizers.length;a.symbolizers=Array(b);for(var c=0;c<b;++c)a.symbolizers[c]=this.symbolizers[c].clone()}else{a.symbolizer={};for(var d in this.symbolizer)b=this.symbolizer[d],c=typeof b,"object"===c?a.symbolizer[d]=OpenLayers.Util.extend({},b):"string"===c&&(a.symbolizer[d]=b)}a.filter=this.filter&&this.filter.clone();a.context=this.context&&OpenLayers.Util.extend({},
2368 this.context);return new OpenLayers.Rule(a)},CLASS_NAME:"OpenLayers.Rule"});OpenLayers.Format.SLD=OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC,{profile:null,defaultVersion:"1.0.0",stringifyOutput:!0,namedLayersAsArray:!1,CLASS_NAME:"OpenLayers.Format.SLD"});OpenLayers.Symbolizer.Polygon=OpenLayers.Class(OpenLayers.Symbolizer,{initialize:function(a){OpenLayers.Symbolizer.prototype.initialize.apply(this,arguments)},CLASS_NAME:"OpenLayers.Symbolizer.Polygon"});OpenLayers.Format.GML.v2=OpenLayers.Class(OpenLayers.Format.GML.Base,{schemaLocation:"http://www.opengis.net/gml http://schemas.opengis.net/gml/2.1.2/feature.xsd",initialize:function(a){OpenLayers.Format.GML.Base.prototype.initialize.apply(this,[a])},readers:{gml:OpenLayers.Util.applyDefaults({outerBoundaryIs:function(a,b){var c={};this.readChildNodes(a,c);b.outer=c.components[0]},innerBoundaryIs:function(a,b){var c={};this.readChildNodes(a,c);b.inner.push(c.components[0])},Box:function(a,b){var c=
2369 {};this.readChildNodes(a,c);b.components||(b.components=[]);var d=c.points[0],c=c.points[1];b.components.push(new OpenLayers.Bounds(d.x,d.y,c.x,c.y))}},OpenLayers.Format.GML.Base.prototype.readers.gml),feature:OpenLayers.Format.GML.Base.prototype.readers.feature,wfs:OpenLayers.Format.GML.Base.prototype.readers.wfs},write:function(a){var b;b=OpenLayers.Util.isArray(a)?"wfs:FeatureCollection":"gml:featureMember";a=this.writeNode(b,a);this.setAttributeNS(a,this.namespaces.xsi,"xsi:schemaLocation",this.schemaLocation);
2370 return OpenLayers.Format.XML.prototype.write.apply(this,[a])},writers:{gml:OpenLayers.Util.applyDefaults({Point:function(a){var b=this.createElementNSPlus("gml:Point");this.writeNode("coordinates",[a],b);return b},coordinates:function(a){for(var b=a.length,c=Array(b),d,e=0;e<b;++e)d=a[e],c[e]=this.xy?d.x+","+d.y:d.y+","+d.x,void 0!=d.z&&(c[e]+=","+d.z);return this.createElementNSPlus("gml:coordinates",{attributes:{decimal:".",cs:",",ts:" "},value:1==b?c[0]:c.join(" ")})},LineString:function(a){var b=
2371 this.createElementNSPlus("gml:LineString");this.writeNode("coordinates",a.components,b);return b},Polygon:function(a){var b=this.createElementNSPlus("gml:Polygon");this.writeNode("outerBoundaryIs",a.components[0],b);for(var c=1;c<a.components.length;++c)this.writeNode("innerBoundaryIs",a.components[c],b);return b},outerBoundaryIs:function(a){var b=this.createElementNSPlus("gml:outerBoundaryIs");this.writeNode("LinearRing",a,b);return b},innerBoundaryIs:function(a){var b=this.createElementNSPlus("gml:innerBoundaryIs");
2372 this.writeNode("LinearRing",a,b);return b},LinearRing:function(a){var b=this.createElementNSPlus("gml:LinearRing");this.writeNode("coordinates",a.components,b);return b},Box:function(a){var b=this.createElementNSPlus("gml:Box");this.writeNode("coordinates",[{x:a.left,y:a.bottom},{x:a.right,y:a.top}],b);this.srsName&&b.setAttribute("srsName",this.srsName);return b}},OpenLayers.Format.GML.Base.prototype.writers.gml),feature:OpenLayers.Format.GML.Base.prototype.writers.feature,wfs:OpenLayers.Format.GML.Base.prototype.writers.wfs},
2373 CLASS_NAME:"OpenLayers.Format.GML.v2"});OpenLayers.Format.Filter.v1_0_0=OpenLayers.Class(OpenLayers.Format.GML.v2,OpenLayers.Format.Filter.v1,{VERSION:"1.0.0",schemaLocation:"http://www.opengis.net/ogc/filter/1.0.0/filter.xsd",initialize:function(a){OpenLayers.Format.GML.v2.prototype.initialize.apply(this,[a])},readers:{ogc:OpenLayers.Util.applyDefaults({PropertyIsEqualTo:function(a,b){var c=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.EQUAL_TO});this.readChildNodes(a,c);b.filters.push(c)},PropertyIsNotEqualTo:function(a,
2374 b){var c=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.NOT_EQUAL_TO});this.readChildNodes(a,c);b.filters.push(c)},PropertyIsLike:function(a,b){var c=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.LIKE});this.readChildNodes(a,c);var d=a.getAttribute("wildCard"),e=a.getAttribute("singleChar"),f=a.getAttribute("escape");c.value2regex(d,e,f);b.filters.push(c)}},OpenLayers.Format.Filter.v1.prototype.readers.ogc),gml:OpenLayers.Format.GML.v2.prototype.readers.gml,
2375 feature:OpenLayers.Format.GML.v2.prototype.readers.feature},writers:{ogc:OpenLayers.Util.applyDefaults({PropertyIsEqualTo:function(a){var b=this.createElementNSPlus("ogc:PropertyIsEqualTo");this.writeNode("PropertyName",a,b);this.writeOgcExpression(a.value,b);return b},PropertyIsNotEqualTo:function(a){var b=this.createElementNSPlus("ogc:PropertyIsNotEqualTo");this.writeNode("PropertyName",a,b);this.writeOgcExpression(a.value,b);return b},PropertyIsLike:function(a){var b=this.createElementNSPlus("ogc:PropertyIsLike",
2376 {attributes:{wildCard:"*",singleChar:".",escape:"!"}});this.writeNode("PropertyName",a,b);this.writeNode("Literal",a.regex2value(),b);return b},BBOX:function(a){var b=this.createElementNSPlus("ogc:BBOX");a.property&&this.writeNode("PropertyName",a,b);var c=this.writeNode("gml:Box",a.value,b);a.projection&&c.setAttribute("srsName",a.projection);return b}},OpenLayers.Format.Filter.v1.prototype.writers.ogc),gml:OpenLayers.Format.GML.v2.prototype.writers.gml,feature:OpenLayers.Format.GML.v2.prototype.writers.feature},
2377 writeSpatial:function(a,b){var c=this.createElementNSPlus("ogc:"+b);this.writeNode("PropertyName",a,c);if(a.value instanceof OpenLayers.Filter.Function)this.writeNode("Function",a.value,c);else{var d;d=a.value instanceof OpenLayers.Geometry?this.writeNode("feature:_geometry",a.value).firstChild:this.writeNode("gml:Box",a.value);a.projection&&d.setAttribute("srsName",a.projection);c.appendChild(d)}return c},CLASS_NAME:"OpenLayers.Format.Filter.v1_0_0"});OpenLayers.Format.WFST.v1_0_0=OpenLayers.Class(OpenLayers.Format.Filter.v1_0_0,OpenLayers.Format.WFST.v1,{version:"1.0.0",srsNameInQuery:!1,schemaLocations:{wfs:"http://schemas.opengis.net/wfs/1.0.0/WFS-transaction.xsd"},initialize:function(a){OpenLayers.Format.Filter.v1_0_0.prototype.initialize.apply(this,[a]);OpenLayers.Format.WFST.v1.prototype.initialize.apply(this,[a])},readNode:function(a,b,c){return OpenLayers.Format.GML.v2.prototype.readNode.apply(this,arguments)},readers:{wfs:OpenLayers.Util.applyDefaults({WFS_TransactionResponse:function(a,
2378 b){b.insertIds=[];b.success=!1;this.readChildNodes(a,b)},InsertResult:function(a,b){var c={fids:[]};this.readChildNodes(a,c);b.insertIds=b.insertIds.concat(c.fids)},TransactionResult:function(a,b){this.readChildNodes(a,b)},Status:function(a,b){this.readChildNodes(a,b)},SUCCESS:function(a,b){b.success=!0}},OpenLayers.Format.WFST.v1.prototype.readers.wfs),gml:OpenLayers.Format.GML.v2.prototype.readers.gml,feature:OpenLayers.Format.GML.v2.prototype.readers.feature,ogc:OpenLayers.Format.Filter.v1_0_0.prototype.readers.ogc},
2379 writers:{wfs:OpenLayers.Util.applyDefaults({Query:function(a){a=OpenLayers.Util.extend({featureNS:this.featureNS,featurePrefix:this.featurePrefix,featureType:this.featureType,srsName:this.srsName,srsNameInQuery:this.srsNameInQuery},a);var b=a.featurePrefix,c=this.createElementNSPlus("wfs:Query",{attributes:{typeName:(b?b+":":"")+a.featureType}});a.srsNameInQuery&&a.srsName&&c.setAttribute("srsName",a.srsName);a.featureNS&&c.setAttribute("xmlns:"+b,a.featureNS);if(a.propertyNames)for(var b=0,d=a.propertyNames.length;b<
2380 d;b++)this.writeNode("ogc:PropertyName",{property:a.propertyNames[b]},c);a.filter&&(this.setFilterProperty(a.filter),this.writeNode("ogc:Filter",a.filter,c));return c}},OpenLayers.Format.WFST.v1.prototype.writers.wfs),gml:OpenLayers.Format.GML.v2.prototype.writers.gml,feature:OpenLayers.Format.GML.v2.prototype.writers.feature,ogc:OpenLayers.Format.Filter.v1_0_0.prototype.writers.ogc},CLASS_NAME:"OpenLayers.Format.WFST.v1_0_0"});OpenLayers.ElementsIndexer=OpenLayers.Class({maxZIndex:null,order:null,indices:null,compare:null,initialize:function(a){this.compare=a?OpenLayers.ElementsIndexer.IndexingMethods.Z_ORDER_Y_ORDER:OpenLayers.ElementsIndexer.IndexingMethods.Z_ORDER_DRAWING_ORDER;this.clear()},insert:function(a){this.exists(a)&&this.remove(a);var b=a.id;this.determineZIndex(a);for(var c=-1,d=this.order.length,e;1<d-c;)e=parseInt((c+d)/2),0<this.compare(this,a,OpenLayers.Util.getElement(this.order[e]))?c=e:d=e;this.order.splice(d,
2381 0,b);this.indices[b]=this.getZIndex(a);return this.getNextElement(d)},remove:function(a){a=a.id;var b=OpenLayers.Util.indexOf(this.order,a);0<=b&&(this.order.splice(b,1),delete this.indices[a],this.maxZIndex=0<this.order.length?this.indices[this.order[this.order.length-1]]:0)},clear:function(){this.order=[];this.indices={};this.maxZIndex=0},exists:function(a){return null!=this.indices[a.id]},getZIndex:function(a){return a._style.graphicZIndex},determineZIndex:function(a){var b=a._style.graphicZIndex;
2382 null==b?(b=this.maxZIndex,a._style.graphicZIndex=b):b>this.maxZIndex&&(this.maxZIndex=b)},getNextElement:function(a){a+=1;if(a<this.order.length){var b=OpenLayers.Util.getElement(this.order[a]);void 0==b&&(b=this.getNextElement(a));return b}return null},CLASS_NAME:"OpenLayers.ElementsIndexer"});
2383 OpenLayers.ElementsIndexer.IndexingMethods={Z_ORDER:function(a,b,c){b=a.getZIndex(b);var d=0;c&&(a=a.getZIndex(c),d=b-a);return d},Z_ORDER_DRAWING_ORDER:function(a,b,c){a=OpenLayers.ElementsIndexer.IndexingMethods.Z_ORDER(a,b,c);c&&0==a&&(a=1);return a},Z_ORDER_Y_ORDER:function(a,b,c){a=OpenLayers.ElementsIndexer.IndexingMethods.Z_ORDER(a,b,c);c&&0===a&&(b=c._boundsBottom-b._boundsBottom,a=0===b?1:b);return a}};
2384 OpenLayers.Renderer.Elements=OpenLayers.Class(OpenLayers.Renderer,{rendererRoot:null,root:null,vectorRoot:null,textRoot:null,xmlns:null,xOffset:0,indexer:null,BACKGROUND_ID_SUFFIX:"_background",LABEL_ID_SUFFIX:"_label",LABEL_OUTLINE_SUFFIX:"_outline",initialize:function(a,b){OpenLayers.Renderer.prototype.initialize.apply(this,arguments);this.rendererRoot=this.createRenderRoot();this.root=this.createRoot("_root");this.vectorRoot=this.createRoot("_vroot");this.textRoot=this.createRoot("_troot");this.root.appendChild(this.vectorRoot);
2385 this.root.appendChild(this.textRoot);this.rendererRoot.appendChild(this.root);this.container.appendChild(this.rendererRoot);b&&(b.zIndexing||b.yOrdering)&&(this.indexer=new OpenLayers.ElementsIndexer(b.yOrdering))},destroy:function(){this.clear();this.xmlns=this.root=this.rendererRoot=null;OpenLayers.Renderer.prototype.destroy.apply(this,arguments)},clear:function(){var a,b=this.vectorRoot;if(b)for(;a=b.firstChild;)b.removeChild(a);if(b=this.textRoot)for(;a=b.firstChild;)b.removeChild(a);this.indexer&&
2386 this.indexer.clear()},setExtent:function(a,b){var c=OpenLayers.Renderer.prototype.setExtent.apply(this,arguments),d=this.getResolution();if(this.map.baseLayer&&this.map.baseLayer.wrapDateLine){var e,f=a.getWidth()/this.map.getExtent().getWidth();a=a.scale(1/f);f=this.map.getMaxExtent();f.right>a.left&&f.right<a.right?e=!0:f.left>a.left&&f.left<a.right&&(e=!1);if(e!==this.rightOfDateLine||b)c=!1,this.xOffset=!0===e?f.getWidth()/d:0;this.rightOfDateLine=e}return c},getNodeType:function(a,b){},drawGeometry:function(a,
2387 b,c){var d=a.CLASS_NAME,e=!0;if("OpenLayers.Geometry.Collection"==d||"OpenLayers.Geometry.MultiPoint"==d||"OpenLayers.Geometry.MultiLineString"==d||"OpenLayers.Geometry.MultiPolygon"==d){for(var d=0,f=a.components.length;d<f;d++)e=this.drawGeometry(a.components[d],b,c)&&e;return e}d=e=!1;"none"!=b.display&&(b.backgroundGraphic?this.redrawBackgroundNode(a.id,a,b,c):d=!0,e=this.redrawNode(a.id,a,b,c));!1==e&&(b=document.getElementById(a.id))&&(b._style.backgroundGraphic&&(d=!0),b.parentNode.removeChild(b));
2388 d&&(b=document.getElementById(a.id+this.BACKGROUND_ID_SUFFIX))&&b.parentNode.removeChild(b);return e},redrawNode:function(a,b,c,d){c=this.applyDefaultSymbolizer(c);a=this.nodeFactory(a,this.getNodeType(b,c));a._featureId=d;a._boundsBottom=b.getBounds().bottom;a._geometryClass=b.CLASS_NAME;a._style=c;b=this.drawGeometryNode(a,b,c);if(!1===b)return!1;a=b.node;this.indexer?(c=this.indexer.insert(a))?this.vectorRoot.insertBefore(a,c):this.vectorRoot.appendChild(a):a.parentNode!==this.vectorRoot&&this.vectorRoot.appendChild(a);
2389 this.postDraw(a);return b.complete},redrawBackgroundNode:function(a,b,c,d){c=OpenLayers.Util.extend({},c);c.externalGraphic=c.backgroundGraphic;c.graphicXOffset=c.backgroundXOffset;c.graphicYOffset=c.backgroundYOffset;c.graphicZIndex=c.backgroundGraphicZIndex;c.graphicWidth=c.backgroundWidth||c.graphicWidth;c.graphicHeight=c.backgroundHeight||c.graphicHeight;c.backgroundGraphic=null;c.backgroundXOffset=null;c.backgroundYOffset=null;c.backgroundGraphicZIndex=null;return this.redrawNode(a+this.BACKGROUND_ID_SUFFIX,
2390 b,c,null)},drawGeometryNode:function(a,b,c){c=c||a._style;var d={isFilled:void 0===c.fill?!0:c.fill,isStroked:void 0===c.stroke?!!c.strokeWidth:c.stroke},e;switch(b.CLASS_NAME){case "OpenLayers.Geometry.Point":!1===c.graphic&&(d.isFilled=!1,d.isStroked=!1);e=this.drawPoint(a,b);break;case "OpenLayers.Geometry.LineString":d.isFilled=!1;e=this.drawLineString(a,b);break;case "OpenLayers.Geometry.LinearRing":e=this.drawLinearRing(a,b);break;case "OpenLayers.Geometry.Polygon":e=this.drawPolygon(a,b);break;
2391 case "OpenLayers.Geometry.Rectangle":e=this.drawRectangle(a,b)}a._options=d;return!1!=e?{node:this.setStyle(a,c,d,b),complete:e}:!1},postDraw:function(a){},drawPoint:function(a,b){},drawLineString:function(a,b){},drawLinearRing:function(a,b){},drawPolygon:function(a,b){},drawRectangle:function(a,b){},drawCircle:function(a,b){},removeText:function(a){var b=document.getElementById(a+this.LABEL_ID_SUFFIX);b&&this.textRoot.removeChild(b);(a=document.getElementById(a+this.LABEL_OUTLINE_SUFFIX))&&this.textRoot.removeChild(a)},
2392 getFeatureIdFromEvent:function(a){var b=a.target,c=b&&b.correspondingUseElement;return(c?c:b||a.srcElement)._featureId},eraseGeometry:function(a,b){if("OpenLayers.Geometry.MultiPoint"==a.CLASS_NAME||"OpenLayers.Geometry.MultiLineString"==a.CLASS_NAME||"OpenLayers.Geometry.MultiPolygon"==a.CLASS_NAME||"OpenLayers.Geometry.Collection"==a.CLASS_NAME)for(var c=0,d=a.components.length;c<d;c++)this.eraseGeometry(a.components[c],b);else(c=OpenLayers.Util.getElement(a.id))&&c.parentNode&&(c.geometry&&(c.geometry.destroy(),
2393 c.geometry=null),c.parentNode.removeChild(c),this.indexer&&this.indexer.remove(c),c._style.backgroundGraphic&&(c=OpenLayers.Util.getElement(a.id+this.BACKGROUND_ID_SUFFIX))&&c.parentNode&&c.parentNode.removeChild(c))},nodeFactory:function(a,b){var c=OpenLayers.Util.getElement(a);c?this.nodeTypeCompare(c,b)||(c.parentNode.removeChild(c),c=this.nodeFactory(a,b)):c=this.createNode(b,a);return c},nodeTypeCompare:function(a,b){},createNode:function(a,b){},moveRoot:function(a){var b=this.root;a.root.parentNode==
2394 this.rendererRoot&&(b=a.root);b.parentNode.removeChild(b);a.rendererRoot.appendChild(b)},getRenderLayerId:function(){return this.root.parentNode.parentNode.id},isComplexSymbol:function(a){return"circle"!=a&&!!a},CLASS_NAME:"OpenLayers.Renderer.Elements"});OpenLayers.Control.ArgParser=OpenLayers.Class(OpenLayers.Control,{center:null,zoom:null,layers:null,displayProjection:null,getParameters:function(a){a=a||window.location.href;var b=OpenLayers.Util.getParameters(a),c=a.indexOf("#");0<c&&(a="?"+a.substring(c+1,a.length),OpenLayers.Util.extend(b,OpenLayers.Util.getParameters(a)));return b},setMap:function(a){OpenLayers.Control.prototype.setMap.apply(this,arguments);for(var b=0,c=this.map.controls.length;b<c;b++){var d=this.map.controls[b];if(d!=this&&
2395 "OpenLayers.Control.ArgParser"==d.CLASS_NAME){d.displayProjection!=this.displayProjection&&(this.displayProjection=d.displayProjection);break}}b==this.map.controls.length&&(b=this.getParameters(),b.layers&&(this.layers=b.layers,this.map.events.register("addlayer",this,this.configureLayers),this.configureLayers()),b.lat&&b.lon&&(this.center=new OpenLayers.LonLat(parseFloat(b.lon),parseFloat(b.lat)),b.zoom&&(this.zoom=parseFloat(b.zoom)),this.map.events.register("changebaselayer",this,this.setCenter),
2396 this.setCenter()))},setCenter:function(){this.map.baseLayer&&(this.map.events.unregister("changebaselayer",this,this.setCenter),this.displayProjection&&this.center.transform(this.displayProjection,this.map.getProjectionObject()),this.map.setCenter(this.center,this.zoom))},configureLayers:function(){if(this.layers.length==this.map.layers.length){this.map.events.unregister("addlayer",this,this.configureLayers);for(var a=0,b=this.layers.length;a<b;a++){var c=this.map.layers[a],d=this.layers.charAt(a);
2397 "B"==d?this.map.setBaseLayer(c):"T"!=d&&"F"!=d||c.setVisibility("T"==d)}}},CLASS_NAME:"OpenLayers.Control.ArgParser"});OpenLayers.Control.Permalink=OpenLayers.Class(OpenLayers.Control,{argParserClass:OpenLayers.Control.ArgParser,element:null,anchor:!1,base:"",displayProjection:null,initialize:function(a,b,c){null===a||"object"!=typeof a||OpenLayers.Util.isElement(a)?(OpenLayers.Control.prototype.initialize.apply(this,[c]),this.element=OpenLayers.Util.getElement(a),this.base=b||document.location.href):(this.base=document.location.href,OpenLayers.Control.prototype.initialize.apply(this,[a]),null!=this.element&&(this.element=
2398 OpenLayers.Util.getElement(this.element)))},destroy:function(){this.element&&this.element.parentNode==this.div&&(this.div.removeChild(this.element),this.element=null);this.map&&this.map.events.unregister("moveend",this,this.updateLink);OpenLayers.Control.prototype.destroy.apply(this,arguments)},setMap:function(a){OpenLayers.Control.prototype.setMap.apply(this,arguments);for(var b=0,c=this.map.controls.length;b<c;b++){var d=this.map.controls[b];if(d.CLASS_NAME==this.argParserClass.CLASS_NAME){d.displayProjection!=
2399 this.displayProjection&&(this.displayProjection=d.displayProjection);break}}b==this.map.controls.length&&this.map.addControl(new this.argParserClass({displayProjection:this.displayProjection}))},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);this.element||this.anchor||(this.element=document.createElement("a"),this.element.innerHTML=OpenLayers.i18n("Permalink"),this.element.href="",this.div.appendChild(this.element));this.map.events.on({moveend:this.updateLink,changelayer:this.updateLink,
2400 changebaselayer:this.updateLink,scope:this});this.updateLink();return this.div},updateLink:function(){var a=this.anchor?"#":"?",b=this.base,c=null;-1!=b.indexOf("#")&&!1==this.anchor&&(c=b.substring(b.indexOf("#"),b.length));-1!=b.indexOf(a)&&(b=b.substring(0,b.indexOf(a)));b=b.split("#")[0]+a+OpenLayers.Util.getParameterString(this.createParams());c&&(b+=c);this.anchor&&!this.element?window.location.href=b:this.element.href=b},createParams:function(a,b,c){a=a||this.map.getCenter();var d=OpenLayers.Util.getParameters(this.base);
2401 if(a)for(d.zoom=b||this.map.getZoom(),b=a.lat,a=a.lon,this.displayProjection&&(b=OpenLayers.Projection.transform({x:a,y:b},this.map.getProjectionObject(),this.displayProjection),a=b.x,b=b.y),d.lat=Math.round(1E5*b)/1E5,d.lon=Math.round(1E5*a)/1E5,c=c||this.map.layers,d.layers="",a=0,b=c.length;a<b;a++){var e=c[a];d.layers=e.isBaseLayer?d.layers+(e==this.map.baseLayer?"B":"0"):d.layers+(e.getVisibility()?"T":"F")}return d},CLASS_NAME:"OpenLayers.Control.Permalink"});OpenLayers.Layer.TMS=OpenLayers.Class(OpenLayers.Layer.Grid,{serviceVersion:"1.0.0",layername:null,type:null,isBaseLayer:!0,tileOrigin:null,serverResolutions:null,zoomOffset:0,initialize:function(a,b,c){var d=[];d.push(a,b,{},c);OpenLayers.Layer.Grid.prototype.initialize.apply(this,d)},clone:function(a){null==a&&(a=new OpenLayers.Layer.TMS(this.name,this.url,this.getOptions()));return a=OpenLayers.Layer.Grid.prototype.clone.apply(this,[a])},getURL:function(a){a=this.adjustBounds(a);var b=this.getServerResolution(),
2402 c=Math.round((a.left-this.tileOrigin.lon)/(b*this.tileSize.w));a=Math.round((a.bottom-this.tileOrigin.lat)/(b*this.tileSize.h));b=this.getServerZoom();c=this.serviceVersion+"/"+this.layername+"/"+b+"/"+c+"/"+a+"."+this.type;a=this.url;OpenLayers.Util.isArray(a)&&(a=this.selectUrl(c,a));return a+c},setMap:function(a){OpenLayers.Layer.Grid.prototype.setMap.apply(this,arguments);this.tileOrigin||(this.tileOrigin=new OpenLayers.LonLat(this.map.maxExtent.left,this.map.maxExtent.bottom))},CLASS_NAME:"OpenLayers.Layer.TMS"});OpenLayers.Format.WCSCapabilities=OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC,{defaultVersion:"1.1.0",CLASS_NAME:"OpenLayers.Format.WCSCapabilities"});OpenLayers.Format.WCSCapabilities.v1=OpenLayers.Class(OpenLayers.Format.XML,{regExes:{trimSpace:/^\s*|\s*$/g,splitSpace:/\s+/},defaultPrefix:"wcs",read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));a&&9==a.nodeType&&(a=a.documentElement);var b={};this.readNode(a,b);return b},CLASS_NAME:"OpenLayers.Format.WCSCapabilities.v1"});OpenLayers.Format.WCSCapabilities.v1_0_0=OpenLayers.Class(OpenLayers.Format.WCSCapabilities.v1,{namespaces:{wcs:"http://www.opengis.net/wcs",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance",ows:"http://www.opengis.net/ows"},errorProperty:"service",readers:{wcs:{WCS_Capabilities:function(a,b){this.readChildNodes(a,b)},Service:function(a,b){b.service={};this.readChildNodes(a,b.service)},name:function(a,b){b.name=this.getChildValue(a)},label:function(a,b){b.label=
2403 this.getChildValue(a)},keywords:function(a,b){b.keywords=[];this.readChildNodes(a,b.keywords)},keyword:function(a,b){b.push(this.getChildValue(a))},responsibleParty:function(a,b){b.responsibleParty={};this.readChildNodes(a,b.responsibleParty)},individualName:function(a,b){b.individualName=this.getChildValue(a)},organisationName:function(a,b){b.organisationName=this.getChildValue(a)},positionName:function(a,b){b.positionName=this.getChildValue(a)},contactInfo:function(a,b){b.contactInfo={};this.readChildNodes(a,
2404 b.contactInfo)},phone:function(a,b){b.phone={};this.readChildNodes(a,b.phone)},voice:function(a,b){b.voice=this.getChildValue(a)},facsimile:function(a,b){b.facsimile=this.getChildValue(a)},address:function(a,b){b.address={};this.readChildNodes(a,b.address)},deliveryPoint:function(a,b){b.deliveryPoint=this.getChildValue(a)},city:function(a,b){b.city=this.getChildValue(a)},postalCode:function(a,b){b.postalCode=this.getChildValue(a)},country:function(a,b){b.country=this.getChildValue(a)},electronicMailAddress:function(a,
2405 b){b.electronicMailAddress=this.getChildValue(a)},fees:function(a,b){b.fees=this.getChildValue(a)},accessConstraints:function(a,b){b.accessConstraints=this.getChildValue(a)},ContentMetadata:function(a,b){b.contentMetadata=[];this.readChildNodes(a,b.contentMetadata)},CoverageOfferingBrief:function(a,b){var c={};this.readChildNodes(a,c);b.push(c)},name:function(a,b){b.name=this.getChildValue(a)},label:function(a,b){b.label=this.getChildValue(a)},lonLatEnvelope:function(a,b){var c=this.getElementsByTagNameNS(a,
2406 "http://www.opengis.net/gml","pos");if(2==c.length){var d={},e={};OpenLayers.Format.GML.v3.prototype.readers.gml.pos.apply(this,[c[0],d]);OpenLayers.Format.GML.v3.prototype.readers.gml.pos.apply(this,[c[1],e]);b.lonLatEnvelope={};b.lonLatEnvelope.srsName=a.getAttribute("srsName");b.lonLatEnvelope.min=d.points[0];b.lonLatEnvelope.max=e.points[0]}}}},CLASS_NAME:"OpenLayers.Format.WCSCapabilities.v1_0_0"});OpenLayers.Strategy.Fixed=OpenLayers.Class(OpenLayers.Strategy,{preload:!1,activate:function(){var a=OpenLayers.Strategy.prototype.activate.apply(this,arguments);if(a)if(this.layer.events.on({refresh:this.load,scope:this}),!0==this.layer.visibility||this.preload)this.load();else this.layer.events.on({visibilitychanged:this.load,scope:this});return a},deactivate:function(){var a=OpenLayers.Strategy.prototype.deactivate.call(this);a&&this.layer.events.un({refresh:this.load,visibilitychanged:this.load,
2407 scope:this});return a},load:function(a){var b=this.layer;b.events.triggerEvent("loadstart",{filter:b.filter});b.protocol.read(OpenLayers.Util.applyDefaults({callback:this.merge,filter:b.filter,scope:this},a));b.events.un({visibilitychanged:this.load,scope:this})},merge:function(a){var b=this.layer;b.destroyFeatures();var c=a.features;if(c&&0<c.length){var d=b.projection,e=b.map.getProjectionObject();if(!e.equals(d))for(var f,g=0,h=c.length;g<h;++g)(f=c[g].geometry)&&f.transform(d,e);b.addFeatures(c)}b.events.triggerEvent("loadend",
2408 {response:a})},CLASS_NAME:"OpenLayers.Strategy.Fixed"});OpenLayers.Control.Zoom=OpenLayers.Class(OpenLayers.Control,{zoomInText:"+",zoomInId:"olZoomInLink",zoomOutText:"\u2212",zoomOutId:"olZoomOutLink",draw:function(){var a=OpenLayers.Control.prototype.draw.apply(this),b=this.getOrCreateLinks(a),c=b.zoomIn,b=b.zoomOut,d=this.map.events;b.parentNode!==a&&(d=this.events,d.attachToElement(b.parentNode));d.register("buttonclick",this,this.onZoomClick);this.zoomInLink=c;this.zoomOutLink=b;return a},getOrCreateLinks:function(a){var b=document.getElementById(this.zoomInId),
2409 c=document.getElementById(this.zoomOutId);b||(b=document.createElement("a"),b.href="#zoomIn",b.appendChild(document.createTextNode(this.zoomInText)),b.className="olControlZoomIn",a.appendChild(b));OpenLayers.Element.addClass(b,"olButton");c||(c=document.createElement("a"),c.href="#zoomOut",c.appendChild(document.createTextNode(this.zoomOutText)),c.className="olControlZoomOut",a.appendChild(c));OpenLayers.Element.addClass(c,"olButton");return{zoomIn:b,zoomOut:c}},onZoomClick:function(a){a=a.buttonElement;
2410 a===this.zoomInLink?this.map.zoomIn():a===this.zoomOutLink&&this.map.zoomOut()},destroy:function(){this.map&&this.map.events.unregister("buttonclick",this,this.onZoomClick);delete this.zoomInLink;delete this.zoomOutLink;OpenLayers.Control.prototype.destroy.apply(this)},CLASS_NAME:"OpenLayers.Control.Zoom"});OpenLayers.Layer.PointTrack=OpenLayers.Class(OpenLayers.Layer.Vector,{dataFrom:null,styleFrom:null,addNodes:function(a,b){if(2>a.length)throw Error("At least two point features have to be added to create a line from");for(var c=Array(a.length-1),d,e,f,g=0,h=a.length;g<h;g++){d=a[g];f=d.geometry;if(!f)f=d.lonlat,f=new OpenLayers.Geometry.Point(f.lon,f.lat);else if("OpenLayers.Geometry.Point"!=f.CLASS_NAME)throw new TypeError("Only features with point geometries are supported.");if(0<g){d=null!=this.dataFrom?
2411 a[g+this.dataFrom].data||a[g+this.dataFrom].attributes:null;var k=null!=this.styleFrom?a[g+this.styleFrom].style:null;e=new OpenLayers.Geometry.LineString([e,f]);c[g-1]=new OpenLayers.Feature.Vector(e,d,k)}e=f}this.addFeatures(c,b)},CLASS_NAME:"OpenLayers.Layer.PointTrack"});OpenLayers.Layer.PointTrack.SOURCE_NODE=-1;OpenLayers.Layer.PointTrack.TARGET_NODE=0;OpenLayers.Layer.PointTrack.dataFrom={SOURCE_NODE:-1,TARGET_NODE:0};OpenLayers.Protocol.WFS=function(a){a=OpenLayers.Util.applyDefaults(a,OpenLayers.Protocol.WFS.DEFAULTS);var b=OpenLayers.Protocol.WFS["v"+a.version.replace(/\./g,"_")];if(!b)throw"Unsupported WFS version: "+a.version;return new b(a)};
2412 OpenLayers.Protocol.WFS.fromWMSLayer=function(a,b){var c,d;c=a.params.LAYERS;c=(OpenLayers.Util.isArray(c)?c[0]:c).split(":");1<c.length&&(d=c[0]);c=c.pop();d={url:a.url,featureType:c,featurePrefix:d,srsName:a.projection&&a.projection.getCode()||a.map&&a.map.getProjectionObject().getCode(),version:"1.1.0"};return new OpenLayers.Protocol.WFS(OpenLayers.Util.applyDefaults(b,d))};OpenLayers.Protocol.WFS.DEFAULTS={version:"1.0.0"};OpenLayers.Layer.Markers=OpenLayers.Class(OpenLayers.Layer,{isBaseLayer:!1,markers:null,drawn:!1,initialize:function(a,b){OpenLayers.Layer.prototype.initialize.apply(this,arguments);this.markers=[]},destroy:function(){this.clearMarkers();this.markers=null;OpenLayers.Layer.prototype.destroy.apply(this,arguments)},setOpacity:function(a){if(a!=this.opacity){this.opacity=a;a=0;for(var b=this.markers.length;a<b;a++)this.markers[a].setOpacity(this.opacity)}},moveTo:function(a,b,c){OpenLayers.Layer.prototype.moveTo.apply(this,
2413 arguments);if(b||!this.drawn){for(var d=0,e=this.markers.length;d<e;d++)this.drawMarker(this.markers[d]);this.drawn=!0}},addMarker:function(a){this.markers.push(a);1>this.opacity&&a.setOpacity(this.opacity);this.map&&this.map.getExtent()&&(a.map=this.map,this.drawMarker(a))},removeMarker:function(a){this.markers&&this.markers.length&&(OpenLayers.Util.removeItem(this.markers,a),a.erase())},clearMarkers:function(){if(null!=this.markers)for(;0<this.markers.length;)this.removeMarker(this.markers[0])},
2414 drawMarker:function(a){var b=this.map.getLayerPxFromLonLat(a.lonlat);null==b?a.display(!1):a.isDrawn()?a.icon&&a.icon.moveTo(b):(a=a.draw(b),this.div.appendChild(a))},getDataExtent:function(){var a=null;if(this.markers&&0<this.markers.length)for(var a=new OpenLayers.Bounds,b=0,c=this.markers.length;b<c;b++)a.extend(this.markers[b].lonlat);return a},CLASS_NAME:"OpenLayers.Layer.Markers"});OpenLayers.Control.Pan=OpenLayers.Class(OpenLayers.Control.Button,{slideFactor:50,slideRatio:null,direction:null,initialize:function(a,b){this.direction=a;this.CLASS_NAME+=this.direction;OpenLayers.Control.prototype.initialize.apply(this,[b])},trigger:function(){if(this.map){var a=OpenLayers.Function.bind(function(a){return this.slideRatio?this.map.getSize()[a]*this.slideRatio:this.slideFactor},this);switch(this.direction){case OpenLayers.Control.Pan.NORTH:this.map.pan(0,-a("h"));break;case OpenLayers.Control.Pan.SOUTH:this.map.pan(0,
2415 a("h"));break;case OpenLayers.Control.Pan.WEST:this.map.pan(-a("w"),0);break;case OpenLayers.Control.Pan.EAST:this.map.pan(a("w"),0)}}},CLASS_NAME:"OpenLayers.Control.Pan"});OpenLayers.Control.Pan.NORTH="North";OpenLayers.Control.Pan.SOUTH="South";OpenLayers.Control.Pan.EAST="East";OpenLayers.Control.Pan.WEST="West";OpenLayers.Format.CSWGetDomain=function(a){a=OpenLayers.Util.applyDefaults(a,OpenLayers.Format.CSWGetDomain.DEFAULTS);var b=OpenLayers.Format.CSWGetDomain["v"+a.version.replace(/\./g,"_")];if(!b)throw"Unsupported CSWGetDomain version: "+a.version;return new b(a)};OpenLayers.Format.CSWGetDomain.DEFAULTS={version:"2.0.2"};OpenLayers.Format.CSWGetDomain.v2_0_2=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance",csw:"http://www.opengis.net/cat/csw/2.0.2"},defaultPrefix:"csw",version:"2.0.2",schemaLocation:"http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd",PropertyName:null,ParameterName:null,read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));a&&9==
2416 a.nodeType&&(a=a.documentElement);var b={};this.readNode(a,b);return b},readers:{csw:{GetDomainResponse:function(a,b){this.readChildNodes(a,b)},DomainValues:function(a,b){OpenLayers.Util.isArray(b.DomainValues)||(b.DomainValues=[]);for(var c=a.attributes,d={},e=0,f=c.length;e<f;++e)d[c[e].name]=c[e].nodeValue;this.readChildNodes(a,d);b.DomainValues.push(d)},PropertyName:function(a,b){b.PropertyName=this.getChildValue(a)},ParameterName:function(a,b){b.ParameterName=this.getChildValue(a)},ListOfValues:function(a,
2417 b){OpenLayers.Util.isArray(b.ListOfValues)||(b.ListOfValues=[]);this.readChildNodes(a,b.ListOfValues)},Value:function(a,b){for(var c=a.attributes,d={},e=0,f=c.length;e<f;++e)d[c[e].name]=c[e].nodeValue;d.value=this.getChildValue(a);b.push({Value:d})},ConceptualScheme:function(a,b){b.ConceptualScheme={};this.readChildNodes(a,b.ConceptualScheme)},Name:function(a,b){b.Name=this.getChildValue(a)},Document:function(a,b){b.Document=this.getChildValue(a)},Authority:function(a,b){b.Authority=this.getChildValue(a)},
2418 RangeOfValues:function(a,b){b.RangeOfValues={};this.readChildNodes(a,b.RangeOfValues)},MinValue:function(a,b){for(var c=a.attributes,d={},e=0,f=c.length;e<f;++e)d[c[e].name]=c[e].nodeValue;d.value=this.getChildValue(a);b.MinValue=d},MaxValue:function(a,b){for(var c=a.attributes,d={},e=0,f=c.length;e<f;++e)d[c[e].name]=c[e].nodeValue;d.value=this.getChildValue(a);b.MaxValue=d}}},write:function(a){a=this.writeNode("csw:GetDomain",a);return OpenLayers.Format.XML.prototype.write.apply(this,[a])},writers:{csw:{GetDomain:function(a){var b=
2419 this.createElementNSPlus("csw:GetDomain",{attributes:{service:"CSW",version:this.version}});a.PropertyName||this.PropertyName?this.writeNode("csw:PropertyName",a.PropertyName||this.PropertyName,b):(a.ParameterName||this.ParameterName)&&this.writeNode("csw:ParameterName",a.ParameterName||this.ParameterName,b);this.readChildNodes(b,a);return b},PropertyName:function(a){return this.createElementNSPlus("csw:PropertyName",{value:a})},ParameterName:function(a){return this.createElementNSPlus("csw:ParameterName",
2420 {value:a})}}},CLASS_NAME:"OpenLayers.Format.CSWGetDomain.v2_0_2"});OpenLayers.Format.ArcXML.Features=OpenLayers.Class(OpenLayers.Format.XML,{read:function(a){return(new OpenLayers.Format.ArcXML).read(a).features.feature}});OpenLayers.Control.Snapping=OpenLayers.Class(OpenLayers.Control,{DEFAULTS:{tolerance:10,node:!0,edge:!0,vertex:!0},greedy:!0,precedence:["node","vertex","edge"],resolution:null,geoToleranceCache:null,layer:null,feature:null,point:null,initialize:function(a){OpenLayers.Control.prototype.initialize.apply(this,[a]);this.options=a||{};this.options.layer&&this.setLayer(this.options.layer);a=OpenLayers.Util.extend({},this.options.defaults);this.defaults=OpenLayers.Util.applyDefaults(a,this.DEFAULTS);this.setTargets(this.options.targets);
2421 0===this.targets.length&&this.layer&&this.addTargetLayer(this.layer);this.geoToleranceCache={}},setLayer:function(a){this.active?(this.deactivate(),this.layer=a,this.activate()):this.layer=a},setTargets:function(a){this.targets=[];if(a&&a.length)for(var b,c=0,d=a.length;c<d;++c)b=a[c],b instanceof OpenLayers.Layer.Vector?this.addTargetLayer(b):this.addTarget(b)},addTargetLayer:function(a){this.addTarget({layer:a})},addTarget:function(a){a=OpenLayers.Util.applyDefaults(a,this.defaults);a.nodeTolerance=
2422 a.nodeTolerance||a.tolerance;a.vertexTolerance=a.vertexTolerance||a.tolerance;a.edgeTolerance=a.edgeTolerance||a.tolerance;this.targets.push(a)},removeTargetLayer:function(a){for(var b,c=this.targets.length-1;0<=c;--c)b=this.targets[c],b.layer===a&&this.removeTarget(b)},removeTarget:function(a){return OpenLayers.Util.removeItem(this.targets,a)},activate:function(){var a=OpenLayers.Control.prototype.activate.call(this);if(a&&this.layer&&this.layer.events)this.layer.events.on({sketchstarted:this.onSketchModified,
2423 sketchmodified:this.onSketchModified,vertexmodified:this.onVertexModified,scope:this});return a},deactivate:function(){var a=OpenLayers.Control.prototype.deactivate.call(this);a&&this.layer&&this.layer.events&&this.layer.events.un({sketchstarted:this.onSketchModified,sketchmodified:this.onSketchModified,vertexmodified:this.onVertexModified,scope:this});this.point=this.feature=null;return a},onSketchModified:function(a){this.feature=a.feature;this.considerSnapping(a.vertex,a.vertex)},onVertexModified:function(a){this.feature=
2424 a.feature;var b=this.layer.map.getLonLatFromViewPortPx(a.pixel);this.considerSnapping(a.vertex,new OpenLayers.Geometry.Point(b.lon,b.lat))},considerSnapping:function(a,b){for(var c={rank:Number.POSITIVE_INFINITY,dist:Number.POSITIVE_INFINITY,x:null,y:null},d=!1,e,f,g=0,h=this.targets.length;g<h;++g)if(f=this.targets[g],e=this.testTarget(f,b))if(this.greedy){c=e;c.target=f;d=!0;break}else if(e.rank<c.rank||e.rank===c.rank&&e.dist<c.dist)c=e,c.target=f,d=!0;d&&(!1!==this.events.triggerEvent("beforesnap",
2425 {point:a,x:c.x,y:c.y,distance:c.dist,layer:c.target.layer,snapType:this.precedence[c.rank]})?(a.x=c.x,a.y=c.y,this.point=a,this.events.triggerEvent("snap",{point:a,snapType:this.precedence[c.rank],layer:c.target.layer,distance:c.dist})):d=!1);this.point&&!d&&(a.x=b.x,a.y=b.y,this.point=null,this.events.triggerEvent("unsnap",{point:a}))},testTarget:function(a,b){var c=this.layer.map.getResolution();if("minResolution"in a&&c<a.minResolution||"maxResolution"in a&&c>=a.maxResolution)return null;for(var c=
2426 {node:this.getGeoTolerance(a.nodeTolerance,c),vertex:this.getGeoTolerance(a.vertexTolerance,c),edge:this.getGeoTolerance(a.edgeTolerance,c)},d=Math.max(c.node,c.vertex,c.edge),e={rank:Number.POSITIVE_INFINITY,dist:Number.POSITIVE_INFINITY},f=!1,g=a.layer.features,h,k,l,m,n,p,q=this.precedence.length,r=new OpenLayers.LonLat(b.x,b.y),s=0,t=g.length;s<t;++s)if(h=g[s],h!==this.feature&&(!h._sketch&&h.state!==OpenLayers.State.DELETE&&(!a.filter||a.filter.evaluate(h)))&&h.atPoint(r,d,d))for(var u=0,v=Math.min(e.rank+
2427 1,q);u<v;++u)if(k=this.precedence[u],a[k])if("edge"===k){if(l=h.geometry.distanceTo(b,{details:!0}),n=l.distance,n<=c[k]&&n<e.dist){e={rank:u,dist:n,x:l.x0,y:l.y0};f=!0;break}}else{l=h.geometry.getVertices("node"===k);p=!1;for(var w=0,x=l.length;w<x;++w)m=l[w],n=m.distanceTo(b),n<=c[k]&&(u<e.rank||u===e.rank&&n<e.dist)&&(e={rank:u,dist:n,x:m.x,y:m.y},p=f=!0);if(p)break}return f?e:null},getGeoTolerance:function(a,b){b!==this.resolution&&(this.resolution=b,this.geoToleranceCache={});var c=this.geoToleranceCache[a];
2428 void 0===c&&(c=a*b,this.geoToleranceCache[a]=c);return c},destroy:function(){this.active&&this.deactivate();delete this.layer;delete this.targets;OpenLayers.Control.prototype.destroy.call(this)},CLASS_NAME:"OpenLayers.Control.Snapping"});OpenLayers.Format.OWSCommon.v1_1_0=OpenLayers.Class(OpenLayers.Format.OWSCommon.v1,{namespaces:{ows:"http://www.opengis.net/ows/1.1",xlink:"http://www.w3.org/1999/xlink"},readers:{ows:OpenLayers.Util.applyDefaults({ExceptionReport:function(a,b){b.exceptionReport={version:a.getAttribute("version"),language:a.getAttribute("xml:lang"),exceptions:[]};this.readChildNodes(a,b.exceptionReport)},AllowedValues:function(a,b){b.allowedValues={};this.readChildNodes(a,b.allowedValues)},AnyValue:function(a,b){b.anyValue=
2429 !0},DataType:function(a,b){b.dataType=this.getChildValue(a)},Range:function(a,b){b.range={};this.readChildNodes(a,b.range)},MinimumValue:function(a,b){b.minValue=this.getChildValue(a)},MaximumValue:function(a,b){b.maxValue=this.getChildValue(a)},Identifier:function(a,b){b.identifier=this.getChildValue(a)},SupportedCRS:function(a,b){b.supportedCRS=this.getChildValue(a)}},OpenLayers.Format.OWSCommon.v1.prototype.readers.ows)},writers:{ows:OpenLayers.Util.applyDefaults({Range:function(a){var b=this.createElementNSPlus("ows:Range",
2430 {attributes:{"ows:rangeClosure":a.closure}});this.writeNode("ows:MinimumValue",a.minValue,b);this.writeNode("ows:MaximumValue",a.maxValue,b);return b},MinimumValue:function(a){return this.createElementNSPlus("ows:MinimumValue",{value:a})},MaximumValue:function(a){return this.createElementNSPlus("ows:MaximumValue",{value:a})},Value:function(a){return this.createElementNSPlus("ows:Value",{value:a})}},OpenLayers.Format.OWSCommon.v1.prototype.writers.ows)},CLASS_NAME:"OpenLayers.Format.OWSCommon.v1_1_0"});OpenLayers.Format.WCSGetCoverage=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{ows:"http://www.opengis.net/ows/1.1",wcs:"http://www.opengis.net/wcs/1.1",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance"},regExes:{trimSpace:/^\s*|\s*$/g,removeSpace:/\s*/g,splitSpace:/\s+/,trimComma:/\s*,\s*/g},VERSION:"1.1.2",schemaLocation:"http://www.opengis.net/wcs/1.1 http://schemas.opengis.net/wcs/1.1/wcsGetCoverage.xsd",write:function(a){a=this.writeNode("wcs:GetCoverage",
2431 a);this.setAttributeNS(a,this.namespaces.xsi,"xsi:schemaLocation",this.schemaLocation);return OpenLayers.Format.XML.prototype.write.apply(this,[a])},writers:{wcs:{GetCoverage:function(a){var b=this.createElementNSPlus("wcs:GetCoverage",{attributes:{version:a.version||this.VERSION,service:"WCS"}});this.writeNode("ows:Identifier",a.identifier,b);this.writeNode("wcs:DomainSubset",a.domainSubset,b);this.writeNode("wcs:Output",a.output,b);return b},DomainSubset:function(a){var b=this.createElementNSPlus("wcs:DomainSubset",
2432 {});this.writeNode("ows:BoundingBox",a.boundingBox,b);a.temporalSubset&&this.writeNode("wcs:TemporalSubset",a.temporalSubset,b);return b},TemporalSubset:function(a){for(var b=this.createElementNSPlus("wcs:TemporalSubset",{}),c=0,d=a.timePeriods.length;c<d;++c)this.writeNode("wcs:TimePeriod",a.timePeriods[c],b);return b},TimePeriod:function(a){var b=this.createElementNSPlus("wcs:TimePeriod",{});this.writeNode("wcs:BeginPosition",a.begin,b);this.writeNode("wcs:EndPosition",a.end,b);a.resolution&&this.writeNode("wcs:TimeResolution",
2433 a.resolution,b);return b},BeginPosition:function(a){return this.createElementNSPlus("wcs:BeginPosition",{value:a})},EndPosition:function(a){return this.createElementNSPlus("wcs:EndPosition",{value:a})},TimeResolution:function(a){return this.createElementNSPlus("wcs:TimeResolution",{value:a})},Output:function(a){var b=this.createElementNSPlus("wcs:Output",{attributes:{format:a.format,store:a.store}});a.gridCRS&&this.writeNode("wcs:GridCRS",a.gridCRS,b);return b},GridCRS:function(a){var b=this.createElementNSPlus("wcs:GridCRS",
2434 {});this.writeNode("wcs:GridBaseCRS",a.baseCRS,b);a.type&&this.writeNode("wcs:GridType",a.type,b);a.origin&&this.writeNode("wcs:GridOrigin",a.origin,b);this.writeNode("wcs:GridOffsets",a.offsets,b);a.CS&&this.writeNode("wcs:GridCS",a.CS,b);return b},GridBaseCRS:function(a){return this.createElementNSPlus("wcs:GridBaseCRS",{value:a})},GridOrigin:function(a){return this.createElementNSPlus("wcs:GridOrigin",{value:a})},GridType:function(a){return this.createElementNSPlus("wcs:GridType",{value:a})},GridOffsets:function(a){return this.createElementNSPlus("wcs:GridOffsets",
2435 {value:a})},GridCS:function(a){return this.createElementNSPlus("wcs:GridCS",{value:a})}},ows:OpenLayers.Format.OWSCommon.v1_1_0.prototype.writers.ows},CLASS_NAME:"OpenLayers.Format.WCSGetCoverage"});OpenLayers.Format.KML=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{kml:"http://www.opengis.net/kml/2.2",gx:"http://www.google.com/kml/ext/2.2"},kmlns:"http://earth.google.com/kml/2.0",placemarksDesc:"No description available",foldersName:"OpenLayers export",foldersDesc:"Exported on "+new Date,extractAttributes:!0,kvpAttributes:!1,extractStyles:!1,extractTracks:!1,trackAttributes:null,internalns:null,features:null,styles:null,styleBaseUrl:"",fetched:null,maxDepth:0,initialize:function(a){this.regExes=
2436 {trimSpace:/^\s*|\s*$/g,removeSpace:/\s*/g,splitSpace:/\s+/,trimComma:/\s*,\s*/g,kmlColor:/(\w{2})(\w{2})(\w{2})(\w{2})/,kmlIconPalette:/root:\/\/icons\/palette-(\d+)(\.\w+)/,straightBracket:/\$\[(.*?)\]/g};this.externalProjection=new OpenLayers.Projection("EPSG:4326");OpenLayers.Format.XML.prototype.initialize.apply(this,[a])},read:function(a){this.features=[];this.styles={};this.fetched={};return this.parseData(a,{depth:0,styleBaseUrl:this.styleBaseUrl})},parseData:function(a,b){"string"==typeof a&&
2437 (a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));for(var c=["Link","NetworkLink","Style","StyleMap","Placemark"],d=0,e=c.length;d<e;++d){var f=c[d],g=this.getElementsByTagNameNS(a,"*",f);if(0!=g.length)switch(f.toLowerCase()){case "link":case "networklink":this.parseLinks(g,b);break;case "style":this.extractStyles&&this.parseStyles(g,b);break;case "stylemap":this.extractStyles&&this.parseStyleMaps(g,b);break;case "placemark":this.parseFeatures(g,b)}}return this.features},parseLinks:function(a,
2438 b){if(b.depth>=this.maxDepth)return!1;var c=OpenLayers.Util.extend({},b);c.depth++;for(var d=0,e=a.length;d<e;d++){var f=this.parseProperty(a[d],"*","href");f&&!this.fetched[f]&&(this.fetched[f]=!0,(f=this.fetchLink(f))&&this.parseData(f,c))}},fetchLink:function(a){if(a=OpenLayers.Request.GET({url:a,async:!1}))return a.responseText},parseStyles:function(a,b){for(var c=0,d=a.length;c<d;c++){var e=this.parseStyle(a[c]);e&&(this.styles[(b.styleBaseUrl||"")+"#"+e.id]=e)}},parseKmlColor:function(a){var b=
2439 null;a&&(a=a.match(this.regExes.kmlColor))&&(b={color:"#"+a[4]+a[3]+a[2],opacity:parseInt(a[1],16)/255});return b},parseStyle:function(a){for(var b={},c=["LineStyle","PolyStyle","IconStyle","BalloonStyle","LabelStyle"],d,e,f=0,g=c.length;f<g;++f)if(d=c[f],e=this.getElementsByTagNameNS(a,"*",d)[0])switch(d.toLowerCase()){case "linestyle":d=this.parseProperty(e,"*","color");if(d=this.parseKmlColor(d))b.strokeColor=d.color,b.strokeOpacity=d.opacity;(d=this.parseProperty(e,"*","width"))&&(b.strokeWidth=
2440 d);break;case "polystyle":d=this.parseProperty(e,"*","color");if(d=this.parseKmlColor(d))b.fillOpacity=d.opacity,b.fillColor=d.color;"0"==this.parseProperty(e,"*","fill")&&(b.fillColor="none");"0"==this.parseProperty(e,"*","outline")&&(b.strokeWidth="0");break;case "iconstyle":var h=parseFloat(this.parseProperty(e,"*","scale")||1);d=32*h;var k=32*h,l=this.getElementsByTagNameNS(e,"*","Icon")[0];if(l){var m=this.parseProperty(l,"*","href");if(m){var n=this.parseProperty(l,"*","w"),p=this.parseProperty(l,
2441 "*","h");!OpenLayers.String.startsWith(m,"http://maps.google.com/mapfiles/kml")||(n||p)||(p=n=64,h/=2);n=n||p;p=p||n;n&&(d=parseInt(n)*h);p&&(k=parseInt(p)*h);if(p=m.match(this.regExes.kmlIconPalette))n=p[1],p=p[2],m=this.parseProperty(l,"*","x"),l=this.parseProperty(l,"*","y"),m="http://maps.google.com/mapfiles/kml/pal"+n+"/icon"+(8*(l?7-l/32:7)+(m?m/32:0))+p;b.graphicOpacity=1;b.externalGraphic=m}}if(e=this.getElementsByTagNameNS(e,"*","hotSpot")[0])m=parseFloat(e.getAttribute("x")),l=parseFloat(e.getAttribute("y")),
2442 n=e.getAttribute("xunits"),"pixels"==n?b.graphicXOffset=-m*h:"insetPixels"==n?b.graphicXOffset=-d+m*h:"fraction"==n&&(b.graphicXOffset=-d*m),e=e.getAttribute("yunits"),"pixels"==e?b.graphicYOffset=-k+l*h+1:"insetPixels"==e?b.graphicYOffset=-(l*h)+1:"fraction"==e&&(b.graphicYOffset=-k*(1-l)+1);b.graphicWidth=d;b.graphicHeight=k;break;case "balloonstyle":(e=OpenLayers.Util.getXmlNodeValue(e))&&(b.balloonStyle=e.replace(this.regExes.straightBracket,"${$1}"));break;case "labelstyle":if(d=this.parseProperty(e,
2443 "*","color"),d=this.parseKmlColor(d))b.fontColor=d.color,b.fontOpacity=d.opacity}!b.strokeColor&&b.fillColor&&(b.strokeColor=b.fillColor);(a=a.getAttribute("id"))&&b&&(b.id=a);return b},parseStyleMaps:function(a,b){for(var c=0,d=a.length;c<d;c++)for(var e=a[c],f=this.getElementsByTagNameNS(e,"*","Pair"),e=e.getAttribute("id"),g=0,h=f.length;g<h;g++){var k=f[g],l=this.parseProperty(k,"*","key");(k=this.parseProperty(k,"*","styleUrl"))&&"normal"==l&&(this.styles[(b.styleBaseUrl||"")+"#"+e]=this.styles[(b.styleBaseUrl||
2444 "")+k])}},parseFeatures:function(a,b){for(var c=[],d=0,e=a.length;d<e;d++){var f=a[d],g=this.parseFeature.apply(this,[f]);if(g){this.extractStyles&&(g.attributes&&g.attributes.styleUrl)&&(g.style=this.getStyle(g.attributes.styleUrl,b));if(this.extractStyles){var h=this.getElementsByTagNameNS(f,"*","Style")[0];h&&(h=this.parseStyle(h))&&(g.style=OpenLayers.Util.extend(g.style,h))}this.extractTracks?(f=this.getElementsByTagNameNS(f,this.namespaces.gx,"Track"))&&0<f.length&&(g={features:[],feature:g},
2445 this.readNode(f[0],g),0<g.features.length&&c.push.apply(c,g.features)):c.push(g)}else throw"Bad Placemark: "+d;}this.features=this.features.concat(c)},readers:{kml:{when:function(a,b){b.whens.push(OpenLayers.Date.parse(this.getChildValue(a)))},_trackPointAttribute:function(a,b){var c=a.nodeName.split(":").pop();b.attributes[c].push(this.getChildValue(a))}},gx:{Track:function(a,b){var c={whens:[],points:[],angles:[]};if(this.trackAttributes){var d;c.attributes={};for(var e=0,f=this.trackAttributes.length;e<
2446 f;++e)d=this.trackAttributes[e],c.attributes[d]=[],d in this.readers.kml||(this.readers.kml[d]=this.readers.kml._trackPointAttribute)}this.readChildNodes(a,c);if(c.whens.length!==c.points.length)throw Error("gx:Track with unequal number of when ("+c.whens.length+") and gx:coord ("+c.points.length+") elements.");var g=0<c.angles.length;if(g&&c.whens.length!==c.angles.length)throw Error("gx:Track with unequal number of when ("+c.whens.length+") and gx:angles ("+c.angles.length+") elements.");for(var h,
2447 e=0,f=c.whens.length;e<f;++e){h=b.feature.clone();h.fid=b.feature.fid||b.feature.id;d=c.points[e];h.geometry=d;"z"in d&&(h.attributes.altitude=d.z);this.internalProjection&&this.externalProjection&&h.geometry.transform(this.externalProjection,this.internalProjection);if(this.trackAttributes)for(var k=0,l=this.trackAttributes.length;k<l;++k)d=this.trackAttributes[k],h.attributes[d]=c.attributes[d][e];h.attributes.when=c.whens[e];h.attributes.trackId=b.feature.id;g&&(d=c.angles[e],h.attributes.heading=
2448 parseFloat(d[0]),h.attributes.tilt=parseFloat(d[1]),h.attributes.roll=parseFloat(d[2]));b.features.push(h)}},coord:function(a,b){var c=this.getChildValue(a).replace(this.regExes.trimSpace,"").split(/\s+/),d=new OpenLayers.Geometry.Point(c[0],c[1]);2<c.length&&(d.z=parseFloat(c[2]));b.points.push(d)},angles:function(a,b){var c=this.getChildValue(a).replace(this.regExes.trimSpace,"").split(/\s+/);b.angles.push(c)}}},parseFeature:function(a){for(var b=["MultiGeometry","Polygon","LineString","Point"],
2449 c,d,e,f=0,g=b.length;f<g;++f)if(c=b[f],this.internalns=a.namespaceURI?a.namespaceURI:this.kmlns,d=this.getElementsByTagNameNS(a,this.internalns,c),0<d.length){if(b=this.parseGeometry[c.toLowerCase()])e=b.apply(this,[d[0]]),this.internalProjection&&this.externalProjection&&e.transform(this.externalProjection,this.internalProjection);else throw new TypeError("Unsupported geometry type: "+c);break}var h;this.extractAttributes&&(h=this.parseAttributes(a));c=new OpenLayers.Feature.Vector(e,h);a=a.getAttribute("id")||
2450 a.getAttribute("name");null!=a&&(c.fid=a);return c},getStyle:function(a,b){var c=OpenLayers.Util.removeTail(a),d=OpenLayers.Util.extend({},b);d.depth++;d.styleBaseUrl=c;!this.styles[a]&&!OpenLayers.String.startsWith(a,"#")&&d.depth<=this.maxDepth&&!this.fetched[c]&&(c=this.fetchLink(c))&&this.parseData(c,d);return OpenLayers.Util.extend({},this.styles[a])},parseGeometry:{point:function(a){var b=this.getElementsByTagNameNS(a,this.internalns,"coordinates");a=[];if(0<b.length){var c=b[0].firstChild.nodeValue,
2451 c=c.replace(this.regExes.removeSpace,"");a=c.split(",")}b=null;if(1<a.length)2==a.length&&(a[2]=null),b=new OpenLayers.Geometry.Point(a[0],a[1],a[2]);else throw"Bad coordinate string: "+c;return b},linestring:function(a,b){var c=this.getElementsByTagNameNS(a,this.internalns,"coordinates"),d=null;if(0<c.length){for(var c=this.getChildValue(c[0]),c=c.replace(this.regExes.trimSpace,""),c=c.replace(this.regExes.trimComma,","),d=c.split(this.regExes.splitSpace),e=d.length,f=Array(e),g,h,k=0;k<e;++k)if(g=
2452 d[k].split(","),h=g.length,1<h)2==g.length&&(g[2]=null),f[k]=new OpenLayers.Geometry.Point(g[0],g[1],g[2]);else throw"Bad LineString point coordinates: "+d[k];if(e)d=b?new OpenLayers.Geometry.LinearRing(f):new OpenLayers.Geometry.LineString(f);else throw"Bad LineString coordinates: "+c;}return d},polygon:function(a){a=this.getElementsByTagNameNS(a,this.internalns,"LinearRing");var b=a.length,c=Array(b);if(0<b)for(var d=0,e=a.length;d<e;++d)if(b=this.parseGeometry.linestring.apply(this,[a[d],!0]))c[d]=
2453 b;else throw"Bad LinearRing geometry: "+d;return new OpenLayers.Geometry.Polygon(c)},multigeometry:function(a){for(var b,c=[],d=a.childNodes,e=0,f=d.length;e<f;++e)a=d[e],1==a.nodeType&&(b=a.prefix?a.nodeName.split(":")[1]:a.nodeName,(b=this.parseGeometry[b.toLowerCase()])&&c.push(b.apply(this,[a])));return new OpenLayers.Geometry.Collection(c)}},parseAttributes:function(a){var b={},c=a.getElementsByTagName("ExtendedData");c.length&&(b=this.parseExtendedData(c[0]));var d,e,f;a=a.childNodes;for(var c=
2454 0,g=a.length;c<g;++c)if(d=a[c],1==d.nodeType&&(e=d.childNodes,1<=e.length&&3>=e.length)){switch(e.length){case 1:f=e[0];break;case 2:f=e[0];e=e[1];f=3==f.nodeType||4==f.nodeType?f:e;break;default:f=e[1]}if(3==f.nodeType||4==f.nodeType)if(d=d.prefix?d.nodeName.split(":")[1]:d.nodeName,f=OpenLayers.Util.getXmlNodeValue(f))f=f.replace(this.regExes.trimSpace,""),b[d]=f}return b},parseExtendedData:function(a){var b={},c,d,e,f,g=a.getElementsByTagName("Data");c=0;for(d=g.length;c<d;c++){e=g[c];f=e.getAttribute("name");
2455 var h={},k=e.getElementsByTagName("value");k.length&&(h.value=this.getChildValue(k[0]));this.kvpAttributes?b[f]=h.value:(e=e.getElementsByTagName("displayName"),e.length&&(h.displayName=this.getChildValue(e[0])),b[f]=h)}a=a.getElementsByTagName("SimpleData");c=0;for(d=a.length;c<d;c++)h={},e=a[c],f=e.getAttribute("name"),h.value=this.getChildValue(e),this.kvpAttributes?b[f]=h.value:(h.displayName=f,b[f]=h);return b},parseProperty:function(a,b,c){var d;a=this.getElementsByTagNameNS(a,b,c);try{d=OpenLayers.Util.getXmlNodeValue(a[0])}catch(e){d=
2456 null}return d},write:function(a){OpenLayers.Util.isArray(a)||(a=[a]);for(var b=this.createElementNS(this.kmlns,"kml"),c=this.createFolderXML(),d=0,e=a.length;d<e;++d)c.appendChild(this.createPlacemarkXML(a[d]));b.appendChild(c);return OpenLayers.Format.XML.prototype.write.apply(this,[b])},createFolderXML:function(){var a=this.createElementNS(this.kmlns,"Folder");if(this.foldersName){var b=this.createElementNS(this.kmlns,"name"),c=this.createTextNode(this.foldersName);b.appendChild(c);a.appendChild(b)}this.foldersDesc&&
2457 (b=this.createElementNS(this.kmlns,"description"),c=this.createTextNode(this.foldersDesc),b.appendChild(c),a.appendChild(b));return a},createPlacemarkXML:function(a){var b=this.createElementNS(this.kmlns,"name"),c=a.style&&a.style.label?a.style.label:a.id;b.appendChild(this.createTextNode(a.attributes.name||c));var d=this.createElementNS(this.kmlns,"description");d.appendChild(this.createTextNode(a.attributes.description||this.placemarksDesc));c=this.createElementNS(this.kmlns,"Placemark");null!=
2458 a.fid&&c.setAttribute("id",a.fid);c.appendChild(b);c.appendChild(d);b=this.buildGeometryNode(a.geometry);c.appendChild(b);a.attributes&&(a=this.buildExtendedData(a.attributes))&&c.appendChild(a);return c},buildGeometryNode:function(a){var b=a.CLASS_NAME,b=b.substring(b.lastIndexOf(".")+1),b=this.buildGeometry[b.toLowerCase()],c=null;b&&(c=b.apply(this,[a]));return c},buildGeometry:{point:function(a){var b=this.createElementNS(this.kmlns,"Point");b.appendChild(this.buildCoordinatesNode(a));return b},
2459 multipoint:function(a){return this.buildGeometry.collection.apply(this,[a])},linestring:function(a){var b=this.createElementNS(this.kmlns,"LineString");b.appendChild(this.buildCoordinatesNode(a));return b},multilinestring:function(a){return this.buildGeometry.collection.apply(this,[a])},linearring:function(a){var b=this.createElementNS(this.kmlns,"LinearRing");b.appendChild(this.buildCoordinatesNode(a));return b},polygon:function(a){var b=this.createElementNS(this.kmlns,"Polygon");a=a.components;
2460 for(var c,d,e=0,f=a.length;e<f;++e)c=0==e?"outerBoundaryIs":"innerBoundaryIs",c=this.createElementNS(this.kmlns,c),d=this.buildGeometry.linearring.apply(this,[a[e]]),c.appendChild(d),b.appendChild(c);return b},multipolygon:function(a){return this.buildGeometry.collection.apply(this,[a])},collection:function(a){for(var b=this.createElementNS(this.kmlns,"MultiGeometry"),c,d=0,e=a.components.length;d<e;++d)(c=this.buildGeometryNode.apply(this,[a.components[d]]))&&b.appendChild(c);return b}},buildCoordinatesNode:function(a){var b=
2461 this.createElementNS(this.kmlns,"coordinates"),c;if(c=a.components){for(var d=c.length,e=Array(d),f=0;f<d;++f)a=c[f],e[f]=this.buildCoordinates(a);c=e.join(" ")}else c=this.buildCoordinates(a);c=this.createTextNode(c);b.appendChild(c);return b},buildCoordinates:function(a){this.internalProjection&&this.externalProjection&&(a=a.clone(),a.transform(this.internalProjection,this.externalProjection));return a.x+","+a.y},buildExtendedData:function(a){var b=this.createElementNS(this.kmlns,"ExtendedData"),
2462 c;for(c in a)if(a[c]&&"name"!=c&&"description"!=c&&"styleUrl"!=c){var d=this.createElementNS(this.kmlns,"Data");d.setAttribute("name",c);var e=this.createElementNS(this.kmlns,"value");if("object"==typeof a[c]){if(a[c].value&&e.appendChild(this.createTextNode(a[c].value)),a[c].displayName){var f=this.createElementNS(this.kmlns,"displayName");f.appendChild(this.getXMLDoc().createCDATASection(a[c].displayName));d.appendChild(f)}}else e.appendChild(this.createTextNode(a[c]));d.appendChild(e);b.appendChild(d)}return this.isSimpleContent(b)?
2463 null:b},CLASS_NAME:"OpenLayers.Format.KML"});OpenLayers.Format.WMSCapabilities=OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC,{defaultVersion:"1.1.1",profile:null,CLASS_NAME:"OpenLayers.Format.WMSCapabilities"});OpenLayers.Format.WMSCapabilities.v1=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{wms:"http://www.opengis.net/wms",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance"},defaultPrefix:"wms",read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));var b=a;a&&9==a.nodeType&&(a=a.documentElement);var c={};this.readNode(a,c);void 0===c.service&&(a=new OpenLayers.Format.OGCExceptionReport,c.error=a.read(b));return c},readers:{wms:{Service:function(a,
2464 b){b.service={};this.readChildNodes(a,b.service)},Name:function(a,b){b.name=this.getChildValue(a)},Title:function(a,b){b.title=this.getChildValue(a)},Abstract:function(a,b){b["abstract"]=this.getChildValue(a)},BoundingBox:function(a,b){var c={};c.bbox=[parseFloat(a.getAttribute("minx")),parseFloat(a.getAttribute("miny")),parseFloat(a.getAttribute("maxx")),parseFloat(a.getAttribute("maxy"))];var d={x:parseFloat(a.getAttribute("resx")),y:parseFloat(a.getAttribute("resy"))};isNaN(d.x)&&isNaN(d.y)||(c.res=
2465 d);return c},OnlineResource:function(a,b){b.href=this.getAttributeNS(a,this.namespaces.xlink,"href")},ContactInformation:function(a,b){b.contactInformation={};this.readChildNodes(a,b.contactInformation)},ContactPersonPrimary:function(a,b){b.personPrimary={};this.readChildNodes(a,b.personPrimary)},ContactPerson:function(a,b){b.person=this.getChildValue(a)},ContactOrganization:function(a,b){b.organization=this.getChildValue(a)},ContactPosition:function(a,b){b.position=this.getChildValue(a)},ContactAddress:function(a,
2466 b){b.contactAddress={};this.readChildNodes(a,b.contactAddress)},AddressType:function(a,b){b.type=this.getChildValue(a)},Address:function(a,b){b.address=this.getChildValue(a)},City:function(a,b){b.city=this.getChildValue(a)},StateOrProvince:function(a,b){b.stateOrProvince=this.getChildValue(a)},PostCode:function(a,b){b.postcode=this.getChildValue(a)},Country:function(a,b){b.country=this.getChildValue(a)},ContactVoiceTelephone:function(a,b){b.phone=this.getChildValue(a)},ContactFacsimileTelephone:function(a,
2467 b){b.fax=this.getChildValue(a)},ContactElectronicMailAddress:function(a,b){b.email=this.getChildValue(a)},Fees:function(a,b){var c=this.getChildValue(a);c&&"none"!=c.toLowerCase()&&(b.fees=c)},AccessConstraints:function(a,b){var c=this.getChildValue(a);c&&"none"!=c.toLowerCase()&&(b.accessConstraints=c)},Capability:function(a,b){b.capability={nestedLayers:[],layers:[]};this.readChildNodes(a,b.capability)},Request:function(a,b){b.request={};this.readChildNodes(a,b.request)},GetCapabilities:function(a,
2468 b){b.getcapabilities={formats:[]};this.readChildNodes(a,b.getcapabilities)},Format:function(a,b){OpenLayers.Util.isArray(b.formats)?b.formats.push(this.getChildValue(a)):b.format=this.getChildValue(a)},DCPType:function(a,b){this.readChildNodes(a,b)},HTTP:function(a,b){this.readChildNodes(a,b)},Get:function(a,b){b.get={};this.readChildNodes(a,b.get);b.href||(b.href=b.get.href)},Post:function(a,b){b.post={};this.readChildNodes(a,b.post);b.href||(b.href=b.get.href)},GetMap:function(a,b){b.getmap={formats:[]};
2469 this.readChildNodes(a,b.getmap)},GetFeatureInfo:function(a,b){b.getfeatureinfo={formats:[]};this.readChildNodes(a,b.getfeatureinfo)},Exception:function(a,b){b.exception={formats:[]};this.readChildNodes(a,b.exception)},Layer:function(a,b){var c,d;b.capability?(d=b.capability,c=b):d=b;var e=a.getAttributeNode("queryable"),f=e&&e.specified?a.getAttribute("queryable"):null,g=(e=a.getAttributeNode("cascaded"))&&e.specified?a.getAttribute("cascaded"):null,e=(e=a.getAttributeNode("opaque"))&&e.specified?
2470 a.getAttribute("opaque"):null,h=a.getAttribute("noSubsets"),k=a.getAttribute("fixedWidth"),l=a.getAttribute("fixedHeight"),m=c||{},n=OpenLayers.Util.extend;c={nestedLayers:[],styles:c?[].concat(c.styles):[],srs:c?n({},m.srs):{},metadataURLs:[],bbox:c?n({},m.bbox):{},llbbox:m.llbbox,dimensions:c?n({},m.dimensions):{},authorityURLs:c?n({},m.authorityURLs):{},identifiers:{},keywords:[],queryable:f&&""!==f?"1"===f||"true"===f:m.queryable||!1,cascaded:null!==g?parseInt(g):m.cascaded||0,opaque:e?"1"===
2471 e||"true"===e:m.opaque||!1,noSubsets:null!==h?"1"===h||"true"===h:m.noSubsets||!1,fixedWidth:null!=k?parseInt(k):m.fixedWidth||0,fixedHeight:null!=l?parseInt(l):m.fixedHeight||0,minScale:m.minScale,maxScale:m.maxScale,attribution:m.attribution};b.nestedLayers.push(c);c.capability=d;this.readChildNodes(a,c);delete c.capability;c.name&&(f=c.name.split(":"),g=d.request,e=g.getfeatureinfo,0<f.length&&(c.prefix=f[0]),d.layers.push(c),void 0===c.formats&&(c.formats=g.getmap.formats),void 0===c.infoFormats&&
2472 e&&(c.infoFormats=e.formats))},Attribution:function(a,b){b.attribution={};this.readChildNodes(a,b.attribution)},LogoURL:function(a,b){b.logo={width:a.getAttribute("width"),height:a.getAttribute("height")};this.readChildNodes(a,b.logo)},Style:function(a,b){var c={};b.styles.push(c);this.readChildNodes(a,c)},LegendURL:function(a,b){var c={width:a.getAttribute("width"),height:a.getAttribute("height")};b.legend=c;this.readChildNodes(a,c)},MetadataURL:function(a,b){var c={type:a.getAttribute("type")};
2473 b.metadataURLs.push(c);this.readChildNodes(a,c)},DataURL:function(a,b){b.dataURL={};this.readChildNodes(a,b.dataURL)},FeatureListURL:function(a,b){b.featureListURL={};this.readChildNodes(a,b.featureListURL)},AuthorityURL:function(a,b){var c=a.getAttribute("name"),d={};this.readChildNodes(a,d);b.authorityURLs[c]=d.href},Identifier:function(a,b){var c=a.getAttribute("authority");b.identifiers[c]=this.getChildValue(a)},KeywordList:function(a,b){this.readChildNodes(a,b)},SRS:function(a,b){b.srs[this.getChildValue(a)]=
2474 !0}}},CLASS_NAME:"OpenLayers.Format.WMSCapabilities.v1"});OpenLayers.Format.WMSCapabilities.v1_1=OpenLayers.Class(OpenLayers.Format.WMSCapabilities.v1,{readers:{wms:OpenLayers.Util.applyDefaults({WMT_MS_Capabilities:function(a,b){this.readChildNodes(a,b)},Keyword:function(a,b){b.keywords&&b.keywords.push(this.getChildValue(a))},DescribeLayer:function(a,b){b.describelayer={formats:[]};this.readChildNodes(a,b.describelayer)},GetLegendGraphic:function(a,b){b.getlegendgraphic={formats:[]};this.readChildNodes(a,b.getlegendgraphic)},GetStyles:function(a,b){b.getstyles=
2475 {formats:[]};this.readChildNodes(a,b.getstyles)},PutStyles:function(a,b){b.putstyles={formats:[]};this.readChildNodes(a,b.putstyles)},UserDefinedSymbolization:function(a,b){var c={supportSLD:1==parseInt(a.getAttribute("SupportSLD")),userLayer:1==parseInt(a.getAttribute("UserLayer")),userStyle:1==parseInt(a.getAttribute("UserStyle")),remoteWFS:1==parseInt(a.getAttribute("RemoteWFS"))};b.userSymbols=c},LatLonBoundingBox:function(a,b){b.llbbox=[parseFloat(a.getAttribute("minx")),parseFloat(a.getAttribute("miny")),
2476 parseFloat(a.getAttribute("maxx")),parseFloat(a.getAttribute("maxy"))]},BoundingBox:function(a,b){var c=OpenLayers.Format.WMSCapabilities.v1.prototype.readers.wms.BoundingBox.apply(this,[a,b]);c.srs=a.getAttribute("SRS");b.bbox[c.srs]=c},ScaleHint:function(a,b){var c=a.getAttribute("min"),d=a.getAttribute("max"),e=Math.pow(2,0.5),f=OpenLayers.INCHES_PER_UNIT.m;0!=c&&(b.maxScale=parseFloat((c/e*f*OpenLayers.DOTS_PER_INCH).toPrecision(13)));d!=Number.POSITIVE_INFINITY&&(b.minScale=parseFloat((d/e*f*
2477 OpenLayers.DOTS_PER_INCH).toPrecision(13)))},Dimension:function(a,b){var c={name:a.getAttribute("name").toLowerCase(),units:a.getAttribute("units"),unitsymbol:a.getAttribute("unitSymbol")};b.dimensions[c.name]=c},Extent:function(a,b){var c=a.getAttribute("name").toLowerCase();if(c in b.dimensions){c=b.dimensions[c];c.nearestVal="1"===a.getAttribute("nearestValue");c.multipleVal="1"===a.getAttribute("multipleValues");c.current="1"===a.getAttribute("current");c["default"]=a.getAttribute("default")||
2478 "";var d=this.getChildValue(a);c.values=d.split(",")}}},OpenLayers.Format.WMSCapabilities.v1.prototype.readers.wms)},CLASS_NAME:"OpenLayers.Format.WMSCapabilities.v1_1"});OpenLayers.Format.WMSCapabilities.v1_1_0=OpenLayers.Class(OpenLayers.Format.WMSCapabilities.v1_1,{version:"1.1.0",readers:{wms:OpenLayers.Util.applyDefaults({SRS:function(a,b){for(var c=this.getChildValue(a).split(/ +/),d=0,e=c.length;d<e;d++)b.srs[c[d]]=!0}},OpenLayers.Format.WMSCapabilities.v1_1.prototype.readers.wms)},CLASS_NAME:"OpenLayers.Format.WMSCapabilities.v1_1_0"});OpenLayers.Protocol.WFS.v1=OpenLayers.Class(OpenLayers.Protocol,{version:null,srsName:"EPSG:4326",featureType:null,featureNS:null,geometryName:"the_geom",schema:null,featurePrefix:"feature",formatOptions:null,readFormat:null,readOptions:null,initialize:function(a){OpenLayers.Protocol.prototype.initialize.apply(this,[a]);a.format||(this.format=OpenLayers.Format.WFST(OpenLayers.Util.extend({version:this.version,featureType:this.featureType,featureNS:this.featureNS,featurePrefix:this.featurePrefix,geometryName:this.geometryName,
2479 srsName:this.srsName,schema:this.schema},this.formatOptions)));!a.geometryName&&1<parseFloat(this.format.version)&&this.setGeometryName(null)},destroy:function(){this.options&&!this.options.format&&this.format.destroy();this.format=null;OpenLayers.Protocol.prototype.destroy.apply(this)},read:function(a){OpenLayers.Protocol.prototype.read.apply(this,arguments);a=OpenLayers.Util.extend({},a);OpenLayers.Util.applyDefaults(a,this.options||{});var b=new OpenLayers.Protocol.Response({requestType:"read"}),
2480 c=OpenLayers.Format.XML.prototype.write.apply(this.format,[this.format.writeNode("wfs:GetFeature",a)]);b.priv=OpenLayers.Request.POST({url:a.url,callback:this.createCallback(this.handleRead,b,a),params:a.params,headers:a.headers,data:c});return b},setFeatureType:function(a){this.featureType=a;this.format.featureType=a},setGeometryName:function(a){this.geometryName=a;this.format.geometryName=a},handleRead:function(a,b){b=OpenLayers.Util.extend({},b);OpenLayers.Util.applyDefaults(b,this.options);if(b.callback){var c=
2481 a.priv;200<=c.status&&300>c.status?(c=this.parseResponse(c,b.readOptions))&&!1!==c.success?(b.readOptions&&"object"==b.readOptions.output?OpenLayers.Util.extend(a,c):a.features=c,a.code=OpenLayers.Protocol.Response.SUCCESS):(a.code=OpenLayers.Protocol.Response.FAILURE,a.error=c):a.code=OpenLayers.Protocol.Response.FAILURE;b.callback.call(b.scope,a)}},parseResponse:function(a,b){var c=a.responseXML;c&&c.documentElement||(c=a.responseText);if(!c||0>=c.length)return null;c=null!==this.readFormat?this.readFormat.read(c):
2482 this.format.read(c,b);if(!this.featureNS){var d=this.readFormat||this.format;this.featureNS=d.featureNS;d.autoConfig=!1;this.geometryName||this.setGeometryName(d.geometryName)}return c},commit:function(a,b){b=OpenLayers.Util.extend({},b);OpenLayers.Util.applyDefaults(b,this.options);var c=new OpenLayers.Protocol.Response({requestType:"commit",reqFeatures:a});c.priv=OpenLayers.Request.POST({url:b.url,headers:b.headers,data:this.format.write(a,b),callback:this.createCallback(this.handleCommit,c,b)});
2483 return c},handleCommit:function(a,b){if(b.callback){var c=a.priv,d=c.responseXML;d&&d.documentElement||(d=c.responseText);c=this.format.read(d)||{};a.insertIds=c.insertIds||[];c.success?a.code=OpenLayers.Protocol.Response.SUCCESS:(a.code=OpenLayers.Protocol.Response.FAILURE,a.error=c);b.callback.call(b.scope,a)}},filterDelete:function(a,b){b=OpenLayers.Util.extend({},b);OpenLayers.Util.applyDefaults(b,this.options);new OpenLayers.Protocol.Response({requestType:"commit"});var c=this.format.createElementNSPlus("wfs:Transaction",
2484 {attributes:{service:"WFS",version:this.version}}),d=this.format.createElementNSPlus("wfs:Delete",{attributes:{typeName:(b.featureNS?this.featurePrefix+":":"")+b.featureType}});b.featureNS&&d.setAttribute("xmlns:"+this.featurePrefix,b.featureNS);var e=this.format.writeNode("ogc:Filter",a);d.appendChild(e);c.appendChild(d);c=OpenLayers.Format.XML.prototype.write.apply(this.format,[c]);return OpenLayers.Request.POST({url:this.url,callback:b.callback||function(){},data:c})},abort:function(a){a&&a.priv.abort()},
2485 CLASS_NAME:"OpenLayers.Protocol.WFS.v1"});OpenLayers.Handler.Feature=OpenLayers.Class(OpenLayers.Handler,{EVENTMAP:{click:{"in":"click",out:"clickout"},mousemove:{"in":"over",out:"out"},dblclick:{"in":"dblclick",out:null},mousedown:{"in":null,out:null},mouseup:{"in":null,out:null},touchstart:{"in":"click",out:"clickout"}},feature:null,lastFeature:null,down:null,up:null,clickTolerance:4,geometryTypes:null,stopClick:!0,stopDown:!0,stopUp:!1,initialize:function(a,b,c,d){OpenLayers.Handler.prototype.initialize.apply(this,[a,c,d]);this.layer=
2486 b},touchstart:function(a){this.startTouch();return OpenLayers.Event.isMultiTouch(a)?!0:this.mousedown(a)},touchmove:function(a){OpenLayers.Event.preventDefault(a)},mousedown:function(a){if(OpenLayers.Event.isLeftClick(a)||OpenLayers.Event.isSingleTouch(a))this.down=a.xy;return this.handle(a)?!this.stopDown:!0},mouseup:function(a){this.up=a.xy;return this.handle(a)?!this.stopUp:!0},click:function(a){return this.handle(a)?!this.stopClick:!0},mousemove:function(a){if(!this.callbacks.over&&!this.callbacks.out)return!0;
2487 this.handle(a);return!0},dblclick:function(a){return!this.handle(a)},geometryTypeMatches:function(a){return null==this.geometryTypes||-1<OpenLayers.Util.indexOf(this.geometryTypes,a.geometry.CLASS_NAME)},handle:function(a){this.feature&&!this.feature.layer&&(this.feature=null);var b=a.type,c=!1,d=!!this.feature,e="click"==b||"dblclick"==b||"touchstart"==b;(this.feature=this.layer.getFeatureFromEvent(a))&&!this.feature.layer&&(this.feature=null);this.lastFeature&&!this.lastFeature.layer&&(this.lastFeature=
2488 null);this.feature?("touchstart"===b&&OpenLayers.Event.preventDefault(a),a=this.feature!=this.lastFeature,this.geometryTypeMatches(this.feature)?(d&&a?(this.lastFeature&&this.triggerCallback(b,"out",[this.lastFeature]),this.triggerCallback(b,"in",[this.feature])):d&&!e||this.triggerCallback(b,"in",[this.feature]),this.lastFeature=this.feature,c=!0):(this.lastFeature&&(d&&a||e)&&this.triggerCallback(b,"out",[this.lastFeature]),this.feature=null)):this.lastFeature&&(d||e)&&this.triggerCallback(b,"out",
2489 [this.lastFeature]);return c},triggerCallback:function(a,b,c){if(b=this.EVENTMAP[a][b])"click"==a&&this.up&&this.down?(Math.sqrt(Math.pow(this.up.x-this.down.x,2)+Math.pow(this.up.y-this.down.y,2))<=this.clickTolerance&&this.callback(b,c),this.up=this.down=null):this.callback(b,c)},activate:function(){var a=!1;OpenLayers.Handler.prototype.activate.apply(this,arguments)&&(this.moveLayerToTop(),this.map.events.on({removelayer:this.handleMapEvents,changelayer:this.handleMapEvents,scope:this}),a=!0);
2490 return a},deactivate:function(){var a=!1;OpenLayers.Handler.prototype.deactivate.apply(this,arguments)&&(this.moveLayerBack(),this.up=this.down=this.lastFeature=this.feature=null,this.map.events.un({removelayer:this.handleMapEvents,changelayer:this.handleMapEvents,scope:this}),a=!0);return a},handleMapEvents:function(a){"removelayer"!=a.type&&"order"!=a.property||this.moveLayerToTop()},moveLayerToTop:function(){var a=Math.max(this.map.Z_INDEX_BASE.Feature-1,this.layer.getZIndex())+1;this.layer.setZIndex(a)},
2491 moveLayerBack:function(){var a=this.layer.getZIndex()-1;a>=this.map.Z_INDEX_BASE.Feature?this.layer.setZIndex(a):this.map.setLayerZIndex(this.layer,this.map.getLayerIndex(this.layer))},CLASS_NAME:"OpenLayers.Handler.Feature"});OpenLayers.Layer.Vector.RootContainer=OpenLayers.Class(OpenLayers.Layer.Vector,{displayInLayerSwitcher:!1,layers:null,display:function(){},getFeatureFromEvent:function(a){for(var b=this.layers,c,d=0;d<b.length;d++)if(c=b[d].getFeatureFromEvent(a))return c},setMap:function(a){OpenLayers.Layer.Vector.prototype.setMap.apply(this,arguments);this.collectRoots();a.events.register("changelayer",this,this.handleChangeLayer)},removeMap:function(a){a.events.unregister("changelayer",this,this.handleChangeLayer);
2492 this.resetRoots();OpenLayers.Layer.Vector.prototype.removeMap.apply(this,arguments)},collectRoots:function(){for(var a,b=0;b<this.map.layers.length;++b)a=this.map.layers[b],-1!=OpenLayers.Util.indexOf(this.layers,a)&&a.renderer.moveRoot(this.renderer)},resetRoots:function(){for(var a,b=0;b<this.layers.length;++b)a=this.layers[b],this.renderer&&a.renderer.getRenderLayerId()==this.id&&this.renderer.moveRoot(a.renderer)},handleChangeLayer:function(a){var b=a.layer;"order"==a.property&&-1!=OpenLayers.Util.indexOf(this.layers,
2493 b)&&(this.resetRoots(),this.collectRoots())},CLASS_NAME:"OpenLayers.Layer.Vector.RootContainer"});OpenLayers.Control.SelectFeature=OpenLayers.Class(OpenLayers.Control,{multipleKey:null,toggleKey:null,multiple:!1,clickout:!0,toggle:!1,hover:!1,highlightOnly:!1,box:!1,onBeforeSelect:function(){},onSelect:function(){},onUnselect:function(){},scope:null,geometryTypes:null,layer:null,layers:null,callbacks:null,selectStyle:null,renderIntent:"select",handlers:null,initialize:function(a,b){OpenLayers.Control.prototype.initialize.apply(this,[b]);null===this.scope&&(this.scope=this);this.initLayer(a);var c=
2494 {click:this.clickFeature,clickout:this.clickoutFeature};this.hover&&(c.over=this.overFeature,c.out=this.outFeature);this.callbacks=OpenLayers.Util.extend(c,this.callbacks);this.handlers={feature:new OpenLayers.Handler.Feature(this,this.layer,this.callbacks,{geometryTypes:this.geometryTypes})};this.box&&(this.handlers.box=new OpenLayers.Handler.Box(this,{done:this.selectBox},{boxDivClassName:"olHandlerBoxSelectFeature"}))},initLayer:function(a){OpenLayers.Util.isArray(a)?(this.layers=a,this.layer=
2495 new OpenLayers.Layer.Vector.RootContainer(this.id+"_container",{layers:a})):this.layer=a},destroy:function(){this.active&&this.layers&&this.map.removeLayer(this.layer);OpenLayers.Control.prototype.destroy.apply(this,arguments);this.layers&&this.layer.destroy()},activate:function(){this.active||(this.layers&&this.map.addLayer(this.layer),this.handlers.feature.activate(),this.box&&this.handlers.box&&this.handlers.box.activate());return OpenLayers.Control.prototype.activate.apply(this,arguments)},deactivate:function(){this.active&&
2496 (this.handlers.feature.deactivate(),this.handlers.box&&this.handlers.box.deactivate(),this.layers&&this.map.removeLayer(this.layer));return OpenLayers.Control.prototype.deactivate.apply(this,arguments)},unselectAll:function(a){var b=this.layers||[this.layer],c,d,e,f;for(e=0;e<b.length;++e)if(c=b[e],f=0,null!=c.selectedFeatures)for(;c.selectedFeatures.length>f;)d=c.selectedFeatures[f],a&&a.except==d?++f:this.unselect(d)},clickFeature:function(a){this.hover||(-1<OpenLayers.Util.indexOf(a.layer.selectedFeatures,
2497 a)?this.toggleSelect()?this.unselect(a):this.multipleSelect()||this.unselectAll({except:a}):(this.multipleSelect()||this.unselectAll({except:a}),this.select(a)))},multipleSelect:function(){return this.multiple||this.handlers.feature.evt&&this.handlers.feature.evt[this.multipleKey]},toggleSelect:function(){return this.toggle||this.handlers.feature.evt&&this.handlers.feature.evt[this.toggleKey]},clickoutFeature:function(a){!this.hover&&this.clickout&&this.unselectAll()},overFeature:function(a){var b=
2498 a.layer;this.hover&&(this.highlightOnly?this.highlight(a):-1==OpenLayers.Util.indexOf(b.selectedFeatures,a)&&this.select(a))},outFeature:function(a){if(this.hover)if(this.highlightOnly){if(a._lastHighlighter==this.id)if(a._prevHighlighter&&a._prevHighlighter!=this.id){delete a._lastHighlighter;var b=this.map.getControl(a._prevHighlighter);b&&b.highlight(a)}else this.unhighlight(a)}else this.unselect(a)},highlight:function(a){var b=a.layer;!1!==this.events.triggerEvent("beforefeaturehighlighted",{feature:a})&&
2499 (a._prevHighlighter=a._lastHighlighter,a._lastHighlighter=this.id,b.drawFeature(a,this.selectStyle||this.renderIntent),this.events.triggerEvent("featurehighlighted",{feature:a}))},unhighlight:function(a){var b=a.layer;void 0==a._prevHighlighter?delete a._lastHighlighter:(a._prevHighlighter!=this.id&&(a._lastHighlighter=a._prevHighlighter),delete a._prevHighlighter);b.drawFeature(a,a.style||a.layer.style||"default");this.events.triggerEvent("featureunhighlighted",{feature:a})},select:function(a){var b=
2500 this.onBeforeSelect.call(this.scope,a),c=a.layer;!1!==b&&(b=c.events.triggerEvent("beforefeatureselected",{feature:a}),!1!==b&&(c.selectedFeatures.push(a),this.highlight(a),this.handlers.feature.lastFeature||(this.handlers.feature.lastFeature=c.selectedFeatures[0]),c.events.triggerEvent("featureselected",{feature:a}),this.onSelect.call(this.scope,a)))},unselect:function(a){var b=a.layer;this.unhighlight(a);OpenLayers.Util.removeItem(b.selectedFeatures,a);b.events.triggerEvent("featureunselected",
2501 {feature:a});this.onUnselect.call(this.scope,a)},selectBox:function(a){if(a instanceof OpenLayers.Bounds){var b=this.map.getLonLatFromPixel({x:a.left,y:a.bottom});a=this.map.getLonLatFromPixel({x:a.right,y:a.top});b=new OpenLayers.Bounds(b.lon,b.lat,a.lon,a.lat);this.multipleSelect()||this.unselectAll();a=this.multiple;this.multiple=!0;var c=this.layers||[this.layer];this.events.triggerEvent("boxselectionstart",{layers:c});for(var d,e=0;e<c.length;++e){d=c[e];for(var f=0,g=d.features.length;f<g;++f){var h=
2502 d.features[f];h.getVisibility()&&(null==this.geometryTypes||-1<OpenLayers.Util.indexOf(this.geometryTypes,h.geometry.CLASS_NAME))&&b.toGeometry().intersects(h.geometry)&&-1==OpenLayers.Util.indexOf(d.selectedFeatures,h)&&this.select(h)}}this.multiple=a;this.events.triggerEvent("boxselectionend",{layers:c})}},setMap:function(a){this.handlers.feature.setMap(a);this.box&&this.handlers.box.setMap(a);OpenLayers.Control.prototype.setMap.apply(this,arguments)},setLayer:function(a){var b=this.active;this.unselectAll();
2503 this.deactivate();this.layers&&(this.layer.destroy(),this.layers=null);this.initLayer(a);this.handlers.feature.layer=this.layer;b&&this.activate()},CLASS_NAME:"OpenLayers.Control.SelectFeature"});OpenLayers.Handler.Point=OpenLayers.Class(OpenLayers.Handler,{point:null,layer:null,multi:!1,citeCompliant:!1,mouseDown:!1,stoppedDown:null,lastDown:null,lastUp:null,persist:!1,stopDown:!1,stopUp:!1,layerOptions:null,pixelTolerance:5,lastTouchPx:null,initialize:function(a,b,c){c&&c.layerOptions&&c.layerOptions.styleMap||(this.style=OpenLayers.Util.extend(OpenLayers.Feature.Vector.style["default"],{}));OpenLayers.Handler.prototype.initialize.apply(this,arguments)},activate:function(){if(!OpenLayers.Handler.prototype.activate.apply(this,
2504 arguments))return!1;var a=OpenLayers.Util.extend({displayInLayerSwitcher:!1,calculateInRange:OpenLayers.Function.True,wrapDateLine:this.citeCompliant},this.layerOptions);this.layer=new OpenLayers.Layer.Vector(this.CLASS_NAME,a);this.map.addLayer(this.layer);return!0},createFeature:function(a){a=this.layer.getLonLatFromViewPortPx(a);a=new OpenLayers.Geometry.Point(a.lon,a.lat);this.point=new OpenLayers.Feature.Vector(a);this.callback("create",[this.point.geometry,this.point]);this.point.geometry.clearBounds();
2505 this.layer.addFeatures([this.point],{silent:!0})},deactivate:function(){if(!OpenLayers.Handler.prototype.deactivate.apply(this,arguments))return!1;this.cancel();null!=this.layer.map&&(this.destroyFeature(!0),this.layer.destroy(!1));this.layer=null;return!0},destroyFeature:function(a){!this.layer||!a&&this.persist||this.layer.destroyFeatures();this.point=null},destroyPersistedFeature:function(){var a=this.layer;a&&1<a.features.length&&this.layer.features[0].destroy()},finalize:function(a){this.mouseDown=
2506 !1;this.lastTouchPx=this.lastUp=this.lastDown=null;this.callback(a?"cancel":"done",[this.geometryClone()]);this.destroyFeature(a)},cancel:function(){this.finalize(!0)},click:function(a){OpenLayers.Event.stop(a);return!1},dblclick:function(a){OpenLayers.Event.stop(a);return!1},modifyFeature:function(a){this.point||this.createFeature(a);a=this.layer.getLonLatFromViewPortPx(a);this.point.geometry.x=a.lon;this.point.geometry.y=a.lat;this.callback("modify",[this.point.geometry,this.point,!1]);this.point.geometry.clearBounds();
2507 this.drawFeature()},drawFeature:function(){this.layer.drawFeature(this.point,this.style)},getGeometry:function(){var a=this.point&&this.point.geometry;a&&this.multi&&(a=new OpenLayers.Geometry.MultiPoint([a]));return a},geometryClone:function(){var a=this.getGeometry();return a&&a.clone()},mousedown:function(a){return this.down(a)},touchstart:function(a){this.startTouch();this.lastTouchPx=a.xy;return this.down(a)},mousemove:function(a){return this.move(a)},touchmove:function(a){this.lastTouchPx=a.xy;
2508 return this.move(a)},mouseup:function(a){return this.up(a)},touchend:function(a){a.xy=this.lastTouchPx;return this.up(a)},down:function(a){this.mouseDown=!0;this.lastDown=a.xy;this.touch||this.modifyFeature(a.xy);this.stoppedDown=this.stopDown;return!this.stopDown},move:function(a){this.touch||this.mouseDown&&!this.stoppedDown||this.modifyFeature(a.xy);return!0},up:function(a){this.mouseDown=!1;this.stoppedDown=this.stopDown;if(!this.checkModifiers(a)||this.lastUp&&this.lastUp.equals(a.xy)||!this.lastDown||
2509 !this.passesTolerance(this.lastDown,a.xy,this.pixelTolerance))return!0;this.touch&&this.modifyFeature(a.xy);this.persist&&this.destroyPersistedFeature();this.lastUp=a.xy;this.finalize();return!this.stopUp},mouseout:function(a){OpenLayers.Util.mouseLeft(a,this.map.viewPortDiv)&&(this.stoppedDown=this.stopDown,this.mouseDown=!1)},passesTolerance:function(a,b,c){var d=!0;null!=c&&a&&b&&a.distanceTo(b)>c&&(d=!1);return d},CLASS_NAME:"OpenLayers.Handler.Point"});OpenLayers.Handler.Path=OpenLayers.Class(OpenLayers.Handler.Point,{line:null,maxVertices:null,doubleTouchTolerance:20,freehand:!1,freehandToggle:"shiftKey",timerId:null,redoStack:null,createFeature:function(a){a=this.layer.getLonLatFromViewPortPx(a);a=new OpenLayers.Geometry.Point(a.lon,a.lat);this.point=new OpenLayers.Feature.Vector(a);this.line=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString([this.point.geometry]));this.callback("create",[this.point.geometry,this.getSketch()]);
2510 this.point.geometry.clearBounds();this.layer.addFeatures([this.line,this.point],{silent:!0})},destroyFeature:function(a){OpenLayers.Handler.Point.prototype.destroyFeature.call(this,a);this.line=null},destroyPersistedFeature:function(){var a=this.layer;a&&2<a.features.length&&this.layer.features[0].destroy()},removePoint:function(){this.point&&this.layer.removeFeatures([this.point])},addPoint:function(a){this.layer.removeFeatures([this.point]);a=this.layer.getLonLatFromViewPortPx(a);this.point=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(a.lon,
2511 a.lat));this.line.geometry.addComponent(this.point.geometry,this.line.geometry.components.length);this.layer.addFeatures([this.point]);this.callback("point",[this.point.geometry,this.getGeometry()]);this.callback("modify",[this.point.geometry,this.getSketch()]);this.drawFeature();delete this.redoStack},insertXY:function(a,b){this.line.geometry.addComponent(new OpenLayers.Geometry.Point(a,b),this.getCurrentPointIndex());this.drawFeature();delete this.redoStack},insertDeltaXY:function(a,b){var c=this.getCurrentPointIndex()-
2512 1,c=this.line.geometry.components[c];!c||(isNaN(c.x)||isNaN(c.y))||this.insertXY(c.x+a,c.y+b)},insertDirectionLength:function(a,b){a*=Math.PI/180;var c=b*Math.cos(a),d=b*Math.sin(a);this.insertDeltaXY(c,d)},insertDeflectionLength:function(a,b){var c=this.getCurrentPointIndex()-1;if(0<c){var d=this.line.geometry.components[c],c=this.line.geometry.components[c-1],d=Math.atan2(d.y-c.y,d.x-c.x);this.insertDirectionLength(180*d/Math.PI+a,b)}},getCurrentPointIndex:function(){return this.line.geometry.components.length-
2513 1},undo:function(){var a=this.line.geometry,b=a.components,c=this.getCurrentPointIndex()-1,d=b[c],e=a.removeComponent(d);e&&(this.touch&&0<c&&(b=a.components,a=b[c-1],c=this.getCurrentPointIndex(),b=b[c],b.x=a.x,b.y=a.y),this.redoStack||(this.redoStack=[]),this.redoStack.push(d),this.drawFeature());return e},redo:function(){var a=this.redoStack&&this.redoStack.pop();a&&(this.line.geometry.addComponent(a,this.getCurrentPointIndex()),this.drawFeature());return!!a},freehandMode:function(a){return this.freehandToggle&&
2514 a[this.freehandToggle]?!this.freehand:this.freehand},modifyFeature:function(a,b){this.line||this.createFeature(a);var c=this.layer.getLonLatFromViewPortPx(a);this.point.geometry.x=c.lon;this.point.geometry.y=c.lat;this.callback("modify",[this.point.geometry,this.getSketch(),b]);this.point.geometry.clearBounds();this.drawFeature()},drawFeature:function(){this.layer.drawFeature(this.line,this.style);this.layer.drawFeature(this.point,this.style)},getSketch:function(){return this.line},getGeometry:function(){var a=
2515 this.line&&this.line.geometry;a&&this.multi&&(a=new OpenLayers.Geometry.MultiLineString([a]));return a},touchstart:function(a){if(this.timerId&&this.passesTolerance(this.lastTouchPx,a.xy,this.doubleTouchTolerance))return this.finishGeometry(),window.clearTimeout(this.timerId),this.timerId=null,!1;this.timerId&&(window.clearTimeout(this.timerId),this.timerId=null);this.timerId=window.setTimeout(OpenLayers.Function.bind(function(){this.timerId=null},this),300);return OpenLayers.Handler.Point.prototype.touchstart.call(this,
2516 a)},down:function(a){var b=this.stopDown;this.freehandMode(a)&&(b=!0,this.touch&&(this.modifyFeature(a.xy,!!this.lastUp),OpenLayers.Event.stop(a)));this.touch||this.lastDown&&this.passesTolerance(this.lastDown,a.xy,this.pixelTolerance)||this.modifyFeature(a.xy,!!this.lastUp);this.mouseDown=!0;this.lastDown=a.xy;this.stoppedDown=b;return!b},move:function(a){if(this.stoppedDown&&this.freehandMode(a))return this.persist&&this.destroyPersistedFeature(),this.maxVertices&&this.line&&this.line.geometry.components.length===
2517 this.maxVertices?(this.removePoint(),this.finalize()):this.addPoint(a.xy),!1;this.touch||this.mouseDown&&!this.stoppedDown||this.modifyFeature(a.xy,!!this.lastUp);return!0},up:function(a){!this.mouseDown||this.lastUp&&this.lastUp.equals(a.xy)||(this.stoppedDown&&this.freehandMode(a)?(this.persist&&this.destroyPersistedFeature(),this.removePoint(),this.finalize()):this.passesTolerance(this.lastDown,a.xy,this.pixelTolerance)&&(this.touch&&this.modifyFeature(a.xy),null==this.lastUp&&this.persist&&this.destroyPersistedFeature(),
2518 this.addPoint(a.xy),this.lastUp=a.xy,this.line.geometry.components.length===this.maxVertices+1&&this.finishGeometry()));this.stoppedDown=this.stopDown;this.mouseDown=!1;return!this.stopUp},finishGeometry:function(){this.line.geometry.removeComponent(this.line.geometry.components[this.line.geometry.components.length-1]);this.removePoint();this.finalize()},dblclick:function(a){this.freehandMode(a)||this.finishGeometry();return!1},CLASS_NAME:"OpenLayers.Handler.Path"});OpenLayers.Spherical=OpenLayers.Spherical||{};OpenLayers.Spherical.DEFAULT_RADIUS=6378137;OpenLayers.Spherical.computeDistanceBetween=function(a,b,c){c=c||OpenLayers.Spherical.DEFAULT_RADIUS;var d=Math.sin(Math.PI*(b.lon-a.lon)/360),e=Math.sin(Math.PI*(b.lat-a.lat)/360);a=e*e+d*d*Math.cos(Math.PI*a.lat/180)*Math.cos(Math.PI*b.lat/180);return 2*c*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))};
2519 OpenLayers.Spherical.computeHeading=function(a,b){var c=Math.sin(Math.PI*(a.lon-b.lon)/180)*Math.cos(Math.PI*b.lat/180),d=Math.cos(Math.PI*a.lat/180)*Math.sin(Math.PI*b.lat/180)-Math.sin(Math.PI*a.lat/180)*Math.cos(Math.PI*b.lat/180)*Math.cos(Math.PI*(a.lon-b.lon)/180);return 180*Math.atan2(c,d)/Math.PI};OpenLayers.Control.CacheWrite=OpenLayers.Class(OpenLayers.Control,{layers:null,imageFormat:"image/png",quotaRegEx:/quota/i,setMap:function(a){OpenLayers.Control.prototype.setMap.apply(this,arguments);var b,c=this.layers||a.layers;for(b=c.length-1;0<=b;--b)this.addLayer({layer:c[b]});if(!this.layers)a.events.on({addlayer:this.addLayer,removeLayer:this.removeLayer,scope:this})},addLayer:function(a){a.layer.events.on({tileloadstart:this.makeSameOrigin,tileloaded:this.onTileLoaded,scope:this})},removeLayer:function(a){a.layer.events.un({tileloadstart:this.makeSameOrigin,
2520 tileloaded:this.onTileLoaded,scope:this})},makeSameOrigin:function(a){if(this.active&&(a=a.tile,a instanceof OpenLayers.Tile.Image&&!a.crossOriginKeyword&&"data:"!==a.url.substr(0,5))){var b=OpenLayers.Request.makeSameOrigin(a.url,OpenLayers.ProxyHost);OpenLayers.Control.CacheWrite.urlMap[b]=a.url;a.url=b}},onTileLoaded:function(a){this.active&&(!a.aborted&&a.tile instanceof OpenLayers.Tile.Image&&"data:"!==a.tile.url.substr(0,5))&&(this.cache({tile:a.tile}),delete OpenLayers.Control.CacheWrite.urlMap[a.tile.url])},
2521 cache:function(a){if(window.localStorage){a=a.tile;try{var b=a.getCanvasContext();b&&window.localStorage.setItem("olCache_"+(OpenLayers.Control.CacheWrite.urlMap[a.url]||a.url),b.canvas.toDataURL(this.imageFormat))}catch(c){(b=c.name||c.message)&&this.quotaRegEx.test(b)?this.events.triggerEvent("cachefull",{tile:a}):OpenLayers.Console.error(c.toString())}}},destroy:function(){if(this.layers||this.map){var a,b=this.layers||this.map.layers;for(a=b.length-1;0<=a;--a)this.removeLayer({layer:b[a]})}this.map&&
2522 this.map.events.un({addlayer:this.addLayer,removeLayer:this.removeLayer,scope:this});OpenLayers.Control.prototype.destroy.apply(this,arguments)},CLASS_NAME:"OpenLayers.Control.CacheWrite"});OpenLayers.Control.CacheWrite.clearCache=function(){if(window.localStorage){var a,b;for(a=window.localStorage.length-1;0<=a;--a)b=window.localStorage.key(a),"olCache_"===b.substr(0,8)&&window.localStorage.removeItem(b)}};OpenLayers.Control.CacheWrite.urlMap={};OpenLayers.Format.Context=OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC,{layerOptions:null,layerParams:null,read:function(a,b){var c=OpenLayers.Format.XML.VersionedOGC.prototype.read.apply(this,arguments);if(b&&b.map)if(this.context=c,b.map instanceof OpenLayers.Map)c=this.mergeContextToMap(c,b.map);else{var d=b.map;if(OpenLayers.Util.isElement(d)||"string"==typeof d)d={div:d};c=this.contextToMap(c,d)}return c},getLayerFromContext:function(a){var b,c,d={queryable:a.queryable,visibility:a.visibility,
2523 maxExtent:a.maxExtent,metadata:OpenLayers.Util.applyDefaults(a.metadata,{styles:a.styles,formats:a.formats,"abstract":a["abstract"],dataURL:a.dataURL}),numZoomLevels:a.numZoomLevels,units:a.units,isBaseLayer:a.isBaseLayer,opacity:a.opacity,displayInLayerSwitcher:a.displayInLayerSwitcher,singleTile:a.singleTile,tileSize:a.tileSize?new OpenLayers.Size(a.tileSize.width,a.tileSize.height):void 0,minScale:a.minScale||a.maxScaleDenominator,maxScale:a.maxScale||a.minScaleDenominator,srs:a.srs,dimensions:a.dimensions,
2524 metadataURL:a.metadataURL};this.layerOptions&&OpenLayers.Util.applyDefaults(d,this.layerOptions);var e={layers:a.name,transparent:a.transparent,version:a.version};if(a.formats&&0<a.formats.length)for(e.format=a.formats[0].value,b=0,c=a.formats.length;b<c;b++){var f=a.formats[b];if(!0==f.current){e.format=f.value;break}}if(a.styles&&0<a.styles.length)for(b=0,c=a.styles.length;b<c;b++)if(f=a.styles[b],!0==f.current){f.href?e.sld=f.href:f.body?e.sld_body=f.body:e.styles=f.name;break}this.layerParams&&
2525 OpenLayers.Util.applyDefaults(e,this.layerParams);b=null;c=a.service;c==OpenLayers.Format.Context.serviceTypes.WFS?(d.strategies=[new OpenLayers.Strategy.BBOX],d.protocol=new OpenLayers.Protocol.WFS({url:a.url,featurePrefix:a.name.split(":")[0],featureType:a.name.split(":").pop()}),b=new OpenLayers.Layer.Vector(a.title||a.name,d)):c==OpenLayers.Format.Context.serviceTypes.KML?(d.strategies=[new OpenLayers.Strategy.Fixed],d.protocol=new OpenLayers.Protocol.HTTP({url:a.url,format:new OpenLayers.Format.KML}),
2526 b=new OpenLayers.Layer.Vector(a.title||a.name,d)):c==OpenLayers.Format.Context.serviceTypes.GML?(d.strategies=[new OpenLayers.Strategy.Fixed],d.protocol=new OpenLayers.Protocol.HTTP({url:a.url,format:new OpenLayers.Format.GML}),b=new OpenLayers.Layer.Vector(a.title||a.name,d)):a.features?(b=new OpenLayers.Layer.Vector(a.title||a.name,d),b.addFeatures(a.features)):!0!==a.categoryLayer&&(b=new OpenLayers.Layer.WMS(a.title||a.name,a.url,e,d));return b},getLayersFromContext:function(a){for(var b=[],c=
2527 0,d=a.length;c<d;c++){var e=this.getLayerFromContext(a[c]);null!==e&&b.push(e)}return b},contextToMap:function(a,b){b=OpenLayers.Util.applyDefaults({maxExtent:a.maxExtent,projection:a.projection,units:a.units},b);b.maxExtent&&(b.maxResolution=b.maxExtent.getWidth()/OpenLayers.Map.TILE_WIDTH);b.metadata={contactInformation:a.contactInformation,"abstract":a["abstract"],keywords:a.keywords,logo:a.logo,descriptionURL:a.descriptionURL};var c=new OpenLayers.Map(b);c.addLayers(this.getLayersFromContext(a.layersContext));
2528 c.setCenter(a.bounds.getCenterLonLat(),c.getZoomForExtent(a.bounds,!0));return c},mergeContextToMap:function(a,b){b.addLayers(this.getLayersFromContext(a.layersContext));return b},write:function(a,b){a=this.toContext(a);return OpenLayers.Format.XML.VersionedOGC.prototype.write.apply(this,arguments)},CLASS_NAME:"OpenLayers.Format.Context"});
2529 OpenLayers.Format.Context.serviceTypes={WMS:"urn:ogc:serviceType:WMS",WFS:"urn:ogc:serviceType:WFS",WCS:"urn:ogc:serviceType:WCS",GML:"urn:ogc:serviceType:GML",SLD:"urn:ogc:serviceType:SLD",FES:"urn:ogc:serviceType:FES",KML:"urn:ogc:serviceType:KML"};OpenLayers.Format.WMC=OpenLayers.Class(OpenLayers.Format.Context,{defaultVersion:"1.1.0",layerToContext:function(a){var b=this.getParser(),c={queryable:a.queryable,visibility:a.visibility,name:a.params.LAYERS,title:a.name,"abstract":a.metadata["abstract"],dataURL:a.metadata.dataURL,metadataURL:a.metadataURL,server:{version:a.params.VERSION,url:a.url},maxExtent:a.maxExtent,transparent:a.params.TRANSPARENT,numZoomLevels:a.numZoomLevels,units:a.units,isBaseLayer:a.isBaseLayer,opacity:1==a.opacity?void 0:
2530 a.opacity,displayInLayerSwitcher:a.displayInLayerSwitcher,singleTile:a.singleTile,tileSize:a.singleTile||!a.tileSize?void 0:{width:a.tileSize.w,height:a.tileSize.h},minScale:a.options.resolutions||a.options.scales||a.options.maxResolution||a.options.minScale?a.minScale:void 0,maxScale:a.options.resolutions||a.options.scales||a.options.minResolution||a.options.maxScale?a.maxScale:void 0,formats:[],styles:[],srs:a.srs,dimensions:a.dimensions};a.metadata.servertitle&&(c.server.title=a.metadata.servertitle);
2531 if(a.metadata.formats&&0<a.metadata.formats.length)for(var d=0,e=a.metadata.formats.length;d<e;d++){var f=a.metadata.formats[d];c.formats.push({value:f.value,current:f.value==a.params.FORMAT})}else c.formats.push({value:a.params.FORMAT,current:!0});if(a.metadata.styles&&0<a.metadata.styles.length)for(d=0,e=a.metadata.styles.length;d<e;d++)b=a.metadata.styles[d],b.current=b.href==a.params.SLD||b.body==a.params.SLD_BODY||b.name==a.params.STYLES?!0:!1,c.styles.push(b);else c.styles.push({href:a.params.SLD,
2532 body:a.params.SLD_BODY,name:a.params.STYLES||b.defaultStyleName,title:b.defaultStyleTitle,current:!0});return c},toContext:function(a){var b={},c=a.layers;if("OpenLayers.Map"==a.CLASS_NAME){var d=a.metadata||{};b.size=a.getSize();b.bounds=a.getExtent();b.projection=a.projection;b.title=a.title;b.keywords=d.keywords;b["abstract"]=d["abstract"];b.logo=d.logo;b.descriptionURL=d.descriptionURL;b.contactInformation=d.contactInformation;b.maxExtent=a.maxExtent}else OpenLayers.Util.applyDefaults(b,a),void 0!=
2533 b.layers&&delete b.layers;void 0==b.layersContext&&(b.layersContext=[]);if(void 0!=c&&OpenLayers.Util.isArray(c))for(a=0,d=c.length;a<d;a++){var e=c[a];e instanceof OpenLayers.Layer.WMS&&b.layersContext.push(this.layerToContext(e))}return b},CLASS_NAME:"OpenLayers.Format.WMC"});OpenLayers.Format.WMC.v1=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{ol:"http://openlayers.org/context",wmc:"http://www.opengis.net/context",sld:"http://www.opengis.net/sld",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance"},schemaLocation:"",getNamespacePrefix:function(a){var b=null;if(null==a)b=this.namespaces[this.defaultPrefix];else for(b in this.namespaces)if(this.namespaces[b]==a)break;return b},defaultPrefix:"wmc",rootPrefix:null,defaultStyleName:"",
2534 defaultStyleTitle:"Default",initialize:function(a){OpenLayers.Format.XML.prototype.initialize.apply(this,[a])},read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));a=a.documentElement;this.rootPrefix=a.prefix;var b={version:a.getAttribute("version")};this.runChildNodes(b,a);return b},runChildNodes:function(a,b){for(var c=b.childNodes,d,e,f,g=0,h=c.length;g<h;++g)d=c[g],1==d.nodeType&&(e=this.getNamespacePrefix(d.namespaceURI),f=d.nodeName.split(":").pop(),
2535 (e=this["read_"+e+"_"+f])&&e.apply(this,[a,d]))},read_wmc_General:function(a,b){this.runChildNodes(a,b)},read_wmc_BoundingBox:function(a,b){a.projection=b.getAttribute("SRS");a.bounds=new OpenLayers.Bounds(b.getAttribute("minx"),b.getAttribute("miny"),b.getAttribute("maxx"),b.getAttribute("maxy"))},read_wmc_LayerList:function(a,b){a.layersContext=[];this.runChildNodes(a,b)},read_wmc_Layer:function(a,b){var c={visibility:"1"!=b.getAttribute("hidden"),queryable:"1"==b.getAttribute("queryable"),formats:[],
2536 styles:[],metadata:{}};this.runChildNodes(c,b);a.layersContext.push(c)},read_wmc_Extension:function(a,b){this.runChildNodes(a,b)},read_ol_units:function(a,b){a.units=this.getChildValue(b)},read_ol_maxExtent:function(a,b){var c=new OpenLayers.Bounds(b.getAttribute("minx"),b.getAttribute("miny"),b.getAttribute("maxx"),b.getAttribute("maxy"));a.maxExtent=c},read_ol_transparent:function(a,b){a.transparent=this.getChildValue(b)},read_ol_numZoomLevels:function(a,b){a.numZoomLevels=parseInt(this.getChildValue(b))},
2537 read_ol_opacity:function(a,b){a.opacity=parseFloat(this.getChildValue(b))},read_ol_singleTile:function(a,b){a.singleTile="true"==this.getChildValue(b)},read_ol_tileSize:function(a,b){var c={width:b.getAttribute("width"),height:b.getAttribute("height")};a.tileSize=c},read_ol_isBaseLayer:function(a,b){a.isBaseLayer="true"==this.getChildValue(b)},read_ol_displayInLayerSwitcher:function(a,b){a.displayInLayerSwitcher="true"==this.getChildValue(b)},read_wmc_Server:function(a,b){a.version=b.getAttribute("version");
2538 a.url=this.getOnlineResource_href(b);a.metadata.servertitle=b.getAttribute("title")},read_wmc_FormatList:function(a,b){this.runChildNodes(a,b)},read_wmc_Format:function(a,b){var c={value:this.getChildValue(b)};"1"==b.getAttribute("current")&&(c.current=!0);a.formats.push(c)},read_wmc_StyleList:function(a,b){this.runChildNodes(a,b)},read_wmc_Style:function(a,b){var c={};this.runChildNodes(c,b);"1"==b.getAttribute("current")&&(c.current=!0);a.styles.push(c)},read_wmc_SLD:function(a,b){this.runChildNodes(a,
2539 b)},read_sld_StyledLayerDescriptor:function(a,b){var c=OpenLayers.Format.XML.prototype.write.apply(this,[b]);a.body=c},read_sld_FeatureTypeStyle:function(a,b){var c=OpenLayers.Format.XML.prototype.write.apply(this,[b]);a.body=c},read_wmc_OnlineResource:function(a,b){a.href=this.getAttributeNS(b,this.namespaces.xlink,"href")},read_wmc_Name:function(a,b){var c=this.getChildValue(b);c&&(a.name=c)},read_wmc_Title:function(a,b){var c=this.getChildValue(b);c&&(a.title=c)},read_wmc_MetadataURL:function(a,
2540 b){a.metadataURL=this.getOnlineResource_href(b)},read_wmc_KeywordList:function(a,b){a.keywords=[];this.runChildNodes(a.keywords,b)},read_wmc_Keyword:function(a,b){a.push(this.getChildValue(b))},read_wmc_Abstract:function(a,b){var c=this.getChildValue(b);c&&(a["abstract"]=c)},read_wmc_LogoURL:function(a,b){a.logo={width:b.getAttribute("width"),height:b.getAttribute("height"),format:b.getAttribute("format"),href:this.getOnlineResource_href(b)}},read_wmc_DescriptionURL:function(a,b){a.descriptionURL=
2541 this.getOnlineResource_href(b)},read_wmc_ContactInformation:function(a,b){var c={};this.runChildNodes(c,b);a.contactInformation=c},read_wmc_ContactPersonPrimary:function(a,b){var c={};this.runChildNodes(c,b);a.personPrimary=c},read_wmc_ContactPerson:function(a,b){var c=this.getChildValue(b);c&&(a.person=c)},read_wmc_ContactOrganization:function(a,b){var c=this.getChildValue(b);c&&(a.organization=c)},read_wmc_ContactPosition:function(a,b){var c=this.getChildValue(b);c&&(a.position=c)},read_wmc_ContactAddress:function(a,
2542 b){var c={};this.runChildNodes(c,b);a.contactAddress=c},read_wmc_AddressType:function(a,b){var c=this.getChildValue(b);c&&(a.type=c)},read_wmc_Address:function(a,b){var c=this.getChildValue(b);c&&(a.address=c)},read_wmc_City:function(a,b){var c=this.getChildValue(b);c&&(a.city=c)},read_wmc_StateOrProvince:function(a,b){var c=this.getChildValue(b);c&&(a.stateOrProvince=c)},read_wmc_PostCode:function(a,b){var c=this.getChildValue(b);c&&(a.postcode=c)},read_wmc_Country:function(a,b){var c=this.getChildValue(b);
2543 c&&(a.country=c)},read_wmc_ContactVoiceTelephone:function(a,b){var c=this.getChildValue(b);c&&(a.phone=c)},read_wmc_ContactFacsimileTelephone:function(a,b){var c=this.getChildValue(b);c&&(a.fax=c)},read_wmc_ContactElectronicMailAddress:function(a,b){var c=this.getChildValue(b);c&&(a.email=c)},read_wmc_DataURL:function(a,b){a.dataURL=this.getOnlineResource_href(b)},read_wmc_LegendURL:function(a,b){var c={width:b.getAttribute("width"),height:b.getAttribute("height"),format:b.getAttribute("format"),
2544 href:this.getOnlineResource_href(b)};a.legend=c},read_wmc_DimensionList:function(a,b){a.dimensions={};this.runChildNodes(a.dimensions,b)},read_wmc_Dimension:function(a,b){var c={name:b.getAttribute("name").toLowerCase(),units:b.getAttribute("units")||"",unitSymbol:b.getAttribute("unitSymbol")||"",userValue:b.getAttribute("userValue")||"",nearestValue:"1"===b.getAttribute("nearestValue"),multipleValues:"1"===b.getAttribute("multipleValues"),current:"1"===b.getAttribute("current"),"default":b.getAttribute("default")||
2545 ""},d=this.getChildValue(b);c.values=d.split(",");a[c.name]=c},write:function(a,b){var c=this.createElementDefaultNS("ViewContext");this.setAttributes(c,{version:this.VERSION,id:b&&"string"==typeof b.id?b.id:OpenLayers.Util.createUniqueID("OpenLayers_Context_")});this.setAttributeNS(c,this.namespaces.xsi,"xsi:schemaLocation",this.schemaLocation);c.appendChild(this.write_wmc_General(a));c.appendChild(this.write_wmc_LayerList(a));return OpenLayers.Format.XML.prototype.write.apply(this,[c])},createElementDefaultNS:function(a,
2546 b,c){a=this.createElementNS(this.namespaces[this.defaultPrefix],a);b&&a.appendChild(this.createTextNode(b));c&&this.setAttributes(a,c);return a},setAttributes:function(a,b){var c,d;for(d in b)c=b[d].toString(),c.match(/[A-Z]/)?this.setAttributeNS(a,null,d,c):a.setAttribute(d,c)},write_wmc_General:function(a){var b=this.createElementDefaultNS("General");a.size&&b.appendChild(this.createElementDefaultNS("Window",null,{width:a.size.w,height:a.size.h}));var c=a.bounds;b.appendChild(this.createElementDefaultNS("BoundingBox",
2547 null,{minx:c.left.toPrecision(18),miny:c.bottom.toPrecision(18),maxx:c.right.toPrecision(18),maxy:c.top.toPrecision(18),SRS:a.projection}));b.appendChild(this.createElementDefaultNS("Title",a.title));a.keywords&&b.appendChild(this.write_wmc_KeywordList(a.keywords));a["abstract"]&&b.appendChild(this.createElementDefaultNS("Abstract",a["abstract"]));a.logo&&b.appendChild(this.write_wmc_URLType("LogoURL",a.logo.href,a.logo));a.descriptionURL&&b.appendChild(this.write_wmc_URLType("DescriptionURL",a.descriptionURL));
2548 a.contactInformation&&b.appendChild(this.write_wmc_ContactInformation(a.contactInformation));b.appendChild(this.write_ol_MapExtension(a));return b},write_wmc_KeywordList:function(a){for(var b=this.createElementDefaultNS("KeywordList"),c=0,d=a.length;c<d;c++)b.appendChild(this.createElementDefaultNS("Keyword",a[c]));return b},write_wmc_ContactInformation:function(a){var b=this.createElementDefaultNS("ContactInformation");a.personPrimary&&b.appendChild(this.write_wmc_ContactPersonPrimary(a.personPrimary));
2549 a.position&&b.appendChild(this.createElementDefaultNS("ContactPosition",a.position));a.contactAddress&&b.appendChild(this.write_wmc_ContactAddress(a.contactAddress));a.phone&&b.appendChild(this.createElementDefaultNS("ContactVoiceTelephone",a.phone));a.fax&&b.appendChild(this.createElementDefaultNS("ContactFacsimileTelephone",a.fax));a.email&&b.appendChild(this.createElementDefaultNS("ContactElectronicMailAddress",a.email));return b},write_wmc_ContactPersonPrimary:function(a){var b=this.createElementDefaultNS("ContactPersonPrimary");
2550 a.person&&b.appendChild(this.createElementDefaultNS("ContactPerson",a.person));a.organization&&b.appendChild(this.createElementDefaultNS("ContactOrganization",a.organization));return b},write_wmc_ContactAddress:function(a){var b=this.createElementDefaultNS("ContactAddress");a.type&&b.appendChild(this.createElementDefaultNS("AddressType",a.type));a.address&&b.appendChild(this.createElementDefaultNS("Address",a.address));a.city&&b.appendChild(this.createElementDefaultNS("City",a.city));a.stateOrProvince&&
2551 b.appendChild(this.createElementDefaultNS("StateOrProvince",a.stateOrProvince));a.postcode&&b.appendChild(this.createElementDefaultNS("PostCode",a.postcode));a.country&&b.appendChild(this.createElementDefaultNS("Country",a.country));return b},write_ol_MapExtension:function(a){var b=this.createElementDefaultNS("Extension");if(a=a.maxExtent){var c=this.createElementNS(this.namespaces.ol,"ol:maxExtent");this.setAttributes(c,{minx:a.left.toPrecision(18),miny:a.bottom.toPrecision(18),maxx:a.right.toPrecision(18),
2552 maxy:a.top.toPrecision(18)});b.appendChild(c)}return b},write_wmc_LayerList:function(a){for(var b=this.createElementDefaultNS("LayerList"),c=0,d=a.layersContext.length;c<d;++c)b.appendChild(this.write_wmc_Layer(a.layersContext[c]));return b},write_wmc_Layer:function(a){var b=this.createElementDefaultNS("Layer",null,{queryable:a.queryable?"1":"0",hidden:a.visibility?"0":"1"});b.appendChild(this.write_wmc_Server(a));b.appendChild(this.createElementDefaultNS("Name",a.name));b.appendChild(this.createElementDefaultNS("Title",
2553 a.title));a["abstract"]&&b.appendChild(this.createElementDefaultNS("Abstract",a["abstract"]));a.dataURL&&b.appendChild(this.write_wmc_URLType("DataURL",a.dataURL));a.metadataURL&&b.appendChild(this.write_wmc_URLType("MetadataURL",a.metadataURL));return b},write_wmc_LayerExtension:function(a){var b=this.createElementDefaultNS("Extension"),c=a.maxExtent,d=this.createElementNS(this.namespaces.ol,"ol:maxExtent");this.setAttributes(d,{minx:c.left.toPrecision(18),miny:c.bottom.toPrecision(18),maxx:c.right.toPrecision(18),
2554 maxy:c.top.toPrecision(18)});b.appendChild(d);a.tileSize&&!a.singleTile&&(c=this.createElementNS(this.namespaces.ol,"ol:tileSize"),this.setAttributes(c,a.tileSize),b.appendChild(c));for(var c="transparent numZoomLevels units isBaseLayer opacity displayInLayerSwitcher singleTile".split(" "),e=0,f=c.length;e<f;++e)(d=this.createOLPropertyNode(a,c[e]))&&b.appendChild(d);return b},createOLPropertyNode:function(a,b){var c=null;null!=a[b]&&(c=this.createElementNS(this.namespaces.ol,"ol:"+b),c.appendChild(this.createTextNode(a[b].toString())));
2555 return c},write_wmc_Server:function(a){a=a.server;var b=this.createElementDefaultNS("Server"),c={service:"OGC:WMS",version:a.version};a.title&&(c.title=a.title);this.setAttributes(b,c);b.appendChild(this.write_wmc_OnlineResource(a.url));return b},write_wmc_URLType:function(a,b,c){a=this.createElementDefaultNS(a);a.appendChild(this.write_wmc_OnlineResource(b));if(c){b=["width","height","format"];for(var d=0;d<b.length;d++)b[d]in c&&a.setAttribute(b[d],c[b[d]])}return a},write_wmc_DimensionList:function(a){var b=
2556 this.createElementDefaultNS("DimensionList"),c;for(c in a.dimensions){var d={},e=a.dimensions[c],f;for(f in e)d[f]="boolean"==typeof e[f]?Number(e[f]):e[f];e="";d.values&&(e=d.values.join(","),delete d.values);b.appendChild(this.createElementDefaultNS("Dimension",e,d))}return b},write_wmc_FormatList:function(a){for(var b=this.createElementDefaultNS("FormatList"),c=0,d=a.formats.length;c<d;c++){var e=a.formats[c];b.appendChild(this.createElementDefaultNS("Format",e.value,e.current&&!0==e.current?{current:"1"}:
2557 null))}return b},write_wmc_StyleList:function(a){var b=this.createElementDefaultNS("StyleList");if((a=a.styles)&&OpenLayers.Util.isArray(a))for(var c,d=0,e=a.length;d<e;d++){var f=a[d],g=this.createElementDefaultNS("Style",null,f.current&&!0==f.current?{current:"1"}:null);f.href?(c=this.createElementDefaultNS("SLD"),f.name&&c.appendChild(this.createElementDefaultNS("Name",f.name)),f.title&&c.appendChild(this.createElementDefaultNS("Title",f.title)),f.legend&&c.appendChild(this.write_wmc_URLType("LegendURL",
2558 f.legend.href,f.legend)),f=this.write_wmc_OnlineResource(f.href),c.appendChild(f),g.appendChild(c)):f.body?(c=this.createElementDefaultNS("SLD"),f.name&&c.appendChild(this.createElementDefaultNS("Name",f.name)),f.title&&c.appendChild(this.createElementDefaultNS("Title",f.title)),f.legend&&c.appendChild(this.write_wmc_URLType("LegendURL",f.legend.href,f.legend)),f=OpenLayers.Format.XML.prototype.read.apply(this,[f.body]).documentElement,c.ownerDocument&&c.ownerDocument.importNode&&(f=c.ownerDocument.importNode(f,
2559 !0)),c.appendChild(f),g.appendChild(c)):(g.appendChild(this.createElementDefaultNS("Name",f.name)),g.appendChild(this.createElementDefaultNS("Title",f.title)),f["abstract"]&&g.appendChild(this.createElementDefaultNS("Abstract",f["abstract"])),f.legend&&g.appendChild(this.write_wmc_URLType("LegendURL",f.legend.href,f.legend)));b.appendChild(g)}return b},write_wmc_OnlineResource:function(a){var b=this.createElementDefaultNS("OnlineResource");this.setAttributeNS(b,this.namespaces.xlink,"xlink:type",
2560 "simple");this.setAttributeNS(b,this.namespaces.xlink,"xlink:href",a);return b},getOnlineResource_href:function(a){var b={};a=a.getElementsByTagName("OnlineResource");0<a.length&&this.read_wmc_OnlineResource(b,a[0]);return b.href},CLASS_NAME:"OpenLayers.Format.WMC.v1"});OpenLayers.Control.PanPanel=OpenLayers.Class(OpenLayers.Control.Panel,{slideFactor:50,slideRatio:null,initialize:function(a){OpenLayers.Control.Panel.prototype.initialize.apply(this,[a]);a={slideFactor:this.slideFactor,slideRatio:this.slideRatio};this.addControls([new OpenLayers.Control.Pan(OpenLayers.Control.Pan.NORTH,a),new OpenLayers.Control.Pan(OpenLayers.Control.Pan.SOUTH,a),new OpenLayers.Control.Pan(OpenLayers.Control.Pan.EAST,a),new OpenLayers.Control.Pan(OpenLayers.Control.Pan.WEST,a)])},
2561 CLASS_NAME:"OpenLayers.Control.PanPanel"});OpenLayers.Control.Attribution=OpenLayers.Class(OpenLayers.Control,{separator:", ",template:"${layers}",destroy:function(){this.map.events.un({removelayer:this.updateAttribution,addlayer:this.updateAttribution,changelayer:this.updateAttribution,changebaselayer:this.updateAttribution,scope:this});OpenLayers.Control.prototype.destroy.apply(this,arguments)},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);this.map.events.on({changebaselayer:this.updateAttribution,changelayer:this.updateAttribution,
2562 addlayer:this.updateAttribution,removelayer:this.updateAttribution,scope:this});this.updateAttribution();return this.div},updateAttribution:function(){var a=[];if(this.map&&this.map.layers){for(var b=0,c=this.map.layers.length;b<c;b++){var d=this.map.layers[b];d.attribution&&d.getVisibility()&&-1===OpenLayers.Util.indexOf(a,d.attribution)&&a.push(d.attribution)}this.div.innerHTML=OpenLayers.String.format(this.template,{layers:a.join(this.separator)})}},CLASS_NAME:"OpenLayers.Control.Attribution"});OpenLayers.Kinetic=OpenLayers.Class({threshold:0,deceleration:0.0035,nbPoints:100,delay:200,points:void 0,timerId:void 0,initialize:function(a){OpenLayers.Util.extend(this,a)},begin:function(){OpenLayers.Animation.stop(this.timerId);this.timerId=void 0;this.points=[]},update:function(a){this.points.unshift({xy:a,tick:(new Date).getTime()});this.points.length>this.nbPoints&&this.points.pop()},end:function(a){for(var b,c=(new Date).getTime(),d=0,e=this.points.length,f;d<e;d++){f=this.points[d];if(c-
2563 f.tick>this.delay)break;b=f}if(b&&(d=(new Date).getTime()-b.tick,c=Math.sqrt(Math.pow(a.x-b.xy.x,2)+Math.pow(a.y-b.xy.y,2)),d=c/d,!(0==d||d<this.threshold)))return c=Math.asin((a.y-b.xy.y)/c),b.xy.x<=a.x&&(c=Math.PI-c),{speed:d,theta:c}},move:function(a,b){var c=a.speed,d=Math.cos(a.theta),e=-Math.sin(a.theta),f=(new Date).getTime(),g=0,h=0;this.timerId=OpenLayers.Animation.start(OpenLayers.Function.bind(function(){if(null!=this.timerId){var a=(new Date).getTime()-f,l=-this.deceleration*Math.pow(a,
2564 2)/2+c*a,m=l*d,l=l*e,n,p;n=!1;0>=-this.deceleration*a+c&&(OpenLayers.Animation.stop(this.timerId),this.timerId=null,n=!0);a=m-g;p=l-h;g=m;h=l;b(a,p,n)}},this))},CLASS_NAME:"OpenLayers.Kinetic"});OpenLayers.Format.WPSExecute=OpenLayers.Class(OpenLayers.Format.XML,OpenLayers.Format.Filter.v1_1_0,{namespaces:{ows:"http://www.opengis.net/ows/1.1",gml:"http://www.opengis.net/gml",wps:"http://www.opengis.net/wps/1.0.0",wfs:"http://www.opengis.net/wfs",ogc:"http://www.opengis.net/ogc",wcs:"http://www.opengis.net/wcs",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance"},regExes:{trimSpace:/^\s*|\s*$/g,removeSpace:/\s*/g,splitSpace:/\s+/,trimComma:/\s*,\s*/g},VERSION:"1.0.0",
2565 schemaLocation:"http://www.opengis.net/wps/1.0.0 http://schemas.opengis.net/wps/1.0.0/wpsAll.xsd",schemaLocationAttr:function(a){},write:function(a){var b;window.ActiveXObject?this.xmldom=b=new ActiveXObject("Microsoft.XMLDOM"):b=document.implementation.createDocument("","",null);a=this.writeNode("wps:Execute",a,b);this.setAttributeNS(a,this.namespaces.xsi,"xsi:schemaLocation",this.schemaLocation);return OpenLayers.Format.XML.prototype.write.apply(this,[a])},read:function(a){"string"==typeof a&&(a=
2566 OpenLayers.Format.XML.prototype.read.apply(this,[a]));a&&9==a.nodeType&&(a=a.documentElement);var b={};this.readNode(a,b);return b},writers:{wps:{Execute:function(a){var b=this.createElementNSPlus("wps:Execute",{attributes:{version:this.VERSION,service:"WPS"}});this.writeNode("ows:Identifier",a.identifier,b);this.writeNode("wps:DataInputs",a.dataInputs,b);this.writeNode("wps:ResponseForm",a.responseForm,b);return b},ResponseForm:function(a){var b=this.createElementNSPlus("wps:ResponseForm",{});a.rawDataOutput&&
2567 this.writeNode("wps:RawDataOutput",a.rawDataOutput,b);a.responseDocument&&this.writeNode("wps:ResponseDocument",a.responseDocument,b);return b},ResponseDocument:function(a){var b=this.createElementNSPlus("wps:ResponseDocument",{attributes:{storeExecuteResponse:a.storeExecuteResponse,lineage:a.lineage,status:a.status}});if(a.outputs)for(var c=0,d=a.outputs.length;c<d;c++)this.writeNode("wps:Output",a.outputs[c],b);return b},Output:function(a){var b=this.createElementNSPlus("wps:Output",{attributes:{asReference:a.asReference,
2568 mimeType:a.mimeType,encoding:a.encoding,schema:a.schema}});this.writeNode("ows:Identifier",a.identifier,b);this.writeNode("ows:Title",a.title,b);this.writeNode("ows:Abstract",a["abstract"],b);return b},RawDataOutput:function(a){var b=this.createElementNSPlus("wps:RawDataOutput",{attributes:{mimeType:a.mimeType,encoding:a.encoding,schema:a.schema}});this.writeNode("ows:Identifier",a.identifier,b);return b},DataInputs:function(a){for(var b=this.createElementNSPlus("wps:DataInputs",{}),c=0,d=a.length;c<
2569 d;++c)this.writeNode("wps:Input",a[c],b);return b},Input:function(a){var b=this.createElementNSPlus("wps:Input",{});this.writeNode("ows:Identifier",a.identifier,b);a.title&&this.writeNode("ows:Title",a.title,b);a.data&&this.writeNode("wps:Data",a.data,b);a.reference&&this.writeNode("wps:Reference",a.reference,b);a.boundingBoxData&&this.writeNode("wps:BoundingBoxData",a.boundingBoxData,b);return b},Data:function(a){var b=this.createElementNSPlus("wps:Data",{});a.literalData?this.writeNode("wps:LiteralData",
2570 a.literalData,b):a.complexData?this.writeNode("wps:ComplexData",a.complexData,b):a.boundingBoxData&&this.writeNode("ows:BoundingBox",a.boundingBoxData,b);return b},LiteralData:function(a){return this.createElementNSPlus("wps:LiteralData",{attributes:{uom:a.uom},value:a.value})},ComplexData:function(a){var b=this.createElementNSPlus("wps:ComplexData",{attributes:{mimeType:a.mimeType,encoding:a.encoding,schema:a.schema}}),c=a.value;"string"===typeof c?b.appendChild(this.getXMLDoc().createCDATASection(a.value)):
2571 b.appendChild(c);return b},Reference:function(a){var b=this.createElementNSPlus("wps:Reference",{attributes:{mimeType:a.mimeType,"xlink:href":a.href,method:a.method,encoding:a.encoding,schema:a.schema}});a.body&&this.writeNode("wps:Body",a.body,b);return b},BoundingBoxData:function(a,b){this.writers.ows.BoundingBox.apply(this,[a,b,"wps:BoundingBoxData"])},Body:function(a){var b=this.createElementNSPlus("wps:Body",{});a.wcs?this.writeNode("wcs:GetCoverage",a.wcs,b):a.wfs?(this.featureType=a.wfs.featureType,
2572 this.version=a.wfs.version,this.writeNode("wfs:GetFeature",a.wfs,b)):this.writeNode("wps:Execute",a,b);return b}},wcs:OpenLayers.Format.WCSGetCoverage.prototype.writers.wcs,wfs:OpenLayers.Format.WFST.v1_1_0.prototype.writers.wfs,ogc:OpenLayers.Format.Filter.v1_1_0.prototype.writers.ogc,ows:OpenLayers.Format.OWSCommon.v1_1_0.prototype.writers.ows},readers:{wps:{ExecuteResponse:function(a,b){b.executeResponse={lang:a.getAttribute("lang"),statusLocation:a.getAttribute("statusLocation"),serviceInstance:a.getAttribute("serviceInstance"),
2573 service:a.getAttribute("service")};this.readChildNodes(a,b.executeResponse)},Process:function(a,b){b.process={};this.readChildNodes(a,b.process)},Status:function(a,b){b.status={creationTime:a.getAttribute("creationTime")};this.readChildNodes(a,b.status)},ProcessSucceeded:function(a,b){b.processSucceeded=!0},ProcessOutputs:function(a,b){b.processOutputs=[];this.readChildNodes(a,b.processOutputs)},Output:function(a,b){var c={};this.readChildNodes(a,c);b.push(c)},Reference:function(a,b){b.reference=
2574 {href:a.getAttribute("href"),mimeType:a.getAttribute("mimeType"),encoding:a.getAttribute("encoding"),schema:a.getAttribute("schema")}},Data:function(a,b){b.data={};this.readChildNodes(a,b)},LiteralData:function(a,b){b.literalData={dataType:a.getAttribute("dataType"),uom:a.getAttribute("uom"),value:this.getChildValue(a)}},ComplexData:function(a,b){b.complexData={mimeType:a.getAttribute("mimeType"),schema:a.getAttribute("schema"),encoding:a.getAttribute("encoding"),value:""};if(this.isSimpleContent(a)){var c;
2575 for(c=a.firstChild;c;c=c.nextSibling)switch(c.nodeType){case 3:case 4:b.complexData.value+=c.nodeValue}}else for(c=a.firstChild;c;c=c.nextSibling)1==c.nodeType&&(b.complexData.value=c)},BoundingBox:function(a,b){b.boundingBoxData={dimensions:a.getAttribute("dimensions"),crs:a.getAttribute("crs")};this.readChildNodes(a,b.boundingBoxData)}},ows:OpenLayers.Format.OWSCommon.v1_1_0.prototype.readers.ows},CLASS_NAME:"OpenLayers.Format.WPSExecute"});OpenLayers.Layer.GeoRSS=OpenLayers.Class(OpenLayers.Layer.Markers,{location:null,features:null,formatOptions:null,selectedFeature:null,icon:null,popupSize:null,useFeedTitle:!0,initialize:function(a,b,c){OpenLayers.Layer.Markers.prototype.initialize.apply(this,[a,c]);this.location=b;this.features=[]},destroy:function(){OpenLayers.Layer.Markers.prototype.destroy.apply(this,arguments);this.clearFeatures();this.features=null},loadRSS:function(){this.loaded||(this.events.triggerEvent("loadstart"),OpenLayers.Request.GET({url:this.location,
2576 success:this.parseData,scope:this}),this.loaded=!0)},moveTo:function(a,b,c){OpenLayers.Layer.Markers.prototype.moveTo.apply(this,arguments);this.visibility&&!this.loaded&&this.loadRSS()},parseData:function(a){var b=a.responseXML;b&&b.documentElement||(b=OpenLayers.Format.XML.prototype.read(a.responseText));if(this.useFeedTitle){a=null;try{a=b.getElementsByTagNameNS("*","title")[0].firstChild.nodeValue}catch(c){a=b.getElementsByTagName("title")[0].firstChild.nodeValue}a&&this.setName(a)}a={};OpenLayers.Util.extend(a,
2577 this.formatOptions);this.map&&!this.projection.equals(this.map.getProjectionObject())&&(a.externalProjection=this.projection,a.internalProjection=this.map.getProjectionObject());b=(new OpenLayers.Format.GeoRSS(a)).read(b);a=0;for(var d=b.length;a<d;a++){var e={},f=b[a];if(f.geometry){var g=f.attributes.title?f.attributes.title:"Untitled",h=f.attributes.description?f.attributes.description:"No description.",k=f.attributes.link?f.attributes.link:"",f=f.geometry.getBounds().getCenterLonLat();e.icon=
2578 null==this.icon?OpenLayers.Marker.defaultIcon():this.icon.clone();e.popupSize=this.popupSize?this.popupSize.clone():new OpenLayers.Size(250,120);if(g||h){e.title=g;e.description=h;var l='<div class="olLayerGeoRSSClose">[x]</div>',l=l+'<div class="olLayerGeoRSSTitle">';k&&(l+='<a class="link" href="'+k+'" target="_blank">');l+=g;k&&(l+="</a>");l+="</div>";l+='<div style="" class="olLayerGeoRSSDescription">';l+=h;l+="</div>";e.popupContentHTML=l}f=new OpenLayers.Feature(this,f,e);this.features.push(f);
2579 e=f.createMarker();e.events.register("click",f,this.markerClick);this.addMarker(e)}}this.events.triggerEvent("loadend")},markerClick:function(a){var b=this==this.layer.selectedFeature;this.layer.selectedFeature=b?null:this;for(var c=0,d=this.layer.map.popups.length;c<d;c++)this.layer.map.removePopup(this.layer.map.popups[c]);b||(b=this.createPopup(),OpenLayers.Event.observe(b.div,"click",OpenLayers.Function.bind(function(){for(var a=0,b=this.layer.map.popups.length;a<b;a++)this.layer.map.removePopup(this.layer.map.popups[a])},
2580 this)),this.layer.map.addPopup(b));OpenLayers.Event.stop(a)},clearFeatures:function(){if(null!=this.features)for(;0<this.features.length;){var a=this.features[0];OpenLayers.Util.removeItem(this.features,a);a.destroy()}},CLASS_NAME:"OpenLayers.Layer.GeoRSS"});OpenLayers.Symbolizer.Point=OpenLayers.Class(OpenLayers.Symbolizer,{initialize:function(a){OpenLayers.Symbolizer.prototype.initialize.apply(this,arguments)},CLASS_NAME:"OpenLayers.Symbolizer.Point"});OpenLayers.Symbolizer.Line=OpenLayers.Class(OpenLayers.Symbolizer,{initialize:function(a){OpenLayers.Symbolizer.prototype.initialize.apply(this,arguments)},CLASS_NAME:"OpenLayers.Symbolizer.Line"});OpenLayers.Symbolizer.Text=OpenLayers.Class(OpenLayers.Symbolizer,{initialize:function(a){OpenLayers.Symbolizer.prototype.initialize.apply(this,arguments)},CLASS_NAME:"OpenLayers.Symbolizer.Text"});OpenLayers.Format.SLD.v1=OpenLayers.Class(OpenLayers.Format.Filter.v1_0_0,{namespaces:{sld:"http://www.opengis.net/sld",ogc:"http://www.opengis.net/ogc",gml:"http://www.opengis.net/gml",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance"},defaultPrefix:"sld",schemaLocation:null,multipleSymbolizers:!1,featureTypeCounter:null,defaultSymbolizer:{fillColor:"#808080",fillOpacity:1,strokeColor:"#000000",strokeOpacity:1,strokeWidth:1,strokeDashstyle:"solid",pointRadius:3,
2581 graphicName:"square"},read:function(a,b){b=OpenLayers.Util.applyDefaults(b,this.options);var c={namedLayers:!0===b.namedLayersAsArray?[]:{}};this.readChildNodes(a,c);return c},readers:OpenLayers.Util.applyDefaults({sld:{StyledLayerDescriptor:function(a,b){b.version=a.getAttribute("version");this.readChildNodes(a,b)},Name:function(a,b){b.name=this.getChildValue(a)},Title:function(a,b){b.title=this.getChildValue(a)},Abstract:function(a,b){b.description=this.getChildValue(a)},NamedLayer:function(a,b){var c=
2582 {userStyles:[],namedStyles:[]};this.readChildNodes(a,c);for(var d=0,e=c.userStyles.length;d<e;++d)c.userStyles[d].layerName=c.name;OpenLayers.Util.isArray(b.namedLayers)?b.namedLayers.push(c):b.namedLayers[c.name]=c},NamedStyle:function(a,b){b.namedStyles.push(this.getChildName(a.firstChild))},UserStyle:function(a,b){var c={defaultsPerSymbolizer:!0,rules:[]};this.featureTypeCounter=-1;this.readChildNodes(a,c);this.multipleSymbolizers?(delete c.defaultsPerSymbolizer,c=new OpenLayers.Style2(c)):c=new OpenLayers.Style(this.defaultSymbolizer,
2583 c);b.userStyles.push(c)},IsDefault:function(a,b){"1"==this.getChildValue(a)&&(b.isDefault=!0)},FeatureTypeStyle:function(a,b){++this.featureTypeCounter;var c={rules:this.multipleSymbolizers?b.rules:[]};this.readChildNodes(a,c);this.multipleSymbolizers||(b.rules=c.rules)},Rule:function(a,b){var c;this.multipleSymbolizers&&(c={symbolizers:[]});c=new OpenLayers.Rule(c);this.readChildNodes(a,c);b.rules.push(c)},ElseFilter:function(a,b){b.elseFilter=!0},MinScaleDenominator:function(a,b){b.minScaleDenominator=
2584 parseFloat(this.getChildValue(a))},MaxScaleDenominator:function(a,b){b.maxScaleDenominator=parseFloat(this.getChildValue(a))},TextSymbolizer:function(a,b){var c={};this.readChildNodes(a,c);this.multipleSymbolizers?(c.zIndex=this.featureTypeCounter,b.symbolizers.push(new OpenLayers.Symbolizer.Text(c))):b.symbolizer.Text=OpenLayers.Util.applyDefaults(c,b.symbolizer.Text)},LabelPlacement:function(a,b){this.readChildNodes(a,b)},PointPlacement:function(a,b){var c={};this.readChildNodes(a,c);c.labelRotation=
2585 c.rotation;delete c.rotation;var d,e=b.labelAnchorPointX,f=b.labelAnchorPointY;e<=1/3?d="l":e>1/3&&e<2/3?d="c":e>=2/3&&(d="r");f<=1/3?d+="b":f>1/3&&f<2/3?d+="m":f>=2/3&&(d+="t");c.labelAlign=d;OpenLayers.Util.applyDefaults(b,c)},AnchorPoint:function(a,b){this.readChildNodes(a,b)},AnchorPointX:function(a,b){var c=this.readers.ogc._expression.call(this,a);c&&(b.labelAnchorPointX=c)},AnchorPointY:function(a,b){var c=this.readers.ogc._expression.call(this,a);c&&(b.labelAnchorPointY=c)},Displacement:function(a,
2586 b){this.readChildNodes(a,b)},DisplacementX:function(a,b){var c=this.readers.ogc._expression.call(this,a);c&&(b.labelXOffset=c)},DisplacementY:function(a,b){var c=this.readers.ogc._expression.call(this,a);c&&(b.labelYOffset=c)},LinePlacement:function(a,b){this.readChildNodes(a,b)},PerpendicularOffset:function(a,b){var c=this.readers.ogc._expression.call(this,a);c&&(b.labelPerpendicularOffset=c)},Label:function(a,b){var c=this.readers.ogc._expression.call(this,a);c&&(b.label=c)},Font:function(a,b){this.readChildNodes(a,
2587 b)},Halo:function(a,b){var c={};this.readChildNodes(a,c);b.haloRadius=c.haloRadius;b.haloColor=c.fillColor;b.haloOpacity=c.fillOpacity},Radius:function(a,b){var c=this.readers.ogc._expression.call(this,a);null!=c&&(b.haloRadius=c)},RasterSymbolizer:function(a,b){var c={};this.readChildNodes(a,c);this.multipleSymbolizers?(c.zIndex=this.featureTypeCounter,b.symbolizers.push(new OpenLayers.Symbolizer.Raster(c))):b.symbolizer.Raster=OpenLayers.Util.applyDefaults(c,b.symbolizer.Raster)},Geometry:function(a,
2588 b){b.geometry={};this.readChildNodes(a,b.geometry)},ColorMap:function(a,b){b.colorMap=[];this.readChildNodes(a,b.colorMap)},ColorMapEntry:function(a,b){var c=a.getAttribute("quantity"),d=a.getAttribute("opacity");b.push({color:a.getAttribute("color"),quantity:null!==c?parseFloat(c):void 0,label:a.getAttribute("label")||void 0,opacity:null!==d?parseFloat(d):void 0})},LineSymbolizer:function(a,b){var c={};this.readChildNodes(a,c);this.multipleSymbolizers?(c.zIndex=this.featureTypeCounter,b.symbolizers.push(new OpenLayers.Symbolizer.Line(c))):
2589 b.symbolizer.Line=OpenLayers.Util.applyDefaults(c,b.symbolizer.Line)},PolygonSymbolizer:function(a,b){var c={fill:!1,stroke:!1};this.multipleSymbolizers||(c=b.symbolizer.Polygon||c);this.readChildNodes(a,c);this.multipleSymbolizers?(c.zIndex=this.featureTypeCounter,b.symbolizers.push(new OpenLayers.Symbolizer.Polygon(c))):b.symbolizer.Polygon=c},PointSymbolizer:function(a,b){var c={fill:!1,stroke:!1,graphic:!1};this.multipleSymbolizers||(c=b.symbolizer.Point||c);this.readChildNodes(a,c);this.multipleSymbolizers?
2590 (c.zIndex=this.featureTypeCounter,b.symbolizers.push(new OpenLayers.Symbolizer.Point(c))):b.symbolizer.Point=c},Stroke:function(a,b){b.stroke=!0;this.readChildNodes(a,b)},Fill:function(a,b){b.fill=!0;this.readChildNodes(a,b)},CssParameter:function(a,b){var c=a.getAttribute("name"),d=this.cssMap[c];b.label&&("fill"===c?d="fontColor":"fill-opacity"===c&&(d="fontOpacity"));d&&(c=this.readers.ogc._expression.call(this,a))&&(b[d]=c)},Graphic:function(a,b){b.graphic=!0;var c={};this.readChildNodes(a,c);
2591 for(var d="stroke strokeColor strokeWidth strokeOpacity strokeLinecap fill fillColor fillOpacity graphicName rotation graphicFormat".split(" "),e,f,g=0,h=d.length;g<h;++g)e=d[g],f=c[e],void 0!=f&&(b[e]=f);void 0!=c.opacity&&(b.graphicOpacity=c.opacity);void 0!=c.size&&(isNaN(c.size/2)?b.graphicWidth=c.size:b.pointRadius=c.size/2);void 0!=c.href&&(b.externalGraphic=c.href);void 0!=c.rotation&&(b.rotation=c.rotation)},ExternalGraphic:function(a,b){this.readChildNodes(a,b)},Mark:function(a,b){this.readChildNodes(a,
2592 b)},WellKnownName:function(a,b){b.graphicName=this.getChildValue(a)},Opacity:function(a,b){var c=this.readers.ogc._expression.call(this,a);c&&(b.opacity=c)},Size:function(a,b){var c=this.readers.ogc._expression.call(this,a);c&&(b.size=c)},Rotation:function(a,b){var c=this.readers.ogc._expression.call(this,a);c&&(b.rotation=c)},OnlineResource:function(a,b){b.href=this.getAttributeNS(a,this.namespaces.xlink,"href")},Format:function(a,b){b.graphicFormat=this.getChildValue(a)}}},OpenLayers.Format.Filter.v1_0_0.prototype.readers),
2593 cssMap:{stroke:"strokeColor","stroke-opacity":"strokeOpacity","stroke-width":"strokeWidth","stroke-linecap":"strokeLinecap","stroke-dasharray":"strokeDashstyle",fill:"fillColor","fill-opacity":"fillOpacity","font-family":"fontFamily","font-size":"fontSize","font-weight":"fontWeight","font-style":"fontStyle"},getCssProperty:function(a){var b=null,c;for(c in this.cssMap)if(this.cssMap[c]==a){b=c;break}return b},getGraphicFormat:function(a){var b,c;for(c in this.graphicFormats)if(this.graphicFormats[c].test(a)){b=
2594 c;break}return b||this.defaultGraphicFormat},defaultGraphicFormat:"image/png",graphicFormats:{"image/jpeg":/\.jpe?g$/i,"image/gif":/\.gif$/i,"image/png":/\.png$/i},write:function(a){return this.writers.sld.StyledLayerDescriptor.apply(this,[a])},writers:OpenLayers.Util.applyDefaults({sld:{_OGCExpression:function(a,b){var c=this.createElementNSPlus(a),d="string"==typeof b?b.split("${"):[b];c.appendChild(this.createTextNode(d[0]));for(var e,f,g=1,h=d.length;g<h;g++)e=d[g],f=e.indexOf("}"),0<f?(this.writeNode("ogc:PropertyName",
2595 {property:e.substring(0,f)},c),c.appendChild(this.createTextNode(e.substring(++f)))):c.appendChild(this.createTextNode("${"+e));return c},StyledLayerDescriptor:function(a){var b=this.createElementNSPlus("sld:StyledLayerDescriptor",{attributes:{version:this.VERSION,"xsi:schemaLocation":this.schemaLocation}});b.setAttribute("xmlns:ogc",this.namespaces.ogc);b.setAttribute("xmlns:gml",this.namespaces.gml);a.name&&this.writeNode("Name",a.name,b);a.title&&this.writeNode("Title",a.title,b);a.description&&
2596 this.writeNode("Abstract",a.description,b);if(OpenLayers.Util.isArray(a.namedLayers))for(var c=0,d=a.namedLayers.length;c<d;++c)this.writeNode("NamedLayer",a.namedLayers[c],b);else for(c in a.namedLayers)this.writeNode("NamedLayer",a.namedLayers[c],b);return b},Name:function(a){return this.createElementNSPlus("sld:Name",{value:a})},Title:function(a){return this.createElementNSPlus("sld:Title",{value:a})},Abstract:function(a){return this.createElementNSPlus("sld:Abstract",{value:a})},NamedLayer:function(a){var b=
2597 this.createElementNSPlus("sld:NamedLayer");this.writeNode("Name",a.name,b);if(a.namedStyles)for(var c=0,d=a.namedStyles.length;c<d;++c)this.writeNode("NamedStyle",a.namedStyles[c],b);if(a.userStyles)for(c=0,d=a.userStyles.length;c<d;++c)this.writeNode("UserStyle",a.userStyles[c],b);return b},NamedStyle:function(a){var b=this.createElementNSPlus("sld:NamedStyle");this.writeNode("Name",a,b);return b},UserStyle:function(a){var b=this.createElementNSPlus("sld:UserStyle");a.name&&this.writeNode("Name",
2598 a.name,b);a.title&&this.writeNode("Title",a.title,b);a.description&&this.writeNode("Abstract",a.description,b);a.isDefault&&this.writeNode("IsDefault",a.isDefault,b);if(this.multipleSymbolizers&&a.rules){for(var c={0:[]},d=[0],e,f,g,h,k,l=0,m=a.rules.length;l<m;++l)if(e=a.rules[l],e.symbolizers){f={};for(var n=0,p=e.symbolizers.length;n<p;++n)g=e.symbolizers[n],h=g.zIndex,h in f||(k=e.clone(),k.symbolizers=[],f[h]=k),f[h].symbolizers.push(g.clone());for(h in f)h in c||(d.push(h),c[h]=[]),c[h].push(f[h])}else c[0].push(e.clone());
2599 d.sort();l=0;for(m=d.length;l<m;++l)e=c[d[l]],0<e.length&&(k=a.clone(),k.rules=c[d[l]],this.writeNode("FeatureTypeStyle",k,b))}else this.writeNode("FeatureTypeStyle",a,b);return b},IsDefault:function(a){return this.createElementNSPlus("sld:IsDefault",{value:a?"1":"0"})},FeatureTypeStyle:function(a){for(var b=this.createElementNSPlus("sld:FeatureTypeStyle"),c=0,d=a.rules.length;c<d;++c)this.writeNode("Rule",a.rules[c],b);return b},Rule:function(a){var b=this.createElementNSPlus("sld:Rule");a.name&&
2600 this.writeNode("Name",a.name,b);a.title&&this.writeNode("Title",a.title,b);a.description&&this.writeNode("Abstract",a.description,b);a.elseFilter?this.writeNode("ElseFilter",null,b):a.filter&&this.writeNode("ogc:Filter",a.filter,b);void 0!=a.minScaleDenominator&&this.writeNode("MinScaleDenominator",a.minScaleDenominator,b);void 0!=a.maxScaleDenominator&&this.writeNode("MaxScaleDenominator",a.maxScaleDenominator,b);var c,d;if(this.multipleSymbolizers&&a.symbolizers)for(var e=0,f=a.symbolizers.length;e<
2601 f;++e)d=a.symbolizers[e],c=d.CLASS_NAME.split(".").pop(),this.writeNode(c+"Symbolizer",d,b);else for(var f=OpenLayers.Style.SYMBOLIZER_PREFIXES,e=0,g=f.length;e<g;++e)c=f[e],(d=a.symbolizer[c])&&this.writeNode(c+"Symbolizer",d,b);return b},ElseFilter:function(){return this.createElementNSPlus("sld:ElseFilter")},MinScaleDenominator:function(a){return this.createElementNSPlus("sld:MinScaleDenominator",{value:a})},MaxScaleDenominator:function(a){return this.createElementNSPlus("sld:MaxScaleDenominator",
2602 {value:a})},LineSymbolizer:function(a){var b=this.createElementNSPlus("sld:LineSymbolizer");this.writeNode("Stroke",a,b);return b},Stroke:function(a){var b=this.createElementNSPlus("sld:Stroke");void 0!=a.strokeColor&&this.writeNode("CssParameter",{symbolizer:a,key:"strokeColor"},b);void 0!=a.strokeOpacity&&this.writeNode("CssParameter",{symbolizer:a,key:"strokeOpacity"},b);void 0!=a.strokeWidth&&this.writeNode("CssParameter",{symbolizer:a,key:"strokeWidth"},b);void 0!=a.strokeDashstyle&&"solid"!==
2603 a.strokeDashstyle&&this.writeNode("CssParameter",{symbolizer:a,key:"strokeDashstyle"},b);void 0!=a.strokeLinecap&&this.writeNode("CssParameter",{symbolizer:a,key:"strokeLinecap"},b);return b},CssParameter:function(a){return this.createElementNSPlus("sld:CssParameter",{attributes:{name:this.getCssProperty(a.key)},value:a.symbolizer[a.key]})},TextSymbolizer:function(a){var b=this.createElementNSPlus("sld:TextSymbolizer");null!=a.label&&this.writeNode("Label",a.label,b);null==a.fontFamily&&null==a.fontSize&&
2604 null==a.fontWeight&&null==a.fontStyle||this.writeNode("Font",a,b);null==a.labelAnchorPointX&&null==a.labelAnchorPointY&&null==a.labelAlign&&null==a.labelXOffset&&null==a.labelYOffset&&null==a.labelRotation&&null==a.labelPerpendicularOffset||this.writeNode("LabelPlacement",a,b);null==a.haloRadius&&null==a.haloColor&&null==a.haloOpacity||this.writeNode("Halo",a,b);null==a.fontColor&&null==a.fontOpacity||this.writeNode("Fill",{fillColor:a.fontColor,fillOpacity:a.fontOpacity},b);return b},LabelPlacement:function(a){var b=
2605 this.createElementNSPlus("sld:LabelPlacement");null==a.labelAnchorPointX&&null==a.labelAnchorPointY&&null==a.labelAlign&&null==a.labelXOffset&&null==a.labelYOffset&&null==a.labelRotation||null!=a.labelPerpendicularOffset||this.writeNode("PointPlacement",a,b);null!=a.labelPerpendicularOffset&&this.writeNode("LinePlacement",a,b);return b},LinePlacement:function(a){var b=this.createElementNSPlus("sld:LinePlacement");this.writeNode("PerpendicularOffset",a.labelPerpendicularOffset,b);return b},PerpendicularOffset:function(a){return this.createElementNSPlus("sld:PerpendicularOffset",
2606 {value:a})},PointPlacement:function(a){var b=this.createElementNSPlus("sld:PointPlacement");null==a.labelAnchorPointX&&null==a.labelAnchorPointY&&null==a.labelAlign||this.writeNode("AnchorPoint",a,b);null==a.labelXOffset&&null==a.labelYOffset||this.writeNode("Displacement",a,b);null!=a.labelRotation&&this.writeNode("Rotation",a.labelRotation,b);return b},AnchorPoint:function(a){var b=this.createElementNSPlus("sld:AnchorPoint"),c=a.labelAnchorPointX,d=a.labelAnchorPointY;null!=c&&this.writeNode("AnchorPointX",
2607 c,b);null!=d&&this.writeNode("AnchorPointY",d,b);if(null==c&&null==d){var e=a.labelAlign.substr(0,1);a=a.labelAlign.substr(1,1);"l"===e?c=0:"c"===e?c=0.5:"r"===e&&(c=1);"b"===a?d=0:"m"===a?d=0.5:"t"===a&&(d=1);this.writeNode("AnchorPointX",c,b);this.writeNode("AnchorPointY",d,b)}return b},AnchorPointX:function(a){return this.createElementNSPlus("sld:AnchorPointX",{value:a})},AnchorPointY:function(a){return this.createElementNSPlus("sld:AnchorPointY",{value:a})},Displacement:function(a){var b=this.createElementNSPlus("sld:Displacement");
2608 null!=a.labelXOffset&&this.writeNode("DisplacementX",a.labelXOffset,b);null!=a.labelYOffset&&this.writeNode("DisplacementY",a.labelYOffset,b);return b},DisplacementX:function(a){return this.createElementNSPlus("sld:DisplacementX",{value:a})},DisplacementY:function(a){return this.createElementNSPlus("sld:DisplacementY",{value:a})},Font:function(a){var b=this.createElementNSPlus("sld:Font");a.fontFamily&&this.writeNode("CssParameter",{symbolizer:a,key:"fontFamily"},b);a.fontSize&&this.writeNode("CssParameter",
2609 {symbolizer:a,key:"fontSize"},b);a.fontWeight&&this.writeNode("CssParameter",{symbolizer:a,key:"fontWeight"},b);a.fontStyle&&this.writeNode("CssParameter",{symbolizer:a,key:"fontStyle"},b);return b},Label:function(a){return this.writers.sld._OGCExpression.call(this,"sld:Label",a)},Halo:function(a){var b=this.createElementNSPlus("sld:Halo");a.haloRadius&&this.writeNode("Radius",a.haloRadius,b);(a.haloColor||a.haloOpacity)&&this.writeNode("Fill",{fillColor:a.haloColor,fillOpacity:a.haloOpacity},b);
2610 return b},Radius:function(a){return this.createElementNSPlus("sld:Radius",{value:a})},RasterSymbolizer:function(a){var b=this.createElementNSPlus("sld:RasterSymbolizer");a.geometry&&this.writeNode("Geometry",a.geometry,b);a.opacity&&this.writeNode("Opacity",a.opacity,b);a.colorMap&&this.writeNode("ColorMap",a.colorMap,b);return b},Geometry:function(a){var b=this.createElementNSPlus("sld:Geometry");a.property&&this.writeNode("ogc:PropertyName",a,b);return b},ColorMap:function(a){for(var b=this.createElementNSPlus("sld:ColorMap"),
2611 c=0,d=a.length;c<d;++c)this.writeNode("ColorMapEntry",a[c],b);return b},ColorMapEntry:function(a){var b=this.createElementNSPlus("sld:ColorMapEntry");b.setAttribute("color",a.color);void 0!==a.opacity&&b.setAttribute("opacity",parseFloat(a.opacity));void 0!==a.quantity&&b.setAttribute("quantity",parseFloat(a.quantity));void 0!==a.label&&b.setAttribute("label",a.label);return b},PolygonSymbolizer:function(a){var b=this.createElementNSPlus("sld:PolygonSymbolizer");!1!==a.fill&&this.writeNode("Fill",
2612 a,b);!1!==a.stroke&&this.writeNode("Stroke",a,b);return b},Fill:function(a){var b=this.createElementNSPlus("sld:Fill");a.fillColor&&this.writeNode("CssParameter",{symbolizer:a,key:"fillColor"},b);null!=a.fillOpacity&&this.writeNode("CssParameter",{symbolizer:a,key:"fillOpacity"},b);return b},PointSymbolizer:function(a){var b=this.createElementNSPlus("sld:PointSymbolizer");this.writeNode("Graphic",a,b);return b},Graphic:function(a){var b=this.createElementNSPlus("sld:Graphic");void 0!=a.externalGraphic?
2613 this.writeNode("ExternalGraphic",a,b):this.writeNode("Mark",a,b);void 0!=a.graphicOpacity&&this.writeNode("Opacity",a.graphicOpacity,b);void 0!=a.pointRadius?this.writeNode("Size",2*a.pointRadius,b):void 0!=a.graphicWidth&&this.writeNode("Size",a.graphicWidth,b);void 0!=a.rotation&&this.writeNode("Rotation",a.rotation,b);return b},ExternalGraphic:function(a){var b=this.createElementNSPlus("sld:ExternalGraphic");this.writeNode("OnlineResource",a.externalGraphic,b);a=a.graphicFormat||this.getGraphicFormat(a.externalGraphic);
2614 this.writeNode("Format",a,b);return b},Mark:function(a){var b=this.createElementNSPlus("sld:Mark");a.graphicName&&this.writeNode("WellKnownName",a.graphicName,b);!1!==a.fill&&this.writeNode("Fill",a,b);!1!==a.stroke&&this.writeNode("Stroke",a,b);return b},WellKnownName:function(a){return this.createElementNSPlus("sld:WellKnownName",{value:a})},Opacity:function(a){return this.createElementNSPlus("sld:Opacity",{value:a})},Size:function(a){return this.writers.sld._OGCExpression.call(this,"sld:Size",
2615 a)},Rotation:function(a){return this.createElementNSPlus("sld:Rotation",{value:a})},OnlineResource:function(a){return this.createElementNSPlus("sld:OnlineResource",{attributes:{"xlink:type":"simple","xlink:href":a}})},Format:function(a){return this.createElementNSPlus("sld:Format",{value:a})}}},OpenLayers.Format.Filter.v1_0_0.prototype.writers),CLASS_NAME:"OpenLayers.Format.SLD.v1"});OpenLayers.Layer.WMS=OpenLayers.Class(OpenLayers.Layer.Grid,{DEFAULT_PARAMS:{service:"WMS",version:"1.1.1",request:"GetMap",styles:"",format:"image/jpeg"},isBaseLayer:!0,encodeBBOX:!1,noMagic:!1,yx:{},initialize:function(a,b,c,d){var e=[];c=OpenLayers.Util.upperCaseObject(c);1.3<=parseFloat(c.VERSION)&&!c.EXCEPTIONS&&(c.EXCEPTIONS="INIMAGE");e.push(a,b,c,d);OpenLayers.Layer.Grid.prototype.initialize.apply(this,e);OpenLayers.Util.applyDefaults(this.params,OpenLayers.Util.upperCaseObject(this.DEFAULT_PARAMS));
2616 !this.noMagic&&(this.params.TRANSPARENT&&"true"==this.params.TRANSPARENT.toString().toLowerCase())&&(null!=d&&d.isBaseLayer||(this.isBaseLayer=!1),"image/jpeg"==this.params.FORMAT&&(this.params.FORMAT=OpenLayers.Util.alphaHack()?"image/gif":"image/png"))},clone:function(a){null==a&&(a=new OpenLayers.Layer.WMS(this.name,this.url,this.params,this.getOptions()));return a=OpenLayers.Layer.Grid.prototype.clone.apply(this,[a])},reverseAxisOrder:function(){var a=this.projection.getCode();return 1.3<=parseFloat(this.params.VERSION)&&
2617 !!(this.yx[a]||OpenLayers.Projection.defaults[a]&&OpenLayers.Projection.defaults[a].yx)},getURL:function(a){a=this.adjustBounds(a);var b=this.getImageSize(),c={},d=this.reverseAxisOrder();c.BBOX=this.encodeBBOX?a.toBBOX(null,d):a.toArray(d);c.WIDTH=b.w;c.HEIGHT=b.h;return this.getFullRequestString(c)},mergeNewParams:function(a){a=[OpenLayers.Util.upperCaseObject(a)];return OpenLayers.Layer.Grid.prototype.mergeNewParams.apply(this,a)},getFullRequestString:function(a,b){var c=this.map.getProjectionObject(),
2618 c=this.projection&&this.projection.equals(c)?this.projection.getCode():c.getCode(),c="none"==c?null:c;1.3<=parseFloat(this.params.VERSION)?this.params.CRS=c:this.params.SRS=c;"boolean"==typeof this.params.TRANSPARENT&&(a.TRANSPARENT=this.params.TRANSPARENT?"TRUE":"FALSE");return OpenLayers.Layer.Grid.prototype.getFullRequestString.apply(this,arguments)},CLASS_NAME:"OpenLayers.Layer.WMS"});OpenLayers.Layer.KaMap=OpenLayers.Class(OpenLayers.Layer.Grid,{isBaseLayer:!0,DEFAULT_PARAMS:{i:"jpeg",map:""},initialize:function(a,b,c,d){OpenLayers.Layer.Grid.prototype.initialize.apply(this,arguments);this.params=OpenLayers.Util.applyDefaults(this.params,this.DEFAULT_PARAMS)},getURL:function(a){a=this.adjustBounds(a);var b=this.map.getResolution(),c=Math.round(1E4*this.map.getScale())/1E4,d=Math.round(a.left/b);a=-Math.round(a.top/b);return this.getFullRequestString({t:a,l:d,s:c})},calculateGridLayout:function(a,
2619 b,c){b=c*this.tileSize.w;c*=this.tileSize.h;return{tilelon:b,tilelat:c,startcol:Math.floor(a.left/b)-this.buffer,startrow:Math.floor(a.top/c)+this.buffer}},getTileBoundsForGridIndex:function(a,b){this.getTileOrigin();var c=this.gridLayout,d=c.tilelon,e=c.tilelat,f=(c.startcol+b)*d,c=(c.startrow-a)*e;return new OpenLayers.Bounds(f,c,f+d,c+e)},clone:function(a){null==a&&(a=new OpenLayers.Layer.KaMap(this.name,this.url,this.params,this.getOptions()));a=OpenLayers.Layer.Grid.prototype.clone.apply(this,
2620 [a]);null!=this.tileSize&&(a.tileSize=this.tileSize.clone());a.grid=[];return a},getTileBounds:function(a){var b=this.getResolution(),c=b*this.tileSize.w,b=b*this.tileSize.h,d=this.getLonLatFromViewPortPx(a);a=c*Math.floor(d.lon/c);d=b*Math.floor(d.lat/b);return new OpenLayers.Bounds(a,d,a+c,d+b)},CLASS_NAME:"OpenLayers.Layer.KaMap"});OpenLayers.Format.WMC.v1_1_0=OpenLayers.Class(OpenLayers.Format.WMC.v1,{VERSION:"1.1.0",schemaLocation:"http://www.opengis.net/context http://schemas.opengis.net/context/1.1.0/context.xsd",initialize:function(a){OpenLayers.Format.WMC.v1.prototype.initialize.apply(this,[a])},read_sld_MinScaleDenominator:function(a,b){var c=parseFloat(this.getChildValue(b));0<c&&(a.maxScale=c)},read_sld_MaxScaleDenominator:function(a,b){a.minScale=parseFloat(this.getChildValue(b))},read_wmc_SRS:function(a,b){"srs"in
2621 a||(a.srs={});a.srs[this.getChildValue(b)]=!0},write_wmc_Layer:function(a){var b=OpenLayers.Format.WMC.v1.prototype.write_wmc_Layer.apply(this,[a]);if(a.maxScale){var c=this.createElementNS(this.namespaces.sld,"sld:MinScaleDenominator");c.appendChild(this.createTextNode(a.maxScale.toPrecision(16)));b.appendChild(c)}a.minScale&&(c=this.createElementNS(this.namespaces.sld,"sld:MaxScaleDenominator"),c.appendChild(this.createTextNode(a.minScale.toPrecision(16))),b.appendChild(c));if(a.srs)for(var d in a.srs)b.appendChild(this.createElementDefaultNS("SRS",
2622 d));b.appendChild(this.write_wmc_FormatList(a));b.appendChild(this.write_wmc_StyleList(a));a.dimensions&&b.appendChild(this.write_wmc_DimensionList(a));b.appendChild(this.write_wmc_LayerExtension(a));return b},CLASS_NAME:"OpenLayers.Format.WMC.v1_1_0"});OpenLayers.Format.XLS=OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC,{defaultVersion:"1.1.0",stringifyOutput:!0,CLASS_NAME:"OpenLayers.Format.XLS"});OpenLayers.Format.XLS.v1=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{xls:"http://www.opengis.net/xls",gml:"http://www.opengis.net/gml",xsi:"http://www.w3.org/2001/XMLSchema-instance"},regExes:{trimSpace:/^\s*|\s*$/g,removeSpace:/\s*/g,splitSpace:/\s+/,trimComma:/\s*,\s*/g},xy:!0,defaultPrefix:"xls",schemaLocation:null,read:function(a,b){OpenLayers.Util.applyDefaults(b,this.options);var c={};this.readChildNodes(a,c);return c},readers:{xls:{XLS:function(a,b){b.version=a.getAttribute("version");
2623 this.readChildNodes(a,b)},Response:function(a,b){this.readChildNodes(a,b)},GeocodeResponse:function(a,b){b.responseLists=[];this.readChildNodes(a,b)},GeocodeResponseList:function(a,b){var c={features:[],numberOfGeocodedAddresses:parseInt(a.getAttribute("numberOfGeocodedAddresses"))};b.responseLists.push(c);this.readChildNodes(a,c)},GeocodedAddress:function(a,b){var c=new OpenLayers.Feature.Vector;b.features.push(c);this.readChildNodes(a,c);c.geometry=c.components[0]},GeocodeMatchCode:function(a,b){b.attributes.matchCode=
2624 {accuracy:parseFloat(a.getAttribute("accuracy")),matchType:a.getAttribute("matchType")}},Address:function(a,b){var c={countryCode:a.getAttribute("countryCode"),addressee:a.getAttribute("addressee"),street:[],place:[]};b.attributes.address=c;this.readChildNodes(a,c)},freeFormAddress:function(a,b){b.freeFormAddress=this.getChildValue(a)},StreetAddress:function(a,b){this.readChildNodes(a,b)},Building:function(a,b){b.building={number:a.getAttribute("number"),subdivision:a.getAttribute("subdivision"),
2625 buildingName:a.getAttribute("buildingName")}},Street:function(a,b){b.street.push(this.getChildValue(a))},Place:function(a,b){b.place[a.getAttribute("type")]=this.getChildValue(a)},PostalCode:function(a,b){b.postalCode=this.getChildValue(a)}},gml:OpenLayers.Format.GML.v3.prototype.readers.gml},write:function(a){return this.writers.xls.XLS.apply(this,[a])},writers:{xls:{XLS:function(a){var b=this.createElementNSPlus("xls:XLS",{attributes:{version:this.VERSION,"xsi:schemaLocation":this.schemaLocation}});
2626 this.writeNode("RequestHeader",a.header,b);this.writeNode("Request",a,b);return b},RequestHeader:function(a){return this.createElementNSPlus("xls:RequestHeader")},Request:function(a){var b=this.createElementNSPlus("xls:Request",{attributes:{methodName:"GeocodeRequest",requestID:a.requestID||"",version:this.VERSION}});this.writeNode("GeocodeRequest",a.addresses,b);return b},GeocodeRequest:function(a){for(var b=this.createElementNSPlus("xls:GeocodeRequest"),c=0,d=a.length;c<d;c++)this.writeNode("Address",
2627 a[c],b);return b},Address:function(a){var b=this.createElementNSPlus("xls:Address",{attributes:{countryCode:a.countryCode}});a.freeFormAddress?this.writeNode("freeFormAddress",a.freeFormAddress,b):(a.street&&this.writeNode("StreetAddress",a,b),a.municipality&&this.writeNode("Municipality",a.municipality,b),a.countrySubdivision&&this.writeNode("CountrySubdivision",a.countrySubdivision,b),a.postalCode&&this.writeNode("PostalCode",a.postalCode,b));return b},freeFormAddress:function(a){return this.createElementNSPlus("freeFormAddress",
2628 {value:a})},StreetAddress:function(a){var b=this.createElementNSPlus("xls:StreetAddress");a.building&&this.writeNode(b,"Building",a.building);a=a.street;OpenLayers.Util.isArray(a)||(a=[a]);for(var c=0,d=a.length;c<d;c++)this.writeNode("Street",a[c],b);return b},Building:function(a){return this.createElementNSPlus("xls:Building",{attributes:{number:a.number,subdivision:a.subdivision,buildingName:a.buildingName}})},Street:function(a){return this.createElementNSPlus("xls:Street",{value:a})},Municipality:function(a){return this.createElementNSPlus("xls:Place",
2629 {attributes:{type:"Municipality"},value:a})},CountrySubdivision:function(a){return this.createElementNSPlus("xls:Place",{attributes:{type:"CountrySubdivision"},value:a})},PostalCode:function(a){return this.createElementNSPlus("xls:PostalCode",{value:a})}}},CLASS_NAME:"OpenLayers.Format.XLS.v1"});OpenLayers.Format.XLS.v1_1_0=OpenLayers.Class(OpenLayers.Format.XLS.v1,{VERSION:"1.1",schemaLocation:"http://www.opengis.net/xls http://schemas.opengis.net/ols/1.1.0/LocationUtilityService.xsd",CLASS_NAME:"OpenLayers.Format.XLS.v1_1_0"});OpenLayers.Format.XLS.v1_1=OpenLayers.Format.XLS.v1_1_0;OpenLayers.Renderer.SVG=OpenLayers.Class(OpenLayers.Renderer.Elements,{xmlns:"http://www.w3.org/2000/svg",xlinkns:"http://www.w3.org/1999/xlink",MAX_PIXEL:15E3,translationParameters:null,symbolMetrics:null,initialize:function(a){this.supported()&&(OpenLayers.Renderer.Elements.prototype.initialize.apply(this,arguments),this.translationParameters={x:0,y:0},this.symbolMetrics={})},supported:function(){return document.implementation&&(document.implementation.hasFeature("org.w3c.svg","1.0")||document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#SVG",
2630 "1.1")||document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1"))},inValidRange:function(a,b,c){a+=c?0:this.translationParameters.x;b+=c?0:this.translationParameters.y;return a>=-this.MAX_PIXEL&&a<=this.MAX_PIXEL&&b>=-this.MAX_PIXEL&&b<=this.MAX_PIXEL},setExtent:function(a,b){var c=OpenLayers.Renderer.Elements.prototype.setExtent.apply(this,arguments),d=this.getResolution(),e=-a.left/d,d=a.top/d;if(b)return this.left=e,this.top=d,this.rendererRoot.setAttributeNS(null,
2631 "viewBox","0 0 "+this.size.w+" "+this.size.h),this.translate(this.xOffset,0),!0;(e=this.translate(e-this.left+this.xOffset,d-this.top))||this.setExtent(a,!0);return c&&e},translate:function(a,b){if(this.inValidRange(a,b,!0)){var c="";if(a||b)c="translate("+a+","+b+")";this.root.setAttributeNS(null,"transform",c);this.translationParameters={x:a,y:b};return!0}return!1},setSize:function(a){OpenLayers.Renderer.prototype.setSize.apply(this,arguments);this.rendererRoot.setAttributeNS(null,"width",this.size.w);
2632 this.rendererRoot.setAttributeNS(null,"height",this.size.h)},getNodeType:function(a,b){var c=null;switch(a.CLASS_NAME){case "OpenLayers.Geometry.Point":c=b.externalGraphic?"image":this.isComplexSymbol(b.graphicName)?"svg":"circle";break;case "OpenLayers.Geometry.Rectangle":c="rect";break;case "OpenLayers.Geometry.LineString":c="polyline";break;case "OpenLayers.Geometry.LinearRing":c="polygon";break;case "OpenLayers.Geometry.Polygon":case "OpenLayers.Geometry.Curve":c="path"}return c},setStyle:function(a,
2633 b,c){b=b||a._style;c=c||a._options;var d=b.title||b.graphicTitle;if(d){a.setAttributeNS(null,"title",d);var e=a.getElementsByTagName("title");0<e.length?e[0].firstChild.textContent=d:(e=this.nodeFactory(null,"title"),e.textContent=d,a.appendChild(e))}var e=parseFloat(a.getAttributeNS(null,"r")),d=1,f;if("OpenLayers.Geometry.Point"==a._geometryClass&&e){a.style.visibility="";if(!1===b.graphic)a.style.visibility="hidden";else if(b.externalGraphic){f=this.getPosition(a);b.graphicWidth&&b.graphicHeight&&
2634 a.setAttributeNS(null,"preserveAspectRatio","none");var e=b.graphicWidth||b.graphicHeight,g=b.graphicHeight||b.graphicWidth,e=e?e:2*b.pointRadius,g=g?g:2*b.pointRadius,h=void 0!=b.graphicYOffset?b.graphicYOffset:-(0.5*g),k=b.graphicOpacity||b.fillOpacity;a.setAttributeNS(null,"x",(f.x+(void 0!=b.graphicXOffset?b.graphicXOffset:-(0.5*e))).toFixed());a.setAttributeNS(null,"y",(f.y+h).toFixed());a.setAttributeNS(null,"width",e);a.setAttributeNS(null,"height",g);a.setAttributeNS(this.xlinkns,"xlink:href",
2635 b.externalGraphic);a.setAttributeNS(null,"style","opacity: "+k);a.onclick=OpenLayers.Event.preventDefault}else if(this.isComplexSymbol(b.graphicName)){var e=3*b.pointRadius,g=2*e,l=this.importSymbol(b.graphicName);f=this.getPosition(a);d=3*this.symbolMetrics[l.id][0]/g;h=a.parentNode;k=a.nextSibling;h&&h.removeChild(a);a.firstChild&&a.removeChild(a.firstChild);a.appendChild(l.firstChild.cloneNode(!0));a.setAttributeNS(null,"viewBox",l.getAttributeNS(null,"viewBox"));a.setAttributeNS(null,"width",
2636 g);a.setAttributeNS(null,"height",g);a.setAttributeNS(null,"x",f.x-e);a.setAttributeNS(null,"y",f.y-e);k?h.insertBefore(a,k):h&&h.appendChild(a)}else a.setAttributeNS(null,"r",b.pointRadius);e=b.rotation;void 0===e&&void 0===a._rotation||!f||(a._rotation=e,e|=0,"svg"!==a.nodeName?a.setAttributeNS(null,"transform","rotate("+e+" "+f.x+" "+f.y+")"):(f=this.symbolMetrics[l.id],a.firstChild.setAttributeNS(null,"transform","rotate("+e+" "+f[1]+" "+f[2]+")")))}c.isFilled?(a.setAttributeNS(null,"fill",b.fillColor),
2637 a.setAttributeNS(null,"fill-opacity",b.fillOpacity)):a.setAttributeNS(null,"fill","none");c.isStroked?(a.setAttributeNS(null,"stroke",b.strokeColor),a.setAttributeNS(null,"stroke-opacity",b.strokeOpacity),a.setAttributeNS(null,"stroke-width",b.strokeWidth*d),a.setAttributeNS(null,"stroke-linecap",b.strokeLinecap||"round"),a.setAttributeNS(null,"stroke-linejoin","round"),b.strokeDashstyle&&a.setAttributeNS(null,"stroke-dasharray",this.dashStyle(b,d))):a.setAttributeNS(null,"stroke","none");b.pointerEvents&&
2638 a.setAttributeNS(null,"pointer-events",b.pointerEvents);null!=b.cursor&&a.setAttributeNS(null,"cursor",b.cursor);return a},dashStyle:function(a,b){var c=a.strokeWidth*b,d=a.strokeDashstyle;switch(d){case "solid":return"none";case "dot":return[1,4*c].join();case "dash":return[4*c,4*c].join();case "dashdot":return[4*c,4*c,1,4*c].join();case "longdash":return[8*c,4*c].join();case "longdashdot":return[8*c,4*c,1,4*c].join();default:return OpenLayers.String.trim(d).replace(/\s+/g,",")}},createNode:function(a,
2639 b){var c=document.createElementNS(this.xmlns,a);b&&c.setAttributeNS(null,"id",b);return c},nodeTypeCompare:function(a,b){return b==a.nodeName},createRenderRoot:function(){var a=this.nodeFactory(this.container.id+"_svgRoot","svg");a.style.display="block";return a},createRoot:function(a){return this.nodeFactory(this.container.id+a,"g")},createDefs:function(){var a=this.nodeFactory(this.container.id+"_defs","defs");this.rendererRoot.appendChild(a);return a},drawPoint:function(a,b){return this.drawCircle(a,
2640 b,1)},drawCircle:function(a,b,c){var d=this.getResolution(),e=(b.x-this.featureDx)/d+this.left;b=this.top-b.y/d;return this.inValidRange(e,b)?(a.setAttributeNS(null,"cx",e),a.setAttributeNS(null,"cy",b),a.setAttributeNS(null,"r",c),a):!1},drawLineString:function(a,b){var c=this.getComponentsString(b.components);return c.path?(a.setAttributeNS(null,"points",c.path),c.complete?a:null):!1},drawLinearRing:function(a,b){var c=this.getComponentsString(b.components);return c.path?(a.setAttributeNS(null,
2641 "points",c.path),c.complete?a:null):!1},drawPolygon:function(a,b){for(var c="",d=!0,e=!0,f,g,h=0,k=b.components.length;h<k;h++)c+=" M",f=this.getComponentsString(b.components[h].components," "),(g=f.path)?(c+=" "+g,e=f.complete&&e):d=!1;return d?(a.setAttributeNS(null,"d",c+" z"),a.setAttributeNS(null,"fill-rule","evenodd"),e?a:null):!1},drawRectangle:function(a,b){var c=this.getResolution(),d=(b.x-this.featureDx)/c+this.left,e=this.top-b.y/c;return this.inValidRange(d,e)?(a.setAttributeNS(null,"x",
2642 d),a.setAttributeNS(null,"y",e),a.setAttributeNS(null,"width",b.width/c),a.setAttributeNS(null,"height",b.height/c),a):!1},drawText:function(a,b,c){var d=!!b.labelOutlineWidth;if(d){var e=OpenLayers.Util.extend({},b);e.fontColor=e.labelOutlineColor;e.fontStrokeColor=e.labelOutlineColor;e.fontStrokeWidth=b.labelOutlineWidth;b.labelOutlineOpacity&&(e.fontOpacity=b.labelOutlineOpacity);delete e.labelOutlineWidth;this.drawText(a,e,c)}var f=this.getResolution(),e=(c.x-this.featureDx)/f+this.left,g=c.y/
2643 f-this.top,d=d?this.LABEL_OUTLINE_SUFFIX:this.LABEL_ID_SUFFIX,f=this.nodeFactory(a+d,"text");f.setAttributeNS(null,"x",e);f.setAttributeNS(null,"y",-g);b.fontColor&&f.setAttributeNS(null,"fill",b.fontColor);b.fontStrokeColor&&f.setAttributeNS(null,"stroke",b.fontStrokeColor);b.fontStrokeWidth&&f.setAttributeNS(null,"stroke-width",b.fontStrokeWidth);b.fontOpacity&&f.setAttributeNS(null,"opacity",b.fontOpacity);b.fontFamily&&f.setAttributeNS(null,"font-family",b.fontFamily);b.fontSize&&f.setAttributeNS(null,
2644 "font-size",b.fontSize);b.fontWeight&&f.setAttributeNS(null,"font-weight",b.fontWeight);b.fontStyle&&f.setAttributeNS(null,"font-style",b.fontStyle);!0===b.labelSelect?(f.setAttributeNS(null,"pointer-events","visible"),f._featureId=a):f.setAttributeNS(null,"pointer-events","none");g=b.labelAlign||OpenLayers.Renderer.defaultSymbolizer.labelAlign;f.setAttributeNS(null,"text-anchor",OpenLayers.Renderer.SVG.LABEL_ALIGN[g[0]]||"middle");!0===OpenLayers.IS_GECKO&&f.setAttributeNS(null,"dominant-baseline",
2645 OpenLayers.Renderer.SVG.LABEL_ALIGN[g[1]]||"central");for(var h=b.label.split("\n"),k=h.length;f.childNodes.length>k;)f.removeChild(f.lastChild);for(var l=0;l<k;l++){var m=this.nodeFactory(a+d+"_tspan_"+l,"tspan");!0===b.labelSelect&&(m._featureId=a,m._geometry=c,m._geometryClass=c.CLASS_NAME);!1===OpenLayers.IS_GECKO&&m.setAttributeNS(null,"baseline-shift",OpenLayers.Renderer.SVG.LABEL_VSHIFT[g[1]]||"-35%");m.setAttribute("x",e);if(0==l){var n=OpenLayers.Renderer.SVG.LABEL_VFACTOR[g[1]];null==n&&
2646 (n=-0.5);m.setAttribute("dy",n*(k-1)+"em")}else m.setAttribute("dy","1em");m.textContent=""===h[l]?" ":h[l];m.parentNode||f.appendChild(m)}f.parentNode||this.textRoot.appendChild(f)},getComponentsString:function(a,b){for(var c=[],d=!0,e=a.length,f=[],g,h=0;h<e;h++)g=a[h],c.push(g),(g=this.getShortString(g))?f.push(g):(0<h&&this.getShortString(a[h-1])&&f.push(this.clipLine(a[h],a[h-1])),h<e-1&&this.getShortString(a[h+1])&&f.push(this.clipLine(a[h],a[h+1])),d=!1);return{path:f.join(b||","),complete:d}},
2647 clipLine:function(a,b){if(b.equals(a))return"";var c=this.getResolution(),d=this.MAX_PIXEL-this.translationParameters.x,e=this.MAX_PIXEL-this.translationParameters.y,f=(b.x-this.featureDx)/c+this.left,g=this.top-b.y/c,h=(a.x-this.featureDx)/c+this.left,c=this.top-a.y/c,k;if(h<-d||h>d)k=(c-g)/(h-f),h=0>h?-d:d,c=g+(h-f)*k;if(c<-e||c>e)k=(h-f)/(c-g),c=0>c?-e:e,h=f+(c-g)*k;return h+","+c},getShortString:function(a){var b=this.getResolution(),c=(a.x-this.featureDx)/b+this.left;a=this.top-a.y/b;return this.inValidRange(c,
2648 a)?c+","+a:!1},getPosition:function(a){return{x:parseFloat(a.getAttributeNS(null,"cx")),y:parseFloat(a.getAttributeNS(null,"cy"))}},importSymbol:function(a){this.defs||(this.defs=this.createDefs());var b=this.container.id+"-"+a,c=document.getElementById(b);if(null!=c)return c;var d=OpenLayers.Renderer.symbol[a];if(!d)throw Error(a+" is not a valid symbol name");a=this.nodeFactory(b,"symbol");var e=this.nodeFactory(null,"polygon");a.appendChild(e);for(var c=new OpenLayers.Bounds(Number.MAX_VALUE,Number.MAX_VALUE,
2649 0,0),f=[],g,h,k=0;k<d.length;k+=2)g=d[k],h=d[k+1],c.left=Math.min(c.left,g),c.bottom=Math.min(c.bottom,h),c.right=Math.max(c.right,g),c.top=Math.max(c.top,h),f.push(g,",",h);e.setAttributeNS(null,"points",f.join(" "));d=c.getWidth();e=c.getHeight();a.setAttributeNS(null,"viewBox",[c.left-d,c.bottom-e,3*d,3*e].join(" "));this.symbolMetrics[b]=[Math.max(d,e),c.getCenterLonLat().lon,c.getCenterLonLat().lat];this.defs.appendChild(a);return a},getFeatureIdFromEvent:function(a){var b=OpenLayers.Renderer.Elements.prototype.getFeatureIdFromEvent.apply(this,
2650 arguments);b||(b=a.target,b=b.parentNode&&b!=this.rendererRoot?b.parentNode._featureId:void 0);return b},CLASS_NAME:"OpenLayers.Renderer.SVG"});OpenLayers.Renderer.SVG.LABEL_ALIGN={l:"start",r:"end",b:"bottom",t:"hanging"};OpenLayers.Renderer.SVG.LABEL_VSHIFT={t:"-70%",b:"0"};OpenLayers.Renderer.SVG.LABEL_VFACTOR={t:0,b:-1};OpenLayers.Renderer.SVG.preventDefault=function(a){OpenLayers.Event.preventDefault(a)};OpenLayers.Format.SLD.v1_0_0=OpenLayers.Class(OpenLayers.Format.SLD.v1,{VERSION:"1.0.0",schemaLocation:"http://www.opengis.net/sld http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd",CLASS_NAME:"OpenLayers.Format.SLD.v1_0_0"});OpenLayers.Format.OWSContext=OpenLayers.Class(OpenLayers.Format.Context,{defaultVersion:"0.3.1",getVersion:function(a,b){var c=OpenLayers.Format.XML.VersionedOGC.prototype.getVersion.apply(this,arguments);"0.3.0"===c&&(c=this.defaultVersion);return c},toContext:function(a){var b={};"OpenLayers.Map"==a.CLASS_NAME&&(b.bounds=a.getExtent(),b.maxExtent=a.maxExtent,b.projection=a.projection,b.size=a.getSize(),b.layers=a.layers);return b},CLASS_NAME:"OpenLayers.Format.OWSContext"});OpenLayers.Format.OWSContext.v0_3_1=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{owc:"http://www.opengis.net/ows-context",gml:"http://www.opengis.net/gml",kml:"http://www.opengis.net/kml/2.2",ogc:"http://www.opengis.net/ogc",ows:"http://www.opengis.net/ows",sld:"http://www.opengis.net/sld",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance"},VERSION:"0.3.1",schemaLocation:"http://www.opengis.net/ows-context http://www.ogcnetwork.net/schemas/owc/0.3.1/owsContext.xsd",
2651 defaultPrefix:"owc",extractAttributes:!0,xy:!0,regExes:{trimSpace:/^\s*|\s*$/g,removeSpace:/\s*/g,splitSpace:/\s+/,trimComma:/\s*,\s*/g},featureNS:"http://mapserver.gis.umn.edu/mapserver",featureType:"vector",geometryName:"geometry",nestingLayerLookup:null,initialize:function(a){OpenLayers.Format.XML.prototype.initialize.apply(this,[a]);OpenLayers.Format.GML.v2.prototype.setGeometryTypes.call(this)},setNestingPath:function(a){if(a.layersContext)for(var b=0,c=a.layersContext.length;b<c;b++){var d=
2652 a.layersContext[b],e=[],f=a.title||"";a.metadata&&a.metadata.nestingPath&&(e=a.metadata.nestingPath.slice());""!=f&&e.push(f);d.metadata.nestingPath=e;d.layersContext&&this.setNestingPath(d)}},decomposeNestingPath:function(a){var b=[];if(OpenLayers.Util.isArray(a)){for(a=a.slice();0<a.length;)b.push(a.slice()),a.pop();b.reverse()}return b},read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));a&&9==a.nodeType&&(a=a.documentElement);var b={};this.readNode(a,
2653 b);this.setNestingPath({layersContext:b.layersContext});a=[];this.processLayer(a,b);delete b.layersContext;b.layersContext=a;return b},processLayer:function(a,b){if(b.layersContext)for(var c=0,d=b.layersContext.length;c<d;c++){var e=b.layersContext[c];a.push(e);e.layersContext&&this.processLayer(a,e)}},write:function(a,b){this.nestingLayerLookup={};b=b||{};OpenLayers.Util.applyDefaults(b,a);var c=this.writeNode("OWSContext",b);this.nestingLayerLookup=null;this.setAttributeNS(c,this.namespaces.xsi,
2654 "xsi:schemaLocation",this.schemaLocation);return OpenLayers.Format.XML.prototype.write.apply(this,[c])},readers:{kml:{Document:function(a,b){b.features=(new OpenLayers.Format.KML({kmlns:this.namespaces.kml,extractStyles:!0})).read(a)}},owc:{OWSContext:function(a,b){this.readChildNodes(a,b)},General:function(a,b){this.readChildNodes(a,b)},ResourceList:function(a,b){this.readChildNodes(a,b)},Layer:function(a,b){var c={metadata:{},visibility:"1"!=a.getAttribute("hidden"),queryable:"1"==a.getAttribute("queryable"),
2655 opacity:null!=a.getAttribute("opacity")?parseFloat(a.getAttribute("opacity")):null,name:a.getAttribute("name"),categoryLayer:null==a.getAttribute("name"),formats:[],styles:[]};b.layersContext||(b.layersContext=[]);b.layersContext.push(c);this.readChildNodes(a,c)},InlineGeometry:function(a,b){b.features=[];var c=this.getElementsByTagNameNS(a,this.namespaces.gml,"featureMember"),d;1<=c.length&&(d=c[0]);d&&d.firstChild&&(c=d.firstChild.nextSibling?d.firstChild.nextSibling:d.firstChild,this.setNamespace("feature",
2656 c.namespaceURI),this.featureType=c.localName||c.nodeName.split(":").pop(),this.readChildNodes(a,b))},Server:function(a,b){if(!b.service&&!b.version||b.service!=OpenLayers.Format.Context.serviceTypes.WMS)b.service=a.getAttribute("service"),b.version=a.getAttribute("version"),this.readChildNodes(a,b)},Name:function(a,b){b.name=this.getChildValue(a);this.readChildNodes(a,b)},Title:function(a,b){b.title=this.getChildValue(a);this.readChildNodes(a,b)},StyleList:function(a,b){this.readChildNodes(a,b.styles)},
2657 Style:function(a,b){var c={};b.push(c);this.readChildNodes(a,c)},LegendURL:function(a,b){var c={};b.legend=c;this.readChildNodes(a,c)},OnlineResource:function(a,b){b.url=this.getAttributeNS(a,this.namespaces.xlink,"href");this.readChildNodes(a,b)}},ows:OpenLayers.Format.OWSCommon.v1_0_0.prototype.readers.ows,gml:OpenLayers.Format.GML.v2.prototype.readers.gml,sld:OpenLayers.Format.SLD.v1_0_0.prototype.readers.sld,feature:OpenLayers.Format.GML.v2.prototype.readers.feature},writers:{owc:{OWSContext:function(a){var b=
2658 this.createElementNSPlus("OWSContext",{attributes:{version:this.VERSION,id:a.id||OpenLayers.Util.createUniqueID("OpenLayers_OWSContext_")}});this.writeNode("General",a,b);this.writeNode("ResourceList",a,b);return b},General:function(a){var b=this.createElementNSPlus("General");this.writeNode("ows:BoundingBox",a,b);this.writeNode("ows:Title",a.title||"OpenLayers OWSContext",b);return b},ResourceList:function(a){for(var b=this.createElementNSPlus("ResourceList"),c=0,d=a.layers.length;c<d;c++){var e=
2659 a.layers[c],f=this.decomposeNestingPath(e.metadata.nestingPath);this.writeNode("_Layer",{layer:e,subPaths:f},b)}return b},Server:function(a){var b=this.createElementNSPlus("Server",{attributes:{version:a.version,service:a.service}});this.writeNode("OnlineResource",a,b);return b},OnlineResource:function(a){return this.createElementNSPlus("OnlineResource",{attributes:{"xlink:href":a.url}})},InlineGeometry:function(a){var b=this.createElementNSPlus("InlineGeometry"),c=a.getDataExtent();null!==c&&this.writeNode("gml:boundedBy",
2660 c,b);for(var c=0,d=a.features.length;c<d;c++)this.writeNode("gml:featureMember",a.features[c],b);return b},StyleList:function(a){for(var b=this.createElementNSPlus("StyleList"),c=0,d=a.length;c<d;c++)this.writeNode("Style",a[c],b);return b},Style:function(a){var b=this.createElementNSPlus("Style");this.writeNode("Name",a,b);this.writeNode("Title",a,b);a.legend&&this.writeNode("LegendURL",a,b);return b},Name:function(a){return this.createElementNSPlus("Name",{value:a.name})},Title:function(a){return this.createElementNSPlus("Title",
2661 {value:a.title})},LegendURL:function(a){var b=this.createElementNSPlus("LegendURL");this.writeNode("OnlineResource",a.legend,b);return b},_WMS:function(a){var b=this.createElementNSPlus("Layer",{attributes:{name:a.params.LAYERS,queryable:a.queryable?"1":"0",hidden:a.visibility?"0":"1",opacity:a.hasOwnProperty("opacity")?a.opacity:null}});this.writeNode("ows:Title",a.name,b);this.writeNode("ows:OutputFormat",a.params.FORMAT,b);this.writeNode("Server",{service:OpenLayers.Format.Context.serviceTypes.WMS,
2662 version:a.params.VERSION,url:a.url},b);a.metadata.styles&&0<a.metadata.styles.length&&this.writeNode("StyleList",a.metadata.styles,b);return b},_Layer:function(a){var b,c,d;b=a.layer;c=a.subPaths;d=null;0<c.length?(b=c[0].join("/"),c=b.lastIndexOf("/"),d=this.nestingLayerLookup[b],c=0<c?b.substring(c+1,b.length):b,d||(d=this.createElementNSPlus("Layer"),this.writeNode("ows:Title",c,d),this.nestingLayerLookup[b]=d),a.subPaths.shift(),this.writeNode("_Layer",a,d)):(b instanceof OpenLayers.Layer.WMS?
2663 d=this.writeNode("_WMS",b):b instanceof OpenLayers.Layer.Vector&&(b.protocol instanceof OpenLayers.Protocol.WFS.v1?d=this.writeNode("_WFS",b):b.protocol instanceof OpenLayers.Protocol.HTTP?b.protocol.format instanceof OpenLayers.Format.GML?(b.protocol.format.version="2.1.2",d=this.writeNode("_GML",b)):b.protocol.format instanceof OpenLayers.Format.KML&&(b.protocol.format.version="2.2",d=this.writeNode("_KML",b)):(this.setNamespace("feature",this.featureNS),d=this.writeNode("_InlineGeometry",b))),
2664 b.options.maxScale&&this.writeNode("sld:MinScaleDenominator",b.options.maxScale,d),b.options.minScale&&this.writeNode("sld:MaxScaleDenominator",b.options.minScale,d),this.nestingLayerLookup[b.name]=d);return d},_WFS:function(a){var b=this.createElementNSPlus("Layer",{attributes:{name:a.protocol.featurePrefix+":"+a.protocol.featureType,hidden:a.visibility?"0":"1"}});this.writeNode("ows:Title",a.name,b);this.writeNode("Server",{service:OpenLayers.Format.Context.serviceTypes.WFS,version:a.protocol.version,
2665 url:a.protocol.url},b);return b},_InlineGeometry:function(a){var b=this.createElementNSPlus("Layer",{attributes:{name:this.featureType,hidden:a.visibility?"0":"1"}});this.writeNode("ows:Title",a.name,b);this.writeNode("InlineGeometry",a,b);return b},_GML:function(a){var b=this.createElementNSPlus("Layer");this.writeNode("ows:Title",a.name,b);this.writeNode("Server",{service:OpenLayers.Format.Context.serviceTypes.GML,url:a.protocol.url,version:a.protocol.format.version},b);return b},_KML:function(a){var b=
2666 this.createElementNSPlus("Layer");this.writeNode("ows:Title",a.name,b);this.writeNode("Server",{service:OpenLayers.Format.Context.serviceTypes.KML,version:a.protocol.format.version,url:a.protocol.url},b);return b}},gml:OpenLayers.Util.applyDefaults({boundedBy:function(a){var b=this.createElementNSPlus("gml:boundedBy");this.writeNode("gml:Box",a,b);return b}},OpenLayers.Format.GML.v2.prototype.writers.gml),ows:OpenLayers.Format.OWSCommon.v1_0_0.prototype.writers.ows,sld:OpenLayers.Format.SLD.v1_0_0.prototype.writers.sld,
2667 feature:OpenLayers.Format.GML.v2.prototype.writers.feature},CLASS_NAME:"OpenLayers.Format.OWSContext.v0_3_1"});OpenLayers.Popup=OpenLayers.Class({events:null,id:"",lonlat:null,div:null,contentSize:null,size:null,contentHTML:null,backgroundColor:"",opacity:"",border:"",contentDiv:null,groupDiv:null,closeDiv:null,autoSize:!1,minSize:null,maxSize:null,displayClass:"olPopup",contentDisplayClass:"olPopupContent",padding:0,disableFirefoxOverflowHack:!1,fixPadding:function(){"number"==typeof this.padding&&(this.padding=new OpenLayers.Bounds(this.padding,this.padding,this.padding,this.padding))},panMapIfOutOfView:!1,
2668 keepInMap:!1,closeOnMove:!1,map:null,initialize:function(a,b,c,d,e,f){null==a&&(a=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_"));this.id=a;this.lonlat=b;this.contentSize=null!=c?c:new OpenLayers.Size(OpenLayers.Popup.WIDTH,OpenLayers.Popup.HEIGHT);null!=d&&(this.contentHTML=d);this.backgroundColor=OpenLayers.Popup.COLOR;this.opacity=OpenLayers.Popup.OPACITY;this.border=OpenLayers.Popup.BORDER;this.div=OpenLayers.Util.createDiv(this.id,null,null,null,null,null,"hidden");this.div.className=this.displayClass;
2669 this.groupDiv=OpenLayers.Util.createDiv(this.id+"_GroupDiv",null,null,null,"relative",null,"hidden");a=this.div.id+"_contentDiv";this.contentDiv=OpenLayers.Util.createDiv(a,null,this.contentSize.clone(),null,"relative");this.contentDiv.className=this.contentDisplayClass;this.groupDiv.appendChild(this.contentDiv);this.div.appendChild(this.groupDiv);e&&this.addCloseBox(f);this.registerEvents()},destroy:function(){this.border=this.opacity=this.backgroundColor=this.contentHTML=this.size=this.lonlat=this.id=
2670 null;this.closeOnMove&&this.map&&this.map.events.unregister("movestart",this,this.hide);this.events.destroy();this.events=null;this.closeDiv&&(OpenLayers.Event.stopObservingElement(this.closeDiv),this.groupDiv.removeChild(this.closeDiv));this.closeDiv=null;this.div.removeChild(this.groupDiv);this.groupDiv=null;null!=this.map&&this.map.removePopup(this);this.panMapIfOutOfView=this.padding=this.maxSize=this.minSize=this.autoSize=this.div=this.map=null},draw:function(a){null==a&&null!=this.lonlat&&null!=
2671 this.map&&(a=this.map.getLayerPxFromLonLat(this.lonlat));this.closeOnMove&&this.map.events.register("movestart",this,this.hide);this.disableFirefoxOverflowHack||"firefox"!=OpenLayers.BROWSER_NAME||(this.map.events.register("movestart",this,function(){var a=document.defaultView.getComputedStyle(this.contentDiv,null).getPropertyValue("overflow");"hidden"!=a&&(this.contentDiv._oldOverflow=a,this.contentDiv.style.overflow="hidden")}),this.map.events.register("moveend",this,function(){var a=this.contentDiv._oldOverflow;
2672 a&&(this.contentDiv.style.overflow=a,this.contentDiv._oldOverflow=null)}));this.moveTo(a);this.autoSize||this.size||this.setSize(this.contentSize);this.setBackgroundColor();this.setOpacity();this.setBorder();this.setContentHTML();this.panMapIfOutOfView&&this.panIntoView();return this.div},updatePosition:function(){if(this.lonlat&&this.map){var a=this.map.getLayerPxFromLonLat(this.lonlat);a&&this.moveTo(a)}},moveTo:function(a){null!=a&&null!=this.div&&(this.div.style.left=a.x+"px",this.div.style.top=
2673 a.y+"px")},visible:function(){return OpenLayers.Element.visible(this.div)},toggle:function(){this.visible()?this.hide():this.show()},show:function(){this.div.style.display="";this.panMapIfOutOfView&&this.panIntoView()},hide:function(){this.div.style.display="none"},setSize:function(a){this.size=a.clone();var b=this.getContentDivPadding(),c=b.left+b.right,d=b.top+b.bottom;this.fixPadding();c+=this.padding.left+this.padding.right;d+=this.padding.top+this.padding.bottom;if(this.closeDiv)var e=parseInt(this.closeDiv.style.width),
2674 c=c+(e+b.right);this.size.w+=c;this.size.h+=d;"msie"==OpenLayers.BROWSER_NAME&&(this.contentSize.w+=b.left+b.right,this.contentSize.h+=b.bottom+b.top);null!=this.div&&(this.div.style.width=this.size.w+"px",this.div.style.height=this.size.h+"px");null!=this.contentDiv&&(this.contentDiv.style.width=a.w+"px",this.contentDiv.style.height=a.h+"px")},updateSize:function(){var a="<div class='"+this.contentDisplayClass+"'>"+this.contentDiv.innerHTML+"</div>",b=this.map?this.map.div:document.body,c=OpenLayers.Util.getRenderedDimensions(a,
2675 null,{displayClass:this.displayClass,containerElement:b}),d=this.getSafeContentSize(c),e=null;d.equals(c)?e=c:(c={w:d.w<c.w?d.w:null,h:d.h<c.h?d.h:null},c.w&&c.h?e=d:(a=OpenLayers.Util.getRenderedDimensions(a,c,{displayClass:this.contentDisplayClass,containerElement:b}),"hidden"!=OpenLayers.Element.getStyle(this.contentDiv,"overflow")&&a.equals(d)&&(d=OpenLayers.Util.getScrollbarWidth(),c.w?a.h+=d:a.w+=d),e=this.getSafeContentSize(a)));this.setSize(e)},setBackgroundColor:function(a){void 0!=a&&(this.backgroundColor=
2676 a);null!=this.div&&(this.div.style.backgroundColor=this.backgroundColor)},setOpacity:function(a){void 0!=a&&(this.opacity=a);null!=this.div&&(this.div.style.opacity=this.opacity,this.div.style.filter="alpha(opacity="+100*this.opacity+")")},setBorder:function(a){void 0!=a&&(this.border=a);null!=this.div&&(this.div.style.border=this.border)},setContentHTML:function(a){null!=a&&(this.contentHTML=a);null!=this.contentDiv&&(null!=this.contentHTML&&this.contentHTML!=this.contentDiv.innerHTML)&&(this.contentDiv.innerHTML=
2677 this.contentHTML,this.autoSize&&(this.registerImageListeners(),this.updateSize()))},registerImageListeners:function(){for(var a=function(){null!==this.popup.id&&(this.popup.updateSize(),this.popup.visible()&&this.popup.panMapIfOutOfView&&this.popup.panIntoView(),OpenLayers.Event.stopObserving(this.img,"load",this.img._onImgLoad))},b=this.contentDiv.getElementsByTagName("img"),c=0,d=b.length;c<d;c++){var e=b[c];if(0==e.width||0==e.height)e._onImgLoad=OpenLayers.Function.bind(a,{popup:this,img:e}),
2678 OpenLayers.Event.observe(e,"load",e._onImgLoad)}},getSafeContentSize:function(a){a=a.clone();var b=this.getContentDivPadding(),c=b.left+b.right,d=b.top+b.bottom;this.fixPadding();c+=this.padding.left+this.padding.right;d+=this.padding.top+this.padding.bottom;if(this.closeDiv)var e=parseInt(this.closeDiv.style.width),c=c+(e+b.right);this.minSize&&(a.w=Math.max(a.w,this.minSize.w-c),a.h=Math.max(a.h,this.minSize.h-d));this.maxSize&&(a.w=Math.min(a.w,this.maxSize.w-c),a.h=Math.min(a.h,this.maxSize.h-
2679 d));if(this.map&&this.map.size){e=b=0;if(this.keepInMap&&!this.panMapIfOutOfView)switch(e=this.map.getPixelFromLonLat(this.lonlat),this.relativePosition){case "tr":b=e.x;e=this.map.size.h-e.y;break;case "tl":b=this.map.size.w-e.x;e=this.map.size.h-e.y;break;case "bl":b=this.map.size.w-e.x;e=e.y;break;case "br":b=e.x;e=e.y;break;default:b=e.x,e=this.map.size.h-e.y}d=this.map.size.h-this.map.paddingForPopups.top-this.map.paddingForPopups.bottom-d-e;a.w=Math.min(a.w,this.map.size.w-this.map.paddingForPopups.left-
2680 this.map.paddingForPopups.right-c-b);a.h=Math.min(a.h,d)}return a},getContentDivPadding:function(){var a=this._contentDivPadding;a||(null==this.div.parentNode&&(this.div.style.display="none",document.body.appendChild(this.div)),this._contentDivPadding=a=new OpenLayers.Bounds(OpenLayers.Element.getStyle(this.contentDiv,"padding-left"),OpenLayers.Element.getStyle(this.contentDiv,"padding-bottom"),OpenLayers.Element.getStyle(this.contentDiv,"padding-right"),OpenLayers.Element.getStyle(this.contentDiv,
2681 "padding-top")),this.div.parentNode==document.body&&(document.body.removeChild(this.div),this.div.style.display=""));return a},addCloseBox:function(a){this.closeDiv=OpenLayers.Util.createDiv(this.id+"_close",null,{w:17,h:17});this.closeDiv.className="olPopupCloseBox";var b=this.getContentDivPadding();this.closeDiv.style.right=b.right+"px";this.closeDiv.style.top=b.top+"px";this.groupDiv.appendChild(this.closeDiv);a=a||function(a){this.hide();OpenLayers.Event.stop(a)};OpenLayers.Event.observe(this.closeDiv,
2682 "touchend",OpenLayers.Function.bindAsEventListener(a,this));OpenLayers.Event.observe(this.closeDiv,"click",OpenLayers.Function.bindAsEventListener(a,this))},panIntoView:function(){var a=this.map.getSize(),b=this.map.getViewPortPxFromLayerPx(new OpenLayers.Pixel(parseInt(this.div.style.left),parseInt(this.div.style.top))),c=b.clone();b.x<this.map.paddingForPopups.left?c.x=this.map.paddingForPopups.left:b.x+this.size.w>a.w-this.map.paddingForPopups.right&&(c.x=a.w-this.map.paddingForPopups.right-this.size.w);
2683 b.y<this.map.paddingForPopups.top?c.y=this.map.paddingForPopups.top:b.y+this.size.h>a.h-this.map.paddingForPopups.bottom&&(c.y=a.h-this.map.paddingForPopups.bottom-this.size.h);this.map.pan(b.x-c.x,b.y-c.y)},registerEvents:function(){this.events=new OpenLayers.Events(this,this.div,null,!0);this.events.on({mousedown:this.onmousedown,mousemove:this.onmousemove,mouseup:this.onmouseup,click:this.onclick,mouseout:this.onmouseout,dblclick:this.ondblclick,touchstart:function(a){OpenLayers.Event.stop(a,!0)},
2684 scope:this})},onmousedown:function(a){this.mousedown=!0;OpenLayers.Event.stop(a,!0)},onmousemove:function(a){this.mousedown&&OpenLayers.Event.stop(a,!0)},onmouseup:function(a){this.mousedown&&(this.mousedown=!1,OpenLayers.Event.stop(a,!0))},onclick:function(a){OpenLayers.Event.stop(a,!0)},onmouseout:function(a){this.mousedown=!1},ondblclick:function(a){OpenLayers.Event.stop(a,!0)},CLASS_NAME:"OpenLayers.Popup"});OpenLayers.Popup.WIDTH=200;OpenLayers.Popup.HEIGHT=200;OpenLayers.Popup.COLOR="white";
2685 OpenLayers.Popup.OPACITY=1;OpenLayers.Popup.BORDER="0px";OpenLayers.Control.ScaleLine=OpenLayers.Class(OpenLayers.Control,{maxWidth:100,topOutUnits:"km",topInUnits:"m",bottomOutUnits:"mi",bottomInUnits:"ft",eTop:null,eBottom:null,geodesic:!1,draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);this.eTop||(this.eTop=document.createElement("div"),this.eTop.className=this.displayClass+"Top",this.div.appendChild(this.eTop),this.eTop.style.visibility=""==this.topOutUnits||""==this.topInUnits?"hidden":"visible",this.eBottom=document.createElement("div"),
2686 this.eBottom.className=this.displayClass+"Bottom",this.div.appendChild(this.eBottom),this.eBottom.style.visibility=""==this.bottomOutUnits||""==this.bottomInUnits?"hidden":"visible");this.map.events.register("moveend",this,this.update);this.update();return this.div},getBarLen:function(a){var b=parseInt(Math.log(a)/Math.log(10)),b=Math.pow(10,b);a=parseInt(a/b);return(5<a?5:2<a?2:1)*b},update:function(){var a=this.map.getResolution();if(a){var b=this.map.getUnits(),c=OpenLayers.INCHES_PER_UNIT,d=this.maxWidth*
2687 a*c[b],e=1;!0===this.geodesic&&(e=(this.map.getGeodesicPixelSize().w||1E-6)*this.maxWidth/(d/c.km),d*=e);var f,g;1E5<d?(f=this.topOutUnits,g=this.bottomOutUnits):(f=this.topInUnits,g=this.bottomInUnits);var h=d/c[f],k=d/c[g],d=this.getBarLen(h),l=this.getBarLen(k),h=d/c[b]*c[f],k=l/c[b]*c[g],b=h/a/e,a=k/a/e;"visible"==this.eBottom.style.visibility&&(this.eBottom.style.width=Math.round(a)+"px",this.eBottom.innerHTML=l+" "+g);"visible"==this.eTop.style.visibility&&(this.eTop.style.width=Math.round(b)+
2688 "px",this.eTop.innerHTML=d+" "+f)}},CLASS_NAME:"OpenLayers.Control.ScaleLine"});OpenLayers.Icon=OpenLayers.Class({url:null,size:null,offset:null,calculateOffset:null,imageDiv:null,px:null,initialize:function(a,b,c,d){this.url=a;this.size=b||{w:20,h:20};this.offset=c||{x:-(this.size.w/2),y:-(this.size.h/2)};this.calculateOffset=d;a=OpenLayers.Util.createUniqueID("OL_Icon_");this.imageDiv=OpenLayers.Util.createAlphaImageDiv(a)},destroy:function(){this.erase();OpenLayers.Event.stopObservingElement(this.imageDiv.firstChild);this.imageDiv.innerHTML="";this.imageDiv=null},clone:function(){return new OpenLayers.Icon(this.url,
2689 this.size,this.offset,this.calculateOffset)},setSize:function(a){null!=a&&(this.size=a);this.draw()},setUrl:function(a){null!=a&&(this.url=a);this.draw()},draw:function(a){OpenLayers.Util.modifyAlphaImageDiv(this.imageDiv,null,null,this.size,this.url,"absolute");this.moveTo(a);return this.imageDiv},erase:function(){null!=this.imageDiv&&null!=this.imageDiv.parentNode&&OpenLayers.Element.remove(this.imageDiv)},setOpacity:function(a){OpenLayers.Util.modifyAlphaImageDiv(this.imageDiv,null,null,null,null,
2690 null,null,null,a)},moveTo:function(a){null!=a&&(this.px=a);null!=this.imageDiv&&(null==this.px?this.display(!1):(this.calculateOffset&&(this.offset=this.calculateOffset(this.size)),OpenLayers.Util.modifyAlphaImageDiv(this.imageDiv,null,{x:this.px.x+this.offset.x,y:this.px.y+this.offset.y})))},display:function(a){this.imageDiv.style.display=a?"":"none"},isDrawn:function(){return this.imageDiv&&this.imageDiv.parentNode&&11!=this.imageDiv.parentNode.nodeType},CLASS_NAME:"OpenLayers.Icon"});OpenLayers.Marker=OpenLayers.Class({icon:null,lonlat:null,events:null,map:null,initialize:function(a,b){this.lonlat=a;var c=b?b:OpenLayers.Marker.defaultIcon();null==this.icon?this.icon=c:(this.icon.url=c.url,this.icon.size=c.size,this.icon.offset=c.offset,this.icon.calculateOffset=c.calculateOffset);this.events=new OpenLayers.Events(this,this.icon.imageDiv)},destroy:function(){this.erase();this.map=null;this.events.destroy();this.events=null;null!=this.icon&&(this.icon.destroy(),this.icon=null)},
2691 draw:function(a){return this.icon.draw(a)},erase:function(){null!=this.icon&&this.icon.erase()},moveTo:function(a){null!=a&&null!=this.icon&&this.icon.moveTo(a);this.lonlat=this.map.getLonLatFromLayerPx(a)},isDrawn:function(){return this.icon&&this.icon.isDrawn()},onScreen:function(){var a=!1;this.map&&(a=this.map.getExtent().containsLonLat(this.lonlat));return a},inflate:function(a){this.icon&&this.icon.setSize({w:this.icon.size.w*a,h:this.icon.size.h*a})},setOpacity:function(a){this.icon.setOpacity(a)},
2692 setUrl:function(a){this.icon.setUrl(a)},display:function(a){this.icon.display(a)},CLASS_NAME:"OpenLayers.Marker"});OpenLayers.Marker.defaultIcon=function(){return new OpenLayers.Icon(OpenLayers.Util.getImageLocation("marker.png"),{w:21,h:25},{x:-10.5,y:-25})};OpenLayers.Layer.TileCache=OpenLayers.Class(OpenLayers.Layer.Grid,{isBaseLayer:!0,format:"image/png",serverResolutions:null,initialize:function(a,b,c,d){this.layername=c;OpenLayers.Layer.Grid.prototype.initialize.apply(this,[a,b,{},d]);this.extension=this.format.split("/")[1].toLowerCase();this.extension="jpg"==this.extension?"jpeg":this.extension},clone:function(a){null==a&&(a=new OpenLayers.Layer.TileCache(this.name,this.url,this.layername,this.getOptions()));return a=OpenLayers.Layer.Grid.prototype.clone.apply(this,
2693 [a])},getURL:function(a){var b=this.getServerResolution(),c=this.maxExtent,d=this.tileSize,e=Math.round((a.left-c.left)/(b*d.w));a=Math.round((a.bottom-c.bottom)/(b*d.h));b=null!=this.serverResolutions?OpenLayers.Util.indexOf(this.serverResolutions,b):this.map.getZoom();e=[this.layername,OpenLayers.Number.zeroPad(b,2),OpenLayers.Number.zeroPad(parseInt(e/1E6),3),OpenLayers.Number.zeroPad(parseInt(e/1E3)%1E3,3),OpenLayers.Number.zeroPad(parseInt(e)%1E3,3),OpenLayers.Number.zeroPad(parseInt(a/1E6),
2694 3),OpenLayers.Number.zeroPad(parseInt(a/1E3)%1E3,3),OpenLayers.Number.zeroPad(parseInt(a)%1E3,3)+"."+this.extension].join("/");b=this.url;OpenLayers.Util.isArray(b)&&(b=this.selectUrl(e,b));b="/"==b.charAt(b.length-1)?b:b+"/";return b+e},CLASS_NAME:"OpenLayers.Layer.TileCache"});OpenLayers.Strategy.Paging=OpenLayers.Class(OpenLayers.Strategy,{features:null,length:10,num:null,paging:!1,activate:function(){var a=OpenLayers.Strategy.prototype.activate.call(this);if(a)this.layer.events.on({beforefeaturesadded:this.cacheFeatures,scope:this});return a},deactivate:function(){var a=OpenLayers.Strategy.prototype.deactivate.call(this);a&&(this.clearCache(),this.layer.events.un({beforefeaturesadded:this.cacheFeatures,scope:this}));return a},cacheFeatures:function(a){this.paging||(this.clearCache(),
2695 this.features=a.features,this.pageNext(a))},clearCache:function(){if(this.features)for(var a=0;a<this.features.length;++a)this.features[a].destroy();this.num=this.features=null},pageCount:function(){return Math.ceil((this.features?this.features.length:0)/this.length)},pageNum:function(){return this.num},pageLength:function(a){a&&0<a&&(this.length=a);return this.length},pageNext:function(a){var b=!1;this.features&&(null===this.num&&(this.num=-1),b=this.page((this.num+1)*this.length,a));return b},pagePrevious:function(){var a=
2696 !1;this.features&&(null===this.num&&(this.num=this.pageCount()),a=this.page((this.num-1)*this.length));return a},page:function(a,b){var c=!1;if(this.features&&0<=a&&a<this.features.length){var d=Math.floor(a/this.length);d!=this.num&&(this.paging=!0,c=this.features.slice(a,a+this.length),this.layer.removeFeatures(this.layer.features),this.num=d,b&&b.features?b.features=c:this.layer.addFeatures(c),this.paging=!1,c=!0)}return c},CLASS_NAME:"OpenLayers.Strategy.Paging"});OpenLayers.Control.DragFeature=OpenLayers.Class(OpenLayers.Control,{geometryTypes:null,onStart:function(a,b){},onDrag:function(a,b){},onComplete:function(a,b){},onEnter:function(a){},onLeave:function(a){},documentDrag:!1,layer:null,feature:null,dragCallbacks:{},featureCallbacks:{},lastPixel:null,initialize:function(a,b){OpenLayers.Control.prototype.initialize.apply(this,[b]);this.layer=a;this.handlers={drag:new OpenLayers.Handler.Drag(this,OpenLayers.Util.extend({down:this.downFeature,move:this.moveFeature,
2697 up:this.upFeature,out:this.cancel,done:this.doneDragging},this.dragCallbacks),{documentDrag:this.documentDrag}),feature:new OpenLayers.Handler.Feature(this,this.layer,OpenLayers.Util.extend({click:this.clickFeature,clickout:this.clickoutFeature,over:this.overFeature,out:this.outFeature},this.featureCallbacks),{geometryTypes:this.geometryTypes})}},clickFeature:function(a){this.handlers.feature.touch&&(!this.over&&this.overFeature(a))&&(this.handlers.drag.dragstart(this.handlers.feature.evt),this.handlers.drag.stopDown=
2698 !1)},clickoutFeature:function(a){this.handlers.feature.touch&&this.over&&(this.outFeature(a),this.handlers.drag.stopDown=!0)},destroy:function(){this.layer=null;OpenLayers.Control.prototype.destroy.apply(this,[])},activate:function(){return this.handlers.feature.activate()&&OpenLayers.Control.prototype.activate.apply(this,arguments)},deactivate:function(){this.handlers.drag.deactivate();this.handlers.feature.deactivate();this.feature=null;this.dragging=!1;this.lastPixel=null;OpenLayers.Element.removeClass(this.map.viewPortDiv,
2699 this.displayClass+"Over");return OpenLayers.Control.prototype.deactivate.apply(this,arguments)},overFeature:function(a){var b=!1;this.handlers.drag.dragging?this.over=this.feature.id==a.id?!0:!1:(this.feature=a,this.handlers.drag.activate(),this.over=b=!0,OpenLayers.Element.addClass(this.map.viewPortDiv,this.displayClass+"Over"),this.onEnter(a));return b},downFeature:function(a){this.lastPixel=a;this.onStart(this.feature,a)},moveFeature:function(a){var b=this.map.getResolution();this.feature.geometry.move(b*
2700 (a.x-this.lastPixel.x),b*(this.lastPixel.y-a.y));this.layer.drawFeature(this.feature);this.lastPixel=a;this.onDrag(this.feature,a)},upFeature:function(a){this.over||this.handlers.drag.deactivate()},doneDragging:function(a){this.onComplete(this.feature,a)},outFeature:function(a){this.handlers.drag.dragging?this.feature.id==a.id&&(this.over=!1):(this.over=!1,this.handlers.drag.deactivate(),OpenLayers.Element.removeClass(this.map.viewPortDiv,this.displayClass+"Over"),this.onLeave(a),this.feature=null)},
2701 cancel:function(){this.handlers.drag.deactivate();this.over=!1},setMap:function(a){this.handlers.drag.setMap(a);this.handlers.feature.setMap(a);OpenLayers.Control.prototype.setMap.apply(this,arguments)},CLASS_NAME:"OpenLayers.Control.DragFeature"});OpenLayers.Control.TransformFeature=OpenLayers.Class(OpenLayers.Control,{geometryTypes:null,layer:null,preserveAspectRatio:!1,rotate:!0,feature:null,renderIntent:"temporary",rotationHandleSymbolizer:null,box:null,center:null,scale:1,ratio:1,rotation:0,handles:null,rotationHandles:null,dragControl:null,irregular:!1,initialize:function(a,b){OpenLayers.Control.prototype.initialize.apply(this,[b]);this.layer=a;this.rotationHandleSymbolizer||(this.rotationHandleSymbolizer={stroke:!1,pointRadius:10,fillOpacity:0,
2702 cursor:"pointer"});this.createBox();this.createControl()},activate:function(){var a=!1;OpenLayers.Control.prototype.activate.apply(this,arguments)&&(this.dragControl.activate(),this.layer.addFeatures([this.box]),this.rotate&&this.layer.addFeatures(this.rotationHandles),this.layer.addFeatures(this.handles),a=!0);return a},deactivate:function(){var a=!1;OpenLayers.Control.prototype.deactivate.apply(this,arguments)&&(this.layer.removeFeatures(this.handles),this.rotate&&this.layer.removeFeatures(this.rotationHandles),
2703 this.layer.removeFeatures([this.box]),this.dragControl.deactivate(),a=!0);return a},setMap:function(a){this.dragControl.setMap(a);OpenLayers.Control.prototype.setMap.apply(this,arguments)},setFeature:function(a,b){b=OpenLayers.Util.applyDefaults(b,{rotation:0,scale:1,ratio:1});var c=this.rotation,d=this.center;OpenLayers.Util.extend(this,b);if(!1!==this.events.triggerEvent("beforesetfeature",{feature:a})){this.feature=a;this.activate();this._setfeature=!0;var e=this.feature.geometry.getBounds();this.box.move(e.getCenterLonLat());
2704 this.box.geometry.rotate(-c,d);this._angle=0;this.rotation?(c=a.geometry.clone(),c.rotate(-this.rotation,this.center),c=new OpenLayers.Feature.Vector(c.getBounds().toGeometry()),c.geometry.rotate(this.rotation,this.center),this.box.geometry.rotate(this.rotation,this.center),this.box.move(c.geometry.getBounds().getCenterLonLat()),c=c.geometry.components[0].components[0].getBounds().getCenterLonLat()):c=new OpenLayers.LonLat(e.left,e.bottom);this.handles[0].move(c);delete this._setfeature;this.events.triggerEvent("setfeature",
2705 {feature:a})}},unsetFeature:function(){this.active?this.deactivate():(this.feature=null,this.rotation=0,this.ratio=this.scale=1)},createBox:function(){var a=this;this.center=new OpenLayers.Geometry.Point(0,0);this.box=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString([new OpenLayers.Geometry.Point(-1,-1),new OpenLayers.Geometry.Point(0,-1),new OpenLayers.Geometry.Point(1,-1),new OpenLayers.Geometry.Point(1,0),new OpenLayers.Geometry.Point(1,1),new OpenLayers.Geometry.Point(0,1),new OpenLayers.Geometry.Point(-1,
2706 1),new OpenLayers.Geometry.Point(-1,0),new OpenLayers.Geometry.Point(-1,-1)]),null,"string"==typeof this.renderIntent?null:this.renderIntent);this.box.geometry.move=function(b,c){a._moving=!0;OpenLayers.Geometry.LineString.prototype.move.apply(this,arguments);a.center.move(b,c);delete a._moving};for(var b=function(a,b){OpenLayers.Geometry.Point.prototype.move.apply(this,arguments);this._rotationHandle&&this._rotationHandle.geometry.move(a,b);this._handle.geometry.move(a,b)},c=function(a,b,c){OpenLayers.Geometry.Point.prototype.resize.apply(this,
2707 arguments);this._rotationHandle&&this._rotationHandle.geometry.resize(a,b,c);this._handle.geometry.resize(a,b,c)},d=function(a,b){OpenLayers.Geometry.Point.prototype.rotate.apply(this,arguments);this._rotationHandle&&this._rotationHandle.geometry.rotate(a,b);this._handle.geometry.rotate(a,b)},e=function(b,c){var d=this.x,e=this.y;OpenLayers.Geometry.Point.prototype.move.call(this,b,c);if(!a._moving){var f=a.dragControl.handlers.drag.evt,g=!(!a._setfeature&&a.preserveAspectRatio)&&!(f&&f.shiftKey),
2708 h=new OpenLayers.Geometry.Point(d,e),f=a.center;this.rotate(-a.rotation,f);h.rotate(-a.rotation,f);var k=this.x-f.x,l=this.y-f.y,m=k-(this.x-h.x),n=l-(this.y-h.y);a.irregular&&!a._setfeature&&(k-=(this.x-h.x)/2,l-=(this.y-h.y)/2);this.x=d;this.y=e;h=1;g?(l=1E-5>Math.abs(n)?1:l/n,h=(1E-5>Math.abs(m)?1:k/m)/l):(m=Math.sqrt(m*m+n*n),l=Math.sqrt(k*k+l*l)/m);a._moving=!0;a.box.geometry.rotate(-a.rotation,f);delete a._moving;a.box.geometry.resize(l,f,h);a.box.geometry.rotate(a.rotation,f);a.transformFeature({scale:l,
2709 ratio:h});a.irregular&&!a._setfeature&&(k=f.clone(),k.x+=1E-5>Math.abs(d-f.x)?0:this.x-d,k.y+=1E-5>Math.abs(e-f.y)?0:this.y-e,a.box.geometry.move(this.x-d,this.y-e),a.transformFeature({center:k}))}},f=function(b,c){var d=this.x,e=this.y;OpenLayers.Geometry.Point.prototype.move.call(this,b,c);if(!a._moving){var f=a.dragControl.handlers.drag.evt,f=f&&f.shiftKey?45:1,g=a.center,h=this.x-g.x,k=this.y-g.y;this.x=d;this.y=e;d=Math.atan2(k-c,h-b);d=Math.atan2(k,h)-d;d*=180/Math.PI;a._angle=(a._angle+d)%
2710 360;d=a.rotation%f;if(Math.abs(a._angle)>=f||0!==d)d=Math.round(a._angle/f)*f-d,a._angle=0,a.box.geometry.rotate(d,g),a.transformFeature({rotation:d})}},g=Array(8),h=Array(4),k,l,m,n="sw s se e ne n nw w".split(" "),p=0;8>p;++p)k=this.box.geometry.components[p],l=new OpenLayers.Feature.Vector(k.clone(),{role:n[p]+"-resize"},"string"==typeof this.renderIntent?null:this.renderIntent),0==p%2&&(m=new OpenLayers.Feature.Vector(k.clone(),{role:n[p]+"-rotate"},"string"==typeof this.rotationHandleSymbolizer?
2711 null:this.rotationHandleSymbolizer),m.geometry.move=f,k._rotationHandle=m,h[p/2]=m),k.move=b,k.resize=c,k.rotate=d,l.geometry.move=e,k._handle=l,g[p]=l;this.rotationHandles=h;this.handles=g},createControl:function(){var a=this;this.dragControl=new OpenLayers.Control.DragFeature(this.layer,{documentDrag:!0,moveFeature:function(b){this.feature===a.feature&&(this.feature=a.box);OpenLayers.Control.DragFeature.prototype.moveFeature.apply(this,arguments)},onDrag:function(b,c){b===a.box&&a.transformFeature({center:a.center})},
2712 onStart:function(b,c){var d=!a.geometryTypes||-1!==OpenLayers.Util.indexOf(a.geometryTypes,b.geometry.CLASS_NAME),e=OpenLayers.Util.indexOf(a.handles,b),e=e+OpenLayers.Util.indexOf(a.rotationHandles,b);b!==a.feature&&(b!==a.box&&-2==e&&d)&&a.setFeature(b)},onComplete:function(b,c){a.events.triggerEvent("transformcomplete",{feature:a.feature})}})},drawHandles:function(){for(var a=this.layer,b=0;8>b;++b)this.rotate&&0===b%2&&a.drawFeature(this.rotationHandles[b/2],this.rotationHandleSymbolizer),a.drawFeature(this.handles[b],
2713 this.renderIntent)},transformFeature:function(a){if(!this._setfeature){this.scale*=a.scale||1;this.ratio*=a.ratio||1;var b=this.rotation;this.rotation=(this.rotation+(a.rotation||0))%360;if(!1!==this.events.triggerEvent("beforetransform",a)){var c=this.feature,d=c.geometry,e=this.center;d.rotate(-b,e);a.scale||a.ratio?d.resize(a.scale,e,a.ratio):a.center&&c.move(a.center.getBounds().getCenterLonLat());d.rotate(this.rotation,e);this.layer.drawFeature(c);c.toState(OpenLayers.State.UPDATE);this.events.triggerEvent("transform",
2714 a)}}this.layer.drawFeature(this.box,this.renderIntent);this.drawHandles()},destroy:function(){for(var a,b=0;8>b;++b)a=this.box.geometry.components[b],a._handle.destroy(),a._handle=null,a._rotationHandle&&a._rotationHandle.destroy(),a._rotationHandle=null;this.rotationHandles=this.rotationHandleSymbolizer=this.handles=this.feature=this.center=null;this.box.destroy();this.layer=this.box=null;this.dragControl.destroy();this.dragControl=null;OpenLayers.Control.prototype.destroy.apply(this,arguments)},
2715 CLASS_NAME:"OpenLayers.Control.TransformFeature"});OpenLayers.Handler.Box=OpenLayers.Class(OpenLayers.Handler,{dragHandler:null,boxDivClassName:"olHandlerBoxZoomBox",boxOffsets:null,initialize:function(a,b,c){OpenLayers.Handler.prototype.initialize.apply(this,arguments);this.dragHandler=new OpenLayers.Handler.Drag(this,{down:this.startBox,move:this.moveBox,out:this.removeBox,up:this.endBox},{keyMask:this.keyMask})},destroy:function(){OpenLayers.Handler.prototype.destroy.apply(this,arguments);this.dragHandler&&(this.dragHandler.destroy(),this.dragHandler=
2716 null)},setMap:function(a){OpenLayers.Handler.prototype.setMap.apply(this,arguments);this.dragHandler&&this.dragHandler.setMap(a)},startBox:function(a){this.callback("start",[]);this.zoomBox=OpenLayers.Util.createDiv("zoomBox",{x:-9999,y:-9999});this.zoomBox.className=this.boxDivClassName;this.zoomBox.style.zIndex=this.map.Z_INDEX_BASE.Popup-1;this.map.viewPortDiv.appendChild(this.zoomBox);OpenLayers.Element.addClass(this.map.viewPortDiv,"olDrawBox")},moveBox:function(a){var b=this.dragHandler.start.x,
2717 c=this.dragHandler.start.y,d=Math.abs(b-a.x),e=Math.abs(c-a.y),f=this.getBoxOffsets();this.zoomBox.style.width=d+f.width+1+"px";this.zoomBox.style.height=e+f.height+1+"px";this.zoomBox.style.left=(a.x<b?b-d-f.left:b-f.left)+"px";this.zoomBox.style.top=(a.y<c?c-e-f.top:c-f.top)+"px"},endBox:function(a){var b;if(5<Math.abs(this.dragHandler.start.x-a.x)||5<Math.abs(this.dragHandler.start.y-a.y)){var c=this.dragHandler.start;b=Math.min(c.y,a.y);var d=Math.max(c.y,a.y),e=Math.min(c.x,a.x);a=Math.max(c.x,
2718 a.x);b=new OpenLayers.Bounds(e,d,a,b)}else b=this.dragHandler.start.clone();this.removeBox();this.callback("done",[b])},removeBox:function(){this.map.viewPortDiv.removeChild(this.zoomBox);this.boxOffsets=this.zoomBox=null;OpenLayers.Element.removeClass(this.map.viewPortDiv,"olDrawBox")},activate:function(){return OpenLayers.Handler.prototype.activate.apply(this,arguments)?(this.dragHandler.activate(),!0):!1},deactivate:function(){return OpenLayers.Handler.prototype.deactivate.apply(this,arguments)?
2719 (this.dragHandler.deactivate()&&this.zoomBox&&this.removeBox(),!0):!1},getBoxOffsets:function(){if(!this.boxOffsets){var a=document.createElement("div");a.style.position="absolute";a.style.border="1px solid black";a.style.width="3px";document.body.appendChild(a);var b=3==a.clientWidth;document.body.removeChild(a);var a=parseInt(OpenLayers.Element.getStyle(this.zoomBox,"border-left-width")),c=parseInt(OpenLayers.Element.getStyle(this.zoomBox,"border-right-width")),d=parseInt(OpenLayers.Element.getStyle(this.zoomBox,
2720 "border-top-width")),e=parseInt(OpenLayers.Element.getStyle(this.zoomBox,"border-bottom-width"));this.boxOffsets={left:a,right:c,top:d,bottom:e,width:!1===b?a+c:0,height:!1===b?d+e:0}}return this.boxOffsets},CLASS_NAME:"OpenLayers.Handler.Box"});OpenLayers.Control.ZoomBox=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_TOOL,out:!1,keyMask:null,alwaysZoom:!1,zoomOnClick:!0,draw:function(){this.handler=new OpenLayers.Handler.Box(this,{done:this.zoomBox},{keyMask:this.keyMask})},zoomBox:function(a){if(a instanceof OpenLayers.Bounds){var b,c=a.getCenterPixel();if(this.out){b=Math.min(this.map.size.h/(a.bottom-a.top),this.map.size.w/(a.right-a.left));var d=this.map.getExtent(),e=this.map.getLonLatFromPixel(c),f=e.lon-d.getWidth()/
2721 2*b;a=e.lon+d.getWidth()/2*b;var g=e.lat-d.getHeight()/2*b;b=e.lat+d.getHeight()/2*b;b=new OpenLayers.Bounds(f,g,a,b)}else f=this.map.getLonLatFromPixel({x:a.left,y:a.bottom}),a=this.map.getLonLatFromPixel({x:a.right,y:a.top}),b=new OpenLayers.Bounds(f.lon,f.lat,a.lon,a.lat);f=this.map.getZoom();g=this.map.getSize();a=g.w/2;g=g.h/2;b=this.map.getZoomForExtent(b);d=this.map.getResolution();e=this.map.getResolutionForZoom(b);d==e?this.map.setCenter(this.map.getLonLatFromPixel(c)):this.map.zoomTo(b,
2722 {x:(d*c.x-e*a)/(d-e),y:(d*c.y-e*g)/(d-e)});f==this.map.getZoom()&&!0==this.alwaysZoom&&this.map.zoomTo(f+(this.out?-1:1))}else this.zoomOnClick&&(this.out?this.map.zoomTo(this.map.getZoom()-1,a):this.map.zoomTo(this.map.getZoom()+1,a))},CLASS_NAME:"OpenLayers.Control.ZoomBox"});OpenLayers.Control.DragPan=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_TOOL,panned:!1,interval:0,documentDrag:!1,kinetic:null,enableKinetic:!0,kineticInterval:10,draw:function(){if(this.enableKinetic&&OpenLayers.Kinetic){var a={interval:this.kineticInterval};"object"===typeof this.enableKinetic&&(a=OpenLayers.Util.extend(a,this.enableKinetic));this.kinetic=new OpenLayers.Kinetic(a)}this.handler=new OpenLayers.Handler.Drag(this,{move:this.panMap,done:this.panMapDone,down:this.panMapStart},
2723 {interval:this.interval,documentDrag:this.documentDrag})},panMapStart:function(){this.kinetic&&this.kinetic.begin()},panMap:function(a){this.kinetic&&this.kinetic.update(a);this.panned=!0;this.map.pan(this.handler.last.x-a.x,this.handler.last.y-a.y,{dragging:!0,animate:!1})},panMapDone:function(a){if(this.panned){var b=null;this.kinetic&&(b=this.kinetic.end(a));this.map.pan(this.handler.last.x-a.x,this.handler.last.y-a.y,{dragging:!!b,animate:!1});if(b){var c=this;this.kinetic.move(b,function(a,b,
2724 f){c.map.pan(a,b,{dragging:!f,animate:!1})})}this.panned=!1}},CLASS_NAME:"OpenLayers.Control.DragPan"});OpenLayers.Control.Navigation=OpenLayers.Class(OpenLayers.Control,{dragPan:null,dragPanOptions:null,pinchZoom:null,pinchZoomOptions:null,documentDrag:!1,zoomBox:null,zoomBoxEnabled:!0,zoomWheelEnabled:!0,mouseWheelOptions:null,handleRightClicks:!1,zoomBoxKeyMask:OpenLayers.Handler.MOD_SHIFT,autoActivate:!0,initialize:function(a){this.handlers={};OpenLayers.Control.prototype.initialize.apply(this,arguments)},destroy:function(){this.deactivate();this.dragPan&&this.dragPan.destroy();this.dragPan=null;
2725 this.zoomBox&&this.zoomBox.destroy();this.zoomBox=null;this.pinchZoom&&this.pinchZoom.destroy();this.pinchZoom=null;OpenLayers.Control.prototype.destroy.apply(this,arguments)},activate:function(){this.dragPan.activate();this.zoomWheelEnabled&&this.handlers.wheel.activate();this.handlers.click.activate();this.zoomBoxEnabled&&this.zoomBox.activate();this.pinchZoom&&this.pinchZoom.activate();return OpenLayers.Control.prototype.activate.apply(this,arguments)},deactivate:function(){this.pinchZoom&&this.pinchZoom.deactivate();
2726 this.zoomBox.deactivate();this.dragPan.deactivate();this.handlers.click.deactivate();this.handlers.wheel.deactivate();return OpenLayers.Control.prototype.deactivate.apply(this,arguments)},draw:function(){this.handleRightClicks&&(this.map.viewPortDiv.oncontextmenu=OpenLayers.Function.False);this.handlers.click=new OpenLayers.Handler.Click(this,{click:this.defaultClick,dblclick:this.defaultDblClick,dblrightclick:this.defaultDblRightClick},{"double":!0,stopDouble:!0});this.dragPan=new OpenLayers.Control.DragPan(OpenLayers.Util.extend({map:this.map,
2727 documentDrag:this.documentDrag},this.dragPanOptions));this.zoomBox=new OpenLayers.Control.ZoomBox({map:this.map,keyMask:this.zoomBoxKeyMask});this.dragPan.draw();this.zoomBox.draw();this.handlers.wheel=new OpenLayers.Handler.MouseWheel(this,{up:this.wheelUp,down:this.wheelDown},OpenLayers.Util.extend(this.map.fractionalZoom?{}:{cumulative:!1,interval:50,maxDelta:6},this.mouseWheelOptions));OpenLayers.Control.PinchZoom&&(this.pinchZoom=new OpenLayers.Control.PinchZoom(OpenLayers.Util.extend({map:this.map},
2728 this.pinchZoomOptions)))},defaultClick:function(a){a.lastTouches&&2==a.lastTouches.length&&this.map.zoomOut()},defaultDblClick:function(a){this.map.zoomTo(this.map.zoom+1,a.xy)},defaultDblRightClick:function(a){this.map.zoomTo(this.map.zoom-1,a.xy)},wheelChange:function(a,b){this.map.fractionalZoom||(b=Math.round(b));var c=this.map.getZoom(),d;d=Math.max(c+b,0);d=Math.min(d,this.map.getNumZoomLevels());d!==c&&this.map.zoomTo(d,a.xy)},wheelUp:function(a,b){this.wheelChange(a,b||1)},wheelDown:function(a,
2729 b){this.wheelChange(a,b||-1)},disableZoomBox:function(){this.zoomBoxEnabled=!1;this.zoomBox.deactivate()},enableZoomBox:function(){this.zoomBoxEnabled=!0;this.active&&this.zoomBox.activate()},disableZoomWheel:function(){this.zoomWheelEnabled=!1;this.handlers.wheel.deactivate()},enableZoomWheel:function(){this.zoomWheelEnabled=!0;this.active&&this.handlers.wheel.activate()},CLASS_NAME:"OpenLayers.Control.Navigation"});OpenLayers.Control.DrawFeature=OpenLayers.Class(OpenLayers.Control,{layer:null,callbacks:null,multi:!1,featureAdded:function(){},initialize:function(a,b,c){OpenLayers.Control.prototype.initialize.apply(this,[c]);this.callbacks=OpenLayers.Util.extend({done:this.drawFeature,modify:function(a,b){this.layer.events.triggerEvent("sketchmodified",{vertex:a,feature:b})},create:function(a,b){this.layer.events.triggerEvent("sketchstarted",{vertex:a,feature:b})}},this.callbacks);this.layer=a;this.handlerOptions=
2730 this.handlerOptions||{};this.handlerOptions.layerOptions=OpenLayers.Util.applyDefaults(this.handlerOptions.layerOptions,{renderers:a.renderers,rendererOptions:a.rendererOptions});"multi"in this.handlerOptions||(this.handlerOptions.multi=this.multi);if(a=this.layer.styleMap&&this.layer.styleMap.styles.temporary)this.handlerOptions.layerOptions=OpenLayers.Util.applyDefaults(this.handlerOptions.layerOptions,{styleMap:new OpenLayers.StyleMap({"default":a})});this.handler=new b(this,this.callbacks,this.handlerOptions)},
2731 drawFeature:function(a){a=new OpenLayers.Feature.Vector(a);!1!==this.layer.events.triggerEvent("sketchcomplete",{feature:a})&&(a.state=OpenLayers.State.INSERT,this.layer.addFeatures([a]),this.featureAdded(a),this.events.triggerEvent("featureadded",{feature:a}))},insertXY:function(a,b){this.handler&&this.handler.line&&this.handler.insertXY(a,b)},insertDeltaXY:function(a,b){this.handler&&this.handler.line&&this.handler.insertDeltaXY(a,b)},insertDirectionLength:function(a,b){this.handler&&this.handler.line&&
2732 this.handler.insertDirectionLength(a,b)},insertDeflectionLength:function(a,b){this.handler&&this.handler.line&&this.handler.insertDeflectionLength(a,b)},undo:function(){return this.handler.undo&&this.handler.undo()},redo:function(){return this.handler.redo&&this.handler.redo()},finishSketch:function(){this.handler.finishGeometry()},cancel:function(){this.handler.cancel()},CLASS_NAME:"OpenLayers.Control.DrawFeature"});OpenLayers.Handler.Polygon=OpenLayers.Class(OpenLayers.Handler.Path,{holeModifier:null,drawingHole:!1,polygon:null,createFeature:function(a){a=this.layer.getLonLatFromViewPortPx(a);a=new OpenLayers.Geometry.Point(a.lon,a.lat);this.point=new OpenLayers.Feature.Vector(a);this.line=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LinearRing([this.point.geometry]));this.polygon=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([this.line.geometry]));this.callback("create",[this.point.geometry,
2733 this.getSketch()]);this.point.geometry.clearBounds();this.layer.addFeatures([this.polygon,this.point],{silent:!0})},addPoint:function(a){if(!this.drawingHole&&this.holeModifier&&this.evt&&this.evt[this.holeModifier])for(var b=this.point.geometry,c=this.control.layer.features,d,e=c.length-1;0<=e;--e)if(d=c[e].geometry,(d instanceof OpenLayers.Geometry.Polygon||d instanceof OpenLayers.Geometry.MultiPolygon)&&d.intersects(b)){b=c[e];this.control.layer.removeFeatures([b],{silent:!0});this.control.layer.events.registerPriority("sketchcomplete",
2734 this,this.finalizeInteriorRing);this.control.layer.events.registerPriority("sketchmodified",this,this.enforceTopology);b.geometry.addComponent(this.line.geometry);this.polygon=b;this.drawingHole=!0;break}OpenLayers.Handler.Path.prototype.addPoint.apply(this,arguments)},getCurrentPointIndex:function(){return this.line.geometry.components.length-2},enforceTopology:function(a){a=a.vertex;var b=this.line.geometry.components;this.polygon.geometry.intersects(a)||(b=b[b.length-3],a.x=b.x,a.y=b.y)},finishGeometry:function(){this.line.geometry.removeComponent(this.line.geometry.components[this.line.geometry.components.length-
2735 2]);this.removePoint();this.finalize()},finalizeInteriorRing:function(){var a=this.line.geometry,b=0!==a.getArea();if(b){for(var c=this.polygon.geometry.components,d=c.length-2;0<=d;--d)if(a.intersects(c[d])){b=!1;break}if(b)a:for(d=c.length-2;0<d;--d)for(var e=c[d].components,f=0,g=e.length;f<g;++f)if(a.containsPoint(e[f])){b=!1;break a}}b?this.polygon.state!==OpenLayers.State.INSERT&&(this.polygon.state=OpenLayers.State.UPDATE):this.polygon.geometry.removeComponent(a);this.restoreFeature();return!1},
2736 cancel:function(){this.drawingHole&&(this.polygon.geometry.removeComponent(this.line.geometry),this.restoreFeature(!0));return OpenLayers.Handler.Path.prototype.cancel.apply(this,arguments)},restoreFeature:function(a){this.control.layer.events.unregister("sketchcomplete",this,this.finalizeInteriorRing);this.control.layer.events.unregister("sketchmodified",this,this.enforceTopology);this.layer.removeFeatures([this.polygon],{silent:!0});this.control.layer.addFeatures([this.polygon],{silent:!0});this.drawingHole=
2737 !1;a||this.control.layer.events.triggerEvent("sketchcomplete",{feature:this.polygon})},destroyFeature:function(a){OpenLayers.Handler.Path.prototype.destroyFeature.call(this,a);this.polygon=null},drawFeature:function(){this.layer.drawFeature(this.polygon,this.style);this.layer.drawFeature(this.point,this.style)},getSketch:function(){return this.polygon},getGeometry:function(){var a=this.polygon&&this.polygon.geometry;a&&this.multi&&(a=new OpenLayers.Geometry.MultiPolygon([a]));return a},CLASS_NAME:"OpenLayers.Handler.Polygon"});OpenLayers.Control.EditingToolbar=OpenLayers.Class(OpenLayers.Control.Panel,{citeCompliant:!1,initialize:function(a,b){OpenLayers.Control.Panel.prototype.initialize.apply(this,[b]);this.addControls([new OpenLayers.Control.Navigation]);var c=[new OpenLayers.Control.DrawFeature(a,OpenLayers.Handler.Point,{displayClass:"olControlDrawFeaturePoint",handlerOptions:{citeCompliant:this.citeCompliant}}),new OpenLayers.Control.DrawFeature(a,OpenLayers.Handler.Path,{displayClass:"olControlDrawFeaturePath",handlerOptions:{citeCompliant:this.citeCompliant}}),
2738 new OpenLayers.Control.DrawFeature(a,OpenLayers.Handler.Polygon,{displayClass:"olControlDrawFeaturePolygon",handlerOptions:{citeCompliant:this.citeCompliant}})];this.addControls(c)},draw:function(){var a=OpenLayers.Control.Panel.prototype.draw.apply(this,arguments);null===this.defaultControl&&(this.defaultControl=this.controls[0]);return a},CLASS_NAME:"OpenLayers.Control.EditingToolbar"});OpenLayers.Strategy.BBOX=OpenLayers.Class(OpenLayers.Strategy,{bounds:null,resolution:null,ratio:2,resFactor:null,response:null,activate:function(){var a=OpenLayers.Strategy.prototype.activate.call(this);a&&(this.layer.events.on({moveend:this.update,refresh:this.update,visibilitychanged:this.update,scope:this}),this.update());return a},deactivate:function(){var a=OpenLayers.Strategy.prototype.deactivate.call(this);a&&this.layer.events.un({moveend:this.update,refresh:this.update,visibilitychanged:this.update,
2739 scope:this});return a},update:function(a){var b=this.getMapBounds();null!==b&&(a&&a.force||this.layer.visibility&&this.layer.calculateInRange()&&this.invalidBounds(b))&&(this.calculateBounds(b),this.resolution=this.layer.map.getResolution(),this.triggerRead(a))},getMapBounds:function(){if(null===this.layer.map)return null;var a=this.layer.map.getExtent();a&&!this.layer.projection.equals(this.layer.map.getProjectionObject())&&(a=a.clone().transform(this.layer.map.getProjectionObject(),this.layer.projection));
2740 return a},invalidBounds:function(a){a||(a=this.getMapBounds());a=!this.bounds||!this.bounds.containsBounds(a);!a&&this.resFactor&&(a=this.resolution/this.layer.map.getResolution(),a=a>=this.resFactor||a<=1/this.resFactor);return a},calculateBounds:function(a){a||(a=this.getMapBounds());var b=a.getCenterLonLat(),c=a.getWidth()*this.ratio;a=a.getHeight()*this.ratio;this.bounds=new OpenLayers.Bounds(b.lon-c/2,b.lat-a/2,b.lon+c/2,b.lat+a/2)},triggerRead:function(a){!this.response||a&&!0===a.noAbort||
2741 (this.layer.protocol.abort(this.response),this.layer.events.triggerEvent("loadend"));var b={filter:this.createFilter()};this.layer.events.triggerEvent("loadstart",b);this.response=this.layer.protocol.read(OpenLayers.Util.applyDefaults({filter:b.filter,callback:this.merge,scope:this},a))},createFilter:function(){var a=new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.BBOX,value:this.bounds,projection:this.layer.projection});this.layer.filter&&(a=new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.AND,
2742 filters:[this.layer.filter,a]}));return a},merge:function(a){this.layer.destroyFeatures();if(a.success()){var b=a.features;if(b&&0<b.length){var c=this.layer.projection,d=this.layer.map.getProjectionObject();if(!d.equals(c))for(var e,f=0,g=b.length;f<g;++f)(e=b[f].geometry)&&e.transform(c,d);this.layer.addFeatures(b)}}else this.bounds=null;this.response=null;this.layer.events.triggerEvent("loadend",{response:a})},CLASS_NAME:"OpenLayers.Strategy.BBOX"});OpenLayers.Layer.WorldWind=OpenLayers.Class(OpenLayers.Layer.Grid,{DEFAULT_PARAMS:{},isBaseLayer:!0,lzd:null,zoomLevels:null,initialize:function(a,b,c,d,e,f){this.lzd=c;this.zoomLevels=d;c=[];c.push(a,b,e,f);OpenLayers.Layer.Grid.prototype.initialize.apply(this,c);this.params=OpenLayers.Util.applyDefaults(this.params,this.DEFAULT_PARAMS)},getZoom:function(){var a=this.map.getZoom();this.map.getMaxExtent();return a-=Math.log(this.maxResolution/(this.lzd/512))/Math.log(2)},getURL:function(a){a=this.adjustBounds(a);
2743 var b=this.getZoom(),c=this.map.getMaxExtent(),d=this.lzd/Math.pow(2,this.getZoom()),e=Math.floor((a.left-c.left)/d);a=Math.floor((a.bottom-c.bottom)/d);return this.map.getResolution()<=this.lzd/512&&this.getZoom()<=this.zoomLevels?this.getFullRequestString({L:b,X:e,Y:a}):OpenLayers.Util.getImageLocation("blank.gif")},CLASS_NAME:"OpenLayers.Layer.WorldWind"});OpenLayers.Protocol.CSW=function(a){a=OpenLayers.Util.applyDefaults(a,OpenLayers.Protocol.CSW.DEFAULTS);var b=OpenLayers.Protocol.CSW["v"+a.version.replace(/\./g,"_")];if(!b)throw"Unsupported CSW version: "+a.version;return new b(a)};OpenLayers.Protocol.CSW.DEFAULTS={version:"2.0.2"};OpenLayers.Format.WMTSCapabilities=OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC,{defaultVersion:"1.0.0",yx:{"urn:ogc:def:crs:EPSG::4326":!0},createLayer:function(a,b){if(!("layer"in b))throw Error("Missing property 'layer' in configuration.");for(var c=a.contents,d,e=0,f=c.layers.length;e<f;++e)if(c.layers[e].identifier===b.layer){d=c.layers[e];break}if(!d)throw Error("Layer not found");var g=b.format;!g&&(d.formats&&d.formats.length)&&(g=d.formats[0]);var h;b.matrixSet?h=c.tileMatrixSets[b.matrixSet]:
2744 1<=d.tileMatrixSetLinks.length&&(h=c.tileMatrixSets[d.tileMatrixSetLinks[0].tileMatrixSet]);if(!h)throw Error("matrixSet not found");for(var k,e=0,f=d.styles.length;e<f&&(k=d.styles[e],!k.isDefault);++e);c=b.requestEncoding;if(!c&&(c="KVP",a.operationsMetadata.GetTile.dcp.http)){var l=a.operationsMetadata.GetTile.dcp.http;l.get[0].constraints&&(l=l.get[0].constraints.GetEncoding.allowedValues,l.KVP||!l.REST&&!l.RESTful||(c="REST"))}var l=[],m=b.params||{};delete b.params;for(var n=0,p=d.dimensions.length;n<
2745 p;n++){var q=d.dimensions[n];l.push(q.identifier);m.hasOwnProperty(q.identifier)||(m[q.identifier]=q["default"])}var n=b.projection||h.supportedCRS.replace(/urn:ogc:def:crs:(\w+):(.*:)?(\w+)$/,"$1:$3"),p=b.units||("EPSG:4326"===n?"degrees":"m"),q=[],r;for(r in h.matrixIds)h.matrixIds.hasOwnProperty(r)&&q.push(2.8E-4*h.matrixIds[r].scaleDenominator/OpenLayers.METERS_PER_INCH/OpenLayers.INCHES_PER_UNIT[p]);if("REST"===c&&d.resourceUrls){r=[];for(var f=0,s=d.resourceUrls.length;f<s;++f)e=d.resourceUrls[f],
2746 e.format===g&&"tile"===e.resourceType&&r.push(e.template)}else{s=a.operationsMetadata.GetTile.dcp.http.get;r=[];for(var t,e=0,f=s.length;e<f;e++)t=s[e].constraints,(!t||t&&t.GetEncoding.allowedValues[c])&&r.push(s[e].url)}return new OpenLayers.Layer.WMTS(OpenLayers.Util.applyDefaults(b,{url:r,requestEncoding:c,name:d.title,style:k.identifier,format:g,matrixIds:h.matrixIds,matrixSet:h.identifier,projection:n,units:p,resolutions:!1===b.isBaseLayer?void 0:q,serverResolutions:q,tileFullExtent:h.bounds,
2747 dimensions:l,params:m}))},CLASS_NAME:"OpenLayers.Format.WMTSCapabilities"});OpenLayers.Layer.Google.v3={DEFAULTS:{sphericalMercator:!0,projection:"EPSG:900913"},animationEnabled:!0,loadMapObject:function(){this.type||(this.type=google.maps.MapTypeId.ROADMAP);var a,b=OpenLayers.Layer.Google.cache[this.map.id];b?(a=b.mapObject,++b.count):(a=this.map.getCenter(),b=document.createElement("div"),b.className="olForeignContainer",b.style.width="100%",b.style.height="100%",a=new google.maps.Map(b,{center:a?new google.maps.LatLng(a.lat,a.lon):new google.maps.LatLng(0,0),zoom:this.map.getZoom()||
2748 0,mapTypeId:this.type,disableDefaultUI:!0,keyboardShortcuts:!1,draggable:!1,disableDoubleClickZoom:!0,scrollwheel:!1,streetViewControl:!1}),b=document.createElement("div"),b.style.width="100%",b.style.height="100%",a.controls[google.maps.ControlPosition.TOP_LEFT].push(b),b={googleControl:b,mapObject:a,count:1},OpenLayers.Layer.Google.cache[this.map.id]=b);this.mapObject=a;this.setGMapVisibility(this.visibility)},onMapResize:function(){this.visibility&&google.maps.event.trigger(this.mapObject,"resize")},
2749 setGMapVisibility:function(a){var b=OpenLayers.Layer.Google.cache[this.map.id],c=this.map;if(b){for(var d=this.type,e=c.layers,f,g=e.length-1;0<=g;--g)if(f=e[g],f instanceof OpenLayers.Layer.Google&&!0===f.visibility&&!0===f.inRange){d=f.type;a=!0;break}e=this.mapObject.getDiv();if(!0===a){if(e.parentNode!==c.div)if(b.rendered)c.div.appendChild(e),b.googleControl.appendChild(c.viewPortDiv),google.maps.event.trigger(this.mapObject,"resize");else{var h=this;google.maps.event.addListenerOnce(this.mapObject,
2750 "tilesloaded",function(){b.rendered=!0;h.setGMapVisibility(h.getVisibility());h.moveTo(h.map.getCenter())})}this.mapObject.setMapTypeId(d)}else b.googleControl.hasChildNodes()&&(c.div.appendChild(c.viewPortDiv),c.div.removeChild(e))}},getMapContainer:function(){return this.mapObject.getDiv()},getMapObjectBoundsFromOLBounds:function(a){var b=null;null!=a&&(b=this.sphericalMercator?this.inverseMercator(a.bottom,a.left):new OpenLayers.LonLat(a.bottom,a.left),a=this.sphericalMercator?this.inverseMercator(a.top,
2751 a.right):new OpenLayers.LonLat(a.top,a.right),b=new google.maps.LatLngBounds(new google.maps.LatLng(b.lat,b.lon),new google.maps.LatLng(a.lat,a.lon)));return b},getMapObjectLonLatFromMapObjectPixel:function(a){var b=this.map.getSize(),c=this.getLongitudeFromMapObjectLonLat(this.mapObject.center),d=this.getLatitudeFromMapObjectLonLat(this.mapObject.center),e=this.map.getResolution();a=new OpenLayers.LonLat(c+(a.x-b.w/2)*e,d-(a.y-b.h/2)*e);this.wrapDateLine&&(a=a.wrapDateLine(this.maxExtent));return this.getMapObjectLonLatFromLonLat(a.lon,
2752 a.lat)},getMapObjectPixelFromMapObjectLonLat:function(a){var b=this.getLongitudeFromMapObjectLonLat(a);a=this.getLatitudeFromMapObjectLonLat(a);var c=this.map.getResolution(),d=this.map.getExtent();return this.getMapObjectPixelFromXY(1/c*(b-d.left),1/c*(d.top-a))},setMapObjectCenter:function(a,b){if(!1===this.animationEnabled&&b!=this.mapObject.zoom){var c=this.getMapContainer();google.maps.event.addListenerOnce(this.mapObject,"idle",function(){c.style.visibility=""});c.style.visibility="hidden"}this.mapObject.setOptions({center:a,
2753 zoom:b})},getMapObjectZoomFromMapObjectBounds:function(a){return this.mapObject.getBoundsZoomLevel(a)},getMapObjectLonLatFromLonLat:function(a,b){var c;this.sphericalMercator?(c=this.inverseMercator(a,b),c=new google.maps.LatLng(c.lat,c.lon)):c=new google.maps.LatLng(b,a);return c},getMapObjectPixelFromXY:function(a,b){return new google.maps.Point(a,b)}};OpenLayers.Format.WPSDescribeProcess=OpenLayers.Class(OpenLayers.Format.XML,{VERSION:"1.0.0",namespaces:{wps:"http://www.opengis.net/wps/1.0.0",ows:"http://www.opengis.net/ows/1.1",xsi:"http://www.w3.org/2001/XMLSchema-instance"},schemaLocation:"http://www.opengis.net/wps/1.0.0 http://schemas.opengis.net/wps/1.0.0/wpsAll.xsd",defaultPrefix:"wps",regExes:{trimSpace:/^\s*|\s*$/g,removeSpace:/\s*/g,splitSpace:/\s+/,trimComma:/\s*,\s*/g},read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,
2754 [a]));a&&9==a.nodeType&&(a=a.documentElement);var b={};this.readNode(a,b);return b},readers:{wps:{ProcessDescriptions:function(a,b){b.processDescriptions={};this.readChildNodes(a,b.processDescriptions)},ProcessDescription:function(a,b){var c={processVersion:this.getAttributeNS(a,this.namespaces.wps,"processVersion"),statusSupported:"true"===a.getAttribute("statusSupported"),storeSupported:"true"===a.getAttribute("storeSupported")};this.readChildNodes(a,c);b[c.identifier]=c},DataInputs:function(a,
2755 b){b.dataInputs=[];this.readChildNodes(a,b.dataInputs)},ProcessOutputs:function(a,b){b.processOutputs=[];this.readChildNodes(a,b.processOutputs)},Output:function(a,b){var c={};this.readChildNodes(a,c);b.push(c)},ComplexOutput:function(a,b){b.complexOutput={};this.readChildNodes(a,b.complexOutput)},LiteralOutput:function(a,b){b.literalOutput={};this.readChildNodes(a,b.literalOutput)},Input:function(a,b){var c={maxOccurs:parseInt(a.getAttribute("maxOccurs")),minOccurs:parseInt(a.getAttribute("minOccurs"))};
2756 this.readChildNodes(a,c);b.push(c)},BoundingBoxData:function(a,b){b.boundingBoxData={};this.readChildNodes(a,b.boundingBoxData)},CRS:function(a,b){b.CRSs||(b.CRSs={});b.CRSs[this.getChildValue(a)]=!0},LiteralData:function(a,b){b.literalData={};this.readChildNodes(a,b.literalData)},ComplexData:function(a,b){b.complexData={};this.readChildNodes(a,b.complexData)},Default:function(a,b){b["default"]={};this.readChildNodes(a,b["default"])},Supported:function(a,b){b.supported={};this.readChildNodes(a,b.supported)},
2757 Format:function(a,b){var c={};this.readChildNodes(a,c);b.formats||(b.formats={});b.formats[c.mimeType]=!0},MimeType:function(a,b){b.mimeType=this.getChildValue(a)}},ows:OpenLayers.Format.OWSCommon.v1_1_0.prototype.readers.ows},CLASS_NAME:"OpenLayers.Format.WPSDescribeProcess"});OpenLayers.Format.WKT=OpenLayers.Class(OpenLayers.Format,{initialize:function(a){this.regExes={typeStr:/^\s*(\w+)\s*\(\s*(.*)\s*\)\s*$/,spaces:/\s+/,parenComma:/\)\s*,\s*\(/,doubleParenComma:/\)\s*\)\s*,\s*\(\s*\(/,trimParens:/^\s*\(?(.*?)\)?\s*$/};OpenLayers.Format.prototype.initialize.apply(this,[a])},read:function(a){var b,c;a=a.replace(/[\n\r]/g," ");if(c=this.regExes.typeStr.exec(a))if(a=c[1].toLowerCase(),c=c[2],this.parse[a]&&(b=this.parse[a].apply(this,[c])),this.internalProjection&&this.externalProjection)if(b&&
2758 "OpenLayers.Feature.Vector"==b.CLASS_NAME)b.geometry.transform(this.externalProjection,this.internalProjection);else if(b&&"geometrycollection"!=a&&"object"==typeof b)for(a=0,c=b.length;a<c;a++)b[a].geometry.transform(this.externalProjection,this.internalProjection);return b},write:function(a){var b,c;a.constructor==Array?c=!0:(a=[a],c=!1);var d=[];c&&d.push("GEOMETRYCOLLECTION(");for(var e=0,f=a.length;e<f;++e)c&&0<e&&d.push(","),b=a[e].geometry,d.push(this.extractGeometry(b));c&&d.push(")");return d.join("")},
2759 extractGeometry:function(a){var b=a.CLASS_NAME.split(".")[2].toLowerCase();if(!this.extract[b])return null;this.internalProjection&&this.externalProjection&&(a=a.clone(),a.transform(this.internalProjection,this.externalProjection));return("collection"==b?"GEOMETRYCOLLECTION":b.toUpperCase())+"("+this.extract[b].apply(this,[a])+")"},extract:{point:function(a){return a.x+" "+a.y},multipoint:function(a){for(var b=[],c=0,d=a.components.length;c<d;++c)b.push("("+this.extract.point.apply(this,[a.components[c]])+
2760 ")");return b.join(",")},linestring:function(a){for(var b=[],c=0,d=a.components.length;c<d;++c)b.push(this.extract.point.apply(this,[a.components[c]]));return b.join(",")},multilinestring:function(a){for(var b=[],c=0,d=a.components.length;c<d;++c)b.push("("+this.extract.linestring.apply(this,[a.components[c]])+")");return b.join(",")},polygon:function(a){for(var b=[],c=0,d=a.components.length;c<d;++c)b.push("("+this.extract.linestring.apply(this,[a.components[c]])+")");return b.join(",")},multipolygon:function(a){for(var b=
2761 [],c=0,d=a.components.length;c<d;++c)b.push("("+this.extract.polygon.apply(this,[a.components[c]])+")");return b.join(",")},collection:function(a){for(var b=[],c=0,d=a.components.length;c<d;++c)b.push(this.extractGeometry.apply(this,[a.components[c]]));return b.join(",")}},parse:{point:function(a){a=OpenLayers.String.trim(a).split(this.regExes.spaces);return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(a[0],a[1]))},multipoint:function(a){for(var b=OpenLayers.String.trim(a).split(","),
2762 c=[],d=0,e=b.length;d<e;++d)a=b[d].replace(this.regExes.trimParens,"$1"),c.push(this.parse.point.apply(this,[a]).geometry);return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.MultiPoint(c))},linestring:function(a){a=OpenLayers.String.trim(a).split(",");for(var b=[],c=0,d=a.length;c<d;++c)b.push(this.parse.point.apply(this,[a[c]]).geometry);return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(b))},multilinestring:function(a){for(var b=OpenLayers.String.trim(a).split(this.regExes.parenComma),
2763 c=[],d=0,e=b.length;d<e;++d)a=b[d].replace(this.regExes.trimParens,"$1"),c.push(this.parse.linestring.apply(this,[a]).geometry);return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.MultiLineString(c))},polygon:function(a){var b;a=OpenLayers.String.trim(a).split(this.regExes.parenComma);for(var c=[],d=0,e=a.length;d<e;++d)b=a[d].replace(this.regExes.trimParens,"$1"),b=this.parse.linestring.apply(this,[b]).geometry,b=new OpenLayers.Geometry.LinearRing(b.components),c.push(b);return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon(c))},
2764 multipolygon:function(a){for(var b=OpenLayers.String.trim(a).split(this.regExes.doubleParenComma),c=[],d=0,e=b.length;d<e;++d)a=b[d].replace(this.regExes.trimParens,"$1"),c.push(this.parse.polygon.apply(this,[a]).geometry);return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.MultiPolygon(c))},geometrycollection:function(a){a=a.replace(/,\s*([A-Za-z])/g,"|$1");a=OpenLayers.String.trim(a).split("|");for(var b=[],c=0,d=a.length;c<d;++c)b.push(OpenLayers.Format.WKT.prototype.read.apply(this,[a[c]]));
2765 return b}},CLASS_NAME:"OpenLayers.Format.WKT"});OpenLayers.WPSProcess=OpenLayers.Class({client:null,server:null,identifier:null,description:null,localWPS:"http://geoserver/wps",formats:null,chained:0,executeCallbacks:null,initialize:function(a){OpenLayers.Util.extend(this,a);this.executeCallbacks=[];this.formats={"application/wkt":new OpenLayers.Format.WKT,"application/json":new OpenLayers.Format.GeoJSON}},describe:function(a){a=a||{};if(!this.description)this.client.describeProcess(this.server,this.identifier,function(b){this.description||this.parseDescription(b);
2766 a.callback&&a.callback.call(a.scope,this.description)},this);else if(a.callback){var b=this.description;window.setTimeout(function(){a.callback.call(a.scope,b)},0)}},configure:function(a){this.describe({callback:function(){var b=this.description,c=a.inputs,d,e,f;e=0;for(f=b.dataInputs.length;e<f;++e)d=b.dataInputs[e],this.setInputData(d,c[d.identifier]);a.callback&&a.callback.call(a.scope)},scope:this});return this},execute:function(a){this.configure({inputs:a.inputs,callback:function(){var b=this,
2767 c=this.getOutputIndex(b.description.processOutputs,a.output);b.setResponseForm({outputIndex:c});(function e(){OpenLayers.Util.removeItem(b.executeCallbacks,e);0!==b.chained?b.executeCallbacks.push(e):OpenLayers.Request.POST({url:b.client.servers[b.server].url,data:(new OpenLayers.Format.WPSExecute).write(b.description),success:function(e){var g=b.findMimeType(b.description.processOutputs[c].complexOutput.supported.formats);e=b.formats[g].read(e.responseText);e instanceof OpenLayers.Feature.Vector&&
2768 (e=[e]);a.success&&(g={},g[a.output||"result"]=e,a.success.call(a.scope,g))},scope:b})})()},scope:this})},output:function(a){return new OpenLayers.WPSProcess.ChainLink({process:this,output:a})},parseDescription:function(a){a=this.client.servers[this.server];this.description=(new OpenLayers.Format.WPSDescribeProcess).read(a.processDescription[this.identifier]).processDescriptions[this.identifier]},setInputData:function(a,b){delete a.data;delete a.reference;if(b instanceof OpenLayers.WPSProcess.ChainLink)++this.chained,
2769 a.reference={method:"POST",href:b.process.server===this.server?this.localWPS:this.client.servers[b.process.server].url},b.process.describe({callback:function(){--this.chained;this.chainProcess(a,b)},scope:this});else{a.data={};var c=a.complexData;c?(c=this.findMimeType(c.supported.formats),a.data.complexData={mimeType:c,value:this.formats[c].write(this.toFeatures(b))}):a.data.literalData={value:b}}},setResponseForm:function(a){a=a||{};var b=this.description.processOutputs[a.outputIndex||0];this.description.responseForm=
2770 {rawDataOutput:{identifier:b.identifier,mimeType:this.findMimeType(b.complexOutput.supported.formats,a.supportedFormats)}}},getOutputIndex:function(a,b){var c;if(b)for(var d=a.length-1;0<=d;--d){if(a[d].identifier===b){c=d;break}}else c=0;return c},chainProcess:function(a,b){var c=this.getOutputIndex(b.process.description.processOutputs,b.output);a.reference.mimeType=this.findMimeType(a.complexData.supported.formats,b.process.description.processOutputs[c].complexOutput.supported.formats);var d={};
2771 d[a.reference.mimeType]=!0;b.process.setResponseForm({outputIndex:c,supportedFormats:d});for(a.reference.body=b.process.description;0<this.executeCallbacks.length;)this.executeCallbacks[0]()},toFeatures:function(a){var b=OpenLayers.Util.isArray(a);b||(a=[a]);for(var c=Array(a.length),d,e=0,f=a.length;e<f;++e)d=a[e],c[e]=d instanceof OpenLayers.Feature.Vector?d:new OpenLayers.Feature.Vector(d);return b?c:c[0]},findMimeType:function(a,b){b=b||this.formats;for(var c in a)if(c in b)return c},CLASS_NAME:"OpenLayers.WPSProcess"});
2772 OpenLayers.WPSProcess.ChainLink=OpenLayers.Class({process:null,output:null,initialize:function(a){OpenLayers.Util.extend(this,a)},CLASS_NAME:"OpenLayers.WPSProcess.ChainLink"});OpenLayers.WPSClient=OpenLayers.Class({servers:null,version:"1.0.0",lazy:!1,events:null,initialize:function(a){OpenLayers.Util.extend(this,a);this.events=new OpenLayers.Events(this);this.servers={};for(var b in a.servers)this.servers[b]="string"==typeof a.servers[b]?{url:a.servers[b],version:this.version,processDescription:{}}:a.servers[b]},execute:function(a){this.getProcess(a.server,a.process).execute({inputs:a.inputs,success:a.success,scope:a.scope})},getProcess:function(a,b){var c=new OpenLayers.WPSProcess({client:this,
2773 server:a,identifier:b});this.lazy||c.describe();return c},describeProcess:function(a,b,c,d){var e=this.servers[a];e.processDescription[b]?window.setTimeout(function(){c.call(d,e.processDescription[b])},0):b in e.processDescription?this.events.register("describeprocess",this,function g(a){a.identifier===b&&(this.events.unregister("describeprocess",this,g),c.call(d,a.raw))}):(e.processDescription[b]=null,OpenLayers.Request.GET({url:e.url,params:{SERVICE:"WPS",VERSION:e.version,REQUEST:"DescribeProcess",
2774 IDENTIFIER:b},success:function(a){e.processDescription[b]=a.responseText;this.events.triggerEvent("describeprocess",{identifier:b,raw:a.responseText})},scope:this}))},destroy:function(){this.events.destroy();this.servers=this.events=null},CLASS_NAME:"OpenLayers.WPSClient"});OpenLayers.Format.CSWGetRecords.v2_0_2=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{csw:"http://www.opengis.net/cat/csw/2.0.2",dc:"http://purl.org/dc/elements/1.1/",dct:"http://purl.org/dc/terms/",gmd:"http://www.isotc211.org/2005/gmd",geonet:"http://www.fao.org/geonetwork",ogc:"http://www.opengis.net/ogc",ows:"http://www.opengis.net/ows",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance"},defaultPrefix:"csw",version:"2.0.2",schemaLocation:"http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd",
2775 requestId:null,resultType:null,outputFormat:null,outputSchema:null,startPosition:null,maxRecords:null,DistributedSearch:null,ResponseHandler:null,Query:null,regExes:{trimSpace:/^\s*|\s*$/g,removeSpace:/\s*/g,splitSpace:/\s+/,trimComma:/\s*,\s*/g},initialize:function(a){OpenLayers.Format.XML.prototype.initialize.apply(this,[a])},read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));a&&9==a.nodeType&&(a=a.documentElement);var b={};this.readNode(a,b);return b},
2776 readers:{csw:{GetRecordsResponse:function(a,b){b.records=[];this.readChildNodes(a,b);var c=this.getAttributeNS(a,"","version");""!=c&&(b.version=c)},RequestId:function(a,b){b.RequestId=this.getChildValue(a)},SearchStatus:function(a,b){b.SearchStatus={};var c=this.getAttributeNS(a,"","timestamp");""!=c&&(b.SearchStatus.timestamp=c)},SearchResults:function(a,b){this.readChildNodes(a,b);for(var c=a.attributes,d={},e=0,f=c.length;e<f;++e)d[c[e].name]="numberOfRecordsMatched"==c[e].name||"numberOfRecordsReturned"==
2777 c[e].name||"nextRecord"==c[e].name?parseInt(c[e].nodeValue):c[e].nodeValue;b.SearchResults=d},SummaryRecord:function(a,b){var c={type:"SummaryRecord"};this.readChildNodes(a,c);b.records.push(c)},BriefRecord:function(a,b){var c={type:"BriefRecord"};this.readChildNodes(a,c);b.records.push(c)},DCMIRecord:function(a,b){var c={type:"DCMIRecord"};this.readChildNodes(a,c);b.records.push(c)},Record:function(a,b){var c={type:"Record"};this.readChildNodes(a,c);b.records.push(c)},"*":function(a,b){var c=a.localName||
2778 a.nodeName.split(":").pop();b[c]=this.getChildValue(a)}},geonet:{info:function(a,b){var c={};this.readChildNodes(a,c);b.gninfo=c}},dc:{"*":function(a,b){var c=a.localName||a.nodeName.split(":").pop();OpenLayers.Util.isArray(b[c])||(b[c]=[]);for(var d={},e=a.attributes,f=0,g=e.length;f<g;++f)d[e[f].name]=e[f].nodeValue;d.value=this.getChildValue(a);""!=d.value&&b[c].push(d)}},dct:{"*":function(a,b){var c=a.localName||a.nodeName.split(":").pop();OpenLayers.Util.isArray(b[c])||(b[c]=[]);b[c].push(this.getChildValue(a))}},
2779 ows:OpenLayers.Util.applyDefaults({BoundingBox:function(a,b){b.bounds&&(b.BoundingBox=[{crs:b.projection,value:[b.bounds.left,b.bounds.bottom,b.bounds.right,b.bounds.top]}],delete b.projection,delete b.bounds);OpenLayers.Format.OWSCommon.v1_0_0.prototype.readers.ows.BoundingBox.apply(this,arguments)}},OpenLayers.Format.OWSCommon.v1_0_0.prototype.readers.ows)},write:function(a){a=this.writeNode("csw:GetRecords",a);a.setAttribute("xmlns:gmd",this.namespaces.gmd);return OpenLayers.Format.XML.prototype.write.apply(this,
2780 [a])},writers:{csw:{GetRecords:function(a){a||(a={});var b=this.createElementNSPlus("csw:GetRecords",{attributes:{service:"CSW",version:this.version,requestId:a.requestId||this.requestId,resultType:a.resultType||this.resultType,outputFormat:a.outputFormat||this.outputFormat,outputSchema:a.outputSchema||this.outputSchema,startPosition:a.startPosition||this.startPosition,maxRecords:a.maxRecords||this.maxRecords}});(a.DistributedSearch||this.DistributedSearch)&&this.writeNode("csw:DistributedSearch",
2781 a.DistributedSearch||this.DistributedSearch,b);var c=a.ResponseHandler||this.ResponseHandler;if(OpenLayers.Util.isArray(c)&&0<c.length)for(var d=0,e=c.length;d<e;d++)this.writeNode("csw:ResponseHandler",c[d],b);this.writeNode("Query",a.Query||this.Query,b);return b},DistributedSearch:function(a){return this.createElementNSPlus("csw:DistributedSearch",{attributes:{hopCount:a.hopCount}})},ResponseHandler:function(a){return this.createElementNSPlus("csw:ResponseHandler",{value:a.value})},Query:function(a){a||
2782 (a={});var b=this.createElementNSPlus("csw:Query",{attributes:{typeNames:a.typeNames||"csw:Record"}}),c=a.ElementName;if(OpenLayers.Util.isArray(c)&&0<c.length)for(var d=0,e=c.length;d<e;d++)this.writeNode("csw:ElementName",c[d],b);else this.writeNode("csw:ElementSetName",a.ElementSetName||{value:"summary"},b);a.Constraint&&this.writeNode("csw:Constraint",a.Constraint,b);a.SortBy&&this.writeNode("ogc:SortBy",a.SortBy,b);return b},ElementName:function(a){return this.createElementNSPlus("csw:ElementName",
2783 {value:a.value})},ElementSetName:function(a){return this.createElementNSPlus("csw:ElementSetName",{attributes:{typeNames:a.typeNames},value:a.value})},Constraint:function(a){var b=this.createElementNSPlus("csw:Constraint",{attributes:{version:a.version}});if(a.Filter){var c=new OpenLayers.Format.Filter({version:a.version});b.appendChild(c.write(a.Filter))}else a.CqlText&&(a=this.createElementNSPlus("CqlText",{value:a.CqlText.value}),b.appendChild(a));return b}},ogc:OpenLayers.Format.Filter.v1_1_0.prototype.writers.ogc},
2784 CLASS_NAME:"OpenLayers.Format.CSWGetRecords.v2_0_2"});/*
2785 Apache 2
2786
2787 Contains portions of Rico <http://openrico.org/>
2788
2789 Copyright 2005 Sabre Airline Solutions
2790
2791 Licensed under the Apache License, Version 2.0 (the "License"); you
2792 may not use this file except in compliance with the License. You
2793 may obtain a copy of the License at
2794
2795 http://www.apache.org/licenses/LICENSE-2.0
2796
2797 Unless required by applicable law or agreed to in writing, software
2798 distributed under the License is distributed on an "AS IS" BASIS,
2799 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
2800 implied. See the License for the specific language governing
2801 permissions and limitations under the License.
2802 */
2803 OpenLayers.Marker.Box=OpenLayers.Class(OpenLayers.Marker,{bounds:null,div:null,initialize:function(a,b,c){this.bounds=a;this.div=OpenLayers.Util.createDiv();this.div.style.overflow="hidden";this.events=new OpenLayers.Events(this,this.div);this.setBorder(b,c)},destroy:function(){this.div=this.bounds=null;OpenLayers.Marker.prototype.destroy.apply(this,arguments)},setBorder:function(a,b){a||(a="red");b||(b=2);this.div.style.border=b+"px solid "+a},draw:function(a,b){OpenLayers.Util.modifyDOMElement(this.div,
2804 null,a,b);return this.div},onScreen:function(){var a=!1;this.map&&(a=this.map.getExtent().containsBounds(this.bounds,!0,!0));return a},display:function(a){this.div.style.display=a?"":"none"},CLASS_NAME:"OpenLayers.Marker.Box"});OpenLayers.Format.Text=OpenLayers.Class(OpenLayers.Format,{defaultStyle:null,extractStyles:!0,initialize:function(a){a=a||{};!1!==a.extractStyles&&(a.defaultStyle={externalGraphic:OpenLayers.Util.getImageLocation("marker.png"),graphicWidth:21,graphicHeight:25,graphicXOffset:-10.5,graphicYOffset:-12.5});OpenLayers.Format.prototype.initialize.apply(this,[a])},read:function(a){a=a.split("\n");for(var b,c=[],d=0;d<a.length-1;d++){var e=a[d].replace(/^\s*/,"").replace(/\s*$/,"");if("#"!=e.charAt(0))if(b){for(var e=
2805 e.split("\t"),f=new OpenLayers.Geometry.Point(0,0),g={},h=this.defaultStyle?OpenLayers.Util.applyDefaults({},this.defaultStyle):null,k=!1,l=0;l<e.length;l++)if(e[l])if("point"==b[l])k=e[l].split(","),f.y=parseFloat(k[0]),f.x=parseFloat(k[1]),k=!0;else if("lat"==b[l])f.y=parseFloat(e[l]),k=!0;else if("lon"==b[l])f.x=parseFloat(e[l]),k=!0;else if("title"==b[l])g.title=e[l];else if("image"==b[l]||"icon"==b[l]&&h)h.externalGraphic=e[l];else if("iconSize"==b[l]&&h){var m=e[l].split(",");h.graphicWidth=
2806 parseFloat(m[0]);h.graphicHeight=parseFloat(m[1])}else"iconOffset"==b[l]&&h?(m=e[l].split(","),h.graphicXOffset=parseFloat(m[0]),h.graphicYOffset=parseFloat(m[1])):"description"==b[l]?g.description=e[l]:"overflow"==b[l]?g.overflow=e[l]:g[b[l]]=e[l];k&&(this.internalProjection&&this.externalProjection&&f.transform(this.externalProjection,this.internalProjection),e=new OpenLayers.Feature.Vector(f,g,h),c.push(e))}else b=e.split("\t")}return c},CLASS_NAME:"OpenLayers.Format.Text"});OpenLayers.Layer.Text=OpenLayers.Class(OpenLayers.Layer.Markers,{location:null,features:null,formatOptions:null,selectedFeature:null,initialize:function(a,b){OpenLayers.Layer.Markers.prototype.initialize.apply(this,arguments);this.features=[]},destroy:function(){OpenLayers.Layer.Markers.prototype.destroy.apply(this,arguments);this.clearFeatures();this.features=null},loadText:function(){this.loaded||null==this.location||(this.events.triggerEvent("loadstart"),OpenLayers.Request.GET({url:this.location,
2807 success:this.parseData,failure:function(a){this.events.triggerEvent("loadend")},scope:this}),this.loaded=!0)},moveTo:function(a,b,c){OpenLayers.Layer.Markers.prototype.moveTo.apply(this,arguments);this.visibility&&!this.loaded&&this.loadText()},parseData:function(a){a=a.responseText;var b={};OpenLayers.Util.extend(b,this.formatOptions);this.map&&!this.projection.equals(this.map.getProjectionObject())&&(b.externalProjection=this.projection,b.internalProjection=this.map.getProjectionObject());a=(new OpenLayers.Format.Text(b)).read(a);
2808 for(var b=0,c=a.length;b<c;b++){var d={},e=a[b],f,g,h;f=new OpenLayers.LonLat(e.geometry.x,e.geometry.y);e.style.graphicWidth&&e.style.graphicHeight&&(g=new OpenLayers.Size(e.style.graphicWidth,e.style.graphicHeight));void 0!==e.style.graphicXOffset&&void 0!==e.style.graphicYOffset&&(h=new OpenLayers.Pixel(e.style.graphicXOffset,e.style.graphicYOffset));null!=e.style.externalGraphic?d.icon=new OpenLayers.Icon(e.style.externalGraphic,g,h):(d.icon=OpenLayers.Marker.defaultIcon(),null!=g&&d.icon.setSize(g));
2809 null!=e.attributes.title&&null!=e.attributes.description&&(d.popupContentHTML="<h2>"+e.attributes.title+"</h2><p>"+e.attributes.description+"</p>");d.overflow=e.attributes.overflow||"auto";d=new OpenLayers.Feature(this,f,d);this.features.push(d);f=d.createMarker();null!=e.attributes.title&&null!=e.attributes.description&&f.events.register("click",d,this.markerClick);this.addMarker(f)}this.events.triggerEvent("loadend")},markerClick:function(a){var b=this==this.layer.selectedFeature;this.layer.selectedFeature=
2810 b?null:this;for(var c=0,d=this.layer.map.popups.length;c<d;c++)this.layer.map.removePopup(this.layer.map.popups[c]);b||this.layer.map.addPopup(this.createPopup());OpenLayers.Event.stop(a)},clearFeatures:function(){if(null!=this.features)for(;0<this.features.length;){var a=this.features[0];OpenLayers.Util.removeItem(this.features,a);a.destroy()}},CLASS_NAME:"OpenLayers.Layer.Text"});OpenLayers.Handler.RegularPolygon=OpenLayers.Class(OpenLayers.Handler.Drag,{sides:4,radius:null,snapAngle:null,snapToggle:"shiftKey",layerOptions:null,persist:!1,irregular:!1,citeCompliant:!1,angle:null,fixedRadius:!1,feature:null,layer:null,origin:null,initialize:function(a,b,c){c&&c.layerOptions&&c.layerOptions.styleMap||(this.style=OpenLayers.Util.extend(OpenLayers.Feature.Vector.style["default"],{}));OpenLayers.Handler.Drag.prototype.initialize.apply(this,[a,b,c]);this.options=c?c:{}},setOptions:function(a){OpenLayers.Util.extend(this.options,
2811 a);OpenLayers.Util.extend(this,a)},activate:function(){var a=!1;OpenLayers.Handler.Drag.prototype.activate.apply(this,arguments)&&(a=OpenLayers.Util.extend({displayInLayerSwitcher:!1,calculateInRange:OpenLayers.Function.True,wrapDateLine:this.citeCompliant},this.layerOptions),this.layer=new OpenLayers.Layer.Vector(this.CLASS_NAME,a),this.map.addLayer(this.layer),a=!0);return a},deactivate:function(){var a=!1;OpenLayers.Handler.Drag.prototype.deactivate.apply(this,arguments)&&(this.dragging&&this.cancel(),
2812 null!=this.layer.map&&(this.layer.destroy(!1),this.feature&&this.feature.destroy()),this.feature=this.layer=null,a=!0);return a},down:function(a){this.fixedRadius=!!this.radius;a=this.layer.getLonLatFromViewPortPx(a.xy);this.origin=new OpenLayers.Geometry.Point(a.lon,a.lat);if(!this.fixedRadius||this.irregular)this.radius=this.map.getResolution();this.persist&&this.clear();this.feature=new OpenLayers.Feature.Vector;this.createGeometry();this.callback("create",[this.origin,this.feature]);this.layer.addFeatures([this.feature],
2813 {silent:!0});this.layer.drawFeature(this.feature,this.style)},move:function(a){var b=this.layer.getLonLatFromViewPortPx(a.xy),b=new OpenLayers.Geometry.Point(b.lon,b.lat);this.irregular?(a=Math.sqrt(2)*Math.abs(b.y-this.origin.y)/2,this.radius=Math.max(this.map.getResolution()/2,a)):this.fixedRadius?this.origin=b:(this.calculateAngle(b,a),this.radius=Math.max(this.map.getResolution()/2,b.distanceTo(this.origin)));this.modifyGeometry();if(this.irregular){a=b.x-this.origin.x;var b=b.y-this.origin.y,
2814 c;c=0==b?a/(this.radius*Math.sqrt(2)):a/b;this.feature.geometry.resize(1,this.origin,c);this.feature.geometry.move(a/2,b/2)}this.layer.drawFeature(this.feature,this.style)},up:function(a){this.finalize();this.start==this.last&&this.callback("done",[a.xy])},out:function(a){this.finalize()},createGeometry:function(){this.angle=Math.PI*(1/this.sides-0.5);this.snapAngle&&(this.angle+=this.snapAngle*(Math.PI/180));this.feature.geometry=OpenLayers.Geometry.Polygon.createRegularPolygon(this.origin,this.radius,
2815 this.sides,this.snapAngle)},modifyGeometry:function(){var a,b,c=this.feature.geometry.components[0];c.components.length!=this.sides+1&&(this.createGeometry(),c=this.feature.geometry.components[0]);for(var d=0;d<this.sides;++d)b=c.components[d],a=this.angle+2*d*Math.PI/this.sides,b.x=this.origin.x+this.radius*Math.cos(a),b.y=this.origin.y+this.radius*Math.sin(a),b.clearBounds()},calculateAngle:function(a,b){var c=Math.atan2(a.y-this.origin.y,a.x-this.origin.x);if(this.snapAngle&&this.snapToggle&&!b[this.snapToggle]){var d=
2816 Math.PI/180*this.snapAngle;this.angle=Math.round(c/d)*d}else this.angle=c},cancel:function(){this.callback("cancel",null);this.finalize()},finalize:function(){this.origin=null;this.radius=this.options.radius},clear:function(){this.layer&&(this.layer.renderer.clear(),this.layer.destroyFeatures())},callback:function(a,b){this.callbacks[a]&&this.callbacks[a].apply(this.control,[this.feature.geometry.clone()]);this.persist||"done"!=a&&"cancel"!=a||this.clear()},CLASS_NAME:"OpenLayers.Handler.RegularPolygon"});OpenLayers.Control.SLDSelect=OpenLayers.Class(OpenLayers.Control,{clearOnDeactivate:!1,layers:null,callbacks:null,selectionSymbolizer:{Polygon:{fillColor:"#FF0000",stroke:!1},Line:{strokeColor:"#FF0000",strokeWidth:2},Point:{graphicName:"square",fillColor:"#FF0000",pointRadius:5}},layerOptions:null,sketchStyle:null,wfsCache:{},layerCache:{},initialize:function(a,b){OpenLayers.Control.prototype.initialize.apply(this,[b]);this.callbacks=OpenLayers.Util.extend({done:this.select,click:this.select},this.callbacks);
2817 this.handlerOptions=this.handlerOptions||{};this.layerOptions=OpenLayers.Util.applyDefaults(this.layerOptions,{displayInLayerSwitcher:!1,tileOptions:{maxGetUrlLength:2048}});this.sketchStyle&&(this.handlerOptions.layerOptions=OpenLayers.Util.applyDefaults(this.handlerOptions.layerOptions,{styleMap:new OpenLayers.StyleMap({"default":this.sketchStyle})}));this.handler=new a(this,this.callbacks,this.handlerOptions)},destroy:function(){for(var a in this.layerCache)delete this.layerCache[a];for(a in this.wfsCache)delete this.wfsCache[a];
2818 OpenLayers.Control.prototype.destroy.apply(this,arguments)},coupleLayerVisiblity:function(a){this.setVisibility(a.object.getVisibility())},createSelectionLayer:function(a){var b;if(this.layerCache[a.id])b=this.layerCache[a.id];else{b=new OpenLayers.Layer.WMS(a.name,a.url,a.params,OpenLayers.Util.applyDefaults(this.layerOptions,a.getOptions()));this.layerCache[a.id]=b;if(!1===this.layerOptions.displayInLayerSwitcher)a.events.on({visibilitychanged:this.coupleLayerVisiblity,scope:b});this.map.addLayer(b)}return b},
2819 createSLD:function(a,b,c){for(var d={version:"1.0.0",namedLayers:{}},e=(""+a.params.LAYERS).split(","),f=0,g=e.length;f<g;f++){var h=e[f];d.namedLayers[h]={name:h,userStyles:[]};var k=this.selectionSymbolizer,l=c[f];0<=l.type.indexOf("Polygon")?k={Polygon:this.selectionSymbolizer.Polygon}:0<=l.type.indexOf("LineString")?k={Line:this.selectionSymbolizer.Line}:0<=l.type.indexOf("Point")&&(k={Point:this.selectionSymbolizer.Point});d.namedLayers[h].userStyles.push({name:"default",rules:[new OpenLayers.Rule({symbolizer:k,
2820 filter:b[f],maxScaleDenominator:a.options.minScale})]})}return(new OpenLayers.Format.SLD({srsName:this.map.getProjection()})).write(d)},parseDescribeLayer:function(a){var b=new OpenLayers.Format.WMSDescribeLayer,c=a.responseXML;c&&c.documentElement||(c=a.responseText);a=b.read(c);for(var b=[],c=null,d=0,e=a.length;d<e;d++)"WFS"==a[d].owsType&&(b.push(a[d].typeName),c=a[d].owsURL);OpenLayers.Request.GET({url:c,params:{SERVICE:"WFS",TYPENAME:b.toString(),REQUEST:"DescribeFeatureType",VERSION:"1.0.0"},
2821 callback:function(a){var b=new OpenLayers.Format.WFSDescribeFeatureType,c=a.responseXML;c&&c.documentElement||(c=a.responseText);a=b.read(c);this.control.wfsCache[this.layer.id]=a;this.control._queue&&this.control.applySelection()},scope:this})},getGeometryAttributes:function(a){var b=[];a=this.wfsCache[a.id];for(var c=0,d=a.featureTypes.length;c<d;c++)for(var e=a.featureTypes[c].properties,f=0,g=e.length;f<g;f++){var h=e[f],k=h.type;(0<=k.indexOf("LineString")||0<=k.indexOf("GeometryAssociationType")||
2822 0<=k.indexOf("GeometryPropertyType")||0<=k.indexOf("Point")||0<=k.indexOf("Polygon"))&&b.push(h)}return b},activate:function(){var a=OpenLayers.Control.prototype.activate.call(this);if(a)for(var b=0,c=this.layers.length;b<c;b++){var d=this.layers[b];d&&!this.wfsCache[d.id]&&OpenLayers.Request.GET({url:d.url,params:{SERVICE:"WMS",VERSION:d.params.VERSION,LAYERS:d.params.LAYERS,REQUEST:"DescribeLayer"},callback:this.parseDescribeLayer,scope:{layer:d,control:this}})}return a},deactivate:function(){var a=
2823 OpenLayers.Control.prototype.deactivate.call(this);if(a)for(var b=0,c=this.layers.length;b<c;b++){var d=this.layers[b];if(d&&!0===this.clearOnDeactivate){var e=this.layerCache,f=e[d.id];f&&(d.events.un({visibilitychanged:this.coupleLayerVisiblity,scope:f}),f.destroy(),delete e[d.id])}}return a},setLayers:function(a){this.active?(this.deactivate(),this.layers=a,this.activate()):this.layers=a},createFilter:function(a,b){var c=null;this.handler instanceof OpenLayers.Handler.RegularPolygon?c=!0===this.handler.irregular?
2824 new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.BBOX,property:a.name,value:b.getBounds()}):new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.INTERSECTS,property:a.name,value:b}):this.handler instanceof OpenLayers.Handler.Polygon?c=new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.INTERSECTS,property:a.name,value:b}):this.handler instanceof OpenLayers.Handler.Path?c=0<=a.type.indexOf("Point")?new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.DWITHIN,
2825 property:a.name,distance:0.01*this.map.getExtent().getWidth(),distanceUnits:this.map.getUnits(),value:b}):new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.INTERSECTS,property:a.name,value:b}):this.handler instanceof OpenLayers.Handler.Click&&(c=0<=a.type.indexOf("Polygon")?new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.INTERSECTS,property:a.name,value:b}):new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.DWITHIN,property:a.name,distance:0.01*this.map.getExtent().getWidth(),
2826 distanceUnits:this.map.getUnits(),value:b}));return c},select:function(a){this._queue=function(){for(var b=0,c=this.layers.length;b<c;b++){for(var d=this.layers[b],e=this.getGeometryAttributes(d),f=[],g=0,h=e.length;g<h;g++){var k=e[g];if(null!==k){if(!(a instanceof OpenLayers.Geometry)){var l=this.map.getLonLatFromPixel(a.xy);a=new OpenLayers.Geometry.Point(l.lon,l.lat)}k=this.createFilter(k,a);null!==k&&f.push(k)}}g=this.createSelectionLayer(d);this.events.triggerEvent("selected",{layer:d,filters:f});
2827 d=this.createSLD(d,f,e);g.mergeNewParams({SLD_BODY:d});delete this._queue}};this.applySelection()},applySelection:function(){for(var a=!0,b=0,c=this.layers.length;b<c;b++)if(!this.wfsCache[this.layers[b].id]){a=!1;break}a&&this._queue.call(this)},CLASS_NAME:"OpenLayers.Control.SLDSelect"});OpenLayers.Control.Scale=OpenLayers.Class(OpenLayers.Control,{element:null,geodesic:!1,initialize:function(a,b){OpenLayers.Control.prototype.initialize.apply(this,[b]);this.element=OpenLayers.Util.getElement(a)},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);this.element||(this.element=document.createElement("div"),this.div.appendChild(this.element));this.map.events.register("moveend",this,this.updateScale);this.updateScale();return this.div},updateScale:function(){var a;
2828 if(!0===this.geodesic){if(!this.map.getUnits())return;a=OpenLayers.INCHES_PER_UNIT;a=(this.map.getGeodesicPixelSize().w||1E-6)*a.km*OpenLayers.DOTS_PER_INCH}else a=this.map.getScale();a&&(a=9500<=a&&95E4>=a?Math.round(a/1E3)+"K":95E4<=a?Math.round(a/1E6)+"M":Math.round(a),this.element.innerHTML=OpenLayers.i18n("Scale = 1 : ${scaleDenom}",{scaleDenom:a}))},CLASS_NAME:"OpenLayers.Control.Scale"});OpenLayers.Layer.MapGuide=OpenLayers.Class(OpenLayers.Layer.Grid,{isBaseLayer:!0,useHttpTile:!1,singleTile:!1,useOverlay:!1,useAsyncOverlay:!0,TILE_PARAMS:{operation:"GETTILEIMAGE",version:"1.2.0"},SINGLE_TILE_PARAMS:{operation:"GETMAPIMAGE",format:"PNG",locale:"en",clip:"1",version:"1.0.0"},OVERLAY_PARAMS:{operation:"GETDYNAMICMAPOVERLAYIMAGE",format:"PNG",locale:"en",clip:"1",version:"2.0.0"},FOLDER_PARAMS:{tileColumnsPerFolder:30,tileRowsPerFolder:30,format:"png",querystring:null},defaultSize:new OpenLayers.Size(300,
2829 300),tileOriginCorner:"tl",initialize:function(a,b,c,d){OpenLayers.Layer.Grid.prototype.initialize.apply(this,arguments);if(null==d||null==d.isBaseLayer)this.isBaseLayer="true"!=this.transparent&&!0!=this.transparent;d&&null!=d.useOverlay&&(this.useOverlay=d.useOverlay);this.singleTile?this.useOverlay?(OpenLayers.Util.applyDefaults(this.params,this.OVERLAY_PARAMS),this.useAsyncOverlay||(this.params.version="1.0.0")):OpenLayers.Util.applyDefaults(this.params,this.SINGLE_TILE_PARAMS):(this.useHttpTile?
2830 OpenLayers.Util.applyDefaults(this.params,this.FOLDER_PARAMS):OpenLayers.Util.applyDefaults(this.params,this.TILE_PARAMS),this.setTileSize(this.defaultSize))},clone:function(a){null==a&&(a=new OpenLayers.Layer.MapGuide(this.name,this.url,this.params,this.getOptions()));return a=OpenLayers.Layer.Grid.prototype.clone.apply(this,[a])},getURL:function(a){var b;b=a.getCenterLonLat();var c=this.map.getSize();this.singleTile?(a={setdisplaydpi:OpenLayers.DOTS_PER_INCH,setdisplayheight:c.h*this.ratio,setdisplaywidth:c.w*
2831 this.ratio,setviewcenterx:b.lon,setviewcentery:b.lat,setviewscale:this.map.getScale()},this.useOverlay&&!this.useAsyncOverlay&&(b={},b=OpenLayers.Util.extend(b,a),b.operation="GETVISIBLEMAPEXTENT",b.version="1.0.0",b.session=this.params.session,b.mapName=this.params.mapName,b.format="text/xml",b=this.getFullRequestString(b),OpenLayers.Request.GET({url:b,async:!1})),b=this.getFullRequestString(a)):(c=this.map.getResolution(),b=Math.floor((a.left-this.maxExtent.left)/c),b=Math.round(b/this.tileSize.w),
2832 a=Math.floor((this.maxExtent.top-a.top)/c),a=Math.round(a/this.tileSize.h),b=this.useHttpTile?this.getImageFilePath({tilecol:b,tilerow:a,scaleindex:this.resolutions.length-this.map.zoom-1}):this.getFullRequestString({tilecol:b,tilerow:a,scaleindex:this.resolutions.length-this.map.zoom-1}));return b},getFullRequestString:function(a,b){var c=null==b?this.url:b;"object"==typeof c&&(c=c[Math.floor(Math.random()*c.length)]);var d=c,e=OpenLayers.Util.extend({},this.params),e=OpenLayers.Util.extend(e,a),
2833 f=OpenLayers.Util.upperCaseObject(OpenLayers.Util.getParameters(c)),g;for(g in e)g.toUpperCase()in f&&delete e[g];e=OpenLayers.Util.getParameterString(e);e=e.replace(/,/g,"+");""!=e&&(f=c.charAt(c.length-1),d="&"==f||"?"==f?d+e:-1==c.indexOf("?")?d+("?"+e):d+("&"+e));return d},getImageFilePath:function(a,b){var c=null==b?this.url:b;"object"==typeof c&&(c=c[Math.floor(Math.random()*c.length)]);var d="",e="";0>a.tilerow&&(d="-");d=0==a.tilerow?d+"0":d+Math.floor(Math.abs(a.tilerow/this.params.tileRowsPerFolder))*
2834 this.params.tileRowsPerFolder;0>a.tilecol&&(e="-");e=0==a.tilecol?e+"0":e+Math.floor(Math.abs(a.tilecol/this.params.tileColumnsPerFolder))*this.params.tileColumnsPerFolder;d="/S"+Math.floor(a.scaleindex)+"/"+this.params.basemaplayergroupname+"/R"+d+"/C"+e+"/"+a.tilerow%this.params.tileRowsPerFolder+"_"+a.tilecol%this.params.tileColumnsPerFolder+"."+this.params.format;this.params.querystring&&(d+="?"+this.params.querystring);return c+d},CLASS_NAME:"OpenLayers.Layer.MapGuide"});OpenLayers.Control.Measure=OpenLayers.Class(OpenLayers.Control,{callbacks:null,displaySystem:"metric",geodesic:!1,displaySystemUnits:{geographic:["dd"],english:["mi","ft","in"],metric:["km","m"]},partialDelay:300,delayedTrigger:null,persist:!1,immediate:!1,initialize:function(a,b){OpenLayers.Control.prototype.initialize.apply(this,[b]);var c={done:this.measureComplete,point:this.measurePartial};this.immediate&&(c.modify=this.measureImmediate);this.callbacks=OpenLayers.Util.extend(c,this.callbacks);
2835 this.handlerOptions=OpenLayers.Util.extend({persist:this.persist},this.handlerOptions);this.handler=new a(this,this.callbacks,this.handlerOptions)},deactivate:function(){this.cancelDelay();return OpenLayers.Control.prototype.deactivate.apply(this,arguments)},cancel:function(){this.cancelDelay();this.handler.cancel()},setImmediate:function(a){(this.immediate=a)?this.callbacks.modify=this.measureImmediate:delete this.callbacks.modify},updateHandler:function(a,b){var c=this.active;c&&this.deactivate();
2836 this.handler=new a(this,this.callbacks,b);c&&this.activate()},measureComplete:function(a){this.cancelDelay();this.measure(a,"measure")},measurePartial:function(a,b){this.cancelDelay();b=b.clone();this.handler.freehandMode(this.handler.evt)?this.measure(b,"measurepartial"):this.delayedTrigger=window.setTimeout(OpenLayers.Function.bind(function(){this.delayedTrigger=null;this.measure(b,"measurepartial")},this),this.partialDelay)},measureImmediate:function(a,b,c){c&&!this.handler.freehandMode(this.handler.evt)&&
2837 (this.cancelDelay(),this.measure(b.geometry,"measurepartial"))},cancelDelay:function(){null!==this.delayedTrigger&&(window.clearTimeout(this.delayedTrigger),this.delayedTrigger=null)},measure:function(a,b){var c,d;-1<a.CLASS_NAME.indexOf("LineString")?(c=this.getBestLength(a),d=1):(c=this.getBestArea(a),d=2);this.events.triggerEvent(b,{measure:c[0],units:c[1],order:d,geometry:a})},getBestArea:function(a){for(var b=this.displaySystemUnits[this.displaySystem],c,d,e=0,f=b.length;e<f&&!(c=b[e],d=this.getArea(a,
2838 c),1<d);++e);return[d,c]},getArea:function(a,b){var c,d;this.geodesic?(c=a.getGeodesicArea(this.map.getProjectionObject()),d="m"):(c=a.getArea(),d=this.map.getUnits());var e=OpenLayers.INCHES_PER_UNIT[b];e&&(c*=Math.pow(OpenLayers.INCHES_PER_UNIT[d]/e,2));return c},getBestLength:function(a){for(var b=this.displaySystemUnits[this.displaySystem],c,d,e=0,f=b.length;e<f&&!(c=b[e],d=this.getLength(a,c),1<d);++e);return[d,c]},getLength:function(a,b){var c,d;this.geodesic?(c=a.getGeodesicLength(this.map.getProjectionObject()),
2839 d="m"):(c=a.getLength(),d=this.map.getUnits());var e=OpenLayers.INCHES_PER_UNIT[b];e&&(c*=OpenLayers.INCHES_PER_UNIT[d]/e);return c},CLASS_NAME:"OpenLayers.Control.Measure"});OpenLayers.Format.WMC.v1_0_0=OpenLayers.Class(OpenLayers.Format.WMC.v1,{VERSION:"1.0.0",schemaLocation:"http://www.opengis.net/context http://schemas.opengis.net/context/1.0.0/context.xsd",initialize:function(a){OpenLayers.Format.WMC.v1.prototype.initialize.apply(this,[a])},read_wmc_SRS:function(a,b){var c=this.getChildValue(b);"object"!=typeof a.projections&&(a.projections={});for(var c=c.split(/ +/),d=0,e=c.length;d<e;d++)a.projections[c[d]]=!0},write_wmc_Layer:function(a){var b=OpenLayers.Format.WMC.v1.prototype.write_wmc_Layer.apply(this,
2840 [a]);if(a.srs){var c=[],d;for(d in a.srs)c.push(d);b.appendChild(this.createElementDefaultNS("SRS",c.join(" ")))}b.appendChild(this.write_wmc_FormatList(a));b.appendChild(this.write_wmc_StyleList(a));a.dimensions&&b.appendChild(this.write_wmc_DimensionList(a));b.appendChild(this.write_wmc_LayerExtension(a))},CLASS_NAME:"OpenLayers.Format.WMC.v1_0_0"});OpenLayers.Popup.Anchored=OpenLayers.Class(OpenLayers.Popup,{relativePosition:null,keepInMap:!0,anchor:null,initialize:function(a,b,c,d,e,f,g){OpenLayers.Popup.prototype.initialize.apply(this,[a,b,c,d,f,g]);this.anchor=null!=e?e:{size:new OpenLayers.Size(0,0),offset:new OpenLayers.Pixel(0,0)}},destroy:function(){this.relativePosition=this.anchor=null;OpenLayers.Popup.prototype.destroy.apply(this,arguments)},show:function(){this.updatePosition();OpenLayers.Popup.prototype.show.apply(this,arguments)},
2841 moveTo:function(a){var b=this.relativePosition;this.relativePosition=this.calculateRelativePosition(a);OpenLayers.Popup.prototype.moveTo.call(this,this.calculateNewPx(a));this.relativePosition!=b&&this.updateRelativePosition()},setSize:function(a){OpenLayers.Popup.prototype.setSize.apply(this,arguments);if(this.lonlat&&this.map){var b=this.map.getLayerPxFromLonLat(this.lonlat);this.moveTo(b)}},calculateRelativePosition:function(a){a=this.map.getLonLatFromLayerPx(a);a=this.map.getExtent().determineQuadrant(a);
2842 return OpenLayers.Bounds.oppositeQuadrant(a)},updateRelativePosition:function(){},calculateNewPx:function(a){a=a.offset(this.anchor.offset);var b=this.size||this.contentSize,c="t"==this.relativePosition.charAt(0);a.y+=c?-b.h:this.anchor.size.h;c="l"==this.relativePosition.charAt(1);a.x+=c?-b.w:this.anchor.size.w;return a},CLASS_NAME:"OpenLayers.Popup.Anchored"});OpenLayers.Popup.Framed=OpenLayers.Class(OpenLayers.Popup.Anchored,{imageSrc:null,imageSize:null,isAlphaImage:!1,positionBlocks:null,blocks:null,fixedRelativePosition:!1,initialize:function(a,b,c,d,e,f,g){OpenLayers.Popup.Anchored.prototype.initialize.apply(this,arguments);this.fixedRelativePosition&&(this.updateRelativePosition(),this.calculateRelativePosition=function(a){return this.relativePosition});this.contentDiv.style.position="absolute";this.contentDiv.style.zIndex=1;f&&(this.closeDiv.style.zIndex=
2843 1);this.groupDiv.style.position="absolute";this.groupDiv.style.top="0px";this.groupDiv.style.left="0px";this.groupDiv.style.height="100%";this.groupDiv.style.width="100%"},destroy:function(){this.isAlphaImage=this.imageSize=this.imageSrc=null;this.fixedRelativePosition=!1;this.positionBlocks=null;for(var a=0;a<this.blocks.length;a++){var b=this.blocks[a];b.image&&b.div.removeChild(b.image);b.image=null;b.div&&this.groupDiv.removeChild(b.div);b.div=null}this.blocks=null;OpenLayers.Popup.Anchored.prototype.destroy.apply(this,
2844 arguments)},setBackgroundColor:function(a){},setBorder:function(){},setOpacity:function(a){},setSize:function(a){OpenLayers.Popup.Anchored.prototype.setSize.apply(this,arguments);this.updateBlocks()},updateRelativePosition:function(){this.padding=this.positionBlocks[this.relativePosition].padding;if(this.closeDiv){var a=this.getContentDivPadding();this.closeDiv.style.right=a.right+this.padding.right+"px";this.closeDiv.style.top=a.top+this.padding.top+"px"}this.updateBlocks()},calculateNewPx:function(a){var b=
2845 OpenLayers.Popup.Anchored.prototype.calculateNewPx.apply(this,arguments);return b=b.offset(this.positionBlocks[this.relativePosition].offset)},createBlocks:function(){this.blocks=[];var a=null,b;for(b in this.positionBlocks){a=b;break}a=this.positionBlocks[a];for(b=0;b<a.blocks.length;b++){var c={};this.blocks.push(c);c.div=OpenLayers.Util.createDiv(this.id+"_FrameDecorationDiv_"+b,null,null,null,"absolute",null,"hidden",null);c.image=(this.isAlphaImage?OpenLayers.Util.createAlphaImageDiv:OpenLayers.Util.createImage)(this.id+
2846 "_FrameDecorationImg_"+b,null,this.imageSize,this.imageSrc,"absolute",null,null,null);c.div.appendChild(c.image);this.groupDiv.appendChild(c.div)}},updateBlocks:function(){this.blocks||this.createBlocks();if(this.size&&this.relativePosition){for(var a=this.positionBlocks[this.relativePosition],b=0;b<a.blocks.length;b++){var c=a.blocks[b],d=this.blocks[b],e=c.anchor.left,f=c.anchor.bottom,g=c.anchor.right,h=c.anchor.top,k=isNaN(c.size.w)?this.size.w-(g+e):c.size.w,l=isNaN(c.size.h)?this.size.h-(f+
2847 h):c.size.h;d.div.style.width=(0>k?0:k)+"px";d.div.style.height=(0>l?0:l)+"px";d.div.style.left=null!=e?e+"px":"";d.div.style.bottom=null!=f?f+"px":"";d.div.style.right=null!=g?g+"px":"";d.div.style.top=null!=h?h+"px":"";d.image.style.left=c.position.x+"px";d.image.style.top=c.position.y+"px"}this.contentDiv.style.left=this.padding.left+"px";this.contentDiv.style.top=this.padding.top+"px"}},CLASS_NAME:"OpenLayers.Popup.Framed"});OpenLayers.Popup.FramedCloud=OpenLayers.Class(OpenLayers.Popup.Framed,{contentDisplayClass:"olFramedCloudPopupContent",autoSize:!0,panMapIfOutOfView:!0,imageSize:new OpenLayers.Size(1276,736),isAlphaImage:!1,fixedRelativePosition:!1,positionBlocks:{tl:{offset:new OpenLayers.Pixel(44,0),padding:new OpenLayers.Bounds(8,40,8,9),blocks:[{size:new OpenLayers.Size("auto","auto"),anchor:new OpenLayers.Bounds(0,51,22,0),position:new OpenLayers.Pixel(0,0)},{size:new OpenLayers.Size(22,"auto"),anchor:new OpenLayers.Bounds(null,
2848 50,0,0),position:new OpenLayers.Pixel(-1238,0)},{size:new OpenLayers.Size("auto",19),anchor:new OpenLayers.Bounds(0,32,22,null),position:new OpenLayers.Pixel(0,-631)},{size:new OpenLayers.Size(22,18),anchor:new OpenLayers.Bounds(null,32,0,null),position:new OpenLayers.Pixel(-1238,-632)},{size:new OpenLayers.Size(81,35),anchor:new OpenLayers.Bounds(null,0,0,null),position:new OpenLayers.Pixel(0,-688)}]},tr:{offset:new OpenLayers.Pixel(-45,0),padding:new OpenLayers.Bounds(8,40,8,9),blocks:[{size:new OpenLayers.Size("auto",
2849 "auto"),anchor:new OpenLayers.Bounds(0,51,22,0),position:new OpenLayers.Pixel(0,0)},{size:new OpenLayers.Size(22,"auto"),anchor:new OpenLayers.Bounds(null,50,0,0),position:new OpenLayers.Pixel(-1238,0)},{size:new OpenLayers.Size("auto",19),anchor:new OpenLayers.Bounds(0,32,22,null),position:new OpenLayers.Pixel(0,-631)},{size:new OpenLayers.Size(22,19),anchor:new OpenLayers.Bounds(null,32,0,null),position:new OpenLayers.Pixel(-1238,-631)},{size:new OpenLayers.Size(81,35),anchor:new OpenLayers.Bounds(0,
2850 0,null,null),position:new OpenLayers.Pixel(-215,-687)}]},bl:{offset:new OpenLayers.Pixel(45,0),padding:new OpenLayers.Bounds(8,9,8,40),blocks:[{size:new OpenLayers.Size("auto","auto"),anchor:new OpenLayers.Bounds(0,21,22,32),position:new OpenLayers.Pixel(0,0)},{size:new OpenLayers.Size(22,"auto"),anchor:new OpenLayers.Bounds(null,21,0,32),position:new OpenLayers.Pixel(-1238,0)},{size:new OpenLayers.Size("auto",21),anchor:new OpenLayers.Bounds(0,0,22,null),position:new OpenLayers.Pixel(0,-629)},{size:new OpenLayers.Size(22,
2851 21),anchor:new OpenLayers.Bounds(null,0,0,null),position:new OpenLayers.Pixel(-1238,-629)},{size:new OpenLayers.Size(81,33),anchor:new OpenLayers.Bounds(null,null,0,0),position:new OpenLayers.Pixel(-101,-674)}]},br:{offset:new OpenLayers.Pixel(-44,0),padding:new OpenLayers.Bounds(8,9,8,40),blocks:[{size:new OpenLayers.Size("auto","auto"),anchor:new OpenLayers.Bounds(0,21,22,32),position:new OpenLayers.Pixel(0,0)},{size:new OpenLayers.Size(22,"auto"),anchor:new OpenLayers.Bounds(null,21,0,32),position:new OpenLayers.Pixel(-1238,
2852 0)},{size:new OpenLayers.Size("auto",21),anchor:new OpenLayers.Bounds(0,0,22,null),position:new OpenLayers.Pixel(0,-629)},{size:new OpenLayers.Size(22,21),anchor:new OpenLayers.Bounds(null,0,0,null),position:new OpenLayers.Pixel(-1238,-629)},{size:new OpenLayers.Size(81,33),anchor:new OpenLayers.Bounds(0,null,null,0),position:new OpenLayers.Pixel(-311,-674)}]}},minSize:new OpenLayers.Size(105,10),maxSize:new OpenLayers.Size(1200,660),initialize:function(a,b,c,d,e,f,g){this.imageSrc=OpenLayers.Util.getImageLocation("cloud-popup-relative.png");
2853 OpenLayers.Popup.Framed.prototype.initialize.apply(this,arguments);this.contentDiv.className=this.contentDisplayClass},CLASS_NAME:"OpenLayers.Popup.FramedCloud"});OpenLayers.Tile.Image.IFrame={useIFrame:null,blankImageUrl:"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAQAIBRAA7",draw:function(){if(OpenLayers.Tile.Image.prototype.shouldDraw.call(this)){var a=this.layer.getURL(this.bounds),b=this.useIFrame;this.useIFrame=null!==this.maxGetUrlLength&&!this.layer.async&&a.length>this.maxGetUrlLength;a=b&&!this.useIFrame;b=!b&&this.useIFrame;if(a||b)this.imgDiv&&this.imgDiv.parentNode===this.frame&&this.frame.removeChild(this.imgDiv),this.imgDiv=
2854 null,a&&this.frame.removeChild(this.frame.firstChild)}return OpenLayers.Tile.Image.prototype.draw.apply(this,arguments)},getImage:function(){if(!0===this.useIFrame){if(!this.frame.childNodes.length){var a=document.createElement("div"),b=a.style;b.position="absolute";b.width="100%";b.height="100%";b.zIndex=1;b.backgroundImage="url("+this.blankImageUrl+")";this.frame.appendChild(a)}a=this.id+"_iFrame";9>parseFloat(navigator.appVersion.split("MSIE")[1])?(b=document.createElement('<iframe name="'+a+'">'),
2855 b.style.backgroundColor="#FFFFFF",b.style.filter="chroma(color=#FFFFFF)"):(b=document.createElement("iframe"),b.style.backgroundColor="transparent",b.name=a);b.scrolling="no";b.marginWidth="0px";b.marginHeight="0px";b.frameBorder="0";b.style.position="absolute";b.style.width="100%";b.style.height="100%";1>this.layer.opacity&&OpenLayers.Util.modifyDOMElement(b,null,null,null,null,null,null,this.layer.opacity);this.frame.appendChild(b);return this.imgDiv=b}return OpenLayers.Tile.Image.prototype.getImage.apply(this,
2856 arguments)},createRequestForm:function(){var a=document.createElement("form");a.method="POST";var b=this.layer.params._OLSALT,b=(b?b+"_":"")+this.bounds.toBBOX();a.action=OpenLayers.Util.urlAppend(this.layer.url,b);a.target=this.id+"_iFrame";this.layer.getImageSize();var b=OpenLayers.Util.getParameters(this.url),c,d;for(d in b)c=document.createElement("input"),c.type="hidden",c.name=d,c.value=b[d],a.appendChild(c);return a},setImgSrc:function(a){if(!0===this.useIFrame)if(a){var b=this.createRequestForm();
2857 this.frame.appendChild(b);b.submit();this.frame.removeChild(b)}else this.imgDiv.parentNode===this.frame&&(this.frame.removeChild(this.imgDiv),this.imgDiv=null);else OpenLayers.Tile.Image.prototype.setImgSrc.apply(this,arguments)},onImageLoad:function(){OpenLayers.Tile.Image.prototype.onImageLoad.apply(this,arguments);!0===this.useIFrame&&(this.imgDiv.style.opacity=1,this.frame.style.opacity=this.layer.opacity)},createBackBuffer:function(){var a;!1===this.useIFrame&&(a=OpenLayers.Tile.Image.prototype.createBackBuffer.call(this));
2858 return a}};OpenLayers.Format.SOSCapabilities=OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC,{defaultVersion:"1.0.0",CLASS_NAME:"OpenLayers.Format.SOSCapabilities"});OpenLayers.Format.SOSCapabilities.v1_0_0=OpenLayers.Class(OpenLayers.Format.SOSCapabilities,{namespaces:{ows:"http://www.opengis.net/ows/1.1",sos:"http://www.opengis.net/sos/1.0",gml:"http://www.opengis.net/gml",xlink:"http://www.w3.org/1999/xlink"},regExes:{trimSpace:/^\s*|\s*$/g,removeSpace:/\s*/g,splitSpace:/\s+/,trimComma:/\s*,\s*/g},initialize:function(a){OpenLayers.Format.XML.prototype.initialize.apply(this,[a]);this.options=a},read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,
2859 [a]));a&&9==a.nodeType&&(a=a.documentElement);var b={};this.readNode(a,b);return b},readers:{gml:OpenLayers.Util.applyDefaults({name:function(a,b){b.name=this.getChildValue(a)},TimePeriod:function(a,b){b.timePeriod={};this.readChildNodes(a,b.timePeriod)},beginPosition:function(a,b){b.beginPosition=this.getChildValue(a)},endPosition:function(a,b){b.endPosition=this.getChildValue(a)}},OpenLayers.Format.GML.v3.prototype.readers.gml),sos:{Capabilities:function(a,b){this.readChildNodes(a,b)},Contents:function(a,
2860 b){b.contents={};this.readChildNodes(a,b.contents)},ObservationOfferingList:function(a,b){b.offeringList={};this.readChildNodes(a,b.offeringList)},ObservationOffering:function(a,b){var c=this.getAttributeNS(a,this.namespaces.gml,"id");b[c]={procedures:[],observedProperties:[],featureOfInterestIds:[],responseFormats:[],resultModels:[],responseModes:[]};this.readChildNodes(a,b[c])},time:function(a,b){b.time={};this.readChildNodes(a,b.time)},procedure:function(a,b){b.procedures.push(this.getAttributeNS(a,
2861 this.namespaces.xlink,"href"))},observedProperty:function(a,b){b.observedProperties.push(this.getAttributeNS(a,this.namespaces.xlink,"href"))},featureOfInterest:function(a,b){b.featureOfInterestIds.push(this.getAttributeNS(a,this.namespaces.xlink,"href"))},responseFormat:function(a,b){b.responseFormats.push(this.getChildValue(a))},resultModel:function(a,b){b.resultModels.push(this.getChildValue(a))},responseMode:function(a,b){b.responseModes.push(this.getChildValue(a))}},ows:OpenLayers.Format.OWSCommon.v1_1_0.prototype.readers.ows},
2862 CLASS_NAME:"OpenLayers.Format.SOSCapabilities.v1_0_0"});OpenLayers.Handler.Pinch=OpenLayers.Class(OpenLayers.Handler,{started:!1,stopDown:!1,pinching:!1,last:null,start:null,touchstart:function(a){var b=!0;this.pinching=!1;if(OpenLayers.Event.isMultiTouch(a))this.started=!0,this.last=this.start={distance:this.getDistance(a.touches),delta:0,scale:1},this.callback("start",[a,this.start]),b=!this.stopDown;else{if(this.started)return!1;this.started=!1;this.last=this.start=null}OpenLayers.Event.preventDefault(a);return b},touchmove:function(a){if(this.started&&
2863 OpenLayers.Event.isMultiTouch(a)){this.pinching=!0;var b=this.getPinchData(a);this.callback("move",[a,b]);this.last=b;OpenLayers.Event.stop(a)}else if(this.started)return!1;return!0},touchend:function(a){return this.started&&!OpenLayers.Event.isMultiTouch(a)?(this.pinching=this.started=!1,this.callback("done",[a,this.start,this.last]),this.last=this.start=null,!1):!0},activate:function(){var a=!1;OpenLayers.Handler.prototype.activate.apply(this,arguments)&&(this.pinching=!1,a=!0);return a},deactivate:function(){var a=
2864 !1;OpenLayers.Handler.prototype.deactivate.apply(this,arguments)&&(this.pinching=this.started=!1,this.last=this.start=null,a=!0);return a},getDistance:function(a){var b=a[0];a=a[1];return Math.sqrt(Math.pow(b.olClientX-a.olClientX,2)+Math.pow(b.olClientY-a.olClientY,2))},getPinchData:function(a){a=this.getDistance(a.touches);return{distance:a,delta:this.last.distance-a,scale:a/this.start.distance}},CLASS_NAME:"OpenLayers.Handler.Pinch"});OpenLayers.Control.NavToolbar=OpenLayers.Class(OpenLayers.Control.Panel,{initialize:function(a){OpenLayers.Control.Panel.prototype.initialize.apply(this,[a]);this.addControls([new OpenLayers.Control.Navigation,new OpenLayers.Control.ZoomBox])},draw:function(){var a=OpenLayers.Control.Panel.prototype.draw.apply(this,arguments);null===this.defaultControl&&(this.defaultControl=this.controls[0]);return a},CLASS_NAME:"OpenLayers.Control.NavToolbar"});OpenLayers.Strategy.Refresh=OpenLayers.Class(OpenLayers.Strategy,{force:!1,interval:0,timer:null,activate:function(){var a=OpenLayers.Strategy.prototype.activate.call(this);a&&(!0===this.layer.visibility&&this.start(),this.layer.events.on({visibilitychanged:this.reset,scope:this}));return a},deactivate:function(){var a=OpenLayers.Strategy.prototype.deactivate.call(this);a&&(this.stop(),this.layer.events.un({visibilitychanged:this.reset,scope:this}));return a},reset:function(){!0===this.layer.visibility?
2865 this.start():this.stop()},start:function(){this.interval&&("number"===typeof this.interval&&0<this.interval)&&(this.timer=window.setInterval(OpenLayers.Function.bind(this.refresh,this),this.interval))},refresh:function(){this.layer&&(this.layer.refresh&&"function"==typeof this.layer.refresh)&&this.layer.refresh({force:this.force})},stop:function(){null!==this.timer&&(window.clearInterval(this.timer),this.timer=null)},CLASS_NAME:"OpenLayers.Strategy.Refresh"});OpenLayers.Layer.ArcGIS93Rest=OpenLayers.Class(OpenLayers.Layer.Grid,{DEFAULT_PARAMS:{format:"png"},isBaseLayer:!0,initialize:function(a,b,c,d){var e=[];c=OpenLayers.Util.upperCaseObject(c);e.push(a,b,c,d);OpenLayers.Layer.Grid.prototype.initialize.apply(this,e);OpenLayers.Util.applyDefaults(this.params,OpenLayers.Util.upperCaseObject(this.DEFAULT_PARAMS));this.params.TRANSPARENT&&"true"==this.params.TRANSPARENT.toString().toLowerCase()&&(null!=d&&d.isBaseLayer||(this.isBaseLayer=!1),"jpg"==this.params.FORMAT&&
2866 (this.params.FORMAT=OpenLayers.Util.alphaHack()?"gif":"png"))},clone:function(a){null==a&&(a=new OpenLayers.Layer.ArcGIS93Rest(this.name,this.url,this.params,this.getOptions()));return a=OpenLayers.Layer.Grid.prototype.clone.apply(this,[a])},getURL:function(a){a=this.adjustBounds(a);var b=this.projection.getCode().split(":"),b=b[b.length-1],c=this.getImageSize();a={BBOX:a.toBBOX(),SIZE:c.w+","+c.h,F:"image",BBOXSR:b,IMAGESR:b};if(this.layerDefs){var b=[],d;for(d in this.layerDefs)this.layerDefs.hasOwnProperty(d)&&
2867 this.layerDefs[d]&&(b.push(d),b.push(":"),b.push(this.layerDefs[d]),b.push(";"));0<b.length&&(a.LAYERDEFS=b.join(""))}return this.getFullRequestString(a)},setLayerFilter:function(a,b){this.layerDefs||(this.layerDefs={});b?this.layerDefs[a]=b:delete this.layerDefs[a]},clearLayerFilter:function(a){a?delete this.layerDefs[a]:delete this.layerDefs},mergeNewParams:function(a){a=[OpenLayers.Util.upperCaseObject(a)];return OpenLayers.Layer.Grid.prototype.mergeNewParams.apply(this,a)},CLASS_NAME:"OpenLayers.Layer.ArcGIS93Rest"});OpenLayers.Handler.Hover=OpenLayers.Class(OpenLayers.Handler,{delay:500,pixelTolerance:null,stopMove:!1,px:null,timerId:null,mousemove:function(a){this.passesTolerance(a.xy)&&(this.clearTimer(),this.callback("move",[a]),this.px=a.xy,a=OpenLayers.Util.extend({},a),this.timerId=window.setTimeout(OpenLayers.Function.bind(this.delayedCall,this,a),this.delay));return!this.stopMove},mouseout:function(a){OpenLayers.Util.mouseLeft(a,this.map.viewPortDiv)&&(this.clearTimer(),this.callback("move",[a]));return!0},
2868 passesTolerance:function(a){var b=!0;this.pixelTolerance&&this.px&&Math.sqrt(Math.pow(this.px.x-a.x,2)+Math.pow(this.px.y-a.y,2))<this.pixelTolerance&&(b=!1);return b},clearTimer:function(){null!=this.timerId&&(window.clearTimeout(this.timerId),this.timerId=null)},delayedCall:function(a){this.callback("pause",[a])},deactivate:function(){var a=!1;OpenLayers.Handler.prototype.deactivate.apply(this,arguments)&&(this.clearTimer(),a=!0);return a},CLASS_NAME:"OpenLayers.Handler.Hover"});OpenLayers.Control.GetFeature=OpenLayers.Class(OpenLayers.Control,{protocol:null,multipleKey:null,toggleKey:null,modifiers:null,multiple:!1,click:!0,single:!0,clickout:!0,toggle:!1,clickTolerance:5,hover:!1,box:!1,maxFeatures:10,features:null,hoverFeature:null,handlers:null,hoverResponse:null,filterType:OpenLayers.Filter.Spatial.BBOX,initialize:function(a){a.handlerOptions=a.handlerOptions||{};OpenLayers.Control.prototype.initialize.apply(this,[a]);this.features={};this.handlers={};this.click&&(this.handlers.click=
2869 new OpenLayers.Handler.Click(this,{click:this.selectClick},this.handlerOptions.click||{}));this.box&&(this.handlers.box=new OpenLayers.Handler.Box(this,{done:this.selectBox},OpenLayers.Util.extend(this.handlerOptions.box,{boxDivClassName:"olHandlerBoxSelectFeature"})));this.hover&&(this.handlers.hover=new OpenLayers.Handler.Hover(this,{move:this.cancelHover,pause:this.selectHover},OpenLayers.Util.extend(this.handlerOptions.hover,{delay:250,pixelTolerance:2})))},activate:function(){if(!this.active)for(var a in this.handlers)this.handlers[a].activate();
2870 return OpenLayers.Control.prototype.activate.apply(this,arguments)},deactivate:function(){if(this.active)for(var a in this.handlers)this.handlers[a].deactivate();return OpenLayers.Control.prototype.deactivate.apply(this,arguments)},selectClick:function(a){var b=this.pixelToBounds(a.xy);this.setModifiers(a);this.request(b,{single:this.single})},selectBox:function(a){var b;if(a instanceof OpenLayers.Bounds)b=this.map.getLonLatFromPixel({x:a.left,y:a.bottom}),a=this.map.getLonLatFromPixel({x:a.right,
2871 y:a.top}),b=new OpenLayers.Bounds(b.lon,b.lat,a.lon,a.lat);else{if(this.click)return;b=this.pixelToBounds(a)}this.setModifiers(this.handlers.box.dragHandler.evt);this.request(b)},selectHover:function(a){a=this.pixelToBounds(a.xy);this.request(a,{single:!0,hover:!0})},cancelHover:function(){this.hoverResponse&&(this.protocol.abort(this.hoverResponse),this.hoverResponse=null,OpenLayers.Element.removeClass(this.map.viewPortDiv,"olCursorWait"))},request:function(a,b){b=b||{};var c=new OpenLayers.Filter.Spatial({type:this.filterType,
2872 value:a});OpenLayers.Element.addClass(this.map.viewPortDiv,"olCursorWait");c=this.protocol.read({maxFeatures:!0==b.single?this.maxFeatures:void 0,filter:c,callback:function(c){c.success()&&(c.features.length?!0==b.single?this.selectBestFeature(c.features,a.getCenterLonLat(),b):this.select(c.features):b.hover?this.hoverSelect():(this.events.triggerEvent("clickout"),this.clickout&&this.unselectAll()));OpenLayers.Element.removeClass(this.map.viewPortDiv,"olCursorWait")},scope:this});!0==b.hover&&(this.hoverResponse=
2873 c)},selectBestFeature:function(a,b,c){c=c||{};if(a.length){b=new OpenLayers.Geometry.Point(b.lon,b.lat);for(var d,e,f,g=Number.MAX_VALUE,h=0;h<a.length&&!(d=a[h],d.geometry&&(f=b.distanceTo(d.geometry,{edge:!1}),f<g&&(g=f,e=d,0==g)));++h);!0==c.hover?this.hoverSelect(e):this.select(e||a)}},setModifiers:function(a){this.modifiers={multiple:this.multiple||this.multipleKey&&a[this.multipleKey],toggle:this.toggle||this.toggleKey&&a[this.toggleKey]}},select:function(a){this.modifiers.multiple||this.modifiers.toggle||
2874 this.unselectAll();OpenLayers.Util.isArray(a)||(a=[a]);var b=this.events.triggerEvent("beforefeaturesselected",{features:a});if(!1!==b){for(var c=[],d,e=0,f=a.length;e<f;++e)d=a[e],this.features[d.fid||d.id]?this.modifiers.toggle&&this.unselect(this.features[d.fid||d.id]):(b=this.events.triggerEvent("beforefeatureselected",{feature:d}),!1!==b&&(this.features[d.fid||d.id]=d,c.push(d),this.events.triggerEvent("featureselected",{feature:d})));this.events.triggerEvent("featuresselected",{features:c})}},
2875 hoverSelect:function(a){var b=a?a.fid||a.id:null,c=this.hoverFeature?this.hoverFeature.fid||this.hoverFeature.id:null;c&&c!=b&&(this.events.triggerEvent("outfeature",{feature:this.hoverFeature}),this.hoverFeature=null);b&&b!=c&&(this.events.triggerEvent("hoverfeature",{feature:a}),this.hoverFeature=a)},unselect:function(a){delete this.features[a.fid||a.id];this.events.triggerEvent("featureunselected",{feature:a})},unselectAll:function(){for(var a in this.features)this.unselect(this.features[a])},
2876 setMap:function(a){for(var b in this.handlers)this.handlers[b].setMap(a);OpenLayers.Control.prototype.setMap.apply(this,arguments)},pixelToBounds:function(a){var b=a.add(-this.clickTolerance/2,this.clickTolerance/2);a=a.add(this.clickTolerance/2,-this.clickTolerance/2);b=this.map.getLonLatFromPixel(b);a=this.map.getLonLatFromPixel(a);return new OpenLayers.Bounds(b.lon,b.lat,a.lon,a.lat)},CLASS_NAME:"OpenLayers.Control.GetFeature"});OpenLayers.Format.QueryStringFilter=function(){function a(a){a=a.replace(/%/g,"\\%");a=a.replace(/\\\\\.(\*)?/g,function(a,b){return b?a:"\\\\_"});a=a.replace(/\\\\\.\*/g,"\\\\%");a=a.replace(/(\\)?\.(\*)?/g,function(a,b,c){return b||c?a:"_"});a=a.replace(/(\\)?\.\*/g,function(a,b){return b?a:"%"});a=a.replace(/\\\./g,".");return a=a.replace(/(\\)?\\\*/g,function(a,b){return b?a:"*"})}var b={};b[OpenLayers.Filter.Comparison.EQUAL_TO]="eq";b[OpenLayers.Filter.Comparison.NOT_EQUAL_TO]="ne";b[OpenLayers.Filter.Comparison.LESS_THAN]=
2877 "lt";b[OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO]="lte";b[OpenLayers.Filter.Comparison.GREATER_THAN]="gt";b[OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO]="gte";b[OpenLayers.Filter.Comparison.LIKE]="ilike";return OpenLayers.Class(OpenLayers.Format,{wildcarded:!1,srsInBBOX:!1,write:function(c,d){d=d||{};var e=c.CLASS_NAME,e=e.substring(e.lastIndexOf(".")+1);switch(e){case "Spatial":switch(c.type){case OpenLayers.Filter.Spatial.BBOX:d.bbox=c.value.toArray();this.srsInBBOX&&c.projection&&
2878 d.bbox.push(c.projection.getCode());break;case OpenLayers.Filter.Spatial.DWITHIN:d.tolerance=c.distance;case OpenLayers.Filter.Spatial.WITHIN:d.lon=c.value.x;d.lat=c.value.y;break;default:OpenLayers.Console.warn("Unknown spatial filter type "+c.type)}break;case "Comparison":e=b[c.type];if(void 0!==e){var f=c.value;c.type==OpenLayers.Filter.Comparison.LIKE&&(f=a(f),this.wildcarded&&(f="%"+f+"%"));d[c.property+"__"+e]=f;d.queryable=d.queryable||[];d.queryable.push(c.property)}else OpenLayers.Console.warn("Unknown comparison filter type "+
2879 c.type);break;case "Logical":if(c.type===OpenLayers.Filter.Logical.AND)for(e=0,f=c.filters.length;e<f;e++)d=this.write(c.filters[e],d);else OpenLayers.Console.warn("Unsupported logical filter type "+c.type);break;default:OpenLayers.Console.warn("Unknown filter type "+e)}return d},CLASS_NAME:"OpenLayers.Format.QueryStringFilter"})}();OpenLayers.Control.MousePosition=OpenLayers.Class(OpenLayers.Control,{autoActivate:!0,element:null,prefix:"",separator:", ",suffix:"",numDigits:5,granularity:10,emptyString:null,lastXy:null,displayProjection:null,destroy:function(){this.deactivate();OpenLayers.Control.prototype.destroy.apply(this,arguments)},activate:function(){return OpenLayers.Control.prototype.activate.apply(this,arguments)?(this.map.events.register("mousemove",this,this.redraw),this.map.events.register("mouseout",this,this.reset),
2880 this.redraw(),!0):!1},deactivate:function(){return OpenLayers.Control.prototype.deactivate.apply(this,arguments)?(this.map.events.unregister("mousemove",this,this.redraw),this.map.events.unregister("mouseout",this,this.reset),this.element.innerHTML="",!0):!1},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);this.element||(this.div.left="",this.div.top="",this.element=this.div);return this.div},redraw:function(a){var b;if(null==a)this.reset();else if(null==this.lastXy||Math.abs(a.xy.x-
2881 this.lastXy.x)>this.granularity||Math.abs(a.xy.y-this.lastXy.y)>this.granularity)this.lastXy=a.xy;else if(b=this.map.getLonLatFromPixel(a.xy))this.displayProjection&&b.transform(this.map.getProjectionObject(),this.displayProjection),this.lastXy=a.xy,a=this.formatOutput(b),a!=this.element.innerHTML&&(this.element.innerHTML=a)},reset:function(a){null!=this.emptyString&&(this.element.innerHTML=this.emptyString)},formatOutput:function(a){var b=parseInt(this.numDigits);return this.prefix+a.lon.toFixed(b)+
2882 this.separator+a.lat.toFixed(b)+this.suffix},CLASS_NAME:"OpenLayers.Control.MousePosition"});OpenLayers.Control.Geolocate=OpenLayers.Class(OpenLayers.Control,{geolocation:null,available:"geolocation"in navigator,bind:!0,watch:!1,geolocationOptions:null,destroy:function(){this.deactivate();OpenLayers.Control.prototype.destroy.apply(this,arguments)},activate:function(){this.available&&!this.geolocation&&(this.geolocation=navigator.geolocation);return this.geolocation?OpenLayers.Control.prototype.activate.apply(this,arguments)?(this.watch?this.watchId=this.geolocation.watchPosition(OpenLayers.Function.bind(this.geolocate,
2883 this),OpenLayers.Function.bind(this.failure,this),this.geolocationOptions):this.getCurrentLocation(),!0):!1:(this.events.triggerEvent("locationuncapable"),!1)},deactivate:function(){this.active&&null!==this.watchId&&this.geolocation.clearWatch(this.watchId);return OpenLayers.Control.prototype.deactivate.apply(this,arguments)},geolocate:function(a){var b=(new OpenLayers.LonLat(a.coords.longitude,a.coords.latitude)).transform(new OpenLayers.Projection("EPSG:4326"),this.map.getProjectionObject());this.bind&&
2884 this.map.setCenter(b);this.events.triggerEvent("locationupdated",{position:a,point:new OpenLayers.Geometry.Point(b.lon,b.lat)})},getCurrentLocation:function(){if(!this.active||this.watch)return!1;this.geolocation.getCurrentPosition(OpenLayers.Function.bind(this.geolocate,this),OpenLayers.Function.bind(this.failure,this),this.geolocationOptions);return!0},failure:function(a){this.events.triggerEvent("locationfailed",{error:a})},CLASS_NAME:"OpenLayers.Control.Geolocate"});OpenLayers.Tile.UTFGrid=OpenLayers.Class(OpenLayers.Tile,{url:null,utfgridResolution:2,json:null,format:null,destroy:function(){this.clear();OpenLayers.Tile.prototype.destroy.apply(this,arguments)},draw:function(){var a=OpenLayers.Tile.prototype.draw.apply(this,arguments);if(a)if(this.isLoading?(this.abortLoading(),this.events.triggerEvent("reload")):(this.isLoading=!0,this.events.triggerEvent("loadstart")),this.url=this.layer.getURL(this.bounds),this.layer.useJSONP){var b=new OpenLayers.Protocol.Script({url:this.url,
2885 callback:function(a){this.isLoading=!1;this.events.triggerEvent("loadend");this.json=a.data},scope:this});b.read();this.request=b}else this.request=OpenLayers.Request.GET({url:this.url,callback:function(a){this.isLoading=!1;this.events.triggerEvent("loadend");200===a.status&&this.parseData(a.responseText)},scope:this});else this.unload();return a},abortLoading:function(){this.request&&(this.request.abort(),delete this.request);this.isLoading=!1},getFeatureInfo:function(a,b){var c=null;if(this.json){var d=
2886 this.getFeatureId(a,b);null!==d&&(c={id:d,data:this.json.data[d]})}return c},getFeatureId:function(a,b){var c=null;if(this.json){var d=this.utfgridResolution,d=this.json.grid[Math.floor(b/d)].charCodeAt(Math.floor(a/d)),d=this.indexFromCharCode(d),e=this.json.keys;!isNaN(d)&&d in e&&(c=e[d])}return c},indexFromCharCode:function(a){93<=a&&a--;35<=a&&a--;return a-32},parseData:function(a){this.format||(this.format=new OpenLayers.Format.JSON);this.json=this.format.read(a)},clear:function(){this.json=
2887 null},CLASS_NAME:"OpenLayers.Tile.UTFGrid"});OpenLayers.Protocol.HTTP=OpenLayers.Class(OpenLayers.Protocol,{url:null,headers:null,params:null,callback:null,scope:null,readWithPOST:!1,updateWithPOST:!1,deleteWithPOST:!1,wildcarded:!1,srsInBBOX:!1,initialize:function(a){a=a||{};this.params={};this.headers={};OpenLayers.Protocol.prototype.initialize.apply(this,arguments);if(!this.filterToParams&&OpenLayers.Format.QueryStringFilter){var b=new OpenLayers.Format.QueryStringFilter({wildcarded:this.wildcarded,srsInBBOX:this.srsInBBOX});this.filterToParams=
2888 function(a,d){return b.write(a,d)}}},destroy:function(){this.headers=this.params=null;OpenLayers.Protocol.prototype.destroy.apply(this)},read:function(a){OpenLayers.Protocol.prototype.read.apply(this,arguments);a=a||{};a.params=OpenLayers.Util.applyDefaults(a.params,this.options.params);a=OpenLayers.Util.applyDefaults(a,this.options);a.filter&&this.filterToParams&&(a.params=this.filterToParams(a.filter,a.params));var b=void 0!==a.readWithPOST?a.readWithPOST:this.readWithPOST,c=new OpenLayers.Protocol.Response({requestType:"read"});
2889 b?(b=a.headers||{},b["Content-Type"]="application/x-www-form-urlencoded",c.priv=OpenLayers.Request.POST({url:a.url,callback:this.createCallback(this.handleRead,c,a),data:OpenLayers.Util.getParameterString(a.params),headers:b})):c.priv=OpenLayers.Request.GET({url:a.url,callback:this.createCallback(this.handleRead,c,a),params:a.params,headers:a.headers});return c},handleRead:function(a,b){this.handleResponse(a,b)},create:function(a,b){b=OpenLayers.Util.applyDefaults(b,this.options);var c=new OpenLayers.Protocol.Response({reqFeatures:a,
2890 requestType:"create"});c.priv=OpenLayers.Request.POST({url:b.url,callback:this.createCallback(this.handleCreate,c,b),headers:b.headers,data:this.format.write(a)});return c},handleCreate:function(a,b){this.handleResponse(a,b)},update:function(a,b){b=b||{};var c=b.url||a.url||this.options.url+"/"+a.fid;b=OpenLayers.Util.applyDefaults(b,this.options);var d=new OpenLayers.Protocol.Response({reqFeatures:a,requestType:"update"});d.priv=OpenLayers.Request[this.updateWithPOST?"POST":"PUT"]({url:c,callback:this.createCallback(this.handleUpdate,
2891 d,b),headers:b.headers,data:this.format.write(a)});return d},handleUpdate:function(a,b){this.handleResponse(a,b)},"delete":function(a,b){b=b||{};var c=b.url||a.url||this.options.url+"/"+a.fid;b=OpenLayers.Util.applyDefaults(b,this.options);var d=new OpenLayers.Protocol.Response({reqFeatures:a,requestType:"delete"}),e=this.deleteWithPOST?"POST":"DELETE",c={url:c,callback:this.createCallback(this.handleDelete,d,b),headers:b.headers};this.deleteWithPOST&&(c.data=this.format.write(a));d.priv=OpenLayers.Request[e](c);
2892 return d},handleDelete:function(a,b){this.handleResponse(a,b)},handleResponse:function(a,b){var c=a.priv;b.callback&&(200<=c.status&&300>c.status?("delete"!=a.requestType&&(a.features=this.parseFeatures(c)),a.code=OpenLayers.Protocol.Response.SUCCESS):a.code=OpenLayers.Protocol.Response.FAILURE,b.callback.call(b.scope,a))},parseFeatures:function(a){var b=a.responseXML;b&&b.documentElement||(b=a.responseText);return!b||0>=b.length?null:this.format.read(b)},commit:function(a,b){function c(a){for(var b=
2893 a.features?a.features.length:0,c=Array(b),e=0;e<b;++e)c[e]=a.features[e].fid;r.insertIds=c;d.apply(this,[a])}function d(a){this.callUserCallback(a,b);q=q&&a.success();f++;f>=p&&b.callback&&(r.code=q?OpenLayers.Protocol.Response.SUCCESS:OpenLayers.Protocol.Response.FAILURE,b.callback.apply(b.scope,[r]))}b=OpenLayers.Util.applyDefaults(b,this.options);var e=[],f=0,g={};g[OpenLayers.State.INSERT]=[];g[OpenLayers.State.UPDATE]=[];g[OpenLayers.State.DELETE]=[];for(var h,k,l=[],m=0,n=a.length;m<n;++m)if(h=
2894 a[m],k=g[h.state])k.push(h),l.push(h);var p=(0<g[OpenLayers.State.INSERT].length?1:0)+g[OpenLayers.State.UPDATE].length+g[OpenLayers.State.DELETE].length,q=!0,r=new OpenLayers.Protocol.Response({reqFeatures:l});h=g[OpenLayers.State.INSERT];0<h.length&&e.push(this.create(h,OpenLayers.Util.applyDefaults({callback:c,scope:this},b.create)));h=g[OpenLayers.State.UPDATE];for(m=h.length-1;0<=m;--m)e.push(this.update(h[m],OpenLayers.Util.applyDefaults({callback:d,scope:this},b.update)));h=g[OpenLayers.State.DELETE];
2895 for(m=h.length-1;0<=m;--m)e.push(this["delete"](h[m],OpenLayers.Util.applyDefaults({callback:d,scope:this},b["delete"])));return e},abort:function(a){a&&a.priv.abort()},callUserCallback:function(a,b){var c=b[a.requestType];c&&c.callback&&c.callback.call(c.scope,a)},CLASS_NAME:"OpenLayers.Protocol.HTTP"});OpenLayers.Strategy.Cluster=OpenLayers.Class(OpenLayers.Strategy,{distance:20,threshold:null,features:null,clusters:null,clustering:!1,resolution:null,activate:function(){var a=OpenLayers.Strategy.prototype.activate.call(this);if(a)this.layer.events.on({beforefeaturesadded:this.cacheFeatures,featuresremoved:this.clearCache,moveend:this.cluster,scope:this});return a},deactivate:function(){var a=OpenLayers.Strategy.prototype.deactivate.call(this);a&&(this.clearCache(),this.layer.events.un({beforefeaturesadded:this.cacheFeatures,
2896 featuresremoved:this.clearCache,moveend:this.cluster,scope:this}));return a},cacheFeatures:function(a){var b=!0;this.clustering||(this.clearCache(),this.features=a.features,this.cluster(),b=!1);return b},clearCache:function(){this.clustering||(this.features=null)},cluster:function(a){if((!a||a.zoomChanged)&&this.features&&(a=this.layer.map.getResolution(),a!=this.resolution||!this.clustersExist())){this.resolution=a;a=[];for(var b,c,d,e=0;e<this.features.length;++e)if(b=this.features[e],b.geometry){c=
2897 !1;for(var f=a.length-1;0<=f;--f)if(d=a[f],this.shouldCluster(d,b)){this.addToCluster(d,b);c=!0;break}c||a.push(this.createCluster(this.features[e]))}this.clustering=!0;this.layer.removeAllFeatures();this.clustering=!1;if(0<a.length){if(1<this.threshold)for(b=a.slice(),a=[],e=0,d=b.length;e<d;++e)c=b[e],c.attributes.count<this.threshold?Array.prototype.push.apply(a,c.cluster):a.push(c);this.clustering=!0;this.layer.addFeatures(a);this.clustering=!1}this.clusters=a}},clustersExist:function(){var a=
2898 !1;if(this.clusters&&0<this.clusters.length&&this.clusters.length==this.layer.features.length)for(var a=!0,b=0;b<this.clusters.length;++b)if(this.clusters[b]!=this.layer.features[b]){a=!1;break}return a},shouldCluster:function(a,b){var c=a.geometry.getBounds().getCenterLonLat(),d=b.geometry.getBounds().getCenterLonLat();return Math.sqrt(Math.pow(c.lon-d.lon,2)+Math.pow(c.lat-d.lat,2))/this.resolution<=this.distance},addToCluster:function(a,b){a.cluster.push(b);a.attributes.count+=1},createCluster:function(a){var b=
2899 a.geometry.getBounds().getCenterLonLat(),b=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(b.lon,b.lat),{count:1});b.cluster=[a];return b},CLASS_NAME:"OpenLayers.Strategy.Cluster"});OpenLayers.Strategy.Filter=OpenLayers.Class(OpenLayers.Strategy,{filter:null,cache:null,caching:!1,activate:function(){var a=OpenLayers.Strategy.prototype.activate.apply(this,arguments);a&&(this.cache=[],this.layer.events.on({beforefeaturesadded:this.handleAdd,beforefeaturesremoved:this.handleRemove,scope:this}));return a},deactivate:function(){this.cache=null;this.layer&&this.layer.events&&this.layer.events.un({beforefeaturesadded:this.handleAdd,beforefeaturesremoved:this.handleRemove,scope:this});
2900 return OpenLayers.Strategy.prototype.deactivate.apply(this,arguments)},handleAdd:function(a){if(!this.caching&&this.filter){var b=a.features;a.features=[];for(var c,d=0,e=b.length;d<e;++d)c=b[d],this.filter.evaluate(c)?a.features.push(c):this.cache.push(c)}},handleRemove:function(a){this.caching||(this.cache=[])},setFilter:function(a){this.filter=a;a=this.cache;this.cache=[];this.handleAdd({features:this.layer.features});0<this.cache.length&&(this.caching=!0,this.layer.removeFeatures(this.cache.slice()),
2901 this.caching=!1);0<a.length&&(a={features:a},this.handleAdd(a),0<a.features.length&&(this.caching=!0,this.layer.addFeatures(a.features),this.caching=!1))},CLASS_NAME:"OpenLayers.Strategy.Filter"});OpenLayers.Protocol.SOS=function(a){a=OpenLayers.Util.applyDefaults(a,OpenLayers.Protocol.SOS.DEFAULTS);var b=OpenLayers.Protocol.SOS["v"+a.version.replace(/\./g,"_")];if(!b)throw"Unsupported SOS version: "+a.version;return new b(a)};OpenLayers.Protocol.SOS.DEFAULTS={version:"1.0.0"};OpenLayers.Format.WFSDescribeFeatureType=OpenLayers.Class(OpenLayers.Format.XML,{regExes:{trimSpace:/^\s*|\s*$/g},namespaces:{xsd:"http://www.w3.org/2001/XMLSchema"},readers:{xsd:{schema:function(a,b){var c=[],d={},e,f;this.readChildNodes(a,{complexTypes:c,customTypes:d});var g=a.attributes,h,k;e=0;for(f=g.length;e<f;++e)h=g[e],k=h.name,0===k.indexOf("xmlns")?this.setNamespace(k.split(":")[1]||"",h.value):b[k]=h.value;b.featureTypes=c;b.targetPrefix=this.namespaceAlias[b.targetNamespace];e=0;for(f=
2902 c.length;e<f;++e)g=c[e],h=d[g.typeName],d[g.typeName]&&(g.typeName=h.name)},complexType:function(a,b){var c={typeName:a.getAttribute("name")};this.readChildNodes(a,c);b.complexTypes.push(c)},complexContent:function(a,b){this.readChildNodes(a,b)},extension:function(a,b){this.readChildNodes(a,b)},sequence:function(a,b){var c={elements:[]};this.readChildNodes(a,c);b.properties=c.elements},element:function(a,b){var c;if(b.elements){var d={};c=a.attributes;for(var e,f=0,g=c.length;f<g;++f)e=c[f],d[e.name]=
2903 e.value;c=d.type;c||(c={},this.readChildNodes(a,c),d.restriction=c,d.type=c.base);d.localType=(c.base||c).split(":").pop();b.elements.push(d);this.readChildNodes(a,d)}b.complexTypes&&(c=a.getAttribute("type"),d=c.split(":").pop(),b.customTypes[d]={name:a.getAttribute("name"),type:c})},annotation:function(a,b){b.annotation={};this.readChildNodes(a,b.annotation)},appinfo:function(a,b){b.appinfo||(b.appinfo=[]);b.appinfo.push(this.getChildValue(a))},documentation:function(a,b){b.documentation||(b.documentation=
2904 []);var c=this.getChildValue(a);b.documentation.push({lang:a.getAttribute("xml:lang"),textContent:c.replace(this.regExes.trimSpace,"")})},simpleType:function(a,b){this.readChildNodes(a,b)},restriction:function(a,b){b.base=a.getAttribute("base");this.readRestriction(a,b)}}},readRestriction:function(a,b){for(var c=a.childNodes,d,e,f=0,g=c.length;f<g;++f)d=c[f],1==d.nodeType&&(e=d.nodeName.split(":").pop(),d=d.getAttribute("value"),b[e]?("string"==typeof b[e]&&(b[e]=[b[e]]),b[e].push(d)):b[e]=d)},read:function(a){"string"==
2905 typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));a&&9==a.nodeType&&(a=a.documentElement);var b={};if("ExceptionReport"===a.nodeName.split(":").pop()){var c=new OpenLayers.Format.OGCExceptionReport;b.error=c.read(a)}else this.readNode(a,b);return b},CLASS_NAME:"OpenLayers.Format.WFSDescribeFeatureType"});OpenLayers.Format.GeoRSS=OpenLayers.Class(OpenLayers.Format.XML,{rssns:"http://backend.userland.com/rss2",featureNS:"http://mapserver.gis.umn.edu/mapserver",georssns:"http://www.georss.org/georss",geons:"http://www.w3.org/2003/01/geo/wgs84_pos#",featureTitle:"Untitled",featureDescription:"No Description",gmlParser:null,xy:!1,createGeometryFromItem:function(a){var b=this.getElementsByTagNameNS(a,this.georssns,"point"),c=this.getElementsByTagNameNS(a,this.geons,"lat"),d=this.getElementsByTagNameNS(a,
2906 this.geons,"long"),e=this.getElementsByTagNameNS(a,this.georssns,"line"),f=this.getElementsByTagNameNS(a,this.georssns,"polygon"),g=this.getElementsByTagNameNS(a,this.georssns,"where");a=this.getElementsByTagNameNS(a,this.georssns,"box");if(0<b.length||0<c.length&&0<d.length){0<b.length?(c=OpenLayers.String.trim(b[0].firstChild.nodeValue).split(/\s+/),2!=c.length&&(c=OpenLayers.String.trim(b[0].firstChild.nodeValue).split(/\s*,\s*/))):c=[parseFloat(c[0].firstChild.nodeValue),parseFloat(d[0].firstChild.nodeValue)];
2907 var h=new OpenLayers.Geometry.Point(c[1],c[0])}else if(0<e.length){c=OpenLayers.String.trim(this.getChildValue(e[0])).split(/\s+/);d=[];e=0;for(f=c.length;e<f;e+=2)b=new OpenLayers.Geometry.Point(c[e+1],c[e]),d.push(b);h=new OpenLayers.Geometry.LineString(d)}else if(0<f.length){c=OpenLayers.String.trim(this.getChildValue(f[0])).split(/\s+/);d=[];e=0;for(f=c.length;e<f;e+=2)b=new OpenLayers.Geometry.Point(c[e+1],c[e]),d.push(b);h=new OpenLayers.Geometry.Polygon([new OpenLayers.Geometry.LinearRing(d)])}else 0<
2908 g.length?(this.gmlParser||(this.gmlParser=new OpenLayers.Format.GML({xy:this.xy})),h=this.gmlParser.parseFeature(g[0]).geometry):0<a.length&&(c=OpenLayers.String.trim(a[0].firstChild.nodeValue).split(/\s+/),d=[],3<c.length&&(b=new OpenLayers.Geometry.Point(c[1],c[0]),d.push(b),b=new OpenLayers.Geometry.Point(c[1],c[2]),d.push(b),b=new OpenLayers.Geometry.Point(c[3],c[2]),d.push(b),b=new OpenLayers.Geometry.Point(c[3],c[0]),d.push(b),b=new OpenLayers.Geometry.Point(c[1],c[0]),d.push(b)),h=new OpenLayers.Geometry.Polygon([new OpenLayers.Geometry.LinearRing(d)]));
2909 h&&(this.internalProjection&&this.externalProjection)&&h.transform(this.externalProjection,this.internalProjection);return h},createFeatureFromItem:function(a){var b=this.createGeometryFromItem(a),c=this._getChildValue(a,"*","title",this.featureTitle),d=this._getChildValue(a,"*","description",this._getChildValue(a,"*","content",this._getChildValue(a,"*","summary",this.featureDescription))),e=this._getChildValue(a,"*","link");if(!e)try{e=this.getElementsByTagNameNS(a,"*","link")[0].getAttribute("href")}catch(f){e=
2910 null}a=this._getChildValue(a,"*","id",null);b=new OpenLayers.Feature.Vector(b,{title:c,description:d,link:e});b.fid=a;return b},_getChildValue:function(a,b,c,d){return(a=this.getElementsByTagNameNS(a,b,c))&&a[0]&&a[0].firstChild&&a[0].firstChild.nodeValue?this.getChildValue(a[0]):void 0==d?"":d},read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));var b=null,b=this.getElementsByTagNameNS(a,"*","item");0==b.length&&(b=this.getElementsByTagNameNS(a,"*","entry"));
2911 a=b.length;for(var c=Array(a),d=0;d<a;d++)c[d]=this.createFeatureFromItem(b[d]);return c},write:function(a){var b;if(OpenLayers.Util.isArray(a)){b=this.createElementNS(this.rssns,"rss");for(var c=0,d=a.length;c<d;c++)b.appendChild(this.createFeatureXML(a[c]))}else b=this.createFeatureXML(a);return OpenLayers.Format.XML.prototype.write.apply(this,[b])},createFeatureXML:function(a){var b=this.buildGeometryNode(a.geometry),c=this.createElementNS(this.rssns,"item"),d=this.createElementNS(this.rssns,"title");
2912 d.appendChild(this.createTextNode(a.attributes.title?a.attributes.title:""));var e=this.createElementNS(this.rssns,"description");e.appendChild(this.createTextNode(a.attributes.description?a.attributes.description:""));c.appendChild(d);c.appendChild(e);a.attributes.link&&(d=this.createElementNS(this.rssns,"link"),d.appendChild(this.createTextNode(a.attributes.link)),c.appendChild(d));for(var f in a.attributes)"link"!=f&&("title"!=f&&"description"!=f)&&(d=this.createTextNode(a.attributes[f]),e=f,-1!=
2913 f.search(":")&&(e=f.split(":")[1]),e=this.createElementNS(this.featureNS,"feature:"+e),e.appendChild(d),c.appendChild(e));c.appendChild(b);return c},buildGeometryNode:function(a){this.internalProjection&&this.externalProjection&&(a=a.clone(),a.transform(this.internalProjection,this.externalProjection));var b;if("OpenLayers.Geometry.Polygon"==a.CLASS_NAME)b=this.createElementNS(this.georssns,"georss:polygon"),b.appendChild(this.buildCoordinatesNode(a.components[0]));else if("OpenLayers.Geometry.LineString"==
2914 a.CLASS_NAME)b=this.createElementNS(this.georssns,"georss:line"),b.appendChild(this.buildCoordinatesNode(a));else if("OpenLayers.Geometry.Point"==a.CLASS_NAME)b=this.createElementNS(this.georssns,"georss:point"),b.appendChild(this.buildCoordinatesNode(a));else throw"Couldn't parse "+a.CLASS_NAME;return b},buildCoordinatesNode:function(a){var b=null;a.components&&(b=a.components);if(b){a=b.length;for(var c=Array(a),d=0;d<a;d++)c[d]=b[d].y+" "+b[d].x;b=c.join(" ")}else b=a.y+" "+a.x;return this.createTextNode(b)},
2915 CLASS_NAME:"OpenLayers.Format.GeoRSS"});OpenLayers.Format.WPSCapabilities=OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC,{defaultVersion:"1.0.0",CLASS_NAME:"OpenLayers.Format.WPSCapabilities"});OpenLayers.Format.WPSCapabilities.v1_0_0=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{ows:"http://www.opengis.net/ows/1.1",wps:"http://www.opengis.net/wps/1.0.0",xlink:"http://www.w3.org/1999/xlink"},regExes:{trimSpace:/^\s*|\s*$/g,removeSpace:/\s*/g,splitSpace:/\s+/,trimComma:/\s*,\s*/g},initialize:function(a){OpenLayers.Format.XML.prototype.initialize.apply(this,[a])},read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));a&&9==a.nodeType&&(a=a.documentElement);
2916 var b={};this.readNode(a,b);return b},readers:{wps:{Capabilities:function(a,b){this.readChildNodes(a,b)},ProcessOfferings:function(a,b){b.processOfferings={};this.readChildNodes(a,b.processOfferings)},Process:function(a,b){var c={processVersion:this.getAttributeNS(a,this.namespaces.wps,"processVersion")};this.readChildNodes(a,c);b[c.identifier]=c},Languages:function(a,b){b.languages=[];this.readChildNodes(a,b.languages)},Default:function(a,b){var c={isDefault:!0};this.readChildNodes(a,c);b.push(c)},
2917 Supported:function(a,b){var c={};this.readChildNodes(a,c);b.push(c)}},ows:OpenLayers.Format.OWSCommon.v1_1_0.prototype.readers.ows},CLASS_NAME:"OpenLayers.Format.WPSCapabilities.v1_0_0"});OpenLayers.Control.PinchZoom=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_TOOL,pinchOrigin:null,currentCenter:null,autoActivate:!0,preserveCenter:!1,initialize:function(a){OpenLayers.Control.prototype.initialize.apply(this,arguments);this.handler=new OpenLayers.Handler.Pinch(this,{start:this.pinchStart,move:this.pinchMove,done:this.pinchDone},this.handlerOptions)},pinchStart:function(a,b){var c=this.preserveCenter?this.map.getPixelFromLonLat(this.map.getCenter()):a.xy;this.currentCenter=
2918 this.pinchOrigin=c},pinchMove:function(a,b){var c=b.scale,d=this.map.layerContainerOriginPx,e=this.pinchOrigin,f=this.preserveCenter?this.map.getPixelFromLonLat(this.map.getCenter()):a.xy,g=Math.round(d.x+f.x-e.x+(c-1)*(d.x-e.x)),d=Math.round(d.y+f.y-e.y+(c-1)*(d.y-e.y));this.map.applyTransform(g,d,c);this.currentCenter=f},pinchDone:function(a,b,c){this.map.applyTransform();a=this.map.getZoomForResolution(this.map.getResolution()/c.scale,!0);if(a!==this.map.getZoom()||!this.currentCenter.equals(this.pinchOrigin)){b=
2919 this.map.getResolutionForZoom(a);c=this.map.getLonLatFromPixel(this.pinchOrigin);var d=this.currentCenter,e=this.map.getSize();c.lon+=b*(e.w/2-d.x);c.lat-=b*(e.h/2-d.y);this.map.div.clientWidth=this.map.div.clientWidth;this.map.setCenter(c,a)}},CLASS_NAME:"OpenLayers.Control.PinchZoom"});OpenLayers.Control.TouchNavigation=OpenLayers.Class(OpenLayers.Control,{dragPan:null,dragPanOptions:null,pinchZoom:null,pinchZoomOptions:null,clickHandlerOptions:null,documentDrag:!1,autoActivate:!0,initialize:function(a){this.handlers={};OpenLayers.Control.prototype.initialize.apply(this,arguments)},destroy:function(){this.deactivate();this.dragPan&&this.dragPan.destroy();this.dragPan=null;this.pinchZoom&&(this.pinchZoom.destroy(),delete this.pinchZoom);OpenLayers.Control.prototype.destroy.apply(this,
2920 arguments)},activate:function(){return OpenLayers.Control.prototype.activate.apply(this,arguments)?(this.dragPan.activate(),this.handlers.click.activate(),this.pinchZoom.activate(),!0):!1},deactivate:function(){return OpenLayers.Control.prototype.deactivate.apply(this,arguments)?(this.dragPan.deactivate(),this.handlers.click.deactivate(),this.pinchZoom.deactivate(),!0):!1},draw:function(){var a={click:this.defaultClick,dblclick:this.defaultDblClick},b=OpenLayers.Util.extend({"double":!0,stopDouble:!0,
2921 pixelTolerance:2},this.clickHandlerOptions);this.handlers.click=new OpenLayers.Handler.Click(this,a,b);this.dragPan=new OpenLayers.Control.DragPan(OpenLayers.Util.extend({map:this.map,documentDrag:this.documentDrag},this.dragPanOptions));this.dragPan.draw();this.pinchZoom=new OpenLayers.Control.PinchZoom(OpenLayers.Util.extend({map:this.map},this.pinchZoomOptions))},defaultClick:function(a){a.lastTouches&&2==a.lastTouches.length&&this.map.zoomOut()},defaultDblClick:function(a){this.map.zoomTo(this.map.zoom+
2922 1,a.xy)},CLASS_NAME:"OpenLayers.Control.TouchNavigation"});OpenLayers.Console.warn("OpenLayers.Rico is deprecated");OpenLayers.Rico=OpenLayers.Rico||{};
2923 OpenLayers.Rico.Color=OpenLayers.Class({initialize:function(a,b,c){this.rgb={r:a,g:b,b:c}},setRed:function(a){this.rgb.r=a},setGreen:function(a){this.rgb.g=a},setBlue:function(a){this.rgb.b=a},setHue:function(a){var b=this.asHSB();b.h=a;this.rgb=OpenLayers.Rico.Color.HSBtoRGB(b.h,b.s,b.b)},setSaturation:function(a){var b=this.asHSB();b.s=a;this.rgb=OpenLayers.Rico.Color.HSBtoRGB(b.h,b.s,b.b)},setBrightness:function(a){var b=this.asHSB();b.b=a;this.rgb=OpenLayers.Rico.Color.HSBtoRGB(b.h,b.s,b.b)},
2924 darken:function(a){var b=this.asHSB();this.rgb=OpenLayers.Rico.Color.HSBtoRGB(b.h,b.s,Math.max(b.b-a,0))},brighten:function(a){var b=this.asHSB();this.rgb=OpenLayers.Rico.Color.HSBtoRGB(b.h,b.s,Math.min(b.b+a,1))},blend:function(a){this.rgb.r=Math.floor((this.rgb.r+a.rgb.r)/2);this.rgb.g=Math.floor((this.rgb.g+a.rgb.g)/2);this.rgb.b=Math.floor((this.rgb.b+a.rgb.b)/2)},isBright:function(){this.asHSB();return 0.5<this.asHSB().b},isDark:function(){return!this.isBright()},asRGB:function(){return"rgb("+
2925 this.rgb.r+","+this.rgb.g+","+this.rgb.b+")"},asHex:function(){return"#"+this.rgb.r.toColorPart()+this.rgb.g.toColorPart()+this.rgb.b.toColorPart()},asHSB:function(){return OpenLayers.Rico.Color.RGBtoHSB(this.rgb.r,this.rgb.g,this.rgb.b)},toString:function(){return this.asHex()}});
2926 OpenLayers.Rico.Color.createFromHex=function(a){if(4==a.length){var b=a;a="#";for(var c=1;4>c;c++)a+=b.charAt(c)+b.charAt(c)}0==a.indexOf("#")&&(a=a.substring(1));b=a.substring(0,2);c=a.substring(2,4);a=a.substring(4,6);return new OpenLayers.Rico.Color(parseInt(b,16),parseInt(c,16),parseInt(a,16))};
2927 OpenLayers.Rico.Color.createColorFromBackground=function(a){var b=OpenLayers.Element.getStyle(OpenLayers.Util.getElement(a),"backgroundColor");return"transparent"==b&&a.parentNode?OpenLayers.Rico.Color.createColorFromBackground(a.parentNode):null==b?new OpenLayers.Rico.Color(255,255,255):0==b.indexOf("rgb(")?(a=b.substring(4,b.length-1).split(","),new OpenLayers.Rico.Color(parseInt(a[0]),parseInt(a[1]),parseInt(a[2]))):0==b.indexOf("#")?OpenLayers.Rico.Color.createFromHex(b):new OpenLayers.Rico.Color(255,
2928 255,255)};
2929 OpenLayers.Rico.Color.HSBtoRGB=function(a,b,c){var d=0,e=0,f=0;if(0==b)f=e=d=parseInt(255*c+0.5);else{a=6*(a-Math.floor(a));var g=a-Math.floor(a),h=c*(1-b),k=c*(1-b*g);b=c*(1-b*(1-g));switch(parseInt(a)){case 0:d=255*c+0.5;e=255*b+0.5;f=255*h+0.5;break;case 1:d=255*k+0.5;e=255*c+0.5;f=255*h+0.5;break;case 2:d=255*h+0.5;e=255*c+0.5;f=255*b+0.5;break;case 3:d=255*h+0.5;e=255*k+0.5;f=255*c+0.5;break;case 4:d=255*b+0.5;e=255*h+0.5;f=255*c+0.5;break;case 5:d=255*c+0.5,e=255*h+0.5,f=255*k+0.5}}return{r:parseInt(d),g:parseInt(e),
2930 b:parseInt(f)}};OpenLayers.Rico.Color.RGBtoHSB=function(a,b,c){var d,e=a>b?a:b;c>e&&(e=c);var f=a<b?a:b;c<f&&(f=c);d=0!=e?(e-f)/e:0;if(0==d)a=0;else{var g=(e-a)/(e-f),h=(e-b)/(e-f);c=(e-c)/(e-f);a=(a==e?c-h:b==e?2+g-c:4+h-g)/6;0>a&&(a+=1)}return{h:a,s:d,b:e/255}};OpenLayers.Style2=OpenLayers.Class({id:null,name:null,title:null,description:null,layerName:null,isDefault:!1,rules:null,initialize:function(a){OpenLayers.Util.extend(this,a);this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_")},destroy:function(){for(var a=0,b=this.rules.length;a<b;a++)this.rules[a].destroy();delete this.rules},clone:function(){var a=OpenLayers.Util.extend({},this);if(this.rules){a.rules=[];for(var b=0,c=this.rules.length;b<c;++b)a.rules.push(this.rules[b].clone())}return new OpenLayers.Style2(a)},
2931 CLASS_NAME:"OpenLayers.Style2"});OpenLayers.Format.WFS=OpenLayers.Class(OpenLayers.Format.GML,{layer:null,wfsns:"http://www.opengis.net/wfs",ogcns:"http://www.opengis.net/ogc",initialize:function(a,b){OpenLayers.Format.GML.prototype.initialize.apply(this,[a]);this.layer=b;this.layer.featureNS&&(this.featureNS=this.layer.featureNS);this.layer.options.geometry_column&&(this.geometryName=this.layer.options.geometry_column);this.layer.options.typename&&(this.featureName=this.layer.options.typename)},write:function(a){var b=this.createElementNS(this.wfsns,
2932 "wfs:Transaction");b.setAttribute("version","1.0.0");b.setAttribute("service","WFS");for(var c=0;c<a.length;c++)switch(a[c].state){case OpenLayers.State.INSERT:b.appendChild(this.insert(a[c]));break;case OpenLayers.State.UPDATE:b.appendChild(this.update(a[c]));break;case OpenLayers.State.DELETE:b.appendChild(this.remove(a[c]))}return OpenLayers.Format.XML.prototype.write.apply(this,[b])},createFeatureXML:function(a){var b=this.buildGeometryNode(a.geometry),c=this.createElementNS(this.featureNS,"feature:"+
2933 this.geometryName);c.appendChild(b);b=this.createElementNS(this.featureNS,"feature:"+this.featureName);b.appendChild(c);for(var d in a.attributes){var c=this.createTextNode(a.attributes[d]),e=d;-1!=d.search(":")&&(e=d.split(":")[1]);e=this.createElementNS(this.featureNS,"feature:"+e);e.appendChild(c);b.appendChild(e)}return b},insert:function(a){var b=this.createElementNS(this.wfsns,"wfs:Insert");b.appendChild(this.createFeatureXML(a));return b},update:function(a){a.fid||OpenLayers.Console.userError(OpenLayers.i18n("noFID"));
2934 var b=this.createElementNS(this.wfsns,"wfs:Update");b.setAttribute("typeName",this.featurePrefix+":"+this.featureName);b.setAttribute("xmlns:"+this.featurePrefix,this.featureNS);var c=this.createElementNS(this.wfsns,"wfs:Property"),d=this.createElementNS(this.wfsns,"wfs:Name"),e=this.createTextNode(this.geometryName);d.appendChild(e);c.appendChild(d);d=this.createElementNS(this.wfsns,"wfs:Value");e=this.buildGeometryNode(a.geometry);a.layer&&e.setAttribute("srsName",a.layer.projection.getCode());
2935 d.appendChild(e);c.appendChild(d);b.appendChild(c);for(var f in a.attributes)c=this.createElementNS(this.wfsns,"wfs:Property"),d=this.createElementNS(this.wfsns,"wfs:Name"),d.appendChild(this.createTextNode(f)),c.appendChild(d),d=this.createElementNS(this.wfsns,"wfs:Value"),d.appendChild(this.createTextNode(a.attributes[f])),c.appendChild(d),b.appendChild(c);c=this.createElementNS(this.ogcns,"ogc:Filter");f=this.createElementNS(this.ogcns,"ogc:FeatureId");f.setAttribute("fid",a.fid);c.appendChild(f);
2936 b.appendChild(c);return b},remove:function(a){if(!a.fid)return OpenLayers.Console.userError(OpenLayers.i18n("noFID")),!1;var b=this.createElementNS(this.wfsns,"wfs:Delete");b.setAttribute("typeName",this.featurePrefix+":"+this.featureName);b.setAttribute("xmlns:"+this.featurePrefix,this.featureNS);var c=this.createElementNS(this.ogcns,"ogc:Filter"),d=this.createElementNS(this.ogcns,"ogc:FeatureId");d.setAttribute("fid",a.fid);c.appendChild(d);b.appendChild(c);return b},destroy:function(){this.layer=
2937 null},CLASS_NAME:"OpenLayers.Format.WFS"});OpenLayers.Format.SLD.v1_0_0_GeoServer=OpenLayers.Class(OpenLayers.Format.SLD.v1_0_0,{version:"1.0.0",profile:"GeoServer",readers:OpenLayers.Util.applyDefaults({sld:OpenLayers.Util.applyDefaults({Priority:function(a,b){var c=this.readers.ogc._expression.call(this,a);c&&(b.priority=c)},VendorOption:function(a,b){b.vendorOptions||(b.vendorOptions={});b.vendorOptions[a.getAttribute("name")]=this.getChildValue(a)},TextSymbolizer:function(a,b){OpenLayers.Format.SLD.v1_0_0.prototype.readers.sld.TextSymbolizer.apply(this,
2938 arguments);var c=this.multipleSymbolizers?b.symbolizers[b.symbolizers.length-1]:b.symbolizer.Text;void 0===c.graphic&&(c.graphic=!1)}},OpenLayers.Format.SLD.v1_0_0.prototype.readers.sld)},OpenLayers.Format.SLD.v1_0_0.prototype.readers),writers:OpenLayers.Util.applyDefaults({sld:OpenLayers.Util.applyDefaults({Priority:function(a){return this.writers.sld._OGCExpression.call(this,"sld:Priority",a)},VendorOption:function(a){return this.createElementNSPlus("sld:VendorOption",{attributes:{name:a.name},
2939 value:a.value})},TextSymbolizer:function(a){var b=OpenLayers.Format.SLD.v1_0_0.prototype.writers.sld.TextSymbolizer.apply(this,arguments);!1!==a.graphic&&(a.externalGraphic||a.graphicName)&&this.writeNode("Graphic",a,b);"priority"in a&&this.writeNode("Priority",a.priority,b);return this.addVendorOptions(b,a)},PointSymbolizer:function(a){var b=OpenLayers.Format.SLD.v1_0_0.prototype.writers.sld.PointSymbolizer.apply(this,arguments);return this.addVendorOptions(b,a)},LineSymbolizer:function(a){var b=
2940 OpenLayers.Format.SLD.v1_0_0.prototype.writers.sld.LineSymbolizer.apply(this,arguments);return this.addVendorOptions(b,a)},PolygonSymbolizer:function(a){var b=OpenLayers.Format.SLD.v1_0_0.prototype.writers.sld.PolygonSymbolizer.apply(this,arguments);return this.addVendorOptions(b,a)}},OpenLayers.Format.SLD.v1_0_0.prototype.writers.sld)},OpenLayers.Format.SLD.v1_0_0.prototype.writers),addVendorOptions:function(a,b){if(b.vendorOptions)for(var c in b.vendorOptions)this.writeNode("VendorOption",{name:c,
2941 value:b.vendorOptions[c]},a);return a},CLASS_NAME:"OpenLayers.Format.SLD.v1_0_0_GeoServer"});OpenLayers.Layer.Boxes=OpenLayers.Class(OpenLayers.Layer.Markers,{drawMarker:function(a){var b=this.map.getLayerPxFromLonLat({lon:a.bounds.left,lat:a.bounds.top}),c=this.map.getLayerPxFromLonLat({lon:a.bounds.right,lat:a.bounds.bottom});null==c||null==b?a.display(!1):(b=a.draw(b,{w:Math.max(1,c.x-b.x),h:Math.max(1,c.y-b.y)}),a.drawn||(this.div.appendChild(b),a.drawn=!0))},removeMarker:function(a){OpenLayers.Util.removeItem(this.markers,a);null!=a.div&&a.div.parentNode==this.div&&this.div.removeChild(a.div)},
2942 CLASS_NAME:"OpenLayers.Layer.Boxes"});OpenLayers.Format.WFSCapabilities.v1_0_0=OpenLayers.Class(OpenLayers.Format.WFSCapabilities.v1,{readers:{wfs:OpenLayers.Util.applyDefaults({Service:function(a,b){b.service={};this.readChildNodes(a,b.service)},Fees:function(a,b){var c=this.getChildValue(a);c&&"none"!=c.toLowerCase()&&(b.fees=c)},AccessConstraints:function(a,b){var c=this.getChildValue(a);c&&"none"!=c.toLowerCase()&&(b.accessConstraints=c)},OnlineResource:function(a,b){var c=this.getChildValue(a);c&&"none"!=c.toLowerCase()&&(b.onlineResource=
2943 c)},Keywords:function(a,b){var c=this.getChildValue(a);c&&"none"!=c.toLowerCase()&&(b.keywords=c.split(", "))},Capability:function(a,b){b.capability={};this.readChildNodes(a,b.capability)},Request:function(a,b){b.request={};this.readChildNodes(a,b.request)},GetFeature:function(a,b){b.getfeature={href:{},formats:[]};this.readChildNodes(a,b.getfeature)},ResultFormat:function(a,b){for(var c=a.childNodes,d,e=0;e<c.length;e++)d=c[e],1==d.nodeType&&b.formats.push(d.nodeName)},DCPType:function(a,b){this.readChildNodes(a,
2944 b)},HTTP:function(a,b){this.readChildNodes(a,b.href)},Get:function(a,b){b.get=a.getAttribute("onlineResource")},Post:function(a,b){b.post=a.getAttribute("onlineResource")},SRS:function(a,b){var c=this.getChildValue(a);c&&(b.srs=c)}},OpenLayers.Format.WFSCapabilities.v1.prototype.readers.wfs)},CLASS_NAME:"OpenLayers.Format.WFSCapabilities.v1_0_0"});OpenLayers.Format.WMSCapabilities.v1_3=OpenLayers.Class(OpenLayers.Format.WMSCapabilities.v1,{readers:{wms:OpenLayers.Util.applyDefaults({WMS_Capabilities:function(a,b){this.readChildNodes(a,b)},LayerLimit:function(a,b){b.layerLimit=parseInt(this.getChildValue(a))},MaxWidth:function(a,b){b.maxWidth=parseInt(this.getChildValue(a))},MaxHeight:function(a,b){b.maxHeight=parseInt(this.getChildValue(a))},BoundingBox:function(a,b){var c=OpenLayers.Format.WMSCapabilities.v1.prototype.readers.wms.BoundingBox.apply(this,
2945 [a,b]);c.srs=a.getAttribute("CRS");b.bbox[c.srs]=c},CRS:function(a,b){this.readers.wms.SRS.apply(this,[a,b])},EX_GeographicBoundingBox:function(a,b){b.llbbox=[];this.readChildNodes(a,b.llbbox)},westBoundLongitude:function(a,b){b[0]=this.getChildValue(a)},eastBoundLongitude:function(a,b){b[2]=this.getChildValue(a)},southBoundLatitude:function(a,b){b[1]=this.getChildValue(a)},northBoundLatitude:function(a,b){b[3]=this.getChildValue(a)},MinScaleDenominator:function(a,b){b.maxScale=parseFloat(this.getChildValue(a)).toPrecision(16)},
2946 MaxScaleDenominator:function(a,b){b.minScale=parseFloat(this.getChildValue(a)).toPrecision(16)},Dimension:function(a,b){var c={name:a.getAttribute("name").toLowerCase(),units:a.getAttribute("units"),unitsymbol:a.getAttribute("unitSymbol"),nearestVal:"1"===a.getAttribute("nearestValue"),multipleVal:"1"===a.getAttribute("multipleValues"),"default":a.getAttribute("default")||"",current:"1"===a.getAttribute("current"),values:this.getChildValue(a).split(",")};b.dimensions[c.name]=c},Keyword:function(a,
2947 b){var c={value:this.getChildValue(a),vocabulary:a.getAttribute("vocabulary")};b.keywords&&b.keywords.push(c)}},OpenLayers.Format.WMSCapabilities.v1.prototype.readers.wms),sld:{UserDefinedSymbolization:function(a,b){this.readers.wms.UserDefinedSymbolization.apply(this,[a,b]);b.userSymbols.inlineFeature=1==parseInt(a.getAttribute("InlineFeature"));b.userSymbols.remoteWCS=1==parseInt(a.getAttribute("RemoteWCS"))},DescribeLayer:function(a,b){this.readers.wms.DescribeLayer.apply(this,[a,b])},GetLegendGraphic:function(a,
2948 b){this.readers.wms.GetLegendGraphic.apply(this,[a,b])}}},CLASS_NAME:"OpenLayers.Format.WMSCapabilities.v1_3"});OpenLayers.Layer.Zoomify=OpenLayers.Class(OpenLayers.Layer.Grid,{size:null,isBaseLayer:!0,standardTileSize:256,tileOriginCorner:"tl",numberOfTiers:0,tileCountUpToTier:null,tierSizeInTiles:null,tierImageSize:null,initialize:function(a,b,c,d){this.initializeZoomify(c);OpenLayers.Layer.Grid.prototype.initialize.apply(this,[a,b,c,{},d])},initializeZoomify:function(a){var b=a.clone();this.size=a.clone();a=new OpenLayers.Size(Math.ceil(b.w/this.standardTileSize),Math.ceil(b.h/this.standardTileSize));this.tierSizeInTiles=
2949 [a];for(this.tierImageSize=[b];b.w>this.standardTileSize||b.h>this.standardTileSize;)b=new OpenLayers.Size(Math.floor(b.w/2),Math.floor(b.h/2)),a=new OpenLayers.Size(Math.ceil(b.w/this.standardTileSize),Math.ceil(b.h/this.standardTileSize)),this.tierSizeInTiles.push(a),this.tierImageSize.push(b);this.tierSizeInTiles.reverse();this.tierImageSize.reverse();this.numberOfTiers=this.tierSizeInTiles.length;b=[1];this.tileCountUpToTier=[0];for(a=1;a<this.numberOfTiers;a++)b.unshift(Math.pow(2,a)),this.tileCountUpToTier.push(this.tierSizeInTiles[a-
2950 1].w*this.tierSizeInTiles[a-1].h+this.tileCountUpToTier[a-1]);this.serverResolutions||(this.serverResolutions=b)},destroy:function(){OpenLayers.Layer.Grid.prototype.destroy.apply(this,arguments);this.tileCountUpToTier.length=0;this.tierSizeInTiles.length=0;this.tierImageSize.length=0},clone:function(a){null==a&&(a=new OpenLayers.Layer.Zoomify(this.name,this.url,this.size,this.options));return a=OpenLayers.Layer.Grid.prototype.clone.apply(this,[a])},getURL:function(a){a=this.adjustBounds(a);var b=
2951 this.getServerResolution(),c=Math.round((a.left-this.tileOrigin.lon)/(b*this.tileSize.w));a=Math.round((this.tileOrigin.lat-a.top)/(b*this.tileSize.h));b=this.getZoomForResolution(b);c="TileGroup"+Math.floor((c+a*this.tierSizeInTiles[b].w+this.tileCountUpToTier[b])/256)+"/"+b+"-"+c+"-"+a+".jpg";b=this.url;OpenLayers.Util.isArray(b)&&(b=this.selectUrl(c,b));return b+c},getImageSize:function(){if(0<arguments.length){var a=this.adjustBounds(arguments[0]),b=this.getServerResolution(),c=Math.round((a.left-
2952 this.tileOrigin.lon)/(b*this.tileSize.w)),a=Math.round((this.tileOrigin.lat-a.top)/(b*this.tileSize.h)),b=this.getZoomForResolution(b),d=this.standardTileSize,e=this.standardTileSize;c==this.tierSizeInTiles[b].w-1&&(d=this.tierImageSize[b].w%this.standardTileSize);a==this.tierSizeInTiles[b].h-1&&(e=this.tierImageSize[b].h%this.standardTileSize);return new OpenLayers.Size(d,e)}return this.tileSize},setMap:function(a){OpenLayers.Layer.Grid.prototype.setMap.apply(this,arguments);this.tileOrigin=new OpenLayers.LonLat(this.map.maxExtent.left,
2953 this.map.maxExtent.top)},CLASS_NAME:"OpenLayers.Layer.Zoomify"});OpenLayers.Layer.MapServer=OpenLayers.Class(OpenLayers.Layer.Grid,{DEFAULT_PARAMS:{mode:"map",map_imagetype:"png"},initialize:function(a,b,c,d){OpenLayers.Layer.Grid.prototype.initialize.apply(this,arguments);this.params=OpenLayers.Util.applyDefaults(this.params,this.DEFAULT_PARAMS);if(null==d||null==d.isBaseLayer)this.isBaseLayer="true"!=this.params.transparent&&!0!=this.params.transparent},clone:function(a){null==a&&(a=new OpenLayers.Layer.MapServer(this.name,this.url,this.params,this.getOptions()));
2954 return a=OpenLayers.Layer.Grid.prototype.clone.apply(this,[a])},getURL:function(a){a=this.adjustBounds(a);a=[a.left,a.bottom,a.right,a.top];var b=this.getImageSize();return this.getFullRequestString({mapext:a,imgext:a,map_size:[b.w,b.h],imgx:b.w/2,imgy:b.h/2,imgxy:[b.w,b.h]})},getFullRequestString:function(a,b){var c=null==b?this.url:b,d=OpenLayers.Util.extend({},this.params),d=OpenLayers.Util.extend(d,a),e=OpenLayers.Util.getParameterString(d);OpenLayers.Util.isArray(c)&&(c=this.selectUrl(e,c));
2955 var e=OpenLayers.Util.upperCaseObject(OpenLayers.Util.getParameters(c)),f;for(f in d)f.toUpperCase()in e&&delete d[f];e=OpenLayers.Util.getParameterString(d);d=c;e=e.replace(/,/g,"+");""!=e&&(f=c.charAt(c.length-1),d="&"==f||"?"==f?d+e:-1==c.indexOf("?")?d+("?"+e):d+("&"+e));return d},CLASS_NAME:"OpenLayers.Layer.MapServer"});OpenLayers.Renderer.VML=OpenLayers.Class(OpenLayers.Renderer.Elements,{xmlns:"urn:schemas-microsoft-com:vml",symbolCache:{},offset:null,initialize:function(a){if(this.supported()){if(!document.namespaces.olv){document.namespaces.add("olv",this.xmlns);for(var b=document.createStyleSheet(),c="shape rect oval fill stroke imagedata group textbox".split(" "),d=0,e=c.length;d<e;d++)b.addRule("olv\\:"+c[d],"behavior: url(#default#VML); position: absolute; display: inline-block;")}OpenLayers.Renderer.Elements.prototype.initialize.apply(this,
2956 arguments)}},supported:function(){return!!document.namespaces},setExtent:function(a,b){var c=OpenLayers.Renderer.Elements.prototype.setExtent.apply(this,arguments),d=this.getResolution(),e=a.left/d|0,d=a.top/d-this.size.h|0;b||!this.offset?(this.offset={x:e,y:d},d=e=0):(e-=this.offset.x,d-=this.offset.y);this.root.coordorigin=e-this.xOffset+" "+d;for(var e=[this.root,this.vectorRoot,this.textRoot],f=0,g=e.length;f<g;++f)d=e[f],d.coordsize=this.size.w+" "+this.size.h;this.root.style.flip="y";return c},
2957 setSize:function(a){OpenLayers.Renderer.prototype.setSize.apply(this,arguments);for(var b=[this.rendererRoot,this.root,this.vectorRoot,this.textRoot],c=this.size.w+"px",d=this.size.h+"px",e,f=0,g=b.length;f<g;++f)e=b[f],e.style.width=c,e.style.height=d},getNodeType:function(a,b){var c=null;switch(a.CLASS_NAME){case "OpenLayers.Geometry.Point":c=b.externalGraphic?"olv:rect":this.isComplexSymbol(b.graphicName)?"olv:shape":"olv:oval";break;case "OpenLayers.Geometry.Rectangle":c="olv:rect";break;case "OpenLayers.Geometry.LineString":case "OpenLayers.Geometry.LinearRing":case "OpenLayers.Geometry.Polygon":case "OpenLayers.Geometry.Curve":c=
2958 "olv:shape"}return c},setStyle:function(a,b,c,d){b=b||a._style;c=c||a._options;var e=b.fillColor,f=b.title||b.graphicTitle;f&&(a.title=f);if("OpenLayers.Geometry.Point"===a._geometryClass)if(b.externalGraphic){c.isFilled=!0;var e=b.graphicWidth||b.graphicHeight,f=b.graphicHeight||b.graphicWidth,e=e?e:2*b.pointRadius,f=f?f:2*b.pointRadius,g=this.getResolution(),h=void 0!=b.graphicXOffset?b.graphicXOffset:-(0.5*e),k=void 0!=b.graphicYOffset?b.graphicYOffset:-(0.5*f);a.style.left=((d.x-this.featureDx)/
2959 g-this.offset.x+h|0)+"px";a.style.top=(d.y/g-this.offset.y-(k+f)|0)+"px";a.style.width=e+"px";a.style.height=f+"px";a.style.flip="y";e="none";c.isStroked=!1}else this.isComplexSymbol(b.graphicName)?(f=this.importSymbol(b.graphicName),a.path=f.path,a.coordorigin=f.left+","+f.bottom,f=f.size,a.coordsize=f+","+f,this.drawCircle(a,d,b.pointRadius),a.style.flip="y"):this.drawCircle(a,d,b.pointRadius);c.isFilled?a.fillcolor=e:a.filled="false";d=a.getElementsByTagName("fill");d=0==d.length?null:d[0];c.isFilled?
2960 (d||(d=this.createNode("olv:fill",a.id+"_fill")),d.opacity=b.fillOpacity,"OpenLayers.Geometry.Point"===a._geometryClass&&b.externalGraphic&&(b.graphicOpacity&&(d.opacity=b.graphicOpacity),d.src=b.externalGraphic,d.type="frame",b.graphicWidth&&b.graphicHeight||(d.aspect="atmost")),d.parentNode!=a&&a.appendChild(d)):d&&a.removeChild(d);e=b.rotation;if(void 0!==e||void 0!==a._rotation)a._rotation=e,b.externalGraphic?(this.graphicRotate(a,h,k,b),d.opacity=0):"OpenLayers.Geometry.Point"===a._geometryClass&&
2961 (a.style.rotation=e||0);h=a.getElementsByTagName("stroke");h=0==h.length?null:h[0];c.isStroked?(h||(h=this.createNode("olv:stroke",a.id+"_stroke"),a.appendChild(h)),h.on=!0,h.color=b.strokeColor,h.weight=b.strokeWidth+"px",h.opacity=b.strokeOpacity,h.endcap="butt"==b.strokeLinecap?"flat":b.strokeLinecap||"round",b.strokeDashstyle&&(h.dashstyle=this.dashStyle(b))):(a.stroked=!1,h&&(h.on=!1));"inherit"!=b.cursor&&null!=b.cursor&&(a.style.cursor=b.cursor);return a},graphicRotate:function(a,b,c,d){d=
2962 d||a._style;var e=d.rotation||0,f,g;if(d.graphicWidth&&d.graphicHeight){g=Math.max(d.graphicWidth,d.graphicHeight);f=d.graphicWidth/d.graphicHeight;var h=Math.round(d.graphicWidth||g*f),k=Math.round(d.graphicHeight||g);a.style.width=h+"px";a.style.height=k+"px";var l=document.getElementById(a.id+"_image");l||(l=this.createNode("olv:imagedata",a.id+"_image"),a.appendChild(l));l.style.width=h+"px";l.style.height=k+"px";l.src=d.externalGraphic;l.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='', sizingMethod='scale')";
2963 l=e*Math.PI/180;e=Math.sin(l);l=Math.cos(l);e="progid:DXImageTransform.Microsoft.Matrix(M11="+l+",M12="+-e+",M21="+e+",M22="+l+",SizingMethod='auto expand')\n";(l=d.graphicOpacity||d.fillOpacity)&&1!=l&&(e+="progid:DXImageTransform.Microsoft.BasicImage(opacity="+l+")\n");a.style.filter=e;e=new OpenLayers.Geometry.Point(-b,-c);h=(new OpenLayers.Bounds(0,0,h,k)).toGeometry();h.rotate(d.rotation,e);h=h.getBounds();a.style.left=Math.round(parseInt(a.style.left)+h.left)+"px";a.style.top=Math.round(parseInt(a.style.top)-
2964 h.bottom)+"px"}else{var m=new Image;m.onreadystatechange=OpenLayers.Function.bind(function(){if("complete"==m.readyState||"interactive"==m.readyState)f=m.width/m.height,g=Math.max(2*d.pointRadius,d.graphicWidth||0,d.graphicHeight||0),b*=f,d.graphicWidth=g*f,d.graphicHeight=g,this.graphicRotate(a,b,c,d)},this);m.src=d.externalGraphic}},postDraw:function(a){a.style.visibility="visible";var b=a._style.fillColor,c=a._style.strokeColor;"none"==b&&a.fillcolor!=b&&(a.fillcolor=b);"none"==c&&a.strokecolor!=
2965 c&&(a.strokecolor=c)},setNodeDimension:function(a,b){var c=b.getBounds();if(c){var d=this.getResolution(),c=new OpenLayers.Bounds((c.left-this.featureDx)/d-this.offset.x|0,c.bottom/d-this.offset.y|0,(c.right-this.featureDx)/d-this.offset.x|0,c.top/d-this.offset.y|0);a.style.left=c.left+"px";a.style.top=c.top+"px";a.style.width=c.getWidth()+"px";a.style.height=c.getHeight()+"px";a.coordorigin=c.left+" "+c.top;a.coordsize=c.getWidth()+" "+c.getHeight()}},dashStyle:function(a){a=a.strokeDashstyle;switch(a){case "solid":case "dot":case "dash":case "dashdot":case "longdash":case "longdashdot":return a;
2966 default:return a=a.split(/[ ,]/),2==a.length?1*a[0]>=2*a[1]?"longdash":1==a[0]||1==a[1]?"dot":"dash":4==a.length?1*a[0]>=2*a[1]?"longdashdot":"dashdot":"solid"}},createNode:function(a,b){var c=document.createElement(a);b&&(c.id=b);c.unselectable="on";c.onselectstart=OpenLayers.Function.False;return c},nodeTypeCompare:function(a,b){var c=b,d=c.indexOf(":");-1!=d&&(c=c.substr(d+1));var e=a.nodeName,d=e.indexOf(":");-1!=d&&(e=e.substr(d+1));return c==e},createRenderRoot:function(){return this.nodeFactory(this.container.id+
2967 "_vmlRoot","div")},createRoot:function(a){return this.nodeFactory(this.container.id+a,"olv:group")},drawPoint:function(a,b){return this.drawCircle(a,b,1)},drawCircle:function(a,b,c){if(!isNaN(b.x)&&!isNaN(b.y)){var d=this.getResolution();a.style.left=((b.x-this.featureDx)/d-this.offset.x|0)-c+"px";a.style.top=(b.y/d-this.offset.y|0)-c+"px";b=2*c;a.style.width=b+"px";a.style.height=b+"px";return a}return!1},drawLineString:function(a,b){return this.drawLine(a,b,!1)},drawLinearRing:function(a,b){return this.drawLine(a,
2968 b,!0)},drawLine:function(a,b,c){this.setNodeDimension(a,b);for(var d=this.getResolution(),e=b.components.length,f=Array(e),g,h,k=0;k<e;k++)g=b.components[k],h=(g.x-this.featureDx)/d-this.offset.x|0,g=g.y/d-this.offset.y|0,f[k]=" "+h+","+g+" l ";b=c?" x e":" e";a.path="m"+f.join("")+b;return a},drawPolygon:function(a,b){this.setNodeDimension(a,b);var c=this.getResolution(),d=[],e,f,g,h,k,l,m,n,p,q;e=0;for(f=b.components.length;e<f;e++){d.push("m");g=b.components[e].components;h=0===e;l=k=null;m=0;
2969 for(n=g.length;m<n;m++)p=g[m],q=(p.x-this.featureDx)/c-this.offset.x|0,p=p.y/c-this.offset.y|0,q=" "+q+","+p,d.push(q),0==m&&d.push(" l"),h||(k?k!=q&&(l?l!=q&&(h=!0):l=q):k=q);d.push(h?" x ":" ")}d.push("e");a.path=d.join("");return a},drawRectangle:function(a,b){var c=this.getResolution();a.style.left=((b.x-this.featureDx)/c-this.offset.x|0)+"px";a.style.top=(b.y/c-this.offset.y|0)+"px";a.style.width=(b.width/c|0)+"px";a.style.height=(b.height/c|0)+"px";return a},drawText:function(a,b,c){var d=this.nodeFactory(a+
2970 this.LABEL_ID_SUFFIX,"olv:rect"),e=this.nodeFactory(a+this.LABEL_ID_SUFFIX+"_textbox","olv:textbox"),f=this.getResolution();d.style.left=((c.x-this.featureDx)/f-this.offset.x|0)+"px";d.style.top=(c.y/f-this.offset.y|0)+"px";d.style.flip="y";e.innerText=b.label;"inherit"!=b.cursor&&null!=b.cursor&&(e.style.cursor=b.cursor);b.fontColor&&(e.style.color=b.fontColor);b.fontOpacity&&(e.style.filter="alpha(opacity="+100*b.fontOpacity+")");b.fontFamily&&(e.style.fontFamily=b.fontFamily);b.fontSize&&(e.style.fontSize=
2971 b.fontSize);b.fontWeight&&(e.style.fontWeight=b.fontWeight);b.fontStyle&&(e.style.fontStyle=b.fontStyle);!0===b.labelSelect&&(d._featureId=a,e._featureId=a,e._geometry=c,e._geometryClass=c.CLASS_NAME);e.style.whiteSpace="nowrap";e.inset="1px,0px,0px,0px";d.parentNode||(d.appendChild(e),this.textRoot.appendChild(d));b=b.labelAlign||"cm";1==b.length&&(b+="m");a=e.clientWidth*OpenLayers.Renderer.VML.LABEL_SHIFT[b.substr(0,1)];e=e.clientHeight*OpenLayers.Renderer.VML.LABEL_SHIFT[b.substr(1,1)];d.style.left=
2972 parseInt(d.style.left)-a-1+"px";d.style.top=parseInt(d.style.top)+e+"px"},moveRoot:function(a){var b=this.map.getLayer(a.container.id);b instanceof OpenLayers.Layer.Vector.RootContainer&&(b=this.map.getLayer(this.container.id));b&&b.renderer.clear();OpenLayers.Renderer.Elements.prototype.moveRoot.apply(this,arguments);b&&b.redraw()},importSymbol:function(a){var b=this.container.id+"-"+a,c=this.symbolCache[b];if(c)return c;c=OpenLayers.Renderer.symbol[a];if(!c)throw Error(a+" is not a valid symbol name");
2973 a=new OpenLayers.Bounds(Number.MAX_VALUE,Number.MAX_VALUE,0,0);for(var d=["m"],e=0;e<c.length;e+=2){var f=c[e],g=c[e+1];a.left=Math.min(a.left,f);a.bottom=Math.min(a.bottom,g);a.right=Math.max(a.right,f);a.top=Math.max(a.top,g);d.push(f);d.push(g);0==e&&d.push("l")}d.push("x e");c=d.join(" ");d=(a.getWidth()-a.getHeight())/2;0<d?(a.bottom-=d,a.top+=d):(a.left+=d,a.right-=d);c={path:c,size:a.getWidth(),left:a.left,bottom:a.bottom};return this.symbolCache[b]=c},CLASS_NAME:"OpenLayers.Renderer.VML"});
2974 OpenLayers.Renderer.VML.LABEL_SHIFT={l:0,c:0.5,r:1,t:0,m:0.5,b:1};OpenLayers.Control.CacheRead=OpenLayers.Class(OpenLayers.Control,{fetchEvent:"tileloadstart",layers:null,autoActivate:!0,setMap:function(a){OpenLayers.Control.prototype.setMap.apply(this,arguments);var b,c=this.layers||a.layers;for(b=c.length-1;0<=b;--b)this.addLayer({layer:c[b]});if(!this.layers)a.events.on({addlayer:this.addLayer,removeLayer:this.removeLayer,scope:this})},addLayer:function(a){a.layer.events.register(this.fetchEvent,this,this.fetch)},removeLayer:function(a){a.layer.events.unregister(this.fetchEvent,
2975 this,this.fetch)},fetch:function(a){if(this.active&&window.localStorage&&a.tile instanceof OpenLayers.Tile.Image){var b=a.tile,c=b.url;!b.layer.crossOriginKeyword&&(OpenLayers.ProxyHost&&0===c.indexOf(OpenLayers.ProxyHost))&&(c=OpenLayers.Control.CacheWrite.urlMap[c]);if(c=window.localStorage.getItem("olCache_"+c))b.url=c,"tileerror"===a.type&&b.setImgSrc(c)}},destroy:function(){if(this.layers||this.map){var a,b=this.layers||this.map.layers;for(a=b.length-1;0<=a;--a)this.removeLayer({layer:b[a]})}this.map&&
2976 this.map.events.un({addlayer:this.addLayer,removeLayer:this.removeLayer,scope:this});OpenLayers.Control.prototype.destroy.apply(this,arguments)},CLASS_NAME:"OpenLayers.Control.CacheRead"});OpenLayers.Protocol.WFS.v1_0_0=OpenLayers.Class(OpenLayers.Protocol.WFS.v1,{version:"1.0.0",CLASS_NAME:"OpenLayers.Protocol.WFS.v1_0_0"});OpenLayers.Format.WMSGetFeatureInfo=OpenLayers.Class(OpenLayers.Format.XML,{layerIdentifier:"_layer",featureIdentifier:"_feature",regExes:{trimSpace:/^\s*|\s*$/g,removeSpace:/\s*/g,splitSpace:/\s+/,trimComma:/\s*,\s*/g},gmlFormat:null,read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));var b=a.documentElement;if(b){var c=this["read_"+b.nodeName];a=c?c.call(this,b):(new OpenLayers.Format.GML(this.options?this.options:{})).read(a)}return a},read_msGMLOutput:function(a){var b=
2977 [];if(a=this.getSiblingNodesByTagCriteria(a,this.layerIdentifier))for(var c=0,d=a.length;c<d;++c){var e=a[c],f=e.nodeName;e.prefix&&(f=f.split(":")[1]);f=f.replace(this.layerIdentifier,"");if(e=this.getSiblingNodesByTagCriteria(e,this.featureIdentifier))for(var g=0;g<e.length;g++){var h=e[g],k=this.parseGeometry(h),h=this.parseAttributes(h),h=new OpenLayers.Feature.Vector(k.geometry,h,null);h.bounds=k.bounds;h.type=f;b.push(h)}}return b},read_FeatureInfoResponse:function(a){var b=[];a=this.getElementsByTagNameNS(a,
2978 "*","FIELDS");for(var c=0,d=a.length;c<d;c++){var e=a[c],f={},g,h=e.attributes.length;if(0<h)for(g=0;g<h;g++){var k=e.attributes[g];f[k.nodeName]=k.nodeValue}else for(e=e.childNodes,g=0,h=e.length;g<h;++g)k=e[g],3!=k.nodeType&&(f[k.getAttribute("name")]=k.getAttribute("value"));b.push(new OpenLayers.Feature.Vector(null,f,null))}return b},getSiblingNodesByTagCriteria:function(a,b){var c=[],d,e,f,g;if(a&&a.hasChildNodes()){d=a.childNodes;f=d.length;for(var h=0;h<f;h++){for(g=d[h];g&&1!=g.nodeType;)g=
2979 g.nextSibling,h++;e=g?g.nodeName:"";0<e.length&&-1<e.indexOf(b)?c.push(g):(e=this.getSiblingNodesByTagCriteria(g,b),0<e.length&&(0==c.length?c=e:c.push(e)))}}return c},parseAttributes:function(a){var b={};if(1==a.nodeType){a=a.childNodes;for(var c=a.length,d=0;d<c;++d){var e=a[d];if(1==e.nodeType){var f=e.childNodes,e=e.prefix?e.nodeName.split(":")[1]:e.nodeName;0==f.length?b[e]=null:1==f.length&&(f=f[0],3==f.nodeType||4==f.nodeType)&&(f=f.nodeValue.replace(this.regExes.trimSpace,""),b[e]=f)}}}return b},
2980 parseGeometry:function(a){this.gmlFormat||(this.gmlFormat=new OpenLayers.Format.GML);a=this.gmlFormat.parseFeature(a);var b,c=null;a&&(b=a.geometry&&a.geometry.clone(),c=a.bounds&&a.bounds.clone(),a.destroy());return{geometry:b,bounds:c}},CLASS_NAME:"OpenLayers.Format.WMSGetFeatureInfo"});OpenLayers.Control.WMTSGetFeatureInfo=OpenLayers.Class(OpenLayers.Control,{hover:!1,requestEncoding:"KVP",drillDown:!1,maxFeatures:10,clickCallback:"click",layers:null,queryVisible:!0,infoFormat:"text/html",vendorParams:{},format:null,formatOptions:null,handler:null,hoverRequest:null,pending:0,initialize:function(a){a=a||{};a.handlerOptions=a.handlerOptions||{};OpenLayers.Control.prototype.initialize.apply(this,[a]);this.format||(this.format=new OpenLayers.Format.WMSGetFeatureInfo(a.formatOptions));
2981 !0===this.drillDown&&(this.hover=!1);this.hover?this.handler=new OpenLayers.Handler.Hover(this,{move:this.cancelHover,pause:this.getInfoForHover},OpenLayers.Util.extend(this.handlerOptions.hover||{},{delay:250})):(a={},a[this.clickCallback]=this.getInfoForClick,this.handler=new OpenLayers.Handler.Click(this,a,this.handlerOptions.click||{}))},getInfoForClick:function(a){this.request(a.xy,{})},getInfoForHover:function(a){this.request(a.xy,{hover:!0})},cancelHover:function(){this.hoverRequest&&(--this.pending,
2982 0>=this.pending&&(OpenLayers.Element.removeClass(this.map.viewPortDiv,"olCursorWait"),this.pending=0),this.hoverRequest.abort(),this.hoverRequest=null)},findLayers:function(){for(var a=this.layers||this.map.layers,b=[],c,d=a.length-1;0<=d&&(c=a[d],!(c instanceof OpenLayers.Layer.WMTS)||(c.requestEncoding!==this.requestEncoding||this.queryVisible&&!c.getVisibility())||(b.push(c),this.drillDown&&!this.hover));--d);return b},buildRequestOptions:function(a,b){var c=this.map.getLonLatFromPixel(b),d=a.getURL(new OpenLayers.Bounds(c.lon,
2983 c.lat,c.lon,c.lat)),d=OpenLayers.Util.getParameters(d),c=a.getTileInfo(c);OpenLayers.Util.extend(d,{service:"WMTS",version:a.version,request:"GetFeatureInfo",infoFormat:this.infoFormat,i:c.i,j:c.j});OpenLayers.Util.applyDefaults(d,this.vendorParams);return{url:OpenLayers.Util.isArray(a.url)?a.url[0]:a.url,params:OpenLayers.Util.upperCaseObject(d),callback:function(c){this.handleResponse(b,c,a)},scope:this}},request:function(a,b){b=b||{};var c=this.findLayers();if(0<c.length){for(var d,e,f=0,g=c.length;f<
2984 g;f++)e=c[f],d=this.events.triggerEvent("beforegetfeatureinfo",{xy:a,layer:e}),!1!==d&&(++this.pending,d=this.buildRequestOptions(e,a),d=OpenLayers.Request.GET(d),!0===b.hover&&(this.hoverRequest=d));0<this.pending&&OpenLayers.Element.addClass(this.map.viewPortDiv,"olCursorWait")}},handleResponse:function(a,b,c){--this.pending;0>=this.pending&&(OpenLayers.Element.removeClass(this.map.viewPortDiv,"olCursorWait"),this.pending=0);if(b.status&&(200>b.status||300<=b.status))this.events.triggerEvent("exception",
2985 {xy:a,request:b,layer:c});else{var d=b.responseXML;d&&d.documentElement||(d=b.responseText);var e,f;try{e=this.format.read(d)}catch(g){f=!0,this.events.triggerEvent("exception",{xy:a,request:b,error:g,layer:c})}f||this.events.triggerEvent("getfeatureinfo",{text:b.responseText,features:e,request:b,xy:a,layer:c})}},CLASS_NAME:"OpenLayers.Control.WMTSGetFeatureInfo"});OpenLayers.Protocol.CSW.v2_0_2=OpenLayers.Class(OpenLayers.Protocol,{formatOptions:null,initialize:function(a){OpenLayers.Protocol.prototype.initialize.apply(this,[a]);a.format||(this.format=new OpenLayers.Format.CSWGetRecords.v2_0_2(OpenLayers.Util.extend({},this.formatOptions)))},destroy:function(){this.options&&!this.options.format&&this.format.destroy();this.format=null;OpenLayers.Protocol.prototype.destroy.apply(this)},read:function(a){a=OpenLayers.Util.extend({},a);OpenLayers.Util.applyDefaults(a,
2986 this.options||{});var b=new OpenLayers.Protocol.Response({requestType:"read"}),c=this.format.write(a.params||a);b.priv=OpenLayers.Request.POST({url:a.url,callback:this.createCallback(this.handleRead,b,a),params:a.params,headers:a.headers,data:c});return b},handleRead:function(a,b){if(b.callback){var c=a.priv;200<=c.status&&300>c.status?(a.data=this.parseData(c),a.code=OpenLayers.Protocol.Response.SUCCESS):a.code=OpenLayers.Protocol.Response.FAILURE;b.callback.call(b.scope,a)}},parseData:function(a){var b=
2987 a.responseXML;b&&b.documentElement||(b=a.responseText);return!b||0>=b.length?null:this.format.read(b)},CLASS_NAME:"OpenLayers.Protocol.CSW.v2_0_2"});OpenLayers.Format.WCSCapabilities.v1_1_0=OpenLayers.Class(OpenLayers.Format.WCSCapabilities.v1,{namespaces:{wcs:"http://www.opengis.net/wcs/1.1",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance",ows:"http://www.opengis.net/ows/1.1"},errorProperty:"operationsMetadata",readers:{wcs:OpenLayers.Util.applyDefaults({Capabilities:function(a,b){this.readChildNodes(a,b)},Contents:function(a,b){b.contentMetadata=[];this.readChildNodes(a,b.contentMetadata)},CoverageSummary:function(a,
2988 b){var c={};this.readChildNodes(a,c);b.push(c)},Identifier:function(a,b){b.identifier=this.getChildValue(a)},Title:function(a,b){b.title=this.getChildValue(a)},Abstract:function(a,b){b["abstract"]=this.getChildValue(a)},SupportedCRS:function(a,b){var c=this.getChildValue(a);c&&(b.supportedCRS||(b.supportedCRS=[]),b.supportedCRS.push(c))},SupportedFormat:function(a,b){var c=this.getChildValue(a);c&&(b.supportedFormat||(b.supportedFormat=[]),b.supportedFormat.push(c))}},OpenLayers.Format.WCSCapabilities.v1.prototype.readers.wcs),
2989 ows:OpenLayers.Format.OWSCommon.v1_1_0.prototype.readers.ows},CLASS_NAME:"OpenLayers.Format.WCSCapabilities.v1_1_0"});OpenLayers.Control.Graticule=OpenLayers.Class(OpenLayers.Control,{autoActivate:!0,intervals:[45,30,20,10,5,2,1,0.5,0.2,0.1,0.05,0.01,0.005,0.002,0.001],displayInLayerSwitcher:!0,visible:!0,numPoints:50,targetSize:200,layerName:null,labelled:!0,labelFormat:"dm",lineSymbolizer:{strokeColor:"#333",strokeWidth:1,strokeOpacity:0.5},labelSymbolizer:{},gratLayer:null,initialize:function(a){a=a||{};a.layerName=a.layerName||OpenLayers.i18n("Graticule");OpenLayers.Control.prototype.initialize.apply(this,[a]);
2990 this.labelSymbolizer.stroke=!1;this.labelSymbolizer.fill=!1;this.labelSymbolizer.label="${label}";this.labelSymbolizer.labelAlign="${labelAlign}";this.labelSymbolizer.labelXOffset="${xOffset}";this.labelSymbolizer.labelYOffset="${yOffset}"},destroy:function(){this.deactivate();OpenLayers.Control.prototype.destroy.apply(this,arguments);this.gratLayer&&(this.gratLayer.destroy(),this.gratLayer=null)},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);if(!this.gratLayer){var a=new OpenLayers.Style({},
2991 {rules:[new OpenLayers.Rule({symbolizer:{Point:this.labelSymbolizer,Line:this.lineSymbolizer}})]});this.gratLayer=new OpenLayers.Layer.Vector(this.layerName,{styleMap:new OpenLayers.StyleMap({"default":a}),visibility:this.visible,displayInLayerSwitcher:this.displayInLayerSwitcher})}return this.div},activate:function(){return OpenLayers.Control.prototype.activate.apply(this,arguments)?(this.map.addLayer(this.gratLayer),this.map.events.register("moveend",this,this.update),this.update(),!0):!1},deactivate:function(){return OpenLayers.Control.prototype.deactivate.apply(this,
2992 arguments)?(this.map.events.unregister("moveend",this,this.update),this.map.removeLayer(this.gratLayer),!0):!1},update:function(){var a=this.map.getExtent();if(a){this.gratLayer.destroyFeatures();var b=new OpenLayers.Projection("EPSG:4326"),c=this.map.getProjectionObject(),d=this.map.getResolution();c.proj&&"longlat"==c.proj.projName&&(this.numPoints=1);var e=this.map.getCenter(),f=new OpenLayers.Pixel(e.lon,e.lat);OpenLayers.Projection.transform(f,c,b);for(var e=this.targetSize*d,e=e*e,g,d=0;d<this.intervals.length;++d){g=
2993 this.intervals[d];var h=g/2,k=f.offset({x:-h,y:-h}),h=f.offset({x:h,y:h});OpenLayers.Projection.transform(k,b,c);OpenLayers.Projection.transform(h,b,c);if((k.x-h.x)*(k.x-h.x)+(k.y-h.y)*(k.y-h.y)<=e)break}f.x=Math.floor(f.x/g)*g;f.y=Math.floor(f.y/g)*g;var d=0,e=[f.clone()],h=f.clone(),l;do h=h.offset({x:0,y:g}),l=OpenLayers.Projection.transform(h.clone(),b,c),e.unshift(h);while(a.containsPixel(l)&&1E3>++d);h=f.clone();do h=h.offset({x:0,y:-g}),l=OpenLayers.Projection.transform(h.clone(),b,c),e.push(h);
2994 while(a.containsPixel(l)&&1E3>++d);d=0;k=[f.clone()];h=f.clone();do h=h.offset({x:-g,y:0}),l=OpenLayers.Projection.transform(h.clone(),b,c),k.unshift(h);while(a.containsPixel(l)&&1E3>++d);h=f.clone();do h=h.offset({x:g,y:0}),l=OpenLayers.Projection.transform(h.clone(),b,c),k.push(h);while(a.containsPixel(l)&&1E3>++d);g=[];for(d=0;d<k.length;++d){l=k[d].x;for(var f=[],m=null,n=Math.min(e[0].y,90),h=Math.max(e[e.length-1].y,-90),p=(n-h)/this.numPoints,n=h,h=0;h<=this.numPoints;++h){var q=new OpenLayers.Geometry.Point(l,
2995 n);q.transform(b,c);f.push(q);n+=p;q.y>=a.bottom&&!m&&(m=q)}this.labelled&&(m=new OpenLayers.Geometry.Point(m.x,a.bottom),l={value:l,label:this.labelled?OpenLayers.Util.getFormattedLonLat(l,"lon",this.labelFormat):"",labelAlign:"cb",xOffset:0,yOffset:2},this.gratLayer.addFeatures(new OpenLayers.Feature.Vector(m,l)));f=new OpenLayers.Geometry.LineString(f);g.push(new OpenLayers.Feature.Vector(f))}for(h=0;h<e.length;++h)if(n=e[h].y,!(-90>n||90<n)){f=[];d=k[0].x;p=(k[k.length-1].x-d)/this.numPoints;
2996 l=d;m=null;for(d=0;d<=this.numPoints;++d)q=new OpenLayers.Geometry.Point(l,n),q.transform(b,c),f.push(q),l+=p,q.x<a.right&&(m=q);this.labelled&&(m=new OpenLayers.Geometry.Point(a.right,m.y),l={value:n,label:this.labelled?OpenLayers.Util.getFormattedLonLat(n,"lat",this.labelFormat):"",labelAlign:"rb",xOffset:-2,yOffset:2},this.gratLayer.addFeatures(new OpenLayers.Feature.Vector(m,l)));f=new OpenLayers.Geometry.LineString(f);g.push(new OpenLayers.Feature.Vector(f))}this.gratLayer.addFeatures(g)}},CLASS_NAME:"OpenLayers.Control.Graticule"});OpenLayers.Console.warn("OpenLayers.Rico is deprecated");OpenLayers.Rico=OpenLayers.Rico||{};
2997 OpenLayers.Rico.Corner={round:function(a,b){a=OpenLayers.Util.getElement(a);this._setOptions(b);var c=this.options.color;"fromElement"==this.options.color&&(c=this._background(a));var d=this.options.bgColor;"fromParent"==this.options.bgColor&&(d=this._background(a.offsetParent));this._roundCornersImpl(a,c,d)},changeColor:function(a,b){a.style.backgroundColor=b;for(var c=a.parentNode.getElementsByTagName("span"),d=0;d<c.length;d++)c[d].style.backgroundColor=b},changeOpacity:function(a,b){var c="alpha(opacity="+
2998 100*b+")";a.style.opacity=b;a.style.filter=c;for(var d=a.parentNode.getElementsByTagName("span"),e=0;e<d.length;e++)d[e].style.opacity=b,d[e].style.filter=c},reRound:function(a,b){var c=a.parentNode.childNodes[2];a.parentNode.removeChild(a.parentNode.childNodes[0]);a.parentNode.removeChild(c);this.round(a.parentNode,b)},_roundCornersImpl:function(a,b,c){this.options.border&&this._renderBorder(a,c);this._isTopRounded()&&this._roundTopCorners(a,b,c);this._isBottomRounded()&&this._roundBottomCorners(a,
2999 b,c)},_renderBorder:function(a,b){var c="1px solid "+this._borderColor(b);a.innerHTML="<div "+("style='border-left: "+c+";"+("border-right: "+c)+"'")+">"+a.innerHTML+"</div>"},_roundTopCorners:function(a,b,c){for(var d=this._createCorner(c),e=0;e<this.options.numSlices;e++)d.appendChild(this._createCornerSlice(b,c,e,"top"));a.style.paddingTop=0;a.insertBefore(d,a.firstChild)},_roundBottomCorners:function(a,b,c){for(var d=this._createCorner(c),e=this.options.numSlices-1;0<=e;e--)d.appendChild(this._createCornerSlice(b,
3000 c,e,"bottom"));a.style.paddingBottom=0;a.appendChild(d)},_createCorner:function(a){var b=document.createElement("div");b.style.backgroundColor=this._isTransparent()?"transparent":a;return b},_createCornerSlice:function(a,b,c,d){var e=document.createElement("span"),f=e.style;f.backgroundColor=a;f.display="block";f.height="1px";f.overflow="hidden";f.fontSize="1px";a=this._borderColor(a,b);this.options.border&&0==c?(f.borderTopStyle="solid",f.borderTopWidth="1px",f.borderLeftWidth="0px",f.borderRightWidth=
3001 "0px",f.borderBottomWidth="0px",f.height="0px",f.borderColor=a):a&&(f.borderColor=a,f.borderStyle="solid",f.borderWidth="0px 1px");this.options.compact||c!=this.options.numSlices-1||(f.height="2px");this._setMargin(e,c,d);this._setBorder(e,c,d);return e},_setOptions:function(a){this.options={corners:"all",color:"fromElement",bgColor:"fromParent",blend:!0,border:!1,compact:!1};OpenLayers.Util.extend(this.options,a||{});this.options.numSlices=this.options.compact?2:4;this._isTransparent()&&(this.options.blend=
3002 !1)},_whichSideTop:function(){return this._hasString(this.options.corners,"all","top")||0<=this.options.corners.indexOf("tl")&&0<=this.options.corners.indexOf("tr")?"":0<=this.options.corners.indexOf("tl")?"left":0<=this.options.corners.indexOf("tr")?"right":""},_whichSideBottom:function(){return this._hasString(this.options.corners,"all","bottom")||0<=this.options.corners.indexOf("bl")&&0<=this.options.corners.indexOf("br")?"":0<=this.options.corners.indexOf("bl")?"left":0<=this.options.corners.indexOf("br")?
3003 "right":""},_borderColor:function(a,b){return"transparent"==a?b:this.options.border?this.options.border:this.options.blend?this._blend(b,a):""},_setMargin:function(a,b,c){b=this._marginSize(b);c="top"==c?this._whichSideTop():this._whichSideBottom();"left"==c?(a.style.marginLeft=b+"px",a.style.marginRight="0px"):"right"==c?(a.style.marginRight=b+"px",a.style.marginLeft="0px"):(a.style.marginLeft=b+"px",a.style.marginRight=b+"px")},_setBorder:function(a,b,c){b=this._borderSize(b);c="top"==c?this._whichSideTop():
3004 this._whichSideBottom();"left"==c?(a.style.borderLeftWidth=b+"px",a.style.borderRightWidth="0px"):"right"==c?(a.style.borderRightWidth=b+"px",a.style.borderLeftWidth="0px"):(a.style.borderLeftWidth=b+"px",a.style.borderRightWidth=b+"px");!1!=this.options.border&&(a.style.borderLeftWidth=b+"px",a.style.borderRightWidth=b+"px")},_marginSize:function(a){if(this._isTransparent())return 0;var b=[5,3,2,1],c=[3,2,1,0],d=[2,1],e=[1,0];return this.options.compact&&this.options.blend?e[a]:this.options.compact?
3005 d[a]:this.options.blend?c[a]:b[a]},_borderSize:function(a){var b=[5,3,2,1],c=[2,1,1,1],d=[1,0],e=[0,2,0,0];return this.options.compact&&(this.options.blend||this._isTransparent())?1:this.options.compact?d[a]:this.options.blend?c[a]:this.options.border?e[a]:this._isTransparent()?b[a]:0},_hasString:function(a){for(var b=1;b<arguments.length;b++)if(0<=a.indexOf(arguments[b]))return!0;return!1},_blend:function(a,b){var c=OpenLayers.Rico.Color.createFromHex(a);c.blend(OpenLayers.Rico.Color.createFromHex(b));
3006 return c},_background:function(a){try{return OpenLayers.Rico.Color.createColorFromBackground(a).asHex()}catch(b){return"#ffffff"}},_isTransparent:function(){return"transparent"==this.options.color},_isTopRounded:function(){return this._hasString(this.options.corners,"all","top","tl","tr")},_isBottomRounded:function(){return this._hasString(this.options.corners,"all","bottom","bl","br")},_hasSingleTextChild:function(a){return 1==a.childNodes.length&&3==a.childNodes[0].nodeType}};OpenLayers.Control.NavigationHistory=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_TOGGLE,previous:null,previousOptions:null,next:null,nextOptions:null,limit:50,autoActivate:!0,clearOnDeactivate:!1,registry:null,nextStack:null,previousStack:null,listeners:null,restoring:!1,initialize:function(a){OpenLayers.Control.prototype.initialize.apply(this,[a]);this.registry=OpenLayers.Util.extend({moveend:this.getState},this.registry);a={trigger:OpenLayers.Function.bind(this.previousTrigger,
3007 this),displayClass:this.displayClass+" "+this.displayClass+"Previous"};OpenLayers.Util.extend(a,this.previousOptions);this.previous=new OpenLayers.Control.Button(a);a={trigger:OpenLayers.Function.bind(this.nextTrigger,this),displayClass:this.displayClass+" "+this.displayClass+"Next"};OpenLayers.Util.extend(a,this.nextOptions);this.next=new OpenLayers.Control.Button(a);this.clear()},onPreviousChange:function(a,b){a&&!this.previous.active?this.previous.activate():!a&&this.previous.active&&this.previous.deactivate()},
3008 onNextChange:function(a,b){a&&!this.next.active?this.next.activate():!a&&this.next.active&&this.next.deactivate()},destroy:function(){OpenLayers.Control.prototype.destroy.apply(this);this.previous.destroy();this.next.destroy();this.deactivate();for(var a in this)this[a]=null},setMap:function(a){this.map=a;this.next.setMap(a);this.previous.setMap(a)},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);this.next.draw();this.previous.draw()},previousTrigger:function(){var a=this.previousStack.shift(),
3009 b=this.previousStack.shift();void 0!=b?(this.nextStack.unshift(a),this.previousStack.unshift(b),this.restoring=!0,this.restore(b),this.restoring=!1,this.onNextChange(this.nextStack[0],this.nextStack.length),this.onPreviousChange(this.previousStack[1],this.previousStack.length-1)):this.previousStack.unshift(a);return b},nextTrigger:function(){var a=this.nextStack.shift();void 0!=a&&(this.previousStack.unshift(a),this.restoring=!0,this.restore(a),this.restoring=!1,this.onNextChange(this.nextStack[0],
3010 this.nextStack.length),this.onPreviousChange(this.previousStack[1],this.previousStack.length-1));return a},clear:function(){this.previousStack=[];this.previous.deactivate();this.nextStack=[];this.next.deactivate()},getState:function(){return{center:this.map.getCenter(),resolution:this.map.getResolution(),projection:this.map.getProjectionObject(),units:this.map.getProjectionObject().getUnits()||this.map.units||this.map.baseLayer.units}},restore:function(a){var b,c;if(this.map.getProjectionObject()==
3011 a.projection)c=this.map.getZoomForResolution(a.resolution),b=a.center;else{b=a.center.clone();b.transform(a.projection,this.map.getProjectionObject());c=a.units;var d=this.map.getProjectionObject().getUnits()||this.map.units||this.map.baseLayer.units;c=this.map.getZoomForResolution((c&&d?OpenLayers.INCHES_PER_UNIT[c]/OpenLayers.INCHES_PER_UNIT[d]:1)*a.resolution)}this.map.setCenter(b,c)},setListeners:function(){this.listeners={};for(var a in this.registry)this.listeners[a]=OpenLayers.Function.bind(function(){if(!this.restoring){var b=
3012 this.registry[a].apply(this,arguments);this.previousStack.unshift(b);if(1<this.previousStack.length)this.onPreviousChange(this.previousStack[1],this.previousStack.length-1);this.previousStack.length>this.limit+1&&this.previousStack.pop();0<this.nextStack.length&&(this.nextStack=[],this.onNextChange(null,0))}return!0},this)},activate:function(){var a=!1;if(this.map&&OpenLayers.Control.prototype.activate.apply(this)){null==this.listeners&&this.setListeners();for(var b in this.listeners)this.map.events.register(b,
3013 this,this.listeners[b]);a=!0;0==this.previousStack.length&&this.initStack()}return a},initStack:function(){this.map.getCenter()&&this.listeners.moveend()},deactivate:function(){var a=!1;if(this.map&&OpenLayers.Control.prototype.deactivate.apply(this)){for(var b in this.listeners)this.map.events.unregister(b,this,this.listeners[b]);this.clearOnDeactivate&&this.clear();a=!0}return a},CLASS_NAME:"OpenLayers.Control.NavigationHistory"});OpenLayers.Layer.UTFGrid=OpenLayers.Class(OpenLayers.Layer.XYZ,{isBaseLayer:!1,projection:new OpenLayers.Projection("EPSG:900913"),useJSONP:!1,tileClass:OpenLayers.Tile.UTFGrid,initialize:function(a){OpenLayers.Layer.Grid.prototype.initialize.apply(this,[a.name,a.url,{},a]);this.tileOptions=OpenLayers.Util.extend({utfgridResolution:this.utfgridResolution},this.tileOptions)},createBackBuffer:function(){},clone:function(a){null==a&&(a=new OpenLayers.Layer.UTFGrid(this.getOptions()));return a=OpenLayers.Layer.Grid.prototype.clone.apply(this,
3014 [a])},getFeatureInfo:function(a){var b=null;(a=this.getTileData(a))&&a.tile&&(b=a.tile.getFeatureInfo(a.i,a.j));return b},getFeatureId:function(a){var b=null;a=this.getTileData(a);a.tile&&(b=a.tile.getFeatureId(a.i,a.j));return b},CLASS_NAME:"OpenLayers.Layer.UTFGrid"});OpenLayers.TileManager=OpenLayers.Class({cacheSize:256,tilesPerFrame:2,frameDelay:16,moveDelay:100,zoomDelay:200,maps:null,tileQueueId:null,tileQueue:null,tileCache:null,tileCacheIndex:null,initialize:function(a){OpenLayers.Util.extend(this,a);this.maps=[];this.tileQueueId={};this.tileQueue={};this.tileCache={};this.tileCacheIndex=[]},addMap:function(a){if(!this._destroyed&&OpenLayers.Layer.Grid){this.maps.push(a);this.tileQueue[a.id]=[];for(var b=0,c=a.layers.length;b<c;++b)this.addLayer({layer:a.layers[b]});
3015 a.events.on({move:this.move,zoomend:this.zoomEnd,changelayer:this.changeLayer,addlayer:this.addLayer,preremovelayer:this.removeLayer,scope:this})}},removeMap:function(a){if(!this._destroyed&&OpenLayers.Layer.Grid){window.clearTimeout(this.tileQueueId[a.id]);if(a.layers)for(var b=0,c=a.layers.length;b<c;++b)this.removeLayer({layer:a.layers[b]});a.events&&a.events.un({move:this.move,zoomend:this.zoomEnd,changelayer:this.changeLayer,addlayer:this.addLayer,preremovelayer:this.removeLayer,scope:this});
3016 delete this.tileQueue[a.id];delete this.tileQueueId[a.id];OpenLayers.Util.removeItem(this.maps,a)}},move:function(a){this.updateTimeout(a.object,this.moveDelay,!0)},zoomEnd:function(a){this.updateTimeout(a.object,this.zoomDelay)},changeLayer:function(a){"visibility"!==a.property&&"params"!==a.property||this.updateTimeout(a.object,0)},addLayer:function(a){a=a.layer;if(a instanceof OpenLayers.Layer.Grid){a.events.on({addtile:this.addTile,retile:this.clearTileQueue,scope:this});var b,c,d;for(b=a.grid.length-
3017 1;0<=b;--b)for(c=a.grid[b].length-1;0<=c;--c)d=a.grid[b][c],this.addTile({tile:d}),d.url&&!d.imgDiv&&this.manageTileCache({object:d})}},removeLayer:function(a){a=a.layer;if(a instanceof OpenLayers.Layer.Grid&&(this.clearTileQueue({object:a}),a.events&&a.events.un({addtile:this.addTile,retile:this.clearTileQueue,scope:this}),a.grid)){var b,c,d;for(b=a.grid.length-1;0<=b;--b)for(c=a.grid[b].length-1;0<=c;--c)d=a.grid[b][c],this.unloadTile({object:d})}},updateTimeout:function(a,b,c){window.clearTimeout(this.tileQueueId[a.id]);
3018 var d=this.tileQueue[a.id];if(!c||d.length)this.tileQueueId[a.id]=window.setTimeout(OpenLayers.Function.bind(function(){this.drawTilesFromQueue(a);d.length&&this.updateTimeout(a,this.frameDelay)},this),b)},addTile:function(a){if(a.tile instanceof OpenLayers.Tile.Image)a.tile.events.on({beforedraw:this.queueTileDraw,beforeload:this.manageTileCache,loadend:this.addToCache,unload:this.unloadTile,scope:this});else this.removeLayer({layer:a.tile.layer})},unloadTile:function(a){a=a.object;a.events.un({beforedraw:this.queueTileDraw,
3019 beforeload:this.manageTileCache,loadend:this.addToCache,unload:this.unloadTile,scope:this});OpenLayers.Util.removeItem(this.tileQueue[a.layer.map.id],a)},queueTileDraw:function(a){a=a.object;var b=!1,c=a.layer,d=c.getURL(a.bounds),e=this.tileCache[d];e&&"olTileImage"!==e.className&&(delete this.tileCache[d],OpenLayers.Util.removeItem(this.tileCacheIndex,d),e=null);!c.url||!c.async&&e||(b=this.tileQueue[c.map.id],~OpenLayers.Util.indexOf(b,a)||b.push(a),b=!0);return!b},drawTilesFromQueue:function(a){var b=
3020 this.tileQueue[a.id],c=this.tilesPerFrame;for(a=a.zoomTween&&a.zoomTween.playing;!a&&b.length&&c;)b.shift().draw(!0),--c},manageTileCache:function(a){a=a.object;var b=this.tileCache[a.url];b&&(b.parentNode&&OpenLayers.Element.hasClass(b.parentNode,"olBackBuffer")&&(b.parentNode.removeChild(b),b.id=null),b.parentNode||(b.style.visibility="hidden",b.style.opacity=0,a.setImage(b),OpenLayers.Util.removeItem(this.tileCacheIndex,a.url),this.tileCacheIndex.push(a.url)))},addToCache:function(a){a=a.object;
3021 this.tileCache[a.url]||OpenLayers.Element.hasClass(a.imgDiv,"olImageLoadError")||(this.tileCacheIndex.length>=this.cacheSize&&(delete this.tileCache[this.tileCacheIndex[0]],this.tileCacheIndex.shift()),this.tileCache[a.url]=a.imgDiv,this.tileCacheIndex.push(a.url))},clearTileQueue:function(a){a=a.object;for(var b=this.tileQueue[a.map.id],c=b.length-1;0<=c;--c)b[c].layer===a&&b.splice(c,1)},destroy:function(){for(var a=this.maps.length-1;0<=a;--a)this.removeMap(this.maps[a]);this.tileCacheIndex=this.tileCache=
3022 this.tileQueueId=this.tileQueue=this.maps=null;this._destroyed=!0}});OpenLayers.Layer.ArcGISCache=OpenLayers.Class(OpenLayers.Layer.XYZ,{url:null,tileOrigin:null,tileSize:new OpenLayers.Size(256,256),useArcGISServer:!0,type:"png",useScales:!1,overrideDPI:!1,initialize:function(a,b,c){OpenLayers.Layer.XYZ.prototype.initialize.apply(this,arguments);this.resolutions&&(this.serverResolutions=this.resolutions,this.maxExtent=this.getMaxExtentForResolution(this.resolutions[0]));if(this.layerInfo){var d=this.layerInfo,e=new OpenLayers.Bounds(d.fullExtent.xmin,d.fullExtent.ymin,
3023 d.fullExtent.xmax,d.fullExtent.ymax);this.projection="EPSG:"+d.spatialReference.wkid;this.sphericalMercator=102100==d.spatialReference.wkid;this.units="esriFeet"==d.units?"ft":"m";if(d.tileInfo){this.tileSize=new OpenLayers.Size(d.tileInfo.width||d.tileInfo.cols,d.tileInfo.height||d.tileInfo.rows);this.tileOrigin=new OpenLayers.LonLat(d.tileInfo.origin.x,d.tileInfo.origin.y);var f=new OpenLayers.Geometry.Point(e.left,e.top),e=new OpenLayers.Geometry.Point(e.right,e.bottom);this.useScales?this.scales=
3024 []:this.resolutions=[];this.lods=[];for(var g in d.tileInfo.lods)if(d.tileInfo.lods.hasOwnProperty(g)){var h=d.tileInfo.lods[g];this.useScales?this.scales.push(h.scale):this.resolutions.push(h.resolution);var k=this.getContainingTileCoords(f,h.resolution);h.startTileCol=k.x;h.startTileRow=k.y;k=this.getContainingTileCoords(e,h.resolution);h.endTileCol=k.x;h.endTileRow=k.y;this.lods.push(h)}this.maxExtent=this.calculateMaxExtentWithLOD(this.lods[0]);this.serverResolutions=this.resolutions;this.overrideDPI&&
3025 d.tileInfo.dpi&&(OpenLayers.DOTS_PER_INCH=d.tileInfo.dpi)}}},getContainingTileCoords:function(a,b){return new OpenLayers.Pixel(Math.max(Math.floor((a.x-this.tileOrigin.lon)/(this.tileSize.w*b)),0),Math.max(Math.floor((this.tileOrigin.lat-a.y)/(this.tileSize.h*b)),0))},calculateMaxExtentWithLOD:function(a){var b=this.tileOrigin.lon+a.startTileCol*this.tileSize.w*a.resolution,c=this.tileOrigin.lat-a.startTileRow*this.tileSize.h*a.resolution;return new OpenLayers.Bounds(b,c-(a.endTileRow-a.startTileRow+
3026 1)*this.tileSize.h*a.resolution,b+(a.endTileCol-a.startTileCol+1)*this.tileSize.w*a.resolution,c)},calculateMaxExtentWithExtent:function(a,b){var c=new OpenLayers.Geometry.Point(a.left,a.top),d=new OpenLayers.Geometry.Point(a.right,a.bottom),c=this.getContainingTileCoords(c,b),d=this.getContainingTileCoords(d,b);return this.calculateMaxExtentWithLOD({resolution:b,startTileCol:c.x,startTileRow:c.y,endTileCol:d.x,endTileRow:d.y})},getUpperLeftTileCoord:function(a){var b=new OpenLayers.Geometry.Point(this.maxExtent.left,
3027 this.maxExtent.top);return this.getContainingTileCoords(b,a)},getLowerRightTileCoord:function(a){var b=new OpenLayers.Geometry.Point(this.maxExtent.right,this.maxExtent.bottom);return this.getContainingTileCoords(b,a)},getMaxExtentForResolution:function(a){var b=this.getUpperLeftTileCoord(a),c=this.getLowerRightTileCoord(a),d=this.tileOrigin.lon+b.x*this.tileSize.w*a,e=this.tileOrigin.lat-b.y*this.tileSize.h*a;return new OpenLayers.Bounds(d,e-(c.y-b.y+1)*this.tileSize.h*a,d+(c.x-b.x+1)*this.tileSize.w*
3028 a,e)},clone:function(a){null==a&&(a=new OpenLayers.Layer.ArcGISCache(this.name,this.url,this.options));return OpenLayers.Layer.XYZ.prototype.clone.apply(this,[a])},initGriddedTiles:function(a){delete this._tileOrigin;OpenLayers.Layer.XYZ.prototype.initGriddedTiles.apply(this,arguments)},getMaxExtent:function(){var a=this.map.getResolution();return this.maxExtent=this.getMaxExtentForResolution(a)},getTileOrigin:function(){if(!this._tileOrigin){var a=this.getMaxExtent();this._tileOrigin=new OpenLayers.LonLat(a.left,
3029 a.bottom)}return this._tileOrigin},getURL:function(a){var b=this.getResolution(),c=this.tileOrigin.lon+b*this.tileSize.w/2,d=this.tileOrigin.lat-b*this.tileSize.h/2;a=a.getCenterLonLat();c=Math.round(Math.abs((a.lon-c)/(b*this.tileSize.w)));d=Math.round(Math.abs((d-a.lat)/(b*this.tileSize.h)));a=this.map.getZoom();if(this.lods){if(b=this.lods[this.map.getZoom()],c<b.startTileCol||c>b.endTileCol||d<b.startTileRow||d>b.endTileRow)return null}else{var e=this.getUpperLeftTileCoord(b),b=this.getLowerRightTileCoord(b);
3030 if(c<e.x||c>=b.x||d<e.y||d>=b.y)return null}b=this.url;e=""+c+d+a;OpenLayers.Util.isArray(b)&&(b=this.selectUrl(e,b));this.useArcGISServer?b+="/tile/${z}/${y}/${x}":(c="C"+OpenLayers.Number.zeroPad(c,8,16),d="R"+OpenLayers.Number.zeroPad(d,8,16),a="L"+OpenLayers.Number.zeroPad(a,2,10),b=b+"/${z}/${y}/${x}."+this.type);b=OpenLayers.String.format(b,{x:c,y:d,z:a});return OpenLayers.Util.urlAppend(b,OpenLayers.Util.getParameterString(this.params))},CLASS_NAME:"OpenLayers.Layer.ArcGISCache"});OpenLayers.Control.WMSGetFeatureInfo=OpenLayers.Class(OpenLayers.Control,{hover:!1,drillDown:!1,maxFeatures:10,clickCallback:"click",output:"features",layers:null,queryVisible:!1,url:null,layerUrls:null,infoFormat:"text/html",vendorParams:{},format:null,formatOptions:null,handler:null,hoverRequest:null,initialize:function(a){a=a||{};a.handlerOptions=a.handlerOptions||{};OpenLayers.Control.prototype.initialize.apply(this,[a]);this.format||(this.format=new OpenLayers.Format.WMSGetFeatureInfo(a.formatOptions));
3031 !0===this.drillDown&&(this.hover=!1);this.hover?this.handler=new OpenLayers.Handler.Hover(this,{move:this.cancelHover,pause:this.getInfoForHover},OpenLayers.Util.extend(this.handlerOptions.hover||{},{delay:250})):(a={},a[this.clickCallback]=this.getInfoForClick,this.handler=new OpenLayers.Handler.Click(this,a,this.handlerOptions.click||{}))},getInfoForClick:function(a){this.events.triggerEvent("beforegetfeatureinfo",{xy:a.xy});OpenLayers.Element.addClass(this.map.viewPortDiv,"olCursorWait");this.request(a.xy,
3032 {})},getInfoForHover:function(a){this.events.triggerEvent("beforegetfeatureinfo",{xy:a.xy});this.request(a.xy,{hover:!0})},cancelHover:function(){this.hoverRequest&&(this.hoverRequest.abort(),this.hoverRequest=null)},findLayers:function(){for(var a=this.layers||this.map.layers,b=[],c,d,e=a.length-1;0<=e;--e)c=a[e],c instanceof OpenLayers.Layer.WMS&&(!this.queryVisible||c.getVisibility())&&(d=OpenLayers.Util.isArray(c.url)?c.url[0]:c.url,!1!==this.drillDown||this.url||(this.url=d),(!0===this.drillDown||
3033 this.urlMatches(d))&&b.push(c));return b},urlMatches:function(a){var b=OpenLayers.Util.isEquivalentUrl(this.url,a);if(!b&&this.layerUrls)for(var c=0,d=this.layerUrls.length;c<d;++c)if(OpenLayers.Util.isEquivalentUrl(this.layerUrls[c],a)){b=!0;break}return b},buildWMSOptions:function(a,b,c,d){for(var e=[],f=[],g=0,h=b.length;g<h;g++)null!=b[g].params.LAYERS&&(e=e.concat(b[g].params.LAYERS),f=f.concat(this.getStyleNames(b[g])));b=b[0];g=this.map.getProjection();(h=b.projection)&&h.equals(this.map.getProjectionObject())&&
3034 (g=h.getCode());d=OpenLayers.Util.extend({service:"WMS",version:b.params.VERSION,request:"GetFeatureInfo",exceptions:b.params.EXCEPTIONS,bbox:this.map.getExtent().toBBOX(null,b.reverseAxisOrder()),feature_count:this.maxFeatures,height:this.map.getSize().h,width:this.map.getSize().w,format:d,info_format:b.params.INFO_FORMAT||this.infoFormat},1.3<=parseFloat(b.params.VERSION)?{crs:g,i:parseInt(c.x),j:parseInt(c.y)}:{srs:g,x:parseInt(c.x),y:parseInt(c.y)});0!=e.length&&(d=OpenLayers.Util.extend({layers:e,
3035 query_layers:e,styles:f},d));OpenLayers.Util.applyDefaults(d,this.vendorParams);return{url:a,params:OpenLayers.Util.upperCaseObject(d),callback:function(b){this.handleResponse(c,b,a)},scope:this}},getStyleNames:function(a){return a.params.STYLES?a.params.STYLES:OpenLayers.Util.isArray(a.params.LAYERS)?Array(a.params.LAYERS.length):a.params.LAYERS.replace(/[^,]/g,"")},request:function(a,b){var c=this.findLayers();if(0==c.length)this.events.triggerEvent("nogetfeatureinfo"),OpenLayers.Element.removeClass(this.map.viewPortDiv,
3036 "olCursorWait");else if(b=b||{},!1===this.drillDown){var c=this.buildWMSOptions(this.url,c,a,c[0].params.FORMAT),d=OpenLayers.Request.GET(c);!0===b.hover&&(this.hoverRequest=d)}else{this._numRequests=this._requestCount=0;this.features=[];for(var d={},e,f=0,g=c.length;f<g;f++){var h=c[f];e=OpenLayers.Util.isArray(h.url)?h.url[0]:h.url;e in d?d[e].push(h):(this._numRequests++,d[e]=[h])}for(e in d)c=d[e],c=this.buildWMSOptions(e,c,a,c[0].params.FORMAT),OpenLayers.Request.GET(c)}},triggerGetFeatureInfo:function(a,
3037 b,c){this.events.triggerEvent("getfeatureinfo",{text:a.responseText,features:c,request:a,xy:b});OpenLayers.Element.removeClass(this.map.viewPortDiv,"olCursorWait")},handleResponse:function(a,b,c){var d=b.responseXML;d&&d.documentElement||(d=b.responseText);d=this.format.read(d);!1===this.drillDown?this.triggerGetFeatureInfo(b,a,d):(this._requestCount++,this._features="object"===this.output?(this._features||[]).concat({url:c,features:d}):(this._features||[]).concat(d),this._requestCount===this._numRequests&&
3038 (this.triggerGetFeatureInfo(b,a,this._features.concat()),delete this._features,delete this._requestCount,delete this._numRequests))},CLASS_NAME:"OpenLayers.Control.WMSGetFeatureInfo"});OpenLayers.Format.WMSCapabilities.v1_3_0=OpenLayers.Class(OpenLayers.Format.WMSCapabilities.v1_3,{version:"1.3.0",CLASS_NAME:"OpenLayers.Format.WMSCapabilities.v1_3_0"});OpenLayers.Format.SOSGetFeatureOfInterest=OpenLayers.Class(OpenLayers.Format.XML,{VERSION:"1.0.0",namespaces:{sos:"http://www.opengis.net/sos/1.0",gml:"http://www.opengis.net/gml",sa:"http://www.opengis.net/sampling/1.0",xsi:"http://www.w3.org/2001/XMLSchema-instance"},schemaLocation:"http://www.opengis.net/sos/1.0 http://schemas.opengis.net/sos/1.0.0/sosAll.xsd",defaultPrefix:"sos",regExes:{trimSpace:/^\s*|\s*$/g,removeSpace:/\s*/g,splitSpace:/\s+/,trimComma:/\s*,\s*/g},read:function(a){"string"==
3039 typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));a&&9==a.nodeType&&(a=a.documentElement);var b={features:[]};this.readNode(a,b);a=[];for(var c=0,d=b.features.length;c<d;c++){var e=b.features[c];this.internalProjection&&(this.externalProjection&&e.components[0])&&e.components[0].transform(this.externalProjection,this.internalProjection);e=new OpenLayers.Feature.Vector(e.components[0],e.attributes);a.push(e)}return a},readers:{sa:{SamplingPoint:function(a,b){if(!b.attributes){var c=
3040 {attributes:{}};b.features.push(c);b=c}b.attributes.id=this.getAttributeNS(a,this.namespaces.gml,"id");this.readChildNodes(a,b)},position:function(a,b){this.readChildNodes(a,b)}},gml:OpenLayers.Util.applyDefaults({FeatureCollection:function(a,b){this.readChildNodes(a,b)},featureMember:function(a,b){var c={attributes:{}};b.features.push(c);this.readChildNodes(a,c)},name:function(a,b){b.attributes.name=this.getChildValue(a)},pos:function(a,b){this.externalProjection||(this.externalProjection=new OpenLayers.Projection(a.getAttribute("srsName")));
3041 OpenLayers.Format.GML.v3.prototype.readers.gml.pos.apply(this,[a,b])}},OpenLayers.Format.GML.v3.prototype.readers.gml)},writers:{sos:{GetFeatureOfInterest:function(a){for(var b=this.createElementNSPlus("GetFeatureOfInterest",{attributes:{version:this.VERSION,service:"SOS","xsi:schemaLocation":this.schemaLocation}}),c=0,d=a.fois.length;c<d;c++)this.writeNode("FeatureOfInterestId",{foi:a.fois[c]},b);return b},FeatureOfInterestId:function(a){return this.createElementNSPlus("FeatureOfInterestId",{value:a.foi})}}},
3042 CLASS_NAME:"OpenLayers.Format.SOSGetFeatureOfInterest"});OpenLayers.Format.SOSGetObservation=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{ows:"http://www.opengis.net/ows",gml:"http://www.opengis.net/gml",sos:"http://www.opengis.net/sos/1.0",ogc:"http://www.opengis.net/ogc",om:"http://www.opengis.net/om/1.0",sa:"http://www.opengis.net/sampling/1.0",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance"},regExes:{trimSpace:/^\s*|\s*$/g,removeSpace:/\s*/g,splitSpace:/\s+/,trimComma:/\s*,\s*/g},VERSION:"1.0.0",schemaLocation:"http://www.opengis.net/sos/1.0 http://schemas.opengis.net/sos/1.0.0/sosGetObservation.xsd",
3043 defaultPrefix:"sos",read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));a&&9==a.nodeType&&(a=a.documentElement);var b={measurements:[],observations:[]};this.readNode(a,b);return b},write:function(a){a=this.writeNode("sos:GetObservation",a);a.setAttribute("xmlns:om",this.namespaces.om);a.setAttribute("xmlns:ogc",this.namespaces.ogc);this.setAttributeNS(a,this.namespaces.xsi,"xsi:schemaLocation",this.schemaLocation);return OpenLayers.Format.XML.prototype.write.apply(this,
3044 [a])},readers:{om:{ObservationCollection:function(a,b){b.id=this.getAttributeNS(a,this.namespaces.gml,"id");this.readChildNodes(a,b)},member:function(a,b){this.readChildNodes(a,b)},Measurement:function(a,b){var c={};b.measurements.push(c);this.readChildNodes(a,c)},Observation:function(a,b){var c={};b.observations.push(c);this.readChildNodes(a,c)},samplingTime:function(a,b){var c={};b.samplingTime=c;this.readChildNodes(a,c)},observedProperty:function(a,b){b.observedProperty=this.getAttributeNS(a,this.namespaces.xlink,
3045 "href");this.readChildNodes(a,b)},procedure:function(a,b){b.procedure=this.getAttributeNS(a,this.namespaces.xlink,"href");this.readChildNodes(a,b)},featureOfInterest:function(a,b){var c={features:[]};b.fois=[];b.fois.push(c);this.readChildNodes(a,c);for(var d=[],e=0,f=c.features.length;e<f;e++){var g=c.features[e];d.push(new OpenLayers.Feature.Vector(g.components[0],g.attributes))}c.features=d},result:function(a,b){var c={};b.result=c;""!==this.getChildValue(a)?(c.value=this.getChildValue(a),c.uom=
3046 a.getAttribute("uom")):this.readChildNodes(a,c)}},sa:OpenLayers.Format.SOSGetFeatureOfInterest.prototype.readers.sa,gml:OpenLayers.Util.applyDefaults({TimeInstant:function(a,b){var c={};b.timeInstant=c;this.readChildNodes(a,c)},timePosition:function(a,b){b.timePosition=this.getChildValue(a)}},OpenLayers.Format.SOSGetFeatureOfInterest.prototype.readers.gml)},writers:{sos:{GetObservation:function(a){var b=this.createElementNSPlus("GetObservation",{attributes:{version:this.VERSION,service:"SOS"}});this.writeNode("offering",
3047 a,b);a.eventTime&&this.writeNode("eventTime",a,b);for(var c in a.procedures)this.writeNode("procedure",a.procedures[c],b);for(var d in a.observedProperties)this.writeNode("observedProperty",a.observedProperties[d],b);a.foi&&this.writeNode("featureOfInterest",a.foi,b);this.writeNode("responseFormat",a,b);a.resultModel&&this.writeNode("resultModel",a,b);a.responseMode&&this.writeNode("responseMode",a,b);return b},featureOfInterest:function(a){var b=this.createElementNSPlus("featureOfInterest");this.writeNode("ObjectID",
3048 a.objectId,b);return b},ObjectID:function(a){return this.createElementNSPlus("ObjectID",{value:a})},responseFormat:function(a){return this.createElementNSPlus("responseFormat",{value:a.responseFormat})},procedure:function(a){return this.createElementNSPlus("procedure",{value:a})},offering:function(a){return this.createElementNSPlus("offering",{value:a.offering})},observedProperty:function(a){return this.createElementNSPlus("observedProperty",{value:a})},eventTime:function(a){var b=this.createElementNSPlus("eventTime");
3049 "latest"===a.eventTime&&this.writeNode("ogc:TM_Equals",a,b);return b},resultModel:function(a){return this.createElementNSPlus("resultModel",{value:a.resultModel})},responseMode:function(a){return this.createElementNSPlus("responseMode",{value:a.responseMode})}},ogc:{TM_Equals:function(a){var b=this.createElementNSPlus("ogc:TM_Equals");this.writeNode("ogc:PropertyName",{property:"urn:ogc:data:time:iso8601"},b);"latest"===a.eventTime&&this.writeNode("gml:TimeInstant",{value:"latest"},b);return b},PropertyName:function(a){return this.createElementNSPlus("ogc:PropertyName",
3050 {value:a.property})}},gml:{TimeInstant:function(a){var b=this.createElementNSPlus("gml:TimeInstant");this.writeNode("gml:timePosition",a,b);return b},timePosition:function(a){return this.createElementNSPlus("gml:timePosition",{value:a.value})}}},CLASS_NAME:"OpenLayers.Format.SOSGetObservation"});OpenLayers.Control.UTFGrid=OpenLayers.Class(OpenLayers.Control,{autoActivate:!0,layers:null,defaultHandlerOptions:{delay:300,pixelTolerance:4,stopMove:!1,single:!0,"double":!1,stopSingle:!1,stopDouble:!1},handlerMode:"click",setHandler:function(a){this.handlerMode=a;this.resetHandler()},resetHandler:function(){this.handler&&(this.handler.deactivate(),this.handler.destroy(),this.handler=null);"hover"==this.handlerMode?this.handler=new OpenLayers.Handler.Hover(this,{pause:this.handleEvent,move:this.reset},
3051 this.handlerOptions):"click"==this.handlerMode?this.handler=new OpenLayers.Handler.Click(this,{click:this.handleEvent},this.handlerOptions):"move"==this.handlerMode&&(this.handler=new OpenLayers.Handler.Hover(this,{pause:this.handleEvent,move:this.handleEvent},this.handlerOptions));return this.handler?!0:!1},initialize:function(a){a=a||{};a.handlerOptions=a.handlerOptions||this.defaultHandlerOptions;OpenLayers.Control.prototype.initialize.apply(this,[a]);this.resetHandler()},handleEvent:function(a){if(null==
3052 a)this.reset();else{var b=this.map.getLonLatFromPixel(a.xy);if(b){var c=this.findLayers();if(0<c.length){for(var d={},e,f,g=0,h=c.length;g<h;g++)e=c[g],f=OpenLayers.Util.indexOf(this.map.layers,e),d[f]=e.getFeatureInfo(b);this.callback(d,b,a.xy)}}}},callback:function(a){},reset:function(a){this.callback(null)},findLayers:function(){for(var a=this.layers||this.map.layers,b=[],c,d=a.length-1;0<=d;--d)c=a[d],c instanceof OpenLayers.Layer.UTFGrid&&b.push(c);return b},CLASS_NAME:"OpenLayers.Control.UTFGrid"});OpenLayers.Format.CQL=function(){function a(a){function b(){var a=e.pop();switch(a.type){case "LOGICAL":var c=b(),g=b();return new OpenLayers.Filter.Logical({filters:[g,c],type:f[a.text.toUpperCase()]});case "NOT":return a=b(),new OpenLayers.Filter.Logical({filters:[a],type:OpenLayers.Filter.Logical.NOT});case "BETWEEN":return e.pop(),g=b(),a=b(),c=b(),new OpenLayers.Filter.Comparison({property:c,lowerBoundary:a,upperBoundary:g,type:OpenLayers.Filter.Comparison.BETWEEN});case "COMPARISON":return g=
3053 b(),c=b(),new OpenLayers.Filter.Comparison({property:c,value:g,type:d[a.text.toUpperCase()]});case "IS_NULL":return c=b(),new OpenLayers.Filter.Comparison({property:c,type:d[a.text.toUpperCase()]});case "VALUE":return(c=a.text.match(/^'(.*)'$/))?c[1].replace(/''/g,"'"):Number(a.text);case "SPATIAL":switch(a.text.toUpperCase()){case "BBOX":var a=b(),c=b(),g=b(),h=b(),k=b();return new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.BBOX,property:k,value:OpenLayers.Bounds.fromArray([h,g,c,
3054 a])});case "INTERSECTS":return g=b(),c=b(),new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.INTERSECTS,property:c,value:g});case "WITHIN":return g=b(),c=b(),new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.WITHIN,property:c,value:g});case "CONTAINS":return g=b(),c=b(),new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.CONTAINS,property:c,value:g});case "DWITHIN":return a=b(),g=b(),c=b(),new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.DWITHIN,value:g,
3055 property:c,distance:Number(a)})}case "GEOMETRY":return OpenLayers.Geometry.fromWKT(a.text);default:return a.text}}for(var c=[],e=[];a.length;){var g=a.shift();switch(g.type){case "PROPERTY":case "GEOMETRY":case "VALUE":e.push(g);break;case "COMPARISON":case "BETWEEN":case "IS_NULL":case "LOGICAL":for(var k=h[g.type];0<c.length&&h[c[c.length-1].type]<=k;)e.push(c.pop());c.push(g);break;case "SPATIAL":case "NOT":case "LPAREN":c.push(g);break;case "RPAREN":for(;0<c.length&&"LPAREN"!=c[c.length-1].type;)e.push(c.pop());
3056 c.pop();0<c.length&&"SPATIAL"==c[c.length-1].type&&e.push(c.pop());case "COMMA":case "END":break;default:throw Error("Unknown token type "+g.type);}}for(;0<c.length;)e.push(c.pop());a=b();if(0<e.length){a="Remaining tokens after building AST: \n";for(c=e.length-1;0<=c;c--)a+=e[c].type+": "+e[c].text+"\n";throw Error(a);}return a}var b={PROPERTY:/^[_a-zA-Z]\w*/,COMPARISON:/^(=|<>|<=|<|>=|>|LIKE)/i,IS_NULL:/^IS NULL/i,COMMA:/^,/,LOGICAL:/^(AND|OR)/i,VALUE:/^('([^']|'')*'|\d+(\.\d*)?|\.\d+)/,LPAREN:/^\(/,
3057 RPAREN:/^\)/,SPATIAL:/^(BBOX|INTERSECTS|DWITHIN|WITHIN|CONTAINS)/i,NOT:/^NOT/i,BETWEEN:/^BETWEEN/i,GEOMETRY:function(a){var b=/^(POINT|LINESTRING|POLYGON|MULTIPOINT|MULTILINESTRING|MULTIPOLYGON|GEOMETRYCOLLECTION)/.exec(a);if(b){var c=a.length,b=a.indexOf("(",b[0].length);if(-1<b)for(var d=1;b<c&&0<d;)switch(b++,a.charAt(b)){case "(":d++;break;case ")":d--}return[a.substr(0,b+1)]}},END:/^$/},c={LPAREN:["GEOMETRY","SPATIAL","PROPERTY","VALUE","LPAREN"],RPAREN:["NOT","LOGICAL","END","RPAREN"],PROPERTY:["COMPARISON",
3058 "BETWEEN","COMMA","IS_NULL"],BETWEEN:["VALUE"],IS_NULL:["END"],COMPARISON:["VALUE"],COMMA:["GEOMETRY","VALUE","PROPERTY"],VALUE:["LOGICAL","COMMA","RPAREN","END"],SPATIAL:["LPAREN"],LOGICAL:["NOT","VALUE","SPATIAL","PROPERTY","LPAREN"],NOT:["PROPERTY","LPAREN"],GEOMETRY:["COMMA","RPAREN"]},d={"=":OpenLayers.Filter.Comparison.EQUAL_TO,"<>":OpenLayers.Filter.Comparison.NOT_EQUAL_TO,"<":OpenLayers.Filter.Comparison.LESS_THAN,"<=":OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO,">":OpenLayers.Filter.Comparison.GREATER_THAN,
3059 ">=":OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO,LIKE:OpenLayers.Filter.Comparison.LIKE,BETWEEN:OpenLayers.Filter.Comparison.BETWEEN,"IS NULL":OpenLayers.Filter.Comparison.IS_NULL},e={},f={AND:OpenLayers.Filter.Logical.AND,OR:OpenLayers.Filter.Logical.OR},g={},h={RPAREN:3,LOGICAL:2,COMPARISON:1},k;for(k in d)d.hasOwnProperty(k)&&(e[d[k]]=k);for(k in f)f.hasOwnProperty(k)&&(g[f[k]]=k);return OpenLayers.Class(OpenLayers.Format,{read:function(d){var e=d;d=[];var f,g=["NOT","GEOMETRY","SPATIAL",
3060 "PROPERTY","LPAREN"];do{a:{f=g;for(var h=void 0,g=void 0,k=f.length,h=0;h<k;h++){var g=f[h],s=b[g]instanceof RegExp?b[g].exec(e):(0,b[g])(e);if(s){f=s[0];e=e.substr(f.length).replace(/^\s*/,"");f={type:g,text:f,remainder:e};break a}}d="ERROR: In parsing: ["+e+"], expected one of: ";for(h=0;h<k;h++)g=f[h],d+="\n "+g+": "+b[g];throw Error(d);}e=f.remainder;g=c[f.type];if("END"!=f.type&&!g)throw Error("No follows list for "+f.type);d.push(f)}while("END"!=f.type);d=a(d);this.keepData&&(this.data=d);
3061 return d},write:function(a){if(a instanceof OpenLayers.Geometry)return a.toString();switch(a.CLASS_NAME){case "OpenLayers.Filter.Spatial":switch(a.type){case OpenLayers.Filter.Spatial.BBOX:return"BBOX("+a.property+","+a.value.toBBOX()+")";case OpenLayers.Filter.Spatial.DWITHIN:return"DWITHIN("+a.property+", "+this.write(a.value)+", "+a.distance+")";case OpenLayers.Filter.Spatial.WITHIN:return"WITHIN("+a.property+", "+this.write(a.value)+")";case OpenLayers.Filter.Spatial.INTERSECTS:return"INTERSECTS("+
3062 a.property+", "+this.write(a.value)+")";case OpenLayers.Filter.Spatial.CONTAINS:return"CONTAINS("+a.property+", "+this.write(a.value)+")";default:throw Error("Unknown spatial filter type: "+a.type);}case "OpenLayers.Filter.Logical":if(a.type==OpenLayers.Filter.Logical.NOT)return"NOT ("+this.write(a.filters[0])+")";for(var b="(",c=!0,d=0;d<a.filters.length;d++)c?c=!1:b+=") "+g[a.type]+" (",b+=this.write(a.filters[d]);return b+")";case "OpenLayers.Filter.Comparison":return a.type==OpenLayers.Filter.Comparison.BETWEEN?
3063 a.property+" BETWEEN "+this.write(a.lowerBoundary)+" AND "+this.write(a.upperBoundary):null!==a.value?a.property+" "+e[a.type]+" "+this.write(a.value):a.property+" "+e[a.type];case void 0:if("string"===typeof a)return"'"+a.replace(/'/g,"''")+"'";if("number"===typeof a)return String(a);default:throw Error("Can't encode: "+a.CLASS_NAME+" "+a);}},CLASS_NAME:"OpenLayers.Format.CQL"})}();OpenLayers.Control.Split=OpenLayers.Class(OpenLayers.Control,{layer:null,source:null,sourceOptions:null,tolerance:null,edge:!0,deferDelete:!1,mutual:!0,targetFilter:null,sourceFilter:null,handler:null,initialize:function(a){OpenLayers.Control.prototype.initialize.apply(this,[a]);this.options=a||{};this.options.source&&this.setSource(this.options.source)},setSource:function(a){this.active?(this.deactivate(),this.handler&&(this.handler.destroy(),delete this.handler),this.source=a,this.activate()):this.source=
3064 a},activate:function(){var a=OpenLayers.Control.prototype.activate.call(this);if(a)if(!this.source)this.handler||(this.handler=new OpenLayers.Handler.Path(this,{done:function(a){this.onSketchComplete({feature:new OpenLayers.Feature.Vector(a)})}},{layerOptions:this.sourceOptions})),this.handler.activate();else if(this.source.events)this.source.events.on({sketchcomplete:this.onSketchComplete,afterfeaturemodified:this.afterFeatureModified,scope:this});return a},deactivate:function(){var a=OpenLayers.Control.prototype.deactivate.call(this);
3065 a&&this.source&&this.source.events&&this.source.events.un({sketchcomplete:this.onSketchComplete,afterfeaturemodified:this.afterFeatureModified,scope:this});return a},onSketchComplete:function(a){this.feature=null;return!this.considerSplit(a.feature)},afterFeatureModified:function(a){a.modified&&"function"===typeof a.feature.geometry.split&&(this.feature=a.feature,this.considerSplit(a.feature))},removeByGeometry:function(a,b){for(var c=0,d=a.length;c<d;++c)if(a[c].geometry===b){a.splice(c,1);break}},
3066 isEligible:function(a){return a.geometry?a.state!==OpenLayers.State.DELETE&&"function"===typeof a.geometry.split&&this.feature!==a&&(!this.targetFilter||this.targetFilter.evaluate(a.attributes)):!1},considerSplit:function(a){var b=!1,c=!1;if(!this.sourceFilter||this.sourceFilter.evaluate(a.attributes)){for(var d=this.layer&&this.layer.features||[],e,f,g=[],h=[],k=this.layer===this.source&&this.mutual,l={edge:this.edge,tolerance:this.tolerance,mutual:k},m=[a.geometry],n,p,q,r=0,s=d.length;r<s;++r)if(n=
3067 d[r],this.isEligible(n)){p=[n.geometry];for(var t=0;t<m.length;++t){q=m[t];for(var u=0;u<p.length;++u)if(e=p[u],q.getBounds().intersectsBounds(e.getBounds())&&(e=q.split(e,l)))f=this.events.triggerEvent("beforesplit",{source:a,target:n}),!1!==f&&(k&&(f=e[0],1<f.length&&(f.unshift(t,1),Array.prototype.splice.apply(m,f),t+=f.length-3),e=e[1]),1<e.length&&(e.unshift(u,1),Array.prototype.splice.apply(p,e),u+=e.length-3))}p&&1<p.length&&(this.geomsToFeatures(n,p),this.events.triggerEvent("split",{original:n,
3068 features:p}),Array.prototype.push.apply(g,p),h.push(n),c=!0)}m&&1<m.length&&(this.geomsToFeatures(a,m),this.events.triggerEvent("split",{original:a,features:m}),Array.prototype.push.apply(g,m),h.push(a),b=!0);if(b||c){if(this.deferDelete){d=[];r=0;for(s=h.length;r<s;++r)c=h[r],c.state===OpenLayers.State.INSERT?d.push(c):(c.state=OpenLayers.State.DELETE,this.layer.drawFeature(c));this.layer.destroyFeatures(d,{silent:!0});r=0;for(s=g.length;r<s;++r)g[r].state=OpenLayers.State.INSERT}else this.layer.destroyFeatures(h,
3069 {silent:!0});this.layer.addFeatures(g,{silent:!0});this.events.triggerEvent("aftersplit",{source:a,features:g})}}return b},geomsToFeatures:function(a,b){var c=a.clone();delete c.geometry;for(var d,e=0,f=b.length;e<f;++e)d=c.clone(),d.geometry=b[e],d.state=OpenLayers.State.INSERT,b[e]=d},destroy:function(){this.active&&this.deactivate();OpenLayers.Control.prototype.destroy.call(this)},CLASS_NAME:"OpenLayers.Control.Split"});OpenLayers.Layer.WMTS=OpenLayers.Class(OpenLayers.Layer.Grid,{isBaseLayer:!0,version:"1.0.0",requestEncoding:"KVP",url:null,layer:null,matrixSet:null,style:null,format:"image/jpeg",tileOrigin:null,tileFullExtent:null,formatSuffix:null,matrixIds:null,dimensions:null,params:null,zoomOffset:0,serverResolutions:null,formatSuffixMap:{"image/png":"png","image/png8":"png","image/png24":"png","image/png32":"png",png:"png","image/jpeg":"jpg","image/jpg":"jpg",jpeg:"jpg",jpg:"jpg"},matrix:null,initialize:function(a){var b=
3070 {url:!0,layer:!0,style:!0,matrixSet:!0},c;for(c in b)if(!(c in a))throw Error("Missing property '"+c+"' in layer configuration.");a.params=OpenLayers.Util.upperCaseObject(a.params);OpenLayers.Layer.Grid.prototype.initialize.apply(this,[a.name,a.url,a.params,a]);this.formatSuffix||(this.formatSuffix=this.formatSuffixMap[this.format]||this.format.split("/").pop());if(this.matrixIds&&(a=this.matrixIds.length)&&"string"===typeof this.matrixIds[0])for(b=this.matrixIds,this.matrixIds=Array(a),c=0;c<a;++c)this.matrixIds[c]=
3071 {identifier:b[c]}},setMap:function(){OpenLayers.Layer.Grid.prototype.setMap.apply(this,arguments)},updateMatrixProperties:function(){if(this.matrix=this.getMatrix())this.matrix.topLeftCorner&&(this.tileOrigin=this.matrix.topLeftCorner),this.matrix.tileWidth&&this.matrix.tileHeight&&(this.tileSize=new OpenLayers.Size(this.matrix.tileWidth,this.matrix.tileHeight)),this.tileOrigin||(this.tileOrigin=new OpenLayers.LonLat(this.maxExtent.left,this.maxExtent.top)),this.tileFullExtent||(this.tileFullExtent=
3072 this.maxExtent)},moveTo:function(a,b,c){!b&&this.matrix||this.updateMatrixProperties();return OpenLayers.Layer.Grid.prototype.moveTo.apply(this,arguments)},clone:function(a){null==a&&(a=new OpenLayers.Layer.WMTS(this.options));return a=OpenLayers.Layer.Grid.prototype.clone.apply(this,[a])},getIdentifier:function(){return this.getServerZoom()},getMatrix:function(){var a;if(this.matrixIds&&0!==this.matrixIds.length)if("scaleDenominator"in this.matrixIds[0])for(var b=OpenLayers.METERS_PER_INCH*OpenLayers.INCHES_PER_UNIT[this.units]*
3073 this.getServerResolution()/2.8E-4,c=Number.POSITIVE_INFINITY,d,e=0,f=this.matrixIds.length;e<f;++e)d=Math.abs(1-this.matrixIds[e].scaleDenominator/b),d<c&&(c=d,a=this.matrixIds[e]);else a=this.matrixIds[this.getIdentifier()];else a={identifier:this.getIdentifier()};return a},getTileInfo:function(a){var b=this.getServerResolution(),c=(a.lon-this.tileOrigin.lon)/(b*this.tileSize.w);a=(this.tileOrigin.lat-a.lat)/(b*this.tileSize.h);var b=Math.floor(c),d=Math.floor(a);return{col:b,row:d,i:Math.floor((c-
3074 b)*this.tileSize.w),j:Math.floor((a-d)*this.tileSize.h)}},getURL:function(a){a=this.adjustBounds(a);var b="";if(!this.tileFullExtent||this.tileFullExtent.intersectsBounds(a)){a=a.getCenterLonLat();var c=this.getTileInfo(a);a=this.dimensions;var d,b=OpenLayers.Util.isArray(this.url)?this.selectUrl([this.version,this.style,this.matrixSet,this.matrix.identifier,c.row,c.col].join(),this.url):this.url;if("REST"===this.requestEncoding.toUpperCase())if(d=this.params,-1!==b.indexOf("{")){b=b.replace(/\{/g,
3075 "${");c={style:this.style,Style:this.style,TileMatrixSet:this.matrixSet,TileMatrix:this.matrix.identifier,TileRow:c.row,TileCol:c.col};if(a){var e,f;for(f=a.length-1;0<=f;--f)e=a[f],c[e]=d[e.toUpperCase()]}b=OpenLayers.String.format(b,c)}else{e=this.version+"/"+this.layer+"/"+this.style+"/";if(a)for(f=0;f<a.length;f++)d[a[f]]&&(e=e+d[a[f]]+"/");e=e+this.matrixSet+"/"+this.matrix.identifier+"/"+c.row+"/"+c.col+"."+this.formatSuffix;b.match(/\/$/)||(b+="/");b+=e}else"KVP"===this.requestEncoding.toUpperCase()&&
3076 (d={SERVICE:"WMTS",REQUEST:"GetTile",VERSION:this.version,LAYER:this.layer,STYLE:this.style,TILEMATRIXSET:this.matrixSet,TILEMATRIX:this.matrix.identifier,TILEROW:c.row,TILECOL:c.col,FORMAT:this.format},b=OpenLayers.Layer.Grid.prototype.getFullRequestString.apply(this,[d]))}return b},mergeNewParams:function(a){if("KVP"===this.requestEncoding.toUpperCase())return OpenLayers.Layer.Grid.prototype.mergeNewParams.apply(this,[OpenLayers.Util.upperCaseObject(a)])},CLASS_NAME:"OpenLayers.Layer.WMTS"});OpenLayers.Protocol.SOS.v1_0_0=OpenLayers.Class(OpenLayers.Protocol,{fois:null,formatOptions:null,initialize:function(a){OpenLayers.Protocol.prototype.initialize.apply(this,[a]);a.format||(this.format=new OpenLayers.Format.SOSGetFeatureOfInterest(this.formatOptions))},destroy:function(){this.options&&!this.options.format&&this.format.destroy();this.format=null;OpenLayers.Protocol.prototype.destroy.apply(this)},read:function(a){a=OpenLayers.Util.extend({},a);OpenLayers.Util.applyDefaults(a,this.options||
3077 {});var b=new OpenLayers.Protocol.Response({requestType:"read"}),c=this.format,c=OpenLayers.Format.XML.prototype.write.apply(c,[c.writeNode("sos:GetFeatureOfInterest",{fois:this.fois})]);b.priv=OpenLayers.Request.POST({url:a.url,callback:this.createCallback(this.handleRead,b,a),data:c});return b},handleRead:function(a,b){if(b.callback){var c=a.priv;200<=c.status&&300>c.status?(a.features=this.parseFeatures(c),a.code=OpenLayers.Protocol.Response.SUCCESS):a.code=OpenLayers.Protocol.Response.FAILURE;
3078 b.callback.call(b.scope,a)}},parseFeatures:function(a){var b=a.responseXML;b&&b.documentElement||(b=a.responseText);return!b||0>=b.length?null:this.format.read(b)},CLASS_NAME:"OpenLayers.Protocol.SOS.v1_0_0"});OpenLayers.Layer.KaMapCache=OpenLayers.Class(OpenLayers.Layer.KaMap,{IMAGE_EXTENSIONS:{jpeg:"jpg",gif:"gif",png:"png",png8:"png",png24:"png",dithered:"png"},DEFAULT_FORMAT:"jpeg",initialize:function(a,b,c,d){OpenLayers.Layer.KaMap.prototype.initialize.apply(this,arguments);this.extension=this.IMAGE_EXTENSIONS[this.params.i.toLowerCase()||this.DEFAULT_FORMAT]},getURL:function(a){a=this.adjustBounds(a);var b=this.map.getResolution(),c=Math.round(1E4*this.map.getScale())/1E4,d=Math.round(a.left/b);a=
3079 -Math.round(a.top/b);var b=Math.floor(d/this.tileSize.w/this.params.metaTileSize.w)*this.tileSize.w*this.params.metaTileSize.w,e=Math.floor(a/this.tileSize.h/this.params.metaTileSize.h)*this.tileSize.h*this.params.metaTileSize.h,c=["/",this.params.map,"/",c,"/",this.params.g.replace(/\s/g,"_"),"/def/t",e,"/l",b,"/t",a,"l",d,".",this.extension],d=this.url;OpenLayers.Util.isArray(d)&&(d=this.selectUrl(c.join(""),d));return d+c.join("")},CLASS_NAME:"OpenLayers.Layer.KaMapCache"});OpenLayers.Protocol.WFS.v1_1_0=OpenLayers.Class(OpenLayers.Protocol.WFS.v1,{version:"1.1.0",initialize:function(a){OpenLayers.Protocol.WFS.v1.prototype.initialize.apply(this,arguments);this.outputFormat&&!this.readFormat&&("gml2"==this.outputFormat.toLowerCase()?this.readFormat=new OpenLayers.Format.GML.v2({featureType:this.featureType,featureNS:this.featureNS,geometryName:this.geometryName}):"json"==this.outputFormat.toLowerCase()&&(this.readFormat=new OpenLayers.Format.GeoJSON))},CLASS_NAME:"OpenLayers.Protocol.WFS.v1_1_0"});OpenLayers.Format.WMSCapabilities.v1_1_1=OpenLayers.Class(OpenLayers.Format.WMSCapabilities.v1_1,{version:"1.1.1",readers:{wms:OpenLayers.Util.applyDefaults({SRS:function(a,b){b.srs[this.getChildValue(a)]=!0}},OpenLayers.Format.WMSCapabilities.v1_1.prototype.readers.wms)},CLASS_NAME:"OpenLayers.Format.WMSCapabilities.v1_1_1"});OpenLayers.Format.WMSCapabilities.v1_1_1_WMSC=OpenLayers.Class(OpenLayers.Format.WMSCapabilities.v1_1_1,{version:"1.1.1",profile:"WMSC",readers:{wms:OpenLayers.Util.applyDefaults({VendorSpecificCapabilities:function(a,b){b.vendorSpecific={tileSets:[]};this.readChildNodes(a,b.vendorSpecific)},TileSet:function(a,b){var c={srs:{},bbox:{},resolutions:[]};this.readChildNodes(a,c);b.tileSets.push(c)},Resolutions:function(a,b){for(var c=this.getChildValue(a).split(" "),d=0,e=c.length;d<e;d++)""!=c[d]&&b.resolutions.push(parseFloat(c[d]))},
3080 Width:function(a,b){b.width=parseInt(this.getChildValue(a))},Height:function(a,b){b.height=parseInt(this.getChildValue(a))},Layers:function(a,b){b.layers=this.getChildValue(a)},Styles:function(a,b){b.styles=this.getChildValue(a)}},OpenLayers.Format.WMSCapabilities.v1_1_1.prototype.readers.wms)},CLASS_NAME:"OpenLayers.Format.WMSCapabilities.v1_1_1_WMSC"});OpenLayers.Control.LayerSwitcher=OpenLayers.Class(OpenLayers.Control,{layerStates:null,layersDiv:null,baseLayersDiv:null,baseLayers:null,dataLbl:null,dataLayersDiv:null,dataLayers:null,minimizeDiv:null,maximizeDiv:null,ascending:!0,initialize:function(a){OpenLayers.Control.prototype.initialize.apply(this,arguments);this.layerStates=[]},destroy:function(){this.clearLayersArray("base");this.clearLayersArray("data");this.map.events.un({buttonclick:this.onButtonClick,addlayer:this.redraw,changelayer:this.redraw,
3081 removelayer:this.redraw,changebaselayer:this.redraw,scope:this});this.events.unregister("buttonclick",this,this.onButtonClick);OpenLayers.Control.prototype.destroy.apply(this,arguments)},setMap:function(a){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.map.events.on({addlayer:this.redraw,changelayer:this.redraw,removelayer:this.redraw,changebaselayer:this.redraw,scope:this});this.outsideViewport?(this.events.attachToElement(this.div),this.events.register("buttonclick",this,this.onButtonClick)):
3082 this.map.events.register("buttonclick",this,this.onButtonClick)},draw:function(){OpenLayers.Control.prototype.draw.apply(this);this.loadContents();this.outsideViewport||this.minimizeControl();this.redraw();return this.div},onButtonClick:function(a){a=a.buttonElement;a===this.minimizeDiv?this.minimizeControl():a===this.maximizeDiv?this.maximizeControl():a._layerSwitcher===this.id&&(a["for"]&&(a=document.getElementById(a["for"])),a.disabled||("radio"==a.type?(a.checked=!0,this.map.setBaseLayer(this.map.getLayer(a._layer))):
3083 (a.checked=!a.checked,this.updateMap())))},clearLayersArray:function(a){this[a+"LayersDiv"].innerHTML="";this[a+"Layers"]=[]},checkRedraw:function(){if(!this.layerStates.length||this.map.layers.length!=this.layerStates.length)return!0;for(var a=0,b=this.layerStates.length;a<b;a++){var c=this.layerStates[a],d=this.map.layers[a];if(c.name!=d.name||c.inRange!=d.inRange||c.id!=d.id||c.visibility!=d.visibility)return!0}return!1},redraw:function(){if(!this.checkRedraw())return this.div;this.clearLayersArray("base");
3084 this.clearLayersArray("data");var a=!1,b=!1,c=this.map.layers.length;this.layerStates=Array(c);for(var d=0;d<c;d++){var e=this.map.layers[d];this.layerStates[d]={name:e.name,visibility:e.visibility,inRange:e.inRange,id:e.id}}var f=this.map.layers.slice();this.ascending||f.reverse();d=0;for(c=f.length;d<c;d++){var e=f[d],g=e.isBaseLayer;if(e.displayInLayerSwitcher){g?b=!0:a=!0;var h=g?e==this.map.baseLayer:e.getVisibility(),k=document.createElement("input"),l=OpenLayers.Util.createUniqueID(this.id+
3085 "_input_");k.id=l;k.name=g?this.id+"_baseLayers":e.name;k.type=g?"radio":"checkbox";k.value=e.name;k.checked=h;k.defaultChecked=h;k.className="olButton";k._layer=e.id;k._layerSwitcher=this.id;g||e.inRange||(k.disabled=!0);h=document.createElement("label");h["for"]=k.id;OpenLayers.Element.addClass(h,"labelSpan olButton");h._layer=e.id;h._layerSwitcher=this.id;g||e.inRange||(h.style.color="gray");h.innerHTML=e.name;h.style.verticalAlign=g?"bottom":"baseline";l=document.createElement("br");(g?this.baseLayers:
3086 this.dataLayers).push({layer:e,inputElem:k,labelSpan:h});e=g?this.baseLayersDiv:this.dataLayersDiv;e.appendChild(k);e.appendChild(h);e.appendChild(l)}}this.dataLbl.style.display=a?"":"none";this.baseLbl.style.display=b?"":"none";return this.div},updateMap:function(){for(var a=0,b=this.baseLayers.length;a<b;a++){var c=this.baseLayers[a];c.inputElem.checked&&this.map.setBaseLayer(c.layer,!1)}a=0;for(b=this.dataLayers.length;a<b;a++)c=this.dataLayers[a],c.layer.setVisibility(c.inputElem.checked)},maximizeControl:function(a){this.div.style.width=
3087 "";this.div.style.height="";this.showControls(!1);null!=a&&OpenLayers.Event.stop(a)},minimizeControl:function(a){this.div.style.width="0px";this.div.style.height="0px";this.showControls(!0);null!=a&&OpenLayers.Event.stop(a)},showControls:function(a){this.maximizeDiv.style.display=a?"":"none";this.minimizeDiv.style.display=a?"none":"";this.layersDiv.style.display=a?"none":""},loadContents:function(){this.layersDiv=document.createElement("div");this.layersDiv.id=this.id+"_layersDiv";OpenLayers.Element.addClass(this.layersDiv,
3088 "layersDiv");this.baseLbl=document.createElement("div");this.baseLbl.innerHTML=OpenLayers.i18n("Base Layer");OpenLayers.Element.addClass(this.baseLbl,"baseLbl");this.baseLayersDiv=document.createElement("div");OpenLayers.Element.addClass(this.baseLayersDiv,"baseLayersDiv");this.dataLbl=document.createElement("div");this.dataLbl.innerHTML=OpenLayers.i18n("Overlays");OpenLayers.Element.addClass(this.dataLbl,"dataLbl");this.dataLayersDiv=document.createElement("div");OpenLayers.Element.addClass(this.dataLayersDiv,
3089 "dataLayersDiv");this.ascending?(this.layersDiv.appendChild(this.baseLbl),this.layersDiv.appendChild(this.baseLayersDiv),this.layersDiv.appendChild(this.dataLbl),this.layersDiv.appendChild(this.dataLayersDiv)):(this.layersDiv.appendChild(this.dataLbl),this.layersDiv.appendChild(this.dataLayersDiv),this.layersDiv.appendChild(this.baseLbl),this.layersDiv.appendChild(this.baseLayersDiv));this.div.appendChild(this.layersDiv);var a=OpenLayers.Util.getImageLocation("layer-switcher-maximize.png");this.maximizeDiv=
3090 OpenLayers.Util.createAlphaImageDiv("OpenLayers_Control_MaximizeDiv",null,null,a,"absolute");OpenLayers.Element.addClass(this.maximizeDiv,"maximizeDiv olButton");this.maximizeDiv.style.display="none";this.div.appendChild(this.maximizeDiv);a=OpenLayers.Util.getImageLocation("layer-switcher-minimize.png");this.minimizeDiv=OpenLayers.Util.createAlphaImageDiv("OpenLayers_Control_MinimizeDiv",null,null,a,"absolute");OpenLayers.Element.addClass(this.minimizeDiv,"minimizeDiv olButton");this.minimizeDiv.style.display=
3091 "none";this.div.appendChild(this.minimizeDiv)},CLASS_NAME:"OpenLayers.Control.LayerSwitcher"});OpenLayers.Format.Atom=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{atom:"http://www.w3.org/2005/Atom",georss:"http://www.georss.org/georss"},feedTitle:"untitled",defaultEntryTitle:"untitled",gmlParser:null,xy:!1,read:function(a){"string"==typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));return this.parseFeatures(a)},write:function(a){var b;if(OpenLayers.Util.isArray(a)){b=this.createElementNSPlus("atom:feed");b.appendChild(this.createElementNSPlus("atom:title",{value:this.feedTitle}));
3092 for(var c=0,d=a.length;c<d;c++)b.appendChild(this.buildEntryNode(a[c]))}else b=this.buildEntryNode(a);return OpenLayers.Format.XML.prototype.write.apply(this,[b])},buildContentNode:function(a){var b=this.createElementNSPlus("atom:content",{attributes:{type:a.type||null}});if(a.src)b.setAttribute("src",a.src);else if("text"==a.type||null==a.type)b.appendChild(this.createTextNode(a.value));else if("html"==a.type){if("string"!=typeof a.value)throw"HTML content must be in form of an escaped string";b.appendChild(this.createTextNode(a.value))}else"xhtml"==
3093 a.type?b.appendChild(a.value):"xhtml"==a.type||a.type.match(/(\+|\/)xml$/)?b.appendChild(a.value):b.appendChild(this.createTextNode(a.value));return b},buildEntryNode:function(a){var b=a.attributes,c=b.atom||{},d=this.createElementNSPlus("atom:entry");if(c.authors)for(var e=OpenLayers.Util.isArray(c.authors)?c.authors:[c.authors],f=0,g=e.length;f<g;f++)d.appendChild(this.buildPersonConstructNode("author",e[f]));if(c.categories)for(var e=OpenLayers.Util.isArray(c.categories)?c.categories:[c.categories],
3094 h,f=0,g=e.length;f<g;f++)h=e[f],d.appendChild(this.createElementNSPlus("atom:category",{attributes:{term:h.term,scheme:h.scheme||null,label:h.label||null}}));c.content&&d.appendChild(this.buildContentNode(c.content));if(c.contributors)for(e=OpenLayers.Util.isArray(c.contributors)?c.contributors:[c.contributors],f=0,g=e.length;f<g;f++)d.appendChild(this.buildPersonConstructNode("contributor",e[f]));a.fid&&d.appendChild(this.createElementNSPlus("atom:id",{value:a.fid}));if(c.links)for(e=OpenLayers.Util.isArray(c.links)?
3095 c.links:[c.links],f=0,g=e.length;f<g;f++)h=e[f],d.appendChild(this.createElementNSPlus("atom:link",{attributes:{href:h.href,rel:h.rel||null,type:h.type||null,hreflang:h.hreflang||null,title:h.title||null,length:h.length||null}}));c.published&&d.appendChild(this.createElementNSPlus("atom:published",{value:c.published}));c.rights&&d.appendChild(this.createElementNSPlus("atom:rights",{value:c.rights}));(c.summary||b.description)&&d.appendChild(this.createElementNSPlus("atom:summary",{value:c.summary||
3096 b.description}));d.appendChild(this.createElementNSPlus("atom:title",{value:c.title||b.title||this.defaultEntryTitle}));c.updated&&d.appendChild(this.createElementNSPlus("atom:updated",{value:c.updated}));a.geometry&&(b=this.createElementNSPlus("georss:where"),b.appendChild(this.buildGeometryNode(a.geometry)),d.appendChild(b));return d},initGmlParser:function(){this.gmlParser=new OpenLayers.Format.GML.v3({xy:this.xy,featureNS:"http://example.com#feature",internalProjection:this.internalProjection,
3097 externalProjection:this.externalProjection})},buildGeometryNode:function(a){this.gmlParser||this.initGmlParser();return this.gmlParser.writeNode("feature:_geometry",a).firstChild},buildPersonConstructNode:function(a,b){var c=["uri","email"],d=this.createElementNSPlus("atom:"+a);d.appendChild(this.createElementNSPlus("atom:name",{value:b.name}));for(var e=0,f=c.length;e<f;e++)b[c[e]]&&d.appendChild(this.createElementNSPlus("atom:"+c[e],{value:b[c[e]]}));return d},getFirstChildValue:function(a,b,c,
3098 d){return(a=this.getElementsByTagNameNS(a,b,c))&&0<a.length?this.getChildValue(a[0],d):d},parseFeature:function(a){var b={},c=null,d=null,e=null,f=this.namespaces.atom;this.parsePersonConstructs(a,"author",b);d=this.getElementsByTagNameNS(a,f,"category");0<d.length&&(b.categories=[]);for(var g=0,h=d.length;g<h;g++){c={};c.term=d[g].getAttribute("term");if(e=d[g].getAttribute("scheme"))c.scheme=e;if(e=d[g].getAttribute("label"))c.label=e;b.categories.push(c)}d=this.getElementsByTagNameNS(a,f,"content");
3099 if(0<d.length){c={};if(e=d[0].getAttribute("type"))c.type=e;(e=d[0].getAttribute("src"))?c.src=e:("text"==c.type||"html"==c.type||null==c.type?c.value=this.getFirstChildValue(a,f,"content",null):"xhtml"==c.type||c.type.match(/(\+|\/)xml$/)?c.value=this.getChildEl(d[0]):c.value=this.getFirstChildValue(a,f,"content",null),b.content=c)}this.parsePersonConstructs(a,"contributor",b);b.id=this.getFirstChildValue(a,f,"id",null);d=this.getElementsByTagNameNS(a,f,"link");0<d.length&&(b.links=Array(d.length));
3100 for(var k=["rel","type","hreflang","title","length"],g=0,h=d.length;g<h;g++){c={};c.href=d[g].getAttribute("href");for(var l=0,m=k.length;l<m;l++)(e=d[g].getAttribute(k[l]))&&(c[k[l]]=e);b.links[g]=c}if(c=this.getFirstChildValue(a,f,"published",null))b.published=c;if(c=this.getFirstChildValue(a,f,"rights",null))b.rights=c;if(c=this.getFirstChildValue(a,f,"summary",null))b.summary=c;b.title=this.getFirstChildValue(a,f,"title",null);b.updated=this.getFirstChildValue(a,f,"updated",null);c={title:b.title,
3101 description:b.summary,atom:b};a=this.parseLocations(a)[0];a=new OpenLayers.Feature.Vector(a,c);a.fid=b.id;return a},parseFeatures:function(a){var b=[],c=this.getElementsByTagNameNS(a,this.namespaces.atom,"entry");0==c.length&&(c=[a]);a=0;for(var d=c.length;a<d;a++)b.push(this.parseFeature(c[a]));return b},parseLocations:function(a){var b=this.namespaces.georss,c={components:[]},d=this.getElementsByTagNameNS(a,b,"where");if(d&&0<d.length){this.gmlParser||this.initGmlParser();for(var e=0,f=d.length;e<
3102 f;e++)this.gmlParser.readChildNodes(d[e],c)}c=c.components;if((d=this.getElementsByTagNameNS(a,b,"point"))&&0<d.length)for(e=0,f=d.length;e<f;e++){var g=OpenLayers.String.trim(d[e].firstChild.nodeValue).split(/\s+/);2!=g.length&&(g=OpenLayers.String.trim(d[e].firstChild.nodeValue).split(/\s*,\s*/));c.push(new OpenLayers.Geometry.Point(g[1],g[0]))}var h=this.getElementsByTagNameNS(a,b,"line");if(h&&0<h.length)for(var k,e=0,f=h.length;e<f;e++){d=OpenLayers.String.trim(h[e].firstChild.nodeValue).split(/\s+/);
3103 k=[];for(var l=0,m=d.length;l<m;l+=2)g=new OpenLayers.Geometry.Point(d[l+1],d[l]),k.push(g);c.push(new OpenLayers.Geometry.LineString(k))}if((a=this.getElementsByTagNameNS(a,b,"polygon"))&&0<a.length)for(e=0,f=a.length;e<f;e++){d=OpenLayers.String.trim(a[e].firstChild.nodeValue).split(/\s+/);k=[];l=0;for(m=d.length;l<m;l+=2)g=new OpenLayers.Geometry.Point(d[l+1],d[l]),k.push(g);c.push(new OpenLayers.Geometry.Polygon([new OpenLayers.Geometry.LinearRing(k)]))}if(this.internalProjection&&this.externalProjection)for(e=
3104 0,f=c.length;e<f;e++)c[e]&&c[e].transform(this.externalProjection,this.internalProjection);return c},parsePersonConstructs:function(a,b,c){var d=[],e=this.namespaces.atom;a=this.getElementsByTagNameNS(a,e,b);for(var f=["uri","email"],g=0,h=a.length;g<h;g++){var k={};k.name=this.getFirstChildValue(a[g],e,"name",null);for(var l=0,m=f.length;l<m;l++){var n=this.getFirstChildValue(a[g],e,f[l],null);n&&(k[f[l]]=n)}d.push(k)}0<d.length&&(c[b+"s"]=d)},CLASS_NAME:"OpenLayers.Format.Atom"});OpenLayers.Control.KeyboardDefaults=OpenLayers.Class(OpenLayers.Control,{autoActivate:!0,slideFactor:75,observeElement:null,draw:function(){this.handler=new OpenLayers.Handler.Keyboard(this,{keydown:this.defaultKeyPress},{observeElement:this.observeElement||document})},defaultKeyPress:function(a){var b,c=!0;b=OpenLayers.Event.element(a);if(!b||"INPUT"!=b.tagName&&"TEXTAREA"!=b.tagName&&"SELECT"!=b.tagName){switch(a.keyCode){case OpenLayers.Event.KEY_LEFT:this.map.pan(-this.slideFactor,0);break;case OpenLayers.Event.KEY_RIGHT:this.map.pan(this.slideFactor,
3105 0);break;case OpenLayers.Event.KEY_UP:this.map.pan(0,-this.slideFactor);break;case OpenLayers.Event.KEY_DOWN:this.map.pan(0,this.slideFactor);break;case 33:b=this.map.getSize();this.map.pan(0,-0.75*b.h);break;case 34:b=this.map.getSize();this.map.pan(0,0.75*b.h);break;case 35:b=this.map.getSize();this.map.pan(0.75*b.w,0);break;case 36:b=this.map.getSize();this.map.pan(-0.75*b.w,0);break;case 43:case 61:case 187:case 107:this.map.zoomIn();break;case 45:case 109:case 189:case 95:this.map.zoomOut();
3106 break;default:c=!1}c&&OpenLayers.Event.stop(a)}},CLASS_NAME:"OpenLayers.Control.KeyboardDefaults"});OpenLayers.Format.WMTSCapabilities.v1_0_0=OpenLayers.Class(OpenLayers.Format.OWSCommon.v1_1_0,{version:"1.0.0",namespaces:{ows:"http://www.opengis.net/ows/1.1",wmts:"http://www.opengis.net/wmts/1.0",xlink:"http://www.w3.org/1999/xlink"},yx:null,defaultPrefix:"wmts",initialize:function(a){OpenLayers.Format.XML.prototype.initialize.apply(this,[a]);this.options=a;a=OpenLayers.Util.extend({},OpenLayers.Format.WMTSCapabilities.prototype.yx);this.yx=OpenLayers.Util.extend(a,this.yx)},read:function(a){"string"==
3107 typeof a&&(a=OpenLayers.Format.XML.prototype.read.apply(this,[a]));a&&9==a.nodeType&&(a=a.documentElement);var b={};this.readNode(a,b);b.version=this.version;return b},readers:{wmts:{Capabilities:function(a,b){this.readChildNodes(a,b)},Contents:function(a,b){b.contents={};b.contents.layers=[];b.contents.tileMatrixSets={};this.readChildNodes(a,b.contents)},Layer:function(a,b){var c={styles:[],formats:[],dimensions:[],tileMatrixSetLinks:[],layers:[]};this.readChildNodes(a,c);b.layers.push(c)},Style:function(a,
3108 b){var c={};c.isDefault="true"===a.getAttribute("isDefault");this.readChildNodes(a,c);b.styles.push(c)},Format:function(a,b){b.formats.push(this.getChildValue(a))},TileMatrixSetLink:function(a,b){var c={};this.readChildNodes(a,c);b.tileMatrixSetLinks.push(c)},TileMatrixSet:function(a,b){if(b.layers){var c={matrixIds:[]};this.readChildNodes(a,c);b.tileMatrixSets[c.identifier]=c}else b.tileMatrixSet=this.getChildValue(a)},TileMatrix:function(a,b){var c={supportedCRS:b.supportedCRS};this.readChildNodes(a,
3109 c);b.matrixIds.push(c)},ScaleDenominator:function(a,b){b.scaleDenominator=parseFloat(this.getChildValue(a))},TopLeftCorner:function(a,b){var c=this.getChildValue(a).split(" "),d;b.supportedCRS&&(d=b.supportedCRS.replace(/urn:ogc:def:crs:(\w+):.+:(\w+)$/,"urn:ogc:def:crs:$1::$2"),d=!!this.yx[d]);b.topLeftCorner=d?new OpenLayers.LonLat(c[1],c[0]):new OpenLayers.LonLat(c[0],c[1])},TileWidth:function(a,b){b.tileWidth=parseInt(this.getChildValue(a))},TileHeight:function(a,b){b.tileHeight=parseInt(this.getChildValue(a))},
3110 MatrixWidth:function(a,b){b.matrixWidth=parseInt(this.getChildValue(a))},MatrixHeight:function(a,b){b.matrixHeight=parseInt(this.getChildValue(a))},ResourceURL:function(a,b){b.resourceUrl=b.resourceUrl||{};var c=a.getAttribute("resourceType");b.resourceUrls||(b.resourceUrls=[]);c=b.resourceUrl[c]={format:a.getAttribute("format"),template:a.getAttribute("template"),resourceType:c};b.resourceUrls.push(c)},WSDL:function(a,b){b.wsdl={};b.wsdl.href=a.getAttribute("xlink:href")},ServiceMetadataURL:function(a,
3111 b){b.serviceMetadataUrl={};b.serviceMetadataUrl.href=a.getAttribute("xlink:href")},LegendURL:function(a,b){b.legend={};b.legend.href=a.getAttribute("xlink:href");b.legend.format=a.getAttribute("format")},Dimension:function(a,b){var c={values:[]};this.readChildNodes(a,c);b.dimensions.push(c)},Default:function(a,b){b["default"]=this.getChildValue(a)},Value:function(a,b){b.values.push(this.getChildValue(a))}},ows:OpenLayers.Format.OWSCommon.v1_1_0.prototype.readers.ows},CLASS_NAME:"OpenLayers.Format.WMTSCapabilities.v1_0_0"});
3112 (function(h){h.deparam=function(i,j){var d={},k={"true":!0,"false":!1,"null":null};h.each(i.replace(/\+/g," ").split("&"),function(i,l){var m;var a=l.split("="),c=decodeURIComponent(a[0]),g=d,f=0,b=c.split("]["),e=b.length-1;/\[/.test(b[0])&&/\]$/.test(b[e])?(b[e]=b[e].replace(/\]$/,""),b=b.shift().split("[").concat(b),e=b.length-1):e=0;if(2===a.length)if(a=decodeURIComponent(a[1]),j&&(a=a&&!isNaN(a)?+a:"undefined"===a?void 0:void 0!==k[a]?k[a]:a),e)for(;f<=e;f++)c=""===b[f]?g.length:b[f],m=g[c]=
3113 f<e?g[c]||(b[f+1]&&isNaN(b[f+1])?{}:[]):a,g=m;else h.isArray(d[c])?d[c].push(a):d[c]=void 0!==d[c]?[d[c],a]:a;else c&&(d[c]=j?void 0:"")});return d}})(jQuery);
3114 /*!
3115 *
3116 * jQuery Remember Plugin
3117 * Version 0.1.1
3118 *
3119 * Copyright Nick Dreckshage, licensed GPL & MIT
3120 * https://github.com/ndreckshage/jquery-remember
3121 *
3122 * A fork of jQuery Cookie Plugin
3123 * https://github.com/carhartl/jquery-cookie
3124 * Copyright Klaus Hartl
3125 * Released under the MIT licensed
3126 *
3127 */
3128
3129 (function($){
3130
3131 // recommend changing to return function(options) { if using require.js...
3132 $.remember = function(options){
3133 var settings,
3134 remember,
3135 controller;
3136
3137 settings = $.extend({
3138 name: null, // name/key of the cookie/localstorage item
3139 value: undefined, // value pair of cookie/localstorage
3140 getSet: false, // if true, will get if available, set if not. default is to just get OR set
3141 remove: false, // if true, will remove based on name/key
3142 use: 'default', // whether to use localstorage or cookies. default localstorage with cookie fallback.
3143 expires: null, // forces cookie (invalid localstorage attribue).
3144 path: null, // forces cookie.
3145 domain: null, // forces cookie.
3146 secure: null, // forces cookie.
3147 json: false, // will convert to json when set. parse with get.
3148 fallback: true, // whether to fallback to cookies if localstorage not available.
3149 raw: false, // if true, will skip uri encoding/decoding
3150 modernizr: false // set true if youd rather handle localstorage detection through modernizr
3151 }, options);
3152
3153 remember = {
3154 init: function(){
3155 var controller;
3156
3157 // controls what to do with the input. set - get - set/get - erase
3158 // set if name exists, value exists, and not set to remove cookie.
3159 // get if name exists, value does not exist, and not set to remove
3160 // remove if remove set to true
3161 if (settings.name !== null && settings.value !== undefined && settings.remove !== true){
3162 if (settings.getSet === true){
3163 var get = this.get();
3164 // if the value of get exists, return it. otherwise, set the value as specified.
3165 if (get === null){
3166 this.set();
3167 } else {
3168 controller = get;
3169 }
3170 } else {
3171 this.set();
3172 }
3173 } else if (settings.name !== null && settings.value === undefined && settings.remove !== true){
3174 controller = this.get();
3175 } else if (settings.name !== null && settings.remove === true){
3176 this.erase();
3177 }
3178
3179 // will return result of everything to calling js
3180 return controller;
3181 },
3182 get: function(){
3183 var use = this._use(),
3184 value = null,
3185 cookies,
3186 parts,
3187 name;
3188
3189 // grab the key value pair from localstorage
3190 if (use === 'localstorage') {
3191 value = localStorage.getItem(settings.name);
3192 }
3193
3194 // hit if cookie requested, and when double checking a get on an empty localstorage item
3195 if ((use === 'cookie') || (use === 'localstorage' && value === null && settings.fallback !== false)) {
3196
3197 // grab all the cookies from the browser, check if set, and loop through
3198 cookies = document.cookie ? document.cookie : null;
3199 if (cookies !== null){
3200 cookies = cookies.split(';');
3201 for (var i = 0; i < cookies.length; i++){
3202 // separate the key value pair
3203 parts = cookies[i].split('=');
3204 // set name and value to split parts, cleaning up whitespace
3205 name = parts.shift();
3206 name = settings.raw === false ? this._trim(this._decode(name)) : this._trim(name);
3207 value = parts[0];
3208 // break when we hit a match, or cookie is empty
3209 if (settings.name === name) {
3210 break;
3211 } else if (settings.fallback !== false) {
3212 value = localStorage.getItem(settings.name) || null;
3213 } else {
3214 value = null;
3215 }
3216 }
3217 }
3218 }
3219
3220 // decode uri and if json is requested, parse the cookie/localstorage and return to controller
3221 value = (value && settings.raw === false) ? this._decode(value) : value;
3222 value = (value && settings.json === true) ? JSON.parse(value) : value;
3223
3224 return value;
3225 },
3226 set: function(){
3227 var use = this._use();
3228
3229 // if set is hit, user has intentionally tried to set (get/set not hit)
3230 // clear the storage alternative, so the same value isnt stored in both
3231 this.erase();
3232
3233 // convert the value to store in json if requested
3234 settings.value = settings.json === true ? JSON.stringify(settings.value) : settings.value;
3235
3236 // encode
3237 settings.name = settings.raw === false ? encodeURIComponent(settings.name) : settings.name;
3238 settings.value = settings.raw === false ? encodeURIComponent(settings.value) : settings.value;
3239
3240 // store the key value pair in appropriate storage. set unless storage requirements failed
3241 if (use === 'localstorage'){
3242 localStorage.setItem(settings.name, settings.value);
3243 } else if (use !== false){
3244 // convert values that cant be stored and set
3245 settings.value = settings.value === null ? 'null' : settings.value;
3246 this._setCookie();
3247 }
3248 },
3249 erase: function(){
3250 var use = this._use();
3251
3252 // clear localstorage and cookies by setting expiration to negative
3253 if (use !== 'cookie' || settings.fallback !== false){
3254 localStorage.removeItem(settings.name);
3255 }
3256 if (use !== 'localstorage' || settings.fallback !== false){
3257 this._setCookie('', -1);
3258 }
3259 },
3260 _use: function(){
3261 var use,
3262 localStorageSupport = this._localStorage();
3263
3264 // if cookie requested, or any options set that only apply to cookies
3265 if (settings.use === 'cookie' || settings.expires !== null || settings.path !== null || settings.domain !== null || settings.secure !== null){
3266 use = 'cookie';
3267 } else {
3268 // use local storage if available
3269 if (localStorageSupport){
3270 use = 'localstorage';
3271 } else if (settings.fallback !== false) {
3272 // default to cookie, unless fallback banned
3273 use = 'cookie';
3274 } else {
3275 // if all this fails, nothing can be set
3276 use = false;
3277 }
3278 }
3279
3280 return use;
3281 },
3282 _setCookie: function(){
3283 // allow for varying parameters with defaults. value then expires as optional params
3284 var value = arguments.length > 0 ? arguments[0] : settings.value,
3285 expires = arguments.length > 1 ? arguments[1] : settings.expires,
3286 expire;
3287
3288 // set a date in the future (or negative to delete) based on expires date offset
3289 if (typeof expires === 'number') {
3290 expire = new Date();
3291 expire.setDate(expire.getDate() + expires);
3292 }
3293
3294 // set the cookies with all the varying settings
3295 document.cookie = [
3296 settings.name,
3297 '=',
3298 value,
3299 expire ? '; expires=' + expire.toUTCString() : '',
3300 settings.path ? '; path=' + settings.path : '',
3301 settings.domain ? '; domain=' + settings.domain : '',
3302 settings.secure ? '; secure' : ''
3303 ].join('');
3304 },
3305 _localStorage: function(){
3306 if (settings.modernizr === true && typeof Modernizr !== 'undefined'){
3307 return Modernizr.localstorage;
3308 } else {
3309 // check if a browser supports localstorage with simple try catch
3310 try {
3311 localStorage.setItem('jquery-remember-test','jquery-remember-test');
3312 localStorage.removeItem('jquery-remember-test');
3313 return true;
3314 } catch(e){
3315 return false;
3316 }
3317 }
3318 },
3319 _trim: function(s){
3320 // trail a strings leading/ending whitespace
3321 return s.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
3322 },
3323 _decode: function(s){
3324 return decodeURIComponent(s.replace(/\+/g, ' '));
3325 }
3326 };
3327
3328 return remember.init();
3329 };
3330
3331 return $.remember;
3332
3333 }(jQuery));
3334 (function(a){if(typeof define==="function"&&define.amd){if(typeof jQuery!=="undefined"){define(["jquery"],a)}else{define([],a)}}else{if(typeof jQuery!=="undefined"){a(jQuery)}else{a()}}})(function(b,e){var q={a:"href",img:"src",form:"action",base:"href",script:"src",iframe:"src",link:"href"},t=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","fragment"],p={anchor:"fragment"},a={strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/},s=/^[0-9]+$/;function o(u,x){var z=decodeURI(u),w=a[x||false?"strict":"loose"].exec(z),y={attr:{},param:{},seg:{}},v=14;while(v--){y.attr[t[v]]=w[v]||""}y.param.query=f(y.attr.query);y.param.fragment=f(y.attr.fragment);y.seg.path=y.attr.path.replace(/^\/+|\/+$/g,"").split("/");y.seg.fragment=y.attr.fragment.replace(/^\/+|\/+$/g,"").split("/");y.attr.base=y.attr.host?(y.attr.protocol?y.attr.protocol+"://"+y.attr.host:y.attr.host)+(y.attr.port?":"+y.attr.port:""):"";return y}function m(v){var u=v.tagName;if(typeof u!=="undefined"){return q[u.toLowerCase()]}return u}function c(x,w){if(x[w].length===0){return x[w]={}}var v={};for(var u in x[w]){v[u]=x[w][u]}x[w]=v;return v}function l(y,w,v,z){var u=y.shift();if(!u){if(g(w[v])){w[v].push(z)}else{if("object"==typeof w[v]){w[v]=z}else{if("undefined"==typeof w[v]){w[v]=z}else{w[v]=[w[v],z]}}}}else{var x=w[v]=w[v]||[];if("]"==u){if(g(x)){if(""!=z){x.push(z)}}else{if("object"==typeof x){x[j(x).length]=z}else{x=w[v]=[w[v],z]}}}else{if(~u.indexOf("]")){u=u.substr(0,u.length-1);if(!s.test(u)&&g(x)){x=c(w,v)}l(y,x,u,z)}else{if(!s.test(u)&&g(x)){x=c(w,v)}l(y,x,u,z)}}}}function d(x,w,z){if(~w.indexOf("]")){var y=w.split("[");l(y,x,"base",z)}else{if(!s.test(w)&&g(x.base)){var v={};for(var u in x.base){v[u]=x.base[u]}x.base=v}i(x.base,w,z)}return x}function f(u){if(u==""){return{}}return h(String(u).split(/&|;/),function(v,A){try{A=decodeURIComponent(A.replace(/\+/g," "))}catch(x){}var B=A.indexOf("="),z=n(A),w=A.substr(0,z||B),y=A.substr(z||B,A.length),y=y.substr(y.indexOf("=")+1,y.length);if(""==w){w=A,y=""}return d(v,w,y)},{base:{}}).base}function i(x,w,y){var u=x[w];if(e===u){x[w]=y}else{if(g(u)){u.push(y)}else{x[w]=[u,y]}}}function n(x){var u=x.length,w,y;for(var v=0;v<u;++v){y=x[v];if("]"==y){w=false}if("["==y){w=true}if("="==y&&!w){return v}}}function h(y,v){var w=0,u=y.length>>0,x=arguments[2];while(w<u){if(w in y){x=v.call(e,x,y[w],w,y)}++w}return x}function g(u){return Object.prototype.toString.call(u)==="[object Array]"}function j(v){var u=[];for(prop in v){if(v.hasOwnProperty(prop)){u.push(prop)}}return u}function k(u){return Object(u)===u&&Object.getPrototypeOf(u)===Object.prototype}function r(u,v){if(arguments.length===1&&u===true){v=true;u=e}v=v||false;u=u||window.location.toString();return{data:o(u,v),attr:function(w){w=p[w]||w;return typeof w!=="undefined"?this.data.attr[w]:this.data.attr},param:function(x,w){if(k(x)){this.data.param.query=x;return this}else{if(w==e){return typeof x!=="undefined"?this.data.param.query[x]:this.data.param.query}else{this.data.param.query[x]=w;return this}}},removeParam:function(w){delete this.data.param.query[w]},fparam:function(w){return typeof w!=="undefined"?this.data.param.fragment[w]:this.data.param.fragment},segment:function(w){if(typeof w==="undefined"){return this.data.seg.path}else{w=w<0?this.data.seg.path.length+w:w-1;return this.data.seg.path[w]}},fsegment:function(w){if(typeof w==="undefined"){return this.data.seg.fragment}else{w=w<0?this.data.seg.fragment.length+w:w-1;return this.data.seg.fragment[w]}},toString:function(){var w="";if(this.data.attr.host!==""){w+=this.data.attr.protocol+"://"+this.data.attr.host}if(this.data.attr.port!=="80"){w+=":"+this.data.attr.port}w+=this.data.attr.path;Object.keys=Object.keys||function(C){var A=[];for(var B in C){if(C.hasOwnProperty(B)){A.push(B)}}return A};if(Object.keys(this.data.param.query).length>0){w+="?";var x=[];for(var y in this.data.param.query){x.push(encodeURIComponent(y)+"="+encodeURIComponent(this.data.param.query[y]))}w+=x.join("&")}if(Object.keys(this.data.param.fragment).length>0){w+="#";var z=[];for(var y in this.data.param.fragment){if(this.data.param.fragment[y]===""){z.push(y)}else{z.push(y+"="+this.data.param.fragment[y])}}w+=z.join("&")}return w}}}if(typeof b!=="undefined"){b.fn.url=function(v){var u="";if(this.length){u=b(this).attr(m(this[0]))||""}return r(u,v)};b.url=r}else{window.purl=r}});
3335 /*! jQuery UI - v1.10.3 - 2013-05-29
3336 * http://jqueryui.com
3337 * Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.menu.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.spinner.js, jquery.ui.tabs.js, jquery.ui.tooltip.js, jquery.ui.effect.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js
3338 * Copyright 2013 jQuery Foundation and other contributors Licensed MIT */
3339
3340 (function( $, undefined ) {
3341
3342 var uuid = 0,
3343 runiqueId = /^ui-id-\d+$/;
3344
3345 // $.ui might exist from components with no dependencies, e.g., $.ui.position
3346 $.ui = $.ui || {};
3347
3348 $.extend( $.ui, {
3349 version: "1.10.3",
3350
3351 keyCode: {
3352 BACKSPACE: 8,
3353 COMMA: 188,
3354 DELETE: 46,
3355 DOWN: 40,
3356 END: 35,
3357 ENTER: 13,
3358 ESCAPE: 27,
3359 HOME: 36,
3360 LEFT: 37,
3361 NUMPAD_ADD: 107,
3362 NUMPAD_DECIMAL: 110,
3363 NUMPAD_DIVIDE: 111,
3364 NUMPAD_ENTER: 108,
3365 NUMPAD_MULTIPLY: 106,
3366 NUMPAD_SUBTRACT: 109,
3367 PAGE_DOWN: 34,
3368 PAGE_UP: 33,
3369 PERIOD: 190,
3370 RIGHT: 39,
3371 SPACE: 32,
3372 TAB: 9,
3373 UP: 38
3374 }
3375 });
3376
3377 // plugins
3378 $.fn.extend({
3379 focus: (function( orig ) {
3380 return function( delay, fn ) {
3381 return typeof delay === "number" ?
3382 this.each(function() {
3383 var elem = this;
3384 setTimeout(function() {
3385 $( elem ).focus();
3386 if ( fn ) {
3387 fn.call( elem );
3388 }
3389 }, delay );
3390 }) :
3391 orig.apply( this, arguments );
3392 };
3393 })( $.fn.focus ),
3394
3395 scrollParent: function() {
3396 var scrollParent;
3397 if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) {
3398 scrollParent = this.parents().filter(function() {
3399 return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
3400 }).eq(0);
3401 } else {
3402 scrollParent = this.parents().filter(function() {
3403 return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
3404 }).eq(0);
3405 }
3406
3407 return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent;
3408 },
3409
3410 zIndex: function( zIndex ) {
3411 if ( zIndex !== undefined ) {
3412 return this.css( "zIndex", zIndex );
3413 }
3414
3415 if ( this.length ) {
3416 var elem = $( this[ 0 ] ), position, value;
3417 while ( elem.length && elem[ 0 ] !== document ) {
3418 // Ignore z-index if position is set to a value where z-index is ignored by the browser
3419 // This makes behavior of this function consistent across browsers
3420 // WebKit always returns auto if the element is positioned
3421 position = elem.css( "position" );
3422 if ( position === "absolute" || position === "relative" || position === "fixed" ) {
3423 // IE returns 0 when zIndex is not specified
3424 // other browsers return a string
3425 // we ignore the case of nested elements with an explicit value of 0
3426 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
3427 value = parseInt( elem.css( "zIndex" ), 10 );
3428 if ( !isNaN( value ) && value !== 0 ) {
3429 return value;
3430 }
3431 }
3432 elem = elem.parent();
3433 }
3434 }
3435
3436 return 0;
3437 },
3438
3439 uniqueId: function() {
3440 return this.each(function() {
3441 if ( !this.id ) {
3442 this.id = "ui-id-" + (++uuid);
3443 }
3444 });
3445 },
3446
3447 removeUniqueId: function() {
3448 return this.each(function() {
3449 if ( runiqueId.test( this.id ) ) {
3450 $( this ).removeAttr( "id" );
3451 }
3452 });
3453 }
3454 });
3455
3456 // selectors
3457 function focusable( element, isTabIndexNotNaN ) {
3458 var map, mapName, img,
3459 nodeName = element.nodeName.toLowerCase();
3460 if ( "area" === nodeName ) {
3461 map = element.parentNode;
3462 mapName = map.name;
3463 if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
3464 return false;
3465 }
3466 img = $( "img[usemap=#" + mapName + "]" )[0];
3467 return !!img && visible( img );
3468 }
3469 return ( /input|select|textarea|button|object/.test( nodeName ) ?
3470 !element.disabled :
3471 "a" === nodeName ?
3472 element.href || isTabIndexNotNaN :
3473 isTabIndexNotNaN) &&
3474 // the element and all of its ancestors must be visible
3475 visible( element );
3476 }
3477
3478 function visible( element ) {
3479 return $.expr.filters.visible( element ) &&
3480 !$( element ).parents().addBack().filter(function() {
3481 return $.css( this, "visibility" ) === "hidden";
3482 }).length;
3483 }
3484
3485 $.extend( $.expr[ ":" ], {
3486 data: $.expr.createPseudo ?
3487 $.expr.createPseudo(function( dataName ) {
3488 return function( elem ) {
3489 return !!$.data( elem, dataName );
3490 };
3491 }) :
3492 // support: jQuery <1.8
3493 function( elem, i, match ) {
3494 return !!$.data( elem, match[ 3 ] );
3495 },
3496
3497 focusable: function( element ) {
3498 return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
3499 },
3500
3501 tabbable: function( element ) {
3502 var tabIndex = $.attr( element, "tabindex" ),
3503 isTabIndexNaN = isNaN( tabIndex );
3504 return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
3505 }
3506 });
3507
3508 // support: jQuery <1.8
3509 if ( !$( "<a>" ).outerWidth( 1 ).jquery ) {
3510 $.each( [ "Width", "Height" ], function( i, name ) {
3511 var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
3512 type = name.toLowerCase(),
3513 orig = {
3514 innerWidth: $.fn.innerWidth,
3515 innerHeight: $.fn.innerHeight,
3516 outerWidth: $.fn.outerWidth,
3517 outerHeight: $.fn.outerHeight
3518 };
3519
3520 function reduce( elem, size, border, margin ) {
3521 $.each( side, function() {
3522 size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
3523 if ( border ) {
3524 size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
3525 }
3526 if ( margin ) {
3527 size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
3528 }
3529 });
3530 return size;
3531 }
3532
3533 $.fn[ "inner" + name ] = function( size ) {
3534 if ( size === undefined ) {
3535 return orig[ "inner" + name ].call( this );
3536 }
3537
3538 return this.each(function() {
3539 $( this ).css( type, reduce( this, size ) + "px" );
3540 });
3541 };
3542
3543 $.fn[ "outer" + name] = function( size, margin ) {
3544 if ( typeof size !== "number" ) {
3545 return orig[ "outer" + name ].call( this, size );
3546 }
3547
3548 return this.each(function() {
3549 $( this).css( type, reduce( this, size, true, margin ) + "px" );
3550 });
3551 };
3552 });
3553 }
3554
3555 // support: jQuery <1.8
3556 if ( !$.fn.addBack ) {
3557 $.fn.addBack = function( selector ) {
3558 return this.add( selector == null ?
3559 this.prevObject : this.prevObject.filter( selector )
3560 );
3561 };
3562 }
3563
3564 // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
3565 if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
3566 $.fn.removeData = (function( removeData ) {
3567 return function( key ) {
3568 if ( arguments.length ) {
3569 return removeData.call( this, $.camelCase( key ) );
3570 } else {
3571 return removeData.call( this );
3572 }
3573 };
3574 })( $.fn.removeData );
3575 }
3576
3577
3578
3579
3580
3581 // deprecated
3582 $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );
3583
3584 $.support.selectstart = "onselectstart" in document.createElement( "div" );
3585 $.fn.extend({
3586 disableSelection: function() {
3587 return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
3588 ".ui-disableSelection", function( event ) {
3589 event.preventDefault();
3590 });
3591 },
3592
3593 enableSelection: function() {
3594 return this.unbind( ".ui-disableSelection" );
3595 }
3596 });
3597
3598 $.extend( $.ui, {
3599 // $.ui.plugin is deprecated. Use $.widget() extensions instead.
3600 plugin: {
3601 add: function( module, option, set ) {
3602 var i,
3603 proto = $.ui[ module ].prototype;
3604 for ( i in set ) {
3605 proto.plugins[ i ] = proto.plugins[ i ] || [];
3606 proto.plugins[ i ].push( [ option, set[ i ] ] );
3607 }
3608 },
3609 call: function( instance, name, args ) {
3610 var i,
3611 set = instance.plugins[ name ];
3612 if ( !set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) {
3613 return;
3614 }
3615
3616 for ( i = 0; i < set.length; i++ ) {
3617 if ( instance.options[ set[ i ][ 0 ] ] ) {
3618 set[ i ][ 1 ].apply( instance.element, args );
3619 }
3620 }
3621 }
3622 },
3623
3624 // only used by resizable
3625 hasScroll: function( el, a ) {
3626
3627 //If overflow is hidden, the element might have extra content, but the user wants to hide it
3628 if ( $( el ).css( "overflow" ) === "hidden") {
3629 return false;
3630 }
3631
3632 var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
3633 has = false;
3634
3635 if ( el[ scroll ] > 0 ) {
3636 return true;
3637 }
3638
3639 // TODO: determine which cases actually cause this to happen
3640 // if the element doesn't have the scroll set, see if it's possible to
3641 // set the scroll
3642 el[ scroll ] = 1;
3643 has = ( el[ scroll ] > 0 );
3644 el[ scroll ] = 0;
3645 return has;
3646 }
3647 });
3648
3649 })( jQuery );
3650 (function( $, undefined ) {
3651
3652 var uuid = 0,
3653 slice = Array.prototype.slice,
3654 _cleanData = $.cleanData;
3655 $.cleanData = function( elems ) {
3656 for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
3657 try {
3658 $( elem ).triggerHandler( "remove" );
3659 // http://bugs.jquery.com/ticket/8235
3660 } catch( e ) {}
3661 }
3662 _cleanData( elems );
3663 };
3664
3665 $.widget = function( name, base, prototype ) {
3666 var fullName, existingConstructor, constructor, basePrototype,
3667 // proxiedPrototype allows the provided prototype to remain unmodified
3668 // so that it can be used as a mixin for multiple widgets (#8876)
3669 proxiedPrototype = {},
3670 namespace = name.split( "." )[ 0 ];
3671
3672 name = name.split( "." )[ 1 ];
3673 fullName = namespace + "-" + name;
3674
3675 if ( !prototype ) {
3676 prototype = base;
3677 base = $.Widget;
3678 }
3679
3680 // create selector for plugin
3681 $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
3682 return !!$.data( elem, fullName );
3683 };
3684
3685 $[ namespace ] = $[ namespace ] || {};
3686 existingConstructor = $[ namespace ][ name ];
3687 constructor = $[ namespace ][ name ] = function( options, element ) {
3688 // allow instantiation without "new" keyword
3689 if ( !this._createWidget ) {
3690 return new constructor( options, element );
3691 }
3692
3693 // allow instantiation without initializing for simple inheritance
3694 // must use "new" keyword (the code above always passes args)
3695 if ( arguments.length ) {
3696 this._createWidget( options, element );
3697 }
3698 };
3699 // extend with the existing constructor to carry over any static properties
3700 $.extend( constructor, existingConstructor, {
3701 version: prototype.version,
3702 // copy the object used to create the prototype in case we need to
3703 // redefine the widget later
3704 _proto: $.extend( {}, prototype ),
3705 // track widgets that inherit from this widget in case this widget is
3706 // redefined after a widget inherits from it
3707 _childConstructors: []
3708 });
3709
3710 basePrototype = new base();
3711 // we need to make the options hash a property directly on the new instance
3712 // otherwise we'll modify the options hash on the prototype that we're
3713 // inheriting from
3714 basePrototype.options = $.widget.extend( {}, basePrototype.options );
3715 $.each( prototype, function( prop, value ) {
3716 if ( !$.isFunction( value ) ) {
3717 proxiedPrototype[ prop ] = value;
3718 return;
3719 }
3720 proxiedPrototype[ prop ] = (function() {
3721 var _super = function() {
3722 return base.prototype[ prop ].apply( this, arguments );
3723 },
3724 _superApply = function( args ) {
3725 return base.prototype[ prop ].apply( this, args );
3726 };
3727 return function() {
3728 var __super = this._super,
3729 __superApply = this._superApply,
3730 returnValue;
3731
3732 this._super = _super;
3733 this._superApply = _superApply;
3734
3735 returnValue = value.apply( this, arguments );
3736
3737 this._super = __super;
3738 this._superApply = __superApply;
3739
3740 return returnValue;
3741 };
3742 })();
3743 });
3744 constructor.prototype = $.widget.extend( basePrototype, {
3745 // TODO: remove support for widgetEventPrefix
3746 // always use the name + a colon as the prefix, e.g., draggable:start
3747 // don't prefix for widgets that aren't DOM-based
3748 widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name
3749 }, proxiedPrototype, {
3750 constructor: constructor,
3751 namespace: namespace,
3752 widgetName: name,
3753 widgetFullName: fullName
3754 });
3755
3756 // If this widget is being redefined then we need to find all widgets that
3757 // are inheriting from it and redefine all of them so that they inherit from
3758 // the new version of this widget. We're essentially trying to replace one
3759 // level in the prototype chain.
3760 if ( existingConstructor ) {
3761 $.each( existingConstructor._childConstructors, function( i, child ) {
3762 var childPrototype = child.prototype;
3763
3764 // redefine the child widget using the same prototype that was
3765 // originally used, but inherit from the new version of the base
3766 $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
3767 });
3768 // remove the list of existing child constructors from the old constructor
3769 // so the old child constructors can be garbage collected
3770 delete existingConstructor._childConstructors;
3771 } else {
3772 base._childConstructors.push( constructor );
3773 }
3774
3775 $.widget.bridge( name, constructor );
3776 };
3777
3778 $.widget.extend = function( target ) {
3779 var input = slice.call( arguments, 1 ),
3780 inputIndex = 0,
3781 inputLength = input.length,
3782 key,
3783 value;
3784 for ( ; inputIndex < inputLength; inputIndex++ ) {
3785 for ( key in input[ inputIndex ] ) {
3786 value = input[ inputIndex ][ key ];
3787 if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
3788 // Clone objects
3789 if ( $.isPlainObject( value ) ) {
3790 target[ key ] = $.isPlainObject( target[ key ] ) ?
3791 $.widget.extend( {}, target[ key ], value ) :
3792 // Don't extend strings, arrays, etc. with objects
3793 $.widget.extend( {}, value );
3794 // Copy everything else by reference
3795 } else {
3796 target[ key ] = value;
3797 }
3798 }
3799 }
3800 }
3801 return target;
3802 };
3803
3804 $.widget.bridge = function( name, object ) {
3805 var fullName = object.prototype.widgetFullName || name;
3806 $.fn[ name ] = function( options ) {
3807 var isMethodCall = typeof options === "string",
3808 args = slice.call( arguments, 1 ),
3809 returnValue = this;
3810
3811 // allow multiple hashes to be passed on init
3812 options = !isMethodCall && args.length ?
3813 $.widget.extend.apply( null, [ options ].concat(args) ) :
3814 options;
3815
3816 if ( isMethodCall ) {
3817 this.each(function() {
3818 var methodValue,
3819 instance = $.data( this, fullName );
3820 if ( !instance ) {
3821 return $.error( "cannot call methods on " + name + " prior to initialization; " +
3822 "attempted to call method '" + options + "'" );
3823 }
3824 if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
3825 return $.error( "no such method '" + options + "' for " + name + " widget instance" );
3826 }
3827 methodValue = instance[ options ].apply( instance, args );
3828 if ( methodValue !== instance && methodValue !== undefined ) {
3829 returnValue = methodValue && methodValue.jquery ?
3830 returnValue.pushStack( methodValue.get() ) :
3831 methodValue;
3832 return false;
3833 }
3834 });
3835 } else {
3836 this.each(function() {
3837 var instance = $.data( this, fullName );
3838 if ( instance ) {
3839 instance.option( options || {} )._init();
3840 } else {
3841 $.data( this, fullName, new object( options, this ) );
3842 }
3843 });
3844 }
3845
3846 return returnValue;
3847 };
3848 };
3849
3850 $.Widget = function( /* options, element */ ) {};
3851 $.Widget._childConstructors = [];
3852
3853 $.Widget.prototype = {
3854 widgetName: "widget",
3855 widgetEventPrefix: "",
3856 defaultElement: "<div>",
3857 options: {
3858 disabled: false,
3859
3860 // callbacks
3861 create: null
3862 },
3863 _createWidget: function( options, element ) {
3864 element = $( element || this.defaultElement || this )[ 0 ];
3865 this.element = $( element );
3866 this.uuid = uuid++;
3867 this.eventNamespace = "." + this.widgetName + this.uuid;
3868 this.options = $.widget.extend( {},
3869 this.options,
3870 this._getCreateOptions(),
3871 options );
3872
3873 this.bindings = $();
3874 this.hoverable = $();
3875 this.focusable = $();
3876
3877 if ( element !== this ) {
3878 $.data( element, this.widgetFullName, this );
3879 this._on( true, this.element, {
3880 remove: function( event ) {
3881 if ( event.target === element ) {
3882 this.destroy();
3883 }
3884 }
3885 });
3886 this.document = $( element.style ?
3887 // element within the document
3888 element.ownerDocument :
3889 // element is window or document
3890 element.document || element );
3891 this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
3892 }
3893
3894 this._create();
3895 this._trigger( "create", null, this._getCreateEventData() );
3896 this._init();
3897 },
3898 _getCreateOptions: $.noop,
3899 _getCreateEventData: $.noop,
3900 _create: $.noop,
3901 _init: $.noop,
3902
3903 destroy: function() {
3904 this._destroy();
3905 // we can probably remove the unbind calls in 2.0
3906 // all event bindings should go through this._on()
3907 this.element
3908 .unbind( this.eventNamespace )
3909 // 1.9 BC for #7810
3910 // TODO remove dual storage
3911 .removeData( this.widgetName )
3912 .removeData( this.widgetFullName )
3913 // support: jquery <1.6.3
3914 // http://bugs.jquery.com/ticket/9413
3915 .removeData( $.camelCase( this.widgetFullName ) );
3916 this.widget()
3917 .unbind( this.eventNamespace )
3918 .removeAttr( "aria-disabled" )
3919 .removeClass(
3920 this.widgetFullName + "-disabled " +
3921 "ui-state-disabled" );
3922
3923 // clean up events and states
3924 this.bindings.unbind( this.eventNamespace );
3925 this.hoverable.removeClass( "ui-state-hover" );
3926 this.focusable.removeClass( "ui-state-focus" );
3927 },
3928 _destroy: $.noop,
3929
3930 widget: function() {
3931 return this.element;
3932 },
3933
3934 option: function( key, value ) {
3935 var options = key,
3936 parts,
3937 curOption,
3938 i;
3939
3940 if ( arguments.length === 0 ) {
3941 // don't return a reference to the internal hash
3942 return $.widget.extend( {}, this.options );
3943 }
3944
3945 if ( typeof key === "string" ) {
3946 // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
3947 options = {};
3948 parts = key.split( "." );
3949 key = parts.shift();
3950 if ( parts.length ) {
3951 curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
3952 for ( i = 0; i < parts.length - 1; i++ ) {
3953 curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
3954 curOption = curOption[ parts[ i ] ];
3955 }
3956 key = parts.pop();
3957 if ( value === undefined ) {
3958 return curOption[ key ] === undefined ? null : curOption[ key ];
3959 }
3960 curOption[ key ] = value;
3961 } else {
3962 if ( value === undefined ) {
3963 return this.options[ key ] === undefined ? null : this.options[ key ];
3964 }
3965 options[ key ] = value;
3966 }
3967 }
3968
3969 this._setOptions( options );
3970
3971 return this;
3972 },
3973 _setOptions: function( options ) {
3974 var key;
3975
3976 for ( key in options ) {
3977 this._setOption( key, options[ key ] );
3978 }
3979
3980 return this;
3981 },
3982 _setOption: function( key, value ) {
3983 this.options[ key ] = value;
3984
3985 if ( key === "disabled" ) {
3986 this.widget()
3987 .toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
3988 .attr( "aria-disabled", value );
3989 this.hoverable.removeClass( "ui-state-hover" );
3990 this.focusable.removeClass( "ui-state-focus" );
3991 }
3992
3993 return this;
3994 },
3995
3996 enable: function() {
3997 return this._setOption( "disabled", false );
3998 },
3999 disable: function() {
4000 return this._setOption( "disabled", true );
4001 },
4002
4003 _on: function( suppressDisabledCheck, element, handlers ) {
4004 var delegateElement,
4005 instance = this;
4006
4007 // no suppressDisabledCheck flag, shuffle arguments
4008 if ( typeof suppressDisabledCheck !== "boolean" ) {
4009 handlers = element;
4010 element = suppressDisabledCheck;
4011 suppressDisabledCheck = false;
4012 }
4013
4014 // no element argument, shuffle and use this.element
4015 if ( !handlers ) {
4016 handlers = element;
4017 element = this.element;
4018 delegateElement = this.widget();
4019 } else {
4020 // accept selectors, DOM elements
4021 element = delegateElement = $( element );
4022 this.bindings = this.bindings.add( element );
4023 }
4024
4025 $.each( handlers, function( event, handler ) {
4026 function handlerProxy() {
4027 // allow widgets to customize the disabled handling
4028 // - disabled as an array instead of boolean
4029 // - disabled class as method for disabling individual parts
4030 if ( !suppressDisabledCheck &&
4031 ( instance.options.disabled === true ||
4032 $( this ).hasClass( "ui-state-disabled" ) ) ) {
4033 return;
4034 }
4035 return ( typeof handler === "string" ? instance[ handler ] : handler )
4036 .apply( instance, arguments );
4037 }
4038
4039 // copy the guid so direct unbinding works
4040 if ( typeof handler !== "string" ) {
4041 handlerProxy.guid = handler.guid =
4042 handler.guid || handlerProxy.guid || $.guid++;
4043 }
4044
4045 var match = event.match( /^(\w+)\s*(.*)$/ ),
4046 eventName = match[1] + instance.eventNamespace,
4047 selector = match[2];
4048 if ( selector ) {
4049 delegateElement.delegate( selector, eventName, handlerProxy );
4050 } else {
4051 element.bind( eventName, handlerProxy );
4052 }
4053 });
4054 },
4055
4056 _off: function( element, eventName ) {
4057 eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
4058 element.unbind( eventName ).undelegate( eventName );
4059 },
4060
4061 _delay: function( handler, delay ) {
4062 function handlerProxy() {
4063 return ( typeof handler === "string" ? instance[ handler ] : handler )
4064 .apply( instance, arguments );
4065 }
4066 var instance = this;
4067 return setTimeout( handlerProxy, delay || 0 );
4068 },
4069
4070 _hoverable: function( element ) {
4071 this.hoverable = this.hoverable.add( element );
4072 this._on( element, {
4073 mouseenter: function( event ) {
4074 $( event.currentTarget ).addClass( "ui-state-hover" );
4075 },
4076 mouseleave: function( event ) {
4077 $( event.currentTarget ).removeClass( "ui-state-hover" );
4078 }
4079 });
4080 },
4081
4082 _focusable: function( element ) {
4083 this.focusable = this.focusable.add( element );
4084 this._on( element, {
4085 focusin: function( event ) {
4086 $( event.currentTarget ).addClass( "ui-state-focus" );
4087 },
4088 focusout: function( event ) {
4089 $( event.currentTarget ).removeClass( "ui-state-focus" );
4090 }
4091 });
4092 },
4093
4094 _trigger: function( type, event, data ) {
4095 var prop, orig,
4096 callback = this.options[ type ];
4097
4098 data = data || {};
4099 event = $.Event( event );
4100 event.type = ( type === this.widgetEventPrefix ?
4101 type :
4102 this.widgetEventPrefix + type ).toLowerCase();
4103 // the original event may come from any element
4104 // so we need to reset the target on the new event
4105 event.target = this.element[ 0 ];
4106
4107 // copy original event properties over to the new event
4108 orig = event.originalEvent;
4109 if ( orig ) {
4110 for ( prop in orig ) {
4111 if ( !( prop in event ) ) {
4112 event[ prop ] = orig[ prop ];
4113 }
4114 }
4115 }
4116
4117 this.element.trigger( event, data );
4118 return !( $.isFunction( callback ) &&
4119 callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
4120 event.isDefaultPrevented() );
4121 }
4122 };
4123
4124 $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
4125 $.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
4126 if ( typeof options === "string" ) {
4127 options = { effect: options };
4128 }
4129 var hasOptions,
4130 effectName = !options ?
4131 method :
4132 options === true || typeof options === "number" ?
4133 defaultEffect :
4134 options.effect || defaultEffect;
4135 options = options || {};
4136 if ( typeof options === "number" ) {
4137 options = { duration: options };
4138 }
4139 hasOptions = !$.isEmptyObject( options );
4140 options.complete = callback;
4141 if ( options.delay ) {
4142 element.delay( options.delay );
4143 }
4144 if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
4145 element[ method ]( options );
4146 } else if ( effectName !== method && element[ effectName ] ) {
4147 element[ effectName ]( options.duration, options.easing, callback );
4148 } else {
4149 element.queue(function( next ) {
4150 $( this )[ method ]();
4151 if ( callback ) {
4152 callback.call( element[ 0 ] );
4153 }
4154 next();
4155 });
4156 }
4157 };
4158 });
4159
4160 })( jQuery );
4161 (function( $, undefined ) {
4162
4163 var mouseHandled = false;
4164 $( document ).mouseup( function() {
4165 mouseHandled = false;
4166 });
4167
4168 $.widget("ui.mouse", {
4169 version: "1.10.3",
4170 options: {
4171 cancel: "input,textarea,button,select,option",
4172 distance: 1,
4173 delay: 0
4174 },
4175 _mouseInit: function() {
4176 var that = this;
4177
4178 this.element
4179 .bind("mousedown."+this.widgetName, function(event) {
4180 return that._mouseDown(event);
4181 })
4182 .bind("click."+this.widgetName, function(event) {
4183 if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) {
4184 $.removeData(event.target, that.widgetName + ".preventClickEvent");
4185 event.stopImmediatePropagation();
4186 return false;
4187 }
4188 });
4189
4190 this.started = false;
4191 },
4192
4193 // TODO: make sure destroying one instance of mouse doesn't mess with
4194 // other instances of mouse
4195 _mouseDestroy: function() {
4196 this.element.unbind("."+this.widgetName);
4197 if ( this._mouseMoveDelegate ) {
4198 $(document)
4199 .unbind("mousemove."+this.widgetName, this._mouseMoveDelegate)
4200 .unbind("mouseup."+this.widgetName, this._mouseUpDelegate);
4201 }
4202 },
4203
4204 _mouseDown: function(event) {
4205 // don't let more than one widget handle mouseStart
4206 if( mouseHandled ) { return; }
4207
4208 // we may have missed mouseup (out of window)
4209 (this._mouseStarted && this._mouseUp(event));
4210
4211 this._mouseDownEvent = event;
4212
4213 var that = this,
4214 btnIsLeft = (event.which === 1),
4215 // event.target.nodeName works around a bug in IE 8 with
4216 // disabled inputs (#7620)
4217 elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
4218 if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
4219 return true;
4220 }
4221
4222 this.mouseDelayMet = !this.options.delay;
4223 if (!this.mouseDelayMet) {
4224 this._mouseDelayTimer = setTimeout(function() {
4225 that.mouseDelayMet = true;
4226 }, this.options.delay);
4227 }
4228
4229 if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
4230 this._mouseStarted = (this._mouseStart(event) !== false);
4231 if (!this._mouseStarted) {
4232 event.preventDefault();
4233 return true;
4234 }
4235 }
4236
4237 // Click event may never have fired (Gecko & Opera)
4238 if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) {
4239 $.removeData(event.target, this.widgetName + ".preventClickEvent");
4240 }
4241
4242 // these delegates are required to keep context
4243 this._mouseMoveDelegate = function(event) {
4244 return that._mouseMove(event);
4245 };
4246 this._mouseUpDelegate = function(event) {
4247 return that._mouseUp(event);
4248 };
4249 $(document)
4250 .bind("mousemove."+this.widgetName, this._mouseMoveDelegate)
4251 .bind("mouseup."+this.widgetName, this._mouseUpDelegate);
4252
4253 event.preventDefault();
4254
4255 mouseHandled = true;
4256 return true;
4257 },
4258
4259 _mouseMove: function(event) {
4260 // IE mouseup check - mouseup happened when mouse was out of window
4261 if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) {
4262 return this._mouseUp(event);
4263 }
4264
4265 if (this._mouseStarted) {
4266 this._mouseDrag(event);
4267 return event.preventDefault();
4268 }
4269
4270 if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
4271 this._mouseStarted =
4272 (this._mouseStart(this._mouseDownEvent, event) !== false);
4273 (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
4274 }
4275
4276 return !this._mouseStarted;
4277 },
4278
4279 _mouseUp: function(event) {
4280 $(document)
4281 .unbind("mousemove."+this.widgetName, this._mouseMoveDelegate)
4282 .unbind("mouseup."+this.widgetName, this._mouseUpDelegate);
4283
4284 if (this._mouseStarted) {
4285 this._mouseStarted = false;
4286
4287 if (event.target === this._mouseDownEvent.target) {
4288 $.data(event.target, this.widgetName + ".preventClickEvent", true);
4289 }
4290
4291 this._mouseStop(event);
4292 }
4293
4294 return false;
4295 },
4296
4297 _mouseDistanceMet: function(event) {
4298 return (Math.max(
4299 Math.abs(this._mouseDownEvent.pageX - event.pageX),
4300 Math.abs(this._mouseDownEvent.pageY - event.pageY)
4301 ) >= this.options.distance
4302 );
4303 },
4304
4305 _mouseDelayMet: function(/* event */) {
4306 return this.mouseDelayMet;
4307 },
4308
4309 // These are placeholder methods, to be overriden by extending plugin
4310 _mouseStart: function(/* event */) {},
4311 _mouseDrag: function(/* event */) {},
4312 _mouseStop: function(/* event */) {},
4313 _mouseCapture: function(/* event */) { return true; }
4314 });
4315
4316 })(jQuery);
4317 (function( $, undefined ) {
4318
4319 $.ui = $.ui || {};
4320
4321 var cachedScrollbarWidth,
4322 max = Math.max,
4323 abs = Math.abs,
4324 round = Math.round,
4325 rhorizontal = /left|center|right/,
4326 rvertical = /top|center|bottom/,
4327 roffset = /[\+\-]\d+(\.[\d]+)?%?/,
4328 rposition = /^\w+/,
4329 rpercent = /%$/,
4330 _position = $.fn.position;
4331
4332 function getOffsets( offsets, width, height ) {
4333 return [
4334 parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
4335 parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
4336 ];
4337 }
4338
4339 function parseCss( element, property ) {
4340 return parseInt( $.css( element, property ), 10 ) || 0;
4341 }
4342
4343 function getDimensions( elem ) {
4344 var raw = elem[0];
4345 if ( raw.nodeType === 9 ) {
4346 return {
4347 width: elem.width(),
4348 height: elem.height(),
4349 offset: { top: 0, left: 0 }
4350 };
4351 }
4352 if ( $.isWindow( raw ) ) {
4353 return {
4354 width: elem.width(),
4355 height: elem.height(),
4356 offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
4357 };
4358 }
4359 if ( raw.preventDefault ) {
4360 return {
4361 width: 0,
4362 height: 0,
4363 offset: { top: raw.pageY, left: raw.pageX }
4364 };
4365 }
4366 return {
4367 width: elem.outerWidth(),
4368 height: elem.outerHeight(),
4369 offset: elem.offset()
4370 };
4371 }
4372
4373 $.position = {
4374 scrollbarWidth: function() {
4375 if ( cachedScrollbarWidth !== undefined ) {
4376 return cachedScrollbarWidth;
4377 }
4378 var w1, w2,
4379 div = $( "<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ),
4380 innerDiv = div.children()[0];
4381
4382 $( "body" ).append( div );
4383 w1 = innerDiv.offsetWidth;
4384 div.css( "overflow", "scroll" );
4385
4386 w2 = innerDiv.offsetWidth;
4387
4388 if ( w1 === w2 ) {
4389 w2 = div[0].clientWidth;
4390 }
4391
4392 div.remove();
4393
4394 return (cachedScrollbarWidth = w1 - w2);
4395 },
4396 getScrollInfo: function( within ) {
4397 var overflowX = within.isWindow ? "" : within.element.css( "overflow-x" ),
4398 overflowY = within.isWindow ? "" : within.element.css( "overflow-y" ),
4399 hasOverflowX = overflowX === "scroll" ||
4400 ( overflowX === "auto" && within.width < within.element[0].scrollWidth ),
4401 hasOverflowY = overflowY === "scroll" ||
4402 ( overflowY === "auto" && within.height < within.element[0].scrollHeight );
4403 return {
4404 width: hasOverflowY ? $.position.scrollbarWidth() : 0,
4405 height: hasOverflowX ? $.position.scrollbarWidth() : 0
4406 };
4407 },
4408 getWithinInfo: function( element ) {
4409 var withinElement = $( element || window ),
4410 isWindow = $.isWindow( withinElement[0] );
4411 return {
4412 element: withinElement,
4413 isWindow: isWindow,
4414 offset: withinElement.offset() || { left: 0, top: 0 },
4415 scrollLeft: withinElement.scrollLeft(),
4416 scrollTop: withinElement.scrollTop(),
4417 width: isWindow ? withinElement.width() : withinElement.outerWidth(),
4418 height: isWindow ? withinElement.height() : withinElement.outerHeight()
4419 };
4420 }
4421 };
4422
4423 $.fn.position = function( options ) {
4424 if ( !options || !options.of ) {
4425 return _position.apply( this, arguments );
4426 }
4427
4428 // make a copy, we don't want to modify arguments
4429 options = $.extend( {}, options );
4430
4431 var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
4432 target = $( options.of ),
4433 within = $.position.getWithinInfo( options.within ),
4434 scrollInfo = $.position.getScrollInfo( within ),
4435 collision = ( options.collision || "flip" ).split( " " ),
4436 offsets = {};
4437
4438 dimensions = getDimensions( target );
4439 if ( target[0].preventDefault ) {
4440 // force left top to allow flipping
4441 options.at = "left top";
4442 }
4443 targetWidth = dimensions.width;
4444 targetHeight = dimensions.height;
4445 targetOffset = dimensions.offset;
4446 // clone to reuse original targetOffset later
4447 basePosition = $.extend( {}, targetOffset );
4448
4449 // force my and at to have valid horizontal and vertical positions
4450 // if a value is missing or invalid, it will be converted to center
4451 $.each( [ "my", "at" ], function() {
4452 var pos = ( options[ this ] || "" ).split( " " ),
4453 horizontalOffset,
4454 verticalOffset;
4455
4456 if ( pos.length === 1) {
4457 pos = rhorizontal.test( pos[ 0 ] ) ?
4458 pos.concat( [ "center" ] ) :
4459 rvertical.test( pos[ 0 ] ) ?
4460 [ "center" ].concat( pos ) :
4461 [ "center", "center" ];
4462 }
4463 pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
4464 pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";
4465
4466 // calculate offsets
4467 horizontalOffset = roffset.exec( pos[ 0 ] );
4468 verticalOffset = roffset.exec( pos[ 1 ] );
4469 offsets[ this ] = [
4470 horizontalOffset ? horizontalOffset[ 0 ] : 0,
4471 verticalOffset ? verticalOffset[ 0 ] : 0
4472 ];
4473
4474 // reduce to just the positions without the offsets
4475 options[ this ] = [
4476 rposition.exec( pos[ 0 ] )[ 0 ],
4477 rposition.exec( pos[ 1 ] )[ 0 ]
4478 ];
4479 });
4480
4481 // normalize collision option
4482 if ( collision.length === 1 ) {
4483 collision[ 1 ] = collision[ 0 ];
4484 }
4485
4486 if ( options.at[ 0 ] === "right" ) {
4487 basePosition.left += targetWidth;
4488 } else if ( options.at[ 0 ] === "center" ) {
4489 basePosition.left += targetWidth / 2;
4490 }
4491
4492 if ( options.at[ 1 ] === "bottom" ) {
4493 basePosition.top += targetHeight;
4494 } else if ( options.at[ 1 ] === "center" ) {
4495 basePosition.top += targetHeight / 2;
4496 }
4497
4498 atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
4499 basePosition.left += atOffset[ 0 ];
4500 basePosition.top += atOffset[ 1 ];
4501
4502 return this.each(function() {
4503 var collisionPosition, using,
4504 elem = $( this ),
4505 elemWidth = elem.outerWidth(),
4506 elemHeight = elem.outerHeight(),
4507 marginLeft = parseCss( this, "marginLeft" ),
4508 marginTop = parseCss( this, "marginTop" ),
4509 collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width,
4510 collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height,
4511 position = $.extend( {}, basePosition ),
4512 myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );
4513
4514 if ( options.my[ 0 ] === "right" ) {
4515 position.left -= elemWidth;
4516 } else if ( options.my[ 0 ] === "center" ) {
4517 position.left -= elemWidth / 2;
4518 }
4519
4520 if ( options.my[ 1 ] === "bottom" ) {
4521 position.top -= elemHeight;
4522 } else if ( options.my[ 1 ] === "center" ) {
4523 position.top -= elemHeight / 2;
4524 }
4525
4526 position.left += myOffset[ 0 ];
4527 position.top += myOffset[ 1 ];
4528
4529 // if the browser doesn't support fractions, then round for consistent results
4530 if ( !$.support.offsetFractions ) {
4531 position.left = round( position.left );
4532 position.top = round( position.top );
4533 }
4534
4535 collisionPosition = {
4536 marginLeft: marginLeft,
4537 marginTop: marginTop
4538 };
4539
4540 $.each( [ "left", "top" ], function( i, dir ) {
4541 if ( $.ui.position[ collision[ i ] ] ) {
4542 $.ui.position[ collision[ i ] ][ dir ]( position, {
4543 targetWidth: targetWidth,
4544 targetHeight: targetHeight,
4545 elemWidth: elemWidth,
4546 elemHeight: elemHeight,
4547 collisionPosition: collisionPosition,
4548 collisionWidth: collisionWidth,
4549 collisionHeight: collisionHeight,
4550 offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
4551 my: options.my,
4552 at: options.at,
4553 within: within,
4554 elem : elem
4555 });
4556 }
4557 });
4558
4559 if ( options.using ) {
4560 // adds feedback as second argument to using callback, if present
4561 using = function( props ) {
4562 var left = targetOffset.left - position.left,
4563 right = left + targetWidth - elemWidth,
4564 top = targetOffset.top - position.top,
4565 bottom = top + targetHeight - elemHeight,
4566 feedback = {
4567 target: {
4568 element: target,
4569 left: targetOffset.left,
4570 top: targetOffset.top,
4571 width: targetWidth,
4572 height: targetHeight
4573 },
4574 element: {
4575 element: elem,
4576 left: position.left,
4577 top: position.top,
4578 width: elemWidth,
4579 height: elemHeight
4580 },
4581 horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
4582 vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
4583 };
4584 if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
4585 feedback.horizontal = "center";
4586 }
4587 if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
4588 feedback.vertical = "middle";
4589 }
4590 if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
4591 feedback.important = "horizontal";
4592 } else {
4593 feedback.important = "vertical";
4594 }
4595 options.using.call( this, props, feedback );
4596 };
4597 }
4598
4599 elem.offset( $.extend( position, { using: using } ) );
4600 });
4601 };
4602
4603 $.ui.position = {
4604 fit: {
4605 left: function( position, data ) {
4606 var within = data.within,
4607 withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
4608 outerWidth = within.width,
4609 collisionPosLeft = position.left - data.collisionPosition.marginLeft,
4610 overLeft = withinOffset - collisionPosLeft,
4611 overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
4612 newOverRight;
4613
4614 // element is wider than within
4615 if ( data.collisionWidth > outerWidth ) {
4616 // element is initially over the left side of within
4617 if ( overLeft > 0 && overRight <= 0 ) {
4618 newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
4619 position.left += overLeft - newOverRight;
4620 // element is initially over right side of within
4621 } else if ( overRight > 0 && overLeft <= 0 ) {
4622 position.left = withinOffset;
4623 // element is initially over both left and right sides of within
4624 } else {
4625 if ( overLeft > overRight ) {
4626 position.left = withinOffset + outerWidth - data.collisionWidth;
4627 } else {
4628 position.left = withinOffset;
4629 }
4630 }
4631 // too far left -> align with left edge
4632 } else if ( overLeft > 0 ) {
4633 position.left += overLeft;
4634 // too far right -> align with right edge
4635 } else if ( overRight > 0 ) {
4636 position.left -= overRight;
4637 // adjust based on position and margin
4638 } else {
4639 position.left = max( position.left - collisionPosLeft, position.left );
4640 }
4641 },
4642 top: function( position, data ) {
4643 var within = data.within,
4644 withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
4645 outerHeight = data.within.height,
4646 collisionPosTop = position.top - data.collisionPosition.marginTop,
4647 overTop = withinOffset - collisionPosTop,
4648 overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
4649 newOverBottom;
4650
4651 // element is taller than within
4652 if ( data.collisionHeight > outerHeight ) {
4653 // element is initially over the top of within
4654 if ( overTop > 0 && overBottom <= 0 ) {
4655 newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
4656 position.top += overTop - newOverBottom;
4657 // element is initially over bottom of within
4658 } else if ( overBottom > 0 && overTop <= 0 ) {
4659 position.top = withinOffset;
4660 // element is initially over both top and bottom of within
4661 } else {
4662 if ( overTop > overBottom ) {
4663 position.top = withinOffset + outerHeight - data.collisionHeight;
4664 } else {
4665 position.top = withinOffset;
4666 }
4667 }
4668 // too far up -> align with top
4669 } else if ( overTop > 0 ) {
4670 position.top += overTop;
4671 // too far down -> align with bottom edge
4672 } else if ( overBottom > 0 ) {
4673 position.top -= overBottom;
4674 // adjust based on position and margin
4675 } else {
4676 position.top = max( position.top - collisionPosTop, position.top );
4677 }
4678 }
4679 },
4680 flip: {
4681 left: function( position, data ) {
4682 var within = data.within,
4683 withinOffset = within.offset.left + within.scrollLeft,
4684 outerWidth = within.width,
4685 offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
4686 collisionPosLeft = position.left - data.collisionPosition.marginLeft,
4687 overLeft = collisionPosLeft - offsetLeft,
4688 overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
4689 myOffset = data.my[ 0 ] === "left" ?
4690 -data.elemWidth :
4691 data.my[ 0 ] === "right" ?
4692 data.elemWidth :
4693 0,
4694 atOffset = data.at[ 0 ] === "left" ?
4695 data.targetWidth :
4696 data.at[ 0 ] === "right" ?
4697 -data.targetWidth :
4698 0,
4699 offset = -2 * data.offset[ 0 ],
4700 newOverRight,
4701 newOverLeft;
4702
4703 if ( overLeft < 0 ) {
4704 newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
4705 if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
4706 position.left += myOffset + atOffset + offset;
4707 }
4708 }
4709 else if ( overRight > 0 ) {
4710 newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft;
4711 if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
4712 position.left += myOffset + atOffset + offset;
4713 }
4714 }
4715 },
4716 top: function( position, data ) {
4717 var within = data.within,
4718 withinOffset = within.offset.top + within.scrollTop,
4719 outerHeight = within.height,
4720 offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
4721 collisionPosTop = position.top - data.collisionPosition.marginTop,
4722 overTop = collisionPosTop - offsetTop,
4723 overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
4724 top = data.my[ 1 ] === "top",
4725 myOffset = top ?
4726 -data.elemHeight :
4727 data.my[ 1 ] === "bottom" ?
4728 data.elemHeight :
4729 0,
4730 atOffset = data.at[ 1 ] === "top" ?
4731 data.targetHeight :
4732 data.at[ 1 ] === "bottom" ?
4733 -data.targetHeight :
4734 0,
4735 offset = -2 * data.offset[ 1 ],
4736 newOverTop,
4737 newOverBottom;
4738 if ( overTop < 0 ) {
4739 newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
4740 if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) {
4741 position.top += myOffset + atOffset + offset;
4742 }
4743 }
4744 else if ( overBottom > 0 ) {
4745 newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
4746 if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) {
4747 position.top += myOffset + atOffset + offset;
4748 }
4749 }
4750 }
4751 },
4752 flipfit: {
4753 left: function() {
4754 $.ui.position.flip.left.apply( this, arguments );
4755 $.ui.position.fit.left.apply( this, arguments );
4756 },
4757 top: function() {
4758 $.ui.position.flip.top.apply( this, arguments );
4759 $.ui.position.fit.top.apply( this, arguments );
4760 }
4761 }
4762 };
4763
4764 // fraction support test
4765 (function () {
4766 var testElement, testElementParent, testElementStyle, offsetLeft, i,
4767 body = document.getElementsByTagName( "body" )[ 0 ],
4768 div = document.createElement( "div" );
4769
4770 //Create a "fake body" for testing based on method used in jQuery.support
4771 testElement = document.createElement( body ? "div" : "body" );
4772 testElementStyle = {
4773 visibility: "hidden",
4774 width: 0,
4775 height: 0,
4776 border: 0,
4777 margin: 0,
4778 background: "none"
4779 };
4780 if ( body ) {
4781 $.extend( testElementStyle, {
4782 position: "absolute",
4783 left: "-1000px",
4784 top: "-1000px"
4785 });
4786 }
4787 for ( i in testElementStyle ) {
4788 testElement.style[ i ] = testElementStyle[ i ];
4789 }
4790 testElement.appendChild( div );
4791 testElementParent = body || document.documentElement;
4792 testElementParent.insertBefore( testElement, testElementParent.firstChild );
4793
4794 div.style.cssText = "position: absolute; left: 10.7432222px;";
4795
4796 offsetLeft = $( div ).offset().left;
4797 $.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11;
4798
4799 testElement.innerHTML = "";
4800 testElementParent.removeChild( testElement );
4801 })();
4802
4803 }( jQuery ) );
4804 (function( $, undefined ) {
4805
4806 $.widget("ui.draggable", $.ui.mouse, {
4807 version: "1.10.3",
4808 widgetEventPrefix: "drag",
4809 options: {
4810 addClasses: true,
4811 appendTo: "parent",
4812 axis: false,
4813 connectToSortable: false,
4814 containment: false,
4815 cursor: "auto",
4816 cursorAt: false,
4817 grid: false,
4818 handle: false,
4819 helper: "original",
4820 iframeFix: false,
4821 opacity: false,
4822 refreshPositions: false,
4823 revert: false,
4824 revertDuration: 500,
4825 scope: "default",
4826 scroll: true,
4827 scrollSensitivity: 20,
4828 scrollSpeed: 20,
4829 snap: false,
4830 snapMode: "both",
4831 snapTolerance: 20,
4832 stack: false,
4833 zIndex: false,
4834
4835 // callbacks
4836 drag: null,
4837 start: null,
4838 stop: null
4839 },
4840 _create: function() {
4841
4842 if (this.options.helper === "original" && !(/^(?:r|a|f)/).test(this.element.css("position"))) {
4843 this.element[0].style.position = "relative";
4844 }
4845 if (this.options.addClasses){
4846 this.element.addClass("ui-draggable");
4847 }
4848 if (this.options.disabled){
4849 this.element.addClass("ui-draggable-disabled");
4850 }
4851
4852 this._mouseInit();
4853
4854 },
4855
4856 _destroy: function() {
4857 this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" );
4858 this._mouseDestroy();
4859 },
4860
4861 _mouseCapture: function(event) {
4862
4863 var o = this.options;
4864
4865 // among others, prevent a drag on a resizable-handle
4866 if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) {
4867 return false;
4868 }
4869
4870 //Quit if we're not on a valid handle
4871 this.handle = this._getHandle(event);
4872 if (!this.handle) {
4873 return false;
4874 }
4875
4876 $(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() {
4877 $("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>")
4878 .css({
4879 width: this.offsetWidth+"px", height: this.offsetHeight+"px",
4880 position: "absolute", opacity: "0.001", zIndex: 1000
4881 })
4882 .css($(this).offset())
4883 .appendTo("body");
4884 });
4885
4886 return true;
4887
4888 },
4889
4890 _mouseStart: function(event) {
4891
4892 var o = this.options;
4893
4894 //Create and append the visible helper
4895 this.helper = this._createHelper(event);
4896
4897 this.helper.addClass("ui-draggable-dragging");
4898
4899 //Cache the helper size
4900 this._cacheHelperProportions();
4901
4902 //If ddmanager is used for droppables, set the global draggable
4903 if($.ui.ddmanager) {
4904 $.ui.ddmanager.current = this;
4905 }
4906
4907 /*
4908 * - Position generation -
4909 * This block generates everything position related - it's the core of draggables.
4910 */
4911
4912 //Cache the margins of the original element
4913 this._cacheMargins();
4914
4915 //Store the helper's css position
4916 this.cssPosition = this.helper.css( "position" );
4917 this.scrollParent = this.helper.scrollParent();
4918 this.offsetParent = this.helper.offsetParent();
4919 this.offsetParentCssPosition = this.offsetParent.css( "position" );
4920
4921 //The element's absolute position on the page minus margins
4922 this.offset = this.positionAbs = this.element.offset();
4923 this.offset = {
4924 top: this.offset.top - this.margins.top,
4925 left: this.offset.left - this.margins.left
4926 };
4927
4928 //Reset scroll cache
4929 this.offset.scroll = false;
4930
4931 $.extend(this.offset, {
4932 click: { //Where the click happened, relative to the element
4933 left: event.pageX - this.offset.left,
4934 top: event.pageY - this.offset.top
4935 },
4936 parent: this._getParentOffset(),
4937 relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
4938 });
4939
4940 //Generate the original position
4941 this.originalPosition = this.position = this._generatePosition(event);
4942 this.originalPageX = event.pageX;
4943 this.originalPageY = event.pageY;
4944
4945 //Adjust the mouse offset relative to the helper if "cursorAt" is supplied
4946 (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
4947
4948 //Set a containment if given in the options
4949 this._setContainment();
4950
4951 //Trigger event + callbacks
4952 if(this._trigger("start", event) === false) {
4953 this._clear();
4954 return false;
4955 }
4956
4957 //Recache the helper size
4958 this._cacheHelperProportions();
4959
4960 //Prepare the droppable offsets
4961 if ($.ui.ddmanager && !o.dropBehaviour) {
4962 $.ui.ddmanager.prepareOffsets(this, event);
4963 }
4964
4965
4966 this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position
4967
4968 //If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003)
4969 if ( $.ui.ddmanager ) {
4970 $.ui.ddmanager.dragStart(this, event);
4971 }
4972
4973 return true;
4974 },
4975
4976 _mouseDrag: function(event, noPropagation) {
4977 // reset any necessary cached properties (see #5009)
4978 if ( this.offsetParentCssPosition === "fixed" ) {
4979 this.offset.parent = this._getParentOffset();
4980 }
4981
4982 //Compute the helpers position
4983 this.position = this._generatePosition(event);
4984 this.positionAbs = this._convertPositionTo("absolute");
4985
4986 //Call plugins and callbacks and use the resulting position if something is returned
4987 if (!noPropagation) {
4988 var ui = this._uiHash();
4989 if(this._trigger("drag", event, ui) === false) {
4990 this._mouseUp({});
4991 return false;
4992 }
4993 this.position = ui.position;
4994 }
4995
4996 if(!this.options.axis || this.options.axis !== "y") {
4997 this.helper[0].style.left = this.position.left+"px";
4998 }
4999 if(!this.options.axis || this.options.axis !== "x") {
5000 this.helper[0].style.top = this.position.top+"px";
5001 }
5002 if($.ui.ddmanager) {
5003 $.ui.ddmanager.drag(this, event);
5004 }
5005
5006 return false;
5007 },
5008
5009 _mouseStop: function(event) {
5010
5011 //If we are using droppables, inform the manager about the drop
5012 var that = this,
5013 dropped = false;
5014 if ($.ui.ddmanager && !this.options.dropBehaviour) {
5015 dropped = $.ui.ddmanager.drop(this, event);
5016 }
5017
5018 //if a drop comes from outside (a sortable)
5019 if(this.dropped) {
5020 dropped = this.dropped;
5021 this.dropped = false;
5022 }
5023
5024 //if the original element is no longer in the DOM don't bother to continue (see #8269)
5025 if ( this.options.helper === "original" && !$.contains( this.element[ 0 ].ownerDocument, this.element[ 0 ] ) ) {
5026 return false;
5027 }
5028
5029 if((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
5030 $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
5031 if(that._trigger("stop", event) !== false) {
5032 that._clear();
5033 }
5034 });
5035 } else {
5036 if(this._trigger("stop", event) !== false) {
5037 this._clear();
5038 }
5039 }
5040
5041 return false;
5042 },
5043
5044 _mouseUp: function(event) {
5045 //Remove frame helpers
5046 $("div.ui-draggable-iframeFix").each(function() {
5047 this.parentNode.removeChild(this);
5048 });
5049
5050 //If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003)
5051 if( $.ui.ddmanager ) {
5052 $.ui.ddmanager.dragStop(this, event);
5053 }
5054
5055 return $.ui.mouse.prototype._mouseUp.call(this, event);
5056 },
5057
5058 cancel: function() {
5059
5060 if(this.helper.is(".ui-draggable-dragging")) {
5061 this._mouseUp({});
5062 } else {
5063 this._clear();
5064 }
5065
5066 return this;
5067
5068 },
5069
5070 _getHandle: function(event) {
5071 return this.options.handle ?
5072 !!$( event.target ).closest( this.element.find( this.options.handle ) ).length :
5073 true;
5074 },
5075
5076 _createHelper: function(event) {
5077
5078 var o = this.options,
5079 helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper === "clone" ? this.element.clone().removeAttr("id") : this.element);
5080
5081 if(!helper.parents("body").length) {
5082 helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo));
5083 }
5084
5085 if(helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) {
5086 helper.css("position", "absolute");
5087 }
5088
5089 return helper;
5090
5091 },
5092
5093 _adjustOffsetFromHelper: function(obj) {
5094 if (typeof obj === "string") {
5095 obj = obj.split(" ");
5096 }
5097 if ($.isArray(obj)) {
5098 obj = {left: +obj[0], top: +obj[1] || 0};
5099 }
5100 if ("left" in obj) {
5101 this.offset.click.left = obj.left + this.margins.left;
5102 }
5103 if ("right" in obj) {
5104 this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
5105 }
5106 if ("top" in obj) {
5107 this.offset.click.top = obj.top + this.margins.top;
5108 }
5109 if ("bottom" in obj) {
5110 this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
5111 }
5112 },
5113
5114 _getParentOffset: function() {
5115
5116 //Get the offsetParent and cache its position
5117 var po = this.offsetParent.offset();
5118
5119 // This is a special case where we need to modify a offset calculated on start, since the following happened:
5120 // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
5121 // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
5122 // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
5123 if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
5124 po.left += this.scrollParent.scrollLeft();
5125 po.top += this.scrollParent.scrollTop();
5126 }
5127
5128 //This needs to be actually done for all browsers, since pageX/pageY includes this information
5129 //Ugly IE fix
5130 if((this.offsetParent[0] === document.body) ||
5131 (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
5132 po = { top: 0, left: 0 };
5133 }
5134
5135 return {
5136 top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
5137 left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
5138 };
5139
5140 },
5141
5142 _getRelativeOffset: function() {
5143
5144 if(this.cssPosition === "relative") {
5145 var p = this.element.position();
5146 return {
5147 top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
5148 left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
5149 };
5150 } else {
5151 return { top: 0, left: 0 };
5152 }
5153
5154 },
5155
5156 _cacheMargins: function() {
5157 this.margins = {
5158 left: (parseInt(this.element.css("marginLeft"),10) || 0),
5159 top: (parseInt(this.element.css("marginTop"),10) || 0),
5160 right: (parseInt(this.element.css("marginRight"),10) || 0),
5161 bottom: (parseInt(this.element.css("marginBottom"),10) || 0)
5162 };
5163 },
5164
5165 _cacheHelperProportions: function() {
5166 this.helperProportions = {
5167 width: this.helper.outerWidth(),
5168 height: this.helper.outerHeight()
5169 };
5170 },
5171
5172 _setContainment: function() {
5173
5174 var over, c, ce,
5175 o = this.options;
5176
5177 if ( !o.containment ) {
5178 this.containment = null;
5179 return;
5180 }
5181
5182 if ( o.containment === "window" ) {
5183 this.containment = [
5184 $( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
5185 $( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top,
5186 $( window ).scrollLeft() + $( window ).width() - this.helperProportions.width - this.margins.left,
5187 $( window ).scrollTop() + ( $( window ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top
5188 ];
5189 return;
5190 }
5191
5192 if ( o.containment === "document") {
5193 this.containment = [
5194 0,
5195 0,
5196 $( document ).width() - this.helperProportions.width - this.margins.left,
5197 ( $( document ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top
5198 ];
5199 return;
5200 }
5201
5202 if ( o.containment.constructor === Array ) {
5203 this.containment = o.containment;
5204 return;
5205 }
5206
5207 if ( o.containment === "parent" ) {
5208 o.containment = this.helper[ 0 ].parentNode;
5209 }
5210
5211 c = $( o.containment );
5212 ce = c[ 0 ];
5213
5214 if( !ce ) {
5215 return;
5216 }
5217
5218 over = c.css( "overflow" ) !== "hidden";
5219
5220 this.containment = [
5221 ( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ),
5222 ( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingTop" ), 10 ) || 0 ) ,
5223 ( over ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) - ( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) - this.helperProportions.width - this.margins.left - this.margins.right,
5224 ( over ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) - ( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) - this.helperProportions.height - this.margins.top - this.margins.bottom
5225 ];
5226 this.relative_container = c;
5227 },
5228
5229 _convertPositionTo: function(d, pos) {
5230
5231 if(!pos) {
5232 pos = this.position;
5233 }
5234
5235 var mod = d === "absolute" ? 1 : -1,
5236 scroll = this.cssPosition === "absolute" && !( this.scrollParent[ 0 ] !== document && $.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ? this.offsetParent : this.scrollParent;
5237
5238 //Cache the scroll
5239 if (!this.offset.scroll) {
5240 this.offset.scroll = {top : scroll.scrollTop(), left : scroll.scrollLeft()};
5241 }
5242
5243 return {
5244 top: (
5245 pos.top + // The absolute mouse position
5246 this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
5247 this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border)
5248 ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : this.offset.scroll.top ) * mod )
5249 ),
5250 left: (
5251 pos.left + // The absolute mouse position
5252 this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
5253 this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border)
5254 ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : this.offset.scroll.left ) * mod )
5255 )
5256 };
5257
5258 },
5259
5260 _generatePosition: function(event) {
5261
5262 var containment, co, top, left,
5263 o = this.options,
5264 scroll = this.cssPosition === "absolute" && !( this.scrollParent[ 0 ] !== document && $.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ? this.offsetParent : this.scrollParent,
5265 pageX = event.pageX,
5266 pageY = event.pageY;
5267
5268 //Cache the scroll
5269 if (!this.offset.scroll) {
5270 this.offset.scroll = {top : scroll.scrollTop(), left : scroll.scrollLeft()};
5271 }
5272
5273 /*
5274 * - Position constraining -
5275 * Constrain the position to a mix of grid, containment.
5276 */
5277
5278 // If we are not dragging yet, we won't check for options
5279 if ( this.originalPosition ) {
5280 if ( this.containment ) {
5281 if ( this.relative_container ){
5282 co = this.relative_container.offset();
5283 containment = [
5284 this.containment[ 0 ] + co.left,
5285 this.containment[ 1 ] + co.top,
5286 this.containment[ 2 ] + co.left,
5287 this.containment[ 3 ] + co.top
5288 ];
5289 }
5290 else {
5291 containment = this.containment;
5292 }
5293
5294 if(event.pageX - this.offset.click.left < containment[0]) {
5295 pageX = containment[0] + this.offset.click.left;
5296 }
5297 if(event.pageY - this.offset.click.top < containment[1]) {
5298 pageY = containment[1] + this.offset.click.top;
5299 }
5300 if(event.pageX - this.offset.click.left > containment[2]) {
5301 pageX = containment[2] + this.offset.click.left;
5302 }
5303 if(event.pageY - this.offset.click.top > containment[3]) {
5304 pageY = containment[3] + this.offset.click.top;
5305 }
5306 }
5307
5308 if(o.grid) {
5309 //Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950)
5310 top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY;
5311 pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
5312
5313 left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX;
5314 pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
5315 }
5316
5317 }
5318
5319 return {
5320 top: (
5321 pageY - // The absolute mouse position
5322 this.offset.click.top - // Click offset (relative to the element)
5323 this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent
5324 this.offset.parent.top + // The offsetParent's offset without borders (offset + border)
5325 ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : this.offset.scroll.top )
5326 ),
5327 left: (
5328 pageX - // The absolute mouse position
5329 this.offset.click.left - // Click offset (relative to the element)
5330 this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent
5331 this.offset.parent.left + // The offsetParent's offset without borders (offset + border)
5332 ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : this.offset.scroll.left )
5333 )
5334 };
5335
5336 },
5337
5338 _clear: function() {
5339 this.helper.removeClass("ui-draggable-dragging");
5340 if(this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) {
5341 this.helper.remove();
5342 }
5343 this.helper = null;
5344 this.cancelHelperRemoval = false;
5345 },
5346
5347 // From now on bulk stuff - mainly helpers
5348
5349 _trigger: function(type, event, ui) {
5350 ui = ui || this._uiHash();
5351 $.ui.plugin.call(this, type, [event, ui]);
5352 //The absolute position has to be recalculated after plugins
5353 if(type === "drag") {
5354 this.positionAbs = this._convertPositionTo("absolute");
5355 }
5356 return $.Widget.prototype._trigger.call(this, type, event, ui);
5357 },
5358
5359 plugins: {},
5360
5361 _uiHash: function() {
5362 return {
5363 helper: this.helper,
5364 position: this.position,
5365 originalPosition: this.originalPosition,
5366 offset: this.positionAbs
5367 };
5368 }
5369
5370 });
5371
5372 $.ui.plugin.add("draggable", "connectToSortable", {
5373 start: function(event, ui) {
5374
5375 var inst = $(this).data("ui-draggable"), o = inst.options,
5376 uiSortable = $.extend({}, ui, { item: inst.element });
5377 inst.sortables = [];
5378 $(o.connectToSortable).each(function() {
5379 var sortable = $.data(this, "ui-sortable");
5380 if (sortable && !sortable.options.disabled) {
5381 inst.sortables.push({
5382 instance: sortable,
5383 shouldRevert: sortable.options.revert
5384 });
5385 sortable.refreshPositions(); // Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page).
5386 sortable._trigger("activate", event, uiSortable);
5387 }
5388 });
5389
5390 },
5391 stop: function(event, ui) {
5392
5393 //If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
5394 var inst = $(this).data("ui-draggable"),
5395 uiSortable = $.extend({}, ui, { item: inst.element });
5396
5397 $.each(inst.sortables, function() {
5398 if(this.instance.isOver) {
5399
5400 this.instance.isOver = 0;
5401
5402 inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
5403 this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)
5404
5405 //The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: "valid/invalid"
5406 if(this.shouldRevert) {
5407 this.instance.options.revert = this.shouldRevert;
5408 }
5409
5410 //Trigger the stop of the sortable
5411 this.instance._mouseStop(event);
5412
5413 this.instance.options.helper = this.instance.options._helper;
5414
5415 //If the helper has been the original item, restore properties in the sortable
5416 if(inst.options.helper === "original") {
5417 this.instance.currentItem.css({ top: "auto", left: "auto" });
5418 }
5419
5420 } else {
5421 this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
5422 this.instance._trigger("deactivate", event, uiSortable);
5423 }
5424
5425 });
5426
5427 },
5428 drag: function(event, ui) {
5429
5430 var inst = $(this).data("ui-draggable"), that = this;
5431
5432 $.each(inst.sortables, function() {
5433
5434 var innermostIntersecting = false,
5435 thisSortable = this;
5436
5437 //Copy over some variables to allow calling the sortable's native _intersectsWith
5438 this.instance.positionAbs = inst.positionAbs;
5439 this.instance.helperProportions = inst.helperProportions;
5440 this.instance.offset.click = inst.offset.click;
5441
5442 if(this.instance._intersectsWith(this.instance.containerCache)) {
5443 innermostIntersecting = true;
5444 $.each(inst.sortables, function () {
5445 this.instance.positionAbs = inst.positionAbs;
5446 this.instance.helperProportions = inst.helperProportions;
5447 this.instance.offset.click = inst.offset.click;
5448 if (this !== thisSortable &&
5449 this.instance._intersectsWith(this.instance.containerCache) &&
5450 $.contains(thisSortable.instance.element[0], this.instance.element[0])
5451 ) {
5452 innermostIntersecting = false;
5453 }
5454 return innermostIntersecting;
5455 });
5456 }
5457
5458
5459 if(innermostIntersecting) {
5460 //If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
5461 if(!this.instance.isOver) {
5462
5463 this.instance.isOver = 1;
5464 //Now we fake the start of dragging for the sortable instance,
5465 //by cloning the list group item, appending it to the sortable and using it as inst.currentItem
5466 //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
5467 this.instance.currentItem = $(that).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item", true);
5468 this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
5469 this.instance.options.helper = function() { return ui.helper[0]; };
5470
5471 event.target = this.instance.currentItem[0];
5472 this.instance._mouseCapture(event, true);
5473 this.instance._mouseStart(event, true, true);
5474
5475 //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
5476 this.instance.offset.click.top = inst.offset.click.top;
5477 this.instance.offset.click.left = inst.offset.click.left;
5478 this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
5479 this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;
5480
5481 inst._trigger("toSortable", event);
5482 inst.dropped = this.instance.element; //draggable revert needs that
5483 //hack so receive/update callbacks work (mostly)
5484 inst.currentItem = inst.element;
5485 this.instance.fromOutside = inst;
5486
5487 }
5488
5489 //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
5490 if(this.instance.currentItem) {
5491 this.instance._mouseDrag(event);
5492 }
5493
5494 } else {
5495
5496 //If it doesn't intersect with the sortable, and it intersected before,
5497 //we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
5498 if(this.instance.isOver) {
5499
5500 this.instance.isOver = 0;
5501 this.instance.cancelHelperRemoval = true;
5502
5503 //Prevent reverting on this forced stop
5504 this.instance.options.revert = false;
5505
5506 // The out event needs to be triggered independently
5507 this.instance._trigger("out", event, this.instance._uiHash(this.instance));
5508
5509 this.instance._mouseStop(event, true);
5510 this.instance.options.helper = this.instance.options._helper;
5511
5512 //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
5513 this.instance.currentItem.remove();
5514 if(this.instance.placeholder) {
5515 this.instance.placeholder.remove();
5516 }
5517
5518 inst._trigger("fromSortable", event);
5519 inst.dropped = false; //draggable revert needs that
5520 }
5521
5522 }
5523
5524 });
5525
5526 }
5527 });
5528
5529 $.ui.plugin.add("draggable", "cursor", {
5530 start: function() {
5531 var t = $("body"), o = $(this).data("ui-draggable").options;
5532 if (t.css("cursor")) {
5533 o._cursor = t.css("cursor");
5534 }
5535 t.css("cursor", o.cursor);
5536 },
5537 stop: function() {
5538 var o = $(this).data("ui-draggable").options;
5539 if (o._cursor) {
5540 $("body").css("cursor", o._cursor);
5541 }
5542 }
5543 });
5544
5545 $.ui.plugin.add("draggable", "opacity", {
5546 start: function(event, ui) {
5547 var t = $(ui.helper), o = $(this).data("ui-draggable").options;
5548 if(t.css("opacity")) {
5549 o._opacity = t.css("opacity");
5550 }
5551 t.css("opacity", o.opacity);
5552 },
5553 stop: function(event, ui) {
5554 var o = $(this).data("ui-draggable").options;
5555 if(o._opacity) {
5556 $(ui.helper).css("opacity", o._opacity);
5557 }
5558 }
5559 });
5560
5561 $.ui.plugin.add("draggable", "scroll", {
5562 start: function() {
5563 var i = $(this).data("ui-draggable");
5564 if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") {
5565 i.overflowOffset = i.scrollParent.offset();
5566 }
5567 },
5568 drag: function( event ) {
5569
5570 var i = $(this).data("ui-draggable"), o = i.options, scrolled = false;
5571
5572 if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") {
5573
5574 if(!o.axis || o.axis !== "x") {
5575 if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
5576 i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
5577 } else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity) {
5578 i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;
5579 }
5580 }
5581
5582 if(!o.axis || o.axis !== "y") {
5583 if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
5584 i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
5585 } else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity) {
5586 i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;
5587 }
5588 }
5589
5590 } else {
5591
5592 if(!o.axis || o.axis !== "x") {
5593 if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
5594 scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
5595 } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
5596 scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
5597 }
5598 }
5599
5600 if(!o.axis || o.axis !== "y") {
5601 if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
5602 scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
5603 } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
5604 scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
5605 }
5606 }
5607
5608 }
5609
5610 if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
5611 $.ui.ddmanager.prepareOffsets(i, event);
5612 }
5613
5614 }
5615 });
5616
5617 $.ui.plugin.add("draggable", "snap", {
5618 start: function() {
5619
5620 var i = $(this).data("ui-draggable"),
5621 o = i.options;
5622
5623 i.snapElements = [];
5624
5625 $(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() {
5626 var $t = $(this),
5627 $o = $t.offset();
5628 if(this !== i.element[0]) {
5629 i.snapElements.push({
5630 item: this,
5631 width: $t.outerWidth(), height: $t.outerHeight(),
5632 top: $o.top, left: $o.left
5633 });
5634 }
5635 });
5636
5637 },
5638 drag: function(event, ui) {
5639
5640 var ts, bs, ls, rs, l, r, t, b, i, first,
5641 inst = $(this).data("ui-draggable"),
5642 o = inst.options,
5643 d = o.snapTolerance,
5644 x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
5645 y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;
5646
5647 for (i = inst.snapElements.length - 1; i >= 0; i--){
5648
5649 l = inst.snapElements[i].left;
5650 r = l + inst.snapElements[i].width;
5651 t = inst.snapElements[i].top;
5652 b = t + inst.snapElements[i].height;
5653
5654 if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains( inst.snapElements[ i ].item.ownerDocument, inst.snapElements[ i ].item ) ) {
5655 if(inst.snapElements[i].snapping) {
5656 (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
5657 }
5658 inst.snapElements[i].snapping = false;
5659 continue;
5660 }
5661
5662 if(o.snapMode !== "inner") {
5663 ts = Math.abs(t - y2) <= d;
5664 bs = Math.abs(b - y1) <= d;
5665 ls = Math.abs(l - x2) <= d;
5666 rs = Math.abs(r - x1) <= d;
5667 if(ts) {
5668 ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
5669 }
5670 if(bs) {
5671 ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
5672 }
5673 if(ls) {
5674 ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
5675 }
5676 if(rs) {
5677 ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left;
5678 }
5679 }
5680
5681 first = (ts || bs || ls || rs);
5682
5683 if(o.snapMode !== "outer") {
5684 ts = Math.abs(t - y1) <= d;
5685 bs = Math.abs(b - y2) <= d;
5686 ls = Math.abs(l - x1) <= d;
5687 rs = Math.abs(r - x2) <= d;
5688 if(ts) {
5689 ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top;
5690 }
5691 if(bs) {
5692 ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
5693 }
5694 if(ls) {
5695 ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left;
5696 }
5697 if(rs) {
5698 ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left;
5699 }
5700 }
5701
5702 if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) {
5703 (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
5704 }
5705 inst.snapElements[i].snapping = (ts || bs || ls || rs || first);
5706
5707 }
5708
5709 }
5710 });
5711
5712 $.ui.plugin.add("draggable", "stack", {
5713 start: function() {
5714 var min,
5715 o = this.data("ui-draggable").options,
5716 group = $.makeArray($(o.stack)).sort(function(a,b) {
5717 return (parseInt($(a).css("zIndex"),10) || 0) - (parseInt($(b).css("zIndex"),10) || 0);
5718 });
5719
5720 if (!group.length) { return; }
5721
5722 min = parseInt($(group[0]).css("zIndex"), 10) || 0;
5723 $(group).each(function(i) {
5724 $(this).css("zIndex", min + i);
5725 });
5726 this.css("zIndex", (min + group.length));
5727 }
5728 });
5729
5730 $.ui.plugin.add("draggable", "zIndex", {
5731 start: function(event, ui) {
5732 var t = $(ui.helper), o = $(this).data("ui-draggable").options;
5733 if(t.css("zIndex")) {
5734 o._zIndex = t.css("zIndex");
5735 }
5736 t.css("zIndex", o.zIndex);
5737 },
5738 stop: function(event, ui) {
5739 var o = $(this).data("ui-draggable").options;
5740 if(o._zIndex) {
5741 $(ui.helper).css("zIndex", o._zIndex);
5742 }
5743 }
5744 });
5745
5746 })(jQuery);
5747 (function( $, undefined ) {
5748
5749 function isOverAxis( x, reference, size ) {
5750 return ( x > reference ) && ( x < ( reference + size ) );
5751 }
5752
5753 $.widget("ui.droppable", {
5754 version: "1.10.3",
5755 widgetEventPrefix: "drop",
5756 options: {
5757 accept: "*",
5758 activeClass: false,
5759 addClasses: true,
5760 greedy: false,
5761 hoverClass: false,
5762 scope: "default",
5763 tolerance: "intersect",
5764
5765 // callbacks
5766 activate: null,
5767 deactivate: null,
5768 drop: null,
5769 out: null,
5770 over: null
5771 },
5772 _create: function() {
5773
5774 var o = this.options,
5775 accept = o.accept;
5776
5777 this.isover = false;
5778 this.isout = true;
5779
5780 this.accept = $.isFunction(accept) ? accept : function(d) {
5781 return d.is(accept);
5782 };
5783
5784 //Store the droppable's proportions
5785 this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight };
5786
5787 // Add the reference and positions to the manager
5788 $.ui.ddmanager.droppables[o.scope] = $.ui.ddmanager.droppables[o.scope] || [];
5789 $.ui.ddmanager.droppables[o.scope].push(this);
5790
5791 (o.addClasses && this.element.addClass("ui-droppable"));
5792
5793 },
5794
5795 _destroy: function() {
5796 var i = 0,
5797 drop = $.ui.ddmanager.droppables[this.options.scope];
5798
5799 for ( ; i < drop.length; i++ ) {
5800 if ( drop[i] === this ) {
5801 drop.splice(i, 1);
5802 }
5803 }
5804
5805 this.element.removeClass("ui-droppable ui-droppable-disabled");
5806 },
5807
5808 _setOption: function(key, value) {
5809
5810 if(key === "accept") {
5811 this.accept = $.isFunction(value) ? value : function(d) {
5812 return d.is(value);
5813 };
5814 }
5815 $.Widget.prototype._setOption.apply(this, arguments);
5816 },
5817
5818 _activate: function(event) {
5819 var draggable = $.ui.ddmanager.current;
5820 if(this.options.activeClass) {
5821 this.element.addClass(this.options.activeClass);
5822 }
5823 if(draggable){
5824 this._trigger("activate", event, this.ui(draggable));
5825 }
5826 },
5827
5828 _deactivate: function(event) {
5829 var draggable = $.ui.ddmanager.current;
5830 if(this.options.activeClass) {
5831 this.element.removeClass(this.options.activeClass);
5832 }
5833 if(draggable){
5834 this._trigger("deactivate", event, this.ui(draggable));
5835 }
5836 },
5837
5838 _over: function(event) {
5839
5840 var draggable = $.ui.ddmanager.current;
5841
5842 // Bail if draggable and droppable are same element
5843 if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) {
5844 return;
5845 }
5846
5847 if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
5848 if(this.options.hoverClass) {
5849 this.element.addClass(this.options.hoverClass);
5850 }
5851 this._trigger("over", event, this.ui(draggable));
5852 }
5853
5854 },
5855
5856 _out: function(event) {
5857
5858 var draggable = $.ui.ddmanager.current;
5859
5860 // Bail if draggable and droppable are same element
5861 if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) {
5862 return;
5863 }
5864
5865 if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
5866 if(this.options.hoverClass) {
5867 this.element.removeClass(this.options.hoverClass);
5868 }
5869 this._trigger("out", event, this.ui(draggable));
5870 }
5871
5872 },
5873
5874 _drop: function(event,custom) {
5875
5876 var draggable = custom || $.ui.ddmanager.current,
5877 childrenIntersection = false;
5878
5879 // Bail if draggable and droppable are same element
5880 if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) {
5881 return false;
5882 }
5883
5884 this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function() {
5885 var inst = $.data(this, "ui-droppable");
5886 if(
5887 inst.options.greedy &&
5888 !inst.options.disabled &&
5889 inst.options.scope === draggable.options.scope &&
5890 inst.accept.call(inst.element[0], (draggable.currentItem || draggable.element)) &&
5891 $.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance)
5892 ) { childrenIntersection = true; return false; }
5893 });
5894 if(childrenIntersection) {
5895 return false;
5896 }
5897
5898 if(this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
5899 if(this.options.activeClass) {
5900 this.element.removeClass(this.options.activeClass);
5901 }
5902 if(this.options.hoverClass) {
5903 this.element.removeClass(this.options.hoverClass);
5904 }
5905 this._trigger("drop", event, this.ui(draggable));
5906 return this.element;
5907 }
5908
5909 return false;
5910
5911 },
5912
5913 ui: function(c) {
5914 return {
5915 draggable: (c.currentItem || c.element),
5916 helper: c.helper,
5917 position: c.position,
5918 offset: c.positionAbs
5919 };
5920 }
5921
5922 });
5923
5924 $.ui.intersect = function(draggable, droppable, toleranceMode) {
5925
5926 if (!droppable.offset) {
5927 return false;
5928 }
5929
5930 var draggableLeft, draggableTop,
5931 x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width,
5932 y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height,
5933 l = droppable.offset.left, r = l + droppable.proportions.width,
5934 t = droppable.offset.top, b = t + droppable.proportions.height;
5935
5936 switch (toleranceMode) {
5937 case "fit":
5938 return (l <= x1 && x2 <= r && t <= y1 && y2 <= b);
5939 case "intersect":
5940 return (l < x1 + (draggable.helperProportions.width / 2) && // Right Half
5941 x2 - (draggable.helperProportions.width / 2) < r && // Left Half
5942 t < y1 + (draggable.helperProportions.height / 2) && // Bottom Half
5943 y2 - (draggable.helperProportions.height / 2) < b ); // Top Half
5944 case "pointer":
5945 draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left);
5946 draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top);
5947 return isOverAxis( draggableTop, t, droppable.proportions.height ) && isOverAxis( draggableLeft, l, droppable.proportions.width );
5948 case "touch":
5949 return (
5950 (y1 >= t && y1 <= b) || // Top edge touching
5951 (y2 >= t && y2 <= b) || // Bottom edge touching
5952 (y1 < t && y2 > b) // Surrounded vertically
5953 ) && (
5954 (x1 >= l && x1 <= r) || // Left edge touching
5955 (x2 >= l && x2 <= r) || // Right edge touching
5956 (x1 < l && x2 > r) // Surrounded horizontally
5957 );
5958 default:
5959 return false;
5960 }
5961
5962 };
5963
5964 /*
5965 This manager tracks offsets of draggables and droppables
5966 */
5967 $.ui.ddmanager = {
5968 current: null,
5969 droppables: { "default": [] },
5970 prepareOffsets: function(t, event) {
5971
5972 var i, j,
5973 m = $.ui.ddmanager.droppables[t.options.scope] || [],
5974 type = event ? event.type : null, // workaround for #2317
5975 list = (t.currentItem || t.element).find(":data(ui-droppable)").addBack();
5976
5977 droppablesLoop: for (i = 0; i < m.length; i++) {
5978
5979 //No disabled and non-accepted
5980 if(m[i].options.disabled || (t && !m[i].accept.call(m[i].element[0],(t.currentItem || t.element)))) {
5981 continue;
5982 }
5983
5984 // Filter out elements in the current dragged item
5985 for (j=0; j < list.length; j++) {
5986 if(list[j] === m[i].element[0]) {
5987 m[i].proportions.height = 0;
5988 continue droppablesLoop;
5989 }
5990 }
5991
5992 m[i].visible = m[i].element.css("display") !== "none";
5993 if(!m[i].visible) {
5994 continue;
5995 }
5996
5997 //Activate the droppable if used directly from draggables
5998 if(type === "mousedown") {
5999 m[i]._activate.call(m[i], event);
6000 }
6001
6002 m[i].offset = m[i].element.offset();
6003 m[i].proportions = { width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight };
6004
6005 }
6006
6007 },
6008 drop: function(draggable, event) {
6009
6010 var dropped = false;
6011 // Create a copy of the droppables in case the list changes during the drop (#9116)
6012 $.each(($.ui.ddmanager.droppables[draggable.options.scope] || []).slice(), function() {
6013
6014 if(!this.options) {
6015 return;
6016 }
6017 if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance)) {
6018 dropped = this._drop.call(this, event) || dropped;
6019 }
6020
6021 if (!this.options.disabled && this.visible && this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
6022 this.isout = true;
6023 this.isover = false;
6024 this._deactivate.call(this, event);
6025 }
6026
6027 });
6028 return dropped;
6029
6030 },
6031 dragStart: function( draggable, event ) {
6032 //Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003)
6033 draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() {
6034 if( !draggable.options.refreshPositions ) {
6035 $.ui.ddmanager.prepareOffsets( draggable, event );
6036 }
6037 });
6038 },
6039 drag: function(draggable, event) {
6040
6041 //If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse.
6042 if(draggable.options.refreshPositions) {
6043 $.ui.ddmanager.prepareOffsets(draggable, event);
6044 }
6045
6046 //Run through all droppables and check their positions based on specific tolerance options
6047 $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() {
6048
6049 if(this.options.disabled || this.greedyChild || !this.visible) {
6050 return;
6051 }
6052
6053 var parentInstance, scope, parent,
6054 intersects = $.ui.intersect(draggable, this, this.options.tolerance),
6055 c = !intersects && this.isover ? "isout" : (intersects && !this.isover ? "isover" : null);
6056 if(!c) {
6057 return;
6058 }
6059
6060 if (this.options.greedy) {
6061 // find droppable parents with same scope
6062 scope = this.options.scope;
6063 parent = this.element.parents(":data(ui-droppable)").filter(function () {
6064 return $.data(this, "ui-droppable").options.scope === scope;
6065 });
6066
6067 if (parent.length) {
6068 parentInstance = $.data(parent[0], "ui-droppable");
6069 parentInstance.greedyChild = (c === "isover");
6070 }
6071 }
6072
6073 // we just moved into a greedy child
6074 if (parentInstance && c === "isover") {
6075 parentInstance.isover = false;
6076 parentInstance.isout = true;
6077 parentInstance._out.call(parentInstance, event);
6078 }
6079
6080 this[c] = true;
6081 this[c === "isout" ? "isover" : "isout"] = false;
6082 this[c === "isover" ? "_over" : "_out"].call(this, event);
6083
6084 // we just moved out of a greedy child
6085 if (parentInstance && c === "isout") {
6086 parentInstance.isout = false;
6087 parentInstance.isover = true;
6088 parentInstance._over.call(parentInstance, event);
6089 }
6090 });
6091
6092 },
6093 dragStop: function( draggable, event ) {
6094 draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" );
6095 //Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003)
6096 if( !draggable.options.refreshPositions ) {
6097 $.ui.ddmanager.prepareOffsets( draggable, event );
6098 }
6099 }
6100 };
6101
6102 })(jQuery);
6103 (function( $, undefined ) {
6104
6105 function num(v) {
6106 return parseInt(v, 10) || 0;
6107 }
6108
6109 function isNumber(value) {
6110 return !isNaN(parseInt(value, 10));
6111 }
6112
6113 $.widget("ui.resizable", $.ui.mouse, {
6114 version: "1.10.3",
6115 widgetEventPrefix: "resize",
6116 options: {
6117 alsoResize: false,
6118 animate: false,
6119 animateDuration: "slow",
6120 animateEasing: "swing",
6121 aspectRatio: false,
6122 autoHide: false,
6123 containment: false,
6124 ghost: false,
6125 grid: false,
6126 handles: "e,s,se",
6127 helper: false,
6128 maxHeight: null,
6129 maxWidth: null,
6130 minHeight: 10,
6131 minWidth: 10,
6132 // See #7960
6133 zIndex: 90,
6134
6135 // callbacks
6136 resize: null,
6137 start: null,
6138 stop: null
6139 },
6140 _create: function() {
6141
6142 var n, i, handle, axis, hname,
6143 that = this,
6144 o = this.options;
6145 this.element.addClass("ui-resizable");
6146
6147 $.extend(this, {
6148 _aspectRatio: !!(o.aspectRatio),
6149 aspectRatio: o.aspectRatio,
6150 originalElement: this.element,
6151 _proportionallyResizeElements: [],
6152 _helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null
6153 });
6154
6155 //Wrap the element if it cannot hold child nodes
6156 if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) {
6157
6158 //Create a wrapper element and set the wrapper to the new current internal element
6159 this.element.wrap(
6160 $("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({
6161 position: this.element.css("position"),
6162 width: this.element.outerWidth(),
6163 height: this.element.outerHeight(),
6164 top: this.element.css("top"),
6165 left: this.element.css("left")
6166 })
6167 );
6168
6169 //Overwrite the original this.element
6170 this.element = this.element.parent().data(
6171 "ui-resizable", this.element.data("ui-resizable")
6172 );
6173
6174 this.elementIsWrapper = true;
6175
6176 //Move margins to the wrapper
6177 this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") });
6178 this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0});
6179
6180 //Prevent Safari textarea resize
6181 this.originalResizeStyle = this.originalElement.css("resize");
6182 this.originalElement.css("resize", "none");
6183
6184 //Push the actual element to our proportionallyResize internal array
6185 this._proportionallyResizeElements.push(this.originalElement.css({ position: "static", zoom: 1, display: "block" }));
6186
6187 // avoid IE jump (hard set the margin)
6188 this.originalElement.css({ margin: this.originalElement.css("margin") });
6189
6190 // fix handlers offset
6191 this._proportionallyResize();
6192
6193 }
6194
6195 this.handles = o.handles || (!$(".ui-resizable-handle", this.element).length ? "e,s,se" : { n: ".ui-resizable-n", e: ".ui-resizable-e", s: ".ui-resizable-s", w: ".ui-resizable-w", se: ".ui-resizable-se", sw: ".ui-resizable-sw", ne: ".ui-resizable-ne", nw: ".ui-resizable-nw" });
6196 if(this.handles.constructor === String) {
6197
6198 if ( this.handles === "all") {
6199 this.handles = "n,e,s,w,se,sw,ne,nw";
6200 }
6201
6202 n = this.handles.split(",");
6203 this.handles = {};
6204
6205 for(i = 0; i < n.length; i++) {
6206
6207 handle = $.trim(n[i]);
6208 hname = "ui-resizable-"+handle;
6209 axis = $("<div class='ui-resizable-handle " + hname + "'></div>");
6210
6211 // Apply zIndex to all handles - see #7960
6212 axis.css({ zIndex: o.zIndex });
6213
6214 //TODO : What's going on here?
6215 if ("se" === handle) {
6216 axis.addClass("ui-icon ui-icon-gripsmall-diagonal-se");
6217 }
6218
6219 //Insert into internal handles object and append to element
6220 this.handles[handle] = ".ui-resizable-"+handle;
6221 this.element.append(axis);
6222 }
6223
6224 }
6225
6226 this._renderAxis = function(target) {
6227
6228 var i, axis, padPos, padWrapper;
6229
6230 target = target || this.element;
6231
6232 for(i in this.handles) {
6233
6234 if(this.handles[i].constructor === String) {
6235 this.handles[i] = $(this.handles[i], this.element).show();
6236 }
6237
6238 //Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls)
6239 if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) {
6240
6241 axis = $(this.handles[i], this.element);
6242
6243 //Checking the correct pad and border
6244 padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth();
6245
6246 //The padding type i have to apply...
6247 padPos = [ "padding",
6248 /ne|nw|n/.test(i) ? "Top" :
6249 /se|sw|s/.test(i) ? "Bottom" :
6250 /^e$/.test(i) ? "Right" : "Left" ].join("");
6251
6252 target.css(padPos, padWrapper);
6253
6254 this._proportionallyResize();
6255
6256 }
6257
6258 //TODO: What's that good for? There's not anything to be executed left
6259 if(!$(this.handles[i]).length) {
6260 continue;
6261 }
6262 }
6263 };
6264
6265 //TODO: make renderAxis a prototype function
6266 this._renderAxis(this.element);
6267
6268 this._handles = $(".ui-resizable-handle", this.element)
6269 .disableSelection();
6270
6271 //Matching axis name
6272 this._handles.mouseover(function() {
6273 if (!that.resizing) {
6274 if (this.className) {
6275 axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
6276 }
6277 //Axis, default = se
6278 that.axis = axis && axis[1] ? axis[1] : "se";
6279 }
6280 });
6281
6282 //If we want to auto hide the elements
6283 if (o.autoHide) {
6284 this._handles.hide();
6285 $(this.element)
6286 .addClass("ui-resizable-autohide")
6287 .mouseenter(function() {
6288 if (o.disabled) {
6289 return;
6290 }
6291 $(this).removeClass("ui-resizable-autohide");
6292 that._handles.show();
6293 })
6294 .mouseleave(function(){
6295 if (o.disabled) {
6296 return;
6297 }
6298 if (!that.resizing) {
6299 $(this).addClass("ui-resizable-autohide");
6300 that._handles.hide();
6301 }
6302 });
6303 }
6304
6305 //Initialize the mouse interaction
6306 this._mouseInit();
6307
6308 },
6309
6310 _destroy: function() {
6311
6312 this._mouseDestroy();
6313
6314 var wrapper,
6315 _destroy = function(exp) {
6316 $(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing")
6317 .removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove();
6318 };
6319
6320 //TODO: Unwrap at same DOM position
6321 if (this.elementIsWrapper) {
6322 _destroy(this.element);
6323 wrapper = this.element;
6324 this.originalElement.css({
6325 position: wrapper.css("position"),
6326 width: wrapper.outerWidth(),
6327 height: wrapper.outerHeight(),
6328 top: wrapper.css("top"),
6329 left: wrapper.css("left")
6330 }).insertAfter( wrapper );
6331 wrapper.remove();
6332 }
6333
6334 this.originalElement.css("resize", this.originalResizeStyle);
6335 _destroy(this.originalElement);
6336
6337 return this;
6338 },
6339
6340 _mouseCapture: function(event) {
6341 var i, handle,
6342 capture = false;
6343
6344 for (i in this.handles) {
6345 handle = $(this.handles[i])[0];
6346 if (handle === event.target || $.contains(handle, event.target)) {
6347 capture = true;
6348 }
6349 }
6350
6351 return !this.options.disabled && capture;
6352 },
6353
6354 _mouseStart: function(event) {
6355
6356 var curleft, curtop, cursor,
6357 o = this.options,
6358 iniPos = this.element.position(),
6359 el = this.element;
6360
6361 this.resizing = true;
6362
6363 // bugfix for http://dev.jquery.com/ticket/1749
6364 if ( (/absolute/).test( el.css("position") ) ) {
6365 el.css({ position: "absolute", top: el.css("top"), left: el.css("left") });
6366 } else if (el.is(".ui-draggable")) {
6367 el.css({ position: "absolute", top: iniPos.top, left: iniPos.left });
6368 }
6369
6370 this._renderProxy();
6371
6372 curleft = num(this.helper.css("left"));
6373 curtop = num(this.helper.css("top"));
6374
6375 if (o.containment) {
6376 curleft += $(o.containment).scrollLeft() || 0;
6377 curtop += $(o.containment).scrollTop() || 0;
6378 }
6379
6380 //Store needed variables
6381 this.offset = this.helper.offset();
6382 this.position = { left: curleft, top: curtop };
6383 this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
6384 this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
6385 this.originalPosition = { left: curleft, top: curtop };
6386 this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() };
6387 this.originalMousePosition = { left: event.pageX, top: event.pageY };
6388
6389 //Aspect Ratio
6390 this.aspectRatio = (typeof o.aspectRatio === "number") ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1);
6391
6392 cursor = $(".ui-resizable-" + this.axis).css("cursor");
6393 $("body").css("cursor", cursor === "auto" ? this.axis + "-resize" : cursor);
6394
6395 el.addClass("ui-resizable-resizing");
6396 this._propagate("start", event);
6397 return true;
6398 },
6399
6400 _mouseDrag: function(event) {
6401
6402 //Increase performance, avoid regex
6403 var data,
6404 el = this.helper, props = {},
6405 smp = this.originalMousePosition,
6406 a = this.axis,
6407 prevTop = this.position.top,
6408 prevLeft = this.position.left,
6409 prevWidth = this.size.width,
6410 prevHeight = this.size.height,
6411 dx = (event.pageX-smp.left)||0,
6412 dy = (event.pageY-smp.top)||0,
6413 trigger = this._change[a];
6414
6415 if (!trigger) {
6416 return false;
6417 }
6418
6419 // Calculate the attrs that will be change
6420 data = trigger.apply(this, [event, dx, dy]);
6421
6422 // Put this in the mouseDrag handler since the user can start pressing shift while resizing
6423 this._updateVirtualBoundaries(event.shiftKey);
6424 if (this._aspectRatio || event.shiftKey) {
6425 data = this._updateRatio(data, event);
6426 }
6427
6428 data = this._respectSize(data, event);
6429
6430 this._updateCache(data);
6431
6432 // plugins callbacks need to be called first
6433 this._propagate("resize", event);
6434
6435 if (this.position.top !== prevTop) {
6436 props.top = this.position.top + "px";
6437 }
6438 if (this.position.left !== prevLeft) {
6439 props.left = this.position.left + "px";
6440 }
6441 if (this.size.width !== prevWidth) {
6442 props.width = this.size.width + "px";
6443 }
6444 if (this.size.height !== prevHeight) {
6445 props.height = this.size.height + "px";
6446 }
6447 el.css(props);
6448
6449 if (!this._helper && this._proportionallyResizeElements.length) {
6450 this._proportionallyResize();
6451 }
6452
6453 // Call the user callback if the element was resized
6454 if ( ! $.isEmptyObject(props) ) {
6455 this._trigger("resize", event, this.ui());
6456 }
6457
6458 return false;
6459 },
6460
6461 _mouseStop: function(event) {
6462
6463 this.resizing = false;
6464 var pr, ista, soffseth, soffsetw, s, left, top,
6465 o = this.options, that = this;
6466
6467 if(this._helper) {
6468
6469 pr = this._proportionallyResizeElements;
6470 ista = pr.length && (/textarea/i).test(pr[0].nodeName);
6471 soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height;
6472 soffsetw = ista ? 0 : that.sizeDiff.width;
6473
6474 s = { width: (that.helper.width() - soffsetw), height: (that.helper.height() - soffseth) };
6475 left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null;
6476 top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null;
6477
6478 if (!o.animate) {
6479 this.element.css($.extend(s, { top: top, left: left }));
6480 }
6481
6482 that.helper.height(that.size.height);
6483 that.helper.width(that.size.width);
6484
6485 if (this._helper && !o.animate) {
6486 this._proportionallyResize();
6487 }
6488 }
6489
6490 $("body").css("cursor", "auto");
6491
6492 this.element.removeClass("ui-resizable-resizing");
6493
6494 this._propagate("stop", event);
6495
6496 if (this._helper) {
6497 this.helper.remove();
6498 }
6499
6500 return false;
6501
6502 },
6503
6504 _updateVirtualBoundaries: function(forceAspectRatio) {
6505 var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b,
6506 o = this.options;
6507
6508 b = {
6509 minWidth: isNumber(o.minWidth) ? o.minWidth : 0,
6510 maxWidth: isNumber(o.maxWidth) ? o.maxWidth : Infinity,
6511 minHeight: isNumber(o.minHeight) ? o.minHeight : 0,
6512 maxHeight: isNumber(o.maxHeight) ? o.maxHeight : Infinity
6513 };
6514
6515 if(this._aspectRatio || forceAspectRatio) {
6516 // We want to create an enclosing box whose aspect ration is the requested one
6517 // First, compute the "projected" size for each dimension based on the aspect ratio and other dimension
6518 pMinWidth = b.minHeight * this.aspectRatio;
6519 pMinHeight = b.minWidth / this.aspectRatio;
6520 pMaxWidth = b.maxHeight * this.aspectRatio;
6521 pMaxHeight = b.maxWidth / this.aspectRatio;
6522
6523 if(pMinWidth > b.minWidth) {
6524 b.minWidth = pMinWidth;
6525 }
6526 if(pMinHeight > b.minHeight) {
6527 b.minHeight = pMinHeight;
6528 }
6529 if(pMaxWidth < b.maxWidth) {
6530 b.maxWidth = pMaxWidth;
6531 }
6532 if(pMaxHeight < b.maxHeight) {
6533 b.maxHeight = pMaxHeight;
6534 }
6535 }
6536 this._vBoundaries = b;
6537 },
6538
6539 _updateCache: function(data) {
6540 this.offset = this.helper.offset();
6541 if (isNumber(data.left)) {
6542 this.position.left = data.left;
6543 }
6544 if (isNumber(data.top)) {
6545 this.position.top = data.top;
6546 }
6547 if (isNumber(data.height)) {
6548 this.size.height = data.height;
6549 }
6550 if (isNumber(data.width)) {
6551 this.size.width = data.width;
6552 }
6553 },
6554
6555 _updateRatio: function( data ) {
6556
6557 var cpos = this.position,
6558 csize = this.size,
6559 a = this.axis;
6560
6561 if (isNumber(data.height)) {
6562 data.width = (data.height * this.aspectRatio);
6563 } else if (isNumber(data.width)) {
6564 data.height = (data.width / this.aspectRatio);
6565 }
6566
6567 if (a === "sw") {
6568 data.left = cpos.left + (csize.width - data.width);
6569 data.top = null;
6570 }
6571 if (a === "nw") {
6572 data.top = cpos.top + (csize.height - data.height);
6573 data.left = cpos.left + (csize.width - data.width);
6574 }
6575
6576 return data;
6577 },
6578
6579 _respectSize: function( data ) {
6580
6581 var o = this._vBoundaries,
6582 a = this.axis,
6583 ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height),
6584 isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height),
6585 dw = this.originalPosition.left + this.originalSize.width,
6586 dh = this.position.top + this.size.height,
6587 cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a);
6588 if (isminw) {
6589 data.width = o.minWidth;
6590 }
6591 if (isminh) {
6592 data.height = o.minHeight;
6593 }
6594 if (ismaxw) {
6595 data.width = o.maxWidth;
6596 }
6597 if (ismaxh) {
6598 data.height = o.maxHeight;
6599 }
6600
6601 if (isminw && cw) {
6602 data.left = dw - o.minWidth;
6603 }
6604 if (ismaxw && cw) {
6605 data.left = dw - o.maxWidth;
6606 }
6607 if (isminh && ch) {
6608 data.top = dh - o.minHeight;
6609 }
6610 if (ismaxh && ch) {
6611 data.top = dh - o.maxHeight;
6612 }
6613
6614 // fixing jump error on top/left - bug #2330
6615 if (!data.width && !data.height && !data.left && data.top) {
6616 data.top = null;
6617 } else if (!data.width && !data.height && !data.top && data.left) {
6618 data.left = null;
6619 }
6620
6621 return data;
6622 },
6623
6624 _proportionallyResize: function() {
6625
6626 if (!this._proportionallyResizeElements.length) {
6627 return;
6628 }
6629
6630 var i, j, borders, paddings, prel,
6631 element = this.helper || this.element;
6632
6633 for ( i=0; i < this._proportionallyResizeElements.length; i++) {
6634
6635 prel = this._proportionallyResizeElements[i];
6636
6637 if (!this.borderDif) {
6638 this.borderDif = [];
6639 borders = [prel.css("borderTopWidth"), prel.css("borderRightWidth"), prel.css("borderBottomWidth"), prel.css("borderLeftWidth")];
6640 paddings = [prel.css("paddingTop"), prel.css("paddingRight"), prel.css("paddingBottom"), prel.css("paddingLeft")];
6641
6642 for ( j = 0; j < borders.length; j++ ) {
6643 this.borderDif[ j ] = ( parseInt( borders[ j ], 10 ) || 0 ) + ( parseInt( paddings[ j ], 10 ) || 0 );
6644 }
6645 }
6646
6647 prel.css({
6648 height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0,
6649 width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0
6650 });
6651
6652 }
6653
6654 },
6655
6656 _renderProxy: function() {
6657
6658 var el = this.element, o = this.options;
6659 this.elementOffset = el.offset();
6660
6661 if(this._helper) {
6662
6663 this.helper = this.helper || $("<div style='overflow:hidden;'></div>");
6664
6665 this.helper.addClass(this._helper).css({
6666 width: this.element.outerWidth() - 1,
6667 height: this.element.outerHeight() - 1,
6668 position: "absolute",
6669 left: this.elementOffset.left +"px",
6670 top: this.elementOffset.top +"px",
6671 zIndex: ++o.zIndex //TODO: Don't modify option
6672 });
6673
6674 this.helper
6675 .appendTo("body")
6676 .disableSelection();
6677
6678 } else {
6679 this.helper = this.element;
6680 }
6681
6682 },
6683
6684 _change: {
6685 e: function(event, dx) {
6686 return { width: this.originalSize.width + dx };
6687 },
6688 w: function(event, dx) {
6689 var cs = this.originalSize, sp = this.originalPosition;
6690 return { left: sp.left + dx, width: cs.width - dx };
6691 },
6692 n: function(event, dx, dy) {
6693 var cs = this.originalSize, sp = this.originalPosition;
6694 return { top: sp.top + dy, height: cs.height - dy };
6695 },
6696 s: function(event, dx, dy) {
6697 return { height: this.originalSize.height + dy };
6698 },
6699 se: function(event, dx, dy) {
6700 return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
6701 },
6702 sw: function(event, dx, dy) {
6703 return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
6704 },
6705 ne: function(event, dx, dy) {
6706 return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
6707 },
6708 nw: function(event, dx, dy) {
6709 return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
6710 }
6711 },
6712
6713 _propagate: function(n, event) {
6714 $.ui.plugin.call(this, n, [event, this.ui()]);
6715 (n !== "resize" && this._trigger(n, event, this.ui()));
6716 },
6717
6718 plugins: {},
6719
6720 ui: function() {
6721 return {
6722 originalElement: this.originalElement,
6723 element: this.element,
6724 helper: this.helper,
6725 position: this.position,
6726 size: this.size,
6727 originalSize: this.originalSize,
6728 originalPosition: this.originalPosition
6729 };
6730 }
6731
6732 });
6733
6734 /*
6735 * Resizable Extensions
6736 */
6737
6738 $.ui.plugin.add("resizable", "animate", {
6739
6740 stop: function( event ) {
6741 var that = $(this).data("ui-resizable"),
6742 o = that.options,
6743 pr = that._proportionallyResizeElements,
6744 ista = pr.length && (/textarea/i).test(pr[0].nodeName),
6745 soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height,
6746 soffsetw = ista ? 0 : that.sizeDiff.width,
6747 style = { width: (that.size.width - soffsetw), height: (that.size.height - soffseth) },
6748 left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null,
6749 top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null;
6750
6751 that.element.animate(
6752 $.extend(style, top && left ? { top: top, left: left } : {}), {
6753 duration: o.animateDuration,
6754 easing: o.animateEasing,
6755 step: function() {
6756
6757 var data = {
6758 width: parseInt(that.element.css("width"), 10),
6759 height: parseInt(that.element.css("height"), 10),
6760 top: parseInt(that.element.css("top"), 10),
6761 left: parseInt(that.element.css("left"), 10)
6762 };
6763
6764 if (pr && pr.length) {
6765 $(pr[0]).css({ width: data.width, height: data.height });
6766 }
6767
6768 // propagating resize, and updating values for each animation step
6769 that._updateCache(data);
6770 that._propagate("resize", event);
6771
6772 }
6773 }
6774 );
6775 }
6776
6777 });
6778
6779 $.ui.plugin.add("resizable", "containment", {
6780
6781 start: function() {
6782 var element, p, co, ch, cw, width, height,
6783 that = $(this).data("ui-resizable"),
6784 o = that.options,
6785 el = that.element,
6786 oc = o.containment,
6787 ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc;
6788
6789 if (!ce) {
6790 return;
6791 }
6792
6793 that.containerElement = $(ce);
6794
6795 if (/document/.test(oc) || oc === document) {
6796 that.containerOffset = { left: 0, top: 0 };
6797 that.containerPosition = { left: 0, top: 0 };
6798
6799 that.parentData = {
6800 element: $(document), left: 0, top: 0,
6801 width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight
6802 };
6803 }
6804
6805 // i'm a node, so compute top, left, right, bottom
6806 else {
6807 element = $(ce);
6808 p = [];
6809 $([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); });
6810
6811 that.containerOffset = element.offset();
6812 that.containerPosition = element.position();
6813 that.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) };
6814
6815 co = that.containerOffset;
6816 ch = that.containerSize.height;
6817 cw = that.containerSize.width;
6818 width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw );
6819 height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch);
6820
6821 that.parentData = {
6822 element: ce, left: co.left, top: co.top, width: width, height: height
6823 };
6824 }
6825 },
6826
6827 resize: function( event ) {
6828 var woset, hoset, isParent, isOffsetRelative,
6829 that = $(this).data("ui-resizable"),
6830 o = that.options,
6831 co = that.containerOffset, cp = that.position,
6832 pRatio = that._aspectRatio || event.shiftKey,
6833 cop = { top:0, left:0 }, ce = that.containerElement;
6834
6835 if (ce[0] !== document && (/static/).test(ce.css("position"))) {
6836 cop = co;
6837 }
6838
6839 if (cp.left < (that._helper ? co.left : 0)) {
6840 that.size.width = that.size.width + (that._helper ? (that.position.left - co.left) : (that.position.left - cop.left));
6841 if (pRatio) {
6842 that.size.height = that.size.width / that.aspectRatio;
6843 }
6844 that.position.left = o.helper ? co.left : 0;
6845 }
6846
6847 if (cp.top < (that._helper ? co.top : 0)) {
6848 that.size.height = that.size.height + (that._helper ? (that.position.top - co.top) : that.position.top);
6849 if (pRatio) {
6850 that.size.width = that.size.height * that.aspectRatio;
6851 }
6852 that.position.top = that._helper ? co.top : 0;
6853 }
6854
6855 that.offset.left = that.parentData.left+that.position.left;
6856 that.offset.top = that.parentData.top+that.position.top;
6857
6858 woset = Math.abs( (that._helper ? that.offset.left - cop.left : (that.offset.left - cop.left)) + that.sizeDiff.width );
6859 hoset = Math.abs( (that._helper ? that.offset.top - cop.top : (that.offset.top - co.top)) + that.sizeDiff.height );
6860
6861 isParent = that.containerElement.get(0) === that.element.parent().get(0);
6862 isOffsetRelative = /relative|absolute/.test(that.containerElement.css("position"));
6863
6864 if(isParent && isOffsetRelative) {
6865 woset -= that.parentData.left;
6866 }
6867
6868 if (woset + that.size.width >= that.parentData.width) {
6869 that.size.width = that.parentData.width - woset;
6870 if (pRatio) {
6871 that.size.height = that.size.width / that.aspectRatio;
6872 }
6873 }
6874
6875 if (hoset + that.size.height >= that.parentData.height) {
6876 that.size.height = that.parentData.height - hoset;
6877 if (pRatio) {
6878 that.size.width = that.size.height * that.aspectRatio;
6879 }
6880 }
6881 },
6882
6883 stop: function(){
6884 var that = $(this).data("ui-resizable"),
6885 o = that.options,
6886 co = that.containerOffset,
6887 cop = that.containerPosition,
6888 ce = that.containerElement,
6889 helper = $(that.helper),
6890 ho = helper.offset(),
6891 w = helper.outerWidth() - that.sizeDiff.width,
6892 h = helper.outerHeight() - that.sizeDiff.height;
6893
6894 if (that._helper && !o.animate && (/relative/).test(ce.css("position"))) {
6895 $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });
6896 }
6897
6898 if (that._helper && !o.animate && (/static/).test(ce.css("position"))) {
6899 $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });
6900 }
6901
6902 }
6903 });
6904
6905 $.ui.plugin.add("resizable", "alsoResize", {
6906
6907 start: function () {
6908 var that = $(this).data("ui-resizable"),
6909 o = that.options,
6910 _store = function (exp) {
6911 $(exp).each(function() {
6912 var el = $(this);
6913 el.data("ui-resizable-alsoresize", {
6914 width: parseInt(el.width(), 10), height: parseInt(el.height(), 10),
6915 left: parseInt(el.css("left"), 10), top: parseInt(el.css("top"), 10)
6916 });
6917 });
6918 };
6919
6920 if (typeof(o.alsoResize) === "object" && !o.alsoResize.parentNode) {
6921 if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); }
6922 else { $.each(o.alsoResize, function (exp) { _store(exp); }); }
6923 }else{
6924 _store(o.alsoResize);
6925 }
6926 },
6927
6928 resize: function (event, ui) {
6929 var that = $(this).data("ui-resizable"),
6930 o = that.options,
6931 os = that.originalSize,
6932 op = that.originalPosition,
6933 delta = {
6934 height: (that.size.height - os.height) || 0, width: (that.size.width - os.width) || 0,
6935 top: (that.position.top - op.top) || 0, left: (that.position.left - op.left) || 0
6936 },
6937
6938 _alsoResize = function (exp, c) {
6939 $(exp).each(function() {
6940 var el = $(this), start = $(this).data("ui-resizable-alsoresize"), style = {},
6941 css = c && c.length ? c : el.parents(ui.originalElement[0]).length ? ["width", "height"] : ["width", "height", "top", "left"];
6942
6943 $.each(css, function (i, prop) {
6944 var sum = (start[prop]||0) + (delta[prop]||0);
6945 if (sum && sum >= 0) {
6946 style[prop] = sum || null;
6947 }
6948 });
6949
6950 el.css(style);
6951 });
6952 };
6953
6954 if (typeof(o.alsoResize) === "object" && !o.alsoResize.nodeType) {
6955 $.each(o.alsoResize, function (exp, c) { _alsoResize(exp, c); });
6956 }else{
6957 _alsoResize(o.alsoResize);
6958 }
6959 },
6960
6961 stop: function () {
6962 $(this).removeData("resizable-alsoresize");
6963 }
6964 });
6965
6966 $.ui.plugin.add("resizable", "ghost", {
6967
6968 start: function() {
6969
6970 var that = $(this).data("ui-resizable"), o = that.options, cs = that.size;
6971
6972 that.ghost = that.originalElement.clone();
6973 that.ghost
6974 .css({ opacity: 0.25, display: "block", position: "relative", height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 })
6975 .addClass("ui-resizable-ghost")
6976 .addClass(typeof o.ghost === "string" ? o.ghost : "");
6977
6978 that.ghost.appendTo(that.helper);
6979
6980 },
6981
6982 resize: function(){
6983 var that = $(this).data("ui-resizable");
6984 if (that.ghost) {
6985 that.ghost.css({ position: "relative", height: that.size.height, width: that.size.width });
6986 }
6987 },
6988
6989 stop: function() {
6990 var that = $(this).data("ui-resizable");
6991 if (that.ghost && that.helper) {
6992 that.helper.get(0).removeChild(that.ghost.get(0));
6993 }
6994 }
6995
6996 });
6997
6998 $.ui.plugin.add("resizable", "grid", {
6999
7000 resize: function() {
7001 var that = $(this).data("ui-resizable"),
7002 o = that.options,
7003 cs = that.size,
7004 os = that.originalSize,
7005 op = that.originalPosition,
7006 a = that.axis,
7007 grid = typeof o.grid === "number" ? [o.grid, o.grid] : o.grid,
7008 gridX = (grid[0]||1),
7009 gridY = (grid[1]||1),
7010 ox = Math.round((cs.width - os.width) / gridX) * gridX,
7011 oy = Math.round((cs.height - os.height) / gridY) * gridY,
7012 newWidth = os.width + ox,
7013 newHeight = os.height + oy,
7014 isMaxWidth = o.maxWidth && (o.maxWidth < newWidth),
7015 isMaxHeight = o.maxHeight && (o.maxHeight < newHeight),
7016 isMinWidth = o.minWidth && (o.minWidth > newWidth),
7017 isMinHeight = o.minHeight && (o.minHeight > newHeight);
7018
7019 o.grid = grid;
7020
7021 if (isMinWidth) {
7022 newWidth = newWidth + gridX;
7023 }
7024 if (isMinHeight) {
7025 newHeight = newHeight + gridY;
7026 }
7027 if (isMaxWidth) {
7028 newWidth = newWidth - gridX;
7029 }
7030 if (isMaxHeight) {
7031 newHeight = newHeight - gridY;
7032 }
7033
7034 if (/^(se|s|e)$/.test(a)) {
7035 that.size.width = newWidth;
7036 that.size.height = newHeight;
7037 } else if (/^(ne)$/.test(a)) {
7038 that.size.width = newWidth;
7039 that.size.height = newHeight;
7040 that.position.top = op.top - oy;
7041 } else if (/^(sw)$/.test(a)) {
7042 that.size.width = newWidth;
7043 that.size.height = newHeight;
7044 that.position.left = op.left - ox;
7045 } else {
7046 that.size.width = newWidth;
7047 that.size.height = newHeight;
7048 that.position.top = op.top - oy;
7049 that.position.left = op.left - ox;
7050 }
7051 }
7052
7053 });
7054
7055 })(jQuery);
7056 (function( $, undefined ) {
7057
7058 $.widget("ui.selectable", $.ui.mouse, {
7059 version: "1.10.3",
7060 options: {
7061 appendTo: "body",
7062 autoRefresh: true,
7063 distance: 0,
7064 filter: "*",
7065 tolerance: "touch",
7066
7067 // callbacks
7068 selected: null,
7069 selecting: null,
7070 start: null,
7071 stop: null,
7072 unselected: null,
7073 unselecting: null
7074 },
7075 _create: function() {
7076 var selectees,
7077 that = this;
7078
7079 this.element.addClass("ui-selectable");
7080
7081 this.dragged = false;
7082
7083 // cache selectee children based on filter
7084 this.refresh = function() {
7085 selectees = $(that.options.filter, that.element[0]);
7086 selectees.addClass("ui-selectee");
7087 selectees.each(function() {
7088 var $this = $(this),
7089 pos = $this.offset();
7090 $.data(this, "selectable-item", {
7091 element: this,
7092 $element: $this,
7093 left: pos.left,
7094 top: pos.top,
7095 right: pos.left + $this.outerWidth(),
7096 bottom: pos.top + $this.outerHeight(),
7097 startselected: false,
7098 selected: $this.hasClass("ui-selected"),
7099 selecting: $this.hasClass("ui-selecting"),
7100 unselecting: $this.hasClass("ui-unselecting")
7101 });
7102 });
7103 };
7104 this.refresh();
7105
7106 this.selectees = selectees.addClass("ui-selectee");
7107
7108 this._mouseInit();
7109
7110 this.helper = $("<div class='ui-selectable-helper'></div>");
7111 },
7112
7113 _destroy: function() {
7114 this.selectees
7115 .removeClass("ui-selectee")
7116 .removeData("selectable-item");
7117 this.element
7118 .removeClass("ui-selectable ui-selectable-disabled");
7119 this._mouseDestroy();
7120 },
7121
7122 _mouseStart: function(event) {
7123 var that = this,
7124 options = this.options;
7125
7126 this.opos = [event.pageX, event.pageY];
7127
7128 if (this.options.disabled) {
7129 return;
7130 }
7131
7132 this.selectees = $(options.filter, this.element[0]);
7133
7134 this._trigger("start", event);
7135
7136 $(options.appendTo).append(this.helper);
7137 // position helper (lasso)
7138 this.helper.css({
7139 "left": event.pageX,
7140 "top": event.pageY,
7141 "width": 0,
7142 "height": 0
7143 });
7144
7145 if (options.autoRefresh) {
7146 this.refresh();
7147 }
7148
7149 this.selectees.filter(".ui-selected").each(function() {
7150 var selectee = $.data(this, "selectable-item");
7151 selectee.startselected = true;
7152 if (!event.metaKey && !event.ctrlKey) {
7153 selectee.$element.removeClass("ui-selected");
7154 selectee.selected = false;
7155 selectee.$element.addClass("ui-unselecting");
7156 selectee.unselecting = true;
7157 // selectable UNSELECTING callback
7158 that._trigger("unselecting", event, {
7159 unselecting: selectee.element
7160 });
7161 }
7162 });
7163
7164 $(event.target).parents().addBack().each(function() {
7165 var doSelect,
7166 selectee = $.data(this, "selectable-item");
7167 if (selectee) {
7168 doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass("ui-selected");
7169 selectee.$element
7170 .removeClass(doSelect ? "ui-unselecting" : "ui-selected")
7171 .addClass(doSelect ? "ui-selecting" : "ui-unselecting");
7172 selectee.unselecting = !doSelect;
7173 selectee.selecting = doSelect;
7174 selectee.selected = doSelect;
7175 // selectable (UN)SELECTING callback
7176 if (doSelect) {
7177 that._trigger("selecting", event, {
7178 selecting: selectee.element
7179 });
7180 } else {
7181 that._trigger("unselecting", event, {
7182 unselecting: selectee.element
7183 });
7184 }
7185 return false;
7186 }
7187 });
7188
7189 },
7190
7191 _mouseDrag: function(event) {
7192
7193 this.dragged = true;
7194
7195 if (this.options.disabled) {
7196 return;
7197 }
7198
7199 var tmp,
7200 that = this,
7201 options = this.options,
7202 x1 = this.opos[0],
7203 y1 = this.opos[1],
7204 x2 = event.pageX,
7205 y2 = event.pageY;
7206
7207 if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; }
7208 if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; }
7209 this.helper.css({left: x1, top: y1, width: x2-x1, height: y2-y1});
7210
7211 this.selectees.each(function() {
7212 var selectee = $.data(this, "selectable-item"),
7213 hit = false;
7214
7215 //prevent helper from being selected if appendTo: selectable
7216 if (!selectee || selectee.element === that.element[0]) {
7217 return;
7218 }
7219
7220 if (options.tolerance === "touch") {
7221 hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) );
7222 } else if (options.tolerance === "fit") {
7223 hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2);
7224 }
7225
7226 if (hit) {
7227 // SELECT
7228 if (selectee.selected) {
7229 selectee.$element.removeClass("ui-selected");
7230 selectee.selected = false;
7231 }
7232 if (selectee.unselecting) {
7233 selectee.$element.removeClass("ui-unselecting");
7234 selectee.unselecting = false;
7235 }
7236 if (!selectee.selecting) {
7237 selectee.$element.addClass("ui-selecting");
7238 selectee.selecting = true;
7239 // selectable SELECTING callback
7240 that._trigger("selecting", event, {
7241 selecting: selectee.element
7242 });
7243 }
7244 } else {
7245 // UNSELECT
7246 if (selectee.selecting) {
7247 if ((event.metaKey || event.ctrlKey) && selectee.startselected) {
7248 selectee.$element.removeClass("ui-selecting");
7249 selectee.selecting = false;
7250 selectee.$element.addClass("ui-selected");
7251 selectee.selected = true;
7252 } else {
7253 selectee.$element.removeClass("ui-selecting");
7254 selectee.selecting = false;
7255 if (selectee.startselected) {
7256 selectee.$element.addClass("ui-unselecting");
7257 selectee.unselecting = true;
7258 }
7259 // selectable UNSELECTING callback
7260 that._trigger("unselecting", event, {
7261 unselecting: selectee.element
7262 });
7263 }
7264 }
7265 if (selectee.selected) {
7266 if (!event.metaKey && !event.ctrlKey && !selectee.startselected) {
7267 selectee.$element.removeClass("ui-selected");
7268 selectee.selected = false;
7269
7270 selectee.$element.addClass("ui-unselecting");
7271 selectee.unselecting = true;
7272 // selectable UNSELECTING callback
7273 that._trigger("unselecting", event, {
7274 unselecting: selectee.element
7275 });
7276 }
7277 }
7278 }
7279 });
7280
7281 return false;
7282 },
7283
7284 _mouseStop: function(event) {
7285 var that = this;
7286
7287 this.dragged = false;
7288
7289 $(".ui-unselecting", this.element[0]).each(function() {
7290 var selectee = $.data(this, "selectable-item");
7291 selectee.$element.removeClass("ui-unselecting");
7292 selectee.unselecting = false;
7293 selectee.startselected = false;
7294 that._trigger("unselected", event, {
7295 unselected: selectee.element
7296 });
7297 });
7298 $(".ui-selecting", this.element[0]).each(function() {
7299 var selectee = $.data(this, "selectable-item");
7300 selectee.$element.removeClass("ui-selecting").addClass("ui-selected");
7301 selectee.selecting = false;
7302 selectee.selected = true;
7303 selectee.startselected = true;
7304 that._trigger("selected", event, {
7305 selected: selectee.element
7306 });
7307 });
7308 this._trigger("stop", event);
7309
7310 this.helper.remove();
7311
7312 return false;
7313 }
7314
7315 });
7316
7317 })(jQuery);
7318 (function( $, undefined ) {
7319
7320 /*jshint loopfunc: true */
7321
7322 function isOverAxis( x, reference, size ) {
7323 return ( x > reference ) && ( x < ( reference + size ) );
7324 }
7325
7326 function isFloating(item) {
7327 return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display"));
7328 }
7329
7330 $.widget("ui.sortable", $.ui.mouse, {
7331 version: "1.10.3",
7332 widgetEventPrefix: "sort",
7333 ready: false,
7334 options: {
7335 appendTo: "parent",
7336 axis: false,
7337 connectWith: false,
7338 containment: false,
7339 cursor: "auto",
7340 cursorAt: false,
7341 dropOnEmpty: true,
7342 forcePlaceholderSize: false,
7343 forceHelperSize: false,
7344 grid: false,
7345 handle: false,
7346 helper: "original",
7347 items: "> *",
7348 opacity: false,
7349 placeholder: false,
7350 revert: false,
7351 scroll: true,
7352 scrollSensitivity: 20,
7353 scrollSpeed: 20,
7354 scope: "default",
7355 tolerance: "intersect",
7356 zIndex: 1000,
7357
7358 // callbacks
7359 activate: null,
7360 beforeStop: null,
7361 change: null,
7362 deactivate: null,
7363 out: null,
7364 over: null,
7365 receive: null,
7366 remove: null,
7367 sort: null,
7368 start: null,
7369 stop: null,
7370 update: null
7371 },
7372 _create: function() {
7373
7374 var o = this.options;
7375 this.containerCache = {};
7376 this.element.addClass("ui-sortable");
7377
7378 //Get the items
7379 this.refresh();
7380
7381 //Let's determine if the items are being displayed horizontally
7382 this.floating = this.items.length ? o.axis === "x" || isFloating(this.items[0].item) : false;
7383
7384 //Let's determine the parent's offset
7385 this.offset = this.element.offset();
7386
7387 //Initialize mouse events for interaction
7388 this._mouseInit();
7389
7390 //We're ready to go
7391 this.ready = true;
7392
7393 },
7394
7395 _destroy: function() {
7396 this.element
7397 .removeClass("ui-sortable ui-sortable-disabled");
7398 this._mouseDestroy();
7399
7400 for ( var i = this.items.length - 1; i >= 0; i-- ) {
7401 this.items[i].item.removeData(this.widgetName + "-item");
7402 }
7403
7404 return this;
7405 },
7406
7407 _setOption: function(key, value){
7408 if ( key === "disabled" ) {
7409 this.options[ key ] = value;
7410
7411 this.widget().toggleClass( "ui-sortable-disabled", !!value );
7412 } else {
7413 // Don't call widget base _setOption for disable as it adds ui-state-disabled class
7414 $.Widget.prototype._setOption.apply(this, arguments);
7415 }
7416 },
7417
7418 _mouseCapture: function(event, overrideHandle) {
7419 var currentItem = null,
7420 validHandle = false,
7421 that = this;
7422
7423 if (this.reverting) {
7424 return false;
7425 }
7426
7427 if(this.options.disabled || this.options.type === "static") {
7428 return false;
7429 }
7430
7431 //We have to refresh the items data once first
7432 this._refreshItems(event);
7433
7434 //Find out if the clicked node (or one of its parents) is a actual item in this.items
7435 $(event.target).parents().each(function() {
7436 if($.data(this, that.widgetName + "-item") === that) {
7437 currentItem = $(this);
7438 return false;
7439 }
7440 });
7441 if($.data(event.target, that.widgetName + "-item") === that) {
7442 currentItem = $(event.target);
7443 }
7444
7445 if(!currentItem) {
7446 return false;
7447 }
7448 if(this.options.handle && !overrideHandle) {
7449 $(this.options.handle, currentItem).find("*").addBack().each(function() {
7450 if(this === event.target) {
7451 validHandle = true;
7452 }
7453 });
7454 if(!validHandle) {
7455 return false;
7456 }
7457 }
7458
7459 this.currentItem = currentItem;
7460 this._removeCurrentsFromItems();
7461 return true;
7462
7463 },
7464
7465 _mouseStart: function(event, overrideHandle, noActivation) {
7466
7467 var i, body,
7468 o = this.options;
7469
7470 this.currentContainer = this;
7471
7472 //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
7473 this.refreshPositions();
7474
7475 //Create and append the visible helper
7476 this.helper = this._createHelper(event);
7477
7478 //Cache the helper size
7479 this._cacheHelperProportions();
7480
7481 /*
7482 * - Position generation -
7483 * This block generates everything position related - it's the core of draggables.
7484 */
7485
7486 //Cache the margins of the original element
7487 this._cacheMargins();
7488
7489 //Get the next scrolling parent
7490 this.scrollParent = this.helper.scrollParent();
7491
7492 //The element's absolute position on the page minus margins
7493 this.offset = this.currentItem.offset();
7494 this.offset = {
7495 top: this.offset.top - this.margins.top,
7496 left: this.offset.left - this.margins.left
7497 };
7498
7499 $.extend(this.offset, {
7500 click: { //Where the click happened, relative to the element
7501 left: event.pageX - this.offset.left,
7502 top: event.pageY - this.offset.top
7503 },
7504 parent: this._getParentOffset(),
7505 relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
7506 });
7507
7508 // Only after we got the offset, we can change the helper's position to absolute
7509 // TODO: Still need to figure out a way to make relative sorting possible
7510 this.helper.css("position", "absolute");
7511 this.cssPosition = this.helper.css("position");
7512
7513 //Generate the original position
7514 this.originalPosition = this._generatePosition(event);
7515 this.originalPageX = event.pageX;
7516 this.originalPageY = event.pageY;
7517
7518 //Adjust the mouse offset relative to the helper if "cursorAt" is supplied
7519 (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
7520
7521 //Cache the former DOM position
7522 this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };
7523
7524 //If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
7525 if(this.helper[0] !== this.currentItem[0]) {
7526 this.currentItem.hide();
7527 }
7528
7529 //Create the placeholder
7530 this._createPlaceholder();
7531
7532 //Set a containment if given in the options
7533 if(o.containment) {
7534 this._setContainment();
7535 }
7536
7537 if( o.cursor && o.cursor !== "auto" ) { // cursor option
7538 body = this.document.find( "body" );
7539
7540 // support: IE
7541 this.storedCursor = body.css( "cursor" );
7542 body.css( "cursor", o.cursor );
7543
7544 this.storedStylesheet = $( "<style>*{ cursor: "+o.cursor+" !important; }</style>" ).appendTo( body );
7545 }
7546
7547 if(o.opacity) { // opacity option
7548 if (this.helper.css("opacity")) {
7549 this._storedOpacity = this.helper.css("opacity");
7550 }
7551 this.helper.css("opacity", o.opacity);
7552 }
7553
7554 if(o.zIndex) { // zIndex option
7555 if (this.helper.css("zIndex")) {
7556 this._storedZIndex = this.helper.css("zIndex");
7557 }
7558 this.helper.css("zIndex", o.zIndex);
7559 }
7560
7561 //Prepare scrolling
7562 if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
7563 this.overflowOffset = this.scrollParent.offset();
7564 }
7565
7566 //Call callbacks
7567 this._trigger("start", event, this._uiHash());
7568
7569 //Recache the helper size
7570 if(!this._preserveHelperProportions) {
7571 this._cacheHelperProportions();
7572 }
7573
7574
7575 //Post "activate" events to possible containers
7576 if( !noActivation ) {
7577 for ( i = this.containers.length - 1; i >= 0; i-- ) {
7578 this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) );
7579 }
7580 }
7581
7582 //Prepare possible droppables
7583 if($.ui.ddmanager) {
7584 $.ui.ddmanager.current = this;
7585 }
7586
7587 if ($.ui.ddmanager && !o.dropBehaviour) {
7588 $.ui.ddmanager.prepareOffsets(this, event);
7589 }
7590
7591 this.dragging = true;
7592
7593 this.helper.addClass("ui-sortable-helper");
7594 this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
7595 return true;
7596
7597 },
7598
7599 _mouseDrag: function(event) {
7600 var i, item, itemElement, intersection,
7601 o = this.options,
7602 scrolled = false;
7603
7604 //Compute the helpers position
7605 this.position = this._generatePosition(event);
7606 this.positionAbs = this._convertPositionTo("absolute");
7607
7608 if (!this.lastPositionAbs) {
7609 this.lastPositionAbs = this.positionAbs;
7610 }
7611
7612 //Do scrolling
7613 if(this.options.scroll) {
7614 if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
7615
7616 if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
7617 this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
7618 } else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) {
7619 this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
7620 }
7621
7622 if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
7623 this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
7624 } else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) {
7625 this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;
7626 }
7627
7628 } else {
7629
7630 if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
7631 scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
7632 } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
7633 scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
7634 }
7635
7636 if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
7637 scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
7638 } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
7639 scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
7640 }
7641
7642 }
7643
7644 if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
7645 $.ui.ddmanager.prepareOffsets(this, event);
7646 }
7647 }
7648
7649 //Regenerate the absolute position used for position checks
7650 this.positionAbs = this._convertPositionTo("absolute");
7651
7652 //Set the helper position
7653 if(!this.options.axis || this.options.axis !== "y") {
7654 this.helper[0].style.left = this.position.left+"px";
7655 }
7656 if(!this.options.axis || this.options.axis !== "x") {
7657 this.helper[0].style.top = this.position.top+"px";
7658 }
7659
7660 //Rearrange
7661 for (i = this.items.length - 1; i >= 0; i--) {
7662
7663 //Cache variables and intersection, continue if no intersection
7664 item = this.items[i];
7665 itemElement = item.item[0];
7666 intersection = this._intersectsWithPointer(item);
7667 if (!intersection) {
7668 continue;
7669 }
7670
7671 // Only put the placeholder inside the current Container, skip all
7672 // items form other containers. This works because when moving
7673 // an item from one container to another the
7674 // currentContainer is switched before the placeholder is moved.
7675 //
7676 // Without this moving items in "sub-sortables" can cause the placeholder to jitter
7677 // beetween the outer and inner container.
7678 if (item.instance !== this.currentContainer) {
7679 continue;
7680 }
7681
7682 // cannot intersect with itself
7683 // no useless actions that have been done before
7684 // no action if the item moved is the parent of the item checked
7685 if (itemElement !== this.currentItem[0] &&
7686 this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement &&
7687 !$.contains(this.placeholder[0], itemElement) &&
7688 (this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true)
7689 ) {
7690
7691 this.direction = intersection === 1 ? "down" : "up";
7692
7693 if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) {
7694 this._rearrange(event, item);
7695 } else {
7696 break;
7697 }
7698
7699 this._trigger("change", event, this._uiHash());
7700 break;
7701 }
7702 }
7703
7704 //Post events to containers
7705 this._contactContainers(event);
7706
7707 //Interconnect with droppables
7708 if($.ui.ddmanager) {
7709 $.ui.ddmanager.drag(this, event);
7710 }
7711
7712 //Call callbacks
7713 this._trigger("sort", event, this._uiHash());
7714
7715 this.lastPositionAbs = this.positionAbs;
7716 return false;
7717
7718 },
7719
7720 _mouseStop: function(event, noPropagation) {
7721
7722 if(!event) {
7723 return;
7724 }
7725
7726 //If we are using droppables, inform the manager about the drop
7727 if ($.ui.ddmanager && !this.options.dropBehaviour) {
7728 $.ui.ddmanager.drop(this, event);
7729 }
7730
7731 if(this.options.revert) {
7732 var that = this,
7733 cur = this.placeholder.offset(),
7734 axis = this.options.axis,
7735 animation = {};
7736
7737 if ( !axis || axis === "x" ) {
7738 animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollLeft);
7739 }
7740 if ( !axis || axis === "y" ) {
7741 animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollTop);
7742 }
7743 this.reverting = true;
7744 $(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() {
7745 that._clear(event);
7746 });
7747 } else {
7748 this._clear(event, noPropagation);
7749 }
7750
7751 return false;
7752
7753 },
7754
7755 cancel: function() {
7756
7757 if(this.dragging) {
7758
7759 this._mouseUp({ target: null });
7760
7761 if(this.options.helper === "original") {
7762 this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
7763 } else {
7764 this.currentItem.show();
7765 }
7766
7767 //Post deactivating events to containers
7768 for (var i = this.containers.length - 1; i >= 0; i--){
7769 this.containers[i]._trigger("deactivate", null, this._uiHash(this));
7770 if(this.containers[i].containerCache.over) {
7771 this.containers[i]._trigger("out", null, this._uiHash(this));
7772 this.containers[i].containerCache.over = 0;
7773 }
7774 }
7775
7776 }
7777
7778 if (this.placeholder) {
7779 //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
7780 if(this.placeholder[0].parentNode) {
7781 this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
7782 }
7783 if(this.options.helper !== "original" && this.helper && this.helper[0].parentNode) {
7784 this.helper.remove();
7785 }
7786
7787 $.extend(this, {
7788 helper: null,
7789 dragging: false,
7790 reverting: false,
7791 _noFinalSort: null
7792 });
7793
7794 if(this.domPosition.prev) {
7795 $(this.domPosition.prev).after(this.currentItem);
7796 } else {
7797 $(this.domPosition.parent).prepend(this.currentItem);
7798 }
7799 }
7800
7801 return this;
7802
7803 },
7804
7805 serialize: function(o) {
7806
7807 var items = this._getItemsAsjQuery(o && o.connected),
7808 str = [];
7809 o = o || {};
7810
7811 $(items).each(function() {
7812 var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/));
7813 if (res) {
7814 str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2]));
7815 }
7816 });
7817
7818 if(!str.length && o.key) {
7819 str.push(o.key + "=");
7820 }
7821
7822 return str.join("&");
7823
7824 },
7825
7826 toArray: function(o) {
7827
7828 var items = this._getItemsAsjQuery(o && o.connected),
7829 ret = [];
7830
7831 o = o || {};
7832
7833 items.each(function() { ret.push($(o.item || this).attr(o.attribute || "id") || ""); });
7834 return ret;
7835
7836 },
7837
7838 /* Be careful with the following core functions */
7839 _intersectsWith: function(item) {
7840
7841 var x1 = this.positionAbs.left,
7842 x2 = x1 + this.helperProportions.width,
7843 y1 = this.positionAbs.top,
7844 y2 = y1 + this.helperProportions.height,
7845 l = item.left,
7846 r = l + item.width,
7847 t = item.top,
7848 b = t + item.height,
7849 dyClick = this.offset.click.top,
7850 dxClick = this.offset.click.left,
7851 isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t && ( y1 + dyClick ) < b ),
7852 isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l && ( x1 + dxClick ) < r ),
7853 isOverElement = isOverElementHeight && isOverElementWidth;
7854
7855 if ( this.options.tolerance === "pointer" ||
7856 this.options.forcePointerForContainers ||
7857 (this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"])
7858 ) {
7859 return isOverElement;
7860 } else {
7861
7862 return (l < x1 + (this.helperProportions.width / 2) && // Right Half
7863 x2 - (this.helperProportions.width / 2) < r && // Left Half
7864 t < y1 + (this.helperProportions.height / 2) && // Bottom Half
7865 y2 - (this.helperProportions.height / 2) < b ); // Top Half
7866
7867 }
7868 },
7869
7870 _intersectsWithPointer: function(item) {
7871
7872 var isOverElementHeight = (this.options.axis === "x") || isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
7873 isOverElementWidth = (this.options.axis === "y") || isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
7874 isOverElement = isOverElementHeight && isOverElementWidth,
7875 verticalDirection = this._getDragVerticalDirection(),
7876 horizontalDirection = this._getDragHorizontalDirection();
7877
7878 if (!isOverElement) {
7879 return false;
7880 }
7881
7882 return this.floating ?
7883 ( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 )
7884 : ( verticalDirection && (verticalDirection === "down" ? 2 : 1) );
7885
7886 },
7887
7888 _intersectsWithSides: function(item) {
7889
7890 var isOverBottomHalf = isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
7891 isOverRightHalf = isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
7892 verticalDirection = this._getDragVerticalDirection(),
7893 horizontalDirection = this._getDragHorizontalDirection();
7894
7895 if (this.floating && horizontalDirection) {
7896 return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf));
7897 } else {
7898 return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf));
7899 }
7900
7901 },
7902
7903 _getDragVerticalDirection: function() {
7904 var delta = this.positionAbs.top - this.lastPositionAbs.top;
7905 return delta !== 0 && (delta > 0 ? "down" : "up");
7906 },
7907
7908 _getDragHorizontalDirection: function() {
7909 var delta = this.positionAbs.left - this.lastPositionAbs.left;
7910 return delta !== 0 && (delta > 0 ? "right" : "left");
7911 },
7912
7913 refresh: function(event) {
7914 this._refreshItems(event);
7915 this.refreshPositions();
7916 return this;
7917 },
7918
7919 _connectWith: function() {
7920 var options = this.options;
7921 return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith;
7922 },
7923
7924 _getItemsAsjQuery: function(connected) {
7925
7926 var i, j, cur, inst,
7927 items = [],
7928 queries = [],
7929 connectWith = this._connectWith();
7930
7931 if(connectWith && connected) {
7932 for (i = connectWith.length - 1; i >= 0; i--){
7933 cur = $(connectWith[i]);
7934 for ( j = cur.length - 1; j >= 0; j--){
7935 inst = $.data(cur[j], this.widgetFullName);
7936 if(inst && inst !== this && !inst.options.disabled) {
7937 queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), inst]);
7938 }
7939 }
7940 }
7941 }
7942
7943 queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), this]);
7944
7945 for (i = queries.length - 1; i >= 0; i--){
7946 queries[i][0].each(function() {
7947 items.push(this);
7948 });
7949 }
7950
7951 return $(items);
7952
7953 },
7954
7955 _removeCurrentsFromItems: function() {
7956
7957 var list = this.currentItem.find(":data(" + this.widgetName + "-item)");
7958
7959 this.items = $.grep(this.items, function (item) {
7960 for (var j=0; j < list.length; j++) {
7961 if(list[j] === item.item[0]) {
7962 return false;
7963 }
7964 }
7965 return true;
7966 });
7967
7968 },
7969
7970 _refreshItems: function(event) {
7971
7972 this.items = [];
7973 this.containers = [this];
7974
7975 var i, j, cur, inst, targetData, _queries, item, queriesLength,
7976 items = this.items,
7977 queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]],
7978 connectWith = this._connectWith();
7979
7980 if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down
7981 for (i = connectWith.length - 1; i >= 0; i--){
7982 cur = $(connectWith[i]);
7983 for (j = cur.length - 1; j >= 0; j--){
7984 inst = $.data(cur[j], this.widgetFullName);
7985 if(inst && inst !== this && !inst.options.disabled) {
7986 queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
7987 this.containers.push(inst);
7988 }
7989 }
7990 }
7991 }
7992
7993 for (i = queries.length - 1; i >= 0; i--) {
7994 targetData = queries[i][1];
7995 _queries = queries[i][0];
7996
7997 for (j=0, queriesLength = _queries.length; j < queriesLength; j++) {
7998 item = $(_queries[j]);
7999
8000 item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager)
8001
8002 items.push({
8003 item: item,
8004 instance: targetData,
8005 width: 0, height: 0,
8006 left: 0, top: 0
8007 });
8008 }
8009 }
8010
8011 },
8012
8013 refreshPositions: function(fast) {
8014
8015 //This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
8016 if(this.offsetParent && this.helper) {
8017 this.offset.parent = this._getParentOffset();
8018 }
8019
8020 var i, item, t, p;
8021
8022 for (i = this.items.length - 1; i >= 0; i--){
8023 item = this.items[i];
8024
8025 //We ignore calculating positions of all connected containers when we're not over them
8026 if(item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) {
8027 continue;
8028 }
8029
8030 t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;
8031
8032 if (!fast) {
8033 item.width = t.outerWidth();
8034 item.height = t.outerHeight();
8035 }
8036
8037 p = t.offset();
8038 item.left = p.left;
8039 item.top = p.top;
8040 }
8041
8042 if(this.options.custom && this.options.custom.refreshContainers) {
8043 this.options.custom.refreshContainers.call(this);
8044 } else {
8045 for (i = this.containers.length - 1; i >= 0; i--){
8046 p = this.containers[i].element.offset();
8047 this.containers[i].containerCache.left = p.left;
8048 this.containers[i].containerCache.top = p.top;
8049 this.containers[i].containerCache.width = this.containers[i].element.outerWidth();
8050 this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
8051 }
8052 }
8053
8054 return this;
8055 },
8056
8057 _createPlaceholder: function(that) {
8058 that = that || this;
8059 var className,
8060 o = that.options;
8061
8062 if(!o.placeholder || o.placeholder.constructor === String) {
8063 className = o.placeholder;
8064 o.placeholder = {
8065 element: function() {
8066
8067 var nodeName = that.currentItem[0].nodeName.toLowerCase(),
8068 element = $( "<" + nodeName + ">", that.document[0] )
8069 .addClass(className || that.currentItem[0].className+" ui-sortable-placeholder")
8070 .removeClass("ui-sortable-helper");
8071
8072 if ( nodeName === "tr" ) {
8073 that.currentItem.children().each(function() {
8074 $( "<td>&#160;</td>", that.document[0] )
8075 .attr( "colspan", $( this ).attr( "colspan" ) || 1 )
8076 .appendTo( element );
8077 });
8078 } else if ( nodeName === "img" ) {
8079 element.attr( "src", that.currentItem.attr( "src" ) );
8080 }
8081
8082 if ( !className ) {
8083 element.css( "visibility", "hidden" );
8084 }
8085
8086 return element;
8087 },
8088 update: function(container, p) {
8089
8090 // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
8091 // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
8092 if(className && !o.forcePlaceholderSize) {
8093 return;
8094 }
8095
8096 //If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
8097 if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); }
8098 if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); }
8099 }
8100 };
8101 }
8102
8103 //Create the placeholder
8104 that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem));
8105
8106 //Append it after the actual current item
8107 that.currentItem.after(that.placeholder);
8108
8109 //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
8110 o.placeholder.update(that, that.placeholder);
8111
8112 },
8113
8114 _contactContainers: function(event) {
8115 var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, base, cur, nearBottom, floating,
8116 innermostContainer = null,
8117 innermostIndex = null;
8118
8119 // get innermost container that intersects with item
8120 for (i = this.containers.length - 1; i >= 0; i--) {
8121
8122 // never consider a container that's located within the item itself
8123 if($.contains(this.currentItem[0], this.containers[i].element[0])) {
8124 continue;
8125 }
8126
8127 if(this._intersectsWith(this.containers[i].containerCache)) {
8128
8129 // if we've already found a container and it's more "inner" than this, then continue
8130 if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) {
8131 continue;
8132 }
8133
8134 innermostContainer = this.containers[i];
8135 innermostIndex = i;
8136
8137 } else {
8138 // container doesn't intersect. trigger "out" event if necessary
8139 if(this.containers[i].containerCache.over) {
8140 this.containers[i]._trigger("out", event, this._uiHash(this));
8141 this.containers[i].containerCache.over = 0;
8142 }
8143 }
8144
8145 }
8146
8147 // if no intersecting containers found, return
8148 if(!innermostContainer) {
8149 return;
8150 }
8151
8152 // move the item into the container if it's not there already
8153 if(this.containers.length === 1) {
8154 if (!this.containers[innermostIndex].containerCache.over) {
8155 this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
8156 this.containers[innermostIndex].containerCache.over = 1;
8157 }
8158 } else {
8159
8160 //When entering a new container, we will find the item with the least distance and append our item near it
8161 dist = 10000;
8162 itemWithLeastDistance = null;
8163 floating = innermostContainer.floating || isFloating(this.currentItem);
8164 posProperty = floating ? "left" : "top";
8165 sizeProperty = floating ? "width" : "height";
8166 base = this.positionAbs[posProperty] + this.offset.click[posProperty];
8167 for (j = this.items.length - 1; j >= 0; j--) {
8168 if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) {
8169 continue;
8170 }
8171 if(this.items[j].item[0] === this.currentItem[0]) {
8172 continue;
8173 }
8174 if (floating && !isOverAxis(this.positionAbs.top + this.offset.click.top, this.items[j].top, this.items[j].height)) {
8175 continue;
8176 }
8177 cur = this.items[j].item.offset()[posProperty];
8178 nearBottom = false;
8179 if(Math.abs(cur - base) > Math.abs(cur + this.items[j][sizeProperty] - base)){
8180 nearBottom = true;
8181 cur += this.items[j][sizeProperty];
8182 }
8183
8184 if(Math.abs(cur - base) < dist) {
8185 dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j];
8186 this.direction = nearBottom ? "up": "down";
8187 }
8188 }
8189
8190 //Check if dropOnEmpty is enabled
8191 if(!itemWithLeastDistance && !this.options.dropOnEmpty) {
8192 return;
8193 }
8194
8195 if(this.currentContainer === this.containers[innermostIndex]) {
8196 return;
8197 }
8198
8199 itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true);
8200 this._trigger("change", event, this._uiHash());
8201 this.containers[innermostIndex]._trigger("change", event, this._uiHash(this));
8202 this.currentContainer = this.containers[innermostIndex];
8203
8204 //Update the placeholder
8205 this.options.placeholder.update(this.currentContainer, this.placeholder);
8206
8207 this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
8208 this.containers[innermostIndex].containerCache.over = 1;
8209 }
8210
8211
8212 },
8213
8214 _createHelper: function(event) {
8215
8216 var o = this.options,
8217 helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem);
8218
8219 //Add the helper to the DOM if that didn't happen already
8220 if(!helper.parents("body").length) {
8221 $(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);
8222 }
8223
8224 if(helper[0] === this.currentItem[0]) {
8225 this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") };
8226 }
8227
8228 if(!helper[0].style.width || o.forceHelperSize) {
8229 helper.width(this.currentItem.width());
8230 }
8231 if(!helper[0].style.height || o.forceHelperSize) {
8232 helper.height(this.currentItem.height());
8233 }
8234
8235 return helper;
8236
8237 },
8238
8239 _adjustOffsetFromHelper: function(obj) {
8240 if (typeof obj === "string") {
8241 obj = obj.split(" ");
8242 }
8243 if ($.isArray(obj)) {
8244 obj = {left: +obj[0], top: +obj[1] || 0};
8245 }
8246 if ("left" in obj) {
8247 this.offset.click.left = obj.left + this.margins.left;
8248 }
8249 if ("right" in obj) {
8250 this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
8251 }
8252 if ("top" in obj) {
8253 this.offset.click.top = obj.top + this.margins.top;
8254 }
8255 if ("bottom" in obj) {
8256 this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
8257 }
8258 },
8259
8260 _getParentOffset: function() {
8261
8262
8263 //Get the offsetParent and cache its position
8264 this.offsetParent = this.helper.offsetParent();
8265 var po = this.offsetParent.offset();
8266
8267 // This is a special case where we need to modify a offset calculated on start, since the following happened:
8268 // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
8269 // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
8270 // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
8271 if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
8272 po.left += this.scrollParent.scrollLeft();
8273 po.top += this.scrollParent.scrollTop();
8274 }
8275
8276 // This needs to be actually done for all browsers, since pageX/pageY includes this information
8277 // with an ugly IE fix
8278 if( this.offsetParent[0] === document.body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
8279 po = { top: 0, left: 0 };
8280 }
8281
8282 return {
8283 top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
8284 left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
8285 };
8286
8287 },
8288
8289 _getRelativeOffset: function() {
8290
8291 if(this.cssPosition === "relative") {
8292 var p = this.currentItem.position();
8293 return {
8294 top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
8295 left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
8296 };
8297 } else {
8298 return { top: 0, left: 0 };
8299 }
8300
8301 },
8302
8303 _cacheMargins: function() {
8304 this.margins = {
8305 left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
8306 top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
8307 };
8308 },
8309
8310 _cacheHelperProportions: function() {
8311 this.helperProportions = {
8312 width: this.helper.outerWidth(),
8313 height: this.helper.outerHeight()
8314 };
8315 },
8316
8317 _setContainment: function() {
8318
8319 var ce, co, over,
8320 o = this.options;
8321 if(o.containment === "parent") {
8322 o.containment = this.helper[0].parentNode;
8323 }
8324 if(o.containment === "document" || o.containment === "window") {
8325 this.containment = [
8326 0 - this.offset.relative.left - this.offset.parent.left,
8327 0 - this.offset.relative.top - this.offset.parent.top,
8328 $(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left,
8329 ($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
8330 ];
8331 }
8332
8333 if(!(/^(document|window|parent)$/).test(o.containment)) {
8334 ce = $(o.containment)[0];
8335 co = $(o.containment).offset();
8336 over = ($(ce).css("overflow") !== "hidden");
8337
8338 this.containment = [
8339 co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
8340 co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
8341 co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
8342 co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
8343 ];
8344 }
8345
8346 },
8347
8348 _convertPositionTo: function(d, pos) {
8349
8350 if(!pos) {
8351 pos = this.position;
8352 }
8353 var mod = d === "absolute" ? 1 : -1,
8354 scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent,
8355 scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
8356
8357 return {
8358 top: (
8359 pos.top + // The absolute mouse position
8360 this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
8361 this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border)
8362 ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
8363 ),
8364 left: (
8365 pos.left + // The absolute mouse position
8366 this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
8367 this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border)
8368 ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
8369 )
8370 };
8371
8372 },
8373
8374 _generatePosition: function(event) {
8375
8376 var top, left,
8377 o = this.options,
8378 pageX = event.pageX,
8379 pageY = event.pageY,
8380 scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
8381
8382 // This is another very weird special case that only happens for relative elements:
8383 // 1. If the css position is relative
8384 // 2. and the scroll parent is the document or similar to the offset parent
8385 // we have to refresh the relative offset during the scroll so there are no jumps
8386 if(this.cssPosition === "relative" && !(this.scrollParent[0] !== document && this.scrollParent[0] !== this.offsetParent[0])) {
8387 this.offset.relative = this._getRelativeOffset();
8388 }
8389
8390 /*
8391 * - Position constraining -
8392 * Constrain the position to a mix of grid, containment.
8393 */
8394
8395 if(this.originalPosition) { //If we are not dragging yet, we won't check for options
8396
8397 if(this.containment) {
8398 if(event.pageX - this.offset.click.left < this.containment[0]) {
8399 pageX = this.containment[0] + this.offset.click.left;
8400 }
8401 if(event.pageY - this.offset.click.top < this.containment[1]) {
8402 pageY = this.containment[1] + this.offset.click.top;
8403 }
8404 if(event.pageX - this.offset.click.left > this.containment[2]) {
8405 pageX = this.containment[2] + this.offset.click.left;
8406 }
8407 if(event.pageY - this.offset.click.top > this.containment[3]) {
8408 pageY = this.containment[3] + this.offset.click.top;
8409 }
8410 }
8411
8412 if(o.grid) {
8413 top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
8414 pageY = this.containment ? ( (top - this.offset.click.top >= this.containment[1] && top - this.offset.click.top <= this.containment[3]) ? top : ((top - this.offset.click.top >= this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
8415
8416 left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
8417 pageX = this.containment ? ( (left - this.offset.click.left >= this.containment[0] && left - this.offset.click.left <= this.containment[2]) ? left : ((left - this.offset.click.left >= this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
8418 }
8419
8420 }
8421
8422 return {
8423 top: (
8424 pageY - // The absolute mouse position
8425 this.offset.click.top - // Click offset (relative to the element)
8426 this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent
8427 this.offset.parent.top + // The offsetParent's offset without borders (offset + border)
8428 ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
8429 ),
8430 left: (
8431 pageX - // The absolute mouse position
8432 this.offset.click.left - // Click offset (relative to the element)
8433 this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent
8434 this.offset.parent.left + // The offsetParent's offset without borders (offset + border)
8435 ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
8436 )
8437 };
8438
8439 },
8440
8441 _rearrange: function(event, i, a, hardRefresh) {
8442
8443 a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction === "down" ? i.item[0] : i.item[0].nextSibling));
8444
8445 //Various things done here to improve the performance:
8446 // 1. we create a setTimeout, that calls refreshPositions
8447 // 2. on the instance, we have a counter variable, that get's higher after every append
8448 // 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
8449 // 4. this lets only the last addition to the timeout stack through
8450 this.counter = this.counter ? ++this.counter : 1;
8451 var counter = this.counter;
8452
8453 this._delay(function() {
8454 if(counter === this.counter) {
8455 this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
8456 }
8457 });
8458
8459 },
8460
8461 _clear: function(event, noPropagation) {
8462
8463 this.reverting = false;
8464 // We delay all events that have to be triggered to after the point where the placeholder has been removed and
8465 // everything else normalized again
8466 var i,
8467 delayedTriggers = [];
8468
8469 // We first have to update the dom position of the actual currentItem
8470 // Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
8471 if(!this._noFinalSort && this.currentItem.parent().length) {
8472 this.placeholder.before(this.currentItem);
8473 }
8474 this._noFinalSort = null;
8475
8476 if(this.helper[0] === this.currentItem[0]) {
8477 for(i in this._storedCSS) {
8478 if(this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") {
8479 this._storedCSS[i] = "";
8480 }
8481 }
8482 this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
8483 } else {
8484 this.currentItem.show();
8485 }
8486
8487 if(this.fromOutside && !noPropagation) {
8488 delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
8489 }
8490 if((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) {
8491 delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
8492 }
8493
8494 // Check if the items Container has Changed and trigger appropriate
8495 // events.
8496 if (this !== this.currentContainer) {
8497 if(!noPropagation) {
8498 delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
8499 delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); }; }).call(this, this.currentContainer));
8500 delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this)); }; }).call(this, this.currentContainer));
8501 }
8502 }
8503
8504
8505 //Post events to containers
8506 for (i = this.containers.length - 1; i >= 0; i--){
8507 if(!noPropagation) {
8508 delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); }; }).call(this, this.containers[i]));
8509 }
8510 if(this.containers[i].containerCache.over) {
8511 delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); }; }).call(this, this.containers[i]));
8512 this.containers[i].containerCache.over = 0;
8513 }
8514 }
8515
8516 //Do what was originally in plugins
8517 if ( this.storedCursor ) {
8518 this.document.find( "body" ).css( "cursor", this.storedCursor );
8519 this.storedStylesheet.remove();
8520 }
8521 if(this._storedOpacity) {
8522 this.helper.css("opacity", this._storedOpacity);
8523 }
8524 if(this._storedZIndex) {
8525 this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex);
8526 }
8527
8528 this.dragging = false;
8529 if(this.cancelHelperRemoval) {
8530 if(!noPropagation) {
8531 this._trigger("beforeStop", event, this._uiHash());
8532 for (i=0; i < delayedTriggers.length; i++) {
8533 delayedTriggers[i].call(this, event);
8534 } //Trigger all delayed events
8535 this._trigger("stop", event, this._uiHash());
8536 }
8537
8538 this.fromOutside = false;
8539 return false;
8540 }
8541
8542 if(!noPropagation) {
8543 this._trigger("beforeStop", event, this._uiHash());
8544 }
8545
8546 //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
8547 this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
8548
8549 if(this.helper[0] !== this.currentItem[0]) {
8550 this.helper.remove();
8551 }
8552 this.helper = null;
8553
8554 if(!noPropagation) {
8555 for (i=0; i < delayedTriggers.length; i++) {
8556 delayedTriggers[i].call(this, event);
8557 } //Trigger all delayed events
8558 this._trigger("stop", event, this._uiHash());
8559 }
8560
8561 this.fromOutside = false;
8562 return true;
8563
8564 },
8565
8566 _trigger: function() {
8567 if ($.Widget.prototype._trigger.apply(this, arguments) === false) {
8568 this.cancel();
8569 }
8570 },
8571
8572 _uiHash: function(_inst) {
8573 var inst = _inst || this;
8574 return {
8575 helper: inst.helper,
8576 placeholder: inst.placeholder || $([]),
8577 position: inst.position,
8578 originalPosition: inst.originalPosition,
8579 offset: inst.positionAbs,
8580 item: inst.currentItem,
8581 sender: _inst ? _inst.element : null
8582 };
8583 }
8584
8585 });
8586
8587 })(jQuery);
8588 (function( $, undefined ) {
8589
8590 var uid = 0,
8591 hideProps = {},
8592 showProps = {};
8593
8594 hideProps.height = hideProps.paddingTop = hideProps.paddingBottom =
8595 hideProps.borderTopWidth = hideProps.borderBottomWidth = "hide";
8596 showProps.height = showProps.paddingTop = showProps.paddingBottom =
8597 showProps.borderTopWidth = showProps.borderBottomWidth = "show";
8598
8599 $.widget( "ui.accordion", {
8600 version: "1.10.3",
8601 options: {
8602 active: 0,
8603 animate: {},
8604 collapsible: false,
8605 event: "click",
8606 header: "> li > :first-child,> :not(li):even",
8607 heightStyle: "auto",
8608 icons: {
8609 activeHeader: "ui-icon-triangle-1-s",
8610 header: "ui-icon-triangle-1-e"
8611 },
8612
8613 // callbacks
8614 activate: null,
8615 beforeActivate: null
8616 },
8617
8618 _create: function() {
8619 var options = this.options;
8620 this.prevShow = this.prevHide = $();
8621 this.element.addClass( "ui-accordion ui-widget ui-helper-reset" )
8622 // ARIA
8623 .attr( "role", "tablist" );
8624
8625 // don't allow collapsible: false and active: false / null
8626 if ( !options.collapsible && (options.active === false || options.active == null) ) {
8627 options.active = 0;
8628 }
8629
8630 this._processPanels();
8631 // handle negative values
8632 if ( options.active < 0 ) {
8633 options.active += this.headers.length;
8634 }
8635 this._refresh();
8636 },
8637
8638 _getCreateEventData: function() {
8639 return {
8640 header: this.active,
8641 panel: !this.active.length ? $() : this.active.next(),
8642 content: !this.active.length ? $() : this.active.next()
8643 };
8644 },
8645
8646 _createIcons: function() {
8647 var icons = this.options.icons;
8648 if ( icons ) {
8649 $( "<span>" )
8650 .addClass( "ui-accordion-header-icon ui-icon " + icons.header )
8651 .prependTo( this.headers );
8652 this.active.children( ".ui-accordion-header-icon" )
8653 .removeClass( icons.header )
8654 .addClass( icons.activeHeader );
8655 this.headers.addClass( "ui-accordion-icons" );
8656 }
8657 },
8658
8659 _destroyIcons: function() {
8660 this.headers
8661 .removeClass( "ui-accordion-icons" )
8662 .children( ".ui-accordion-header-icon" )
8663 .remove();
8664 },
8665
8666 _destroy: function() {
8667 var contents;
8668
8669 // clean up main element
8670 this.element
8671 .removeClass( "ui-accordion ui-widget ui-helper-reset" )
8672 .removeAttr( "role" );
8673
8674 // clean up headers
8675 this.headers
8676 .removeClass( "ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top" )
8677 .removeAttr( "role" )
8678 .removeAttr( "aria-selected" )
8679 .removeAttr( "aria-controls" )
8680 .removeAttr( "tabIndex" )
8681 .each(function() {
8682 if ( /^ui-accordion/.test( this.id ) ) {
8683 this.removeAttribute( "id" );
8684 }
8685 });
8686 this._destroyIcons();
8687
8688 // clean up content panels
8689 contents = this.headers.next()
8690 .css( "display", "" )
8691 .removeAttr( "role" )
8692 .removeAttr( "aria-expanded" )
8693 .removeAttr( "aria-hidden" )
8694 .removeAttr( "aria-labelledby" )
8695 .removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled" )
8696 .each(function() {
8697 if ( /^ui-accordion/.test( this.id ) ) {
8698 this.removeAttribute( "id" );
8699 }
8700 });
8701 if ( this.options.heightStyle !== "content" ) {
8702 contents.css( "height", "" );
8703 }
8704 },
8705
8706 _setOption: function( key, value ) {
8707 if ( key === "active" ) {
8708 // _activate() will handle invalid values and update this.options
8709 this._activate( value );
8710 return;
8711 }
8712
8713 if ( key === "event" ) {
8714 if ( this.options.event ) {
8715 this._off( this.headers, this.options.event );
8716 }
8717 this._setupEvents( value );
8718 }
8719
8720 this._super( key, value );
8721
8722 // setting collapsible: false while collapsed; open first panel
8723 if ( key === "collapsible" && !value && this.options.active === false ) {
8724 this._activate( 0 );
8725 }
8726
8727 if ( key === "icons" ) {
8728 this._destroyIcons();
8729 if ( value ) {
8730 this._createIcons();
8731 }
8732 }
8733
8734 // #5332 - opacity doesn't cascade to positioned elements in IE
8735 // so we need to add the disabled class to the headers and panels
8736 if ( key === "disabled" ) {
8737 this.headers.add( this.headers.next() )
8738 .toggleClass( "ui-state-disabled", !!value );
8739 }
8740 },
8741
8742 _keydown: function( event ) {
8743 /*jshint maxcomplexity:15*/
8744 if ( event.altKey || event.ctrlKey ) {
8745 return;
8746 }
8747
8748 var keyCode = $.ui.keyCode,
8749 length = this.headers.length,
8750 currentIndex = this.headers.index( event.target ),
8751 toFocus = false;
8752
8753 switch ( event.keyCode ) {
8754 case keyCode.RIGHT:
8755 case keyCode.DOWN:
8756 toFocus = this.headers[ ( currentIndex + 1 ) % length ];
8757 break;
8758 case keyCode.LEFT:
8759 case keyCode.UP:
8760 toFocus = this.headers[ ( currentIndex - 1 + length ) % length ];
8761 break;
8762 case keyCode.SPACE:
8763 case keyCode.ENTER:
8764 this._eventHandler( event );
8765 break;
8766 case keyCode.HOME:
8767 toFocus = this.headers[ 0 ];
8768 break;
8769 case keyCode.END:
8770 toFocus = this.headers[ length - 1 ];
8771 break;
8772 }
8773
8774 if ( toFocus ) {
8775 $( event.target ).attr( "tabIndex", -1 );
8776 $( toFocus ).attr( "tabIndex", 0 );
8777 toFocus.focus();
8778 event.preventDefault();
8779 }
8780 },
8781
8782 _panelKeyDown : function( event ) {
8783 if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) {
8784 $( event.currentTarget ).prev().focus();
8785 }
8786 },
8787
8788 refresh: function() {
8789 var options = this.options;
8790 this._processPanels();
8791
8792 // was collapsed or no panel
8793 if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) {
8794 options.active = false;
8795 this.active = $();
8796 // active false only when collapsible is true
8797 } else if ( options.active === false ) {
8798 this._activate( 0 );
8799 // was active, but active panel is gone
8800 } else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
8801 // all remaining panel are disabled
8802 if ( this.headers.length === this.headers.find(".ui-state-disabled").length ) {
8803 options.active = false;
8804 this.active = $();
8805 // activate previous panel
8806 } else {
8807 this._activate( Math.max( 0, options.active - 1 ) );
8808 }
8809 // was active, active panel still exists
8810 } else {
8811 // make sure active index is correct
8812 options.active = this.headers.index( this.active );
8813 }
8814
8815 this._destroyIcons();
8816
8817 this._refresh();
8818 },
8819
8820 _processPanels: function() {
8821 this.headers = this.element.find( this.options.header )
8822 .addClass( "ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" );
8823
8824 this.headers.next()
8825 .addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" )
8826 .filter(":not(.ui-accordion-content-active)")
8827 .hide();
8828 },
8829
8830 _refresh: function() {
8831 var maxHeight,
8832 options = this.options,
8833 heightStyle = options.heightStyle,
8834 parent = this.element.parent(),
8835 accordionId = this.accordionId = "ui-accordion-" +
8836 (this.element.attr( "id" ) || ++uid);
8837
8838 this.active = this._findActive( options.active )
8839 .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" )
8840 .removeClass( "ui-corner-all" );
8841 this.active.next()
8842 .addClass( "ui-accordion-content-active" )
8843 .show();
8844
8845 this.headers
8846 .attr( "role", "tab" )
8847 .each(function( i ) {
8848 var header = $( this ),
8849 headerId = header.attr( "id" ),
8850 panel = header.next(),
8851 panelId = panel.attr( "id" );
8852 if ( !headerId ) {
8853 headerId = accordionId + "-header-" + i;
8854 header.attr( "id", headerId );
8855 }
8856 if ( !panelId ) {
8857 panelId = accordionId + "-panel-" + i;
8858 panel.attr( "id", panelId );
8859 }
8860 header.attr( "aria-controls", panelId );
8861 panel.attr( "aria-labelledby", headerId );
8862 })
8863 .next()
8864 .attr( "role", "tabpanel" );
8865
8866 this.headers
8867 .not( this.active )
8868 .attr({
8869 "aria-selected": "false",
8870 tabIndex: -1
8871 })
8872 .next()
8873 .attr({
8874 "aria-expanded": "false",
8875 "aria-hidden": "true"
8876 })
8877 .hide();
8878
8879 // make sure at least one header is in the tab order
8880 if ( !this.active.length ) {
8881 this.headers.eq( 0 ).attr( "tabIndex", 0 );
8882 } else {
8883 this.active.attr({
8884 "aria-selected": "true",
8885 tabIndex: 0
8886 })
8887 .next()
8888 .attr({
8889 "aria-expanded": "true",
8890 "aria-hidden": "false"
8891 });
8892 }
8893
8894 this._createIcons();
8895
8896 this._setupEvents( options.event );
8897
8898 if ( heightStyle === "fill" ) {
8899 maxHeight = parent.height();
8900 this.element.siblings( ":visible" ).each(function() {
8901 var elem = $( this ),
8902 position = elem.css( "position" );
8903
8904 if ( position === "absolute" || position === "fixed" ) {
8905 return;
8906 }
8907 maxHeight -= elem.outerHeight( true );
8908 });
8909
8910 this.headers.each(function() {
8911 maxHeight -= $( this ).outerHeight( true );
8912 });
8913
8914 this.headers.next()
8915 .each(function() {
8916 $( this ).height( Math.max( 0, maxHeight -
8917 $( this ).innerHeight() + $( this ).height() ) );
8918 })
8919 .css( "overflow", "auto" );
8920 } else if ( heightStyle === "auto" ) {
8921 maxHeight = 0;
8922 this.headers.next()
8923 .each(function() {
8924 maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() );
8925 })
8926 .height( maxHeight );
8927 }
8928 },
8929
8930 _activate: function( index ) {
8931 var active = this._findActive( index )[ 0 ];
8932
8933 // trying to activate the already active panel
8934 if ( active === this.active[ 0 ] ) {
8935 return;
8936 }
8937
8938 // trying to collapse, simulate a click on the currently active header
8939 active = active || this.active[ 0 ];
8940
8941 this._eventHandler({
8942 target: active,
8943 currentTarget: active,
8944 preventDefault: $.noop
8945 });
8946 },
8947
8948 _findActive: function( selector ) {
8949 return typeof selector === "number" ? this.headers.eq( selector ) : $();
8950 },
8951
8952 _setupEvents: function( event ) {
8953 var events = {
8954 keydown: "_keydown"
8955 };
8956 if ( event ) {
8957 $.each( event.split(" "), function( index, eventName ) {
8958 events[ eventName ] = "_eventHandler";
8959 });
8960 }
8961
8962 this._off( this.headers.add( this.headers.next() ) );
8963 this._on( this.headers, events );
8964 this._on( this.headers.next(), { keydown: "_panelKeyDown" });
8965 this._hoverable( this.headers );
8966 this._focusable( this.headers );
8967 },
8968
8969 _eventHandler: function( event ) {
8970 var options = this.options,
8971 active = this.active,
8972 clicked = $( event.currentTarget ),
8973 clickedIsActive = clicked[ 0 ] === active[ 0 ],
8974 collapsing = clickedIsActive && options.collapsible,
8975 toShow = collapsing ? $() : clicked.next(),
8976 toHide = active.next(),
8977 eventData = {
8978 oldHeader: active,
8979 oldPanel: toHide,
8980 newHeader: collapsing ? $() : clicked,
8981 newPanel: toShow
8982 };
8983
8984 event.preventDefault();
8985
8986 if (
8987 // click on active header, but not collapsible
8988 ( clickedIsActive && !options.collapsible ) ||
8989 // allow canceling activation
8990 ( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
8991 return;
8992 }
8993
8994 options.active = collapsing ? false : this.headers.index( clicked );
8995
8996 // when the call to ._toggle() comes after the class changes
8997 // it causes a very odd bug in IE 8 (see #6720)
8998 this.active = clickedIsActive ? $() : clicked;
8999 this._toggle( eventData );
9000
9001 // switch classes
9002 // corner classes on the previously active header stay after the animation
9003 active.removeClass( "ui-accordion-header-active ui-state-active" );
9004 if ( options.icons ) {
9005 active.children( ".ui-accordion-header-icon" )
9006 .removeClass( options.icons.activeHeader )
9007 .addClass( options.icons.header );
9008 }
9009
9010 if ( !clickedIsActive ) {
9011 clicked
9012 .removeClass( "ui-corner-all" )
9013 .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" );
9014 if ( options.icons ) {
9015 clicked.children( ".ui-accordion-header-icon" )
9016 .removeClass( options.icons.header )
9017 .addClass( options.icons.activeHeader );
9018 }
9019
9020 clicked
9021 .next()
9022 .addClass( "ui-accordion-content-active" );
9023 }
9024 },
9025
9026 _toggle: function( data ) {
9027 var toShow = data.newPanel,
9028 toHide = this.prevShow.length ? this.prevShow : data.oldPanel;
9029
9030 // handle activating a panel during the animation for another activation
9031 this.prevShow.add( this.prevHide ).stop( true, true );
9032 this.prevShow = toShow;
9033 this.prevHide = toHide;
9034
9035 if ( this.options.animate ) {
9036 this._animate( toShow, toHide, data );
9037 } else {
9038 toHide.hide();
9039 toShow.show();
9040 this._toggleComplete( data );
9041 }
9042
9043 toHide.attr({
9044 "aria-expanded": "false",
9045 "aria-hidden": "true"
9046 });
9047 toHide.prev().attr( "aria-selected", "false" );
9048 // if we're switching panels, remove the old header from the tab order
9049 // if we're opening from collapsed state, remove the previous header from the tab order
9050 // if we're collapsing, then keep the collapsing header in the tab order
9051 if ( toShow.length && toHide.length ) {
9052 toHide.prev().attr( "tabIndex", -1 );
9053 } else if ( toShow.length ) {
9054 this.headers.filter(function() {
9055 return $( this ).attr( "tabIndex" ) === 0;
9056 })
9057 .attr( "tabIndex", -1 );
9058 }
9059
9060 toShow
9061 .attr({
9062 "aria-expanded": "true",
9063 "aria-hidden": "false"
9064 })
9065 .prev()
9066 .attr({
9067 "aria-selected": "true",
9068 tabIndex: 0
9069 });
9070 },
9071
9072 _animate: function( toShow, toHide, data ) {
9073 var total, easing, duration,
9074 that = this,
9075 adjust = 0,
9076 down = toShow.length &&
9077 ( !toHide.length || ( toShow.index() < toHide.index() ) ),
9078 animate = this.options.animate || {},
9079 options = down && animate.down || animate,
9080 complete = function() {
9081 that._toggleComplete( data );
9082 };
9083
9084 if ( typeof options === "number" ) {
9085 duration = options;
9086 }
9087 if ( typeof options === "string" ) {
9088 easing = options;
9089 }
9090 // fall back from options to animation in case of partial down settings
9091 easing = easing || options.easing || animate.easing;
9092 duration = duration || options.duration || animate.duration;
9093
9094 if ( !toHide.length ) {
9095 return toShow.animate( showProps, duration, easing, complete );
9096 }
9097 if ( !toShow.length ) {
9098 return toHide.animate( hideProps, duration, easing, complete );
9099 }
9100
9101 total = toShow.show().outerHeight();
9102 toHide.animate( hideProps, {
9103 duration: duration,
9104 easing: easing,
9105 step: function( now, fx ) {
9106 fx.now = Math.round( now );
9107 }
9108 });
9109 toShow
9110 .hide()
9111 .animate( showProps, {
9112 duration: duration,
9113 easing: easing,
9114 complete: complete,
9115 step: function( now, fx ) {
9116 fx.now = Math.round( now );
9117 if ( fx.prop !== "height" ) {
9118 adjust += fx.now;
9119 } else if ( that.options.heightStyle !== "content" ) {
9120 fx.now = Math.round( total - toHide.outerHeight() - adjust );
9121 adjust = 0;
9122 }
9123 }
9124 });
9125 },
9126
9127 _toggleComplete: function( data ) {
9128 var toHide = data.oldPanel;
9129
9130 toHide
9131 .removeClass( "ui-accordion-content-active" )
9132 .prev()
9133 .removeClass( "ui-corner-top" )
9134 .addClass( "ui-corner-all" );
9135
9136 // Work around for rendering bug in IE (#5421)
9137 if ( toHide.length ) {
9138 toHide.parent()[0].className = toHide.parent()[0].className;
9139 }
9140
9141 this._trigger( "activate", null, data );
9142 }
9143 });
9144
9145 })( jQuery );
9146 (function( $, undefined ) {
9147
9148 // used to prevent race conditions with remote data sources
9149 var requestIndex = 0;
9150
9151 $.widget( "ui.autocomplete", {
9152 version: "1.10.3",
9153 defaultElement: "<input>",
9154 options: {
9155 appendTo: null,
9156 autoFocus: false,
9157 delay: 300,
9158 minLength: 1,
9159 position: {
9160 my: "left top",
9161 at: "left bottom",
9162 collision: "none"
9163 },
9164 source: null,
9165
9166 // callbacks
9167 change: null,
9168 close: null,
9169 focus: null,
9170 open: null,
9171 response: null,
9172 search: null,
9173 select: null
9174 },
9175
9176 pending: 0,
9177
9178 _create: function() {
9179 // Some browsers only repeat keydown events, not keypress events,
9180 // so we use the suppressKeyPress flag to determine if we've already
9181 // handled the keydown event. #7269
9182 // Unfortunately the code for & in keypress is the same as the up arrow,
9183 // so we use the suppressKeyPressRepeat flag to avoid handling keypress
9184 // events when we know the keydown event was used to modify the
9185 // search term. #7799
9186 var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
9187 nodeName = this.element[0].nodeName.toLowerCase(),
9188 isTextarea = nodeName === "textarea",
9189 isInput = nodeName === "input";
9190
9191 this.isMultiLine =
9192 // Textareas are always multi-line
9193 isTextarea ? true :
9194 // Inputs are always single-line, even if inside a contentEditable element
9195 // IE also treats inputs as contentEditable
9196 isInput ? false :
9197 // All other element types are determined by whether or not they're contentEditable
9198 this.element.prop( "isContentEditable" );
9199
9200 this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
9201 this.isNewMenu = true;
9202
9203 this.element
9204 .addClass( "ui-autocomplete-input" )
9205 .attr( "autocomplete", "off" );
9206
9207 this._on( this.element, {
9208 keydown: function( event ) {
9209 /*jshint maxcomplexity:15*/
9210 if ( this.element.prop( "readOnly" ) ) {
9211 suppressKeyPress = true;
9212 suppressInput = true;
9213 suppressKeyPressRepeat = true;
9214 return;
9215 }
9216
9217 suppressKeyPress = false;
9218 suppressInput = false;
9219 suppressKeyPressRepeat = false;
9220 var keyCode = $.ui.keyCode;
9221 switch( event.keyCode ) {
9222 case keyCode.PAGE_UP:
9223 suppressKeyPress = true;
9224 this._move( "previousPage", event );
9225 break;
9226 case keyCode.PAGE_DOWN:
9227 suppressKeyPress = true;
9228 this._move( "nextPage", event );
9229 break;
9230 case keyCode.UP:
9231 suppressKeyPress = true;
9232 this._keyEvent( "previous", event );
9233 break;
9234 case keyCode.DOWN:
9235 suppressKeyPress = true;
9236 this._keyEvent( "next", event );
9237 break;
9238 case keyCode.ENTER:
9239 case keyCode.NUMPAD_ENTER:
9240 // when menu is open and has focus
9241 if ( this.menu.active ) {
9242 // #6055 - Opera still allows the keypress to occur
9243 // which causes forms to submit
9244 suppressKeyPress = true;
9245 event.preventDefault();
9246 this.menu.select( event );
9247 }
9248 break;
9249 case keyCode.TAB:
9250 if ( this.menu.active ) {
9251 this.menu.select( event );
9252 }
9253 break;
9254 case keyCode.ESCAPE:
9255 if ( this.menu.element.is( ":visible" ) ) {
9256 this._value( this.term );
9257 this.close( event );
9258 // Different browsers have different default behavior for escape
9259 // Single press can mean undo or clear
9260 // Double press in IE means clear the whole form
9261 event.preventDefault();
9262 }
9263 break;
9264 default:
9265 suppressKeyPressRepeat = true;
9266 // search timeout should be triggered before the input value is changed
9267 this._searchTimeout( event );
9268 break;
9269 }
9270 },
9271 keypress: function( event ) {
9272 if ( suppressKeyPress ) {
9273 suppressKeyPress = false;
9274 if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
9275 event.preventDefault();
9276 }
9277 return;
9278 }
9279 if ( suppressKeyPressRepeat ) {
9280 return;
9281 }
9282
9283 // replicate some key handlers to allow them to repeat in Firefox and Opera
9284 var keyCode = $.ui.keyCode;
9285 switch( event.keyCode ) {
9286 case keyCode.PAGE_UP:
9287 this._move( "previousPage", event );
9288 break;
9289 case keyCode.PAGE_DOWN:
9290 this._move( "nextPage", event );
9291 break;
9292 case keyCode.UP:
9293 this._keyEvent( "previous", event );
9294 break;
9295 case keyCode.DOWN:
9296 this._keyEvent( "next", event );
9297 break;
9298 }
9299 },
9300 input: function( event ) {
9301 if ( suppressInput ) {
9302 suppressInput = false;
9303 event.preventDefault();
9304 return;
9305 }
9306 this._searchTimeout( event );
9307 },
9308 focus: function() {
9309 this.selectedItem = null;
9310 this.previous = this._value();
9311 },
9312 blur: function( event ) {
9313 if ( this.cancelBlur ) {
9314 delete this.cancelBlur;
9315 return;
9316 }
9317
9318 clearTimeout( this.searching );
9319 this.close( event );
9320 this._change( event );
9321 }
9322 });
9323
9324 this._initSource();
9325 this.menu = $( "<ul>" )
9326 .addClass( "ui-autocomplete ui-front" )
9327 .appendTo( this._appendTo() )
9328 .menu({
9329 // disable ARIA support, the live region takes care of that
9330 role: null
9331 })
9332 .hide()
9333 .data( "ui-menu" );
9334
9335 this._on( this.menu.element, {
9336 mousedown: function( event ) {
9337 // prevent moving focus out of the text field
9338 event.preventDefault();
9339
9340 // IE doesn't prevent moving focus even with event.preventDefault()
9341 // so we set a flag to know when we should ignore the blur event
9342 this.cancelBlur = true;
9343 this._delay(function() {
9344 delete this.cancelBlur;
9345 });
9346
9347 // clicking on the scrollbar causes focus to shift to the body
9348 // but we can't detect a mouseup or a click immediately afterward
9349 // so we have to track the next mousedown and close the menu if
9350 // the user clicks somewhere outside of the autocomplete
9351 var menuElement = this.menu.element[ 0 ];
9352 if ( !$( event.target ).closest( ".ui-menu-item" ).length ) {
9353 this._delay(function() {
9354 var that = this;
9355 this.document.one( "mousedown", function( event ) {
9356 if ( event.target !== that.element[ 0 ] &&
9357 event.target !== menuElement &&
9358 !$.contains( menuElement, event.target ) ) {
9359 that.close();
9360 }
9361 });
9362 });
9363 }
9364 },
9365 menufocus: function( event, ui ) {
9366 // support: Firefox
9367 // Prevent accidental activation of menu items in Firefox (#7024 #9118)
9368 if ( this.isNewMenu ) {
9369 this.isNewMenu = false;
9370 if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) {
9371 this.menu.blur();
9372
9373 this.document.one( "mousemove", function() {
9374 $( event.target ).trigger( event.originalEvent );
9375 });
9376
9377 return;
9378 }
9379 }
9380
9381 var item = ui.item.data( "ui-autocomplete-item" );
9382 if ( false !== this._trigger( "focus", event, { item: item } ) ) {
9383 // use value to match what will end up in the input, if it was a key event
9384 if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) {
9385 this._value( item.value );
9386 }
9387 } else {
9388 // Normally the input is populated with the item's value as the
9389 // menu is navigated, causing screen readers to notice a change and
9390 // announce the item. Since the focus event was canceled, this doesn't
9391 // happen, so we update the live region so that screen readers can
9392 // still notice the change and announce it.
9393 this.liveRegion.text( item.value );
9394 }
9395 },
9396 menuselect: function( event, ui ) {
9397 var item = ui.item.data( "ui-autocomplete-item" ),
9398 previous = this.previous;
9399
9400 // only trigger when focus was lost (click on menu)
9401 if ( this.element[0] !== this.document[0].activeElement ) {
9402 this.element.focus();
9403 this.previous = previous;
9404 // #6109 - IE triggers two focus events and the second
9405 // is asynchronous, so we need to reset the previous
9406 // term synchronously and asynchronously :-(
9407 this._delay(function() {
9408 this.previous = previous;
9409 this.selectedItem = item;
9410 });
9411 }
9412
9413 if ( false !== this._trigger( "select", event, { item: item } ) ) {
9414 this._value( item.value );
9415 }
9416 // reset the term after the select event
9417 // this allows custom select handling to work properly
9418 this.term = this._value();
9419
9420 this.close( event );
9421 this.selectedItem = item;
9422 }
9423 });
9424
9425 this.liveRegion = $( "<span>", {
9426 role: "status",
9427 "aria-live": "polite"
9428 })
9429 .addClass( "ui-helper-hidden-accessible" )
9430 .insertBefore( this.element );
9431
9432 // turning off autocomplete prevents the browser from remembering the
9433 // value when navigating through history, so we re-enable autocomplete
9434 // if the page is unloaded before the widget is destroyed. #7790
9435 this._on( this.window, {
9436 beforeunload: function() {
9437 this.element.removeAttr( "autocomplete" );
9438 }
9439 });
9440 },
9441
9442 _destroy: function() {
9443 clearTimeout( this.searching );
9444 this.element
9445 .removeClass( "ui-autocomplete-input" )
9446 .removeAttr( "autocomplete" );
9447 this.menu.element.remove();
9448 this.liveRegion.remove();
9449 },
9450
9451 _setOption: function( key, value ) {
9452 this._super( key, value );
9453 if ( key === "source" ) {
9454 this._initSource();
9455 }
9456 if ( key === "appendTo" ) {
9457 this.menu.element.appendTo( this._appendTo() );
9458 }
9459 if ( key === "disabled" && value && this.xhr ) {
9460 this.xhr.abort();
9461 }
9462 },
9463
9464 _appendTo: function() {
9465 var element = this.options.appendTo;
9466
9467 if ( element ) {
9468 element = element.jquery || element.nodeType ?
9469 $( element ) :
9470 this.document.find( element ).eq( 0 );
9471 }
9472
9473 if ( !element ) {
9474 element = this.element.closest( ".ui-front" );
9475 }
9476
9477 if ( !element.length ) {
9478 element = this.document[0].body;
9479 }
9480
9481 return element;
9482 },
9483
9484 _initSource: function() {
9485 var array, url,
9486 that = this;
9487 if ( $.isArray(this.options.source) ) {
9488 array = this.options.source;
9489 this.source = function( request, response ) {
9490 response( $.ui.autocomplete.filter( array, request.term ) );
9491 };
9492 } else if ( typeof this.options.source === "string" ) {
9493 url = this.options.source;
9494 this.source = function( request, response ) {
9495 if ( that.xhr ) {
9496 that.xhr.abort();
9497 }
9498 that.xhr = $.ajax({
9499 url: url,
9500 data: request,
9501 dataType: "json",
9502 success: function( data ) {
9503 response( data );
9504 },
9505 error: function() {
9506 response( [] );
9507 }
9508 });
9509 };
9510 } else {
9511 this.source = this.options.source;
9512 }
9513 },
9514
9515 _searchTimeout: function( event ) {
9516 clearTimeout( this.searching );
9517 this.searching = this._delay(function() {
9518 // only search if the value has changed
9519 if ( this.term !== this._value() ) {
9520 this.selectedItem = null;
9521 this.search( null, event );
9522 }
9523 }, this.options.delay );
9524 },
9525
9526 search: function( value, event ) {
9527 value = value != null ? value : this._value();
9528
9529 // always save the actual value, not the one passed as an argument
9530 this.term = this._value();
9531
9532 if ( value.length < this.options.minLength ) {
9533 return this.close( event );
9534 }
9535
9536 if ( this._trigger( "search", event ) === false ) {
9537 return;
9538 }
9539
9540 return this._search( value );
9541 },
9542
9543 _search: function( value ) {
9544 this.pending++;
9545 this.element.addClass( "ui-autocomplete-loading" );
9546 this.cancelSearch = false;
9547
9548 this.source( { term: value }, this._response() );
9549 },
9550
9551 _response: function() {
9552 var that = this,
9553 index = ++requestIndex;
9554
9555 return function( content ) {
9556 if ( index === requestIndex ) {
9557 that.__response( content );
9558 }
9559
9560 that.pending--;
9561 if ( !that.pending ) {
9562 that.element.removeClass( "ui-autocomplete-loading" );
9563 }
9564 };
9565 },
9566
9567 __response: function( content ) {
9568 if ( content ) {
9569 content = this._normalize( content );
9570 }
9571 this._trigger( "response", null, { content: content } );
9572 if ( !this.options.disabled && content && content.length && !this.cancelSearch ) {
9573 this._suggest( content );
9574 this._trigger( "open" );
9575 } else {
9576 // use ._close() instead of .close() so we don't cancel future searches
9577 this._close();
9578 }
9579 },
9580
9581 close: function( event ) {
9582 this.cancelSearch = true;
9583 this._close( event );
9584 },
9585
9586 _close: function( event ) {
9587 if ( this.menu.element.is( ":visible" ) ) {
9588 this.menu.element.hide();
9589 this.menu.blur();
9590 this.isNewMenu = true;
9591 this._trigger( "close", event );
9592 }
9593 },
9594
9595 _change: function( event ) {
9596 if ( this.previous !== this._value() ) {
9597 this._trigger( "change", event, { item: this.selectedItem } );
9598 }
9599 },
9600
9601 _normalize: function( items ) {
9602 // assume all items have the right format when the first item is complete
9603 if ( items.length && items[0].label && items[0].value ) {
9604 return items;
9605 }
9606 return $.map( items, function( item ) {
9607 if ( typeof item === "string" ) {
9608 return {
9609 label: item,
9610 value: item
9611 };
9612 }
9613 return $.extend({
9614 label: item.label || item.value,
9615 value: item.value || item.label
9616 }, item );
9617 });
9618 },
9619
9620 _suggest: function( items ) {
9621 var ul = this.menu.element.empty();
9622 this._renderMenu( ul, items );
9623 this.isNewMenu = true;
9624 this.menu.refresh();
9625
9626 // size and position menu
9627 ul.show();
9628 this._resizeMenu();
9629 ul.position( $.extend({
9630 of: this.element
9631 }, this.options.position ));
9632
9633 if ( this.options.autoFocus ) {
9634 this.menu.next();
9635 }
9636 },
9637
9638 _resizeMenu: function() {
9639 var ul = this.menu.element;
9640 ul.outerWidth( Math.max(
9641 // Firefox wraps long text (possibly a rounding bug)
9642 // so we add 1px to avoid the wrapping (#7513)
9643 ul.width( "" ).outerWidth() + 1,
9644 this.element.outerWidth()
9645 ) );
9646 },
9647
9648 _renderMenu: function( ul, items ) {
9649 var that = this;
9650 $.each( items, function( index, item ) {
9651 that._renderItemData( ul, item );
9652 });
9653 },
9654
9655 _renderItemData: function( ul, item ) {
9656 return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
9657 },
9658
9659 _renderItem: function( ul, item ) {
9660 return $( "<li>" )
9661 .append( $( "<a>" ).text( item.label ) )
9662 .appendTo( ul );
9663 },
9664
9665 _move: function( direction, event ) {
9666 if ( !this.menu.element.is( ":visible" ) ) {
9667 this.search( null, event );
9668 return;
9669 }
9670 if ( this.menu.isFirstItem() && /^previous/.test( direction ) ||
9671 this.menu.isLastItem() && /^next/.test( direction ) ) {
9672 this._value( this.term );
9673 this.menu.blur();
9674 return;
9675 }
9676 this.menu[ direction ]( event );
9677 },
9678
9679 widget: function() {
9680 return this.menu.element;
9681 },
9682
9683 _value: function() {
9684 return this.valueMethod.apply( this.element, arguments );
9685 },
9686
9687 _keyEvent: function( keyEvent, event ) {
9688 if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
9689 this._move( keyEvent, event );
9690
9691 // prevents moving cursor to beginning/end of the text field in some browsers
9692 event.preventDefault();
9693 }
9694 }
9695 });
9696
9697 $.extend( $.ui.autocomplete, {
9698 escapeRegex: function( value ) {
9699 return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
9700 },
9701 filter: function(array, term) {
9702 var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
9703 return $.grep( array, function(value) {
9704 return matcher.test( value.label || value.value || value );
9705 });
9706 }
9707 });
9708
9709
9710 // live region extension, adding a `messages` option
9711 // NOTE: This is an experimental API. We are still investigating
9712 // a full solution for string manipulation and internationalization.
9713 $.widget( "ui.autocomplete", $.ui.autocomplete, {
9714 options: {
9715 messages: {
9716 noResults: "No search results.",
9717 results: function( amount ) {
9718 return amount + ( amount > 1 ? " results are" : " result is" ) +
9719 " available, use up and down arrow keys to navigate.";
9720 }
9721 }
9722 },
9723
9724 __response: function( content ) {
9725 var message;
9726 this._superApply( arguments );
9727 if ( this.options.disabled || this.cancelSearch ) {
9728 return;
9729 }
9730 if ( content && content.length ) {
9731 message = this.options.messages.results( content.length );
9732 } else {
9733 message = this.options.messages.noResults;
9734 }
9735 this.liveRegion.text( message );
9736 }
9737 });
9738
9739 }( jQuery ));
9740 (function( $, undefined ) {
9741
9742 var lastActive, startXPos, startYPos, clickDragged,
9743 baseClasses = "ui-button ui-widget ui-state-default ui-corner-all",
9744 stateClasses = "ui-state-hover ui-state-active ",
9745 typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",
9746 formResetHandler = function() {
9747 var form = $( this );
9748 setTimeout(function() {
9749 form.find( ":ui-button" ).button( "refresh" );
9750 }, 1 );
9751 },
9752 radioGroup = function( radio ) {
9753 var name = radio.name,
9754 form = radio.form,
9755 radios = $( [] );
9756 if ( name ) {
9757 name = name.replace( /'/g, "\\'" );
9758 if ( form ) {
9759 radios = $( form ).find( "[name='" + name + "']" );
9760 } else {
9761 radios = $( "[name='" + name + "']", radio.ownerDocument )
9762 .filter(function() {
9763 return !this.form;
9764 });
9765 }
9766 }
9767 return radios;
9768 };
9769
9770 $.widget( "ui.button", {
9771 version: "1.10.3",
9772 defaultElement: "<button>",
9773 options: {
9774 disabled: null,
9775 text: true,
9776 label: null,
9777 icons: {
9778 primary: null,
9779 secondary: null
9780 }
9781 },
9782 _create: function() {
9783 this.element.closest( "form" )
9784 .unbind( "reset" + this.eventNamespace )
9785 .bind( "reset" + this.eventNamespace, formResetHandler );
9786
9787 if ( typeof this.options.disabled !== "boolean" ) {
9788 this.options.disabled = !!this.element.prop( "disabled" );
9789 } else {
9790 this.element.prop( "disabled", this.options.disabled );
9791 }
9792
9793 this._determineButtonType();
9794 this.hasTitle = !!this.buttonElement.attr( "title" );
9795
9796 var that = this,
9797 options = this.options,
9798 toggleButton = this.type === "checkbox" || this.type === "radio",
9799 activeClass = !toggleButton ? "ui-state-active" : "",
9800 focusClass = "ui-state-focus";
9801
9802 if ( options.label === null ) {
9803 options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html());
9804 }
9805
9806 this._hoverable( this.buttonElement );
9807
9808 this.buttonElement
9809 .addClass( baseClasses )
9810 .attr( "role", "button" )
9811 .bind( "mouseenter" + this.eventNamespace, function() {
9812 if ( options.disabled ) {
9813 return;
9814 }
9815 if ( this === lastActive ) {
9816 $( this ).addClass( "ui-state-active" );
9817 }
9818 })
9819 .bind( "mouseleave" + this.eventNamespace, function() {
9820 if ( options.disabled ) {
9821 return;
9822 }
9823 $( this ).removeClass( activeClass );
9824 })
9825 .bind( "click" + this.eventNamespace, function( event ) {
9826 if ( options.disabled ) {
9827 event.preventDefault();
9828 event.stopImmediatePropagation();
9829 }
9830 });
9831
9832 this.element
9833 .bind( "focus" + this.eventNamespace, function() {
9834 // no need to check disabled, focus won't be triggered anyway
9835 that.buttonElement.addClass( focusClass );
9836 })
9837 .bind( "blur" + this.eventNamespace, function() {
9838 that.buttonElement.removeClass( focusClass );
9839 });
9840
9841 if ( toggleButton ) {
9842 this.element.bind( "change" + this.eventNamespace, function() {
9843 if ( clickDragged ) {
9844 return;
9845 }
9846 that.refresh();
9847 });
9848 // if mouse moves between mousedown and mouseup (drag) set clickDragged flag
9849 // prevents issue where button state changes but checkbox/radio checked state
9850 // does not in Firefox (see ticket #6970)
9851 this.buttonElement
9852 .bind( "mousedown" + this.eventNamespace, function( event ) {
9853 if ( options.disabled ) {
9854 return;
9855 }
9856 clickDragged = false;
9857 startXPos = event.pageX;
9858 startYPos = event.pageY;
9859 })
9860 .bind( "mouseup" + this.eventNamespace, function( event ) {
9861 if ( options.disabled ) {
9862 return;
9863 }
9864 if ( startXPos !== event.pageX || startYPos !== event.pageY ) {
9865 clickDragged = true;
9866 }
9867 });
9868 }
9869
9870 if ( this.type === "checkbox" ) {
9871 this.buttonElement.bind( "click" + this.eventNamespace, function() {
9872 if ( options.disabled || clickDragged ) {
9873 return false;
9874 }
9875 });
9876 } else if ( this.type === "radio" ) {
9877 this.buttonElement.bind( "click" + this.eventNamespace, function() {
9878 if ( options.disabled || clickDragged ) {
9879 return false;
9880 }
9881 $( this ).addClass( "ui-state-active" );
9882 that.buttonElement.attr( "aria-pressed", "true" );
9883
9884 var radio = that.element[ 0 ];
9885 radioGroup( radio )
9886 .not( radio )
9887 .map(function() {
9888 return $( this ).button( "widget" )[ 0 ];
9889 })
9890 .removeClass( "ui-state-active" )
9891 .attr( "aria-pressed", "false" );
9892 });
9893 } else {
9894 this.buttonElement
9895 .bind( "mousedown" + this.eventNamespace, function() {
9896 if ( options.disabled ) {
9897 return false;
9898 }
9899 $( this ).addClass( "ui-state-active" );
9900 lastActive = this;
9901 that.document.one( "mouseup", function() {
9902 lastActive = null;
9903 });
9904 })
9905 .bind( "mouseup" + this.eventNamespace, function() {
9906 if ( options.disabled ) {
9907 return false;
9908 }
9909 $( this ).removeClass( "ui-state-active" );
9910 })
9911 .bind( "keydown" + this.eventNamespace, function(event) {
9912 if ( options.disabled ) {
9913 return false;
9914 }
9915 if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) {
9916 $( this ).addClass( "ui-state-active" );
9917 }
9918 })
9919 // see #8559, we bind to blur here in case the button element loses
9920 // focus between keydown and keyup, it would be left in an "active" state
9921 .bind( "keyup" + this.eventNamespace + " blur" + this.eventNamespace, function() {
9922 $( this ).removeClass( "ui-state-active" );
9923 });
9924
9925 if ( this.buttonElement.is("a") ) {
9926 this.buttonElement.keyup(function(event) {
9927 if ( event.keyCode === $.ui.keyCode.SPACE ) {
9928 // TODO pass through original event correctly (just as 2nd argument doesn't work)
9929 $( this ).click();
9930 }
9931 });
9932 }
9933 }
9934
9935 // TODO: pull out $.Widget's handling for the disabled option into
9936 // $.Widget.prototype._setOptionDisabled so it's easy to proxy and can
9937 // be overridden by individual plugins
9938 this._setOption( "disabled", options.disabled );
9939 this._resetButton();
9940 },
9941
9942 _determineButtonType: function() {
9943 var ancestor, labelSelector, checked;
9944
9945 if ( this.element.is("[type=checkbox]") ) {
9946 this.type = "checkbox";
9947 } else if ( this.element.is("[type=radio]") ) {
9948 this.type = "radio";
9949 } else if ( this.element.is("input") ) {
9950 this.type = "input";
9951 } else {
9952 this.type = "button";
9953 }
9954
9955 if ( this.type === "checkbox" || this.type === "radio" ) {
9956 // we don't search against the document in case the element
9957 // is disconnected from the DOM
9958 ancestor = this.element.parents().last();
9959 labelSelector = "label[for='" + this.element.attr("id") + "']";
9960 this.buttonElement = ancestor.find( labelSelector );
9961 if ( !this.buttonElement.length ) {
9962 ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings();
9963 this.buttonElement = ancestor.filter( labelSelector );
9964 if ( !this.buttonElement.length ) {
9965 this.buttonElement = ancestor.find( labelSelector );
9966 }
9967 }
9968 this.element.addClass( "ui-helper-hidden-accessible" );
9969
9970 checked = this.element.is( ":checked" );
9971 if ( checked ) {
9972 this.buttonElement.addClass( "ui-state-active" );
9973 }
9974 this.buttonElement.prop( "aria-pressed", checked );
9975 } else {
9976 this.buttonElement = this.element;
9977 }
9978 },
9979
9980 widget: function() {
9981 return this.buttonElement;
9982 },
9983
9984 _destroy: function() {
9985 this.element
9986 .removeClass( "ui-helper-hidden-accessible" );
9987 this.buttonElement
9988 .removeClass( baseClasses + " " + stateClasses + " " + typeClasses )
9989 .removeAttr( "role" )
9990 .removeAttr( "aria-pressed" )
9991 .html( this.buttonElement.find(".ui-button-text").html() );
9992
9993 if ( !this.hasTitle ) {
9994 this.buttonElement.removeAttr( "title" );
9995 }
9996 },
9997
9998 _setOption: function( key, value ) {
9999 this._super( key, value );
10000 if ( key === "disabled" ) {
10001 if ( value ) {
10002 this.element.prop( "disabled", true );
10003 } else {
10004 this.element.prop( "disabled", false );
10005 }
10006 return;
10007 }
10008 this._resetButton();
10009 },
10010
10011 refresh: function() {
10012 //See #8237 & #8828
10013 var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "ui-button-disabled" );
10014
10015 if ( isDisabled !== this.options.disabled ) {
10016 this._setOption( "disabled", isDisabled );
10017 }
10018 if ( this.type === "radio" ) {
10019 radioGroup( this.element[0] ).each(function() {
10020 if ( $( this ).is( ":checked" ) ) {
10021 $( this ).button( "widget" )
10022 .addClass( "ui-state-active" )
10023 .attr( "aria-pressed", "true" );
10024 } else {
10025 $( this ).button( "widget" )
10026 .removeClass( "ui-state-active" )
10027 .attr( "aria-pressed", "false" );
10028 }
10029 });
10030 } else if ( this.type === "checkbox" ) {
10031 if ( this.element.is( ":checked" ) ) {
10032 this.buttonElement
10033 .addClass( "ui-state-active" )
10034 .attr( "aria-pressed", "true" );
10035 } else {
10036 this.buttonElement
10037 .removeClass( "ui-state-active" )
10038 .attr( "aria-pressed", "false" );
10039 }
10040 }
10041 },
10042
10043 _resetButton: function() {
10044 if ( this.type === "input" ) {
10045 if ( this.options.label ) {
10046 this.element.val( this.options.label );
10047 }
10048 return;
10049 }
10050 var buttonElement = this.buttonElement.removeClass( typeClasses ),
10051 buttonText = $( "<span></span>", this.document[0] )
10052 .addClass( "ui-button-text" )
10053 .html( this.options.label )
10054 .appendTo( buttonElement.empty() )
10055 .text(),
10056 icons = this.options.icons,
10057 multipleIcons = icons.primary && icons.secondary,
10058 buttonClasses = [];
10059
10060 if ( icons.primary || icons.secondary ) {
10061 if ( this.options.text ) {
10062 buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) );
10063 }
10064
10065 if ( icons.primary ) {
10066 buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" );
10067 }
10068
10069 if ( icons.secondary ) {
10070 buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" );
10071 }
10072
10073 if ( !this.options.text ) {
10074 buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" );
10075
10076 if ( !this.hasTitle ) {
10077 buttonElement.attr( "title", $.trim( buttonText ) );
10078 }
10079 }
10080 } else {
10081 buttonClasses.push( "ui-button-text-only" );
10082 }
10083 buttonElement.addClass( buttonClasses.join( " " ) );
10084 }
10085 });
10086
10087 $.widget( "ui.buttonset", {
10088 version: "1.10.3",
10089 options: {
10090 items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"
10091 },
10092
10093 _create: function() {
10094 this.element.addClass( "ui-buttonset" );
10095 },
10096
10097 _init: function() {
10098 this.refresh();
10099 },
10100
10101 _setOption: function( key, value ) {
10102 if ( key === "disabled" ) {
10103 this.buttons.button( "option", key, value );
10104 }
10105
10106 this._super( key, value );
10107 },
10108
10109 refresh: function() {
10110 var rtl = this.element.css( "direction" ) === "rtl";
10111
10112 this.buttons = this.element.find( this.options.items )
10113 .filter( ":ui-button" )
10114 .button( "refresh" )
10115 .end()
10116 .not( ":ui-button" )
10117 .button()
10118 .end()
10119 .map(function() {
10120 return $( this ).button( "widget" )[ 0 ];
10121 })
10122 .removeClass( "ui-corner-all ui-corner-left ui-corner-right" )
10123 .filter( ":first" )
10124 .addClass( rtl ? "ui-corner-right" : "ui-corner-left" )
10125 .end()
10126 .filter( ":last" )
10127 .addClass( rtl ? "ui-corner-left" : "ui-corner-right" )
10128 .end()
10129 .end();
10130 },
10131
10132 _destroy: function() {
10133 this.element.removeClass( "ui-buttonset" );
10134 this.buttons
10135 .map(function() {
10136 return $( this ).button( "widget" )[ 0 ];
10137 })
10138 .removeClass( "ui-corner-left ui-corner-right" )
10139 .end()
10140 .button( "destroy" );
10141 }
10142 });
10143
10144 }( jQuery ) );
10145 (function( $, undefined ) {
10146
10147 $.extend($.ui, { datepicker: { version: "1.10.3" } });
10148
10149 var PROP_NAME = "datepicker",
10150 instActive;
10151
10152 /* Date picker manager.
10153 Use the singleton instance of this class, $.datepicker, to interact with the date picker.
10154 Settings for (groups of) date pickers are maintained in an instance object,
10155 allowing multiple different settings on the same page. */
10156
10157 function Datepicker() {
10158 this._curInst = null; // The current instance in use
10159 this._keyEvent = false; // If the last event was a key event
10160 this._disabledInputs = []; // List of date picker inputs that have been disabled
10161 this._datepickerShowing = false; // True if the popup picker is showing , false if not
10162 this._inDialog = false; // True if showing within a "dialog", false if not
10163 this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
10164 this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
10165 this._appendClass = "ui-datepicker-append"; // The name of the append marker class
10166 this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
10167 this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
10168 this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
10169 this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
10170 this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
10171 this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
10172 this.regional = []; // Available regional settings, indexed by language code
10173 this.regional[""] = { // Default regional settings
10174 closeText: "Done", // Display text for close link
10175 prevText: "Prev", // Display text for previous month link
10176 nextText: "Next", // Display text for next month link
10177 currentText: "Today", // Display text for current month link
10178 monthNames: ["January","February","March","April","May","June",
10179 "July","August","September","October","November","December"], // Names of months for drop-down and formatting
10180 monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting
10181 dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting
10182 dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting
10183 dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday
10184 weekHeader: "Wk", // Column header for week of the year
10185 dateFormat: "mm/dd/yy", // See format options on parseDate
10186 firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
10187 isRTL: false, // True if right-to-left language, false if left-to-right
10188 showMonthAfterYear: false, // True if the year select precedes month, false for month then year
10189 yearSuffix: "" // Additional text to append to the year in the month headers
10190 };
10191 this._defaults = { // Global defaults for all the date picker instances
10192 showOn: "focus", // "focus" for popup on focus,
10193 // "button" for trigger button, or "both" for either
10194 showAnim: "fadeIn", // Name of jQuery animation for popup
10195 showOptions: {}, // Options for enhanced animations
10196 defaultDate: null, // Used when field is blank: actual date,
10197 // +/-number for offset from today, null for today
10198 appendText: "", // Display text following the input box, e.g. showing the format
10199 buttonText: "...", // Text for trigger button
10200 buttonImage: "", // URL for trigger button image
10201 buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
10202 hideIfNoPrevNext: false, // True to hide next/previous month links
10203 // if not applicable, false to just disable them
10204 navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
10205 gotoCurrent: false, // True if today link goes back to current selection instead
10206 changeMonth: false, // True if month can be selected directly, false if only prev/next
10207 changeYear: false, // True if year can be selected directly, false if only prev/next
10208 yearRange: "c-10:c+10", // Range of years to display in drop-down,
10209 // either relative to today's year (-nn:+nn), relative to currently displayed year
10210 // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
10211 showOtherMonths: false, // True to show dates in other months, false to leave blank
10212 selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
10213 showWeek: false, // True to show week of the year, false to not show it
10214 calculateWeek: this.iso8601Week, // How to calculate the week of the year,
10215 // takes a Date and returns the number of the week for it
10216 shortYearCutoff: "+10", // Short year values < this are in the current century,
10217 // > this are in the previous century,
10218 // string value starting with "+" for current year + value
10219 minDate: null, // The earliest selectable date, or null for no limit
10220 maxDate: null, // The latest selectable date, or null for no limit
10221 duration: "fast", // Duration of display/closure
10222 beforeShowDay: null, // Function that takes a date and returns an array with
10223 // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
10224 // [2] = cell title (optional), e.g. $.datepicker.noWeekends
10225 beforeShow: null, // Function that takes an input field and
10226 // returns a set of custom settings for the date picker
10227 onSelect: null, // Define a callback function when a date is selected
10228 onChangeMonthYear: null, // Define a callback function when the month or year is changed
10229 onClose: null, // Define a callback function when the datepicker is closed
10230 numberOfMonths: 1, // Number of months to show at a time
10231 showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
10232 stepMonths: 1, // Number of months to step back/forward
10233 stepBigMonths: 12, // Number of months to step back/forward for the big links
10234 altField: "", // Selector for an alternate field to store selected dates into
10235 altFormat: "", // The date format to use for the alternate field
10236 constrainInput: true, // The input is constrained by the current date format
10237 showButtonPanel: false, // True to show button panel, false to not show it
10238 autoSize: false, // True to size the input for the date format, false to leave as is
10239 disabled: false // The initial disabled state
10240 };
10241 $.extend(this._defaults, this.regional[""]);
10242 this.dpDiv = bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"));
10243 }
10244
10245 $.extend(Datepicker.prototype, {
10246 /* Class name added to elements to indicate already configured with a date picker. */
10247 markerClassName: "hasDatepicker",
10248
10249 //Keep track of the maximum number of rows displayed (see #7043)
10250 maxRows: 4,
10251
10252 // TODO rename to "widget" when switching to widget factory
10253 _widgetDatepicker: function() {
10254 return this.dpDiv;
10255 },
10256
10257 /* Override the default settings for all instances of the date picker.
10258 * @param settings object - the new settings to use as defaults (anonymous object)
10259 * @return the manager object
10260 */
10261 setDefaults: function(settings) {
10262 extendRemove(this._defaults, settings || {});
10263 return this;
10264 },
10265
10266 /* Attach the date picker to a jQuery selection.
10267 * @param target element - the target input field or division or span
10268 * @param settings object - the new settings to use for this date picker instance (anonymous)
10269 */
10270 _attachDatepicker: function(target, settings) {
10271 var nodeName, inline, inst;
10272 nodeName = target.nodeName.toLowerCase();
10273 inline = (nodeName === "div" || nodeName === "span");
10274 if (!target.id) {
10275 this.uuid += 1;
10276 target.id = "dp" + this.uuid;
10277 }
10278 inst = this._newInst($(target), inline);
10279 inst.settings = $.extend({}, settings || {});
10280 if (nodeName === "input") {
10281 this._connectDatepicker(target, inst);
10282 } else if (inline) {
10283 this._inlineDatepicker(target, inst);
10284 }
10285 },
10286
10287 /* Create a new instance object. */
10288 _newInst: function(target, inline) {
10289 var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars
10290 return {id: id, input: target, // associated target
10291 selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
10292 drawMonth: 0, drawYear: 0, // month being drawn
10293 inline: inline, // is datepicker inline or not
10294 dpDiv: (!inline ? this.dpDiv : // presentation div
10295 bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))};
10296 },
10297
10298 /* Attach the date picker to an input field. */
10299 _connectDatepicker: function(target, inst) {
10300 var input = $(target);
10301 inst.append = $([]);
10302 inst.trigger = $([]);
10303 if (input.hasClass(this.markerClassName)) {
10304 return;
10305 }
10306 this._attachments(input, inst);
10307 input.addClass(this.markerClassName).keydown(this._doKeyDown).
10308 keypress(this._doKeyPress).keyup(this._doKeyUp);
10309 this._autoSize(inst);
10310 $.data(target, PROP_NAME, inst);
10311 //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
10312 if( inst.settings.disabled ) {
10313 this._disableDatepicker( target );
10314 }
10315 },
10316
10317 /* Make attachments based on settings. */
10318 _attachments: function(input, inst) {
10319 var showOn, buttonText, buttonImage,
10320 appendText = this._get(inst, "appendText"),
10321 isRTL = this._get(inst, "isRTL");
10322
10323 if (inst.append) {
10324 inst.append.remove();
10325 }
10326 if (appendText) {
10327 inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>");
10328 input[isRTL ? "before" : "after"](inst.append);
10329 }
10330
10331 input.unbind("focus", this._showDatepicker);
10332
10333 if (inst.trigger) {
10334 inst.trigger.remove();
10335 }
10336
10337 showOn = this._get(inst, "showOn");
10338 if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field
10339 input.focus(this._showDatepicker);
10340 }
10341 if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked
10342 buttonText = this._get(inst, "buttonText");
10343 buttonImage = this._get(inst, "buttonImage");
10344 inst.trigger = $(this._get(inst, "buttonImageOnly") ?
10345 $("<img/>").addClass(this._triggerClass).
10346 attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
10347 $("<button type='button'></button>").addClass(this._triggerClass).
10348 html(!buttonImage ? buttonText : $("<img/>").attr(
10349 { src:buttonImage, alt:buttonText, title:buttonText })));
10350 input[isRTL ? "before" : "after"](inst.trigger);
10351 inst.trigger.click(function() {
10352 if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) {
10353 $.datepicker._hideDatepicker();
10354 } else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) {
10355 $.datepicker._hideDatepicker();
10356 $.datepicker._showDatepicker(input[0]);
10357 } else {
10358 $.datepicker._showDatepicker(input[0]);
10359 }
10360 return false;
10361 });
10362 }
10363 },
10364
10365 /* Apply the maximum length for the date format. */
10366 _autoSize: function(inst) {
10367 if (this._get(inst, "autoSize") && !inst.inline) {
10368 var findMax, max, maxI, i,
10369 date = new Date(2009, 12 - 1, 20), // Ensure double digits
10370 dateFormat = this._get(inst, "dateFormat");
10371
10372 if (dateFormat.match(/[DM]/)) {
10373 findMax = function(names) {
10374 max = 0;
10375 maxI = 0;
10376 for (i = 0; i < names.length; i++) {
10377 if (names[i].length > max) {
10378 max = names[i].length;
10379 maxI = i;
10380 }
10381 }
10382 return maxI;
10383 };
10384 date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
10385 "monthNames" : "monthNamesShort"))));
10386 date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
10387 "dayNames" : "dayNamesShort"))) + 20 - date.getDay());
10388 }
10389 inst.input.attr("size", this._formatDate(inst, date).length);
10390 }
10391 },
10392
10393 /* Attach an inline date picker to a div. */
10394 _inlineDatepicker: function(target, inst) {
10395 var divSpan = $(target);
10396 if (divSpan.hasClass(this.markerClassName)) {
10397 return;
10398 }
10399 divSpan.addClass(this.markerClassName).append(inst.dpDiv);
10400 $.data(target, PROP_NAME, inst);
10401 this._setDate(inst, this._getDefaultDate(inst), true);
10402 this._updateDatepicker(inst);
10403 this._updateAlternate(inst);
10404 //If disabled option is true, disable the datepicker before showing it (see ticket #5665)
10405 if( inst.settings.disabled ) {
10406 this._disableDatepicker( target );
10407 }
10408 // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
10409 // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
10410 inst.dpDiv.css( "display", "block" );
10411 },
10412
10413 /* Pop-up the date picker in a "dialog" box.
10414 * @param input element - ignored
10415 * @param date string or Date - the initial date to display
10416 * @param onSelect function - the function to call when a date is selected
10417 * @param settings object - update the dialog date picker instance's settings (anonymous object)
10418 * @param pos int[2] - coordinates for the dialog's position within the screen or
10419 * event - with x/y coordinates or
10420 * leave empty for default (screen centre)
10421 * @return the manager object
10422 */
10423 _dialogDatepicker: function(input, date, onSelect, settings, pos) {
10424 var id, browserWidth, browserHeight, scrollX, scrollY,
10425 inst = this._dialogInst; // internal instance
10426
10427 if (!inst) {
10428 this.uuid += 1;
10429 id = "dp" + this.uuid;
10430 this._dialogInput = $("<input type='text' id='" + id +
10431 "' style='position: absolute; top: -100px; width: 0px;'/>");
10432 this._dialogInput.keydown(this._doKeyDown);
10433 $("body").append(this._dialogInput);
10434 inst = this._dialogInst = this._newInst(this._dialogInput, false);
10435 inst.settings = {};
10436 $.data(this._dialogInput[0], PROP_NAME, inst);
10437 }
10438 extendRemove(inst.settings, settings || {});
10439 date = (date && date.constructor === Date ? this._formatDate(inst, date) : date);
10440 this._dialogInput.val(date);
10441
10442 this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
10443 if (!this._pos) {
10444 browserWidth = document.documentElement.clientWidth;
10445 browserHeight = document.documentElement.clientHeight;
10446 scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
10447 scrollY = document.documentElement.scrollTop || document.body.scrollTop;
10448 this._pos = // should use actual width/height below
10449 [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
10450 }
10451
10452 // move input on screen for focus, but hidden behind dialog
10453 this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px");
10454 inst.settings.onSelect = onSelect;
10455 this._inDialog = true;
10456 this.dpDiv.addClass(this._dialogClass);
10457 this._showDatepicker(this._dialogInput[0]);
10458 if ($.blockUI) {
10459 $.blockUI(this.dpDiv);
10460 }
10461 $.data(this._dialogInput[0], PROP_NAME, inst);
10462 return this;
10463 },
10464
10465 /* Detach a datepicker from its control.
10466 * @param target element - the target input field or division or span
10467 */
10468 _destroyDatepicker: function(target) {
10469 var nodeName,
10470 $target = $(target),
10471 inst = $.data(target, PROP_NAME);
10472
10473 if (!$target.hasClass(this.markerClassName)) {
10474 return;
10475 }
10476
10477 nodeName = target.nodeName.toLowerCase();
10478 $.removeData(target, PROP_NAME);
10479 if (nodeName === "input") {
10480 inst.append.remove();
10481 inst.trigger.remove();
10482 $target.removeClass(this.markerClassName).
10483 unbind("focus", this._showDatepicker).
10484 unbind("keydown", this._doKeyDown).
10485 unbind("keypress", this._doKeyPress).
10486 unbind("keyup", this._doKeyUp);
10487 } else if (nodeName === "div" || nodeName === "span") {
10488 $target.removeClass(this.markerClassName).empty();
10489 }
10490 },
10491
10492 /* Enable the date picker to a jQuery selection.
10493 * @param target element - the target input field or division or span
10494 */
10495 _enableDatepicker: function(target) {
10496 var nodeName, inline,
10497 $target = $(target),
10498 inst = $.data(target, PROP_NAME);
10499
10500 if (!$target.hasClass(this.markerClassName)) {
10501 return;
10502 }
10503
10504 nodeName = target.nodeName.toLowerCase();
10505 if (nodeName === "input") {
10506 target.disabled = false;
10507 inst.trigger.filter("button").
10508 each(function() { this.disabled = false; }).end().
10509 filter("img").css({opacity: "1.0", cursor: ""});
10510 } else if (nodeName === "div" || nodeName === "span") {
10511 inline = $target.children("." + this._inlineClass);
10512 inline.children().removeClass("ui-state-disabled");
10513 inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
10514 prop("disabled", false);
10515 }
10516 this._disabledInputs = $.map(this._disabledInputs,
10517 function(value) { return (value === target ? null : value); }); // delete entry
10518 },
10519
10520 /* Disable the date picker to a jQuery selection.
10521 * @param target element - the target input field or division or span
10522 */
10523 _disableDatepicker: function(target) {
10524 var nodeName, inline,
10525 $target = $(target),
10526 inst = $.data(target, PROP_NAME);
10527
10528 if (!$target.hasClass(this.markerClassName)) {
10529 return;
10530 }
10531
10532 nodeName = target.nodeName.toLowerCase();
10533 if (nodeName === "input") {
10534 target.disabled = true;
10535 inst.trigger.filter("button").
10536 each(function() { this.disabled = true; }).end().
10537 filter("img").css({opacity: "0.5", cursor: "default"});
10538 } else if (nodeName === "div" || nodeName === "span") {
10539 inline = $target.children("." + this._inlineClass);
10540 inline.children().addClass("ui-state-disabled");
10541 inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
10542 prop("disabled", true);
10543 }
10544 this._disabledInputs = $.map(this._disabledInputs,
10545 function(value) { return (value === target ? null : value); }); // delete entry
10546 this._disabledInputs[this._disabledInputs.length] = target;
10547 },
10548
10549 /* Is the first field in a jQuery collection disabled as a datepicker?
10550 * @param target element - the target input field or division or span
10551 * @return boolean - true if disabled, false if enabled
10552 */
10553 _isDisabledDatepicker: function(target) {
10554 if (!target) {
10555 return false;
10556 }
10557 for (var i = 0; i < this._disabledInputs.length; i++) {
10558 if (this._disabledInputs[i] === target) {
10559 return true;
10560 }
10561 }
10562 return false;
10563 },
10564
10565 /* Retrieve the instance data for the target control.
10566 * @param target element - the target input field or division or span
10567 * @return object - the associated instance data
10568 * @throws error if a jQuery problem getting data
10569 */
10570 _getInst: function(target) {
10571 try {
10572 return $.data(target, PROP_NAME);
10573 }
10574 catch (err) {
10575 throw "Missing instance data for this datepicker";
10576 }
10577 },
10578
10579 /* Update or retrieve the settings for a date picker attached to an input field or division.
10580 * @param target element - the target input field or division or span
10581 * @param name object - the new settings to update or
10582 * string - the name of the setting to change or retrieve,
10583 * when retrieving also "all" for all instance settings or
10584 * "defaults" for all global defaults
10585 * @param value any - the new value for the setting
10586 * (omit if above is an object or to retrieve a value)
10587 */
10588 _optionDatepicker: function(target, name, value) {
10589 var settings, date, minDate, maxDate,
10590 inst = this._getInst(target);
10591
10592 if (arguments.length === 2 && typeof name === "string") {
10593 return (name === "defaults" ? $.extend({}, $.datepicker._defaults) :
10594 (inst ? (name === "all" ? $.extend({}, inst.settings) :
10595 this._get(inst, name)) : null));
10596 }
10597
10598 settings = name || {};
10599 if (typeof name === "string") {
10600 settings = {};
10601 settings[name] = value;
10602 }
10603
10604 if (inst) {
10605 if (this._curInst === inst) {
10606 this._hideDatepicker();
10607 }
10608
10609 date = this._getDateDatepicker(target, true);
10610 minDate = this._getMinMaxDate(inst, "min");
10611 maxDate = this._getMinMaxDate(inst, "max");
10612 extendRemove(inst.settings, settings);
10613 // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
10614 if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) {
10615 inst.settings.minDate = this._formatDate(inst, minDate);
10616 }
10617 if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) {
10618 inst.settings.maxDate = this._formatDate(inst, maxDate);
10619 }
10620 if ( "disabled" in settings ) {
10621 if ( settings.disabled ) {
10622 this._disableDatepicker(target);
10623 } else {
10624 this._enableDatepicker(target);
10625 }
10626 }
10627 this._attachments($(target), inst);
10628 this._autoSize(inst);
10629 this._setDate(inst, date);
10630 this._updateAlternate(inst);
10631 this._updateDatepicker(inst);
10632 }
10633 },
10634
10635 // change method deprecated
10636 _changeDatepicker: function(target, name, value) {
10637 this._optionDatepicker(target, name, value);
10638 },
10639
10640 /* Redraw the date picker attached to an input field or division.
10641 * @param target element - the target input field or division or span
10642 */
10643 _refreshDatepicker: function(target) {
10644 var inst = this._getInst(target);
10645 if (inst) {
10646 this._updateDatepicker(inst);
10647 }
10648 },
10649
10650 /* Set the dates for a jQuery selection.
10651 * @param target element - the target input field or division or span
10652 * @param date Date - the new date
10653 */
10654 _setDateDatepicker: function(target, date) {
10655 var inst = this._getInst(target);
10656 if (inst) {
10657 this._setDate(inst, date);
10658 this._updateDatepicker(inst);
10659 this._updateAlternate(inst);
10660 }
10661 },
10662
10663 /* Get the date(s) for the first entry in a jQuery selection.
10664 * @param target element - the target input field or division or span
10665 * @param noDefault boolean - true if no default date is to be used
10666 * @return Date - the current date
10667 */
10668 _getDateDatepicker: function(target, noDefault) {
10669 var inst = this._getInst(target);
10670 if (inst && !inst.inline) {
10671 this._setDateFromField(inst, noDefault);
10672 }
10673 return (inst ? this._getDate(inst) : null);
10674 },
10675
10676 /* Handle keystrokes. */
10677 _doKeyDown: function(event) {
10678 var onSelect, dateStr, sel,
10679 inst = $.datepicker._getInst(event.target),
10680 handled = true,
10681 isRTL = inst.dpDiv.is(".ui-datepicker-rtl");
10682
10683 inst._keyEvent = true;
10684 if ($.datepicker._datepickerShowing) {
10685 switch (event.keyCode) {
10686 case 9: $.datepicker._hideDatepicker();
10687 handled = false;
10688 break; // hide on tab out
10689 case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." +
10690 $.datepicker._currentClass + ")", inst.dpDiv);
10691 if (sel[0]) {
10692 $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
10693 }
10694
10695 onSelect = $.datepicker._get(inst, "onSelect");
10696 if (onSelect) {
10697 dateStr = $.datepicker._formatDate(inst);
10698
10699 // trigger custom callback
10700 onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
10701 } else {
10702 $.datepicker._hideDatepicker();
10703 }
10704
10705 return false; // don't submit the form
10706 case 27: $.datepicker._hideDatepicker();
10707 break; // hide on escape
10708 case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
10709 -$.datepicker._get(inst, "stepBigMonths") :
10710 -$.datepicker._get(inst, "stepMonths")), "M");
10711 break; // previous month/year on page up/+ ctrl
10712 case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
10713 +$.datepicker._get(inst, "stepBigMonths") :
10714 +$.datepicker._get(inst, "stepMonths")), "M");
10715 break; // next month/year on page down/+ ctrl
10716 case 35: if (event.ctrlKey || event.metaKey) {
10717 $.datepicker._clearDate(event.target);
10718 }
10719 handled = event.ctrlKey || event.metaKey;
10720 break; // clear on ctrl or command +end
10721 case 36: if (event.ctrlKey || event.metaKey) {
10722 $.datepicker._gotoToday(event.target);
10723 }
10724 handled = event.ctrlKey || event.metaKey;
10725 break; // current on ctrl or command +home
10726 case 37: if (event.ctrlKey || event.metaKey) {
10727 $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D");
10728 }
10729 handled = event.ctrlKey || event.metaKey;
10730 // -1 day on ctrl or command +left
10731 if (event.originalEvent.altKey) {
10732 $.datepicker._adjustDate(event.target, (event.ctrlKey ?
10733 -$.datepicker._get(inst, "stepBigMonths") :
10734 -$.datepicker._get(inst, "stepMonths")), "M");
10735 }
10736 // next month/year on alt +left on Mac
10737 break;
10738 case 38: if (event.ctrlKey || event.metaKey) {
10739 $.datepicker._adjustDate(event.target, -7, "D");
10740 }
10741 handled = event.ctrlKey || event.metaKey;
10742 break; // -1 week on ctrl or command +up
10743 case 39: if (event.ctrlKey || event.metaKey) {
10744 $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D");
10745 }
10746 handled = event.ctrlKey || event.metaKey;
10747 // +1 day on ctrl or command +right
10748 if (event.originalEvent.altKey) {
10749 $.datepicker._adjustDate(event.target, (event.ctrlKey ?
10750 +$.datepicker._get(inst, "stepBigMonths") :
10751 +$.datepicker._get(inst, "stepMonths")), "M");
10752 }
10753 // next month/year on alt +right
10754 break;
10755 case 40: if (event.ctrlKey || event.metaKey) {
10756 $.datepicker._adjustDate(event.target, +7, "D");
10757 }
10758 handled = event.ctrlKey || event.metaKey;
10759 break; // +1 week on ctrl or command +down
10760 default: handled = false;
10761 }
10762 } else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home
10763 $.datepicker._showDatepicker(this);
10764 } else {
10765 handled = false;
10766 }
10767
10768 if (handled) {
10769 event.preventDefault();
10770 event.stopPropagation();
10771 }
10772 },
10773
10774 /* Filter entered characters - based on date format. */
10775 _doKeyPress: function(event) {
10776 var chars, chr,
10777 inst = $.datepicker._getInst(event.target);
10778
10779 if ($.datepicker._get(inst, "constrainInput")) {
10780 chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat"));
10781 chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode);
10782 return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1);
10783 }
10784 },
10785
10786 /* Synchronise manual entry and field/alternate field. */
10787 _doKeyUp: function(event) {
10788 var date,
10789 inst = $.datepicker._getInst(event.target);
10790
10791 if (inst.input.val() !== inst.lastVal) {
10792 try {
10793 date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
10794 (inst.input ? inst.input.val() : null),
10795 $.datepicker._getFormatConfig(inst));
10796
10797 if (date) { // only if valid
10798 $.datepicker._setDateFromField(inst);
10799 $.datepicker._updateAlternate(inst);
10800 $.datepicker._updateDatepicker(inst);
10801 }
10802 }
10803 catch (err) {
10804 }
10805 }
10806 return true;
10807 },
10808
10809 /* Pop-up the date picker for a given input field.
10810 * If false returned from beforeShow event handler do not show.
10811 * @param input element - the input field attached to the date picker or
10812 * event - if triggered by focus
10813 */
10814 _showDatepicker: function(input) {
10815 input = input.target || input;
10816 if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger
10817 input = $("input", input.parentNode)[0];
10818 }
10819
10820 if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here
10821 return;
10822 }
10823
10824 var inst, beforeShow, beforeShowSettings, isFixed,
10825 offset, showAnim, duration;
10826
10827 inst = $.datepicker._getInst(input);
10828 if ($.datepicker._curInst && $.datepicker._curInst !== inst) {
10829 $.datepicker._curInst.dpDiv.stop(true, true);
10830 if ( inst && $.datepicker._datepickerShowing ) {
10831 $.datepicker._hideDatepicker( $.datepicker._curInst.input[0] );
10832 }
10833 }
10834
10835 beforeShow = $.datepicker._get(inst, "beforeShow");
10836 beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {};
10837 if(beforeShowSettings === false){
10838 return;
10839 }
10840 extendRemove(inst.settings, beforeShowSettings);
10841
10842 inst.lastVal = null;
10843 $.datepicker._lastInput = input;
10844 $.datepicker._setDateFromField(inst);
10845
10846 if ($.datepicker._inDialog) { // hide cursor
10847 input.value = "";
10848 }
10849 if (!$.datepicker._pos) { // position below input
10850 $.datepicker._pos = $.datepicker._findPos(input);
10851 $.datepicker._pos[1] += input.offsetHeight; // add the height
10852 }
10853
10854 isFixed = false;
10855 $(input).parents().each(function() {
10856 isFixed |= $(this).css("position") === "fixed";
10857 return !isFixed;
10858 });
10859
10860 offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
10861 $.datepicker._pos = null;
10862 //to avoid flashes on Firefox
10863 inst.dpDiv.empty();
10864 // determine sizing offscreen
10865 inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"});
10866 $.datepicker._updateDatepicker(inst);
10867 // fix width for dynamic number of date pickers
10868 // and adjust position before showing
10869 offset = $.datepicker._checkOffset(inst, offset, isFixed);
10870 inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
10871 "static" : (isFixed ? "fixed" : "absolute")), display: "none",
10872 left: offset.left + "px", top: offset.top + "px"});
10873
10874 if (!inst.inline) {
10875 showAnim = $.datepicker._get(inst, "showAnim");
10876 duration = $.datepicker._get(inst, "duration");
10877 inst.dpDiv.zIndex($(input).zIndex()+1);
10878 $.datepicker._datepickerShowing = true;
10879
10880 if ( $.effects && $.effects.effect[ showAnim ] ) {
10881 inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration);
10882 } else {
10883 inst.dpDiv[showAnim || "show"](showAnim ? duration : null);
10884 }
10885
10886 if ( $.datepicker._shouldFocusInput( inst ) ) {
10887 inst.input.focus();
10888 }
10889
10890 $.datepicker._curInst = inst;
10891 }
10892 },
10893
10894 /* Generate the date picker content. */
10895 _updateDatepicker: function(inst) {
10896 this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
10897 instActive = inst; // for delegate hover events
10898 inst.dpDiv.empty().append(this._generateHTML(inst));
10899 this._attachHandlers(inst);
10900 inst.dpDiv.find("." + this._dayOverClass + " a").mouseover();
10901
10902 var origyearshtml,
10903 numMonths = this._getNumberOfMonths(inst),
10904 cols = numMonths[1],
10905 width = 17;
10906
10907 inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");
10908 if (cols > 1) {
10909 inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em");
10910 }
10911 inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") +
10912 "Class"]("ui-datepicker-multi");
10913 inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") +
10914 "Class"]("ui-datepicker-rtl");
10915
10916 if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) {
10917 inst.input.focus();
10918 }
10919
10920 // deffered render of the years select (to avoid flashes on Firefox)
10921 if( inst.yearshtml ){
10922 origyearshtml = inst.yearshtml;
10923 setTimeout(function(){
10924 //assure that inst.yearshtml didn't change.
10925 if( origyearshtml === inst.yearshtml && inst.yearshtml ){
10926 inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml);
10927 }
10928 origyearshtml = inst.yearshtml = null;
10929 }, 0);
10930 }
10931 },
10932
10933 // #6694 - don't focus the input if it's already focused
10934 // this breaks the change event in IE
10935 // Support: IE and jQuery <1.9
10936 _shouldFocusInput: function( inst ) {
10937 return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" );
10938 },
10939
10940 /* Check positioning to remain on screen. */
10941 _checkOffset: function(inst, offset, isFixed) {
10942 var dpWidth = inst.dpDiv.outerWidth(),
10943 dpHeight = inst.dpDiv.outerHeight(),
10944 inputWidth = inst.input ? inst.input.outerWidth() : 0,
10945 inputHeight = inst.input ? inst.input.outerHeight() : 0,
10946 viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()),
10947 viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop());
10948
10949 offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0);
10950 offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0;
10951 offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
10952
10953 // now check if datepicker is showing outside window viewport - move to a better place if so.
10954 offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
10955 Math.abs(offset.left + dpWidth - viewWidth) : 0);
10956 offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
10957 Math.abs(dpHeight + inputHeight) : 0);
10958
10959 return offset;
10960 },
10961
10962 /* Find an object's position on the screen. */
10963 _findPos: function(obj) {
10964 var position,
10965 inst = this._getInst(obj),
10966 isRTL = this._get(inst, "isRTL");
10967
10968 while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) {
10969 obj = obj[isRTL ? "previousSibling" : "nextSibling"];
10970 }
10971
10972 position = $(obj).offset();
10973 return [position.left, position.top];
10974 },
10975
10976 /* Hide the date picker from view.
10977 * @param input element - the input field attached to the date picker
10978 */
10979 _hideDatepicker: function(input) {
10980 var showAnim, duration, postProcess, onClose,
10981 inst = this._curInst;
10982
10983 if (!inst || (input && inst !== $.data(input, PROP_NAME))) {
10984 return;
10985 }
10986
10987 if (this._datepickerShowing) {
10988 showAnim = this._get(inst, "showAnim");
10989 duration = this._get(inst, "duration");
10990 postProcess = function() {
10991 $.datepicker._tidyDialog(inst);
10992 };
10993
10994 // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
10995 if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) {
10996 inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess);
10997 } else {
10998 inst.dpDiv[(showAnim === "slideDown" ? "slideUp" :
10999 (showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess);
11000 }
11001
11002 if (!showAnim) {
11003 postProcess();
11004 }
11005 this._datepickerShowing = false;
11006
11007 onClose = this._get(inst, "onClose");
11008 if (onClose) {
11009 onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]);
11010 }
11011
11012 this._lastInput = null;
11013 if (this._inDialog) {
11014 this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" });
11015 if ($.blockUI) {
11016 $.unblockUI();
11017 $("body").append(this.dpDiv);
11018 }
11019 }
11020 this._inDialog = false;
11021 }
11022 },
11023
11024 /* Tidy up after a dialog display. */
11025 _tidyDialog: function(inst) {
11026 inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar");
11027 },
11028
11029 /* Close date picker if clicked elsewhere. */
11030 _checkExternalClick: function(event) {
11031 if (!$.datepicker._curInst) {
11032 return;
11033 }
11034
11035 var $target = $(event.target),
11036 inst = $.datepicker._getInst($target[0]);
11037
11038 if ( ( ( $target[0].id !== $.datepicker._mainDivId &&
11039 $target.parents("#" + $.datepicker._mainDivId).length === 0 &&
11040 !$target.hasClass($.datepicker.markerClassName) &&
11041 !$target.closest("." + $.datepicker._triggerClass).length &&
11042 $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) ||
11043 ( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) {
11044 $.datepicker._hideDatepicker();
11045 }
11046 },
11047
11048 /* Adjust one of the date sub-fields. */
11049 _adjustDate: function(id, offset, period) {
11050 var target = $(id),
11051 inst = this._getInst(target[0]);
11052
11053 if (this._isDisabledDatepicker(target[0])) {
11054 return;
11055 }
11056 this._adjustInstDate(inst, offset +
11057 (period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning
11058 period);
11059 this._updateDatepicker(inst);
11060 },
11061
11062 /* Action for current link. */
11063 _gotoToday: function(id) {
11064 var date,
11065 target = $(id),
11066 inst = this._getInst(target[0]);
11067
11068 if (this._get(inst, "gotoCurrent") && inst.currentDay) {
11069 inst.selectedDay = inst.currentDay;
11070 inst.drawMonth = inst.selectedMonth = inst.currentMonth;
11071 inst.drawYear = inst.selectedYear = inst.currentYear;
11072 } else {
11073 date = new Date();
11074 inst.selectedDay = date.getDate();
11075 inst.drawMonth = inst.selectedMonth = date.getMonth();
11076 inst.drawYear = inst.selectedYear = date.getFullYear();
11077 }
11078 this._notifyChange(inst);
11079 this._adjustDate(target);
11080 },
11081
11082 /* Action for selecting a new month/year. */
11083 _selectMonthYear: function(id, select, period) {
11084 var target = $(id),
11085 inst = this._getInst(target[0]);
11086
11087 inst["selected" + (period === "M" ? "Month" : "Year")] =
11088 inst["draw" + (period === "M" ? "Month" : "Year")] =
11089 parseInt(select.options[select.selectedIndex].value,10);
11090
11091 this._notifyChange(inst);
11092 this._adjustDate(target);
11093 },
11094
11095 /* Action for selecting a day. */
11096 _selectDay: function(id, month, year, td) {
11097 var inst,
11098 target = $(id);
11099
11100 if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
11101 return;
11102 }
11103
11104 inst = this._getInst(target[0]);
11105 inst.selectedDay = inst.currentDay = $("a", td).html();
11106 inst.selectedMonth = inst.currentMonth = month;
11107 inst.selectedYear = inst.currentYear = year;
11108 this._selectDate(id, this._formatDate(inst,
11109 inst.currentDay, inst.currentMonth, inst.currentYear));
11110 },
11111
11112 /* Erase the input field and hide the date picker. */
11113 _clearDate: function(id) {
11114 var target = $(id);
11115 this._selectDate(target, "");
11116 },
11117
11118 /* Update the input field with the selected date. */
11119 _selectDate: function(id, dateStr) {
11120 var onSelect,
11121 target = $(id),
11122 inst = this._getInst(target[0]);
11123
11124 dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
11125 if (inst.input) {
11126 inst.input.val(dateStr);
11127 }
11128 this._updateAlternate(inst);
11129
11130 onSelect = this._get(inst, "onSelect");
11131 if (onSelect) {
11132 onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback
11133 } else if (inst.input) {
11134 inst.input.trigger("change"); // fire the change event
11135 }
11136
11137 if (inst.inline){
11138 this._updateDatepicker(inst);
11139 } else {
11140 this._hideDatepicker();
11141 this._lastInput = inst.input[0];
11142 if (typeof(inst.input[0]) !== "object") {
11143 inst.input.focus(); // restore focus
11144 }
11145 this._lastInput = null;
11146 }
11147 },
11148
11149 /* Update any alternate field to synchronise with the main field. */
11150 _updateAlternate: function(inst) {
11151 var altFormat, date, dateStr,
11152 altField = this._get(inst, "altField");
11153
11154 if (altField) { // update alternate field too
11155 altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat");
11156 date = this._getDate(inst);
11157 dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
11158 $(altField).each(function() { $(this).val(dateStr); });
11159 }
11160 },
11161
11162 /* Set as beforeShowDay function to prevent selection of weekends.
11163 * @param date Date - the date to customise
11164 * @return [boolean, string] - is this date selectable?, what is its CSS class?
11165 */
11166 noWeekends: function(date) {
11167 var day = date.getDay();
11168 return [(day > 0 && day < 6), ""];
11169 },
11170
11171 /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
11172 * @param date Date - the date to get the week for
11173 * @return number - the number of the week within the year that contains this date
11174 */
11175 iso8601Week: function(date) {
11176 var time,
11177 checkDate = new Date(date.getTime());
11178
11179 // Find Thursday of this week starting on Monday
11180 checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
11181
11182 time = checkDate.getTime();
11183 checkDate.setMonth(0); // Compare with Jan 1
11184 checkDate.setDate(1);
11185 return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
11186 },
11187
11188 /* Parse a string value into a date object.
11189 * See formatDate below for the possible formats.
11190 *
11191 * @param format string - the expected format of the date
11192 * @param value string - the date in the above format
11193 * @param settings Object - attributes include:
11194 * shortYearCutoff number - the cutoff year for determining the century (optional)
11195 * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
11196 * dayNames string[7] - names of the days from Sunday (optional)
11197 * monthNamesShort string[12] - abbreviated names of the months (optional)
11198 * monthNames string[12] - names of the months (optional)
11199 * @return Date - the extracted date value or null if value is blank
11200 */
11201 parseDate: function (format, value, settings) {
11202 if (format == null || value == null) {
11203 throw "Invalid arguments";
11204 }
11205
11206 value = (typeof value === "object" ? value.toString() : value + "");
11207 if (value === "") {
11208 return null;
11209 }
11210
11211 var iFormat, dim, extra,
11212 iValue = 0,
11213 shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff,
11214 shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp :
11215 new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)),
11216 dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
11217 dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
11218 monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
11219 monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
11220 year = -1,
11221 month = -1,
11222 day = -1,
11223 doy = -1,
11224 literal = false,
11225 date,
11226 // Check whether a format character is doubled
11227 lookAhead = function(match) {
11228 var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
11229 if (matches) {
11230 iFormat++;
11231 }
11232 return matches;
11233 },
11234 // Extract a number from the string value
11235 getNumber = function(match) {
11236 var isDoubled = lookAhead(match),
11237 size = (match === "@" ? 14 : (match === "!" ? 20 :
11238 (match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))),
11239 digits = new RegExp("^\\d{1," + size + "}"),
11240 num = value.substring(iValue).match(digits);
11241 if (!num) {
11242 throw "Missing number at position " + iValue;
11243 }
11244 iValue += num[0].length;
11245 return parseInt(num[0], 10);
11246 },
11247 // Extract a name from the string value and convert to an index
11248 getName = function(match, shortNames, longNames) {
11249 var index = -1,
11250 names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) {
11251 return [ [k, v] ];
11252 }).sort(function (a, b) {
11253 return -(a[1].length - b[1].length);
11254 });
11255
11256 $.each(names, function (i, pair) {
11257 var name = pair[1];
11258 if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) {
11259 index = pair[0];
11260 iValue += name.length;
11261 return false;
11262 }
11263 });
11264 if (index !== -1) {
11265 return index + 1;
11266 } else {
11267 throw "Unknown name at position " + iValue;
11268 }
11269 },
11270 // Confirm that a literal character matches the string value
11271 checkLiteral = function() {
11272 if (value.charAt(iValue) !== format.charAt(iFormat)) {
11273 throw "Unexpected literal at position " + iValue;
11274 }
11275 iValue++;
11276 };
11277
11278 for (iFormat = 0; iFormat < format.length; iFormat++) {
11279 if (literal) {
11280 if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
11281 literal = false;
11282 } else {
11283 checkLiteral();
11284 }
11285 } else {
11286 switch (format.charAt(iFormat)) {
11287 case "d":
11288 day = getNumber("d");
11289 break;
11290 case "D":
11291 getName("D", dayNamesShort, dayNames);
11292 break;
11293 case "o":
11294 doy = getNumber("o");
11295 break;
11296 case "m":
11297 month = getNumber("m");
11298 break;
11299 case "M":
11300 month = getName("M", monthNamesShort, monthNames);
11301 break;
11302 case "y":
11303 year = getNumber("y");
11304 break;
11305 case "@":
11306 date = new Date(getNumber("@"));
11307 year = date.getFullYear();
11308 month = date.getMonth() + 1;
11309 day = date.getDate();
11310 break;
11311 case "!":
11312 date = new Date((getNumber("!") - this._ticksTo1970) / 10000);
11313 year = date.getFullYear();
11314 month = date.getMonth() + 1;
11315 day = date.getDate();
11316 break;
11317 case "'":
11318 if (lookAhead("'")){
11319 checkLiteral();
11320 } else {
11321 literal = true;
11322 }
11323 break;
11324 default:
11325 checkLiteral();
11326 }
11327 }
11328 }
11329
11330 if (iValue < value.length){
11331 extra = value.substr(iValue);
11332 if (!/^\s+/.test(extra)) {
11333 throw "Extra/unparsed characters found in date: " + extra;
11334 }
11335 }
11336
11337 if (year === -1) {
11338 year = new Date().getFullYear();
11339 } else if (year < 100) {
11340 year += new Date().getFullYear() - new Date().getFullYear() % 100 +
11341 (year <= shortYearCutoff ? 0 : -100);
11342 }
11343
11344 if (doy > -1) {
11345 month = 1;
11346 day = doy;
11347 do {
11348 dim = this._getDaysInMonth(year, month - 1);
11349 if (day <= dim) {
11350 break;
11351 }
11352 month++;
11353 day -= dim;
11354 } while (true);
11355 }
11356
11357 date = this._daylightSavingAdjust(new Date(year, month - 1, day));
11358 if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
11359 throw "Invalid date"; // E.g. 31/02/00
11360 }
11361 return date;
11362 },
11363
11364 /* Standard date formats. */
11365 ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601)
11366 COOKIE: "D, dd M yy",
11367 ISO_8601: "yy-mm-dd",
11368 RFC_822: "D, d M y",
11369 RFC_850: "DD, dd-M-y",
11370 RFC_1036: "D, d M y",
11371 RFC_1123: "D, d M yy",
11372 RFC_2822: "D, d M yy",
11373 RSS: "D, d M y", // RFC 822
11374 TICKS: "!",
11375 TIMESTAMP: "@",
11376 W3C: "yy-mm-dd", // ISO 8601
11377
11378 _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
11379 Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),
11380
11381 /* Format a date object into a string value.
11382 * The format can be combinations of the following:
11383 * d - day of month (no leading zero)
11384 * dd - day of month (two digit)
11385 * o - day of year (no leading zeros)
11386 * oo - day of year (three digit)
11387 * D - day name short
11388 * DD - day name long
11389 * m - month of year (no leading zero)
11390 * mm - month of year (two digit)
11391 * M - month name short
11392 * MM - month name long
11393 * y - year (two digit)
11394 * yy - year (four digit)
11395 * @ - Unix timestamp (ms since 01/01/1970)
11396 * ! - Windows ticks (100ns since 01/01/0001)
11397 * "..." - literal text
11398 * '' - single quote
11399 *
11400 * @param format string - the desired format of the date
11401 * @param date Date - the date value to format
11402 * @param settings Object - attributes include:
11403 * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
11404 * dayNames string[7] - names of the days from Sunday (optional)
11405 * monthNamesShort string[12] - abbreviated names of the months (optional)
11406 * monthNames string[12] - names of the months (optional)
11407 * @return string - the date in the above format
11408 */
11409 formatDate: function (format, date, settings) {
11410 if (!date) {
11411 return "";
11412 }
11413
11414 var iFormat,
11415 dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
11416 dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
11417 monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
11418 monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
11419 // Check whether a format character is doubled
11420 lookAhead = function(match) {
11421 var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
11422 if (matches) {
11423 iFormat++;
11424 }
11425 return matches;
11426 },
11427 // Format a number, with leading zero if necessary
11428 formatNumber = function(match, value, len) {
11429 var num = "" + value;
11430 if (lookAhead(match)) {
11431 while (num.length < len) {
11432 num = "0" + num;
11433 }
11434 }
11435 return num;
11436 },
11437 // Format a name, short or long as requested
11438 formatName = function(match, value, shortNames, longNames) {
11439 return (lookAhead(match) ? longNames[value] : shortNames[value]);
11440 },
11441 output = "",
11442 literal = false;
11443
11444 if (date) {
11445 for (iFormat = 0; iFormat < format.length; iFormat++) {
11446 if (literal) {
11447 if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
11448 literal = false;
11449 } else {
11450 output += format.charAt(iFormat);
11451 }
11452 } else {
11453 switch (format.charAt(iFormat)) {
11454 case "d":
11455 output += formatNumber("d", date.getDate(), 2);
11456 break;
11457 case "D":
11458 output += formatName("D", date.getDay(), dayNamesShort, dayNames);
11459 break;
11460 case "o":
11461 output += formatNumber("o",
11462 Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
11463 break;
11464 case "m":
11465 output += formatNumber("m", date.getMonth() + 1, 2);
11466 break;
11467 case "M":
11468 output += formatName("M", date.getMonth(), monthNamesShort, monthNames);
11469 break;
11470 case "y":
11471 output += (lookAhead("y") ? date.getFullYear() :
11472 (date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100);
11473 break;
11474 case "@":
11475 output += date.getTime();
11476 break;
11477 case "!":
11478 output += date.getTime() * 10000 + this._ticksTo1970;
11479 break;
11480 case "'":
11481 if (lookAhead("'")) {
11482 output += "'";
11483 } else {
11484 literal = true;
11485 }
11486 break;
11487 default:
11488 output += format.charAt(iFormat);
11489 }
11490 }
11491 }
11492 }
11493 return output;
11494 },
11495
11496 /* Extract all possible characters from the date format. */
11497 _possibleChars: function (format) {
11498 var iFormat,
11499 chars = "",
11500 literal = false,
11501 // Check whether a format character is doubled
11502 lookAhead = function(match) {
11503 var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
11504 if (matches) {
11505 iFormat++;
11506 }
11507 return matches;
11508 };
11509
11510 for (iFormat = 0; iFormat < format.length; iFormat++) {
11511 if (literal) {
11512 if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
11513 literal = false;
11514 } else {
11515 chars += format.charAt(iFormat);
11516 }
11517 } else {
11518 switch (format.charAt(iFormat)) {
11519 case "d": case "m": case "y": case "@":
11520 chars += "0123456789";
11521 break;
11522 case "D": case "M":
11523 return null; // Accept anything
11524 case "'":
11525 if (lookAhead("'")) {
11526 chars += "'";
11527 } else {
11528 literal = true;
11529 }
11530 break;
11531 default:
11532 chars += format.charAt(iFormat);
11533 }
11534 }
11535 }
11536 return chars;
11537 },
11538
11539 /* Get a setting value, defaulting if necessary. */
11540 _get: function(inst, name) {
11541 return inst.settings[name] !== undefined ?
11542 inst.settings[name] : this._defaults[name];
11543 },
11544
11545 /* Parse existing date and initialise date picker. */
11546 _setDateFromField: function(inst, noDefault) {
11547 if (inst.input.val() === inst.lastVal) {
11548 return;
11549 }
11550
11551 var dateFormat = this._get(inst, "dateFormat"),
11552 dates = inst.lastVal = inst.input ? inst.input.val() : null,
11553 defaultDate = this._getDefaultDate(inst),
11554 date = defaultDate,
11555 settings = this._getFormatConfig(inst);
11556
11557 try {
11558 date = this.parseDate(dateFormat, dates, settings) || defaultDate;
11559 } catch (event) {
11560 dates = (noDefault ? "" : dates);
11561 }
11562 inst.selectedDay = date.getDate();
11563 inst.drawMonth = inst.selectedMonth = date.getMonth();
11564 inst.drawYear = inst.selectedYear = date.getFullYear();
11565 inst.currentDay = (dates ? date.getDate() : 0);
11566 inst.currentMonth = (dates ? date.getMonth() : 0);
11567 inst.currentYear = (dates ? date.getFullYear() : 0);
11568 this._adjustInstDate(inst);
11569 },
11570
11571 /* Retrieve the default date shown on opening. */
11572 _getDefaultDate: function(inst) {
11573 return this._restrictMinMax(inst,
11574 this._determineDate(inst, this._get(inst, "defaultDate"), new Date()));
11575 },
11576
11577 /* A date may be specified as an exact value or a relative one. */
11578 _determineDate: function(inst, date, defaultDate) {
11579 var offsetNumeric = function(offset) {
11580 var date = new Date();
11581 date.setDate(date.getDate() + offset);
11582 return date;
11583 },
11584 offsetString = function(offset) {
11585 try {
11586 return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
11587 offset, $.datepicker._getFormatConfig(inst));
11588 }
11589 catch (e) {
11590 // Ignore
11591 }
11592
11593 var date = (offset.toLowerCase().match(/^c/) ?
11594 $.datepicker._getDate(inst) : null) || new Date(),
11595 year = date.getFullYear(),
11596 month = date.getMonth(),
11597 day = date.getDate(),
11598 pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
11599 matches = pattern.exec(offset);
11600
11601 while (matches) {
11602 switch (matches[2] || "d") {
11603 case "d" : case "D" :
11604 day += parseInt(matches[1],10); break;
11605 case "w" : case "W" :
11606 day += parseInt(matches[1],10) * 7; break;
11607 case "m" : case "M" :
11608 month += parseInt(matches[1],10);
11609 day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
11610 break;
11611 case "y": case "Y" :
11612 year += parseInt(matches[1],10);
11613 day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
11614 break;
11615 }
11616 matches = pattern.exec(offset);
11617 }
11618 return new Date(year, month, day);
11619 },
11620 newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) :
11621 (typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));
11622
11623 newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate);
11624 if (newDate) {
11625 newDate.setHours(0);
11626 newDate.setMinutes(0);
11627 newDate.setSeconds(0);
11628 newDate.setMilliseconds(0);
11629 }
11630 return this._daylightSavingAdjust(newDate);
11631 },
11632
11633 /* Handle switch to/from daylight saving.
11634 * Hours may be non-zero on daylight saving cut-over:
11635 * > 12 when midnight changeover, but then cannot generate
11636 * midnight datetime, so jump to 1AM, otherwise reset.
11637 * @param date (Date) the date to check
11638 * @return (Date) the corrected date
11639 */
11640 _daylightSavingAdjust: function(date) {
11641 if (!date) {
11642 return null;
11643 }
11644 date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
11645 return date;
11646 },
11647
11648 /* Set the date(s) directly. */
11649 _setDate: function(inst, date, noChange) {
11650 var clear = !date,
11651 origMonth = inst.selectedMonth,
11652 origYear = inst.selectedYear,
11653 newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));
11654
11655 inst.selectedDay = inst.currentDay = newDate.getDate();
11656 inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
11657 inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
11658 if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) {
11659 this._notifyChange(inst);
11660 }
11661 this._adjustInstDate(inst);
11662 if (inst.input) {
11663 inst.input.val(clear ? "" : this._formatDate(inst));
11664 }
11665 },
11666
11667 /* Retrieve the date(s) directly. */
11668 _getDate: function(inst) {
11669 var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null :
11670 this._daylightSavingAdjust(new Date(
11671 inst.currentYear, inst.currentMonth, inst.currentDay)));
11672 return startDate;
11673 },
11674
11675 /* Attach the onxxx handlers. These are declared statically so
11676 * they work with static code transformers like Caja.
11677 */
11678 _attachHandlers: function(inst) {
11679 var stepMonths = this._get(inst, "stepMonths"),
11680 id = "#" + inst.id.replace( /\\\\/g, "\\" );
11681 inst.dpDiv.find("[data-handler]").map(function () {
11682 var handler = {
11683 prev: function () {
11684 $.datepicker._adjustDate(id, -stepMonths, "M");
11685 },
11686 next: function () {
11687 $.datepicker._adjustDate(id, +stepMonths, "M");
11688 },
11689 hide: function () {
11690 $.datepicker._hideDatepicker();
11691 },
11692 today: function () {
11693 $.datepicker._gotoToday(id);
11694 },
11695 selectDay: function () {
11696 $.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this);
11697 return false;
11698 },
11699 selectMonth: function () {
11700 $.datepicker._selectMonthYear(id, this, "M");
11701 return false;
11702 },
11703 selectYear: function () {
11704 $.datepicker._selectMonthYear(id, this, "Y");
11705 return false;
11706 }
11707 };
11708 $(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]);
11709 });
11710 },
11711
11712 /* Generate the HTML for the current state of the date picker. */
11713 _generateHTML: function(inst) {
11714 var maxDraw, prevText, prev, nextText, next, currentText, gotoDate,
11715 controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin,
11716 monthNames, monthNamesShort, beforeShowDay, showOtherMonths,
11717 selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate,
11718 cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows,
11719 printDate, dRow, tbody, daySettings, otherMonth, unselectable,
11720 tempDate = new Date(),
11721 today = this._daylightSavingAdjust(
11722 new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time
11723 isRTL = this._get(inst, "isRTL"),
11724 showButtonPanel = this._get(inst, "showButtonPanel"),
11725 hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"),
11726 navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"),
11727 numMonths = this._getNumberOfMonths(inst),
11728 showCurrentAtPos = this._get(inst, "showCurrentAtPos"),
11729 stepMonths = this._get(inst, "stepMonths"),
11730 isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1),
11731 currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
11732 new Date(inst.currentYear, inst.currentMonth, inst.currentDay))),
11733 minDate = this._getMinMaxDate(inst, "min"),
11734 maxDate = this._getMinMaxDate(inst, "max"),
11735 drawMonth = inst.drawMonth - showCurrentAtPos,
11736 drawYear = inst.drawYear;
11737
11738 if (drawMonth < 0) {
11739 drawMonth += 12;
11740 drawYear--;
11741 }
11742 if (maxDate) {
11743 maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
11744 maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
11745 maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
11746 while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
11747 drawMonth--;
11748 if (drawMonth < 0) {
11749 drawMonth = 11;
11750 drawYear--;
11751 }
11752 }
11753 }
11754 inst.drawMonth = drawMonth;
11755 inst.drawYear = drawYear;
11756
11757 prevText = this._get(inst, "prevText");
11758 prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
11759 this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
11760 this._getFormatConfig(inst)));
11761
11762 prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
11763 "<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" +
11764 " title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" :
11765 (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>"));
11766
11767 nextText = this._get(inst, "nextText");
11768 nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
11769 this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
11770 this._getFormatConfig(inst)));
11771
11772 next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
11773 "<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" +
11774 " title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" :
11775 (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>"));
11776
11777 currentText = this._get(inst, "currentText");
11778 gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today);
11779 currentText = (!navigationAsDateFormat ? currentText :
11780 this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
11781
11782 controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" +
11783 this._get(inst, "closeText") + "</button>" : "");
11784
11785 buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") +
11786 (this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" +
11787 ">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : "";
11788
11789 firstDay = parseInt(this._get(inst, "firstDay"),10);
11790 firstDay = (isNaN(firstDay) ? 0 : firstDay);
11791
11792 showWeek = this._get(inst, "showWeek");
11793 dayNames = this._get(inst, "dayNames");
11794 dayNamesMin = this._get(inst, "dayNamesMin");
11795 monthNames = this._get(inst, "monthNames");
11796 monthNamesShort = this._get(inst, "monthNamesShort");
11797 beforeShowDay = this._get(inst, "beforeShowDay");
11798 showOtherMonths = this._get(inst, "showOtherMonths");
11799 selectOtherMonths = this._get(inst, "selectOtherMonths");
11800 defaultDate = this._getDefaultDate(inst);
11801 html = "";
11802 dow;
11803 for (row = 0; row < numMonths[0]; row++) {
11804 group = "";
11805 this.maxRows = 4;
11806 for (col = 0; col < numMonths[1]; col++) {
11807 selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
11808 cornerClass = " ui-corner-all";
11809 calender = "";
11810 if (isMultiMonth) {
11811 calender += "<div class='ui-datepicker-group";
11812 if (numMonths[1] > 1) {
11813 switch (col) {
11814 case 0: calender += " ui-datepicker-group-first";
11815 cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break;
11816 case numMonths[1]-1: calender += " ui-datepicker-group-last";
11817 cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break;
11818 default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break;
11819 }
11820 }
11821 calender += "'>";
11822 }
11823 calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" +
11824 (/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") +
11825 (/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") +
11826 this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
11827 row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
11828 "</div><table class='ui-datepicker-calendar'><thead>" +
11829 "<tr>";
11830 thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : "");
11831 for (dow = 0; dow < 7; dow++) { // days of the week
11832 day = (dow + firstDay) % 7;
11833 thead += "<th" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" +
11834 "<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>";
11835 }
11836 calender += thead + "</tr></thead><tbody>";
11837 daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
11838 if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) {
11839 inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
11840 }
11841 leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
11842 curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate
11843 numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043)
11844 this.maxRows = numRows;
11845 printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
11846 for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows
11847 calender += "<tr>";
11848 tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" +
11849 this._get(inst, "calculateWeek")(printDate) + "</td>");
11850 for (dow = 0; dow < 7; dow++) { // create date picker days
11851 daySettings = (beforeShowDay ?
11852 beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]);
11853 otherMonth = (printDate.getMonth() !== drawMonth);
11854 unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
11855 (minDate && printDate < minDate) || (maxDate && printDate > maxDate);
11856 tbody += "<td class='" +
11857 ((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends
11858 (otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months
11859 ((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key
11860 (defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ?
11861 // or defaultDate is current printedDate and defaultDate is selectedDate
11862 " " + this._dayOverClass : "") + // highlight selected day
11863 (unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") + // highlight unselectable days
11864 (otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates
11865 (printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day
11866 (printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different)
11867 ((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "&#39;") + "'" : "") + // cell title
11868 (unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions
11869 (otherMonth && !showOtherMonths ? "&#xa0;" : // display for other months
11870 (unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" +
11871 (printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") +
11872 (printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day
11873 (otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months
11874 "' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date
11875 printDate.setDate(printDate.getDate() + 1);
11876 printDate = this._daylightSavingAdjust(printDate);
11877 }
11878 calender += tbody + "</tr>";
11879 }
11880 drawMonth++;
11881 if (drawMonth > 11) {
11882 drawMonth = 0;
11883 drawYear++;
11884 }
11885 calender += "</tbody></table>" + (isMultiMonth ? "</div>" +
11886 ((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : "");
11887 group += calender;
11888 }
11889 html += group;
11890 }
11891 html += buttonPanel;
11892 inst._keyEvent = false;
11893 return html;
11894 },
11895
11896 /* Generate the month and year header. */
11897 _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
11898 secondary, monthNames, monthNamesShort) {
11899
11900 var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
11901 changeMonth = this._get(inst, "changeMonth"),
11902 changeYear = this._get(inst, "changeYear"),
11903 showMonthAfterYear = this._get(inst, "showMonthAfterYear"),
11904 html = "<div class='ui-datepicker-title'>",
11905 monthHtml = "";
11906
11907 // month selection
11908 if (secondary || !changeMonth) {
11909 monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>";
11910 } else {
11911 inMinYear = (minDate && minDate.getFullYear() === drawYear);
11912 inMaxYear = (maxDate && maxDate.getFullYear() === drawYear);
11913 monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>";
11914 for ( month = 0; month < 12; month++) {
11915 if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) {
11916 monthHtml += "<option value='" + month + "'" +
11917 (month === drawMonth ? " selected='selected'" : "") +
11918 ">" + monthNamesShort[month] + "</option>";
11919 }
11920 }
11921 monthHtml += "</select>";
11922 }
11923
11924 if (!showMonthAfterYear) {
11925 html += monthHtml + (secondary || !(changeMonth && changeYear) ? "&#xa0;" : "");
11926 }
11927
11928 // year selection
11929 if ( !inst.yearshtml ) {
11930 inst.yearshtml = "";
11931 if (secondary || !changeYear) {
11932 html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
11933 } else {
11934 // determine range of years to display
11935 years = this._get(inst, "yearRange").split(":");
11936 thisYear = new Date().getFullYear();
11937 determineYear = function(value) {
11938 var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) :
11939 (value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) :
11940 parseInt(value, 10)));
11941 return (isNaN(year) ? thisYear : year);
11942 };
11943 year = determineYear(years[0]);
11944 endYear = Math.max(year, determineYear(years[1] || ""));
11945 year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
11946 endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
11947 inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";
11948 for (; year <= endYear; year++) {
11949 inst.yearshtml += "<option value='" + year + "'" +
11950 (year === drawYear ? " selected='selected'" : "") +
11951 ">" + year + "</option>";
11952 }
11953 inst.yearshtml += "</select>";
11954
11955 html += inst.yearshtml;
11956 inst.yearshtml = null;
11957 }
11958 }
11959
11960 html += this._get(inst, "yearSuffix");
11961 if (showMonthAfterYear) {
11962 html += (secondary || !(changeMonth && changeYear) ? "&#xa0;" : "") + monthHtml;
11963 }
11964 html += "</div>"; // Close datepicker_header
11965 return html;
11966 },
11967
11968 /* Adjust one of the date sub-fields. */
11969 _adjustInstDate: function(inst, offset, period) {
11970 var year = inst.drawYear + (period === "Y" ? offset : 0),
11971 month = inst.drawMonth + (period === "M" ? offset : 0),
11972 day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0),
11973 date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day)));
11974
11975 inst.selectedDay = date.getDate();
11976 inst.drawMonth = inst.selectedMonth = date.getMonth();
11977 inst.drawYear = inst.selectedYear = date.getFullYear();
11978 if (period === "M" || period === "Y") {
11979 this._notifyChange(inst);
11980 }
11981 },
11982
11983 /* Ensure a date is within any min/max bounds. */
11984 _restrictMinMax: function(inst, date) {
11985 var minDate = this._getMinMaxDate(inst, "min"),
11986 maxDate = this._getMinMaxDate(inst, "max"),
11987 newDate = (minDate && date < minDate ? minDate : date);
11988 return (maxDate && newDate > maxDate ? maxDate : newDate);
11989 },
11990
11991 /* Notify change of month/year. */
11992 _notifyChange: function(inst) {
11993 var onChange = this._get(inst, "onChangeMonthYear");
11994 if (onChange) {
11995 onChange.apply((inst.input ? inst.input[0] : null),
11996 [inst.selectedYear, inst.selectedMonth + 1, inst]);
11997 }
11998 },
11999
12000 /* Determine the number of months to show. */
12001 _getNumberOfMonths: function(inst) {
12002 var numMonths = this._get(inst, "numberOfMonths");
12003 return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths));
12004 },
12005
12006 /* Determine the current maximum date - ensure no time components are set. */
12007 _getMinMaxDate: function(inst, minMax) {
12008 return this._determineDate(inst, this._get(inst, minMax + "Date"), null);
12009 },
12010
12011 /* Find the number of days in a given month. */
12012 _getDaysInMonth: function(year, month) {
12013 return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate();
12014 },
12015
12016 /* Find the day of the week of the first of a month. */
12017 _getFirstDayOfMonth: function(year, month) {
12018 return new Date(year, month, 1).getDay();
12019 },
12020
12021 /* Determines if we should allow a "next/prev" month display change. */
12022 _canAdjustMonth: function(inst, offset, curYear, curMonth) {
12023 var numMonths = this._getNumberOfMonths(inst),
12024 date = this._daylightSavingAdjust(new Date(curYear,
12025 curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));
12026
12027 if (offset < 0) {
12028 date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
12029 }
12030 return this._isInRange(inst, date);
12031 },
12032
12033 /* Is the given date in the accepted range? */
12034 _isInRange: function(inst, date) {
12035 var yearSplit, currentYear,
12036 minDate = this._getMinMaxDate(inst, "min"),
12037 maxDate = this._getMinMaxDate(inst, "max"),
12038 minYear = null,
12039 maxYear = null,
12040 years = this._get(inst, "yearRange");
12041 if (years){
12042 yearSplit = years.split(":");
12043 currentYear = new Date().getFullYear();
12044 minYear = parseInt(yearSplit[0], 10);
12045 maxYear = parseInt(yearSplit[1], 10);
12046 if ( yearSplit[0].match(/[+\-].*/) ) {
12047 minYear += currentYear;
12048 }
12049 if ( yearSplit[1].match(/[+\-].*/) ) {
12050 maxYear += currentYear;
12051 }
12052 }
12053
12054 return ((!minDate || date.getTime() >= minDate.getTime()) &&
12055 (!maxDate || date.getTime() <= maxDate.getTime()) &&
12056 (!minYear || date.getFullYear() >= minYear) &&
12057 (!maxYear || date.getFullYear() <= maxYear));
12058 },
12059
12060 /* Provide the configuration settings for formatting/parsing. */
12061 _getFormatConfig: function(inst) {
12062 var shortYearCutoff = this._get(inst, "shortYearCutoff");
12063 shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff :
12064 new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
12065 return {shortYearCutoff: shortYearCutoff,
12066 dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"),
12067 monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")};
12068 },
12069
12070 /* Format the given date for display. */
12071 _formatDate: function(inst, day, month, year) {
12072 if (!day) {
12073 inst.currentDay = inst.selectedDay;
12074 inst.currentMonth = inst.selectedMonth;
12075 inst.currentYear = inst.selectedYear;
12076 }
12077 var date = (day ? (typeof day === "object" ? day :
12078 this._daylightSavingAdjust(new Date(year, month, day))) :
12079 this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
12080 return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst));
12081 }
12082 });
12083
12084 /*
12085 * Bind hover events for datepicker elements.
12086 * Done via delegate so the binding only occurs once in the lifetime of the parent div.
12087 * Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
12088 */
12089 function bindHover(dpDiv) {
12090 var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
12091 return dpDiv.delegate(selector, "mouseout", function() {
12092 $(this).removeClass("ui-state-hover");
12093 if (this.className.indexOf("ui-datepicker-prev") !== -1) {
12094 $(this).removeClass("ui-datepicker-prev-hover");
12095 }
12096 if (this.className.indexOf("ui-datepicker-next") !== -1) {
12097 $(this).removeClass("ui-datepicker-next-hover");
12098 }
12099 })
12100 .delegate(selector, "mouseover", function(){
12101 if (!$.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : instActive.input[0])) {
12102 $(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");
12103 $(this).addClass("ui-state-hover");
12104 if (this.className.indexOf("ui-datepicker-prev") !== -1) {
12105 $(this).addClass("ui-datepicker-prev-hover");
12106 }
12107 if (this.className.indexOf("ui-datepicker-next") !== -1) {
12108 $(this).addClass("ui-datepicker-next-hover");
12109 }
12110 }
12111 });
12112 }
12113
12114 /* jQuery extend now ignores nulls! */
12115 function extendRemove(target, props) {
12116 $.extend(target, props);
12117 for (var name in props) {
12118 if (props[name] == null) {
12119 target[name] = props[name];
12120 }
12121 }
12122 return target;
12123 }
12124
12125 /* Invoke the datepicker functionality.
12126 @param options string - a command, optionally followed by additional parameters or
12127 Object - settings for attaching new datepicker functionality
12128 @return jQuery object */
12129 $.fn.datepicker = function(options){
12130
12131 /* Verify an empty collection wasn't passed - Fixes #6976 */
12132 if ( !this.length ) {
12133 return this;
12134 }
12135
12136 /* Initialise the date picker. */
12137 if (!$.datepicker.initialized) {
12138 $(document).mousedown($.datepicker._checkExternalClick);
12139 $.datepicker.initialized = true;
12140 }
12141
12142 /* Append datepicker main container to body if not exist. */
12143 if ($("#"+$.datepicker._mainDivId).length === 0) {
12144 $("body").append($.datepicker.dpDiv);
12145 }
12146
12147 var otherArgs = Array.prototype.slice.call(arguments, 1);
12148 if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) {
12149 return $.datepicker["_" + options + "Datepicker"].
12150 apply($.datepicker, [this[0]].concat(otherArgs));
12151 }
12152 if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") {
12153 return $.datepicker["_" + options + "Datepicker"].
12154 apply($.datepicker, [this[0]].concat(otherArgs));
12155 }
12156 return this.each(function() {
12157 typeof options === "string" ?
12158 $.datepicker["_" + options + "Datepicker"].
12159 apply($.datepicker, [this].concat(otherArgs)) :
12160 $.datepicker._attachDatepicker(this, options);
12161 });
12162 };
12163
12164 $.datepicker = new Datepicker(); // singleton instance
12165 $.datepicker.initialized = false;
12166 $.datepicker.uuid = new Date().getTime();
12167 $.datepicker.version = "1.10.3";
12168
12169 })(jQuery);
12170 (function( $, undefined ) {
12171
12172 var sizeRelatedOptions = {
12173 buttons: true,
12174 height: true,
12175 maxHeight: true,
12176 maxWidth: true,
12177 minHeight: true,
12178 minWidth: true,
12179 width: true
12180 },
12181 resizableRelatedOptions = {
12182 maxHeight: true,
12183 maxWidth: true,
12184 minHeight: true,
12185 minWidth: true
12186 };
12187
12188 $.widget( "ui.dialog", {
12189 version: "1.10.3",
12190 options: {
12191 appendTo: "body",
12192 autoOpen: true,
12193 buttons: [],
12194 closeOnEscape: true,
12195 closeText: "close",
12196 dialogClass: "",
12197 draggable: true,
12198 hide: null,
12199 height: "auto",
12200 maxHeight: null,
12201 maxWidth: null,
12202 minHeight: 150,
12203 minWidth: 150,
12204 modal: false,
12205 position: {
12206 my: "center",
12207 at: "center",
12208 of: window,
12209 collision: "fit",
12210 // Ensure the titlebar is always visible
12211 using: function( pos ) {
12212 var topOffset = $( this ).css( pos ).offset().top;
12213 if ( topOffset < 0 ) {
12214 $( this ).css( "top", pos.top - topOffset );
12215 }
12216 }
12217 },
12218 resizable: true,
12219 show: null,
12220 title: null,
12221 width: 300,
12222
12223 // callbacks
12224 beforeClose: null,
12225 close: null,
12226 drag: null,
12227 dragStart: null,
12228 dragStop: null,
12229 focus: null,
12230 open: null,
12231 resize: null,
12232 resizeStart: null,
12233 resizeStop: null
12234 },
12235
12236 _create: function() {
12237 this.originalCss = {
12238 display: this.element[0].style.display,
12239 width: this.element[0].style.width,
12240 minHeight: this.element[0].style.minHeight,
12241 maxHeight: this.element[0].style.maxHeight,
12242 height: this.element[0].style.height
12243 };
12244 this.originalPosition = {
12245 parent: this.element.parent(),
12246 index: this.element.parent().children().index( this.element )
12247 };
12248 this.originalTitle = this.element.attr("title");
12249 this.options.title = this.options.title || this.originalTitle;
12250
12251 this._createWrapper();
12252
12253 this.element
12254 .show()
12255 .removeAttr("title")
12256 .addClass("ui-dialog-content ui-widget-content")
12257 .appendTo( this.uiDialog );
12258
12259 this._createTitlebar();
12260 this._createButtonPane();
12261
12262 if ( this.options.draggable && $.fn.draggable ) {
12263 this._makeDraggable();
12264 }
12265 if ( this.options.resizable && $.fn.resizable ) {
12266 this._makeResizable();
12267 }
12268
12269 this._isOpen = false;
12270 },
12271
12272 _init: function() {
12273 if ( this.options.autoOpen ) {
12274 this.open();
12275 }
12276 },
12277
12278 _appendTo: function() {
12279 var element = this.options.appendTo;
12280 if ( element && (element.jquery || element.nodeType) ) {
12281 return $( element );
12282 }
12283 return this.document.find( element || "body" ).eq( 0 );
12284 },
12285
12286 _destroy: function() {
12287 var next,
12288 originalPosition = this.originalPosition;
12289
12290 this._destroyOverlay();
12291
12292 this.element
12293 .removeUniqueId()
12294 .removeClass("ui-dialog-content ui-widget-content")
12295 .css( this.originalCss )
12296 // Without detaching first, the following becomes really slow
12297 .detach();
12298
12299 this.uiDialog.stop( true, true ).remove();
12300
12301 if ( this.originalTitle ) {
12302 this.element.attr( "title", this.originalTitle );
12303 }
12304
12305 next = originalPosition.parent.children().eq( originalPosition.index );
12306 // Don't try to place the dialog next to itself (#8613)
12307 if ( next.length && next[0] !== this.element[0] ) {
12308 next.before( this.element );
12309 } else {
12310 originalPosition.parent.append( this.element );
12311 }
12312 },
12313
12314 widget: function() {
12315 return this.uiDialog;
12316 },
12317
12318 disable: $.noop,
12319 enable: $.noop,
12320
12321 close: function( event ) {
12322 var that = this;
12323
12324 if ( !this._isOpen || this._trigger( "beforeClose", event ) === false ) {
12325 return;
12326 }
12327
12328 this._isOpen = false;
12329 this._destroyOverlay();
12330
12331 if ( !this.opener.filter(":focusable").focus().length ) {
12332 // Hiding a focused element doesn't trigger blur in WebKit
12333 // so in case we have nothing to focus on, explicitly blur the active element
12334 // https://bugs.webkit.org/show_bug.cgi?id=47182
12335 $( this.document[0].activeElement ).blur();
12336 }
12337
12338 this._hide( this.uiDialog, this.options.hide, function() {
12339 that._trigger( "close", event );
12340 });
12341 },
12342
12343 isOpen: function() {
12344 return this._isOpen;
12345 },
12346
12347 moveToTop: function() {
12348 this._moveToTop();
12349 },
12350
12351 _moveToTop: function( event, silent ) {
12352 var moved = !!this.uiDialog.nextAll(":visible").insertBefore( this.uiDialog ).length;
12353 if ( moved && !silent ) {
12354 this._trigger( "focus", event );
12355 }
12356 return moved;
12357 },
12358
12359 open: function() {
12360 var that = this;
12361 if ( this._isOpen ) {
12362 if ( this._moveToTop() ) {
12363 this._focusTabbable();
12364 }
12365 return;
12366 }
12367
12368 this._isOpen = true;
12369 this.opener = $( this.document[0].activeElement );
12370
12371 this._size();
12372 this._position();
12373 this._createOverlay();
12374 this._moveToTop( null, true );
12375 this._show( this.uiDialog, this.options.show, function() {
12376 that._focusTabbable();
12377 that._trigger("focus");
12378 });
12379
12380 this._trigger("open");
12381 },
12382
12383 _focusTabbable: function() {
12384 // Set focus to the first match:
12385 // 1. First element inside the dialog matching [autofocus]
12386 // 2. Tabbable element inside the content element
12387 // 3. Tabbable element inside the buttonpane
12388 // 4. The close button
12389 // 5. The dialog itself
12390 var hasFocus = this.element.find("[autofocus]");
12391 if ( !hasFocus.length ) {
12392 hasFocus = this.element.find(":tabbable");
12393 }
12394 if ( !hasFocus.length ) {
12395 hasFocus = this.uiDialogButtonPane.find(":tabbable");
12396 }
12397 if ( !hasFocus.length ) {
12398 hasFocus = this.uiDialogTitlebarClose.filter(":tabbable");
12399 }
12400 if ( !hasFocus.length ) {
12401 hasFocus = this.uiDialog;
12402 }
12403 hasFocus.eq( 0 ).focus();
12404 },
12405
12406 _keepFocus: function( event ) {
12407 function checkFocus() {
12408 var activeElement = this.document[0].activeElement,
12409 isActive = this.uiDialog[0] === activeElement ||
12410 $.contains( this.uiDialog[0], activeElement );
12411 if ( !isActive ) {
12412 this._focusTabbable();
12413 }
12414 }
12415 event.preventDefault();
12416 checkFocus.call( this );
12417 // support: IE
12418 // IE <= 8 doesn't prevent moving focus even with event.preventDefault()
12419 // so we check again later
12420 this._delay( checkFocus );
12421 },
12422
12423 _createWrapper: function() {
12424 this.uiDialog = $("<div>")
12425 .addClass( "ui-dialog ui-widget ui-widget-content ui-corner-all ui-front " +
12426 this.options.dialogClass )
12427 .hide()
12428 .attr({
12429 // Setting tabIndex makes the div focusable
12430 tabIndex: -1,
12431 role: "dialog"
12432 })
12433 .appendTo( this._appendTo() );
12434
12435 this._on( this.uiDialog, {
12436 keydown: function( event ) {
12437 if ( this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode &&
12438 event.keyCode === $.ui.keyCode.ESCAPE ) {
12439 event.preventDefault();
12440 this.close( event );
12441 return;
12442 }
12443
12444 // prevent tabbing out of dialogs
12445 if ( event.keyCode !== $.ui.keyCode.TAB ) {
12446 return;
12447 }
12448 var tabbables = this.uiDialog.find(":tabbable"),
12449 first = tabbables.filter(":first"),
12450 last = tabbables.filter(":last");
12451
12452 if ( ( event.target === last[0] || event.target === this.uiDialog[0] ) && !event.shiftKey ) {
12453 first.focus( 1 );
12454 event.preventDefault();
12455 } else if ( ( event.target === first[0] || event.target === this.uiDialog[0] ) && event.shiftKey ) {
12456 last.focus( 1 );
12457 event.preventDefault();
12458 }
12459 },
12460 mousedown: function( event ) {
12461 if ( this._moveToTop( event ) ) {
12462 this._focusTabbable();
12463 }
12464 }
12465 });
12466
12467 // We assume that any existing aria-describedby attribute means
12468 // that the dialog content is marked up properly
12469 // otherwise we brute force the content as the description
12470 if ( !this.element.find("[aria-describedby]").length ) {
12471 this.uiDialog.attr({
12472 "aria-describedby": this.element.uniqueId().attr("id")
12473 });
12474 }
12475 },
12476
12477 _createTitlebar: function() {
12478 var uiDialogTitle;
12479
12480 this.uiDialogTitlebar = $("<div>")
12481 .addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix")
12482 .prependTo( this.uiDialog );
12483 this._on( this.uiDialogTitlebar, {
12484 mousedown: function( event ) {
12485 // Don't prevent click on close button (#8838)
12486 // Focusing a dialog that is partially scrolled out of view
12487 // causes the browser to scroll it into view, preventing the click event
12488 if ( !$( event.target ).closest(".ui-dialog-titlebar-close") ) {
12489 // Dialog isn't getting focus when dragging (#8063)
12490 this.uiDialog.focus();
12491 }
12492 }
12493 });
12494
12495 this.uiDialogTitlebarClose = $("<button></button>")
12496 .button({
12497 label: this.options.closeText,
12498 icons: {
12499 primary: "ui-icon-closethick"
12500 },
12501 text: false
12502 })
12503 .addClass("ui-dialog-titlebar-close")
12504 .appendTo( this.uiDialogTitlebar );
12505 this._on( this.uiDialogTitlebarClose, {
12506 click: function( event ) {
12507 event.preventDefault();
12508 this.close( event );
12509 }
12510 });
12511
12512 uiDialogTitle = $("<span>")
12513 .uniqueId()
12514 .addClass("ui-dialog-title")
12515 .prependTo( this.uiDialogTitlebar );
12516 this._title( uiDialogTitle );
12517
12518 this.uiDialog.attr({
12519 "aria-labelledby": uiDialogTitle.attr("id")
12520 });
12521 },
12522
12523 _title: function( title ) {
12524 if ( !this.options.title ) {
12525 title.html("&#160;");
12526 }
12527 title.text( this.options.title );
12528 },
12529
12530 _createButtonPane: function() {
12531 this.uiDialogButtonPane = $("<div>")
12532 .addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix");
12533
12534 this.uiButtonSet = $("<div>")
12535 .addClass("ui-dialog-buttonset")
12536 .appendTo( this.uiDialogButtonPane );
12537
12538 this._createButtons();
12539 },
12540
12541 _createButtons: function() {
12542 var that = this,
12543 buttons = this.options.buttons;
12544
12545 // if we already have a button pane, remove it
12546 this.uiDialogButtonPane.remove();
12547 this.uiButtonSet.empty();
12548
12549 if ( $.isEmptyObject( buttons ) || ($.isArray( buttons ) && !buttons.length) ) {
12550 this.uiDialog.removeClass("ui-dialog-buttons");
12551 return;
12552 }
12553
12554 $.each( buttons, function( name, props ) {
12555 var click, buttonOptions;
12556 props = $.isFunction( props ) ?
12557 { click: props, text: name } :
12558 props;
12559 // Default to a non-submitting button
12560 props = $.extend( { type: "button" }, props );
12561 // Change the context for the click callback to be the main element
12562 click = props.click;
12563 props.click = function() {
12564 click.apply( that.element[0], arguments );
12565 };
12566 buttonOptions = {
12567 icons: props.icons,
12568 text: props.showText
12569 };
12570 delete props.icons;
12571 delete props.showText;
12572 $( "<button></button>", props )
12573 .button( buttonOptions )
12574 .appendTo( that.uiButtonSet );
12575 });
12576 this.uiDialog.addClass("ui-dialog-buttons");
12577 this.uiDialogButtonPane.appendTo( this.uiDialog );
12578 },
12579
12580 _makeDraggable: function() {
12581 var that = this,
12582 options = this.options;
12583
12584 function filteredUi( ui ) {
12585 return {
12586 position: ui.position,
12587 offset: ui.offset
12588 };
12589 }
12590
12591 this.uiDialog.draggable({
12592 cancel: ".ui-dialog-content, .ui-dialog-titlebar-close",
12593 handle: ".ui-dialog-titlebar",
12594 containment: "document",
12595 start: function( event, ui ) {
12596 $( this ).addClass("ui-dialog-dragging");
12597 that._blockFrames();
12598 that._trigger( "dragStart", event, filteredUi( ui ) );
12599 },
12600 drag: function( event, ui ) {
12601 that._trigger( "drag", event, filteredUi( ui ) );
12602 },
12603 stop: function( event, ui ) {
12604 options.position = [
12605 ui.position.left - that.document.scrollLeft(),
12606 ui.position.top - that.document.scrollTop()
12607 ];
12608 $( this ).removeClass("ui-dialog-dragging");
12609 that._unblockFrames();
12610 that._trigger( "dragStop", event, filteredUi( ui ) );
12611 }
12612 });
12613 },
12614
12615 _makeResizable: function() {
12616 var that = this,
12617 options = this.options,
12618 handles = options.resizable,
12619 // .ui-resizable has position: relative defined in the stylesheet
12620 // but dialogs have to use absolute or fixed positioning
12621 position = this.uiDialog.css("position"),
12622 resizeHandles = typeof handles === "string" ?
12623 handles :
12624 "n,e,s,w,se,sw,ne,nw";
12625
12626 function filteredUi( ui ) {
12627 return {
12628 originalPosition: ui.originalPosition,
12629 originalSize: ui.originalSize,
12630 position: ui.position,
12631 size: ui.size
12632 };
12633 }
12634
12635 this.uiDialog.resizable({
12636 cancel: ".ui-dialog-content",
12637 containment: "document",
12638 alsoResize: this.element,
12639 maxWidth: options.maxWidth,
12640 maxHeight: options.maxHeight,
12641 minWidth: options.minWidth,
12642 minHeight: this._minHeight(),
12643 handles: resizeHandles,
12644 start: function( event, ui ) {
12645 $( this ).addClass("ui-dialog-resizing");
12646 that._blockFrames();
12647 that._trigger( "resizeStart", event, filteredUi( ui ) );
12648 },
12649 resize: function( event, ui ) {
12650 that._trigger( "resize", event, filteredUi( ui ) );
12651 },
12652 stop: function( event, ui ) {
12653 options.height = $( this ).height();
12654 options.width = $( this ).width();
12655 $( this ).removeClass("ui-dialog-resizing");
12656 that._unblockFrames();
12657 that._trigger( "resizeStop", event, filteredUi( ui ) );
12658 }
12659 })
12660 .css( "position", position );
12661 },
12662
12663 _minHeight: function() {
12664 var options = this.options;
12665
12666 return options.height === "auto" ?
12667 options.minHeight :
12668 Math.min( options.minHeight, options.height );
12669 },
12670
12671 _position: function() {
12672 // Need to show the dialog to get the actual offset in the position plugin
12673 var isVisible = this.uiDialog.is(":visible");
12674 if ( !isVisible ) {
12675 this.uiDialog.show();
12676 }
12677 this.uiDialog.position( this.options.position );
12678 if ( !isVisible ) {
12679 this.uiDialog.hide();
12680 }
12681 },
12682
12683 _setOptions: function( options ) {
12684 var that = this,
12685 resize = false,
12686 resizableOptions = {};
12687
12688 $.each( options, function( key, value ) {
12689 that._setOption( key, value );
12690
12691 if ( key in sizeRelatedOptions ) {
12692 resize = true;
12693 }
12694 if ( key in resizableRelatedOptions ) {
12695 resizableOptions[ key ] = value;
12696 }
12697 });
12698
12699 if ( resize ) {
12700 this._size();
12701 this._position();
12702 }
12703 if ( this.uiDialog.is(":data(ui-resizable)") ) {
12704 this.uiDialog.resizable( "option", resizableOptions );
12705 }
12706 },
12707
12708 _setOption: function( key, value ) {
12709 /*jshint maxcomplexity:15*/
12710 var isDraggable, isResizable,
12711 uiDialog = this.uiDialog;
12712
12713 if ( key === "dialogClass" ) {
12714 uiDialog
12715 .removeClass( this.options.dialogClass )
12716 .addClass( value );
12717 }
12718
12719 if ( key === "disabled" ) {
12720 return;
12721 }
12722
12723 this._super( key, value );
12724
12725 if ( key === "appendTo" ) {
12726 this.uiDialog.appendTo( this._appendTo() );
12727 }
12728
12729 if ( key === "buttons" ) {
12730 this._createButtons();
12731 }
12732
12733 if ( key === "closeText" ) {
12734 this.uiDialogTitlebarClose.button({
12735 // Ensure that we always pass a string
12736 label: "" + value
12737 });
12738 }
12739
12740 if ( key === "draggable" ) {
12741 isDraggable = uiDialog.is(":data(ui-draggable)");
12742 if ( isDraggable && !value ) {
12743 uiDialog.draggable("destroy");
12744 }
12745
12746 if ( !isDraggable && value ) {
12747 this._makeDraggable();
12748 }
12749 }
12750
12751 if ( key === "position" ) {
12752 this._position();
12753 }
12754
12755 if ( key === "resizable" ) {
12756 // currently resizable, becoming non-resizable
12757 isResizable = uiDialog.is(":data(ui-resizable)");
12758 if ( isResizable && !value ) {
12759 uiDialog.resizable("destroy");
12760 }
12761
12762 // currently resizable, changing handles
12763 if ( isResizable && typeof value === "string" ) {
12764 uiDialog.resizable( "option", "handles", value );
12765 }
12766
12767 // currently non-resizable, becoming resizable
12768 if ( !isResizable && value !== false ) {
12769 this._makeResizable();
12770 }
12771 }
12772
12773 if ( key === "title" ) {
12774 this._title( this.uiDialogTitlebar.find(".ui-dialog-title") );
12775 }
12776 },
12777
12778 _size: function() {
12779 // If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
12780 // divs will both have width and height set, so we need to reset them
12781 var nonContentHeight, minContentHeight, maxContentHeight,
12782 options = this.options;
12783
12784 // Reset content sizing
12785 this.element.show().css({
12786 width: "auto",
12787 minHeight: 0,
12788 maxHeight: "none",
12789 height: 0
12790 });
12791
12792 if ( options.minWidth > options.width ) {
12793 options.width = options.minWidth;
12794 }
12795
12796 // reset wrapper sizing
12797 // determine the height of all the non-content elements
12798 nonContentHeight = this.uiDialog.css({
12799 height: "auto",
12800 width: options.width
12801 })
12802 .outerHeight();
12803 minContentHeight = Math.max( 0, options.minHeight - nonContentHeight );
12804 maxContentHeight = typeof options.maxHeight === "number" ?
12805 Math.max( 0, options.maxHeight - nonContentHeight ) :
12806 "none";
12807
12808 if ( options.height === "auto" ) {
12809 this.element.css({
12810 minHeight: minContentHeight,
12811 maxHeight: maxContentHeight,
12812 height: "auto"
12813 });
12814 } else {
12815 this.element.height( Math.max( 0, options.height - nonContentHeight ) );
12816 }
12817
12818 if (this.uiDialog.is(":data(ui-resizable)") ) {
12819 this.uiDialog.resizable( "option", "minHeight", this._minHeight() );
12820 }
12821 },
12822
12823 _blockFrames: function() {
12824 this.iframeBlocks = this.document.find( "iframe" ).map(function() {
12825 var iframe = $( this );
12826
12827 return $( "<div>" )
12828 .css({
12829 position: "absolute",
12830 width: iframe.outerWidth(),
12831 height: iframe.outerHeight()
12832 })
12833 .appendTo( iframe.parent() )
12834 .offset( iframe.offset() )[0];
12835 });
12836 },
12837
12838 _unblockFrames: function() {
12839 if ( this.iframeBlocks ) {
12840 this.iframeBlocks.remove();
12841 delete this.iframeBlocks;
12842 }
12843 },
12844
12845 _allowInteraction: function( event ) {
12846 if ( $( event.target ).closest(".ui-dialog").length ) {
12847 return true;
12848 }
12849
12850 // TODO: Remove hack when datepicker implements
12851 // the .ui-front logic (#8989)
12852 return !!$( event.target ).closest(".ui-datepicker").length;
12853 },
12854
12855 _createOverlay: function() {
12856 if ( !this.options.modal ) {
12857 return;
12858 }
12859
12860 var that = this,
12861 widgetFullName = this.widgetFullName;
12862 if ( !$.ui.dialog.overlayInstances ) {
12863 // Prevent use of anchors and inputs.
12864 // We use a delay in case the overlay is created from an
12865 // event that we're going to be cancelling. (#2804)
12866 this._delay(function() {
12867 // Handle .dialog().dialog("close") (#4065)
12868 if ( $.ui.dialog.overlayInstances ) {
12869 this.document.bind( "focusin.dialog", function( event ) {
12870 if ( !that._allowInteraction( event ) ) {
12871 event.preventDefault();
12872 $(".ui-dialog:visible:last .ui-dialog-content")
12873 .data( widgetFullName )._focusTabbable();
12874 }
12875 });
12876 }
12877 });
12878 }
12879
12880 this.overlay = $("<div>")
12881 .addClass("ui-widget-overlay ui-front")
12882 .appendTo( this._appendTo() );
12883 this._on( this.overlay, {
12884 mousedown: "_keepFocus"
12885 });
12886 $.ui.dialog.overlayInstances++;
12887 },
12888
12889 _destroyOverlay: function() {
12890 if ( !this.options.modal ) {
12891 return;
12892 }
12893
12894 if ( this.overlay ) {
12895 $.ui.dialog.overlayInstances--;
12896
12897 if ( !$.ui.dialog.overlayInstances ) {
12898 this.document.unbind( "focusin.dialog" );
12899 }
12900 this.overlay.remove();
12901 this.overlay = null;
12902 }
12903 }
12904 });
12905
12906 $.ui.dialog.overlayInstances = 0;
12907
12908 // DEPRECATED
12909 if ( $.uiBackCompat !== false ) {
12910 // position option with array notation
12911 // just override with old implementation
12912 $.widget( "ui.dialog", $.ui.dialog, {
12913 _position: function() {
12914 var position = this.options.position,
12915 myAt = [],
12916 offset = [ 0, 0 ],
12917 isVisible;
12918
12919 if ( position ) {
12920 if ( typeof position === "string" || (typeof position === "object" && "0" in position ) ) {
12921 myAt = position.split ? position.split(" ") : [ position[0], position[1] ];
12922 if ( myAt.length === 1 ) {
12923 myAt[1] = myAt[0];
12924 }
12925
12926 $.each( [ "left", "top" ], function( i, offsetPosition ) {
12927 if ( +myAt[ i ] === myAt[ i ] ) {
12928 offset[ i ] = myAt[ i ];
12929 myAt[ i ] = offsetPosition;
12930 }
12931 });
12932
12933 position = {
12934 my: myAt[0] + (offset[0] < 0 ? offset[0] : "+" + offset[0]) + " " +
12935 myAt[1] + (offset[1] < 0 ? offset[1] : "+" + offset[1]),
12936 at: myAt.join(" ")
12937 };
12938 }
12939
12940 position = $.extend( {}, $.ui.dialog.prototype.options.position, position );
12941 } else {
12942 position = $.ui.dialog.prototype.options.position;
12943 }
12944
12945 // need to show the dialog to get the actual offset in the position plugin
12946 isVisible = this.uiDialog.is(":visible");
12947 if ( !isVisible ) {
12948 this.uiDialog.show();
12949 }
12950 this.uiDialog.position( position );
12951 if ( !isVisible ) {
12952 this.uiDialog.hide();
12953 }
12954 }
12955 });
12956 }
12957
12958 }( jQuery ) );
12959 (function( $, undefined ) {
12960
12961 $.widget( "ui.menu", {
12962 version: "1.10.3",
12963 defaultElement: "<ul>",
12964 delay: 300,
12965 options: {
12966 icons: {
12967 submenu: "ui-icon-carat-1-e"
12968 },
12969 menus: "ul",
12970 position: {
12971 my: "left top",
12972 at: "right top"
12973 },
12974 role: "menu",
12975
12976 // callbacks
12977 blur: null,
12978 focus: null,
12979 select: null
12980 },
12981
12982 _create: function() {
12983 this.activeMenu = this.element;
12984 // flag used to prevent firing of the click handler
12985 // as the event bubbles up through nested menus
12986 this.mouseHandled = false;
12987 this.element
12988 .uniqueId()
12989 .addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
12990 .toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length )
12991 .attr({
12992 role: this.options.role,
12993 tabIndex: 0
12994 })
12995 // need to catch all clicks on disabled menu
12996 // not possible through _on
12997 .bind( "click" + this.eventNamespace, $.proxy(function( event ) {
12998 if ( this.options.disabled ) {
12999 event.preventDefault();
13000 }
13001 }, this ));
13002
13003 if ( this.options.disabled ) {
13004 this.element
13005 .addClass( "ui-state-disabled" )
13006 .attr( "aria-disabled", "true" );
13007 }
13008
13009 this._on({
13010 // Prevent focus from sticking to links inside menu after clicking
13011 // them (focus should always stay on UL during navigation).
13012 "mousedown .ui-menu-item > a": function( event ) {
13013 event.preventDefault();
13014 },
13015 "click .ui-state-disabled > a": function( event ) {
13016 event.preventDefault();
13017 },
13018 "click .ui-menu-item:has(a)": function( event ) {
13019 var target = $( event.target ).closest( ".ui-menu-item" );
13020 if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) {
13021 this.mouseHandled = true;
13022
13023 this.select( event );
13024 // Open submenu on click
13025 if ( target.has( ".ui-menu" ).length ) {
13026 this.expand( event );
13027 } else if ( !this.element.is( ":focus" ) ) {
13028 // Redirect focus to the menu
13029 this.element.trigger( "focus", [ true ] );
13030
13031 // If the active item is on the top level, let it stay active.
13032 // Otherwise, blur the active item since it is no longer visible.
13033 if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) {
13034 clearTimeout( this.timer );
13035 }
13036 }
13037 }
13038 },
13039 "mouseenter .ui-menu-item": function( event ) {
13040 var target = $( event.currentTarget );
13041 // Remove ui-state-active class from siblings of the newly focused menu item
13042 // to avoid a jump caused by adjacent elements both having a class with a border
13043 target.siblings().children( ".ui-state-active" ).removeClass( "ui-state-active" );
13044 this.focus( event, target );
13045 },
13046 mouseleave: "collapseAll",
13047 "mouseleave .ui-menu": "collapseAll",
13048 focus: function( event, keepActiveItem ) {
13049 // If there's already an active item, keep it active
13050 // If not, activate the first item
13051 var item = this.active || this.element.children( ".ui-menu-item" ).eq( 0 );
13052
13053 if ( !keepActiveItem ) {
13054 this.focus( event, item );
13055 }
13056 },
13057 blur: function( event ) {
13058 this._delay(function() {
13059 if ( !$.contains( this.element[0], this.document[0].activeElement ) ) {
13060 this.collapseAll( event );
13061 }
13062 });
13063 },
13064 keydown: "_keydown"
13065 });
13066
13067 this.refresh();
13068
13069 // Clicks outside of a menu collapse any open menus
13070 this._on( this.document, {
13071 click: function( event ) {
13072 if ( !$( event.target ).closest( ".ui-menu" ).length ) {
13073 this.collapseAll( event );
13074 }
13075
13076 // Reset the mouseHandled flag
13077 this.mouseHandled = false;
13078 }
13079 });
13080 },
13081
13082 _destroy: function() {
13083 // Destroy (sub)menus
13084 this.element
13085 .removeAttr( "aria-activedescendant" )
13086 .find( ".ui-menu" ).addBack()
13087 .removeClass( "ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons" )
13088 .removeAttr( "role" )
13089 .removeAttr( "tabIndex" )
13090 .removeAttr( "aria-labelledby" )
13091 .removeAttr( "aria-expanded" )
13092 .removeAttr( "aria-hidden" )
13093 .removeAttr( "aria-disabled" )
13094 .removeUniqueId()
13095 .show();
13096
13097 // Destroy menu items
13098 this.element.find( ".ui-menu-item" )
13099 .removeClass( "ui-menu-item" )
13100 .removeAttr( "role" )
13101 .removeAttr( "aria-disabled" )
13102 .children( "a" )
13103 .removeUniqueId()
13104 .removeClass( "ui-corner-all ui-state-hover" )
13105 .removeAttr( "tabIndex" )
13106 .removeAttr( "role" )
13107 .removeAttr( "aria-haspopup" )
13108 .children().each( function() {
13109 var elem = $( this );
13110 if ( elem.data( "ui-menu-submenu-carat" ) ) {
13111 elem.remove();
13112 }
13113 });
13114
13115 // Destroy menu dividers
13116 this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" );
13117 },
13118
13119 _keydown: function( event ) {
13120 /*jshint maxcomplexity:20*/
13121 var match, prev, character, skip, regex,
13122 preventDefault = true;
13123
13124 function escape( value ) {
13125 return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
13126 }
13127
13128 switch ( event.keyCode ) {
13129 case $.ui.keyCode.PAGE_UP:
13130 this.previousPage( event );
13131 break;
13132 case $.ui.keyCode.PAGE_DOWN:
13133 this.nextPage( event );
13134 break;
13135 case $.ui.keyCode.HOME:
13136 this._move( "first", "first", event );
13137 break;
13138 case $.ui.keyCode.END:
13139 this._move( "last", "last", event );
13140 break;
13141 case $.ui.keyCode.UP:
13142 this.previous( event );
13143 break;
13144 case $.ui.keyCode.DOWN:
13145 this.next( event );
13146 break;
13147 case $.ui.keyCode.LEFT:
13148 this.collapse( event );
13149 break;
13150 case $.ui.keyCode.RIGHT:
13151 if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
13152 this.expand( event );
13153 }
13154 break;
13155 case $.ui.keyCode.ENTER:
13156 case $.ui.keyCode.SPACE:
13157 this._activate( event );
13158 break;
13159 case $.ui.keyCode.ESCAPE:
13160 this.collapse( event );
13161 break;
13162 default:
13163 preventDefault = false;
13164 prev = this.previousFilter || "";
13165 character = String.fromCharCode( event.keyCode );
13166 skip = false;
13167
13168 clearTimeout( this.filterTimer );
13169
13170 if ( character === prev ) {
13171 skip = true;
13172 } else {
13173 character = prev + character;
13174 }
13175
13176 regex = new RegExp( "^" + escape( character ), "i" );
13177 match = this.activeMenu.children( ".ui-menu-item" ).filter(function() {
13178 return regex.test( $( this ).children( "a" ).text() );
13179 });
13180 match = skip && match.index( this.active.next() ) !== -1 ?
13181 this.active.nextAll( ".ui-menu-item" ) :
13182 match;
13183
13184 // If no matches on the current filter, reset to the last character pressed
13185 // to move down the menu to the first item that starts with that character
13186 if ( !match.length ) {
13187 character = String.fromCharCode( event.keyCode );
13188 regex = new RegExp( "^" + escape( character ), "i" );
13189 match = this.activeMenu.children( ".ui-menu-item" ).filter(function() {
13190 return regex.test( $( this ).children( "a" ).text() );
13191 });
13192 }
13193
13194 if ( match.length ) {
13195 this.focus( event, match );
13196 if ( match.length > 1 ) {
13197 this.previousFilter = character;
13198 this.filterTimer = this._delay(function() {
13199 delete this.previousFilter;
13200 }, 1000 );
13201 } else {
13202 delete this.previousFilter;
13203 }
13204 } else {
13205 delete this.previousFilter;
13206 }
13207 }
13208
13209 if ( preventDefault ) {
13210 event.preventDefault();
13211 }
13212 },
13213
13214 _activate: function( event ) {
13215 if ( !this.active.is( ".ui-state-disabled" ) ) {
13216 if ( this.active.children( "a[aria-haspopup='true']" ).length ) {
13217 this.expand( event );
13218 } else {
13219 this.select( event );
13220 }
13221 }
13222 },
13223
13224 refresh: function() {
13225 var menus,
13226 icon = this.options.icons.submenu,
13227 submenus = this.element.find( this.options.menus );
13228
13229 // Initialize nested menus
13230 submenus.filter( ":not(.ui-menu)" )
13231 .addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
13232 .hide()
13233 .attr({
13234 role: this.options.role,
13235 "aria-hidden": "true",
13236 "aria-expanded": "false"
13237 })
13238 .each(function() {
13239 var menu = $( this ),
13240 item = menu.prev( "a" ),
13241 submenuCarat = $( "<span>" )
13242 .addClass( "ui-menu-icon ui-icon " + icon )
13243 .data( "ui-menu-submenu-carat", true );
13244
13245 item
13246 .attr( "aria-haspopup", "true" )
13247 .prepend( submenuCarat );
13248 menu.attr( "aria-labelledby", item.attr( "id" ) );
13249 });
13250
13251 menus = submenus.add( this.element );
13252
13253 // Don't refresh list items that are already adapted
13254 menus.children( ":not(.ui-menu-item):has(a)" )
13255 .addClass( "ui-menu-item" )
13256 .attr( "role", "presentation" )
13257 .children( "a" )
13258 .uniqueId()
13259 .addClass( "ui-corner-all" )
13260 .attr({
13261 tabIndex: -1,
13262 role: this._itemRole()
13263 });
13264
13265 // Initialize unlinked menu-items containing spaces and/or dashes only as dividers
13266 menus.children( ":not(.ui-menu-item)" ).each(function() {
13267 var item = $( this );
13268 // hyphen, em dash, en dash
13269 if ( !/[^\-\u2014\u2013\s]/.test( item.text() ) ) {
13270 item.addClass( "ui-widget-content ui-menu-divider" );
13271 }
13272 });
13273
13274 // Add aria-disabled attribute to any disabled menu item
13275 menus.children( ".ui-state-disabled" ).attr( "aria-disabled", "true" );
13276
13277 // If the active item has been removed, blur the menu
13278 if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
13279 this.blur();
13280 }
13281 },
13282
13283 _itemRole: function() {
13284 return {
13285 menu: "menuitem",
13286 listbox: "option"
13287 }[ this.options.role ];
13288 },
13289
13290 _setOption: function( key, value ) {
13291 if ( key === "icons" ) {
13292 this.element.find( ".ui-menu-icon" )
13293 .removeClass( this.options.icons.submenu )
13294 .addClass( value.submenu );
13295 }
13296 this._super( key, value );
13297 },
13298
13299 focus: function( event, item ) {
13300 var nested, focused;
13301 this.blur( event, event && event.type === "focus" );
13302
13303 this._scrollIntoView( item );
13304
13305 this.active = item.first();
13306 focused = this.active.children( "a" ).addClass( "ui-state-focus" );
13307 // Only update aria-activedescendant if there's a role
13308 // otherwise we assume focus is managed elsewhere
13309 if ( this.options.role ) {
13310 this.element.attr( "aria-activedescendant", focused.attr( "id" ) );
13311 }
13312
13313 // Highlight active parent menu item, if any
13314 this.active
13315 .parent()
13316 .closest( ".ui-menu-item" )
13317 .children( "a:first" )
13318 .addClass( "ui-state-active" );
13319
13320 if ( event && event.type === "keydown" ) {
13321 this._close();
13322 } else {
13323 this.timer = this._delay(function() {
13324 this._close();
13325 }, this.delay );
13326 }
13327
13328 nested = item.children( ".ui-menu" );
13329 if ( nested.length && ( /^mouse/.test( event.type ) ) ) {
13330 this._startOpening(nested);
13331 }
13332 this.activeMenu = item.parent();
13333
13334 this._trigger( "focus", event, { item: item } );
13335 },
13336
13337 _scrollIntoView: function( item ) {
13338 var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
13339 if ( this._hasScroll() ) {
13340 borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0;
13341 paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0;
13342 offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
13343 scroll = this.activeMenu.scrollTop();
13344 elementHeight = this.activeMenu.height();
13345 itemHeight = item.height();
13346
13347 if ( offset < 0 ) {
13348 this.activeMenu.scrollTop( scroll + offset );
13349 } else if ( offset + itemHeight > elementHeight ) {
13350 this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
13351 }
13352 }
13353 },
13354
13355 blur: function( event, fromFocus ) {
13356 if ( !fromFocus ) {
13357 clearTimeout( this.timer );
13358 }
13359
13360 if ( !this.active ) {
13361 return;
13362 }
13363
13364 this.active.children( "a" ).removeClass( "ui-state-focus" );
13365 this.active = null;
13366
13367 this._trigger( "blur", event, { item: this.active } );
13368 },
13369
13370 _startOpening: function( submenu ) {
13371 clearTimeout( this.timer );
13372
13373 // Don't open if already open fixes a Firefox bug that caused a .5 pixel
13374 // shift in the submenu position when mousing over the carat icon
13375 if ( submenu.attr( "aria-hidden" ) !== "true" ) {
13376 return;
13377 }
13378
13379 this.timer = this._delay(function() {
13380 this._close();
13381 this._open( submenu );
13382 }, this.delay );
13383 },
13384
13385 _open: function( submenu ) {
13386 var position = $.extend({
13387 of: this.active
13388 }, this.options.position );
13389
13390 clearTimeout( this.timer );
13391 this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) )
13392 .hide()
13393 .attr( "aria-hidden", "true" );
13394
13395 submenu
13396 .show()
13397 .removeAttr( "aria-hidden" )
13398 .attr( "aria-expanded", "true" )
13399 .position( position );
13400 },
13401
13402 collapseAll: function( event, all ) {
13403 clearTimeout( this.timer );
13404 this.timer = this._delay(function() {
13405 // If we were passed an event, look for the submenu that contains the event
13406 var currentMenu = all ? this.element :
13407 $( event && event.target ).closest( this.element.find( ".ui-menu" ) );
13408
13409 // If we found no valid submenu ancestor, use the main menu to close all sub menus anyway
13410 if ( !currentMenu.length ) {
13411 currentMenu = this.element;
13412 }
13413
13414 this._close( currentMenu );
13415
13416 this.blur( event );
13417 this.activeMenu = currentMenu;
13418 }, this.delay );
13419 },
13420
13421 // With no arguments, closes the currently active menu - if nothing is active
13422 // it closes all menus. If passed an argument, it will search for menus BELOW
13423 _close: function( startMenu ) {
13424 if ( !startMenu ) {
13425 startMenu = this.active ? this.active.parent() : this.element;
13426 }
13427
13428 startMenu
13429 .find( ".ui-menu" )
13430 .hide()
13431 .attr( "aria-hidden", "true" )
13432 .attr( "aria-expanded", "false" )
13433 .end()
13434 .find( "a.ui-state-active" )
13435 .removeClass( "ui-state-active" );
13436 },
13437
13438 collapse: function( event ) {
13439 var newItem = this.active &&
13440 this.active.parent().closest( ".ui-menu-item", this.element );
13441 if ( newItem && newItem.length ) {
13442 this._close();
13443 this.focus( event, newItem );
13444 }
13445 },
13446
13447 expand: function( event ) {
13448 var newItem = this.active &&
13449 this.active
13450 .children( ".ui-menu " )
13451 .children( ".ui-menu-item" )
13452 .first();
13453
13454 if ( newItem && newItem.length ) {
13455 this._open( newItem.parent() );
13456
13457 // Delay so Firefox will not hide activedescendant change in expanding submenu from AT
13458 this._delay(function() {
13459 this.focus( event, newItem );
13460 });
13461 }
13462 },
13463
13464 next: function( event ) {
13465 this._move( "next", "first", event );
13466 },
13467
13468 previous: function( event ) {
13469 this._move( "prev", "last", event );
13470 },
13471
13472 isFirstItem: function() {
13473 return this.active && !this.active.prevAll( ".ui-menu-item" ).length;
13474 },
13475
13476 isLastItem: function() {
13477 return this.active && !this.active.nextAll( ".ui-menu-item" ).length;
13478 },
13479
13480 _move: function( direction, filter, event ) {
13481 var next;
13482 if ( this.active ) {
13483 if ( direction === "first" || direction === "last" ) {
13484 next = this.active
13485 [ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" )
13486 .eq( -1 );
13487 } else {
13488 next = this.active
13489 [ direction + "All" ]( ".ui-menu-item" )
13490 .eq( 0 );
13491 }
13492 }
13493 if ( !next || !next.length || !this.active ) {
13494 next = this.activeMenu.children( ".ui-menu-item" )[ filter ]();
13495 }
13496
13497 this.focus( event, next );
13498 },
13499
13500 nextPage: function( event ) {
13501 var item, base, height;
13502
13503 if ( !this.active ) {
13504 this.next( event );
13505 return;
13506 }
13507 if ( this.isLastItem() ) {
13508 return;
13509 }
13510 if ( this._hasScroll() ) {
13511 base = this.active.offset().top;
13512 height = this.element.height();
13513 this.active.nextAll( ".ui-menu-item" ).each(function() {
13514 item = $( this );
13515 return item.offset().top - base - height < 0;
13516 });
13517
13518 this.focus( event, item );
13519 } else {
13520 this.focus( event, this.activeMenu.children( ".ui-menu-item" )
13521 [ !this.active ? "first" : "last" ]() );
13522 }
13523 },
13524
13525 previousPage: function( event ) {
13526 var item, base, height;
13527 if ( !this.active ) {
13528 this.next( event );
13529 return;
13530 }
13531 if ( this.isFirstItem() ) {
13532 return;
13533 }
13534 if ( this._hasScroll() ) {
13535 base = this.active.offset().top;
13536 height = this.element.height();
13537 this.active.prevAll( ".ui-menu-item" ).each(function() {
13538 item = $( this );
13539 return item.offset().top - base + height > 0;
13540 });
13541
13542 this.focus( event, item );
13543 } else {
13544 this.focus( event, this.activeMenu.children( ".ui-menu-item" ).first() );
13545 }
13546 },
13547
13548 _hasScroll: function() {
13549 return this.element.outerHeight() < this.element.prop( "scrollHeight" );
13550 },
13551
13552 select: function( event ) {
13553 // TODO: It should never be possible to not have an active item at this
13554 // point, but the tests don't trigger mouseenter before click.
13555 this.active = this.active || $( event.target ).closest( ".ui-menu-item" );
13556 var ui = { item: this.active };
13557 if ( !this.active.has( ".ui-menu" ).length ) {
13558 this.collapseAll( event, true );
13559 }
13560 this._trigger( "select", event, ui );
13561 }
13562 });
13563
13564 }( jQuery ));
13565 (function( $, undefined ) {
13566
13567 $.widget( "ui.progressbar", {
13568 version: "1.10.3",
13569 options: {
13570 max: 100,
13571 value: 0,
13572
13573 change: null,
13574 complete: null
13575 },
13576
13577 min: 0,
13578
13579 _create: function() {
13580 // Constrain initial value
13581 this.oldValue = this.options.value = this._constrainedValue();
13582
13583 this.element
13584 .addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
13585 .attr({
13586 // Only set static values, aria-valuenow and aria-valuemax are
13587 // set inside _refreshValue()
13588 role: "progressbar",
13589 "aria-valuemin": this.min
13590 });
13591
13592 this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" )
13593 .appendTo( this.element );
13594
13595 this._refreshValue();
13596 },
13597
13598 _destroy: function() {
13599 this.element
13600 .removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
13601 .removeAttr( "role" )
13602 .removeAttr( "aria-valuemin" )
13603 .removeAttr( "aria-valuemax" )
13604 .removeAttr( "aria-valuenow" );
13605
13606 this.valueDiv.remove();
13607 },
13608
13609 value: function( newValue ) {
13610 if ( newValue === undefined ) {
13611 return this.options.value;
13612 }
13613
13614 this.options.value = this._constrainedValue( newValue );
13615 this._refreshValue();
13616 },
13617
13618 _constrainedValue: function( newValue ) {
13619 if ( newValue === undefined ) {
13620 newValue = this.options.value;
13621 }
13622
13623 this.indeterminate = newValue === false;
13624
13625 // sanitize value
13626 if ( typeof newValue !== "number" ) {
13627 newValue = 0;
13628 }
13629
13630 return this.indeterminate ? false :
13631 Math.min( this.options.max, Math.max( this.min, newValue ) );
13632 },
13633
13634 _setOptions: function( options ) {
13635 // Ensure "value" option is set after other values (like max)
13636 var value = options.value;
13637 delete options.value;
13638
13639 this._super( options );
13640
13641 this.options.value = this._constrainedValue( value );
13642 this._refreshValue();
13643 },
13644
13645 _setOption: function( key, value ) {
13646 if ( key === "max" ) {
13647 // Don't allow a max less than min
13648 value = Math.max( this.min, value );
13649 }
13650
13651 this._super( key, value );
13652 },
13653
13654 _percentage: function() {
13655 return this.indeterminate ? 100 : 100 * ( this.options.value - this.min ) / ( this.options.max - this.min );
13656 },
13657
13658 _refreshValue: function() {
13659 var value = this.options.value,
13660 percentage = this._percentage();
13661
13662 this.valueDiv
13663 .toggle( this.indeterminate || value > this.min )
13664 .toggleClass( "ui-corner-right", value === this.options.max )
13665 .width( percentage.toFixed(0) + "%" );
13666
13667 this.element.toggleClass( "ui-progressbar-indeterminate", this.indeterminate );
13668
13669 if ( this.indeterminate ) {
13670 this.element.removeAttr( "aria-valuenow" );
13671 if ( !this.overlayDiv ) {
13672 this.overlayDiv = $( "<div class='ui-progressbar-overlay'></div>" ).appendTo( this.valueDiv );
13673 }
13674 } else {
13675 this.element.attr({
13676 "aria-valuemax": this.options.max,
13677 "aria-valuenow": value
13678 });
13679 if ( this.overlayDiv ) {
13680 this.overlayDiv.remove();
13681 this.overlayDiv = null;
13682 }
13683 }
13684
13685 if ( this.oldValue !== value ) {
13686 this.oldValue = value;
13687 this._trigger( "change" );
13688 }
13689 if ( value === this.options.max ) {
13690 this._trigger( "complete" );
13691 }
13692 }
13693 });
13694
13695 })( jQuery );
13696 (function( $, undefined ) {
13697
13698 // number of pages in a slider
13699 // (how many times can you page up/down to go through the whole range)
13700 var numPages = 5;
13701
13702 $.widget( "ui.slider", $.ui.mouse, {
13703 version: "1.10.3",
13704 widgetEventPrefix: "slide",
13705
13706 options: {
13707 animate: false,
13708 distance: 0,
13709 max: 100,
13710 min: 0,
13711 orientation: "horizontal",
13712 range: false,
13713 step: 1,
13714 value: 0,
13715 values: null,
13716
13717 // callbacks
13718 change: null,
13719 slide: null,
13720 start: null,
13721 stop: null
13722 },
13723
13724 _create: function() {
13725 this._keySliding = false;
13726 this._mouseSliding = false;
13727 this._animateOff = true;
13728 this._handleIndex = null;
13729 this._detectOrientation();
13730 this._mouseInit();
13731
13732 this.element
13733 .addClass( "ui-slider" +
13734 " ui-slider-" + this.orientation +
13735 " ui-widget" +
13736 " ui-widget-content" +
13737 " ui-corner-all");
13738
13739 this._refresh();
13740 this._setOption( "disabled", this.options.disabled );
13741
13742 this._animateOff = false;
13743 },
13744
13745 _refresh: function() {
13746 this._createRange();
13747 this._createHandles();
13748 this._setupEvents();
13749 this._refreshValue();
13750 },
13751
13752 _createHandles: function() {
13753 var i, handleCount,
13754 options = this.options,
13755 existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ),
13756 handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",
13757 handles = [];
13758
13759 handleCount = ( options.values && options.values.length ) || 1;
13760
13761 if ( existingHandles.length > handleCount ) {
13762 existingHandles.slice( handleCount ).remove();
13763 existingHandles = existingHandles.slice( 0, handleCount );
13764 }
13765
13766 for ( i = existingHandles.length; i < handleCount; i++ ) {
13767 handles.push( handle );
13768 }
13769
13770 this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) );
13771
13772 this.handle = this.handles.eq( 0 );
13773
13774 this.handles.each(function( i ) {
13775 $( this ).data( "ui-slider-handle-index", i );
13776 });
13777 },
13778
13779 _createRange: function() {
13780 var options = this.options,
13781 classes = "";
13782
13783 if ( options.range ) {
13784 if ( options.range === true ) {
13785 if ( !options.values ) {
13786 options.values = [ this._valueMin(), this._valueMin() ];
13787 } else if ( options.values.length && options.values.length !== 2 ) {
13788 options.values = [ options.values[0], options.values[0] ];
13789 } else if ( $.isArray( options.values ) ) {
13790 options.values = options.values.slice(0);
13791 }
13792 }
13793
13794 if ( !this.range || !this.range.length ) {
13795 this.range = $( "<div></div>" )
13796 .appendTo( this.element );
13797
13798 classes = "ui-slider-range" +
13799 // note: this isn't the most fittingly semantic framework class for this element,
13800 // but worked best visually with a variety of themes
13801 " ui-widget-header ui-corner-all";
13802 } else {
13803 this.range.removeClass( "ui-slider-range-min ui-slider-range-max" )
13804 // Handle range switching from true to min/max
13805 .css({
13806 "left": "",
13807 "bottom": ""
13808 });
13809 }
13810
13811 this.range.addClass( classes +
13812 ( ( options.range === "min" || options.range === "max" ) ? " ui-slider-range-" + options.range : "" ) );
13813 } else {
13814 this.range = $([]);
13815 }
13816 },
13817
13818 _setupEvents: function() {
13819 var elements = this.handles.add( this.range ).filter( "a" );
13820 this._off( elements );
13821 this._on( elements, this._handleEvents );
13822 this._hoverable( elements );
13823 this._focusable( elements );
13824 },
13825
13826 _destroy: function() {
13827 this.handles.remove();
13828 this.range.remove();
13829
13830 this.element
13831 .removeClass( "ui-slider" +
13832 " ui-slider-horizontal" +
13833 " ui-slider-vertical" +
13834 " ui-widget" +
13835 " ui-widget-content" +
13836 " ui-corner-all" );
13837
13838 this._mouseDestroy();
13839 },
13840
13841 _mouseCapture: function( event ) {
13842 var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
13843 that = this,
13844 o = this.options;
13845
13846 if ( o.disabled ) {
13847 return false;
13848 }
13849
13850 this.elementSize = {
13851 width: this.element.outerWidth(),
13852 height: this.element.outerHeight()
13853 };
13854 this.elementOffset = this.element.offset();
13855
13856 position = { x: event.pageX, y: event.pageY };
13857 normValue = this._normValueFromMouse( position );
13858 distance = this._valueMax() - this._valueMin() + 1;
13859 this.handles.each(function( i ) {
13860 var thisDistance = Math.abs( normValue - that.values(i) );
13861 if (( distance > thisDistance ) ||
13862 ( distance === thisDistance &&
13863 (i === that._lastChangedValue || that.values(i) === o.min ))) {
13864 distance = thisDistance;
13865 closestHandle = $( this );
13866 index = i;
13867 }
13868 });
13869
13870 allowed = this._start( event, index );
13871 if ( allowed === false ) {
13872 return false;
13873 }
13874 this._mouseSliding = true;
13875
13876 this._handleIndex = index;
13877
13878 closestHandle
13879 .addClass( "ui-state-active" )
13880 .focus();
13881
13882 offset = closestHandle.offset();
13883 mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" );
13884 this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
13885 left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
13886 top: event.pageY - offset.top -
13887 ( closestHandle.height() / 2 ) -
13888 ( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) -
13889 ( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) +
13890 ( parseInt( closestHandle.css("marginTop"), 10 ) || 0)
13891 };
13892
13893 if ( !this.handles.hasClass( "ui-state-hover" ) ) {
13894 this._slide( event, index, normValue );
13895 }
13896 this._animateOff = true;
13897 return true;
13898 },
13899
13900 _mouseStart: function() {
13901 return true;
13902 },
13903
13904 _mouseDrag: function( event ) {
13905 var position = { x: event.pageX, y: event.pageY },
13906 normValue = this._normValueFromMouse( position );
13907
13908 this._slide( event, this._handleIndex, normValue );
13909
13910 return false;
13911 },
13912
13913 _mouseStop: function( event ) {
13914 this.handles.removeClass( "ui-state-active" );
13915 this._mouseSliding = false;
13916
13917 this._stop( event, this._handleIndex );
13918 this._change( event, this._handleIndex );
13919
13920 this._handleIndex = null;
13921 this._clickOffset = null;
13922 this._animateOff = false;
13923
13924 return false;
13925 },
13926
13927 _detectOrientation: function() {
13928 this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
13929 },
13930
13931 _normValueFromMouse: function( position ) {
13932 var pixelTotal,
13933 pixelMouse,
13934 percentMouse,
13935 valueTotal,
13936 valueMouse;
13937
13938 if ( this.orientation === "horizontal" ) {
13939 pixelTotal = this.elementSize.width;
13940 pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 );
13941 } else {
13942 pixelTotal = this.elementSize.height;
13943 pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 );
13944 }
13945
13946 percentMouse = ( pixelMouse / pixelTotal );
13947 if ( percentMouse > 1 ) {
13948 percentMouse = 1;
13949 }
13950 if ( percentMouse < 0 ) {
13951 percentMouse = 0;
13952 }
13953 if ( this.orientation === "vertical" ) {
13954 percentMouse = 1 - percentMouse;
13955 }
13956
13957 valueTotal = this._valueMax() - this._valueMin();
13958 valueMouse = this._valueMin() + percentMouse * valueTotal;
13959
13960 return this._trimAlignValue( valueMouse );
13961 },
13962
13963 _start: function( event, index ) {
13964 var uiHash = {
13965 handle: this.handles[ index ],
13966 value: this.value()
13967 };
13968 if ( this.options.values && this.options.values.length ) {
13969 uiHash.value = this.values( index );
13970 uiHash.values = this.values();
13971 }
13972 return this._trigger( "start", event, uiHash );
13973 },
13974
13975 _slide: function( event, index, newVal ) {
13976 var otherVal,
13977 newValues,
13978 allowed;
13979
13980 if ( this.options.values && this.options.values.length ) {
13981 otherVal = this.values( index ? 0 : 1 );
13982
13983 if ( ( this.options.values.length === 2 && this.options.range === true ) &&
13984 ( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) )
13985 ) {
13986 newVal = otherVal;
13987 }
13988
13989 if ( newVal !== this.values( index ) ) {
13990 newValues = this.values();
13991 newValues[ index ] = newVal;
13992 // A slide can be canceled by returning false from the slide callback
13993 allowed = this._trigger( "slide", event, {
13994 handle: this.handles[ index ],
13995 value: newVal,
13996 values: newValues
13997 } );
13998 otherVal = this.values( index ? 0 : 1 );
13999 if ( allowed !== false ) {
14000 this.values( index, newVal, true );
14001 }
14002 }
14003 } else {
14004 if ( newVal !== this.value() ) {
14005 // A slide can be canceled by returning false from the slide callback
14006 allowed = this._trigger( "slide", event, {
14007 handle: this.handles[ index ],
14008 value: newVal
14009 } );
14010 if ( allowed !== false ) {
14011 this.value( newVal );
14012 }
14013 }
14014 }
14015 },
14016
14017 _stop: function( event, index ) {
14018 var uiHash = {
14019 handle: this.handles[ index ],
14020 value: this.value()
14021 };
14022 if ( this.options.values && this.options.values.length ) {
14023 uiHash.value = this.values( index );
14024 uiHash.values = this.values();
14025 }
14026
14027 this._trigger( "stop", event, uiHash );
14028 },
14029
14030 _change: function( event, index ) {
14031 if ( !this._keySliding && !this._mouseSliding ) {
14032 var uiHash = {
14033 handle: this.handles[ index ],
14034 value: this.value()
14035 };
14036 if ( this.options.values && this.options.values.length ) {
14037 uiHash.value = this.values( index );
14038 uiHash.values = this.values();
14039 }
14040
14041 //store the last changed value index for reference when handles overlap
14042 this._lastChangedValue = index;
14043
14044 this._trigger( "change", event, uiHash );
14045 }
14046 },
14047
14048 value: function( newValue ) {
14049 if ( arguments.length ) {
14050 this.options.value = this._trimAlignValue( newValue );
14051 this._refreshValue();
14052 this._change( null, 0 );
14053 return;
14054 }
14055
14056 return this._value();
14057 },
14058
14059 values: function( index, newValue ) {
14060 var vals,
14061 newValues,
14062 i;
14063
14064 if ( arguments.length > 1 ) {
14065 this.options.values[ index ] = this._trimAlignValue( newValue );
14066 this._refreshValue();
14067 this._change( null, index );
14068 return;
14069 }
14070
14071 if ( arguments.length ) {
14072 if ( $.isArray( arguments[ 0 ] ) ) {
14073 vals = this.options.values;
14074 newValues = arguments[ 0 ];
14075 for ( i = 0; i < vals.length; i += 1 ) {
14076 vals[ i ] = this._trimAlignValue( newValues[ i ] );
14077 this._change( null, i );
14078 }
14079 this._refreshValue();
14080 } else {
14081 if ( this.options.values && this.options.values.length ) {
14082 return this._values( index );
14083 } else {
14084 return this.value();
14085 }
14086 }
14087 } else {
14088 return this._values();
14089 }
14090 },
14091
14092 _setOption: function( key, value ) {
14093 var i,
14094 valsLength = 0;
14095
14096 if ( key === "range" && this.options.range === true ) {
14097 if ( value === "min" ) {
14098 this.options.value = this._values( 0 );
14099 this.options.values = null;
14100 } else if ( value === "max" ) {
14101 this.options.value = this._values( this.options.values.length-1 );
14102 this.options.values = null;
14103 }
14104 }
14105
14106 if ( $.isArray( this.options.values ) ) {
14107 valsLength = this.options.values.length;
14108 }
14109
14110 $.Widget.prototype._setOption.apply( this, arguments );
14111
14112 switch ( key ) {
14113 case "orientation":
14114 this._detectOrientation();
14115 this.element
14116 .removeClass( "ui-slider-horizontal ui-slider-vertical" )
14117 .addClass( "ui-slider-" + this.orientation );
14118 this._refreshValue();
14119 break;
14120 case "value":
14121 this._animateOff = true;
14122 this._refreshValue();
14123 this._change( null, 0 );
14124 this._animateOff = false;
14125 break;
14126 case "values":
14127 this._animateOff = true;
14128 this._refreshValue();
14129 for ( i = 0; i < valsLength; i += 1 ) {
14130 this._change( null, i );
14131 }
14132 this._animateOff = false;
14133 break;
14134 case "min":
14135 case "max":
14136 this._animateOff = true;
14137 this._refreshValue();
14138 this._animateOff = false;
14139 break;
14140 case "range":
14141 this._animateOff = true;
14142 this._refresh();
14143 this._animateOff = false;
14144 break;
14145 }
14146 },
14147
14148 //internal value getter
14149 // _value() returns value trimmed by min and max, aligned by step
14150 _value: function() {
14151 var val = this.options.value;
14152 val = this._trimAlignValue( val );
14153
14154 return val;
14155 },
14156
14157 //internal values getter
14158 // _values() returns array of values trimmed by min and max, aligned by step
14159 // _values( index ) returns single value trimmed by min and max, aligned by step
14160 _values: function( index ) {
14161 var val,
14162 vals,
14163 i;
14164
14165 if ( arguments.length ) {
14166 val = this.options.values[ index ];
14167 val = this._trimAlignValue( val );
14168
14169 return val;
14170 } else if ( this.options.values && this.options.values.length ) {
14171 // .slice() creates a copy of the array
14172 // this copy gets trimmed by min and max and then returned
14173 vals = this.options.values.slice();
14174 for ( i = 0; i < vals.length; i+= 1) {
14175 vals[ i ] = this._trimAlignValue( vals[ i ] );
14176 }
14177
14178 return vals;
14179 } else {
14180 return [];
14181 }
14182 },
14183
14184 // returns the step-aligned value that val is closest to, between (inclusive) min and max
14185 _trimAlignValue: function( val ) {
14186 if ( val <= this._valueMin() ) {
14187 return this._valueMin();
14188 }
14189 if ( val >= this._valueMax() ) {
14190 return this._valueMax();
14191 }
14192 var step = ( this.options.step > 0 ) ? this.options.step : 1,
14193 valModStep = (val - this._valueMin()) % step,
14194 alignValue = val - valModStep;
14195
14196 if ( Math.abs(valModStep) * 2 >= step ) {
14197 alignValue += ( valModStep > 0 ) ? step : ( -step );
14198 }
14199
14200 // Since JavaScript has problems with large floats, round
14201 // the final value to 5 digits after the decimal point (see #4124)
14202 return parseFloat( alignValue.toFixed(5) );
14203 },
14204
14205 _valueMin: function() {
14206 return this.options.min;
14207 },
14208
14209 _valueMax: function() {
14210 return this.options.max;
14211 },
14212
14213 _refreshValue: function() {
14214 var lastValPercent, valPercent, value, valueMin, valueMax,
14215 oRange = this.options.range,
14216 o = this.options,
14217 that = this,
14218 animate = ( !this._animateOff ) ? o.animate : false,
14219 _set = {};
14220
14221 if ( this.options.values && this.options.values.length ) {
14222 this.handles.each(function( i ) {
14223 valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100;
14224 _set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
14225 $( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
14226 if ( that.options.range === true ) {
14227 if ( that.orientation === "horizontal" ) {
14228 if ( i === 0 ) {
14229 that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate );
14230 }
14231 if ( i === 1 ) {
14232 that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
14233 }
14234 } else {
14235 if ( i === 0 ) {
14236 that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate );
14237 }
14238 if ( i === 1 ) {
14239 that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
14240 }
14241 }
14242 }
14243 lastValPercent = valPercent;
14244 });
14245 } else {
14246 value = this.value();
14247 valueMin = this._valueMin();
14248 valueMax = this._valueMax();
14249 valPercent = ( valueMax !== valueMin ) ?
14250 ( value - valueMin ) / ( valueMax - valueMin ) * 100 :
14251 0;
14252 _set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
14253 this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
14254
14255 if ( oRange === "min" && this.orientation === "horizontal" ) {
14256 this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate );
14257 }
14258 if ( oRange === "max" && this.orientation === "horizontal" ) {
14259 this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
14260 }
14261 if ( oRange === "min" && this.orientation === "vertical" ) {
14262 this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate );
14263 }
14264 if ( oRange === "max" && this.orientation === "vertical" ) {
14265 this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
14266 }
14267 }
14268 },
14269
14270 _handleEvents: {
14271 keydown: function( event ) {
14272 /*jshint maxcomplexity:25*/
14273 var allowed, curVal, newVal, step,
14274 index = $( event.target ).data( "ui-slider-handle-index" );
14275
14276 switch ( event.keyCode ) {
14277 case $.ui.keyCode.HOME:
14278 case $.ui.keyCode.END:
14279 case $.ui.keyCode.PAGE_UP:
14280 case $.ui.keyCode.PAGE_DOWN:
14281 case $.ui.keyCode.UP:
14282 case $.ui.keyCode.RIGHT:
14283 case $.ui.keyCode.DOWN:
14284 case $.ui.keyCode.LEFT:
14285 event.preventDefault();
14286 if ( !this._keySliding ) {
14287 this._keySliding = true;
14288 $( event.target ).addClass( "ui-state-active" );
14289 allowed = this._start( event, index );
14290 if ( allowed === false ) {
14291 return;
14292 }
14293 }
14294 break;
14295 }
14296
14297 step = this.options.step;
14298 if ( this.options.values && this.options.values.length ) {
14299 curVal = newVal = this.values( index );
14300 } else {
14301 curVal = newVal = this.value();
14302 }
14303
14304 switch ( event.keyCode ) {
14305 case $.ui.keyCode.HOME:
14306 newVal = this._valueMin();
14307 break;
14308 case $.ui.keyCode.END:
14309 newVal = this._valueMax();
14310 break;
14311 case $.ui.keyCode.PAGE_UP:
14312 newVal = this._trimAlignValue( curVal + ( (this._valueMax() - this._valueMin()) / numPages ) );
14313 break;
14314 case $.ui.keyCode.PAGE_DOWN:
14315 newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / numPages ) );
14316 break;
14317 case $.ui.keyCode.UP:
14318 case $.ui.keyCode.RIGHT:
14319 if ( curVal === this._valueMax() ) {
14320 return;
14321 }
14322 newVal = this._trimAlignValue( curVal + step );
14323 break;
14324 case $.ui.keyCode.DOWN:
14325 case $.ui.keyCode.LEFT:
14326 if ( curVal === this._valueMin() ) {
14327 return;
14328 }
14329 newVal = this._trimAlignValue( curVal - step );
14330 break;
14331 }
14332
14333 this._slide( event, index, newVal );
14334 },
14335 click: function( event ) {
14336 event.preventDefault();
14337 },
14338 keyup: function( event ) {
14339 var index = $( event.target ).data( "ui-slider-handle-index" );
14340
14341 if ( this._keySliding ) {
14342 this._keySliding = false;
14343 this._stop( event, index );
14344 this._change( event, index );
14345 $( event.target ).removeClass( "ui-state-active" );
14346 }
14347 }
14348 }
14349
14350 });
14351
14352 }(jQuery));
14353 (function( $ ) {
14354
14355 function modifier( fn ) {
14356 return function() {
14357 var previous = this.element.val();
14358 fn.apply( this, arguments );
14359 this._refresh();
14360 if ( previous !== this.element.val() ) {
14361 this._trigger( "change" );
14362 }
14363 };
14364 }
14365
14366 $.widget( "ui.spinner", {
14367 version: "1.10.3",
14368 defaultElement: "<input>",
14369 widgetEventPrefix: "spin",
14370 options: {
14371 culture: null,
14372 icons: {
14373 down: "ui-icon-triangle-1-s",
14374 up: "ui-icon-triangle-1-n"
14375 },
14376 incremental: true,
14377 max: null,
14378 min: null,
14379 numberFormat: null,
14380 page: 10,
14381 step: 1,
14382
14383 change: null,
14384 spin: null,
14385 start: null,
14386 stop: null
14387 },
14388
14389 _create: function() {
14390 // handle string values that need to be parsed
14391 this._setOption( "max", this.options.max );
14392 this._setOption( "min", this.options.min );
14393 this._setOption( "step", this.options.step );
14394
14395 // format the value, but don't constrain
14396 this._value( this.element.val(), true );
14397
14398 this._draw();
14399 this._on( this._events );
14400 this._refresh();
14401
14402 // turning off autocomplete prevents the browser from remembering the
14403 // value when navigating through history, so we re-enable autocomplete
14404 // if the page is unloaded before the widget is destroyed. #7790
14405 this._on( this.window, {
14406 beforeunload: function() {
14407 this.element.removeAttr( "autocomplete" );
14408 }
14409 });
14410 },
14411
14412 _getCreateOptions: function() {
14413 var options = {},
14414 element = this.element;
14415
14416 $.each( [ "min", "max", "step" ], function( i, option ) {
14417 var value = element.attr( option );
14418 if ( value !== undefined && value.length ) {
14419 options[ option ] = value;
14420 }
14421 });
14422
14423 return options;
14424 },
14425
14426 _events: {
14427 keydown: function( event ) {
14428 if ( this._start( event ) && this._keydown( event ) ) {
14429 event.preventDefault();
14430 }
14431 },
14432 keyup: "_stop",
14433 focus: function() {
14434 this.previous = this.element.val();
14435 },
14436 blur: function( event ) {
14437 if ( this.cancelBlur ) {
14438 delete this.cancelBlur;
14439 return;
14440 }
14441
14442 this._stop();
14443 this._refresh();
14444 if ( this.previous !== this.element.val() ) {
14445 this._trigger( "change", event );
14446 }
14447 },
14448 mousewheel: function( event, delta ) {
14449 if ( !delta ) {
14450 return;
14451 }
14452 if ( !this.spinning && !this._start( event ) ) {
14453 return false;
14454 }
14455
14456 this._spin( (delta > 0 ? 1 : -1) * this.options.step, event );
14457 clearTimeout( this.mousewheelTimer );
14458 this.mousewheelTimer = this._delay(function() {
14459 if ( this.spinning ) {
14460 this._stop( event );
14461 }
14462 }, 100 );
14463 event.preventDefault();
14464 },
14465 "mousedown .ui-spinner-button": function( event ) {
14466 var previous;
14467
14468 // We never want the buttons to have focus; whenever the user is
14469 // interacting with the spinner, the focus should be on the input.
14470 // If the input is focused then this.previous is properly set from
14471 // when the input first received focus. If the input is not focused
14472 // then we need to set this.previous based on the value before spinning.
14473 previous = this.element[0] === this.document[0].activeElement ?
14474 this.previous : this.element.val();
14475 function checkFocus() {
14476 var isActive = this.element[0] === this.document[0].activeElement;
14477 if ( !isActive ) {
14478 this.element.focus();
14479 this.previous = previous;
14480 // support: IE
14481 // IE sets focus asynchronously, so we need to check if focus
14482 // moved off of the input because the user clicked on the button.
14483 this._delay(function() {
14484 this.previous = previous;
14485 });
14486 }
14487 }
14488
14489 // ensure focus is on (or stays on) the text field
14490 event.preventDefault();
14491 checkFocus.call( this );
14492
14493 // support: IE
14494 // IE doesn't prevent moving focus even with event.preventDefault()
14495 // so we set a flag to know when we should ignore the blur event
14496 // and check (again) if focus moved off of the input.
14497 this.cancelBlur = true;
14498 this._delay(function() {
14499 delete this.cancelBlur;
14500 checkFocus.call( this );
14501 });
14502
14503 if ( this._start( event ) === false ) {
14504 return;
14505 }
14506
14507 this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
14508 },
14509 "mouseup .ui-spinner-button": "_stop",
14510 "mouseenter .ui-spinner-button": function( event ) {
14511 // button will add ui-state-active if mouse was down while mouseleave and kept down
14512 if ( !$( event.currentTarget ).hasClass( "ui-state-active" ) ) {
14513 return;
14514 }
14515
14516 if ( this._start( event ) === false ) {
14517 return false;
14518 }
14519 this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
14520 },
14521 // TODO: do we really want to consider this a stop?
14522 // shouldn't we just stop the repeater and wait until mouseup before
14523 // we trigger the stop event?
14524 "mouseleave .ui-spinner-button": "_stop"
14525 },
14526
14527 _draw: function() {
14528 var uiSpinner = this.uiSpinner = this.element
14529 .addClass( "ui-spinner-input" )
14530 .attr( "autocomplete", "off" )
14531 .wrap( this._uiSpinnerHtml() )
14532 .parent()
14533 // add buttons
14534 .append( this._buttonHtml() );
14535
14536 this.element.attr( "role", "spinbutton" );
14537
14538 // button bindings
14539 this.buttons = uiSpinner.find( ".ui-spinner-button" )
14540 .attr( "tabIndex", -1 )
14541 .button()
14542 .removeClass( "ui-corner-all" );
14543
14544 // IE 6 doesn't understand height: 50% for the buttons
14545 // unless the wrapper has an explicit height
14546 if ( this.buttons.height() > Math.ceil( uiSpinner.height() * 0.5 ) &&
14547 uiSpinner.height() > 0 ) {
14548 uiSpinner.height( uiSpinner.height() );
14549 }
14550
14551 // disable spinner if element was already disabled
14552 if ( this.options.disabled ) {
14553 this.disable();
14554 }
14555 },
14556
14557 _keydown: function( event ) {
14558 var options = this.options,
14559 keyCode = $.ui.keyCode;
14560
14561 switch ( event.keyCode ) {
14562 case keyCode.UP:
14563 this._repeat( null, 1, event );
14564 return true;
14565 case keyCode.DOWN:
14566 this._repeat( null, -1, event );
14567 return true;
14568 case keyCode.PAGE_UP:
14569 this._repeat( null, options.page, event );
14570 return true;
14571 case keyCode.PAGE_DOWN:
14572 this._repeat( null, -options.page, event );
14573 return true;
14574 }
14575
14576 return false;
14577 },
14578
14579 _uiSpinnerHtml: function() {
14580 return "<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>";
14581 },
14582
14583 _buttonHtml: function() {
14584 return "" +
14585 "<a class='ui-spinner-button ui-spinner-up ui-corner-tr'>" +
14586 "<span class='ui-icon " + this.options.icons.up + "'>&#9650;</span>" +
14587 "</a>" +
14588 "<a class='ui-spinner-button ui-spinner-down ui-corner-br'>" +
14589 "<span class='ui-icon " + this.options.icons.down + "'>&#9660;</span>" +
14590 "</a>";
14591 },
14592
14593 _start: function( event ) {
14594 if ( !this.spinning && this._trigger( "start", event ) === false ) {
14595 return false;
14596 }
14597
14598 if ( !this.counter ) {
14599 this.counter = 1;
14600 }
14601 this.spinning = true;
14602 return true;
14603 },
14604
14605 _repeat: function( i, steps, event ) {
14606 i = i || 500;
14607
14608 clearTimeout( this.timer );
14609 this.timer = this._delay(function() {
14610 this._repeat( 40, steps, event );
14611 }, i );
14612
14613 this._spin( steps * this.options.step, event );
14614 },
14615
14616 _spin: function( step, event ) {
14617 var value = this.value() || 0;
14618
14619 if ( !this.counter ) {
14620 this.counter = 1;
14621 }
14622
14623 value = this._adjustValue( value + step * this._increment( this.counter ) );
14624
14625 if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false) {
14626 this._value( value );
14627 this.counter++;
14628 }
14629 },
14630
14631 _increment: function( i ) {
14632 var incremental = this.options.incremental;
14633
14634 if ( incremental ) {
14635 return $.isFunction( incremental ) ?
14636 incremental( i ) :
14637 Math.floor( i*i*i/50000 - i*i/500 + 17*i/200 + 1 );
14638 }
14639
14640 return 1;
14641 },
14642
14643 _precision: function() {
14644 var precision = this._precisionOf( this.options.step );
14645 if ( this.options.min !== null ) {
14646 precision = Math.max( precision, this._precisionOf( this.options.min ) );
14647 }
14648 return precision;
14649 },
14650
14651 _precisionOf: function( num ) {
14652 var str = num.toString(),
14653 decimal = str.indexOf( "." );
14654 return decimal === -1 ? 0 : str.length - decimal - 1;
14655 },
14656
14657 _adjustValue: function( value ) {
14658 var base, aboveMin,
14659 options = this.options;
14660
14661 // make sure we're at a valid step
14662 // - find out where we are relative to the base (min or 0)
14663 base = options.min !== null ? options.min : 0;
14664 aboveMin = value - base;
14665 // - round to the nearest step
14666 aboveMin = Math.round(aboveMin / options.step) * options.step;
14667 // - rounding is based on 0, so adjust back to our base
14668 value = base + aboveMin;
14669
14670 // fix precision from bad JS floating point math
14671 value = parseFloat( value.toFixed( this._precision() ) );
14672
14673 // clamp the value
14674 if ( options.max !== null && value > options.max) {
14675 return options.max;
14676 }
14677 if ( options.min !== null && value < options.min ) {
14678 return options.min;
14679 }
14680
14681 return value;
14682 },
14683
14684 _stop: function( event ) {
14685 if ( !this.spinning ) {
14686 return;
14687 }
14688
14689 clearTimeout( this.timer );
14690 clearTimeout( this.mousewheelTimer );
14691 this.counter = 0;
14692 this.spinning = false;
14693 this._trigger( "stop", event );
14694 },
14695
14696 _setOption: function( key, value ) {
14697 if ( key === "culture" || key === "numberFormat" ) {
14698 var prevValue = this._parse( this.element.val() );
14699 this.options[ key ] = value;
14700 this.element.val( this._format( prevValue ) );
14701 return;
14702 }
14703
14704 if ( key === "max" || key === "min" || key === "step" ) {
14705 if ( typeof value === "string" ) {
14706 value = this._parse( value );
14707 }
14708 }
14709 if ( key === "icons" ) {
14710 this.buttons.first().find( ".ui-icon" )
14711 .removeClass( this.options.icons.up )
14712 .addClass( value.up );
14713 this.buttons.last().find( ".ui-icon" )
14714 .removeClass( this.options.icons.down )
14715 .addClass( value.down );
14716 }
14717
14718 this._super( key, value );
14719
14720 if ( key === "disabled" ) {
14721 if ( value ) {
14722 this.element.prop( "disabled", true );
14723 this.buttons.button( "disable" );
14724 } else {
14725 this.element.prop( "disabled", false );
14726 this.buttons.button( "enable" );
14727 }
14728 }
14729 },
14730
14731 _setOptions: modifier(function( options ) {
14732 this._super( options );
14733 this._value( this.element.val() );
14734 }),
14735
14736 _parse: function( val ) {
14737 if ( typeof val === "string" && val !== "" ) {
14738 val = window.Globalize && this.options.numberFormat ?
14739 Globalize.parseFloat( val, 10, this.options.culture ) : +val;
14740 }
14741 return val === "" || isNaN( val ) ? null : val;
14742 },
14743
14744 _format: function( value ) {
14745 if ( value === "" ) {
14746 return "";
14747 }
14748 return window.Globalize && this.options.numberFormat ?
14749 Globalize.format( value, this.options.numberFormat, this.options.culture ) :
14750 value;
14751 },
14752
14753 _refresh: function() {
14754 this.element.attr({
14755 "aria-valuemin": this.options.min,
14756 "aria-valuemax": this.options.max,
14757 // TODO: what should we do with values that can't be parsed?
14758 "aria-valuenow": this._parse( this.element.val() )
14759 });
14760 },
14761
14762 // update the value without triggering change
14763 _value: function( value, allowAny ) {
14764 var parsed;
14765 if ( value !== "" ) {
14766 parsed = this._parse( value );
14767 if ( parsed !== null ) {
14768 if ( !allowAny ) {
14769 parsed = this._adjustValue( parsed );
14770 }
14771 value = this._format( parsed );
14772 }
14773 }
14774 this.element.val( value );
14775 this._refresh();
14776 },
14777
14778 _destroy: function() {
14779 this.element
14780 .removeClass( "ui-spinner-input" )
14781 .prop( "disabled", false )
14782 .removeAttr( "autocomplete" )
14783 .removeAttr( "role" )
14784 .removeAttr( "aria-valuemin" )
14785 .removeAttr( "aria-valuemax" )
14786 .removeAttr( "aria-valuenow" );
14787 this.uiSpinner.replaceWith( this.element );
14788 },
14789
14790 stepUp: modifier(function( steps ) {
14791 this._stepUp( steps );
14792 }),
14793 _stepUp: function( steps ) {
14794 if ( this._start() ) {
14795 this._spin( (steps || 1) * this.options.step );
14796 this._stop();
14797 }
14798 },
14799
14800 stepDown: modifier(function( steps ) {
14801 this._stepDown( steps );
14802 }),
14803 _stepDown: function( steps ) {
14804 if ( this._start() ) {
14805 this._spin( (steps || 1) * -this.options.step );
14806 this._stop();
14807 }
14808 },
14809
14810 pageUp: modifier(function( pages ) {
14811 this._stepUp( (pages || 1) * this.options.page );
14812 }),
14813
14814 pageDown: modifier(function( pages ) {
14815 this._stepDown( (pages || 1) * this.options.page );
14816 }),
14817
14818 value: function( newVal ) {
14819 if ( !arguments.length ) {
14820 return this._parse( this.element.val() );
14821 }
14822 modifier( this._value ).call( this, newVal );
14823 },
14824
14825 widget: function() {
14826 return this.uiSpinner;
14827 }
14828 });
14829
14830 }( jQuery ) );
14831 (function( $, undefined ) {
14832
14833 var tabId = 0,
14834 rhash = /#.*$/;
14835
14836 function getNextTabId() {
14837 return ++tabId;
14838 }
14839
14840 function isLocal( anchor ) {
14841 return anchor.hash.length > 1 &&
14842 decodeURIComponent( anchor.href.replace( rhash, "" ) ) ===
14843 decodeURIComponent( location.href.replace( rhash, "" ) );
14844 }
14845
14846 $.widget( "ui.tabs", {
14847 version: "1.10.3",
14848 delay: 300,
14849 options: {
14850 active: null,
14851 collapsible: false,
14852 event: "click",
14853 heightStyle: "content",
14854 hide: null,
14855 show: null,
14856
14857 // callbacks
14858 activate: null,
14859 beforeActivate: null,
14860 beforeLoad: null,
14861 load: null
14862 },
14863
14864 _create: function() {
14865 var that = this,
14866 options = this.options;
14867
14868 this.running = false;
14869
14870 this.element
14871 .addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" )
14872 .toggleClass( "ui-tabs-collapsible", options.collapsible )
14873 // Prevent users from focusing disabled tabs via click
14874 .delegate( ".ui-tabs-nav > li", "mousedown" + this.eventNamespace, function( event ) {
14875 if ( $( this ).is( ".ui-state-disabled" ) ) {
14876 event.preventDefault();
14877 }
14878 })
14879 // support: IE <9
14880 // Preventing the default action in mousedown doesn't prevent IE
14881 // from focusing the element, so if the anchor gets focused, blur.
14882 // We don't have to worry about focusing the previously focused
14883 // element since clicking on a non-focusable element should focus
14884 // the body anyway.
14885 .delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() {
14886 if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) {
14887 this.blur();
14888 }
14889 });
14890
14891 this._processTabs();
14892 options.active = this._initialActive();
14893
14894 // Take disabling tabs via class attribute from HTML
14895 // into account and update option properly.
14896 if ( $.isArray( options.disabled ) ) {
14897 options.disabled = $.unique( options.disabled.concat(
14898 $.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) {
14899 return that.tabs.index( li );
14900 })
14901 ) ).sort();
14902 }
14903
14904 // check for length avoids error when initializing empty list
14905 if ( this.options.active !== false && this.anchors.length ) {
14906 this.active = this._findActive( options.active );
14907 } else {
14908 this.active = $();
14909 }
14910
14911 this._refresh();
14912
14913 if ( this.active.length ) {
14914 this.load( options.active );
14915 }
14916 },
14917
14918 _initialActive: function() {
14919 var active = this.options.active,
14920 collapsible = this.options.collapsible,
14921 locationHash = location.hash.substring( 1 );
14922
14923 if ( active === null ) {
14924 // check the fragment identifier in the URL
14925 if ( locationHash ) {
14926 this.tabs.each(function( i, tab ) {
14927 if ( $( tab ).attr( "aria-controls" ) === locationHash ) {
14928 active = i;
14929 return false;
14930 }
14931 });
14932 }
14933
14934 // check for a tab marked active via a class
14935 if ( active === null ) {
14936 active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) );
14937 }
14938
14939 // no active tab, set to false
14940 if ( active === null || active === -1 ) {
14941 active = this.tabs.length ? 0 : false;
14942 }
14943 }
14944
14945 // handle numbers: negative, out of range
14946 if ( active !== false ) {
14947 active = this.tabs.index( this.tabs.eq( active ) );
14948 if ( active === -1 ) {
14949 active = collapsible ? false : 0;
14950 }
14951 }
14952
14953 // don't allow collapsible: false and active: false
14954 if ( !collapsible && active === false && this.anchors.length ) {
14955 active = 0;
14956 }
14957
14958 return active;
14959 },
14960
14961 _getCreateEventData: function() {
14962 return {
14963 tab: this.active,
14964 panel: !this.active.length ? $() : this._getPanelForTab( this.active )
14965 };
14966 },
14967
14968 _tabKeydown: function( event ) {
14969 /*jshint maxcomplexity:15*/
14970 var focusedTab = $( this.document[0].activeElement ).closest( "li" ),
14971 selectedIndex = this.tabs.index( focusedTab ),
14972 goingForward = true;
14973
14974 if ( this._handlePageNav( event ) ) {
14975 return;
14976 }
14977
14978 switch ( event.keyCode ) {
14979 case $.ui.keyCode.RIGHT:
14980 case $.ui.keyCode.DOWN:
14981 selectedIndex++;
14982 break;
14983 case $.ui.keyCode.UP:
14984 case $.ui.keyCode.LEFT:
14985 goingForward = false;
14986 selectedIndex--;
14987 break;
14988 case $.ui.keyCode.END:
14989 selectedIndex = this.anchors.length - 1;
14990 break;
14991 case $.ui.keyCode.HOME:
14992 selectedIndex = 0;
14993 break;
14994 case $.ui.keyCode.SPACE:
14995 // Activate only, no collapsing
14996 event.preventDefault();
14997 clearTimeout( this.activating );
14998 this._activate( selectedIndex );
14999 return;
15000 case $.ui.keyCode.ENTER:
15001 // Toggle (cancel delayed activation, allow collapsing)
15002 event.preventDefault();
15003 clearTimeout( this.activating );
15004 // Determine if we should collapse or activate
15005 this._activate( selectedIndex === this.options.active ? false : selectedIndex );
15006 return;
15007 default:
15008 return;
15009 }
15010
15011 // Focus the appropriate tab, based on which key was pressed
15012 event.preventDefault();
15013 clearTimeout( this.activating );
15014 selectedIndex = this._focusNextTab( selectedIndex, goingForward );
15015
15016 // Navigating with control key will prevent automatic activation
15017 if ( !event.ctrlKey ) {
15018 // Update aria-selected immediately so that AT think the tab is already selected.
15019 // Otherwise AT may confuse the user by stating that they need to activate the tab,
15020 // but the tab will already be activated by the time the announcement finishes.
15021 focusedTab.attr( "aria-selected", "false" );
15022 this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" );
15023
15024 this.activating = this._delay(function() {
15025 this.option( "active", selectedIndex );
15026 }, this.delay );
15027 }
15028 },
15029
15030 _panelKeydown: function( event ) {
15031 if ( this._handlePageNav( event ) ) {
15032 return;
15033 }
15034
15035 // Ctrl+up moves focus to the current tab
15036 if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) {
15037 event.preventDefault();
15038 this.active.focus();
15039 }
15040 },
15041
15042 // Alt+page up/down moves focus to the previous/next tab (and activates)
15043 _handlePageNav: function( event ) {
15044 if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) {
15045 this._activate( this._focusNextTab( this.options.active - 1, false ) );
15046 return true;
15047 }
15048 if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) {
15049 this._activate( this._focusNextTab( this.options.active + 1, true ) );
15050 return true;
15051 }
15052 },
15053
15054 _findNextTab: function( index, goingForward ) {
15055 var lastTabIndex = this.tabs.length - 1;
15056
15057 function constrain() {
15058 if ( index > lastTabIndex ) {
15059 index = 0;
15060 }
15061 if ( index < 0 ) {
15062 index = lastTabIndex;
15063 }
15064 return index;
15065 }
15066
15067 while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) {
15068 index = goingForward ? index + 1 : index - 1;
15069 }
15070
15071 return index;
15072 },
15073
15074 _focusNextTab: function( index, goingForward ) {
15075 index = this._findNextTab( index, goingForward );
15076 this.tabs.eq( index ).focus();
15077 return index;
15078 },
15079
15080 _setOption: function( key, value ) {
15081 if ( key === "active" ) {
15082 // _activate() will handle invalid values and update this.options
15083 this._activate( value );
15084 return;
15085 }
15086
15087 if ( key === "disabled" ) {
15088 // don't use the widget factory's disabled handling
15089 this._setupDisabled( value );
15090 return;
15091 }
15092
15093 this._super( key, value);
15094
15095 if ( key === "collapsible" ) {
15096 this.element.toggleClass( "ui-tabs-collapsible", value );
15097 // Setting collapsible: false while collapsed; open first panel
15098 if ( !value && this.options.active === false ) {
15099 this._activate( 0 );
15100 }
15101 }
15102
15103 if ( key === "event" ) {
15104 this._setupEvents( value );
15105 }
15106
15107 if ( key === "heightStyle" ) {
15108 this._setupHeightStyle( value );
15109 }
15110 },
15111
15112 _tabId: function( tab ) {
15113 return tab.attr( "aria-controls" ) || "ui-tabs-" + getNextTabId();
15114 },
15115
15116 _sanitizeSelector: function( hash ) {
15117 return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : "";
15118 },
15119
15120 refresh: function() {
15121 var options = this.options,
15122 lis = this.tablist.children( ":has(a[href])" );
15123
15124 // get disabled tabs from class attribute from HTML
15125 // this will get converted to a boolean if needed in _refresh()
15126 options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) {
15127 return lis.index( tab );
15128 });
15129
15130 this._processTabs();
15131
15132 // was collapsed or no tabs
15133 if ( options.active === false || !this.anchors.length ) {
15134 options.active = false;
15135 this.active = $();
15136 // was active, but active tab is gone
15137 } else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) {
15138 // all remaining tabs are disabled
15139 if ( this.tabs.length === options.disabled.length ) {
15140 options.active = false;
15141 this.active = $();
15142 // activate previous tab
15143 } else {
15144 this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) );
15145 }
15146 // was active, active tab still exists
15147 } else {
15148 // make sure active index is correct
15149 options.active = this.tabs.index( this.active );
15150 }
15151
15152 this._refresh();
15153 },
15154
15155 _refresh: function() {
15156 this._setupDisabled( this.options.disabled );
15157 this._setupEvents( this.options.event );
15158 this._setupHeightStyle( this.options.heightStyle );
15159
15160 this.tabs.not( this.active ).attr({
15161 "aria-selected": "false",
15162 tabIndex: -1
15163 });
15164 this.panels.not( this._getPanelForTab( this.active ) )
15165 .hide()
15166 .attr({
15167 "aria-expanded": "false",
15168 "aria-hidden": "true"
15169 });
15170
15171 // Make sure one tab is in the tab order
15172 if ( !this.active.length ) {
15173 this.tabs.eq( 0 ).attr( "tabIndex", 0 );
15174 } else {
15175 this.active
15176 .addClass( "ui-tabs-active ui-state-active" )
15177 .attr({
15178 "aria-selected": "true",
15179 tabIndex: 0
15180 });
15181 this._getPanelForTab( this.active )
15182 .show()
15183 .attr({
15184 "aria-expanded": "true",
15185 "aria-hidden": "false"
15186 });
15187 }
15188 },
15189
15190 _processTabs: function() {
15191 var that = this;
15192
15193 this.tablist = this._getList()
15194 .addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" )
15195 .attr( "role", "tablist" );
15196
15197 this.tabs = this.tablist.find( "> li:has(a[href])" )
15198 .addClass( "ui-state-default ui-corner-top" )
15199 .attr({
15200 role: "tab",
15201 tabIndex: -1
15202 });
15203
15204 this.anchors = this.tabs.map(function() {
15205 return $( "a", this )[ 0 ];
15206 })
15207 .addClass( "ui-tabs-anchor" )
15208 .attr({
15209 role: "presentation",
15210 tabIndex: -1
15211 });
15212
15213 this.panels = $();
15214
15215 this.anchors.each(function( i, anchor ) {
15216 var selector, panel, panelId,
15217 anchorId = $( anchor ).uniqueId().attr( "id" ),
15218 tab = $( anchor ).closest( "li" ),
15219 originalAriaControls = tab.attr( "aria-controls" );
15220
15221 // inline tab
15222 if ( isLocal( anchor ) ) {
15223 selector = anchor.hash;
15224 panel = that.element.find( that._sanitizeSelector( selector ) );
15225 // remote tab
15226 } else {
15227 panelId = that._tabId( tab );
15228 selector = "#" + panelId;
15229 panel = that.element.find( selector );
15230 if ( !panel.length ) {
15231 panel = that._createPanel( panelId );
15232 panel.insertAfter( that.panels[ i - 1 ] || that.tablist );
15233 }
15234 panel.attr( "aria-live", "polite" );
15235 }
15236
15237 if ( panel.length) {
15238 that.panels = that.panels.add( panel );
15239 }
15240 if ( originalAriaControls ) {
15241 tab.data( "ui-tabs-aria-controls", originalAriaControls );
15242 }
15243 tab.attr({
15244 "aria-controls": selector.substring( 1 ),
15245 "aria-labelledby": anchorId
15246 });
15247 panel.attr( "aria-labelledby", anchorId );
15248 });
15249
15250 this.panels
15251 .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
15252 .attr( "role", "tabpanel" );
15253 },
15254
15255 // allow overriding how to find the list for rare usage scenarios (#7715)
15256 _getList: function() {
15257 return this.element.find( "ol,ul" ).eq( 0 );
15258 },
15259
15260 _createPanel: function( id ) {
15261 return $( "<div>" )
15262 .attr( "id", id )
15263 .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
15264 .data( "ui-tabs-destroy", true );
15265 },
15266
15267 _setupDisabled: function( disabled ) {
15268 if ( $.isArray( disabled ) ) {
15269 if ( !disabled.length ) {
15270 disabled = false;
15271 } else if ( disabled.length === this.anchors.length ) {
15272 disabled = true;
15273 }
15274 }
15275
15276 // disable tabs
15277 for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) {
15278 if ( disabled === true || $.inArray( i, disabled ) !== -1 ) {
15279 $( li )
15280 .addClass( "ui-state-disabled" )
15281 .attr( "aria-disabled", "true" );
15282 } else {
15283 $( li )
15284 .removeClass( "ui-state-disabled" )
15285 .removeAttr( "aria-disabled" );
15286 }
15287 }
15288
15289 this.options.disabled = disabled;
15290 },
15291
15292 _setupEvents: function( event ) {
15293 var events = {
15294 click: function( event ) {
15295 event.preventDefault();
15296 }
15297 };
15298 if ( event ) {
15299 $.each( event.split(" "), function( index, eventName ) {
15300 events[ eventName ] = "_eventHandler";
15301 });
15302 }
15303
15304 this._off( this.anchors.add( this.tabs ).add( this.panels ) );
15305 this._on( this.anchors, events );
15306 this._on( this.tabs, { keydown: "_tabKeydown" } );
15307 this._on( this.panels, { keydown: "_panelKeydown" } );
15308
15309 this._focusable( this.tabs );
15310 this._hoverable( this.tabs );
15311 },
15312
15313 _setupHeightStyle: function( heightStyle ) {
15314 var maxHeight,
15315 parent = this.element.parent();
15316
15317 if ( heightStyle === "fill" ) {
15318 maxHeight = parent.height();
15319 maxHeight -= this.element.outerHeight() - this.element.height();
15320
15321 this.element.siblings( ":visible" ).each(function() {
15322 var elem = $( this ),
15323 position = elem.css( "position" );
15324
15325 if ( position === "absolute" || position === "fixed" ) {
15326 return;
15327 }
15328 maxHeight -= elem.outerHeight( true );
15329 });
15330
15331 this.element.children().not( this.panels ).each(function() {
15332 maxHeight -= $( this ).outerHeight( true );
15333 });
15334
15335 this.panels.each(function() {
15336 $( this ).height( Math.max( 0, maxHeight -
15337 $( this ).innerHeight() + $( this ).height() ) );
15338 })
15339 .css( "overflow", "auto" );
15340 } else if ( heightStyle === "auto" ) {
15341 maxHeight = 0;
15342 this.panels.each(function() {
15343 maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() );
15344 }).height( maxHeight );
15345 }
15346 },
15347
15348 _eventHandler: function( event ) {
15349 var options = this.options,
15350 active = this.active,
15351 anchor = $( event.currentTarget ),
15352 tab = anchor.closest( "li" ),
15353 clickedIsActive = tab[ 0 ] === active[ 0 ],
15354 collapsing = clickedIsActive && options.collapsible,
15355 toShow = collapsing ? $() : this._getPanelForTab( tab ),
15356 toHide = !active.length ? $() : this._getPanelForTab( active ),
15357 eventData = {
15358 oldTab: active,
15359 oldPanel: toHide,
15360 newTab: collapsing ? $() : tab,
15361 newPanel: toShow
15362 };
15363
15364 event.preventDefault();
15365
15366 if ( tab.hasClass( "ui-state-disabled" ) ||
15367 // tab is already loading
15368 tab.hasClass( "ui-tabs-loading" ) ||
15369 // can't switch durning an animation
15370 this.running ||
15371 // click on active header, but not collapsible
15372 ( clickedIsActive && !options.collapsible ) ||
15373 // allow canceling activation
15374 ( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
15375 return;
15376 }
15377
15378 options.active = collapsing ? false : this.tabs.index( tab );
15379
15380 this.active = clickedIsActive ? $() : tab;
15381 if ( this.xhr ) {
15382 this.xhr.abort();
15383 }
15384
15385 if ( !toHide.length && !toShow.length ) {
15386 $.error( "jQuery UI Tabs: Mismatching fragment identifier." );
15387 }
15388
15389 if ( toShow.length ) {
15390 this.load( this.tabs.index( tab ), event );
15391 }
15392 this._toggle( event, eventData );
15393 },
15394
15395 // handles show/hide for selecting tabs
15396 _toggle: function( event, eventData ) {
15397 var that = this,
15398 toShow = eventData.newPanel,
15399 toHide = eventData.oldPanel;
15400
15401 this.running = true;
15402
15403 function complete() {
15404 that.running = false;
15405 that._trigger( "activate", event, eventData );
15406 }
15407
15408 function show() {
15409 eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" );
15410
15411 if ( toShow.length && that.options.show ) {
15412 that._show( toShow, that.options.show, complete );
15413 } else {
15414 toShow.show();
15415 complete();
15416 }
15417 }
15418
15419 // start out by hiding, then showing, then completing
15420 if ( toHide.length && this.options.hide ) {
15421 this._hide( toHide, this.options.hide, function() {
15422 eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
15423 show();
15424 });
15425 } else {
15426 eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
15427 toHide.hide();
15428 show();
15429 }
15430
15431 toHide.attr({
15432 "aria-expanded": "false",
15433 "aria-hidden": "true"
15434 });
15435 eventData.oldTab.attr( "aria-selected", "false" );
15436 // If we're switching tabs, remove the old tab from the tab order.
15437 // If we're opening from collapsed state, remove the previous tab from the tab order.
15438 // If we're collapsing, then keep the collapsing tab in the tab order.
15439 if ( toShow.length && toHide.length ) {
15440 eventData.oldTab.attr( "tabIndex", -1 );
15441 } else if ( toShow.length ) {
15442 this.tabs.filter(function() {
15443 return $( this ).attr( "tabIndex" ) === 0;
15444 })
15445 .attr( "tabIndex", -1 );
15446 }
15447
15448 toShow.attr({
15449 "aria-expanded": "true",
15450 "aria-hidden": "false"
15451 });
15452 eventData.newTab.attr({
15453 "aria-selected": "true",
15454 tabIndex: 0
15455 });
15456 },
15457
15458 _activate: function( index ) {
15459 var anchor,
15460 active = this._findActive( index );
15461
15462 // trying to activate the already active panel
15463 if ( active[ 0 ] === this.active[ 0 ] ) {
15464 return;
15465 }
15466
15467 // trying to collapse, simulate a click on the current active header
15468 if ( !active.length ) {
15469 active = this.active;
15470 }
15471
15472 anchor = active.find( ".ui-tabs-anchor" )[ 0 ];
15473 this._eventHandler({
15474 target: anchor,
15475 currentTarget: anchor,
15476 preventDefault: $.noop
15477 });
15478 },
15479
15480 _findActive: function( index ) {
15481 return index === false ? $() : this.tabs.eq( index );
15482 },
15483
15484 _getIndex: function( index ) {
15485 // meta-function to give users option to provide a href string instead of a numerical index.
15486 if ( typeof index === "string" ) {
15487 index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) );
15488 }
15489
15490 return index;
15491 },
15492
15493 _destroy: function() {
15494 if ( this.xhr ) {
15495 this.xhr.abort();
15496 }
15497
15498 this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" );
15499
15500 this.tablist
15501 .removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" )
15502 .removeAttr( "role" );
15503
15504 this.anchors
15505 .removeClass( "ui-tabs-anchor" )
15506 .removeAttr( "role" )
15507 .removeAttr( "tabIndex" )
15508 .removeUniqueId();
15509
15510 this.tabs.add( this.panels ).each(function() {
15511 if ( $.data( this, "ui-tabs-destroy" ) ) {
15512 $( this ).remove();
15513 } else {
15514 $( this )
15515 .removeClass( "ui-state-default ui-state-active ui-state-disabled " +
15516 "ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" )
15517 .removeAttr( "tabIndex" )
15518 .removeAttr( "aria-live" )
15519 .removeAttr( "aria-busy" )
15520 .removeAttr( "aria-selected" )
15521 .removeAttr( "aria-labelledby" )
15522 .removeAttr( "aria-hidden" )
15523 .removeAttr( "aria-expanded" )
15524 .removeAttr( "role" );
15525 }
15526 });
15527
15528 this.tabs.each(function() {
15529 var li = $( this ),
15530 prev = li.data( "ui-tabs-aria-controls" );
15531 if ( prev ) {
15532 li
15533 .attr( "aria-controls", prev )
15534 .removeData( "ui-tabs-aria-controls" );
15535 } else {
15536 li.removeAttr( "aria-controls" );
15537 }
15538 });
15539
15540 this.panels.show();
15541
15542 if ( this.options.heightStyle !== "content" ) {
15543 this.panels.css( "height", "" );
15544 }
15545 },
15546
15547 enable: function( index ) {
15548 var disabled = this.options.disabled;
15549 if ( disabled === false ) {
15550 return;
15551 }
15552
15553 if ( index === undefined ) {
15554 disabled = false;
15555 } else {
15556 index = this._getIndex( index );
15557 if ( $.isArray( disabled ) ) {
15558 disabled = $.map( disabled, function( num ) {
15559 return num !== index ? num : null;
15560 });
15561 } else {
15562 disabled = $.map( this.tabs, function( li, num ) {
15563 return num !== index ? num : null;
15564 });
15565 }
15566 }
15567 this._setupDisabled( disabled );
15568 },
15569
15570 disable: function( index ) {
15571 var disabled = this.options.disabled;
15572 if ( disabled === true ) {
15573 return;
15574 }
15575
15576 if ( index === undefined ) {
15577 disabled = true;
15578 } else {
15579 index = this._getIndex( index );
15580 if ( $.inArray( index, disabled ) !== -1 ) {
15581 return;
15582 }
15583 if ( $.isArray( disabled ) ) {
15584 disabled = $.merge( [ index ], disabled ).sort();
15585 } else {
15586 disabled = [ index ];
15587 }
15588 }
15589 this._setupDisabled( disabled );
15590 },
15591
15592 load: function( index, event ) {
15593 index = this._getIndex( index );
15594 var that = this,
15595 tab = this.tabs.eq( index ),
15596 anchor = tab.find( ".ui-tabs-anchor" ),
15597 panel = this._getPanelForTab( tab ),
15598 eventData = {
15599 tab: tab,
15600 panel: panel
15601 };
15602
15603 // not remote
15604 if ( isLocal( anchor[ 0 ] ) ) {
15605 return;
15606 }
15607
15608 this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) );
15609
15610 // support: jQuery <1.8
15611 // jQuery <1.8 returns false if the request is canceled in beforeSend,
15612 // but as of 1.8, $.ajax() always returns a jqXHR object.
15613 if ( this.xhr && this.xhr.statusText !== "canceled" ) {
15614 tab.addClass( "ui-tabs-loading" );
15615 panel.attr( "aria-busy", "true" );
15616
15617 this.xhr
15618 .success(function( response ) {
15619 // support: jQuery <1.8
15620 // http://bugs.jquery.com/ticket/11778
15621 setTimeout(function() {
15622 panel.html( response );
15623 that._trigger( "load", event, eventData );
15624 }, 1 );
15625 })
15626 .complete(function( jqXHR, status ) {
15627 // support: jQuery <1.8
15628 // http://bugs.jquery.com/ticket/11778
15629 setTimeout(function() {
15630 if ( status === "abort" ) {
15631 that.panels.stop( false, true );
15632 }
15633
15634 tab.removeClass( "ui-tabs-loading" );
15635 panel.removeAttr( "aria-busy" );
15636
15637 if ( jqXHR === that.xhr ) {
15638 delete that.xhr;
15639 }
15640 }, 1 );
15641 });
15642 }
15643 },
15644
15645 _ajaxSettings: function( anchor, event, eventData ) {
15646 var that = this;
15647 return {
15648 url: anchor.attr( "href" ),
15649 beforeSend: function( jqXHR, settings ) {
15650 return that._trigger( "beforeLoad", event,
15651 $.extend( { jqXHR : jqXHR, ajaxSettings: settings }, eventData ) );
15652 }
15653 };
15654 },
15655
15656 _getPanelForTab: function( tab ) {
15657 var id = $( tab ).attr( "aria-controls" );
15658 return this.element.find( this._sanitizeSelector( "#" + id ) );
15659 }
15660 });
15661
15662 })( jQuery );
15663 (function( $ ) {
15664
15665 var increments = 0;
15666
15667 function addDescribedBy( elem, id ) {
15668 var describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ );
15669 describedby.push( id );
15670 elem
15671 .data( "ui-tooltip-id", id )
15672 .attr( "aria-describedby", $.trim( describedby.join( " " ) ) );
15673 }
15674
15675 function removeDescribedBy( elem ) {
15676 var id = elem.data( "ui-tooltip-id" ),
15677 describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ),
15678 index = $.inArray( id, describedby );
15679 if ( index !== -1 ) {
15680 describedby.splice( index, 1 );
15681 }
15682
15683 elem.removeData( "ui-tooltip-id" );
15684 describedby = $.trim( describedby.join( " " ) );
15685 if ( describedby ) {
15686 elem.attr( "aria-describedby", describedby );
15687 } else {
15688 elem.removeAttr( "aria-describedby" );
15689 }
15690 }
15691
15692 $.widget( "ui.tooltip", {
15693 version: "1.10.3",
15694 options: {
15695 content: function() {
15696 // support: IE<9, Opera in jQuery <1.7
15697 // .text() can't accept undefined, so coerce to a string
15698 var title = $( this ).attr( "title" ) || "";
15699 // Escape title, since we're going from an attribute to raw HTML
15700 return $( "<a>" ).text( title ).html();
15701 },
15702 hide: true,
15703 // Disabled elements have inconsistent behavior across browsers (#8661)
15704 items: "[title]:not([disabled])",
15705 position: {
15706 my: "left top+15",
15707 at: "left bottom",
15708 collision: "flipfit flip"
15709 },
15710 show: true,
15711 tooltipClass: null,
15712 track: false,
15713
15714 // callbacks
15715 close: null,
15716 open: null
15717 },
15718
15719 _create: function() {
15720 this._on({
15721 mouseover: "open",
15722 focusin: "open"
15723 });
15724
15725 // IDs of generated tooltips, needed for destroy
15726 this.tooltips = {};
15727 // IDs of parent tooltips where we removed the title attribute
15728 this.parents = {};
15729
15730 if ( this.options.disabled ) {
15731 this._disable();
15732 }
15733 },
15734
15735 _setOption: function( key, value ) {
15736 var that = this;
15737
15738 if ( key === "disabled" ) {
15739 this[ value ? "_disable" : "_enable" ]();
15740 this.options[ key ] = value;
15741 // disable element style changes
15742 return;
15743 }
15744
15745 this._super( key, value );
15746
15747 if ( key === "content" ) {
15748 $.each( this.tooltips, function( id, element ) {
15749 that._updateContent( element );
15750 });
15751 }
15752 },
15753
15754 _disable: function() {
15755 var that = this;
15756
15757 // close open tooltips
15758 $.each( this.tooltips, function( id, element ) {
15759 var event = $.Event( "blur" );
15760 event.target = event.currentTarget = element[0];
15761 that.close( event, true );
15762 });
15763
15764 // remove title attributes to prevent native tooltips
15765 this.element.find( this.options.items ).addBack().each(function() {
15766 var element = $( this );
15767 if ( element.is( "[title]" ) ) {
15768 element
15769 .data( "ui-tooltip-title", element.attr( "title" ) )
15770 .attr( "title", "" );
15771 }
15772 });
15773 },
15774
15775 _enable: function() {
15776 // restore title attributes
15777 this.element.find( this.options.items ).addBack().each(function() {
15778 var element = $( this );
15779 if ( element.data( "ui-tooltip-title" ) ) {
15780 element.attr( "title", element.data( "ui-tooltip-title" ) );
15781 }
15782 });
15783 },
15784
15785 open: function( event ) {
15786 var that = this,
15787 target = $( event ? event.target : this.element )
15788 // we need closest here due to mouseover bubbling,
15789 // but always pointing at the same event target
15790 .closest( this.options.items );
15791
15792 // No element to show a tooltip for or the tooltip is already open
15793 if ( !target.length || target.data( "ui-tooltip-id" ) ) {
15794 return;
15795 }
15796
15797 if ( target.attr( "title" ) ) {
15798 target.data( "ui-tooltip-title", target.attr( "title" ) );
15799 }
15800
15801 target.data( "ui-tooltip-open", true );
15802
15803 // kill parent tooltips, custom or native, for hover
15804 if ( event && event.type === "mouseover" ) {
15805 target.parents().each(function() {
15806 var parent = $( this ),
15807 blurEvent;
15808 if ( parent.data( "ui-tooltip-open" ) ) {
15809 blurEvent = $.Event( "blur" );
15810 blurEvent.target = blurEvent.currentTarget = this;
15811 that.close( blurEvent, true );
15812 }
15813 if ( parent.attr( "title" ) ) {
15814 parent.uniqueId();
15815 that.parents[ this.id ] = {
15816 element: this,
15817 title: parent.attr( "title" )
15818 };
15819 parent.attr( "title", "" );
15820 }
15821 });
15822 }
15823
15824 this._updateContent( target, event );
15825 },
15826
15827 _updateContent: function( target, event ) {
15828 var content,
15829 contentOption = this.options.content,
15830 that = this,
15831 eventType = event ? event.type : null;
15832
15833 if ( typeof contentOption === "string" ) {
15834 return this._open( event, target, contentOption );
15835 }
15836
15837 content = contentOption.call( target[0], function( response ) {
15838 // ignore async response if tooltip was closed already
15839 if ( !target.data( "ui-tooltip-open" ) ) {
15840 return;
15841 }
15842 // IE may instantly serve a cached response for ajax requests
15843 // delay this call to _open so the other call to _open runs first
15844 that._delay(function() {
15845 // jQuery creates a special event for focusin when it doesn't
15846 // exist natively. To improve performance, the native event
15847 // object is reused and the type is changed. Therefore, we can't
15848 // rely on the type being correct after the event finished
15849 // bubbling, so we set it back to the previous value. (#8740)
15850 if ( event ) {
15851 event.type = eventType;
15852 }
15853 this._open( event, target, response );
15854 });
15855 });
15856 if ( content ) {
15857 this._open( event, target, content );
15858 }
15859 },
15860
15861 _open: function( event, target, content ) {
15862 var tooltip, events, delayedShow,
15863 positionOption = $.extend( {}, this.options.position );
15864
15865 if ( !content ) {
15866 return;
15867 }
15868
15869 // Content can be updated multiple times. If the tooltip already
15870 // exists, then just update the content and bail.
15871 tooltip = this._find( target );
15872 if ( tooltip.length ) {
15873 tooltip.find( ".ui-tooltip-content" ).html( content );
15874 return;
15875 }
15876
15877 // if we have a title, clear it to prevent the native tooltip
15878 // we have to check first to avoid defining a title if none exists
15879 // (we don't want to cause an element to start matching [title])
15880 //
15881 // We use removeAttr only for key events, to allow IE to export the correct
15882 // accessible attributes. For mouse events, set to empty string to avoid
15883 // native tooltip showing up (happens only when removing inside mouseover).
15884 if ( target.is( "[title]" ) ) {
15885 if ( event && event.type === "mouseover" ) {
15886 target.attr( "title", "" );
15887 } else {
15888 target.removeAttr( "title" );
15889 }
15890 }
15891
15892 tooltip = this._tooltip( target );
15893 addDescribedBy( target, tooltip.attr( "id" ) );
15894 tooltip.find( ".ui-tooltip-content" ).html( content );
15895
15896 function position( event ) {
15897 positionOption.of = event;
15898 if ( tooltip.is( ":hidden" ) ) {
15899 return;
15900 }
15901 tooltip.position( positionOption );
15902 }
15903 if ( this.options.track && event && /^mouse/.test( event.type ) ) {
15904 this._on( this.document, {
15905 mousemove: position
15906 });
15907 // trigger once to override element-relative positioning
15908 position( event );
15909 } else {
15910 tooltip.position( $.extend({
15911 of: target
15912 }, this.options.position ) );
15913 }
15914
15915 tooltip.hide();
15916
15917 this._show( tooltip, this.options.show );
15918 // Handle tracking tooltips that are shown with a delay (#8644). As soon
15919 // as the tooltip is visible, position the tooltip using the most recent
15920 // event.
15921 if ( this.options.show && this.options.show.delay ) {
15922 delayedShow = this.delayedShow = setInterval(function() {
15923 if ( tooltip.is( ":visible" ) ) {
15924 position( positionOption.of );
15925 clearInterval( delayedShow );
15926 }
15927 }, $.fx.interval );
15928 }
15929
15930 this._trigger( "open", event, { tooltip: tooltip } );
15931
15932 events = {
15933 keyup: function( event ) {
15934 if ( event.keyCode === $.ui.keyCode.ESCAPE ) {
15935 var fakeEvent = $.Event(event);
15936 fakeEvent.currentTarget = target[0];
15937 this.close( fakeEvent, true );
15938 }
15939 },
15940 remove: function() {
15941 this._removeTooltip( tooltip );
15942 }
15943 };
15944 if ( !event || event.type === "mouseover" ) {
15945 events.mouseleave = "close";
15946 }
15947 if ( !event || event.type === "focusin" ) {
15948 events.focusout = "close";
15949 }
15950 this._on( true, target, events );
15951 },
15952
15953 close: function( event ) {
15954 var that = this,
15955 target = $( event ? event.currentTarget : this.element ),
15956 tooltip = this._find( target );
15957
15958 // disabling closes the tooltip, so we need to track when we're closing
15959 // to avoid an infinite loop in case the tooltip becomes disabled on close
15960 if ( this.closing ) {
15961 return;
15962 }
15963
15964 // Clear the interval for delayed tracking tooltips
15965 clearInterval( this.delayedShow );
15966
15967 // only set title if we had one before (see comment in _open())
15968 if ( target.data( "ui-tooltip-title" ) ) {
15969 target.attr( "title", target.data( "ui-tooltip-title" ) );
15970 }
15971
15972 removeDescribedBy( target );
15973
15974 tooltip.stop( true );
15975 this._hide( tooltip, this.options.hide, function() {
15976 that._removeTooltip( $( this ) );
15977 });
15978
15979 target.removeData( "ui-tooltip-open" );
15980 this._off( target, "mouseleave focusout keyup" );
15981 // Remove 'remove' binding only on delegated targets
15982 if ( target[0] !== this.element[0] ) {
15983 this._off( target, "remove" );
15984 }
15985 this._off( this.document, "mousemove" );
15986
15987 if ( event && event.type === "mouseleave" ) {
15988 $.each( this.parents, function( id, parent ) {
15989 $( parent.element ).attr( "title", parent.title );
15990 delete that.parents[ id ];
15991 });
15992 }
15993
15994 this.closing = true;
15995 this._trigger( "close", event, { tooltip: tooltip } );
15996 this.closing = false;
15997 },
15998
15999 _tooltip: function( element ) {
16000 var id = "ui-tooltip-" + increments++,
16001 tooltip = $( "<div>" )
16002 .attr({
16003 id: id,
16004 role: "tooltip"
16005 })
16006 .addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content " +
16007 ( this.options.tooltipClass || "" ) );
16008 $( "<div>" )
16009 .addClass( "ui-tooltip-content" )
16010 .appendTo( tooltip );
16011 tooltip.appendTo( this.document[0].body );
16012 this.tooltips[ id ] = element;
16013 return tooltip;
16014 },
16015
16016 _find: function( target ) {
16017 var id = target.data( "ui-tooltip-id" );
16018 return id ? $( "#" + id ) : $();
16019 },
16020
16021 _removeTooltip: function( tooltip ) {
16022 tooltip.remove();
16023 delete this.tooltips[ tooltip.attr( "id" ) ];
16024 },
16025
16026 _destroy: function() {
16027 var that = this;
16028
16029 // close open tooltips
16030 $.each( this.tooltips, function( id, element ) {
16031 // Delegate to close method to handle common cleanup
16032 var event = $.Event( "blur" );
16033 event.target = event.currentTarget = element[0];
16034 that.close( event, true );
16035
16036 // Remove immediately; destroying an open tooltip doesn't use the
16037 // hide animation
16038 $( "#" + id ).remove();
16039
16040 // Restore the title
16041 if ( element.data( "ui-tooltip-title" ) ) {
16042 element.attr( "title", element.data( "ui-tooltip-title" ) );
16043 element.removeData( "ui-tooltip-title" );
16044 }
16045 });
16046 }
16047 });
16048
16049 }( jQuery ) );
16050 (function($, undefined) {
16051
16052 var dataSpace = "ui-effects-";
16053
16054 $.effects = {
16055 effect: {}
16056 };
16057
16058 /*!
16059 * jQuery Color Animations v2.1.2
16060 * https://github.com/jquery/jquery-color
16061 *
16062 * Copyright 2013 jQuery Foundation and other contributors
16063 * Released under the MIT license.
16064 * http://jquery.org/license
16065 *
16066 * Date: Wed Jan 16 08:47:09 2013 -0600
16067 */
16068 (function( jQuery, undefined ) {
16069
16070 var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",
16071
16072 // plusequals test for += 100 -= 100
16073 rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,
16074 // a set of RE's that can match strings and generate color tuples.
16075 stringParsers = [{
16076 re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
16077 parse: function( execResult ) {
16078 return [
16079 execResult[ 1 ],
16080 execResult[ 2 ],
16081 execResult[ 3 ],
16082 execResult[ 4 ]
16083 ];
16084 }
16085 }, {
16086 re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
16087 parse: function( execResult ) {
16088 return [
16089 execResult[ 1 ] * 2.55,
16090 execResult[ 2 ] * 2.55,
16091 execResult[ 3 ] * 2.55,
16092 execResult[ 4 ]
16093 ];
16094 }
16095 }, {
16096 // this regex ignores A-F because it's compared against an already lowercased string
16097 re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,
16098 parse: function( execResult ) {
16099 return [
16100 parseInt( execResult[ 1 ], 16 ),
16101 parseInt( execResult[ 2 ], 16 ),
16102 parseInt( execResult[ 3 ], 16 )
16103 ];
16104 }
16105 }, {
16106 // this regex ignores A-F because it's compared against an already lowercased string
16107 re: /#([a-f0-9])([a-f0-9])([a-f0-9])/,
16108 parse: function( execResult ) {
16109 return [
16110 parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ),
16111 parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ),
16112 parseInt( execResult[ 3 ] + execResult[ 3 ], 16 )
16113 ];
16114 }
16115 }, {
16116 re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
16117 space: "hsla",
16118 parse: function( execResult ) {
16119 return [
16120 execResult[ 1 ],
16121 execResult[ 2 ] / 100,
16122 execResult[ 3 ] / 100,
16123 execResult[ 4 ]
16124 ];
16125 }
16126 }],
16127
16128 // jQuery.Color( )
16129 color = jQuery.Color = function( color, green, blue, alpha ) {
16130 return new jQuery.Color.fn.parse( color, green, blue, alpha );
16131 },
16132 spaces = {
16133 rgba: {
16134 props: {
16135 red: {
16136 idx: 0,
16137 type: "byte"
16138 },
16139 green: {
16140 idx: 1,
16141 type: "byte"
16142 },
16143 blue: {
16144 idx: 2,
16145 type: "byte"
16146 }
16147 }
16148 },
16149
16150 hsla: {
16151 props: {
16152 hue: {
16153 idx: 0,
16154 type: "degrees"
16155 },
16156 saturation: {
16157 idx: 1,
16158 type: "percent"
16159 },
16160 lightness: {
16161 idx: 2,
16162 type: "percent"
16163 }
16164 }
16165 }
16166 },
16167 propTypes = {
16168 "byte": {
16169 floor: true,
16170 max: 255
16171 },
16172 "percent": {
16173 max: 1
16174 },
16175 "degrees": {
16176 mod: 360,
16177 floor: true
16178 }
16179 },
16180 support = color.support = {},
16181
16182 // element for support tests
16183 supportElem = jQuery( "<p>" )[ 0 ],
16184
16185 // colors = jQuery.Color.names
16186 colors,
16187
16188 // local aliases of functions called often
16189 each = jQuery.each;
16190
16191 // determine rgba support immediately
16192 supportElem.style.cssText = "background-color:rgba(1,1,1,.5)";
16193 support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1;
16194
16195 // define cache name and alpha properties
16196 // for rgba and hsla spaces
16197 each( spaces, function( spaceName, space ) {
16198 space.cache = "_" + spaceName;
16199 space.props.alpha = {
16200 idx: 3,
16201 type: "percent",
16202 def: 1
16203 };
16204 });
16205
16206 function clamp( value, prop, allowEmpty ) {
16207 var type = propTypes[ prop.type ] || {};
16208
16209 if ( value == null ) {
16210 return (allowEmpty || !prop.def) ? null : prop.def;
16211 }
16212
16213 // ~~ is an short way of doing floor for positive numbers
16214 value = type.floor ? ~~value : parseFloat( value );
16215
16216 // IE will pass in empty strings as value for alpha,
16217 // which will hit this case
16218 if ( isNaN( value ) ) {
16219 return prop.def;
16220 }
16221
16222 if ( type.mod ) {
16223 // we add mod before modding to make sure that negatives values
16224 // get converted properly: -10 -> 350
16225 return (value + type.mod) % type.mod;
16226 }
16227
16228 // for now all property types without mod have min and max
16229 return 0 > value ? 0 : type.max < value ? type.max : value;
16230 }
16231
16232 function stringParse( string ) {
16233 var inst = color(),
16234 rgba = inst._rgba = [];
16235
16236 string = string.toLowerCase();
16237
16238 each( stringParsers, function( i, parser ) {
16239 var parsed,
16240 match = parser.re.exec( string ),
16241 values = match && parser.parse( match ),
16242 spaceName = parser.space || "rgba";
16243
16244 if ( values ) {
16245 parsed = inst[ spaceName ]( values );
16246
16247 // if this was an rgba parse the assignment might happen twice
16248 // oh well....
16249 inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ];
16250 rgba = inst._rgba = parsed._rgba;
16251
16252 // exit each( stringParsers ) here because we matched
16253 return false;
16254 }
16255 });
16256
16257 // Found a stringParser that handled it
16258 if ( rgba.length ) {
16259
16260 // if this came from a parsed string, force "transparent" when alpha is 0
16261 // chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
16262 if ( rgba.join() === "0,0,0,0" ) {
16263 jQuery.extend( rgba, colors.transparent );
16264 }
16265 return inst;
16266 }
16267
16268 // named colors
16269 return colors[ string ];
16270 }
16271
16272 color.fn = jQuery.extend( color.prototype, {
16273 parse: function( red, green, blue, alpha ) {
16274 if ( red === undefined ) {
16275 this._rgba = [ null, null, null, null ];
16276 return this;
16277 }
16278 if ( red.jquery || red.nodeType ) {
16279 red = jQuery( red ).css( green );
16280 green = undefined;
16281 }
16282
16283 var inst = this,
16284 type = jQuery.type( red ),
16285 rgba = this._rgba = [];
16286
16287 // more than 1 argument specified - assume ( red, green, blue, alpha )
16288 if ( green !== undefined ) {
16289 red = [ red, green, blue, alpha ];
16290 type = "array";
16291 }
16292
16293 if ( type === "string" ) {
16294 return this.parse( stringParse( red ) || colors._default );
16295 }
16296
16297 if ( type === "array" ) {
16298 each( spaces.rgba.props, function( key, prop ) {
16299 rgba[ prop.idx ] = clamp( red[ prop.idx ], prop );
16300 });
16301 return this;
16302 }
16303
16304 if ( type === "object" ) {
16305 if ( red instanceof color ) {
16306 each( spaces, function( spaceName, space ) {
16307 if ( red[ space.cache ] ) {
16308 inst[ space.cache ] = red[ space.cache ].slice();
16309 }
16310 });
16311 } else {
16312 each( spaces, function( spaceName, space ) {
16313 var cache = space.cache;
16314 each( space.props, function( key, prop ) {
16315
16316 // if the cache doesn't exist, and we know how to convert
16317 if ( !inst[ cache ] && space.to ) {
16318
16319 // if the value was null, we don't need to copy it
16320 // if the key was alpha, we don't need to copy it either
16321 if ( key === "alpha" || red[ key ] == null ) {
16322 return;
16323 }
16324 inst[ cache ] = space.to( inst._rgba );
16325 }
16326
16327 // this is the only case where we allow nulls for ALL properties.
16328 // call clamp with alwaysAllowEmpty
16329 inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true );
16330 });
16331
16332 // everything defined but alpha?
16333 if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) {
16334 // use the default of 1
16335 inst[ cache ][ 3 ] = 1;
16336 if ( space.from ) {
16337 inst._rgba = space.from( inst[ cache ] );
16338 }
16339 }
16340 });
16341 }
16342 return this;
16343 }
16344 },
16345 is: function( compare ) {
16346 var is = color( compare ),
16347 same = true,
16348 inst = this;
16349
16350 each( spaces, function( _, space ) {
16351 var localCache,
16352 isCache = is[ space.cache ];
16353 if (isCache) {
16354 localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || [];
16355 each( space.props, function( _, prop ) {
16356 if ( isCache[ prop.idx ] != null ) {
16357 same = ( isCache[ prop.idx ] === localCache[ prop.idx ] );
16358 return same;
16359 }
16360 });
16361 }
16362 return same;
16363 });
16364 return same;
16365 },
16366 _space: function() {
16367 var used = [],
16368 inst = this;
16369 each( spaces, function( spaceName, space ) {
16370 if ( inst[ space.cache ] ) {
16371 used.push( spaceName );
16372 }
16373 });
16374 return used.pop();
16375 },
16376 transition: function( other, distance ) {
16377 var end = color( other ),
16378 spaceName = end._space(),
16379 space = spaces[ spaceName ],
16380 startColor = this.alpha() === 0 ? color( "transparent" ) : this,
16381 start = startColor[ space.cache ] || space.to( startColor._rgba ),
16382 result = start.slice();
16383
16384 end = end[ space.cache ];
16385 each( space.props, function( key, prop ) {
16386 var index = prop.idx,
16387 startValue = start[ index ],
16388 endValue = end[ index ],
16389 type = propTypes[ prop.type ] || {};
16390
16391 // if null, don't override start value
16392 if ( endValue === null ) {
16393 return;
16394 }
16395 // if null - use end
16396 if ( startValue === null ) {
16397 result[ index ] = endValue;
16398 } else {
16399 if ( type.mod ) {
16400 if ( endValue - startValue > type.mod / 2 ) {
16401 startValue += type.mod;
16402 } else if ( startValue - endValue > type.mod / 2 ) {
16403 startValue -= type.mod;
16404 }
16405 }
16406 result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop );
16407 }
16408 });
16409 return this[ spaceName ]( result );
16410 },
16411 blend: function( opaque ) {
16412 // if we are already opaque - return ourself
16413 if ( this._rgba[ 3 ] === 1 ) {
16414 return this;
16415 }
16416
16417 var rgb = this._rgba.slice(),
16418 a = rgb.pop(),
16419 blend = color( opaque )._rgba;
16420
16421 return color( jQuery.map( rgb, function( v, i ) {
16422 return ( 1 - a ) * blend[ i ] + a * v;
16423 }));
16424 },
16425 toRgbaString: function() {
16426 var prefix = "rgba(",
16427 rgba = jQuery.map( this._rgba, function( v, i ) {
16428 return v == null ? ( i > 2 ? 1 : 0 ) : v;
16429 });
16430
16431 if ( rgba[ 3 ] === 1 ) {
16432 rgba.pop();
16433 prefix = "rgb(";
16434 }
16435
16436 return prefix + rgba.join() + ")";
16437 },
16438 toHslaString: function() {
16439 var prefix = "hsla(",
16440 hsla = jQuery.map( this.hsla(), function( v, i ) {
16441 if ( v == null ) {
16442 v = i > 2 ? 1 : 0;
16443 }
16444
16445 // catch 1 and 2
16446 if ( i && i < 3 ) {
16447 v = Math.round( v * 100 ) + "%";
16448 }
16449 return v;
16450 });
16451
16452 if ( hsla[ 3 ] === 1 ) {
16453 hsla.pop();
16454 prefix = "hsl(";
16455 }
16456 return prefix + hsla.join() + ")";
16457 },
16458 toHexString: function( includeAlpha ) {
16459 var rgba = this._rgba.slice(),
16460 alpha = rgba.pop();
16461
16462 if ( includeAlpha ) {
16463 rgba.push( ~~( alpha * 255 ) );
16464 }
16465
16466 return "#" + jQuery.map( rgba, function( v ) {
16467
16468 // default to 0 when nulls exist
16469 v = ( v || 0 ).toString( 16 );
16470 return v.length === 1 ? "0" + v : v;
16471 }).join("");
16472 },
16473 toString: function() {
16474 return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString();
16475 }
16476 });
16477 color.fn.parse.prototype = color.fn;
16478
16479 // hsla conversions adapted from:
16480 // https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021
16481
16482 function hue2rgb( p, q, h ) {
16483 h = ( h + 1 ) % 1;
16484 if ( h * 6 < 1 ) {
16485 return p + (q - p) * h * 6;
16486 }
16487 if ( h * 2 < 1) {
16488 return q;
16489 }
16490 if ( h * 3 < 2 ) {
16491 return p + (q - p) * ((2/3) - h) * 6;
16492 }
16493 return p;
16494 }
16495
16496 spaces.hsla.to = function ( rgba ) {
16497 if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) {
16498 return [ null, null, null, rgba[ 3 ] ];
16499 }
16500 var r = rgba[ 0 ] / 255,
16501 g = rgba[ 1 ] / 255,
16502 b = rgba[ 2 ] / 255,
16503 a = rgba[ 3 ],
16504 max = Math.max( r, g, b ),
16505 min = Math.min( r, g, b ),
16506 diff = max - min,
16507 add = max + min,
16508 l = add * 0.5,
16509 h, s;
16510
16511 if ( min === max ) {
16512 h = 0;
16513 } else if ( r === max ) {
16514 h = ( 60 * ( g - b ) / diff ) + 360;
16515 } else if ( g === max ) {
16516 h = ( 60 * ( b - r ) / diff ) + 120;
16517 } else {
16518 h = ( 60 * ( r - g ) / diff ) + 240;
16519 }
16520
16521 // chroma (diff) == 0 means greyscale which, by definition, saturation = 0%
16522 // otherwise, saturation is based on the ratio of chroma (diff) to lightness (add)
16523 if ( diff === 0 ) {
16524 s = 0;
16525 } else if ( l <= 0.5 ) {
16526 s = diff / add;
16527 } else {
16528 s = diff / ( 2 - add );
16529 }
16530 return [ Math.round(h) % 360, s, l, a == null ? 1 : a ];
16531 };
16532
16533 spaces.hsla.from = function ( hsla ) {
16534 if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) {
16535 return [ null, null, null, hsla[ 3 ] ];
16536 }
16537 var h = hsla[ 0 ] / 360,
16538 s = hsla[ 1 ],
16539 l = hsla[ 2 ],
16540 a = hsla[ 3 ],
16541 q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s,
16542 p = 2 * l - q;
16543
16544 return [
16545 Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ),
16546 Math.round( hue2rgb( p, q, h ) * 255 ),
16547 Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ),
16548 a
16549 ];
16550 };
16551
16552
16553 each( spaces, function( spaceName, space ) {
16554 var props = space.props,
16555 cache = space.cache,
16556 to = space.to,
16557 from = space.from;
16558
16559 // makes rgba() and hsla()
16560 color.fn[ spaceName ] = function( value ) {
16561
16562 // generate a cache for this space if it doesn't exist
16563 if ( to && !this[ cache ] ) {
16564 this[ cache ] = to( this._rgba );
16565 }
16566 if ( value === undefined ) {
16567 return this[ cache ].slice();
16568 }
16569
16570 var ret,
16571 type = jQuery.type( value ),
16572 arr = ( type === "array" || type === "object" ) ? value : arguments,
16573 local = this[ cache ].slice();
16574
16575 each( props, function( key, prop ) {
16576 var val = arr[ type === "object" ? key : prop.idx ];
16577 if ( val == null ) {
16578 val = local[ prop.idx ];
16579 }
16580 local[ prop.idx ] = clamp( val, prop );
16581 });
16582
16583 if ( from ) {
16584 ret = color( from( local ) );
16585 ret[ cache ] = local;
16586 return ret;
16587 } else {
16588 return color( local );
16589 }
16590 };
16591
16592 // makes red() green() blue() alpha() hue() saturation() lightness()
16593 each( props, function( key, prop ) {
16594 // alpha is included in more than one space
16595 if ( color.fn[ key ] ) {
16596 return;
16597 }
16598 color.fn[ key ] = function( value ) {
16599 var vtype = jQuery.type( value ),
16600 fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ),
16601 local = this[ fn ](),
16602 cur = local[ prop.idx ],
16603 match;
16604
16605 if ( vtype === "undefined" ) {
16606 return cur;
16607 }
16608
16609 if ( vtype === "function" ) {
16610 value = value.call( this, cur );
16611 vtype = jQuery.type( value );
16612 }
16613 if ( value == null && prop.empty ) {
16614 return this;
16615 }
16616 if ( vtype === "string" ) {
16617 match = rplusequals.exec( value );
16618 if ( match ) {
16619 value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 );
16620 }
16621 }
16622 local[ prop.idx ] = value;
16623 return this[ fn ]( local );
16624 };
16625 });
16626 });
16627
16628 // add cssHook and .fx.step function for each named hook.
16629 // accept a space separated string of properties
16630 color.hook = function( hook ) {
16631 var hooks = hook.split( " " );
16632 each( hooks, function( i, hook ) {
16633 jQuery.cssHooks[ hook ] = {
16634 set: function( elem, value ) {
16635 var parsed, curElem,
16636 backgroundColor = "";
16637
16638 if ( value !== "transparent" && ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) ) {
16639 value = color( parsed || value );
16640 if ( !support.rgba && value._rgba[ 3 ] !== 1 ) {
16641 curElem = hook === "backgroundColor" ? elem.parentNode : elem;
16642 while (
16643 (backgroundColor === "" || backgroundColor === "transparent") &&
16644 curElem && curElem.style
16645 ) {
16646 try {
16647 backgroundColor = jQuery.css( curElem, "backgroundColor" );
16648 curElem = curElem.parentNode;
16649 } catch ( e ) {
16650 }
16651 }
16652
16653 value = value.blend( backgroundColor && backgroundColor !== "transparent" ?
16654 backgroundColor :
16655 "_default" );
16656 }
16657
16658 value = value.toRgbaString();
16659 }
16660 try {
16661 elem.style[ hook ] = value;
16662 } catch( e ) {
16663 // wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit'
16664 }
16665 }
16666 };
16667 jQuery.fx.step[ hook ] = function( fx ) {
16668 if ( !fx.colorInit ) {
16669 fx.start = color( fx.elem, hook );
16670 fx.end = color( fx.end );
16671 fx.colorInit = true;
16672 }
16673 jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) );
16674 };
16675 });
16676
16677 };
16678
16679 color.hook( stepHooks );
16680
16681 jQuery.cssHooks.borderColor = {
16682 expand: function( value ) {
16683 var expanded = {};
16684
16685 each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) {
16686 expanded[ "border" + part + "Color" ] = value;
16687 });
16688 return expanded;
16689 }
16690 };
16691
16692 // Basic color names only.
16693 // Usage of any of the other color names requires adding yourself or including
16694 // jquery.color.svg-names.js.
16695 colors = jQuery.Color.names = {
16696 // 4.1. Basic color keywords
16697 aqua: "#00ffff",
16698 black: "#000000",
16699 blue: "#0000ff",
16700 fuchsia: "#ff00ff",
16701 gray: "#808080",
16702 green: "#008000",
16703 lime: "#00ff00",
16704 maroon: "#800000",
16705 navy: "#000080",
16706 olive: "#808000",
16707 purple: "#800080",
16708 red: "#ff0000",
16709 silver: "#c0c0c0",
16710 teal: "#008080",
16711 white: "#ffffff",
16712 yellow: "#ffff00",
16713
16714 // 4.2.3. "transparent" color keyword
16715 transparent: [ null, null, null, 0 ],
16716
16717 _default: "#ffffff"
16718 };
16719
16720 })( jQuery );
16721
16722
16723 /******************************************************************************/
16724 /****************************** CLASS ANIMATIONS ******************************/
16725 /******************************************************************************/
16726 (function() {
16727
16728 var classAnimationActions = [ "add", "remove", "toggle" ],
16729 shorthandStyles = {
16730 border: 1,
16731 borderBottom: 1,
16732 borderColor: 1,
16733 borderLeft: 1,
16734 borderRight: 1,
16735 borderTop: 1,
16736 borderWidth: 1,
16737 margin: 1,
16738 padding: 1
16739 };
16740
16741 $.each([ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) {
16742 $.fx.step[ prop ] = function( fx ) {
16743 if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) {
16744 jQuery.style( fx.elem, prop, fx.end );
16745 fx.setAttr = true;
16746 }
16747 };
16748 });
16749
16750 function getElementStyles( elem ) {
16751 var key, len,
16752 style = elem.ownerDocument.defaultView ?
16753 elem.ownerDocument.defaultView.getComputedStyle( elem, null ) :
16754 elem.currentStyle,
16755 styles = {};
16756
16757 if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) {
16758 len = style.length;
16759 while ( len-- ) {
16760 key = style[ len ];
16761 if ( typeof style[ key ] === "string" ) {
16762 styles[ $.camelCase( key ) ] = style[ key ];
16763 }
16764 }
16765 // support: Opera, IE <9
16766 } else {
16767 for ( key in style ) {
16768 if ( typeof style[ key ] === "string" ) {
16769 styles[ key ] = style[ key ];
16770 }
16771 }
16772 }
16773
16774 return styles;
16775 }
16776
16777
16778 function styleDifference( oldStyle, newStyle ) {
16779 var diff = {},
16780 name, value;
16781
16782 for ( name in newStyle ) {
16783 value = newStyle[ name ];
16784 if ( oldStyle[ name ] !== value ) {
16785 if ( !shorthandStyles[ name ] ) {
16786 if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) {
16787 diff[ name ] = value;
16788 }
16789 }
16790 }
16791 }
16792
16793 return diff;
16794 }
16795
16796 // support: jQuery <1.8
16797 if ( !$.fn.addBack ) {
16798 $.fn.addBack = function( selector ) {
16799 return this.add( selector == null ?
16800 this.prevObject : this.prevObject.filter( selector )
16801 );
16802 };
16803 }
16804
16805 $.effects.animateClass = function( value, duration, easing, callback ) {
16806 var o = $.speed( duration, easing, callback );
16807
16808 return this.queue( function() {
16809 var animated = $( this ),
16810 baseClass = animated.attr( "class" ) || "",
16811 applyClassChange,
16812 allAnimations = o.children ? animated.find( "*" ).addBack() : animated;
16813
16814 // map the animated objects to store the original styles.
16815 allAnimations = allAnimations.map(function() {
16816 var el = $( this );
16817 return {
16818 el: el,
16819 start: getElementStyles( this )
16820 };
16821 });
16822
16823 // apply class change
16824 applyClassChange = function() {
16825 $.each( classAnimationActions, function(i, action) {
16826 if ( value[ action ] ) {
16827 animated[ action + "Class" ]( value[ action ] );
16828 }
16829 });
16830 };
16831 applyClassChange();
16832
16833 // map all animated objects again - calculate new styles and diff
16834 allAnimations = allAnimations.map(function() {
16835 this.end = getElementStyles( this.el[ 0 ] );
16836 this.diff = styleDifference( this.start, this.end );
16837 return this;
16838 });
16839
16840 // apply original class
16841 animated.attr( "class", baseClass );
16842
16843 // map all animated objects again - this time collecting a promise
16844 allAnimations = allAnimations.map(function() {
16845 var styleInfo = this,
16846 dfd = $.Deferred(),
16847 opts = $.extend({}, o, {
16848 queue: false,
16849 complete: function() {
16850 dfd.resolve( styleInfo );
16851 }
16852 });
16853
16854 this.el.animate( this.diff, opts );
16855 return dfd.promise();
16856 });
16857
16858 // once all animations have completed:
16859 $.when.apply( $, allAnimations.get() ).done(function() {
16860
16861 // set the final class
16862 applyClassChange();
16863
16864 // for each animated element,
16865 // clear all css properties that were animated
16866 $.each( arguments, function() {
16867 var el = this.el;
16868 $.each( this.diff, function(key) {
16869 el.css( key, "" );
16870 });
16871 });
16872
16873 // this is guarnteed to be there if you use jQuery.speed()
16874 // it also handles dequeuing the next anim...
16875 o.complete.call( animated[ 0 ] );
16876 });
16877 });
16878 };
16879
16880 $.fn.extend({
16881 addClass: (function( orig ) {
16882 return function( classNames, speed, easing, callback ) {
16883 return speed ?
16884 $.effects.animateClass.call( this,
16885 { add: classNames }, speed, easing, callback ) :
16886 orig.apply( this, arguments );
16887 };
16888 })( $.fn.addClass ),
16889
16890 removeClass: (function( orig ) {
16891 return function( classNames, speed, easing, callback ) {
16892 return arguments.length > 1 ?
16893 $.effects.animateClass.call( this,
16894 { remove: classNames }, speed, easing, callback ) :
16895 orig.apply( this, arguments );
16896 };
16897 })( $.fn.removeClass ),
16898
16899 toggleClass: (function( orig ) {
16900 return function( classNames, force, speed, easing, callback ) {
16901 if ( typeof force === "boolean" || force === undefined ) {
16902 if ( !speed ) {
16903 // without speed parameter
16904 return orig.apply( this, arguments );
16905 } else {
16906 return $.effects.animateClass.call( this,
16907 (force ? { add: classNames } : { remove: classNames }),
16908 speed, easing, callback );
16909 }
16910 } else {
16911 // without force parameter
16912 return $.effects.animateClass.call( this,
16913 { toggle: classNames }, force, speed, easing );
16914 }
16915 };
16916 })( $.fn.toggleClass ),
16917
16918 switchClass: function( remove, add, speed, easing, callback) {
16919 return $.effects.animateClass.call( this, {
16920 add: add,
16921 remove: remove
16922 }, speed, easing, callback );
16923 }
16924 });
16925
16926 })();
16927
16928 /******************************************************************************/
16929 /*********************************** EFFECTS **********************************/
16930 /******************************************************************************/
16931
16932 (function() {
16933
16934 $.extend( $.effects, {
16935 version: "1.10.3",
16936
16937 // Saves a set of properties in a data storage
16938 save: function( element, set ) {
16939 for( var i=0; i < set.length; i++ ) {
16940 if ( set[ i ] !== null ) {
16941 element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] );
16942 }
16943 }
16944 },
16945
16946 // Restores a set of previously saved properties from a data storage
16947 restore: function( element, set ) {
16948 var val, i;
16949 for( i=0; i < set.length; i++ ) {
16950 if ( set[ i ] !== null ) {
16951 val = element.data( dataSpace + set[ i ] );
16952 // support: jQuery 1.6.2
16953 // http://bugs.jquery.com/ticket/9917
16954 // jQuery 1.6.2 incorrectly returns undefined for any falsy value.
16955 // We can't differentiate between "" and 0 here, so we just assume
16956 // empty string since it's likely to be a more common value...
16957 if ( val === undefined ) {
16958 val = "";
16959 }
16960 element.css( set[ i ], val );
16961 }
16962 }
16963 },
16964
16965 setMode: function( el, mode ) {
16966 if (mode === "toggle") {
16967 mode = el.is( ":hidden" ) ? "show" : "hide";
16968 }
16969 return mode;
16970 },
16971
16972 // Translates a [top,left] array into a baseline value
16973 // this should be a little more flexible in the future to handle a string & hash
16974 getBaseline: function( origin, original ) {
16975 var y, x;
16976 switch ( origin[ 0 ] ) {
16977 case "top": y = 0; break;
16978 case "middle": y = 0.5; break;
16979 case "bottom": y = 1; break;
16980 default: y = origin[ 0 ] / original.height;
16981 }
16982 switch ( origin[ 1 ] ) {
16983 case "left": x = 0; break;
16984 case "center": x = 0.5; break;
16985 case "right": x = 1; break;
16986 default: x = origin[ 1 ] / original.width;
16987 }
16988 return {
16989 x: x,
16990 y: y
16991 };
16992 },
16993
16994 // Wraps the element around a wrapper that copies position properties
16995 createWrapper: function( element ) {
16996
16997 // if the element is already wrapped, return it
16998 if ( element.parent().is( ".ui-effects-wrapper" )) {
16999 return element.parent();
17000 }
17001
17002 // wrap the element
17003 var props = {
17004 width: element.outerWidth(true),
17005 height: element.outerHeight(true),
17006 "float": element.css( "float" )
17007 },
17008 wrapper = $( "<div></div>" )
17009 .addClass( "ui-effects-wrapper" )
17010 .css({
17011 fontSize: "100%",
17012 background: "transparent",
17013 border: "none",
17014 margin: 0,
17015 padding: 0
17016 }),
17017 // Store the size in case width/height are defined in % - Fixes #5245
17018 size = {
17019 width: element.width(),
17020 height: element.height()
17021 },
17022 active = document.activeElement;
17023
17024 // support: Firefox
17025 // Firefox incorrectly exposes anonymous content
17026 // https://bugzilla.mozilla.org/show_bug.cgi?id=561664
17027 try {
17028 active.id;
17029 } catch( e ) {
17030 active = document.body;
17031 }
17032
17033 element.wrap( wrapper );
17034
17035 // Fixes #7595 - Elements lose focus when wrapped.
17036 if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
17037 $( active ).focus();
17038 }
17039
17040 wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element
17041
17042 // transfer positioning properties to the wrapper
17043 if ( element.css( "position" ) === "static" ) {
17044 wrapper.css({ position: "relative" });
17045 element.css({ position: "relative" });
17046 } else {
17047 $.extend( props, {
17048 position: element.css( "position" ),
17049 zIndex: element.css( "z-index" )
17050 });
17051 $.each([ "top", "left", "bottom", "right" ], function(i, pos) {
17052 props[ pos ] = element.css( pos );
17053 if ( isNaN( parseInt( props[ pos ], 10 ) ) ) {
17054 props[ pos ] = "auto";
17055 }
17056 });
17057 element.css({
17058 position: "relative",
17059 top: 0,
17060 left: 0,
17061 right: "auto",
17062 bottom: "auto"
17063 });
17064 }
17065 element.css(size);
17066
17067 return wrapper.css( props ).show();
17068 },
17069
17070 removeWrapper: function( element ) {
17071 var active = document.activeElement;
17072
17073 if ( element.parent().is( ".ui-effects-wrapper" ) ) {
17074 element.parent().replaceWith( element );
17075
17076 // Fixes #7595 - Elements lose focus when wrapped.
17077 if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
17078 $( active ).focus();
17079 }
17080 }
17081
17082
17083 return element;
17084 },
17085
17086 setTransition: function( element, list, factor, value ) {
17087 value = value || {};
17088 $.each( list, function( i, x ) {
17089 var unit = element.cssUnit( x );
17090 if ( unit[ 0 ] > 0 ) {
17091 value[ x ] = unit[ 0 ] * factor + unit[ 1 ];
17092 }
17093 });
17094 return value;
17095 }
17096 });
17097
17098 // return an effect options object for the given parameters:
17099 function _normalizeArguments( effect, options, speed, callback ) {
17100
17101 // allow passing all options as the first parameter
17102 if ( $.isPlainObject( effect ) ) {
17103 options = effect;
17104 effect = effect.effect;
17105 }
17106
17107 // convert to an object
17108 effect = { effect: effect };
17109
17110 // catch (effect, null, ...)
17111 if ( options == null ) {
17112 options = {};
17113 }
17114
17115 // catch (effect, callback)
17116 if ( $.isFunction( options ) ) {
17117 callback = options;
17118 speed = null;
17119 options = {};
17120 }
17121
17122 // catch (effect, speed, ?)
17123 if ( typeof options === "number" || $.fx.speeds[ options ] ) {
17124 callback = speed;
17125 speed = options;
17126 options = {};
17127 }
17128
17129 // catch (effect, options, callback)
17130 if ( $.isFunction( speed ) ) {
17131 callback = speed;
17132 speed = null;
17133 }
17134
17135 // add options to effect
17136 if ( options ) {
17137 $.extend( effect, options );
17138 }
17139
17140 speed = speed || options.duration;
17141 effect.duration = $.fx.off ? 0 :
17142 typeof speed === "number" ? speed :
17143 speed in $.fx.speeds ? $.fx.speeds[ speed ] :
17144 $.fx.speeds._default;
17145
17146 effect.complete = callback || options.complete;
17147
17148 return effect;
17149 }
17150
17151 function standardAnimationOption( option ) {
17152 // Valid standard speeds (nothing, number, named speed)
17153 if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) {
17154 return true;
17155 }
17156
17157 // Invalid strings - treat as "normal" speed
17158 if ( typeof option === "string" && !$.effects.effect[ option ] ) {
17159 return true;
17160 }
17161
17162 // Complete callback
17163 if ( $.isFunction( option ) ) {
17164 return true;
17165 }
17166
17167 // Options hash (but not naming an effect)
17168 if ( typeof option === "object" && !option.effect ) {
17169 return true;
17170 }
17171
17172 // Didn't match any standard API
17173 return false;
17174 }
17175
17176 $.fn.extend({
17177 effect: function( /* effect, options, speed, callback */ ) {
17178 var args = _normalizeArguments.apply( this, arguments ),
17179 mode = args.mode,
17180 queue = args.queue,
17181 effectMethod = $.effects.effect[ args.effect ];
17182
17183 if ( $.fx.off || !effectMethod ) {
17184 // delegate to the original method (e.g., .show()) if possible
17185 if ( mode ) {
17186 return this[ mode ]( args.duration, args.complete );
17187 } else {
17188 return this.each( function() {
17189 if ( args.complete ) {
17190 args.complete.call( this );
17191 }
17192 });
17193 }
17194 }
17195
17196 function run( next ) {
17197 var elem = $( this ),
17198 complete = args.complete,
17199 mode = args.mode;
17200
17201 function done() {
17202 if ( $.isFunction( complete ) ) {
17203 complete.call( elem[0] );
17204 }
17205 if ( $.isFunction( next ) ) {
17206 next();
17207 }
17208 }
17209
17210 // If the element already has the correct final state, delegate to
17211 // the core methods so the internal tracking of "olddisplay" works.
17212 if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) {
17213 elem[ mode ]();
17214 done();
17215 } else {
17216 effectMethod.call( elem[0], args, done );
17217 }
17218 }
17219
17220 return queue === false ? this.each( run ) : this.queue( queue || "fx", run );
17221 },
17222
17223 show: (function( orig ) {
17224 return function( option ) {
17225 if ( standardAnimationOption( option ) ) {
17226 return orig.apply( this, arguments );
17227 } else {
17228 var args = _normalizeArguments.apply( this, arguments );
17229 args.mode = "show";
17230 return this.effect.call( this, args );
17231 }
17232 };
17233 })( $.fn.show ),
17234
17235 hide: (function( orig ) {
17236 return function( option ) {
17237 if ( standardAnimationOption( option ) ) {
17238 return orig.apply( this, arguments );
17239 } else {
17240 var args = _normalizeArguments.apply( this, arguments );
17241 args.mode = "hide";
17242 return this.effect.call( this, args );
17243 }
17244 };
17245 })( $.fn.hide ),
17246
17247 toggle: (function( orig ) {
17248 return function( option ) {
17249 if ( standardAnimationOption( option ) || typeof option === "boolean" ) {
17250 return orig.apply( this, arguments );
17251 } else {
17252 var args = _normalizeArguments.apply( this, arguments );
17253 args.mode = "toggle";
17254 return this.effect.call( this, args );
17255 }
17256 };
17257 })( $.fn.toggle ),
17258
17259 // helper functions
17260 cssUnit: function(key) {
17261 var style = this.css( key ),
17262 val = [];
17263
17264 $.each( [ "em", "px", "%", "pt" ], function( i, unit ) {
17265 if ( style.indexOf( unit ) > 0 ) {
17266 val = [ parseFloat( style ), unit ];
17267 }
17268 });
17269 return val;
17270 }
17271 });
17272
17273 })();
17274
17275 /******************************************************************************/
17276 /*********************************** EASING ***********************************/
17277 /******************************************************************************/
17278
17279 (function() {
17280
17281 // based on easing equations from Robert Penner (http://www.robertpenner.com/easing)
17282
17283 var baseEasings = {};
17284
17285 $.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) {
17286 baseEasings[ name ] = function( p ) {
17287 return Math.pow( p, i + 2 );
17288 };
17289 });
17290
17291 $.extend( baseEasings, {
17292 Sine: function ( p ) {
17293 return 1 - Math.cos( p * Math.PI / 2 );
17294 },
17295 Circ: function ( p ) {
17296 return 1 - Math.sqrt( 1 - p * p );
17297 },
17298 Elastic: function( p ) {
17299 return p === 0 || p === 1 ? p :
17300 -Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 );
17301 },
17302 Back: function( p ) {
17303 return p * p * ( 3 * p - 2 );
17304 },
17305 Bounce: function ( p ) {
17306 var pow2,
17307 bounce = 4;
17308
17309 while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {}
17310 return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 );
17311 }
17312 });
17313
17314 $.each( baseEasings, function( name, easeIn ) {
17315 $.easing[ "easeIn" + name ] = easeIn;
17316 $.easing[ "easeOut" + name ] = function( p ) {
17317 return 1 - easeIn( 1 - p );
17318 };
17319 $.easing[ "easeInOut" + name ] = function( p ) {
17320 return p < 0.5 ?
17321 easeIn( p * 2 ) / 2 :
17322 1 - easeIn( p * -2 + 2 ) / 2;
17323 };
17324 });
17325
17326 })();
17327
17328 })(jQuery);
17329 (function( $, undefined ) {
17330
17331 var rvertical = /up|down|vertical/,
17332 rpositivemotion = /up|left|vertical|horizontal/;
17333
17334 $.effects.effect.blind = function( o, done ) {
17335 // Create element
17336 var el = $( this ),
17337 props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
17338 mode = $.effects.setMode( el, o.mode || "hide" ),
17339 direction = o.direction || "up",
17340 vertical = rvertical.test( direction ),
17341 ref = vertical ? "height" : "width",
17342 ref2 = vertical ? "top" : "left",
17343 motion = rpositivemotion.test( direction ),
17344 animation = {},
17345 show = mode === "show",
17346 wrapper, distance, margin;
17347
17348 // if already wrapped, the wrapper's properties are my property. #6245
17349 if ( el.parent().is( ".ui-effects-wrapper" ) ) {
17350 $.effects.save( el.parent(), props );
17351 } else {
17352 $.effects.save( el, props );
17353 }
17354 el.show();
17355 wrapper = $.effects.createWrapper( el ).css({
17356 overflow: "hidden"
17357 });
17358
17359 distance = wrapper[ ref ]();
17360 margin = parseFloat( wrapper.css( ref2 ) ) || 0;
17361
17362 animation[ ref ] = show ? distance : 0;
17363 if ( !motion ) {
17364 el
17365 .css( vertical ? "bottom" : "right", 0 )
17366 .css( vertical ? "top" : "left", "auto" )
17367 .css({ position: "absolute" });
17368
17369 animation[ ref2 ] = show ? margin : distance + margin;
17370 }
17371
17372 // start at 0 if we are showing
17373 if ( show ) {
17374 wrapper.css( ref, 0 );
17375 if ( ! motion ) {
17376 wrapper.css( ref2, margin + distance );
17377 }
17378 }
17379
17380 // Animate
17381 wrapper.animate( animation, {
17382 duration: o.duration,
17383 easing: o.easing,
17384 queue: false,
17385 complete: function() {
17386 if ( mode === "hide" ) {
17387 el.hide();
17388 }
17389 $.effects.restore( el, props );
17390 $.effects.removeWrapper( el );
17391 done();
17392 }
17393 });
17394
17395 };
17396
17397 })(jQuery);
17398 (function( $, undefined ) {
17399
17400 $.effects.effect.bounce = function( o, done ) {
17401 var el = $( this ),
17402 props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
17403
17404 // defaults:
17405 mode = $.effects.setMode( el, o.mode || "effect" ),
17406 hide = mode === "hide",
17407 show = mode === "show",
17408 direction = o.direction || "up",
17409 distance = o.distance,
17410 times = o.times || 5,
17411
17412 // number of internal animations
17413 anims = times * 2 + ( show || hide ? 1 : 0 ),
17414 speed = o.duration / anims,
17415 easing = o.easing,
17416
17417 // utility:
17418 ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
17419 motion = ( direction === "up" || direction === "left" ),
17420 i,
17421 upAnim,
17422 downAnim,
17423
17424 // we will need to re-assemble the queue to stack our animations in place
17425 queue = el.queue(),
17426 queuelen = queue.length;
17427
17428 // Avoid touching opacity to prevent clearType and PNG issues in IE
17429 if ( show || hide ) {
17430 props.push( "opacity" );
17431 }
17432
17433 $.effects.save( el, props );
17434 el.show();
17435 $.effects.createWrapper( el ); // Create Wrapper
17436
17437 // default distance for the BIGGEST bounce is the outer Distance / 3
17438 if ( !distance ) {
17439 distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3;
17440 }
17441
17442 if ( show ) {
17443 downAnim = { opacity: 1 };
17444 downAnim[ ref ] = 0;
17445
17446 // if we are showing, force opacity 0 and set the initial position
17447 // then do the "first" animation
17448 el.css( "opacity", 0 )
17449 .css( ref, motion ? -distance * 2 : distance * 2 )
17450 .animate( downAnim, speed, easing );
17451 }
17452
17453 // start at the smallest distance if we are hiding
17454 if ( hide ) {
17455 distance = distance / Math.pow( 2, times - 1 );
17456 }
17457
17458 downAnim = {};
17459 downAnim[ ref ] = 0;
17460 // Bounces up/down/left/right then back to 0 -- times * 2 animations happen here
17461 for ( i = 0; i < times; i++ ) {
17462 upAnim = {};
17463 upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;
17464
17465 el.animate( upAnim, speed, easing )
17466 .animate( downAnim, speed, easing );
17467
17468 distance = hide ? distance * 2 : distance / 2;
17469 }
17470
17471 // Last Bounce when Hiding
17472 if ( hide ) {
17473 upAnim = { opacity: 0 };
17474 upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;
17475
17476 el.animate( upAnim, speed, easing );
17477 }
17478
17479 el.queue(function() {
17480 if ( hide ) {
17481 el.hide();
17482 }
17483 $.effects.restore( el, props );
17484 $.effects.removeWrapper( el );
17485 done();
17486 });
17487
17488 // inject all the animations we just queued to be first in line (after "inprogress")
17489 if ( queuelen > 1) {
17490 queue.splice.apply( queue,
17491 [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
17492 }
17493 el.dequeue();
17494
17495 };
17496
17497 })(jQuery);
17498 (function( $, undefined ) {
17499
17500 $.effects.effect.clip = function( o, done ) {
17501 // Create element
17502 var el = $( this ),
17503 props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
17504 mode = $.effects.setMode( el, o.mode || "hide" ),
17505 show = mode === "show",
17506 direction = o.direction || "vertical",
17507 vert = direction === "vertical",
17508 size = vert ? "height" : "width",
17509 position = vert ? "top" : "left",
17510 animation = {},
17511 wrapper, animate, distance;
17512
17513 // Save & Show
17514 $.effects.save( el, props );
17515 el.show();
17516
17517 // Create Wrapper
17518 wrapper = $.effects.createWrapper( el ).css({
17519 overflow: "hidden"
17520 });
17521 animate = ( el[0].tagName === "IMG" ) ? wrapper : el;
17522 distance = animate[ size ]();
17523
17524 // Shift
17525 if ( show ) {
17526 animate.css( size, 0 );
17527 animate.css( position, distance / 2 );
17528 }
17529
17530 // Create Animation Object:
17531 animation[ size ] = show ? distance : 0;
17532 animation[ position ] = show ? 0 : distance / 2;
17533
17534 // Animate
17535 animate.animate( animation, {
17536 queue: false,
17537 duration: o.duration,
17538 easing: o.easing,
17539 complete: function() {
17540 if ( !show ) {
17541 el.hide();
17542 }
17543 $.effects.restore( el, props );
17544 $.effects.removeWrapper( el );
17545 done();
17546 }
17547 });
17548
17549 };
17550
17551 })(jQuery);
17552 (function( $, undefined ) {
17553
17554 $.effects.effect.drop = function( o, done ) {
17555
17556 var el = $( this ),
17557 props = [ "position", "top", "bottom", "left", "right", "opacity", "height", "width" ],
17558 mode = $.effects.setMode( el, o.mode || "hide" ),
17559 show = mode === "show",
17560 direction = o.direction || "left",
17561 ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
17562 motion = ( direction === "up" || direction === "left" ) ? "pos" : "neg",
17563 animation = {
17564 opacity: show ? 1 : 0
17565 },
17566 distance;
17567
17568 // Adjust
17569 $.effects.save( el, props );
17570 el.show();
17571 $.effects.createWrapper( el );
17572
17573 distance = o.distance || el[ ref === "top" ? "outerHeight": "outerWidth" ]( true ) / 2;
17574
17575 if ( show ) {
17576 el
17577 .css( "opacity", 0 )
17578 .css( ref, motion === "pos" ? -distance : distance );
17579 }
17580
17581 // Animation
17582 animation[ ref ] = ( show ?
17583 ( motion === "pos" ? "+=" : "-=" ) :
17584 ( motion === "pos" ? "-=" : "+=" ) ) +
17585 distance;
17586
17587 // Animate
17588 el.animate( animation, {
17589 queue: false,
17590 duration: o.duration,
17591 easing: o.easing,
17592 complete: function() {
17593 if ( mode === "hide" ) {
17594 el.hide();
17595 }
17596 $.effects.restore( el, props );
17597 $.effects.removeWrapper( el );
17598 done();
17599 }
17600 });
17601 };
17602
17603 })(jQuery);
17604 (function( $, undefined ) {
17605
17606 $.effects.effect.explode = function( o, done ) {
17607
17608 var rows = o.pieces ? Math.round( Math.sqrt( o.pieces ) ) : 3,
17609 cells = rows,
17610 el = $( this ),
17611 mode = $.effects.setMode( el, o.mode || "hide" ),
17612 show = mode === "show",
17613
17614 // show and then visibility:hidden the element before calculating offset
17615 offset = el.show().css( "visibility", "hidden" ).offset(),
17616
17617 // width and height of a piece
17618 width = Math.ceil( el.outerWidth() / cells ),
17619 height = Math.ceil( el.outerHeight() / rows ),
17620 pieces = [],
17621
17622 // loop
17623 i, j, left, top, mx, my;
17624
17625 // children animate complete:
17626 function childComplete() {
17627 pieces.push( this );
17628 if ( pieces.length === rows * cells ) {
17629 animComplete();
17630 }
17631 }
17632
17633 // clone the element for each row and cell.
17634 for( i = 0; i < rows ; i++ ) { // ===>
17635 top = offset.top + i * height;
17636 my = i - ( rows - 1 ) / 2 ;
17637
17638 for( j = 0; j < cells ; j++ ) { // |||
17639 left = offset.left + j * width;
17640 mx = j - ( cells - 1 ) / 2 ;
17641
17642 // Create a clone of the now hidden main element that will be absolute positioned
17643 // within a wrapper div off the -left and -top equal to size of our pieces
17644 el
17645 .clone()
17646 .appendTo( "body" )
17647 .wrap( "<div></div>" )
17648 .css({
17649 position: "absolute",
17650 visibility: "visible",
17651 left: -j * width,
17652 top: -i * height
17653 })
17654
17655 // select the wrapper - make it overflow: hidden and absolute positioned based on
17656 // where the original was located +left and +top equal to the size of pieces
17657 .parent()
17658 .addClass( "ui-effects-explode" )
17659 .css({
17660 position: "absolute",
17661 overflow: "hidden",
17662 width: width,
17663 height: height,
17664 left: left + ( show ? mx * width : 0 ),
17665 top: top + ( show ? my * height : 0 ),
17666 opacity: show ? 0 : 1
17667 }).animate({
17668 left: left + ( show ? 0 : mx * width ),
17669 top: top + ( show ? 0 : my * height ),
17670 opacity: show ? 1 : 0
17671 }, o.duration || 500, o.easing, childComplete );
17672 }
17673 }
17674
17675 function animComplete() {
17676 el.css({
17677 visibility: "visible"
17678 });
17679 $( pieces ).remove();
17680 if ( !show ) {
17681 el.hide();
17682 }
17683 done();
17684 }
17685 };
17686
17687 })(jQuery);
17688 (function( $, undefined ) {
17689
17690 $.effects.effect.fade = function( o, done ) {
17691 var el = $( this ),
17692 mode = $.effects.setMode( el, o.mode || "toggle" );
17693
17694 el.animate({
17695 opacity: mode
17696 }, {
17697 queue: false,
17698 duration: o.duration,
17699 easing: o.easing,
17700 complete: done
17701 });
17702 };
17703
17704 })( jQuery );
17705 (function( $, undefined ) {
17706
17707 $.effects.effect.fold = function( o, done ) {
17708
17709 // Create element
17710 var el = $( this ),
17711 props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
17712 mode = $.effects.setMode( el, o.mode || "hide" ),
17713 show = mode === "show",
17714 hide = mode === "hide",
17715 size = o.size || 15,
17716 percent = /([0-9]+)%/.exec( size ),
17717 horizFirst = !!o.horizFirst,
17718 widthFirst = show !== horizFirst,
17719 ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ],
17720 duration = o.duration / 2,
17721 wrapper, distance,
17722 animation1 = {},
17723 animation2 = {};
17724
17725 $.effects.save( el, props );
17726 el.show();
17727
17728 // Create Wrapper
17729 wrapper = $.effects.createWrapper( el ).css({
17730 overflow: "hidden"
17731 });
17732 distance = widthFirst ?
17733 [ wrapper.width(), wrapper.height() ] :
17734 [ wrapper.height(), wrapper.width() ];
17735
17736 if ( percent ) {
17737 size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ];
17738 }
17739 if ( show ) {
17740 wrapper.css( horizFirst ? {
17741 height: 0,
17742 width: size
17743 } : {
17744 height: size,
17745 width: 0
17746 });
17747 }
17748
17749 // Animation
17750 animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size;
17751 animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0;
17752
17753 // Animate
17754 wrapper
17755 .animate( animation1, duration, o.easing )
17756 .animate( animation2, duration, o.easing, function() {
17757 if ( hide ) {
17758 el.hide();
17759 }
17760 $.effects.restore( el, props );
17761 $.effects.removeWrapper( el );
17762 done();
17763 });
17764
17765 };
17766
17767 })(jQuery);
17768 (function( $, undefined ) {
17769
17770 $.effects.effect.highlight = function( o, done ) {
17771 var elem = $( this ),
17772 props = [ "backgroundImage", "backgroundColor", "opacity" ],
17773 mode = $.effects.setMode( elem, o.mode || "show" ),
17774 animation = {
17775 backgroundColor: elem.css( "backgroundColor" )
17776 };
17777
17778 if (mode === "hide") {
17779 animation.opacity = 0;
17780 }
17781
17782 $.effects.save( elem, props );
17783
17784 elem
17785 .show()
17786 .css({
17787 backgroundImage: "none",
17788 backgroundColor: o.color || "#ffff99"
17789 })
17790 .animate( animation, {
17791 queue: false,
17792 duration: o.duration,
17793 easing: o.easing,
17794 complete: function() {
17795 if ( mode === "hide" ) {
17796 elem.hide();
17797 }
17798 $.effects.restore( elem, props );
17799 done();
17800 }
17801 });
17802 };
17803
17804 })(jQuery);
17805 (function( $, undefined ) {
17806
17807 $.effects.effect.pulsate = function( o, done ) {
17808 var elem = $( this ),
17809 mode = $.effects.setMode( elem, o.mode || "show" ),
17810 show = mode === "show",
17811 hide = mode === "hide",
17812 showhide = ( show || mode === "hide" ),
17813
17814 // showing or hiding leaves of the "last" animation
17815 anims = ( ( o.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ),
17816 duration = o.duration / anims,
17817 animateTo = 0,
17818 queue = elem.queue(),
17819 queuelen = queue.length,
17820 i;
17821
17822 if ( show || !elem.is(":visible")) {
17823 elem.css( "opacity", 0 ).show();
17824 animateTo = 1;
17825 }
17826
17827 // anims - 1 opacity "toggles"
17828 for ( i = 1; i < anims; i++ ) {
17829 elem.animate({
17830 opacity: animateTo
17831 }, duration, o.easing );
17832 animateTo = 1 - animateTo;
17833 }
17834
17835 elem.animate({
17836 opacity: animateTo
17837 }, duration, o.easing);
17838
17839 elem.queue(function() {
17840 if ( hide ) {
17841 elem.hide();
17842 }
17843 done();
17844 });
17845
17846 // We just queued up "anims" animations, we need to put them next in the queue
17847 if ( queuelen > 1 ) {
17848 queue.splice.apply( queue,
17849 [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
17850 }
17851 elem.dequeue();
17852 };
17853
17854 })(jQuery);
17855 (function( $, undefined ) {
17856
17857 $.effects.effect.puff = function( o, done ) {
17858 var elem = $( this ),
17859 mode = $.effects.setMode( elem, o.mode || "hide" ),
17860 hide = mode === "hide",
17861 percent = parseInt( o.percent, 10 ) || 150,
17862 factor = percent / 100,
17863 original = {
17864 height: elem.height(),
17865 width: elem.width(),
17866 outerHeight: elem.outerHeight(),
17867 outerWidth: elem.outerWidth()
17868 };
17869
17870 $.extend( o, {
17871 effect: "scale",
17872 queue: false,
17873 fade: true,
17874 mode: mode,
17875 complete: done,
17876 percent: hide ? percent : 100,
17877 from: hide ?
17878 original :
17879 {
17880 height: original.height * factor,
17881 width: original.width * factor,
17882 outerHeight: original.outerHeight * factor,
17883 outerWidth: original.outerWidth * factor
17884 }
17885 });
17886
17887 elem.effect( o );
17888 };
17889
17890 $.effects.effect.scale = function( o, done ) {
17891
17892 // Create element
17893 var el = $( this ),
17894 options = $.extend( true, {}, o ),
17895 mode = $.effects.setMode( el, o.mode || "effect" ),
17896 percent = parseInt( o.percent, 10 ) ||
17897 ( parseInt( o.percent, 10 ) === 0 ? 0 : ( mode === "hide" ? 0 : 100 ) ),
17898 direction = o.direction || "both",
17899 origin = o.origin,
17900 original = {
17901 height: el.height(),
17902 width: el.width(),
17903 outerHeight: el.outerHeight(),
17904 outerWidth: el.outerWidth()
17905 },
17906 factor = {
17907 y: direction !== "horizontal" ? (percent / 100) : 1,
17908 x: direction !== "vertical" ? (percent / 100) : 1
17909 };
17910
17911 // We are going to pass this effect to the size effect:
17912 options.effect = "size";
17913 options.queue = false;
17914 options.complete = done;
17915
17916 // Set default origin and restore for show/hide
17917 if ( mode !== "effect" ) {
17918 options.origin = origin || ["middle","center"];
17919 options.restore = true;
17920 }
17921
17922 options.from = o.from || ( mode === "show" ? {
17923 height: 0,
17924 width: 0,
17925 outerHeight: 0,
17926 outerWidth: 0
17927 } : original );
17928 options.to = {
17929 height: original.height * factor.y,
17930 width: original.width * factor.x,
17931 outerHeight: original.outerHeight * factor.y,
17932 outerWidth: original.outerWidth * factor.x
17933 };
17934
17935 // Fade option to support puff
17936 if ( options.fade ) {
17937 if ( mode === "show" ) {
17938 options.from.opacity = 0;
17939 options.to.opacity = 1;
17940 }
17941 if ( mode === "hide" ) {
17942 options.from.opacity = 1;
17943 options.to.opacity = 0;
17944 }
17945 }
17946
17947 // Animate
17948 el.effect( options );
17949
17950 };
17951
17952 $.effects.effect.size = function( o, done ) {
17953
17954 // Create element
17955 var original, baseline, factor,
17956 el = $( this ),
17957 props0 = [ "position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity" ],
17958
17959 // Always restore
17960 props1 = [ "position", "top", "bottom", "left", "right", "overflow", "opacity" ],
17961
17962 // Copy for children
17963 props2 = [ "width", "height", "overflow" ],
17964 cProps = [ "fontSize" ],
17965 vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ],
17966 hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ],
17967
17968 // Set options
17969 mode = $.effects.setMode( el, o.mode || "effect" ),
17970 restore = o.restore || mode !== "effect",
17971 scale = o.scale || "both",
17972 origin = o.origin || [ "middle", "center" ],
17973 position = el.css( "position" ),
17974 props = restore ? props0 : props1,
17975 zero = {
17976 height: 0,
17977 width: 0,
17978 outerHeight: 0,
17979 outerWidth: 0
17980 };
17981
17982 if ( mode === "show" ) {
17983 el.show();
17984 }
17985 original = {
17986 height: el.height(),
17987 width: el.width(),
17988 outerHeight: el.outerHeight(),
17989 outerWidth: el.outerWidth()
17990 };
17991
17992 if ( o.mode === "toggle" && mode === "show" ) {
17993 el.from = o.to || zero;
17994 el.to = o.from || original;
17995 } else {
17996 el.from = o.from || ( mode === "show" ? zero : original );
17997 el.to = o.to || ( mode === "hide" ? zero : original );
17998 }
17999
18000 // Set scaling factor
18001 factor = {
18002 from: {
18003 y: el.from.height / original.height,
18004 x: el.from.width / original.width
18005 },
18006 to: {
18007 y: el.to.height / original.height,
18008 x: el.to.width / original.width
18009 }
18010 };
18011
18012 // Scale the css box
18013 if ( scale === "box" || scale === "both" ) {
18014
18015 // Vertical props scaling
18016 if ( factor.from.y !== factor.to.y ) {
18017 props = props.concat( vProps );
18018 el.from = $.effects.setTransition( el, vProps, factor.from.y, el.from );
18019 el.to = $.effects.setTransition( el, vProps, factor.to.y, el.to );
18020 }
18021
18022 // Horizontal props scaling
18023 if ( factor.from.x !== factor.to.x ) {
18024 props = props.concat( hProps );
18025 el.from = $.effects.setTransition( el, hProps, factor.from.x, el.from );
18026 el.to = $.effects.setTransition( el, hProps, factor.to.x, el.to );
18027 }
18028 }
18029
18030 // Scale the content
18031 if ( scale === "content" || scale === "both" ) {
18032
18033 // Vertical props scaling
18034 if ( factor.from.y !== factor.to.y ) {
18035 props = props.concat( cProps ).concat( props2 );
18036 el.from = $.effects.setTransition( el, cProps, factor.from.y, el.from );
18037 el.to = $.effects.setTransition( el, cProps, factor.to.y, el.to );
18038 }
18039 }
18040
18041 $.effects.save( el, props );
18042 el.show();
18043 $.effects.createWrapper( el );
18044 el.css( "overflow", "hidden" ).css( el.from );
18045
18046 // Adjust
18047 if (origin) { // Calculate baseline shifts
18048 baseline = $.effects.getBaseline( origin, original );
18049 el.from.top = ( original.outerHeight - el.outerHeight() ) * baseline.y;
18050 el.from.left = ( original.outerWidth - el.outerWidth() ) * baseline.x;
18051 el.to.top = ( original.outerHeight - el.to.outerHeight ) * baseline.y;
18052 el.to.left = ( original.outerWidth - el.to.outerWidth ) * baseline.x;
18053 }
18054 el.css( el.from ); // set top & left
18055
18056 // Animate
18057 if ( scale === "content" || scale === "both" ) { // Scale the children
18058
18059 // Add margins/font-size
18060 vProps = vProps.concat([ "marginTop", "marginBottom" ]).concat(cProps);
18061 hProps = hProps.concat([ "marginLeft", "marginRight" ]);
18062 props2 = props0.concat(vProps).concat(hProps);
18063
18064 el.find( "*[width]" ).each( function(){
18065 var child = $( this ),
18066 c_original = {
18067 height: child.height(),
18068 width: child.width(),
18069 outerHeight: child.outerHeight(),
18070 outerWidth: child.outerWidth()
18071 };
18072 if (restore) {
18073 $.effects.save(child, props2);
18074 }
18075
18076 child.from = {
18077 height: c_original.height * factor.from.y,
18078 width: c_original.width * factor.from.x,
18079 outerHeight: c_original.outerHeight * factor.from.y,
18080 outerWidth: c_original.outerWidth * factor.from.x
18081 };
18082 child.to = {
18083 height: c_original.height * factor.to.y,
18084 width: c_original.width * factor.to.x,
18085 outerHeight: c_original.height * factor.to.y,
18086 outerWidth: c_original.width * factor.to.x
18087 };
18088
18089 // Vertical props scaling
18090 if ( factor.from.y !== factor.to.y ) {
18091 child.from = $.effects.setTransition( child, vProps, factor.from.y, child.from );
18092 child.to = $.effects.setTransition( child, vProps, factor.to.y, child.to );
18093 }
18094
18095 // Horizontal props scaling
18096 if ( factor.from.x !== factor.to.x ) {
18097 child.from = $.effects.setTransition( child, hProps, factor.from.x, child.from );
18098 child.to = $.effects.setTransition( child, hProps, factor.to.x, child.to );
18099 }
18100
18101 // Animate children
18102 child.css( child.from );
18103 child.animate( child.to, o.duration, o.easing, function() {
18104
18105 // Restore children
18106 if ( restore ) {
18107 $.effects.restore( child, props2 );
18108 }
18109 });
18110 });
18111 }
18112
18113 // Animate
18114 el.animate( el.to, {
18115 queue: false,
18116 duration: o.duration,
18117 easing: o.easing,
18118 complete: function() {
18119 if ( el.to.opacity === 0 ) {
18120 el.css( "opacity", el.from.opacity );
18121 }
18122 if( mode === "hide" ) {
18123 el.hide();
18124 }
18125 $.effects.restore( el, props );
18126 if ( !restore ) {
18127
18128 // we need to calculate our new positioning based on the scaling
18129 if ( position === "static" ) {
18130 el.css({
18131 position: "relative",
18132 top: el.to.top,
18133 left: el.to.left
18134 });
18135 } else {
18136 $.each([ "top", "left" ], function( idx, pos ) {
18137 el.css( pos, function( _, str ) {
18138 var val = parseInt( str, 10 ),
18139 toRef = idx ? el.to.left : el.to.top;
18140
18141 // if original was "auto", recalculate the new value from wrapper
18142 if ( str === "auto" ) {
18143 return toRef + "px";
18144 }
18145
18146 return val + toRef + "px";
18147 });
18148 });
18149 }
18150 }
18151
18152 $.effects.removeWrapper( el );
18153 done();
18154 }
18155 });
18156
18157 };
18158
18159 })(jQuery);
18160 (function( $, undefined ) {
18161
18162 $.effects.effect.shake = function( o, done ) {
18163
18164 var el = $( this ),
18165 props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
18166 mode = $.effects.setMode( el, o.mode || "effect" ),
18167 direction = o.direction || "left",
18168 distance = o.distance || 20,
18169 times = o.times || 3,
18170 anims = times * 2 + 1,
18171 speed = Math.round(o.duration/anims),
18172 ref = (direction === "up" || direction === "down") ? "top" : "left",
18173 positiveMotion = (direction === "up" || direction === "left"),
18174 animation = {},
18175 animation1 = {},
18176 animation2 = {},
18177 i,
18178
18179 // we will need to re-assemble the queue to stack our animations in place
18180 queue = el.queue(),
18181 queuelen = queue.length;
18182
18183 $.effects.save( el, props );
18184 el.show();
18185 $.effects.createWrapper( el );
18186
18187 // Animation
18188 animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance;
18189 animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2;
18190 animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2;
18191
18192 // Animate
18193 el.animate( animation, speed, o.easing );
18194
18195 // Shakes
18196 for ( i = 1; i < times; i++ ) {
18197 el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing );
18198 }
18199 el
18200 .animate( animation1, speed, o.easing )
18201 .animate( animation, speed / 2, o.easing )
18202 .queue(function() {
18203 if ( mode === "hide" ) {
18204 el.hide();
18205 }
18206 $.effects.restore( el, props );
18207 $.effects.removeWrapper( el );
18208 done();
18209 });
18210
18211 // inject all the animations we just queued to be first in line (after "inprogress")
18212 if ( queuelen > 1) {
18213 queue.splice.apply( queue,
18214 [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
18215 }
18216 el.dequeue();
18217
18218 };
18219
18220 })(jQuery);
18221 (function( $, undefined ) {
18222
18223 $.effects.effect.slide = function( o, done ) {
18224
18225 // Create element
18226 var el = $( this ),
18227 props = [ "position", "top", "bottom", "left", "right", "width", "height" ],
18228 mode = $.effects.setMode( el, o.mode || "show" ),
18229 show = mode === "show",
18230 direction = o.direction || "left",
18231 ref = (direction === "up" || direction === "down") ? "top" : "left",
18232 positiveMotion = (direction === "up" || direction === "left"),
18233 distance,
18234 animation = {};
18235
18236 // Adjust
18237 $.effects.save( el, props );
18238 el.show();
18239 distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true );
18240
18241 $.effects.createWrapper( el ).css({
18242 overflow: "hidden"
18243 });
18244
18245 if ( show ) {
18246 el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance );
18247 }
18248
18249 // Animation
18250 animation[ ref ] = ( show ?
18251 ( positiveMotion ? "+=" : "-=") :
18252 ( positiveMotion ? "-=" : "+=")) +
18253 distance;
18254
18255 // Animate
18256 el.animate( animation, {
18257 queue: false,
18258 duration: o.duration,
18259 easing: o.easing,
18260 complete: function() {
18261 if ( mode === "hide" ) {
18262 el.hide();
18263 }
18264 $.effects.restore( el, props );
18265 $.effects.removeWrapper( el );
18266 done();
18267 }
18268 });
18269 };
18270
18271 })(jQuery);
18272 (function( $, undefined ) {
18273
18274 $.effects.effect.transfer = function( o, done ) {
18275 var elem = $( this ),
18276 target = $( o.to ),
18277 targetFixed = target.css( "position" ) === "fixed",
18278 body = $("body"),
18279 fixTop = targetFixed ? body.scrollTop() : 0,
18280 fixLeft = targetFixed ? body.scrollLeft() : 0,
18281 endPosition = target.offset(),
18282 animation = {
18283 top: endPosition.top - fixTop ,
18284 left: endPosition.left - fixLeft ,
18285 height: target.innerHeight(),
18286 width: target.innerWidth()
18287 },
18288 startPosition = elem.offset(),
18289 transfer = $( "<div class='ui-effects-transfer'></div>" )
18290 .appendTo( document.body )
18291 .addClass( o.className )
18292 .css({
18293 top: startPosition.top - fixTop ,
18294 left: startPosition.left - fixLeft ,
18295 height: elem.innerHeight(),
18296 width: elem.innerWidth(),
18297 position: targetFixed ? "fixed" : "absolute"
18298 })
18299 .animate( animation, o.duration, o.easing, function() {
18300 transfer.remove();
18301 done();
18302 });
18303 };
18304
18305 })(jQuery);
18306 /*globals jQuery, define, exports, require, window, document, postMessage */
18307 (function (factory) {
18308 "use strict";
18309 if (typeof define === 'function' && define.amd) {
18310 define(['jquery'], factory);
18311 }
18312 else if(typeof exports === 'object') {
18313 factory(require('jquery'));
18314 }
18315 else {
18316 factory(jQuery);
18317 }
18318 }(function ($, undefined) {
18319 "use strict";
18320 /*!
18321 * jsTree 3.0.9
18322 * http://jstree.com/
18323 *
18324 * Copyright (c) 2014 Ivan Bozhanov (http://vakata.com)
18325 *
18326 * Licensed same as jquery - under the terms of the MIT License
18327 * http://www.opensource.org/licenses/mit-license.php
18328 */
18329 /*!
18330 * if using jslint please allow for the jQuery global and use following options:
18331 * jslint: browser: true, ass: true, bitwise: true, continue: true, nomen: true, plusplus: true, regexp: true, unparam: true, todo: true, white: true
18332 */
18333
18334 // prevent another load? maybe there is a better way?
18335 if($.jstree) {
18336 return;
18337 }
18338
18339 /**
18340 * ### jsTree core functionality
18341 */
18342
18343 // internal variables
18344 var instance_counter = 0,
18345 ccp_node = false,
18346 ccp_mode = false,
18347 ccp_inst = false,
18348 themes_loaded = [],
18349 src = $('script:last').attr('src'),
18350 _d = document, _node = _d.createElement('LI'), _temp1, _temp2;
18351
18352 _node.setAttribute('role', 'treeitem');
18353 _temp1 = _d.createElement('I');
18354 _temp1.className = 'jstree-icon jstree-ocl';
18355 _temp1.setAttribute('role', 'presentation');
18356 _node.appendChild(_temp1);
18357 _temp1 = _d.createElement('A');
18358 _temp1.className = 'jstree-anchor';
18359 _temp1.setAttribute('href','#');
18360 _temp1.setAttribute('tabindex','-1');
18361 _temp2 = _d.createElement('I');
18362 _temp2.className = 'jstree-icon jstree-themeicon';
18363 _temp2.setAttribute('role', 'presentation');
18364 _temp1.appendChild(_temp2);
18365 _node.appendChild(_temp1);
18366 _temp1 = _temp2 = null;
18367
18368
18369 /**
18370 * holds all jstree related functions and variables, including the actual class and methods to create, access and manipulate instances.
18371 * @name $.jstree
18372 */
18373 $.jstree = {
18374 /**
18375 * specifies the jstree version in use
18376 * @name $.jstree.version
18377 */
18378 version : '3.0.9',
18379 /**
18380 * holds all the default options used when creating new instances
18381 * @name $.jstree.defaults
18382 */
18383 defaults : {
18384 /**
18385 * configure which plugins will be active on an instance. Should be an array of strings, where each element is a plugin name. The default is `[]`
18386 * @name $.jstree.defaults.plugins
18387 */
18388 plugins : []
18389 },
18390 /**
18391 * stores all loaded jstree plugins (used internally)
18392 * @name $.jstree.plugins
18393 */
18394 plugins : {},
18395 path : src && src.indexOf('/') !== -1 ? src.replace(/\/[^\/]+$/,'') : '',
18396 idregex : /[\\:&!^|()\[\]<>@*'+~#";.,=\- \/${}%?`]/g
18397 };
18398 /**
18399 * creates a jstree instance
18400 * @name $.jstree.create(el [, options])
18401 * @param {DOMElement|jQuery|String} el the element to create the instance on, can be jQuery extended or a selector
18402 * @param {Object} options options for this instance (extends `$.jstree.defaults`)
18403 * @return {jsTree} the new instance
18404 */
18405 $.jstree.create = function (el, options) {
18406 var tmp = new $.jstree.core(++instance_counter),
18407 opt = options;
18408 options = $.extend(true, {}, $.jstree.defaults, options);
18409 if(opt && opt.plugins) {
18410 options.plugins = opt.plugins;
18411 }
18412 $.each(options.plugins, function (i, k) {
18413 if(i !== 'core') {
18414 tmp = tmp.plugin(k, options[k]);
18415 }
18416 });
18417 tmp.init(el, options);
18418 return tmp;
18419 };
18420 /**
18421 * remove all traces of jstree from the DOM and destroy all instances
18422 * @name $.jstree.destroy()
18423 */
18424 $.jstree.destroy = function () {
18425 $('.jstree:jstree').jstree('destroy');
18426 $(document).off('.jstree');
18427 };
18428 /**
18429 * the jstree class constructor, used only internally
18430 * @private
18431 * @name $.jstree.core(id)
18432 * @param {Number} id this instance's index
18433 */
18434 $.jstree.core = function (id) {
18435 this._id = id;
18436 this._cnt = 0;
18437 this._wrk = null;
18438 this._data = {
18439 core : {
18440 themes : {
18441 name : false,
18442 dots : false,
18443 icons : false
18444 },
18445 selected : [],
18446 last_error : {},
18447 working : false,
18448 worker_queue : [],
18449 focused : null
18450 }
18451 };
18452 };
18453 /**
18454 * get a reference to an existing instance
18455 *
18456 * __Examples__
18457 *
18458 * // provided a container with an ID of "tree", and a nested node with an ID of "branch"
18459 * // all of there will return the same instance
18460 * $.jstree.reference('tree');
18461 * $.jstree.reference('#tree');
18462 * $.jstree.reference($('#tree'));
18463 * $.jstree.reference(document.getElementByID('tree'));
18464 * $.jstree.reference('branch');
18465 * $.jstree.reference('#branch');
18466 * $.jstree.reference($('#branch'));
18467 * $.jstree.reference(document.getElementByID('branch'));
18468 *
18469 * @name $.jstree.reference(needle)
18470 * @param {DOMElement|jQuery|String} needle
18471 * @return {jsTree|null} the instance or `null` if not found
18472 */
18473 $.jstree.reference = function (needle) {
18474 var tmp = null,
18475 obj = null;
18476 if(needle && needle.id) { needle = needle.id; }
18477
18478 if(!obj || !obj.length) {
18479 try { obj = $(needle); } catch (ignore) { }
18480 }
18481 if(!obj || !obj.length) {
18482 try { obj = $('#' + needle.replace($.jstree.idregex,'\\$&')); } catch (ignore) { }
18483 }
18484 if(obj && obj.length && (obj = obj.closest('.jstree')).length && (obj = obj.data('jstree'))) {
18485 tmp = obj;
18486 }
18487 else {
18488 $('.jstree').each(function () {
18489 var inst = $(this).data('jstree');
18490 if(inst && inst._model.data[needle]) {
18491 tmp = inst;
18492 return false;
18493 }
18494 });
18495 }
18496 return tmp;
18497 };
18498 /**
18499 * Create an instance, get an instance or invoke a command on a instance.
18500 *
18501 * If there is no instance associated with the current node a new one is created and `arg` is used to extend `$.jstree.defaults` for this new instance. There would be no return value (chaining is not broken).
18502 *
18503 * If there is an existing instance and `arg` is a string the command specified by `arg` is executed on the instance, with any additional arguments passed to the function. If the function returns a value it will be returned (chaining could break depending on function).
18504 *
18505 * If there is an existing instance and `arg` is not a string the instance itself is returned (similar to `$.jstree.reference`).
18506 *
18507 * In any other case - nothing is returned and chaining is not broken.
18508 *
18509 * __Examples__
18510 *
18511 * $('#tree1').jstree(); // creates an instance
18512 * $('#tree2').jstree({ plugins : [] }); // create an instance with some options
18513 * $('#tree1').jstree('open_node', '#branch_1'); // call a method on an existing instance, passing additional arguments
18514 * $('#tree2').jstree(); // get an existing instance (or create an instance)
18515 * $('#tree2').jstree(true); // get an existing instance (will not create new instance)
18516 * $('#branch_1').jstree().select_node('#branch_1'); // get an instance (using a nested element and call a method)
18517 *
18518 * @name $().jstree([arg])
18519 * @param {String|Object} arg
18520 * @return {Mixed}
18521 */
18522 $.fn.jstree = function (arg) {
18523 // check for string argument
18524 var is_method = (typeof arg === 'string'),
18525 args = Array.prototype.slice.call(arguments, 1),
18526 result = null;
18527 if(arg === true && !this.length) { return false; }
18528 this.each(function () {
18529 // get the instance (if there is one) and method (if it exists)
18530 var instance = $.jstree.reference(this),
18531 method = is_method && instance ? instance[arg] : null;
18532 // if calling a method, and method is available - execute on the instance
18533 result = is_method && method ?
18534 method.apply(instance, args) :
18535 null;
18536 // if there is no instance and no method is being called - create one
18537 if(!instance && !is_method && (arg === undefined || $.isPlainObject(arg))) {
18538 $(this).data('jstree', new $.jstree.create(this, arg));
18539 }
18540 // if there is an instance and no method is called - return the instance
18541 if( (instance && !is_method) || arg === true ) {
18542 result = instance || false;
18543 }
18544 // if there was a method call which returned a result - break and return the value
18545 if(result !== null && result !== undefined) {
18546 return false;
18547 }
18548 });
18549 // if there was a method call with a valid return value - return that, otherwise continue the chain
18550 return result !== null && result !== undefined ?
18551 result : this;
18552 };
18553 /**
18554 * used to find elements containing an instance
18555 *
18556 * __Examples__
18557 *
18558 * $('div:jstree').each(function () {
18559 * $(this).jstree('destroy');
18560 * });
18561 *
18562 * @name $(':jstree')
18563 * @return {jQuery}
18564 */
18565 $.expr[':'].jstree = $.expr.createPseudo(function(search) {
18566 return function(a) {
18567 return $(a).hasClass('jstree') &&
18568 $(a).data('jstree') !== undefined;
18569 };
18570 });
18571
18572 /**
18573 * stores all defaults for the core
18574 * @name $.jstree.defaults.core
18575 */
18576 $.jstree.defaults.core = {
18577 /**
18578 * data configuration
18579 *
18580 * If left as `false` the HTML inside the jstree container element is used to populate the tree (that should be an unordered list with list items).
18581 *
18582 * You can also pass in a HTML string or a JSON array here.
18583 *
18584 * It is possible to pass in a standard jQuery-like AJAX config and jstree will automatically determine if the response is JSON or HTML and use that to populate the tree.
18585 * In addition to the standard jQuery ajax options here you can suppy functions for `data` and `url`, the functions will be run in the current instance's scope and a param will be passed indicating which node is being loaded, the return value of those functions will be used.
18586 *
18587 * The last option is to specify a function, that function will receive the node being loaded as argument and a second param which is a function which should be called with the result.
18588 *
18589 * __Examples__
18590 *
18591 * // AJAX
18592 * $('#tree').jstree({
18593 * 'core' : {
18594 * 'data' : {
18595 * 'url' : '/get/children/',
18596 * 'data' : function (node) {
18597 * return { 'id' : node.id };
18598 * }
18599 * }
18600 * });
18601 *
18602 * // direct data
18603 * $('#tree').jstree({
18604 * 'core' : {
18605 * 'data' : [
18606 * 'Simple root node',
18607 * {
18608 * 'id' : 'node_2',
18609 * 'text' : 'Root node with options',
18610 * 'state' : { 'opened' : true, 'selected' : true },
18611 * 'children' : [ { 'text' : 'Child 1' }, 'Child 2']
18612 * }
18613 * ]
18614 * });
18615 *
18616 * // function
18617 * $('#tree').jstree({
18618 * 'core' : {
18619 * 'data' : function (obj, callback) {
18620 * callback.call(this, ['Root 1', 'Root 2']);
18621 * }
18622 * });
18623 *
18624 * @name $.jstree.defaults.core.data
18625 */
18626 data : false,
18627 /**
18628 * configure the various strings used throughout the tree
18629 *
18630 * You can use an object where the key is the string you need to replace and the value is your replacement.
18631 * Another option is to specify a function which will be called with an argument of the needed string and should return the replacement.
18632 * If left as `false` no replacement is made.
18633 *
18634 * __Examples__
18635 *
18636 * $('#tree').jstree({
18637 * 'core' : {
18638 * 'strings' : {
18639 * 'Loading ...' : 'Please wait ...'
18640 * }
18641 * }
18642 * });
18643 *
18644 * @name $.jstree.defaults.core.strings
18645 */
18646 strings : false,
18647 /**
18648 * determines what happens when a user tries to modify the structure of the tree
18649 * If left as `false` all operations like create, rename, delete, move or copy are prevented.
18650 * You can set this to `true` to allow all interactions or use a function to have better control.
18651 *
18652 * __Examples__
18653 *
18654 * $('#tree').jstree({
18655 * 'core' : {
18656 * 'check_callback' : function (operation, node, node_parent, node_position, more) {
18657 * // operation can be 'create_node', 'rename_node', 'delete_node', 'move_node' or 'copy_node'
18658 * // in case of 'rename_node' node_position is filled with the new node name
18659 * return operation === 'rename_node' ? true : false;
18660 * }
18661 * }
18662 * });
18663 *
18664 * @name $.jstree.defaults.core.check_callback
18665 */
18666 check_callback : false,
18667 /**
18668 * a callback called with a single object parameter in the instance's scope when something goes wrong (operation prevented, ajax failed, etc)
18669 * @name $.jstree.defaults.core.error
18670 */
18671 error : $.noop,
18672 /**
18673 * the open / close animation duration in milliseconds - set this to `false` to disable the animation (default is `200`)
18674 * @name $.jstree.defaults.core.animation
18675 */
18676 animation : 200,
18677 /**
18678 * a boolean indicating if multiple nodes can be selected
18679 * @name $.jstree.defaults.core.multiple
18680 */
18681 multiple : true,
18682 /**
18683 * theme configuration object
18684 * @name $.jstree.defaults.core.themes
18685 */
18686 themes : {
18687 /**
18688 * the name of the theme to use (if left as `false` the default theme is used)
18689 * @name $.jstree.defaults.core.themes.name
18690 */
18691 name : false,
18692 /**
18693 * the URL of the theme's CSS file, leave this as `false` if you have manually included the theme CSS (recommended). You can set this to `true` too which will try to autoload the theme.
18694 * @name $.jstree.defaults.core.themes.url
18695 */
18696 url : false,
18697 /**
18698 * the location of all jstree themes - only used if `url` is set to `true`
18699 * @name $.jstree.defaults.core.themes.dir
18700 */
18701 dir : false,
18702 /**
18703 * a boolean indicating if connecting dots are shown
18704 * @name $.jstree.defaults.core.themes.dots
18705 */
18706 dots : true,
18707 /**
18708 * a boolean indicating if node icons are shown
18709 * @name $.jstree.defaults.core.themes.icons
18710 */
18711 icons : true,
18712 /**
18713 * a boolean indicating if the tree background is striped
18714 * @name $.jstree.defaults.core.themes.stripes
18715 */
18716 stripes : false,
18717 /**
18718 * a string (or boolean `false`) specifying the theme variant to use (if the theme supports variants)
18719 * @name $.jstree.defaults.core.themes.variant
18720 */
18721 variant : false,
18722 /**
18723 * a boolean specifying if a reponsive version of the theme should kick in on smaller screens (if the theme supports it). Defaults to `false`.
18724 * @name $.jstree.defaults.core.themes.responsive
18725 */
18726 responsive : false
18727 },
18728 /**
18729 * if left as `true` all parents of all selected nodes will be opened once the tree loads (so that all selected nodes are visible to the user)
18730 * @name $.jstree.defaults.core.expand_selected_onload
18731 */
18732 expand_selected_onload : true,
18733 /**
18734 * if left as `true` web workers will be used to parse incoming JSON data where possible, so that the UI will not be blocked by large requests. Workers are however about 30% slower. Defaults to `true`
18735 * @name $.jstree.defaults.core.worker
18736 */
18737 worker : true,
18738 /**
18739 * Force node text to plain text (and escape HTML). Defaults to `false`
18740 * @name $.jstree.defaults.core.force_text
18741 */
18742 force_text : false,
18743 /**
18744 * Should the node should be toggled if the text is double clicked . Defaults to `true`
18745 * @name $.jstree.defaults.core.dblclick_toggle
18746 */
18747 dblclick_toggle : true
18748 };
18749 $.jstree.core.prototype = {
18750 /**
18751 * used to decorate an instance with a plugin. Used internally.
18752 * @private
18753 * @name plugin(deco [, opts])
18754 * @param {String} deco the plugin to decorate with
18755 * @param {Object} opts options for the plugin
18756 * @return {jsTree}
18757 */
18758 plugin : function (deco, opts) {
18759 var Child = $.jstree.plugins[deco];
18760 if(Child) {
18761 this._data[deco] = {};
18762 Child.prototype = this;
18763 return new Child(opts, this);
18764 }
18765 return this;
18766 },
18767 /**
18768 * used to decorate an instance with a plugin. Used internally.
18769 * @private
18770 * @name init(el, optons)
18771 * @param {DOMElement|jQuery|String} el the element we are transforming
18772 * @param {Object} options options for this instance
18773 * @trigger init.jstree, loading.jstree, loaded.jstree, ready.jstree, changed.jstree
18774 */
18775 init : function (el, options) {
18776 this._model = {
18777 data : {
18778 '#' : {
18779 id : '#',
18780 parent : null,
18781 parents : [],
18782 children : [],
18783 children_d : [],
18784 state : { loaded : false }
18785 }
18786 },
18787 changed : [],
18788 force_full_redraw : false,
18789 redraw_timeout : false,
18790 default_state : {
18791 loaded : true,
18792 opened : false,
18793 selected : false,
18794 disabled : false
18795 }
18796 };
18797
18798 this.element = $(el).addClass('jstree jstree-' + this._id);
18799 this.settings = options;
18800
18801 this._data.core.ready = false;
18802 this._data.core.loaded = false;
18803 this._data.core.rtl = (this.element.css("direction") === "rtl");
18804 this.element[this._data.core.rtl ? 'addClass' : 'removeClass']("jstree-rtl");
18805 this.element.attr('role','tree');
18806 if(this.settings.core.multiple) {
18807 this.element.attr('aria-multiselectable', true);
18808 }
18809 if(!this.element.attr('tabindex')) {
18810 this.element.attr('tabindex','0');
18811 }
18812
18813 this.bind();
18814 /**
18815 * triggered after all events are bound
18816 * @event
18817 * @name init.jstree
18818 */
18819 this.trigger("init");
18820
18821 this._data.core.original_container_html = this.element.find(" > ul > li").clone(true);
18822 this._data.core.original_container_html
18823 .find("li").addBack()
18824 .contents().filter(function() {
18825 return this.nodeType === 3 && (!this.nodeValue || /^\s+$/.test(this.nodeValue));
18826 })
18827 .remove();
18828 this.element.html("<"+"ul class='jstree-container-ul jstree-children' role='group'><"+"li id='j"+this._id+"_loading' class='jstree-initial-node jstree-loading jstree-leaf jstree-last' role='tree-item'><i class='jstree-icon jstree-ocl'></i><"+"a class='jstree-anchor' href='#'><i class='jstree-icon jstree-themeicon-hidden'></i>" + this.get_string("Loading ...") + "</a></li></ul>");
18829 this.element.attr('aria-activedescendant','j' + this._id + '_loading');
18830 this._data.core.li_height = this.get_container_ul().children("li").first().height() || 24;
18831 /**
18832 * triggered after the loading text is shown and before loading starts
18833 * @event
18834 * @name loading.jstree
18835 */
18836 this.trigger("loading");
18837 this.load_node('#');
18838 },
18839 /**
18840 * destroy an instance
18841 * @name destroy()
18842 * @param {Boolean} keep_html if not set to `true` the container will be emptied, otherwise the current DOM elements will be kept intact
18843 */
18844 destroy : function (keep_html) {
18845 if(this._wrk) {
18846 try {
18847 window.URL.revokeObjectURL(this._wrk);
18848 this._wrk = null;
18849 }
18850 catch (ignore) { }
18851 }
18852 if(!keep_html) { this.element.empty(); }
18853 this.teardown();
18854 },
18855 /**
18856 * part of the destroying of an instance. Used internally.
18857 * @private
18858 * @name teardown()
18859 */
18860 teardown : function () {
18861 this.unbind();
18862 this.element
18863 .removeClass('jstree')
18864 .removeData('jstree')
18865 .find("[class^='jstree']")
18866 .addBack()
18867 .attr("class", function () { return this.className.replace(/jstree[^ ]*|$/ig,''); });
18868 this.element = null;
18869 },
18870 /**
18871 * bind all events. Used internally.
18872 * @private
18873 * @name bind()
18874 */
18875 bind : function () {
18876 var word = '',
18877 tout = null,
18878 was_click = 0;
18879 this.element
18880 .on("dblclick.jstree", function () {
18881 if(document.selection && document.selection.empty) {
18882 document.selection.empty();
18883 }
18884 else {
18885 if(window.getSelection) {
18886 var sel = window.getSelection();
18887 try {
18888 sel.removeAllRanges();
18889 sel.collapse();
18890 } catch (ignore) { }
18891 }
18892 }
18893 })
18894 .on("mousedown.jstree", $.proxy(function (e) {
18895 if(e.target === this.element[0]) {
18896 e.preventDefault(); // prevent losing focus when clicking scroll arrows (FF, Chrome)
18897 was_click = +(new Date()); // ie does not allow to prevent losing focus
18898 }
18899 }, this))
18900 .on("mousedown.jstree", ".jstree-ocl", function (e) {
18901 e.preventDefault(); // prevent any node inside from losing focus when clicking the open/close icon
18902 })
18903 .on("click.jstree", ".jstree-ocl", $.proxy(function (e) {
18904 this.toggle_node(e.target);
18905 }, this))
18906 .on("dblclick.jstree", ".jstree-anchor", $.proxy(function (e) {
18907 if(this.settings.core.dblclick_toggle) {
18908 this.toggle_node(e.target);
18909 }
18910 }, this))
18911 .on("click.jstree", ".jstree-anchor", $.proxy(function (e) {
18912 e.preventDefault();
18913 if(e.currentTarget !== document.activeElement) { $(e.currentTarget).focus(); }
18914 this.activate_node(e.currentTarget, e);
18915 }, this))
18916 .on('keydown.jstree', '.jstree-anchor', $.proxy(function (e) {
18917 if(e.target.tagName === "INPUT") { return true; }
18918 var o = null;
18919 if(this._data.core.rtl) {
18920 if(e.which === 37) { e.which = 39; }
18921 else if(e.which === 39) { e.which = 37; }
18922 }
18923 switch(e.which) {
18924 case 32: // aria defines space only with Ctrl
18925 if(e.ctrlKey) {
18926 e.type = "click";
18927 $(e.currentTarget).trigger(e);
18928 }
18929 break;
18930 case 13: // enter
18931 e.type = "click";
18932 $(e.currentTarget).trigger(e);
18933 break;
18934 case 37: // right
18935 e.preventDefault();
18936 if(this.is_open(e.currentTarget)) {
18937 this.close_node(e.currentTarget);
18938 }
18939 else {
18940 o = this.get_parent(e.currentTarget);
18941 if(o && o.id !== '#') { this.get_node(o, true).children('.jstree-anchor').focus(); }
18942 }
18943 break;
18944 case 38: // up
18945 e.preventDefault();
18946 o = this.get_prev_dom(e.currentTarget);
18947 if(o && o.length) { o.children('.jstree-anchor').focus(); }
18948 break;
18949 case 39: // left
18950 e.preventDefault();
18951 if(this.is_closed(e.currentTarget)) {
18952 this.open_node(e.currentTarget, function (o) { this.get_node(o, true).children('.jstree-anchor').focus(); });
18953 }
18954 else if (this.is_open(e.currentTarget)) {
18955 o = this.get_node(e.currentTarget, true).children('.jstree-children')[0];
18956 if(o) { $(this._firstChild(o)).children('.jstree-anchor').focus(); }
18957 }
18958 break;
18959 case 40: // down
18960 e.preventDefault();
18961 o = this.get_next_dom(e.currentTarget);
18962 if(o && o.length) { o.children('.jstree-anchor').focus(); }
18963 break;
18964 case 106: // aria defines * on numpad as open_all - not very common
18965 this.open_all();
18966 break;
18967 case 36: // home
18968 e.preventDefault();
18969 o = this._firstChild(this.get_container_ul()[0]);
18970 if(o) { $(o).children('.jstree-anchor').filter(':visible').focus(); }
18971 break;
18972 case 35: // end
18973 e.preventDefault();
18974 this.element.find('.jstree-anchor').filter(':visible').last().focus();
18975 break;
18976 /*
18977 // delete
18978 case 46:
18979 e.preventDefault();
18980 o = this.get_node(e.currentTarget);
18981 if(o && o.id && o.id !== '#') {
18982 o = this.is_selected(o) ? this.get_selected() : o;
18983 this.delete_node(o);
18984 }
18985 break;
18986 // f2
18987 case 113:
18988 e.preventDefault();
18989 o = this.get_node(e.currentTarget);
18990 if(o && o.id && o.id !== '#') {
18991 // this.edit(o);
18992 }
18993 break;
18994 default:
18995 // console.log(e.which);
18996 break;
18997 */
18998 }
18999 }, this))
19000 .on("load_node.jstree", $.proxy(function (e, data) {
19001 if(data.status) {
19002 if(data.node.id === '#' && !this._data.core.loaded) {
19003 this._data.core.loaded = true;
19004 if(this._firstChild(this.get_container_ul()[0])) {
19005 this.element.attr('aria-activedescendant',this._firstChild(this.get_container_ul()[0]).id);
19006 }
19007 /**
19008 * triggered after the root node is loaded for the first time
19009 * @event
19010 * @name loaded.jstree
19011 */
19012 this.trigger("loaded");
19013 }
19014 if(!this._data.core.ready) {
19015 setTimeout($.proxy(function() {
19016 if(!this.get_container_ul().find('.jstree-loading').length) {
19017 this._data.core.ready = true;
19018 if(this._data.core.selected.length) {
19019 if(this.settings.core.expand_selected_onload) {
19020 var tmp = [], i, j;
19021 for(i = 0, j = this._data.core.selected.length; i < j; i++) {
19022 tmp = tmp.concat(this._model.data[this._data.core.selected[i]].parents);
19023 }
19024 tmp = $.vakata.array_unique(tmp);
19025 for(i = 0, j = tmp.length; i < j; i++) {
19026 this.open_node(tmp[i], false, 0);
19027 }
19028 }
19029 this.trigger('changed', { 'action' : 'ready', 'selected' : this._data.core.selected });
19030 }
19031 /**
19032 * triggered after all nodes are finished loading
19033 * @event
19034 * @name ready.jstree
19035 */
19036 this.trigger("ready");
19037 }
19038 }, this), 0);
19039 }
19040 }
19041 }, this))
19042 // quick searching when the tree is focused
19043 .on('keypress.jstree', $.proxy(function (e) {
19044 if(e.target.tagName === "INPUT") { return true; }
19045 if(tout) { clearTimeout(tout); }
19046 tout = setTimeout(function () {
19047 word = '';
19048 }, 500);
19049
19050 var chr = String.fromCharCode(e.which).toLowerCase(),
19051 col = this.element.find('.jstree-anchor').filter(':visible'),
19052 ind = col.index(document.activeElement) || 0,
19053 end = false;
19054 word += chr;
19055
19056 // match for whole word from current node down (including the current node)
19057 if(word.length > 1) {
19058 col.slice(ind).each($.proxy(function (i, v) {
19059 if($(v).text().toLowerCase().indexOf(word) === 0) {
19060 $(v).focus();
19061 end = true;
19062 return false;
19063 }
19064 }, this));
19065 if(end) { return; }
19066
19067 // match for whole word from the beginning of the tree
19068 col.slice(0, ind).each($.proxy(function (i, v) {
19069 if($(v).text().toLowerCase().indexOf(word) === 0) {
19070 $(v).focus();
19071 end = true;
19072 return false;
19073 }
19074 }, this));
19075 if(end) { return; }
19076 }
19077 // list nodes that start with that letter (only if word consists of a single char)
19078 if(new RegExp('^' + chr + '+$').test(word)) {
19079 // search for the next node starting with that letter
19080 col.slice(ind + 1).each($.proxy(function (i, v) {
19081 if($(v).text().toLowerCase().charAt(0) === chr) {
19082 $(v).focus();
19083 end = true;
19084 return false;
19085 }
19086 }, this));
19087 if(end) { return; }
19088
19089 // search from the beginning
19090 col.slice(0, ind + 1).each($.proxy(function (i, v) {
19091 if($(v).text().toLowerCase().charAt(0) === chr) {
19092 $(v).focus();
19093 end = true;
19094 return false;
19095 }
19096 }, this));
19097 if(end) { return; }
19098 }
19099 }, this))
19100 // THEME RELATED
19101 .on("init.jstree", $.proxy(function () {
19102 var s = this.settings.core.themes;
19103 this._data.core.themes.dots = s.dots;
19104 this._data.core.themes.stripes = s.stripes;
19105 this._data.core.themes.icons = s.icons;
19106 this.set_theme(s.name || "default", s.url);
19107 this.set_theme_variant(s.variant);
19108 }, this))
19109 .on("loading.jstree", $.proxy(function () {
19110 this[ this._data.core.themes.dots ? "show_dots" : "hide_dots" ]();
19111 this[ this._data.core.themes.icons ? "show_icons" : "hide_icons" ]();
19112 this[ this._data.core.themes.stripes ? "show_stripes" : "hide_stripes" ]();
19113 }, this))
19114 .on('blur.jstree', '.jstree-anchor', $.proxy(function (e) {
19115 this._data.core.focused = null;
19116 $(e.currentTarget).filter('.jstree-hovered').mouseleave();
19117 this.element.attr('tabindex', '0');
19118 }, this))
19119 .on('focus.jstree', '.jstree-anchor', $.proxy(function (e) {
19120 var tmp = this.get_node(e.currentTarget);
19121 if(tmp && tmp.id) {
19122 this._data.core.focused = tmp.id;
19123 }
19124 this.element.find('.jstree-hovered').not(e.currentTarget).mouseleave();
19125 $(e.currentTarget).mouseenter();
19126 this.element.attr('tabindex', '-1');
19127 }, this))
19128 .on('focus.jstree', $.proxy(function () {
19129 if(+(new Date()) - was_click > 500 && !this._data.core.focused) {
19130 was_click = 0;
19131 this.get_node(this.element.attr('aria-activedescendant'), true).find('> .jstree-anchor').focus();
19132 }
19133 }, this))
19134 .on('mouseenter.jstree', '.jstree-anchor', $.proxy(function (e) {
19135 this.hover_node(e.currentTarget);
19136 }, this))
19137 .on('mouseleave.jstree', '.jstree-anchor', $.proxy(function (e) {
19138 this.dehover_node(e.currentTarget);
19139 }, this));
19140 },
19141 /**
19142 * part of the destroying of an instance. Used internally.
19143 * @private
19144 * @name unbind()
19145 */
19146 unbind : function () {
19147 this.element.off('.jstree');
19148 $(document).off('.jstree-' + this._id);
19149 },
19150 /**
19151 * trigger an event. Used internally.
19152 * @private
19153 * @name trigger(ev [, data])
19154 * @param {String} ev the name of the event to trigger
19155 * @param {Object} data additional data to pass with the event
19156 */
19157 trigger : function (ev, data) {
19158 if(!data) {
19159 data = {};
19160 }
19161 data.instance = this;
19162 this.element.triggerHandler(ev.replace('.jstree','') + '.jstree', data);
19163 },
19164 /**
19165 * returns the jQuery extended instance container
19166 * @name get_container()
19167 * @return {jQuery}
19168 */
19169 get_container : function () {
19170 return this.element;
19171 },
19172 /**
19173 * returns the jQuery extended main UL node inside the instance container. Used internally.
19174 * @private
19175 * @name get_container_ul()
19176 * @return {jQuery}
19177 */
19178 get_container_ul : function () {
19179 return this.element.children(".jstree-children").first();
19180 },
19181 /**
19182 * gets string replacements (localization). Used internally.
19183 * @private
19184 * @name get_string(key)
19185 * @param {String} key
19186 * @return {String}
19187 */
19188 get_string : function (key) {
19189 var a = this.settings.core.strings;
19190 if($.isFunction(a)) { return a.call(this, key); }
19191 if(a && a[key]) { return a[key]; }
19192 return key;
19193 },
19194 /**
19195 * gets the first child of a DOM node. Used internally.
19196 * @private
19197 * @name _firstChild(dom)
19198 * @param {DOMElement} dom
19199 * @return {DOMElement}
19200 */
19201 _firstChild : function (dom) {
19202 dom = dom ? dom.firstChild : null;
19203 while(dom !== null && dom.nodeType !== 1) {
19204 dom = dom.nextSibling;
19205 }
19206 return dom;
19207 },
19208 /**
19209 * gets the next sibling of a DOM node. Used internally.
19210 * @private
19211 * @name _nextSibling(dom)
19212 * @param {DOMElement} dom
19213 * @return {DOMElement}
19214 */
19215 _nextSibling : function (dom) {
19216 dom = dom ? dom.nextSibling : null;
19217 while(dom !== null && dom.nodeType !== 1) {
19218 dom = dom.nextSibling;
19219 }
19220 return dom;
19221 },
19222 /**
19223 * gets the previous sibling of a DOM node. Used internally.
19224 * @private
19225 * @name _previousSibling(dom)
19226 * @param {DOMElement} dom
19227 * @return {DOMElement}
19228 */
19229 _previousSibling : function (dom) {
19230 dom = dom ? dom.previousSibling : null;
19231 while(dom !== null && dom.nodeType !== 1) {
19232 dom = dom.previousSibling;
19233 }
19234 return dom;
19235 },
19236 /**
19237 * get the JSON representation of a node (or the actual jQuery extended DOM node) by using any input (child DOM element, ID string, selector, etc)
19238 * @name get_node(obj [, as_dom])
19239 * @param {mixed} obj
19240 * @param {Boolean} as_dom
19241 * @return {Object|jQuery}
19242 */
19243 get_node : function (obj, as_dom) {
19244 if(obj && obj.id) {
19245 obj = obj.id;
19246 }
19247 var dom;
19248 try {
19249 if(this._model.data[obj]) {
19250 obj = this._model.data[obj];
19251 }
19252 else if(typeof obj === "string" && this._model.data[obj.replace(/^#/, '')]) {
19253 obj = this._model.data[obj.replace(/^#/, '')];
19254 }
19255 else if(typeof obj === "string" && (dom = $('#' + obj.replace($.jstree.idregex,'\\$&'), this.element)).length && this._model.data[dom.closest('.jstree-node').attr('id')]) {
19256 obj = this._model.data[dom.closest('.jstree-node').attr('id')];
19257 }
19258 else if((dom = $(obj, this.element)).length && this._model.data[dom.closest('.jstree-node').attr('id')]) {
19259 obj = this._model.data[dom.closest('.jstree-node').attr('id')];
19260 }
19261 else if((dom = $(obj, this.element)).length && dom.hasClass('jstree')) {
19262 obj = this._model.data['#'];
19263 }
19264 else {
19265 return false;
19266 }
19267
19268 if(as_dom) {
19269 obj = obj.id === '#' ? this.element : $('#' + obj.id.replace($.jstree.idregex,'\\$&'), this.element);
19270 }
19271 return obj;
19272 } catch (ex) { return false; }
19273 },
19274 /**
19275 * get the path to a node, either consisting of node texts, or of node IDs, optionally glued together (otherwise an array)
19276 * @name get_path(obj [, glue, ids])
19277 * @param {mixed} obj the node
19278 * @param {String} glue if you want the path as a string - pass the glue here (for example '/'), if a falsy value is supplied here, an array is returned
19279 * @param {Boolean} ids if set to true build the path using ID, otherwise node text is used
19280 * @return {mixed}
19281 */
19282 get_path : function (obj, glue, ids) {
19283 obj = obj.parents ? obj : this.get_node(obj);
19284 if(!obj || obj.id === '#' || !obj.parents) {
19285 return false;
19286 }
19287 var i, j, p = [];
19288 p.push(ids ? obj.id : obj.text);
19289 for(i = 0, j = obj.parents.length; i < j; i++) {
19290 p.push(ids ? obj.parents[i] : this.get_text(obj.parents[i]));
19291 }
19292 p = p.reverse().slice(1);
19293 return glue ? p.join(glue) : p;
19294 },
19295 /**
19296 * get the next visible node that is below the `obj` node. If `strict` is set to `true` only sibling nodes are returned.
19297 * @name get_next_dom(obj [, strict])
19298 * @param {mixed} obj
19299 * @param {Boolean} strict
19300 * @return {jQuery}
19301 */
19302 get_next_dom : function (obj, strict) {
19303 var tmp;
19304 obj = this.get_node(obj, true);
19305 if(obj[0] === this.element[0]) {
19306 tmp = this._firstChild(this.get_container_ul()[0]);
19307 while (tmp && tmp.offsetHeight === 0) {
19308 tmp = this._nextSibling(tmp);
19309 }
19310 return tmp ? $(tmp) : false;
19311 }
19312 if(!obj || !obj.length) {
19313 return false;
19314 }
19315 if(strict) {
19316 tmp = obj[0];
19317 do {
19318 tmp = this._nextSibling(tmp);
19319 } while (tmp && tmp.offsetHeight === 0);
19320 return tmp ? $(tmp) : false;
19321 }
19322 if(obj.hasClass("jstree-open")) {
19323 tmp = this._firstChild(obj.children('.jstree-children')[0]);
19324 while (tmp && tmp.offsetHeight === 0) {
19325 tmp = this._nextSibling(tmp);
19326 }
19327 if(tmp !== null) {
19328 return $(tmp);
19329 }
19330 }
19331 tmp = obj[0];
19332 do {
19333 tmp = this._nextSibling(tmp);
19334 } while (tmp && tmp.offsetHeight === 0);
19335 if(tmp !== null) {
19336 return $(tmp);
19337 }
19338 return obj.parentsUntil(".jstree",".jstree-node").next(".jstree-node:visible").first();
19339 },
19340 /**
19341 * get the previous visible node that is above the `obj` node. If `strict` is set to `true` only sibling nodes are returned.
19342 * @name get_prev_dom(obj [, strict])
19343 * @param {mixed} obj
19344 * @param {Boolean} strict
19345 * @return {jQuery}
19346 */
19347 get_prev_dom : function (obj, strict) {
19348 var tmp;
19349 obj = this.get_node(obj, true);
19350 if(obj[0] === this.element[0]) {
19351 tmp = this.get_container_ul()[0].lastChild;
19352 while (tmp && tmp.offsetHeight === 0) {
19353 tmp = this._previousSibling(tmp);
19354 }
19355 return tmp ? $(tmp) : false;
19356 }
19357 if(!obj || !obj.length) {
19358 return false;
19359 }
19360 if(strict) {
19361 tmp = obj[0];
19362 do {
19363 tmp = this._previousSibling(tmp);
19364 } while (tmp && tmp.offsetHeight === 0);
19365 return tmp ? $(tmp) : false;
19366 }
19367 tmp = obj[0];
19368 do {
19369 tmp = this._previousSibling(tmp);
19370 } while (tmp && tmp.offsetHeight === 0);
19371 if(tmp !== null) {
19372 obj = $(tmp);
19373 while(obj.hasClass("jstree-open")) {
19374 obj = obj.children(".jstree-children").first().children(".jstree-node:visible:last");
19375 }
19376 return obj;
19377 }
19378 tmp = obj[0].parentNode.parentNode;
19379 return tmp && tmp.className && tmp.className.indexOf('jstree-node') !== -1 ? $(tmp) : false;
19380 },
19381 /**
19382 * get the parent ID of a node
19383 * @name get_parent(obj)
19384 * @param {mixed} obj
19385 * @return {String}
19386 */
19387 get_parent : function (obj) {
19388 obj = this.get_node(obj);
19389 if(!obj || obj.id === '#') {
19390 return false;
19391 }
19392 return obj.parent;
19393 },
19394 /**
19395 * get a jQuery collection of all the children of a node (node must be rendered)
19396 * @name get_children_dom(obj)
19397 * @param {mixed} obj
19398 * @return {jQuery}
19399 */
19400 get_children_dom : function (obj) {
19401 obj = this.get_node(obj, true);
19402 if(obj[0] === this.element[0]) {
19403 return this.get_container_ul().children(".jstree-node");
19404 }
19405 if(!obj || !obj.length) {
19406 return false;
19407 }
19408 return obj.children(".jstree-children").children(".jstree-node");
19409 },
19410 /**
19411 * checks if a node has children
19412 * @name is_parent(obj)
19413 * @param {mixed} obj
19414 * @return {Boolean}
19415 */
19416 is_parent : function (obj) {
19417 obj = this.get_node(obj);
19418 return obj && (obj.state.loaded === false || obj.children.length > 0);
19419 },
19420 /**
19421 * checks if a node is loaded (its children are available)
19422 * @name is_loaded(obj)
19423 * @param {mixed} obj
19424 * @return {Boolean}
19425 */
19426 is_loaded : function (obj) {
19427 obj = this.get_node(obj);
19428 return obj && obj.state.loaded;
19429 },
19430 /**
19431 * check if a node is currently loading (fetching children)
19432 * @name is_loading(obj)
19433 * @param {mixed} obj
19434 * @return {Boolean}
19435 */
19436 is_loading : function (obj) {
19437 obj = this.get_node(obj);
19438 return obj && obj.state && obj.state.loading;
19439 },
19440 /**
19441 * check if a node is opened
19442 * @name is_open(obj)
19443 * @param {mixed} obj
19444 * @return {Boolean}
19445 */
19446 is_open : function (obj) {
19447 obj = this.get_node(obj);
19448 return obj && obj.state.opened;
19449 },
19450 /**
19451 * check if a node is in a closed state
19452 * @name is_closed(obj)
19453 * @param {mixed} obj
19454 * @return {Boolean}
19455 */
19456 is_closed : function (obj) {
19457 obj = this.get_node(obj);
19458 return obj && this.is_parent(obj) && !obj.state.opened;
19459 },
19460 /**
19461 * check if a node has no children
19462 * @name is_leaf(obj)
19463 * @param {mixed} obj
19464 * @return {Boolean}
19465 */
19466 is_leaf : function (obj) {
19467 return !this.is_parent(obj);
19468 },
19469 /**
19470 * loads a node (fetches its children using the `core.data` setting). Multiple nodes can be passed to by using an array.
19471 * @name load_node(obj [, callback])
19472 * @param {mixed} obj
19473 * @param {function} callback a function to be executed once loading is complete, the function is executed in the instance's scope and receives two arguments - the node and a boolean status
19474 * @return {Boolean}
19475 * @trigger load_node.jstree
19476 */
19477 load_node : function (obj, callback) {
19478 var k, l, i, j, c;
19479 if($.isArray(obj)) {
19480 this._load_nodes(obj.slice(), callback);
19481 return true;
19482 }
19483 obj = this.get_node(obj);
19484 if(!obj) {
19485 if(callback) { callback.call(this, obj, false); }
19486 return false;
19487 }
19488 // if(obj.state.loading) { } // the node is already loading - just wait for it to load and invoke callback? but if called implicitly it should be loaded again?
19489 if(obj.state.loaded) {
19490 obj.state.loaded = false;
19491 for(k = 0, l = obj.children_d.length; k < l; k++) {
19492 for(i = 0, j = obj.parents.length; i < j; i++) {
19493 this._model.data[obj.parents[i]].children_d = $.vakata.array_remove_item(this._model.data[obj.parents[i]].children_d, obj.children_d[k]);
19494 }
19495 if(this._model.data[obj.children_d[k]].state.selected) {
19496 c = true;
19497 this._data.core.selected = $.vakata.array_remove_item(this._data.core.selected, obj.children_d[k]);
19498 }
19499 delete this._model.data[obj.children_d[k]];
19500 }
19501 obj.children = [];
19502 obj.children_d = [];
19503 if(c) {
19504 this.trigger('changed', { 'action' : 'load_node', 'node' : obj, 'selected' : this._data.core.selected });
19505 }
19506 }
19507 obj.state.loading = true;
19508 this.get_node(obj, true).addClass("jstree-loading").attr('aria-busy',true);
19509 this._load_node(obj, $.proxy(function (status) {
19510 obj = this._model.data[obj.id];
19511 obj.state.loading = false;
19512 obj.state.loaded = status;
19513 var dom = this.get_node(obj, true);
19514 if(obj.state.loaded && !obj.children.length && dom && dom.length && !dom.hasClass('jstree-leaf')) {
19515 dom.removeClass('jstree-closed jstree-open').addClass('jstree-leaf');
19516 }
19517 dom.removeClass("jstree-loading").attr('aria-busy',false);
19518 /**
19519 * triggered after a node is loaded
19520 * @event
19521 * @name load_node.jstree
19522 * @param {Object} node the node that was loading
19523 * @param {Boolean} status was the node loaded successfully
19524 */
19525 this.trigger('load_node', { "node" : obj, "status" : status });
19526 if(callback) {
19527 callback.call(this, obj, status);
19528 }
19529 }, this));
19530 return true;
19531 },
19532 /**
19533 * load an array of nodes (will also load unavailable nodes as soon as the appear in the structure). Used internally.
19534 * @private
19535 * @name _load_nodes(nodes [, callback])
19536 * @param {array} nodes
19537 * @param {function} callback a function to be executed once loading is complete, the function is executed in the instance's scope and receives one argument - the array passed to _load_nodes
19538 */
19539 _load_nodes : function (nodes, callback, is_callback) {
19540 var r = true,
19541 c = function () { this._load_nodes(nodes, callback, true); },
19542 m = this._model.data, i, j;
19543 for(i = 0, j = nodes.length; i < j; i++) {
19544 if(m[nodes[i]] && (!m[nodes[i]].state.loaded || !is_callback)) {
19545 if(!this.is_loading(nodes[i])) {
19546 this.load_node(nodes[i], c);
19547 }
19548 r = false;
19549 }
19550 }
19551 if(r) {
19552 if(callback && !callback.done) {
19553 callback.call(this, nodes);
19554 callback.done = true;
19555 }
19556 }
19557 },
19558 /**
19559 * loads all unloaded nodes
19560 * @name load_all([obj, callback])
19561 * @param {mixed} obj the node to load recursively, omit to load all nodes in the tree
19562 * @param {function} callback a function to be executed once loading all the nodes is complete,
19563 * @trigger load_all.jstree
19564 */
19565 load_all : function (obj, callback) {
19566 if(!obj) { obj = '#'; }
19567 obj = this.get_node(obj);
19568 if(!obj) { return false; }
19569 var to_load = [],
19570 m = this._model.data,
19571 c = m[obj.id].children_d,
19572 i, j;
19573 if(obj.state && !obj.state.loaded) {
19574 to_load.push(obj.id);
19575 }
19576 for(i = 0, j = c.length; i < j; i++) {
19577 if(m[c[i]] && m[c[i]].state && !m[c[i]].state.loaded) {
19578 to_load.push(c[i]);
19579 }
19580 }
19581 if(to_load.length) {
19582 this._load_nodes(to_load, function () {
19583 this.load_all(obj, callback);
19584 });
19585 }
19586 else {
19587 /**
19588 * triggered after a load_all call completes
19589 * @event
19590 * @name load_all.jstree
19591 * @param {Object} node the recursively loaded node
19592 */
19593 if(callback) { callback.call(this, obj); }
19594 this.trigger('load_all', { "node" : obj });
19595 }
19596 },
19597 /**
19598 * handles the actual loading of a node. Used only internally.
19599 * @private
19600 * @name _load_node(obj [, callback])
19601 * @param {mixed} obj
19602 * @param {function} callback a function to be executed once loading is complete, the function is executed in the instance's scope and receives one argument - a boolean status
19603 * @return {Boolean}
19604 */
19605 _load_node : function (obj, callback) {
19606 var s = this.settings.core.data, t;
19607 // use original HTML
19608 if(!s) {
19609 if(obj.id === '#') {
19610 return this._append_html_data(obj, this._data.core.original_container_html.clone(true), function (status) {
19611 callback.call(this, status);
19612 });
19613 }
19614 else {
19615 return callback.call(this, false);
19616 }
19617 // return callback.call(this, obj.id === '#' ? this._append_html_data(obj, this._data.core.original_container_html.clone(true)) : false);
19618 }
19619 if($.isFunction(s)) {
19620 return s.call(this, obj, $.proxy(function (d) {
19621 if(d === false) {
19622 callback.call(this, false);
19623 }
19624 this[typeof d === 'string' ? '_append_html_data' : '_append_json_data'](obj, typeof d === 'string' ? $(d) : d, function (status) {
19625 callback.call(this, status);
19626 });
19627 // return d === false ? callback.call(this, false) : callback.call(this, this[typeof d === 'string' ? '_append_html_data' : '_append_json_data'](obj, typeof d === 'string' ? $(d) : d));
19628 }, this));
19629 }
19630 if(typeof s === 'object') {
19631 if(s.url) {
19632 s = $.extend(true, {}, s);
19633 if($.isFunction(s.url)) {
19634 s.url = s.url.call(this, obj);
19635 }
19636 if($.isFunction(s.data)) {
19637 s.data = s.data.call(this, obj);
19638 }
19639 return $.ajax(s)
19640 .done($.proxy(function (d,t,x) {
19641 var type = x.getResponseHeader('Content-Type');
19642 if(type.indexOf('json') !== -1 || typeof d === "object") {
19643 return this._append_json_data(obj, d, function (status) { callback.call(this, status); });
19644 //return callback.call(this, this._append_json_data(obj, d));
19645 }
19646 if(type.indexOf('html') !== -1 || typeof d === "string") {
19647 return this._append_html_data(obj, $(d), function (status) { callback.call(this, status); });
19648 // return callback.call(this, this._append_html_data(obj, $(d)));
19649 }
19650 this._data.core.last_error = { 'error' : 'ajax', 'plugin' : 'core', 'id' : 'core_04', 'reason' : 'Could not load node', 'data' : JSON.stringify({ 'id' : obj.id, 'xhr' : x }) };
19651 this.settings.core.error.call(this, this._data.core.last_error);
19652 return callback.call(this, false);
19653 }, this))
19654 .fail($.proxy(function (f) {
19655 callback.call(this, false);
19656 this._data.core.last_error = { 'error' : 'ajax', 'plugin' : 'core', 'id' : 'core_04', 'reason' : 'Could not load node', 'data' : JSON.stringify({ 'id' : obj.id, 'xhr' : f }) };
19657 this.settings.core.error.call(this, this._data.core.last_error);
19658 }, this));
19659 }
19660 t = ($.isArray(s) || $.isPlainObject(s)) ? JSON.parse(JSON.stringify(s)) : s;
19661 if(obj.id === '#') {
19662 return this._append_json_data(obj, t, function (status) {
19663 callback.call(this, status);
19664 });
19665 }
19666 else {
19667 this._data.core.last_error = { 'error' : 'nodata', 'plugin' : 'core', 'id' : 'core_05', 'reason' : 'Could not load node', 'data' : JSON.stringify({ 'id' : obj.id }) };
19668 this.settings.core.error.call(this, this._data.core.last_error);
19669 return callback.call(this, false);
19670 }
19671 //return callback.call(this, (obj.id === "#" ? this._append_json_data(obj, t) : false) );
19672 }
19673 if(typeof s === 'string') {
19674 if(obj.id === '#') {
19675 return this._append_html_data(obj, $(s), function (status) {
19676 callback.call(this, status);
19677 });
19678 }
19679 else {
19680 this._data.core.last_error = { 'error' : 'nodata', 'plugin' : 'core', 'id' : 'core_06', 'reason' : 'Could not load node', 'data' : JSON.stringify({ 'id' : obj.id }) };
19681 this.settings.core.error.call(this, this._data.core.last_error);
19682 return callback.call(this, false);
19683 }
19684 //return callback.call(this, (obj.id === "#" ? this._append_html_data(obj, $(s)) : false) );
19685 }
19686 return callback.call(this, false);
19687 },
19688 /**
19689 * adds a node to the list of nodes to redraw. Used only internally.
19690 * @private
19691 * @name _node_changed(obj [, callback])
19692 * @param {mixed} obj
19693 */
19694 _node_changed : function (obj) {
19695 obj = this.get_node(obj);
19696 if(obj) {
19697 this._model.changed.push(obj.id);
19698 }
19699 },
19700 /**
19701 * appends HTML content to the tree. Used internally.
19702 * @private
19703 * @name _append_html_data(obj, data)
19704 * @param {mixed} obj the node to append to
19705 * @param {String} data the HTML string to parse and append
19706 * @trigger model.jstree, changed.jstree
19707 */
19708 _append_html_data : function (dom, data, cb) {
19709 dom = this.get_node(dom);
19710 dom.children = [];
19711 dom.children_d = [];
19712 var dat = data.is('ul') ? data.children() : data,
19713 par = dom.id,
19714 chd = [],
19715 dpc = [],
19716 m = this._model.data,
19717 p = m[par],
19718 s = this._data.core.selected.length,
19719 tmp, i, j;
19720 dat.each($.proxy(function (i, v) {
19721 tmp = this._parse_model_from_html($(v), par, p.parents.concat());
19722 if(tmp) {
19723 chd.push(tmp);
19724 dpc.push(tmp);
19725 if(m[tmp].children_d.length) {
19726 dpc = dpc.concat(m[tmp].children_d);
19727 }
19728 }
19729 }, this));
19730 p.children = chd;
19731 p.children_d = dpc;
19732 for(i = 0, j = p.parents.length; i < j; i++) {
19733 m[p.parents[i]].children_d = m[p.parents[i]].children_d.concat(dpc);
19734 }
19735 /**
19736 * triggered when new data is inserted to the tree model
19737 * @event
19738 * @name model.jstree
19739 * @param {Array} nodes an array of node IDs
19740 * @param {String} parent the parent ID of the nodes
19741 */
19742 this.trigger('model', { "nodes" : dpc, 'parent' : par });
19743 if(par !== '#') {
19744 this._node_changed(par);
19745 this.redraw();
19746 }
19747 else {
19748 this.get_container_ul().children('.jstree-initial-node').remove();
19749 this.redraw(true);
19750 }
19751 if(this._data.core.selected.length !== s) {
19752 this.trigger('changed', { 'action' : 'model', 'selected' : this._data.core.selected });
19753 }
19754 cb.call(this, true);
19755 },
19756 /**
19757 * appends JSON content to the tree. Used internally.
19758 * @private
19759 * @name _append_json_data(obj, data)
19760 * @param {mixed} obj the node to append to
19761 * @param {String} data the JSON object to parse and append
19762 * @param {Boolean} force_processing internal param - do not set
19763 * @trigger model.jstree, changed.jstree
19764 */
19765 _append_json_data : function (dom, data, cb, force_processing) {
19766 dom = this.get_node(dom);
19767 dom.children = [];
19768 dom.children_d = [];
19769 // *%$@!!!
19770 if(data.d) {
19771 data = data.d;
19772 if(typeof data === "string") {
19773 data = JSON.parse(data);
19774 }
19775 }
19776 if(!$.isArray(data)) { data = [data]; }
19777 var w = null,
19778 args = {
19779 'df' : this._model.default_state,
19780 'dat' : data,
19781 'par' : dom.id,
19782 'm' : this._model.data,
19783 't_id' : this._id,
19784 't_cnt' : this._cnt,
19785 'sel' : this._data.core.selected
19786 },
19787 func = function (data, undefined) {
19788 if(data.data) { data = data.data; }
19789 var dat = data.dat,
19790 par = data.par,
19791 chd = [],
19792 dpc = [],
19793 add = [],
19794 df = data.df,
19795 t_id = data.t_id,
19796 t_cnt = data.t_cnt,
19797 m = data.m,
19798 p = m[par],
19799 sel = data.sel,
19800 tmp, i, j, rslt,
19801 parse_flat = function (d, p, ps) {
19802 if(!ps) { ps = []; }
19803 else { ps = ps.concat(); }
19804 if(p) { ps.unshift(p); }
19805 var tid = d.id.toString(),
19806 i, j, c, e,
19807 tmp = {
19808 id : tid,
19809 text : d.text || '',
19810 icon : d.icon !== undefined ? d.icon : true,
19811 parent : p,
19812 parents : ps,
19813 children : d.children || [],
19814 children_d : d.children_d || [],
19815 data : d.data,
19816 state : { },
19817 li_attr : { id : false },
19818 a_attr : { href : '#' },
19819 original : false
19820 };
19821 for(i in df) {
19822 if(df.hasOwnProperty(i)) {
19823 tmp.state[i] = df[i];
19824 }
19825 }
19826 if(d && d.data && d.data.jstree && d.data.jstree.icon) {
19827 tmp.icon = d.data.jstree.icon;
19828 }
19829 if(d && d.data) {
19830 tmp.data = d.data;
19831 if(d.data.jstree) {
19832 for(i in d.data.jstree) {
19833 if(d.data.jstree.hasOwnProperty(i)) {
19834 tmp.state[i] = d.data.jstree[i];
19835 }
19836 }
19837 }
19838 }
19839 if(d && typeof d.state === 'object') {
19840 for (i in d.state) {
19841 if(d.state.hasOwnProperty(i)) {
19842 tmp.state[i] = d.state[i];
19843 }
19844 }
19845 }
19846 if(d && typeof d.li_attr === 'object') {
19847 for (i in d.li_attr) {
19848 if(d.li_attr.hasOwnProperty(i)) {
19849 tmp.li_attr[i] = d.li_attr[i];
19850 }
19851 }
19852 }
19853 if(!tmp.li_attr.id) {
19854 tmp.li_attr.id = tid;
19855 }
19856 if(d && typeof d.a_attr === 'object') {
19857 for (i in d.a_attr) {
19858 if(d.a_attr.hasOwnProperty(i)) {
19859 tmp.a_attr[i] = d.a_attr[i];
19860 }
19861 }
19862 }
19863 if(d && d.children && d.children === true) {
19864 tmp.state.loaded = false;
19865 tmp.children = [];
19866 tmp.children_d = [];
19867 }
19868 m[tmp.id] = tmp;
19869 for(i = 0, j = tmp.children.length; i < j; i++) {
19870 c = parse_flat(m[tmp.children[i]], tmp.id, ps);
19871 e = m[c];
19872 tmp.children_d.push(c);
19873 if(e.children_d.length) {
19874 tmp.children_d = tmp.children_d.concat(e.children_d);
19875 }
19876 }
19877 delete d.data;
19878 delete d.children;
19879 m[tmp.id].original = d;
19880 if(tmp.state.selected) {
19881 add.push(tmp.id);
19882 }
19883 return tmp.id;
19884 },
19885 parse_nest = function (d, p, ps) {
19886 if(!ps) { ps = []; }
19887 else { ps = ps.concat(); }
19888 if(p) { ps.unshift(p); }
19889 var tid = false, i, j, c, e, tmp;
19890 do {
19891 tid = 'j' + t_id + '_' + (++t_cnt);
19892 } while(m[tid]);
19893
19894 tmp = {
19895 id : false,
19896 text : typeof d === 'string' ? d : '',
19897 icon : typeof d === 'object' && d.icon !== undefined ? d.icon : true,
19898 parent : p,
19899 parents : ps,
19900 children : [],
19901 children_d : [],
19902 data : null,
19903 state : { },
19904 li_attr : { id : false },
19905 a_attr : { href : '#' },
19906 original : false
19907 };
19908 for(i in df) {
19909 if(df.hasOwnProperty(i)) {
19910 tmp.state[i] = df[i];
19911 }
19912 }
19913 if(d && d.id) { tmp.id = d.id.toString(); }
19914 if(d && d.text) { tmp.text = d.text; }
19915 if(d && d.data && d.data.jstree && d.data.jstree.icon) {
19916 tmp.icon = d.data.jstree.icon;
19917 }
19918 if(d && d.data) {
19919 tmp.data = d.data;
19920 if(d.data.jstree) {
19921 for(i in d.data.jstree) {
19922 if(d.data.jstree.hasOwnProperty(i)) {
19923 tmp.state[i] = d.data.jstree[i];
19924 }
19925 }
19926 }
19927 }
19928 if(d && typeof d.state === 'object') {
19929 for (i in d.state) {
19930 if(d.state.hasOwnProperty(i)) {
19931 tmp.state[i] = d.state[i];
19932 }
19933 }
19934 }
19935 if(d && typeof d.li_attr === 'object') {
19936 for (i in d.li_attr) {
19937 if(d.li_attr.hasOwnProperty(i)) {
19938 tmp.li_attr[i] = d.li_attr[i];
19939 }
19940 }
19941 }
19942 if(tmp.li_attr.id && !tmp.id) {
19943 tmp.id = tmp.li_attr.id.toString();
19944 }
19945 if(!tmp.id) {
19946 tmp.id = tid;
19947 }
19948 if(!tmp.li_attr.id) {
19949 tmp.li_attr.id = tmp.id;
19950 }
19951 if(d && typeof d.a_attr === 'object') {
19952 for (i in d.a_attr) {
19953 if(d.a_attr.hasOwnProperty(i)) {
19954 tmp.a_attr[i] = d.a_attr[i];
19955 }
19956 }
19957 }
19958 if(d && d.children && d.children.length) {
19959 for(i = 0, j = d.children.length; i < j; i++) {
19960 c = parse_nest(d.children[i], tmp.id, ps);
19961 e = m[c];
19962 tmp.children.push(c);
19963 if(e.children_d.length) {
19964 tmp.children_d = tmp.children_d.concat(e.children_d);
19965 }
19966 }
19967 tmp.children_d = tmp.children_d.concat(tmp.children);
19968 }
19969 if(d && d.children && d.children === true) {
19970 tmp.state.loaded = false;
19971 tmp.children = [];
19972 tmp.children_d = [];
19973 }
19974 delete d.data;
19975 delete d.children;
19976 tmp.original = d;
19977 m[tmp.id] = tmp;
19978 if(tmp.state.selected) {
19979 add.push(tmp.id);
19980 }
19981 return tmp.id;
19982 };
19983
19984 if(dat.length && dat[0].id !== undefined && dat[0].parent !== undefined) {
19985 // Flat JSON support (for easy import from DB):
19986 // 1) convert to object (foreach)
19987 for(i = 0, j = dat.length; i < j; i++) {
19988 if(!dat[i].children) {
19989 dat[i].children = [];
19990 }
19991 m[dat[i].id.toString()] = dat[i];
19992 }
19993 // 2) populate children (foreach)
19994 for(i = 0, j = dat.length; i < j; i++) {
19995 m[dat[i].parent.toString()].children.push(dat[i].id.toString());
19996 // populate parent.children_d
19997 p.children_d.push(dat[i].id.toString());
19998 }
19999 // 3) normalize && populate parents and children_d with recursion
20000 for(i = 0, j = p.children.length; i < j; i++) {
20001 tmp = parse_flat(m[p.children[i]], par, p.parents.concat());
20002 dpc.push(tmp);
20003 if(m[tmp].children_d.length) {
20004 dpc = dpc.concat(m[tmp].children_d);
20005 }
20006 }
20007 for(i = 0, j = p.parents.length; i < j; i++) {
20008 m[p.parents[i]].children_d = m[p.parents[i]].children_d.concat(dpc);
20009 }
20010 // ?) three_state selection - p.state.selected && t - (if three_state foreach(dat => ch) -> foreach(parents) if(parent.selected) child.selected = true;
20011 rslt = {
20012 'cnt' : t_cnt,
20013 'mod' : m,
20014 'sel' : sel,
20015 'par' : par,
20016 'dpc' : dpc,
20017 'add' : add
20018 };
20019 }
20020 else {
20021 for(i = 0, j = dat.length; i < j; i++) {
20022 tmp = parse_nest(dat[i], par, p.parents.concat());
20023 if(tmp) {
20024 chd.push(tmp);
20025 dpc.push(tmp);
20026 if(m[tmp].children_d.length) {
20027 dpc = dpc.concat(m[tmp].children_d);
20028 }
20029 }
20030 }
20031 p.children = chd;
20032 p.children_d = dpc;
20033 for(i = 0, j = p.parents.length; i < j; i++) {
20034 m[p.parents[i]].children_d = m[p.parents[i]].children_d.concat(dpc);
20035 }
20036 rslt = {
20037 'cnt' : t_cnt,
20038 'mod' : m,
20039 'sel' : sel,
20040 'par' : par,
20041 'dpc' : dpc,
20042 'add' : add
20043 };
20044 }
20045 if(typeof window === 'undefined' || typeof window.document === 'undefined') {
20046 postMessage(rslt);
20047 }
20048 else {
20049 return rslt;
20050 }
20051 },
20052 rslt = function (rslt, worker) {
20053 this._cnt = rslt.cnt;
20054 this._model.data = rslt.mod; // breaks the reference in load_node - careful
20055
20056 if(worker) {
20057 var i, j, a = rslt.add, r = rslt.sel, s = this._data.core.selected.slice(), m = this._model.data;
20058 // if selection was changed while calculating in worker
20059 if(r.length !== s.length || $.vakata.array_unique(r.concat(s)).length !== r.length) {
20060 // deselect nodes that are no longer selected
20061 for(i = 0, j = r.length; i < j; i++) {
20062 if($.inArray(r[i], a) === -1 && $.inArray(r[i], s) === -1) {
20063 m[r[i]].state.selected = false;
20064 }
20065 }
20066 // select nodes that were selected in the mean time
20067 for(i = 0, j = s.length; i < j; i++) {
20068 if($.inArray(s[i], r) === -1) {
20069 m[s[i]].state.selected = true;
20070 }
20071 }
20072 }
20073 }
20074 if(rslt.add.length) {
20075 this._data.core.selected = this._data.core.selected.concat(rslt.add);
20076 }
20077
20078 this.trigger('model', { "nodes" : rslt.dpc, 'parent' : rslt.par });
20079
20080 if(rslt.par !== '#') {
20081 this._node_changed(rslt.par);
20082 this.redraw();
20083 }
20084 else {
20085 // this.get_container_ul().children('.jstree-initial-node').remove();
20086 this.redraw(true);
20087 }
20088 if(rslt.add.length) {
20089 this.trigger('changed', { 'action' : 'model', 'selected' : this._data.core.selected });
20090 }
20091 cb.call(this, true);
20092 };
20093 if(this.settings.core.worker && window.Blob && window.URL && window.Worker) {
20094 try {
20095 if(this._wrk === null) {
20096 this._wrk = window.URL.createObjectURL(
20097 new window.Blob(
20098 ['self.onmessage = ' + func.toString()],
20099 {type:"text/javascript"}
20100 )
20101 );
20102 }
20103 if(!this._data.core.working || force_processing) {
20104 this._data.core.working = true;
20105 w = new window.Worker(this._wrk);
20106 w.onmessage = $.proxy(function (e) {
20107 rslt.call(this, e.data, true);
20108 try { w.terminate(); w = null; } catch(ignore) { }
20109 if(this._data.core.worker_queue.length) {
20110 this._append_json_data.apply(this, this._data.core.worker_queue.shift());
20111 }
20112 else {
20113 this._data.core.working = false;
20114 }
20115 }, this);
20116 if(!args.par) {
20117 if(this._data.core.worker_queue.length) {
20118 this._append_json_data.apply(this, this._data.core.worker_queue.shift());
20119 }
20120 else {
20121 this._data.core.working = false;
20122 }
20123 }
20124 else {
20125 w.postMessage(args);
20126 }
20127 }
20128 else {
20129 this._data.core.worker_queue.push([dom, data, cb, true]);
20130 }
20131 }
20132 catch(e) {
20133 rslt.call(this, func(args), false);
20134 if(this._data.core.worker_queue.length) {
20135 this._append_json_data.apply(this, this._data.core.worker_queue.shift());
20136 }
20137 else {
20138 this._data.core.working = false;
20139 }
20140 }
20141 }
20142 else {
20143 rslt.call(this, func(args), false);
20144 }
20145 },
20146 /**
20147 * parses a node from a jQuery object and appends them to the in memory tree model. Used internally.
20148 * @private
20149 * @name _parse_model_from_html(d [, p, ps])
20150 * @param {jQuery} d the jQuery object to parse
20151 * @param {String} p the parent ID
20152 * @param {Array} ps list of all parents
20153 * @return {String} the ID of the object added to the model
20154 */
20155 _parse_model_from_html : function (d, p, ps) {
20156 if(!ps) { ps = []; }
20157 else { ps = [].concat(ps); }
20158 if(p) { ps.unshift(p); }
20159 var c, e, m = this._model.data,
20160 data = {
20161 id : false,
20162 text : false,
20163 icon : true,
20164 parent : p,
20165 parents : ps,
20166 children : [],
20167 children_d : [],
20168 data : null,
20169 state : { },
20170 li_attr : { id : false },
20171 a_attr : { href : '#' },
20172 original : false
20173 }, i, tmp, tid;
20174 for(i in this._model.default_state) {
20175 if(this._model.default_state.hasOwnProperty(i)) {
20176 data.state[i] = this._model.default_state[i];
20177 }
20178 }
20179 tmp = $.vakata.attributes(d, true);
20180 $.each(tmp, function (i, v) {
20181 v = $.trim(v);
20182 if(!v.length) { return true; }
20183 data.li_attr[i] = v;
20184 if(i === 'id') {
20185 data.id = v.toString();
20186 }
20187 });
20188 tmp = d.children('a').first();
20189 if(tmp.length) {
20190 tmp = $.vakata.attributes(tmp, true);
20191 $.each(tmp, function (i, v) {
20192 v = $.trim(v);
20193 if(v.length) {
20194 data.a_attr[i] = v;
20195 }
20196 });
20197 }
20198 tmp = d.children("a").first().length ? d.children("a").first().clone() : d.clone();
20199 tmp.children("ins, i, ul").remove();
20200 tmp = tmp.html();
20201 tmp = $('<div />').html(tmp);
20202 data.text = this.settings.core.force_text ? tmp.text() : tmp.html();
20203 tmp = d.data();
20204 data.data = tmp ? $.extend(true, {}, tmp) : null;
20205 data.state.opened = d.hasClass('jstree-open');
20206 data.state.selected = d.children('a').hasClass('jstree-clicked');
20207 data.state.disabled = d.children('a').hasClass('jstree-disabled');
20208 if(data.data && data.data.jstree) {
20209 for(i in data.data.jstree) {
20210 if(data.data.jstree.hasOwnProperty(i)) {
20211 data.state[i] = data.data.jstree[i];
20212 }
20213 }
20214 }
20215 tmp = d.children("a").children(".jstree-themeicon");
20216 if(tmp.length) {
20217 data.icon = tmp.hasClass('jstree-themeicon-hidden') ? false : tmp.attr('rel');
20218 }
20219 if(data.state.icon) {
20220 data.icon = data.state.icon;
20221 }
20222 tmp = d.children("ul").children("li");
20223 do {
20224 tid = 'j' + this._id + '_' + (++this._cnt);
20225 } while(m[tid]);
20226 data.id = data.li_attr.id ? data.li_attr.id.toString() : tid;
20227 if(tmp.length) {
20228 tmp.each($.proxy(function (i, v) {
20229 c = this._parse_model_from_html($(v), data.id, ps);
20230 e = this._model.data[c];
20231 data.children.push(c);
20232 if(e.children_d.length) {
20233 data.children_d = data.children_d.concat(e.children_d);
20234 }
20235 }, this));
20236 data.children_d = data.children_d.concat(data.children);
20237 }
20238 else {
20239 if(d.hasClass('jstree-closed')) {
20240 data.state.loaded = false;
20241 }
20242 }
20243 if(data.li_attr['class']) {
20244 data.li_attr['class'] = data.li_attr['class'].replace('jstree-closed','').replace('jstree-open','');
20245 }
20246 if(data.a_attr['class']) {
20247 data.a_attr['class'] = data.a_attr['class'].replace('jstree-clicked','').replace('jstree-disabled','');
20248 }
20249 m[data.id] = data;
20250 if(data.state.selected) {
20251 this._data.core.selected.push(data.id);
20252 }
20253 return data.id;
20254 },
20255 /**
20256 * parses a node from a JSON object (used when dealing with flat data, which has no nesting of children, but has id and parent properties) and appends it to the in memory tree model. Used internally.
20257 * @private
20258 * @name _parse_model_from_flat_json(d [, p, ps])
20259 * @param {Object} d the JSON object to parse
20260 * @param {String} p the parent ID
20261 * @param {Array} ps list of all parents
20262 * @return {String} the ID of the object added to the model
20263 */
20264 _parse_model_from_flat_json : function (d, p, ps) {
20265 if(!ps) { ps = []; }
20266 else { ps = ps.concat(); }
20267 if(p) { ps.unshift(p); }
20268 var tid = d.id.toString(),
20269 m = this._model.data,
20270 df = this._model.default_state,
20271 i, j, c, e,
20272 tmp = {
20273 id : tid,
20274 text : d.text || '',
20275 icon : d.icon !== undefined ? d.icon : true,
20276 parent : p,
20277 parents : ps,
20278 children : d.children || [],
20279 children_d : d.children_d || [],
20280 data : d.data,
20281 state : { },
20282 li_attr : { id : false },
20283 a_attr : { href : '#' },
20284 original : false
20285 };
20286 for(i in df) {
20287 if(df.hasOwnProperty(i)) {
20288 tmp.state[i] = df[i];
20289 }
20290 }
20291 if(d && d.data && d.data.jstree && d.data.jstree.icon) {
20292 tmp.icon = d.data.jstree.icon;
20293 }
20294 if(d && d.data) {
20295 tmp.data = d.data;
20296 if(d.data.jstree) {
20297 for(i in d.data.jstree) {
20298 if(d.data.jstree.hasOwnProperty(i)) {
20299 tmp.state[i] = d.data.jstree[i];
20300 }
20301 }
20302 }
20303 }
20304 if(d && typeof d.state === 'object') {
20305 for (i in d.state) {
20306 if(d.state.hasOwnProperty(i)) {
20307 tmp.state[i] = d.state[i];
20308 }
20309 }
20310 }
20311 if(d && typeof d.li_attr === 'object') {
20312 for (i in d.li_attr) {
20313 if(d.li_attr.hasOwnProperty(i)) {
20314 tmp.li_attr[i] = d.li_attr[i];
20315 }
20316 }
20317 }
20318 if(!tmp.li_attr.id) {
20319 tmp.li_attr.id = tid;
20320 }
20321 if(d && typeof d.a_attr === 'object') {
20322 for (i in d.a_attr) {
20323 if(d.a_attr.hasOwnProperty(i)) {
20324 tmp.a_attr[i] = d.a_attr[i];
20325 }
20326 }
20327 }
20328 if(d && d.children && d.children === true) {
20329 tmp.state.loaded = false;
20330 tmp.children = [];
20331 tmp.children_d = [];
20332 }
20333 m[tmp.id] = tmp;
20334 for(i = 0, j = tmp.children.length; i < j; i++) {
20335 c = this._parse_model_from_flat_json(m[tmp.children[i]], tmp.id, ps);
20336 e = m[c];
20337 tmp.children_d.push(c);
20338 if(e.children_d.length) {
20339 tmp.children_d = tmp.children_d.concat(e.children_d);
20340 }
20341 }
20342 delete d.data;
20343 delete d.children;
20344 m[tmp.id].original = d;
20345 if(tmp.state.selected) {
20346 this._data.core.selected.push(tmp.id);
20347 }
20348 return tmp.id;
20349 },
20350 /**
20351 * parses a node from a JSON object and appends it to the in memory tree model. Used internally.
20352 * @private
20353 * @name _parse_model_from_json(d [, p, ps])
20354 * @param {Object} d the JSON object to parse
20355 * @param {String} p the parent ID
20356 * @param {Array} ps list of all parents
20357 * @return {String} the ID of the object added to the model
20358 */
20359 _parse_model_from_json : function (d, p, ps) {
20360 if(!ps) { ps = []; }
20361 else { ps = ps.concat(); }
20362 if(p) { ps.unshift(p); }
20363 var tid = false, i, j, c, e, m = this._model.data, df = this._model.default_state, tmp;
20364 do {
20365 tid = 'j' + this._id + '_' + (++this._cnt);
20366 } while(m[tid]);
20367
20368 tmp = {
20369 id : false,
20370 text : typeof d === 'string' ? d : '',
20371 icon : typeof d === 'object' && d.icon !== undefined ? d.icon : true,
20372 parent : p,
20373 parents : ps,
20374 children : [],
20375 children_d : [],
20376 data : null,
20377 state : { },
20378 li_attr : { id : false },
20379 a_attr : { href : '#' },
20380 original : false
20381 };
20382 for(i in df) {
20383 if(df.hasOwnProperty(i)) {
20384 tmp.state[i] = df[i];
20385 }
20386 }
20387 if(d && d.id) { tmp.id = d.id.toString(); }
20388 if(d && d.text) { tmp.text = d.text; }
20389 if(d && d.data && d.data.jstree && d.data.jstree.icon) {
20390 tmp.icon = d.data.jstree.icon;
20391 }
20392 if(d && d.data) {
20393 tmp.data = d.data;
20394 if(d.data.jstree) {
20395 for(i in d.data.jstree) {
20396 if(d.data.jstree.hasOwnProperty(i)) {
20397 tmp.state[i] = d.data.jstree[i];
20398 }
20399 }
20400 }
20401 }
20402 if(d && typeof d.state === 'object') {
20403 for (i in d.state) {
20404 if(d.state.hasOwnProperty(i)) {
20405 tmp.state[i] = d.state[i];
20406 }
20407 }
20408 }
20409 if(d && typeof d.li_attr === 'object') {
20410 for (i in d.li_attr) {
20411 if(d.li_attr.hasOwnProperty(i)) {
20412 tmp.li_attr[i] = d.li_attr[i];
20413 }
20414 }
20415 }
20416 if(tmp.li_attr.id && !tmp.id) {
20417 tmp.id = tmp.li_attr.id.toString();
20418 }
20419 if(!tmp.id) {
20420 tmp.id = tid;
20421 }
20422 if(!tmp.li_attr.id) {
20423 tmp.li_attr.id = tmp.id;
20424 }
20425 if(d && typeof d.a_attr === 'object') {
20426 for (i in d.a_attr) {
20427 if(d.a_attr.hasOwnProperty(i)) {
20428 tmp.a_attr[i] = d.a_attr[i];
20429 }
20430 }
20431 }
20432 if(d && d.children && d.children.length) {
20433 for(i = 0, j = d.children.length; i < j; i++) {
20434 c = this._parse_model_from_json(d.children[i], tmp.id, ps);
20435 e = m[c];
20436 tmp.children.push(c);
20437 if(e.children_d.length) {
20438 tmp.children_d = tmp.children_d.concat(e.children_d);
20439 }
20440 }
20441 tmp.children_d = tmp.children_d.concat(tmp.children);
20442 }
20443 if(d && d.children && d.children === true) {
20444 tmp.state.loaded = false;
20445 tmp.children = [];
20446 tmp.children_d = [];
20447 }
20448 delete d.data;
20449 delete d.children;
20450 tmp.original = d;
20451 m[tmp.id] = tmp;
20452 if(tmp.state.selected) {
20453 this._data.core.selected.push(tmp.id);
20454 }
20455 return tmp.id;
20456 },
20457 /**
20458 * redraws all nodes that need to be redrawn. Used internally.
20459 * @private
20460 * @name _redraw()
20461 * @trigger redraw.jstree
20462 */
20463 _redraw : function () {
20464 var nodes = this._model.force_full_redraw ? this._model.data['#'].children.concat([]) : this._model.changed.concat([]),
20465 f = document.createElement('UL'), tmp, i, j, fe = this._data.core.focused;
20466 for(i = 0, j = nodes.length; i < j; i++) {
20467 tmp = this.redraw_node(nodes[i], true, this._model.force_full_redraw);
20468 if(tmp && this._model.force_full_redraw) {
20469 f.appendChild(tmp);
20470 }
20471 }
20472 if(this._model.force_full_redraw) {
20473 f.className = this.get_container_ul()[0].className;
20474 f.setAttribute('role','group');
20475 this.element.empty().append(f);
20476 //this.get_container_ul()[0].appendChild(f);
20477 }
20478 if(fe !== null) {
20479 tmp = this.get_node(fe, true);
20480 if(tmp && tmp.length && tmp.children('.jstree-anchor')[0] !== document.activeElement) {
20481 tmp.children('.jstree-anchor').focus();
20482 }
20483 else {
20484 this._data.core.focused = null;
20485 }
20486 }
20487 this._model.force_full_redraw = false;
20488 this._model.changed = [];
20489 /**
20490 * triggered after nodes are redrawn
20491 * @event
20492 * @name redraw.jstree
20493 * @param {array} nodes the redrawn nodes
20494 */
20495 this.trigger('redraw', { "nodes" : nodes });
20496 },
20497 /**
20498 * redraws all nodes that need to be redrawn or optionally - the whole tree
20499 * @name redraw([full])
20500 * @param {Boolean} full if set to `true` all nodes are redrawn.
20501 */
20502 redraw : function (full) {
20503 if(full) {
20504 this._model.force_full_redraw = true;
20505 }
20506 //if(this._model.redraw_timeout) {
20507 // clearTimeout(this._model.redraw_timeout);
20508 //}
20509 //this._model.redraw_timeout = setTimeout($.proxy(this._redraw, this),0);
20510 this._redraw();
20511 },
20512 /**
20513 * redraws a single node's children. Used internally.
20514 * @private
20515 * @name draw_children(node)
20516 * @param {mixed} node the node whose children will be redrawn
20517 */
20518 draw_children : function (node) {
20519 var obj = this.get_node(node),
20520 i = false,
20521 j = false,
20522 k = false,
20523 d = document;
20524 if(!obj) { return false; }
20525 if(obj.id === '#') { return this.redraw(true); }
20526 node = this.get_node(node, true);
20527 if(!node || !node.length) { return false; } // TODO: quick toggle
20528
20529 node.children('.jstree-children').remove();
20530 node = node[0];
20531 if(obj.children.length && obj.state.loaded) {
20532 k = d.createElement('UL');
20533 k.setAttribute('role', 'group');
20534 k.className = 'jstree-children';
20535 for(i = 0, j = obj.children.length; i < j; i++) {
20536 k.appendChild(this.redraw_node(obj.children[i], true, true));
20537 }
20538 node.appendChild(k);
20539 }
20540 },
20541 /**
20542 * redraws a single node. Used internally.
20543 * @private
20544 * @name redraw_node(node, deep, is_callback, force_render)
20545 * @param {mixed} node the node to redraw
20546 * @param {Boolean} deep should child nodes be redrawn too
20547 * @param {Boolean} is_callback is this a recursion call
20548 * @param {Boolean} force_render should children of closed parents be drawn anyway
20549 */
20550 redraw_node : function (node, deep, is_callback, force_render) {
20551 var obj = this.get_node(node),
20552 par = false,
20553 ind = false,
20554 old = false,
20555 i = false,
20556 j = false,
20557 k = false,
20558 c = '',
20559 d = document,
20560 m = this._model.data,
20561 f = false,
20562 s = false,
20563 tmp = null,
20564 t = 0,
20565 l = 0;
20566 if(!obj) { return false; }
20567 if(obj.id === '#') { return this.redraw(true); }
20568 deep = deep || obj.children.length === 0;
20569 node = !document.querySelector ? document.getElementById(obj.id) : this.element[0].querySelector('#' + ("0123456789".indexOf(obj.id[0]) !== -1 ? '\\3' + obj.id[0] + ' ' + obj.id.substr(1).replace($.jstree.idregex,'\\$&') : obj.id.replace($.jstree.idregex,'\\$&')) ); //, this.element);
20570 if(!node) {
20571 deep = true;
20572 //node = d.createElement('LI');
20573 if(!is_callback) {
20574 par = obj.parent !== '#' ? $('#' + obj.parent.replace($.jstree.idregex,'\\$&'), this.element)[0] : null;
20575 if(par !== null && (!par || !m[obj.parent].state.opened)) {
20576 return false;
20577 }
20578 ind = $.inArray(obj.id, par === null ? m['#'].children : m[obj.parent].children);
20579 }
20580 }
20581 else {
20582 node = $(node);
20583 if(!is_callback) {
20584 par = node.parent().parent()[0];
20585 if(par === this.element[0]) {
20586 par = null;
20587 }
20588 ind = node.index();
20589 }
20590 // m[obj.id].data = node.data(); // use only node's data, no need to touch jquery storage
20591 if(!deep && obj.children.length && !node.children('.jstree-children').length) {
20592 deep = true;
20593 }
20594 if(!deep) {
20595 old = node.children('.jstree-children')[0];
20596 }
20597 f = node.children('.jstree-anchor')[0] === document.activeElement;
20598 node.remove();
20599 //node = d.createElement('LI');
20600 //node = node[0];
20601 }
20602 node = _node.cloneNode(true);
20603 // node is DOM, deep is boolean
20604
20605 c = 'jstree-node ';
20606 for(i in obj.li_attr) {
20607 if(obj.li_attr.hasOwnProperty(i)) {
20608 if(i === 'id') { continue; }
20609 if(i !== 'class') {
20610 node.setAttribute(i, obj.li_attr[i]);
20611 }
20612 else {
20613 c += obj.li_attr[i];
20614 }
20615 }
20616 }
20617 if(!obj.a_attr.id) {
20618 obj.a_attr.id = obj.id + '_anchor';
20619 }
20620 node.setAttribute('aria-selected', !!obj.state.selected);
20621 node.setAttribute('aria-level', obj.parents.length);
20622 node.setAttribute('aria-labelledby', obj.a_attr.id);
20623 if(obj.state.disabled) {
20624 node.setAttribute('aria-disabled', true);
20625 }
20626
20627 if(obj.state.loaded && !obj.children.length) {
20628 c += ' jstree-leaf';
20629 }
20630 else {
20631 c += obj.state.opened && obj.state.loaded ? ' jstree-open' : ' jstree-closed';
20632 node.setAttribute('aria-expanded', (obj.state.opened && obj.state.loaded) );
20633 }
20634 if(obj.parent !== null && m[obj.parent].children[m[obj.parent].children.length - 1] === obj.id) {
20635 c += ' jstree-last';
20636 }
20637 node.id = obj.id;
20638 node.className = c;
20639 c = ( obj.state.selected ? ' jstree-clicked' : '') + ( obj.state.disabled ? ' jstree-disabled' : '');
20640 for(j in obj.a_attr) {
20641 if(obj.a_attr.hasOwnProperty(j)) {
20642 if(j === 'href' && obj.a_attr[j] === '#') { continue; }
20643 if(j !== 'class') {
20644 node.childNodes[1].setAttribute(j, obj.a_attr[j]);
20645 }
20646 else {
20647 c += ' ' + obj.a_attr[j];
20648 }
20649 }
20650 }
20651 if(c.length) {
20652 node.childNodes[1].className = 'jstree-anchor ' + c;
20653 }
20654 if((obj.icon && obj.icon !== true) || obj.icon === false) {
20655 if(obj.icon === false) {
20656 node.childNodes[1].childNodes[0].className += ' jstree-themeicon-hidden';
20657 }
20658 else if(obj.icon.indexOf('/') === -1 && obj.icon.indexOf('.') === -1) {
20659 node.childNodes[1].childNodes[0].className += ' ' + obj.icon + ' jstree-themeicon-custom';
20660 }
20661 else {
20662 node.childNodes[1].childNodes[0].style.backgroundImage = 'url('+obj.icon+')';
20663 node.childNodes[1].childNodes[0].style.backgroundPosition = 'center center';
20664 node.childNodes[1].childNodes[0].style.backgroundSize = 'auto';
20665 node.childNodes[1].childNodes[0].className += ' jstree-themeicon-custom';
20666 }
20667 }
20668
20669 if(this.settings.core.force_text) {
20670 node.childNodes[1].appendChild(d.createTextNode(obj.text));
20671 }
20672 else {
20673 node.childNodes[1].innerHTML += obj.text;
20674 }
20675
20676
20677 if(deep && obj.children.length && (obj.state.opened || force_render) && obj.state.loaded) {
20678 k = d.createElement('UL');
20679 k.setAttribute('role', 'group');
20680 k.className = 'jstree-children';
20681 for(i = 0, j = obj.children.length; i < j; i++) {
20682 k.appendChild(this.redraw_node(obj.children[i], deep, true));
20683 }
20684 node.appendChild(k);
20685 }
20686 if(old) {
20687 node.appendChild(old);
20688 }
20689 if(!is_callback) {
20690 // append back using par / ind
20691 if(!par) {
20692 par = this.element[0];
20693 }
20694 for(i = 0, j = par.childNodes.length; i < j; i++) {
20695 if(par.childNodes[i] && par.childNodes[i].className && par.childNodes[i].className.indexOf('jstree-children') !== -1) {
20696 tmp = par.childNodes[i];
20697 break;
20698 }
20699 }
20700 if(!tmp) {
20701 tmp = d.createElement('UL');
20702 tmp.setAttribute('role', 'group');
20703 tmp.className = 'jstree-children';
20704 par.appendChild(tmp);
20705 }
20706 par = tmp;
20707
20708 if(ind < par.childNodes.length) {
20709 par.insertBefore(node, par.childNodes[ind]);
20710 }
20711 else {
20712 par.appendChild(node);
20713 }
20714 if(f) {
20715 t = this.element[0].scrollTop;
20716 l = this.element[0].scrollLeft;
20717 node.childNodes[1].focus();
20718 this.element[0].scrollTop = t;
20719 this.element[0].scrollLeft = l;
20720 }
20721 }
20722 if(obj.state.opened && !obj.state.loaded) {
20723 obj.state.opened = false;
20724 setTimeout($.proxy(function () {
20725 this.open_node(obj.id, false, 0);
20726 }, this), 0);
20727 }
20728 return node;
20729 },
20730 /**
20731 * opens a node, revaling its children. If the node is not loaded it will be loaded and opened once ready.
20732 * @name open_node(obj [, callback, animation])
20733 * @param {mixed} obj the node to open
20734 * @param {Function} callback a function to execute once the node is opened
20735 * @param {Number} animation the animation duration in milliseconds when opening the node (overrides the `core.animation` setting). Use `false` for no animation.
20736 * @trigger open_node.jstree, after_open.jstree, before_open.jstree
20737 */
20738 open_node : function (obj, callback, animation) {
20739 var t1, t2, d, t;
20740 if($.isArray(obj)) {
20741 obj = obj.slice();
20742 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
20743 this.open_node(obj[t1], callback, animation);
20744 }
20745 return true;
20746 }
20747 obj = this.get_node(obj);
20748 if(!obj || obj.id === '#') {
20749 return false;
20750 }
20751 animation = animation === undefined ? this.settings.core.animation : animation;
20752 if(!this.is_closed(obj)) {
20753 if(callback) {
20754 callback.call(this, obj, false);
20755 }
20756 return false;
20757 }
20758 if(!this.is_loaded(obj)) {
20759 if(this.is_loading(obj)) {
20760 return setTimeout($.proxy(function () {
20761 this.open_node(obj, callback, animation);
20762 }, this), 500);
20763 }
20764 this.load_node(obj, function (o, ok) {
20765 return ok ? this.open_node(o, callback, animation) : (callback ? callback.call(this, o, false) : false);
20766 });
20767 }
20768 else {
20769 d = this.get_node(obj, true);
20770 t = this;
20771 if(d.length) {
20772 if(animation && d.children(".jstree-children").length) {
20773 d.children(".jstree-children").stop(true, true);
20774 }
20775 if(obj.children.length && !this._firstChild(d.children('.jstree-children')[0])) {
20776 this.draw_children(obj);
20777 //d = this.get_node(obj, true);
20778 }
20779 if(!animation) {
20780 this.trigger('before_open', { "node" : obj });
20781 d[0].className = d[0].className.replace('jstree-closed', 'jstree-open');
20782 d[0].setAttribute("aria-expanded", true);
20783 }
20784 else {
20785 this.trigger('before_open', { "node" : obj });
20786 d
20787 .children(".jstree-children").css("display","none").end()
20788 .removeClass("jstree-closed").addClass("jstree-open").attr("aria-expanded", true)
20789 .children(".jstree-children").stop(true, true)
20790 .slideDown(animation, function () {
20791 this.style.display = "";
20792 t.trigger("after_open", { "node" : obj });
20793 });
20794 }
20795 }
20796 obj.state.opened = true;
20797 if(callback) {
20798 callback.call(this, obj, true);
20799 }
20800 if(!d.length) {
20801 /**
20802 * triggered when a node is about to be opened (if the node is supposed to be in the DOM, it will be, but it won't be visible yet)
20803 * @event
20804 * @name before_open.jstree
20805 * @param {Object} node the opened node
20806 */
20807 this.trigger('before_open', { "node" : obj });
20808 }
20809 /**
20810 * triggered when a node is opened (if there is an animation it will not be completed yet)
20811 * @event
20812 * @name open_node.jstree
20813 * @param {Object} node the opened node
20814 */
20815 this.trigger('open_node', { "node" : obj });
20816 if(!animation || !d.length) {
20817 /**
20818 * triggered when a node is opened and the animation is complete
20819 * @event
20820 * @name after_open.jstree
20821 * @param {Object} node the opened node
20822 */
20823 this.trigger("after_open", { "node" : obj });
20824 }
20825 }
20826 },
20827 /**
20828 * opens every parent of a node (node should be loaded)
20829 * @name _open_to(obj)
20830 * @param {mixed} obj the node to reveal
20831 * @private
20832 */
20833 _open_to : function (obj) {
20834 obj = this.get_node(obj);
20835 if(!obj || obj.id === '#') {
20836 return false;
20837 }
20838 var i, j, p = obj.parents;
20839 for(i = 0, j = p.length; i < j; i+=1) {
20840 if(i !== '#') {
20841 this.open_node(p[i], false, 0);
20842 }
20843 }
20844 return $('#' + obj.id.replace($.jstree.idregex,'\\$&'), this.element);
20845 },
20846 /**
20847 * closes a node, hiding its children
20848 * @name close_node(obj [, animation])
20849 * @param {mixed} obj the node to close
20850 * @param {Number} animation the animation duration in milliseconds when closing the node (overrides the `core.animation` setting). Use `false` for no animation.
20851 * @trigger close_node.jstree, after_close.jstree
20852 */
20853 close_node : function (obj, animation) {
20854 var t1, t2, t, d;
20855 if($.isArray(obj)) {
20856 obj = obj.slice();
20857 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
20858 this.close_node(obj[t1], animation);
20859 }
20860 return true;
20861 }
20862 obj = this.get_node(obj);
20863 if(!obj || obj.id === '#') {
20864 return false;
20865 }
20866 if(this.is_closed(obj)) {
20867 return false;
20868 }
20869 animation = animation === undefined ? this.settings.core.animation : animation;
20870 t = this;
20871 d = this.get_node(obj, true);
20872 if(d.length) {
20873 if(!animation) {
20874 d[0].className = d[0].className.replace('jstree-open', 'jstree-closed');
20875 d.attr("aria-expanded", false).children('.jstree-children').remove();
20876 }
20877 else {
20878 d
20879 .children(".jstree-children").attr("style","display:block !important").end()
20880 .removeClass("jstree-open").addClass("jstree-closed").attr("aria-expanded", false)
20881 .children(".jstree-children").stop(true, true).slideUp(animation, function () {
20882 this.style.display = "";
20883 d.children('.jstree-children').remove();
20884 t.trigger("after_close", { "node" : obj });
20885 });
20886 }
20887 }
20888 obj.state.opened = false;
20889 /**
20890 * triggered when a node is closed (if there is an animation it will not be complete yet)
20891 * @event
20892 * @name close_node.jstree
20893 * @param {Object} node the closed node
20894 */
20895 this.trigger('close_node',{ "node" : obj });
20896 if(!animation || !d.length) {
20897 /**
20898 * triggered when a node is closed and the animation is complete
20899 * @event
20900 * @name after_close.jstree
20901 * @param {Object} node the closed node
20902 */
20903 this.trigger("after_close", { "node" : obj });
20904 }
20905 },
20906 /**
20907 * toggles a node - closing it if it is open, opening it if it is closed
20908 * @name toggle_node(obj)
20909 * @param {mixed} obj the node to toggle
20910 */
20911 toggle_node : function (obj) {
20912 var t1, t2;
20913 if($.isArray(obj)) {
20914 obj = obj.slice();
20915 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
20916 this.toggle_node(obj[t1]);
20917 }
20918 return true;
20919 }
20920 if(this.is_closed(obj)) {
20921 return this.open_node(obj);
20922 }
20923 if(this.is_open(obj)) {
20924 return this.close_node(obj);
20925 }
20926 },
20927 /**
20928 * opens all nodes within a node (or the tree), revaling their children. If the node is not loaded it will be loaded and opened once ready.
20929 * @name open_all([obj, animation, original_obj])
20930 * @param {mixed} obj the node to open recursively, omit to open all nodes in the tree
20931 * @param {Number} animation the animation duration in milliseconds when opening the nodes, the default is no animation
20932 * @param {jQuery} reference to the node that started the process (internal use)
20933 * @trigger open_all.jstree
20934 */
20935 open_all : function (obj, animation, original_obj) {
20936 if(!obj) { obj = '#'; }
20937 obj = this.get_node(obj);
20938 if(!obj) { return false; }
20939 var dom = obj.id === '#' ? this.get_container_ul() : this.get_node(obj, true), i, j, _this;
20940 if(!dom.length) {
20941 for(i = 0, j = obj.children_d.length; i < j; i++) {
20942 if(this.is_closed(this._model.data[obj.children_d[i]])) {
20943 this._model.data[obj.children_d[i]].state.opened = true;
20944 }
20945 }
20946 return this.trigger('open_all', { "node" : obj });
20947 }
20948 original_obj = original_obj || dom;
20949 _this = this;
20950 dom = this.is_closed(obj) ? dom.find('.jstree-closed').addBack() : dom.find('.jstree-closed');
20951 dom.each(function () {
20952 _this.open_node(
20953 this,
20954 function(node, status) { if(status && this.is_parent(node)) { this.open_all(node, animation, original_obj); } },
20955 animation || 0
20956 );
20957 });
20958 if(original_obj.find('.jstree-closed').length === 0) {
20959 /**
20960 * triggered when an `open_all` call completes
20961 * @event
20962 * @name open_all.jstree
20963 * @param {Object} node the opened node
20964 */
20965 this.trigger('open_all', { "node" : this.get_node(original_obj) });
20966 }
20967 },
20968 /**
20969 * closes all nodes within a node (or the tree), revaling their children
20970 * @name close_all([obj, animation])
20971 * @param {mixed} obj the node to close recursively, omit to close all nodes in the tree
20972 * @param {Number} animation the animation duration in milliseconds when closing the nodes, the default is no animation
20973 * @trigger close_all.jstree
20974 */
20975 close_all : function (obj, animation) {
20976 if(!obj) { obj = '#'; }
20977 obj = this.get_node(obj);
20978 if(!obj) { return false; }
20979 var dom = obj.id === '#' ? this.get_container_ul() : this.get_node(obj, true),
20980 _this = this, i, j;
20981 if(!dom.length) {
20982 for(i = 0, j = obj.children_d.length; i < j; i++) {
20983 this._model.data[obj.children_d[i]].state.opened = false;
20984 }
20985 return this.trigger('close_all', { "node" : obj });
20986 }
20987 dom = this.is_open(obj) ? dom.find('.jstree-open').addBack() : dom.find('.jstree-open');
20988 $(dom.get().reverse()).each(function () { _this.close_node(this, animation || 0); });
20989 /**
20990 * triggered when an `close_all` call completes
20991 * @event
20992 * @name close_all.jstree
20993 * @param {Object} node the closed node
20994 */
20995 this.trigger('close_all', { "node" : obj });
20996 },
20997 /**
20998 * checks if a node is disabled (not selectable)
20999 * @name is_disabled(obj)
21000 * @param {mixed} obj
21001 * @return {Boolean}
21002 */
21003 is_disabled : function (obj) {
21004 obj = this.get_node(obj);
21005 return obj && obj.state && obj.state.disabled;
21006 },
21007 /**
21008 * enables a node - so that it can be selected
21009 * @name enable_node(obj)
21010 * @param {mixed} obj the node to enable
21011 * @trigger enable_node.jstree
21012 */
21013 enable_node : function (obj) {
21014 var t1, t2;
21015 if($.isArray(obj)) {
21016 obj = obj.slice();
21017 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
21018 this.enable_node(obj[t1]);
21019 }
21020 return true;
21021 }
21022 obj = this.get_node(obj);
21023 if(!obj || obj.id === '#') {
21024 return false;
21025 }
21026 obj.state.disabled = false;
21027 this.get_node(obj,true).children('.jstree-anchor').removeClass('jstree-disabled').attr('aria-disabled', false);
21028 /**
21029 * triggered when an node is enabled
21030 * @event
21031 * @name enable_node.jstree
21032 * @param {Object} node the enabled node
21033 */
21034 this.trigger('enable_node', { 'node' : obj });
21035 },
21036 /**
21037 * disables a node - so that it can not be selected
21038 * @name disable_node(obj)
21039 * @param {mixed} obj the node to disable
21040 * @trigger disable_node.jstree
21041 */
21042 disable_node : function (obj) {
21043 var t1, t2;
21044 if($.isArray(obj)) {
21045 obj = obj.slice();
21046 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
21047 this.disable_node(obj[t1]);
21048 }
21049 return true;
21050 }
21051 obj = this.get_node(obj);
21052 if(!obj || obj.id === '#') {
21053 return false;
21054 }
21055 obj.state.disabled = true;
21056 this.get_node(obj,true).children('.jstree-anchor').addClass('jstree-disabled').attr('aria-disabled', true);
21057 /**
21058 * triggered when an node is disabled
21059 * @event
21060 * @name disable_node.jstree
21061 * @param {Object} node the disabled node
21062 */
21063 this.trigger('disable_node', { 'node' : obj });
21064 },
21065 /**
21066 * called when a node is selected by the user. Used internally.
21067 * @private
21068 * @name activate_node(obj, e)
21069 * @param {mixed} obj the node
21070 * @param {Object} e the related event
21071 * @trigger activate_node.jstree, changed.jstree
21072 */
21073 activate_node : function (obj, e) {
21074 if(this.is_disabled(obj)) {
21075 return false;
21076 }
21077
21078 // ensure last_clicked is still in the DOM, make it fresh (maybe it was moved?) and make sure it is still selected, if not - make last_clicked the last selected node
21079 this._data.core.last_clicked = this._data.core.last_clicked && this._data.core.last_clicked.id !== undefined ? this.get_node(this._data.core.last_clicked.id) : null;
21080 if(this._data.core.last_clicked && !this._data.core.last_clicked.state.selected) { this._data.core.last_clicked = null; }
21081 if(!this._data.core.last_clicked && this._data.core.selected.length) { this._data.core.last_clicked = this.get_node(this._data.core.selected[this._data.core.selected.length - 1]); }
21082
21083 if(!this.settings.core.multiple || (!e.metaKey && !e.ctrlKey && !e.shiftKey) || (e.shiftKey && (!this._data.core.last_clicked || !this.get_parent(obj) || this.get_parent(obj) !== this._data.core.last_clicked.parent ) )) {
21084 if(!this.settings.core.multiple && (e.metaKey || e.ctrlKey || e.shiftKey) && this.is_selected(obj)) {
21085 this.deselect_node(obj, false, e);
21086 }
21087 else {
21088 this.deselect_all(true);
21089 this.select_node(obj, false, false, e);
21090 this._data.core.last_clicked = this.get_node(obj);
21091 }
21092 }
21093 else {
21094 if(e.shiftKey) {
21095 var o = this.get_node(obj).id,
21096 l = this._data.core.last_clicked.id,
21097 p = this.get_node(this._data.core.last_clicked.parent).children,
21098 c = false,
21099 i, j;
21100 for(i = 0, j = p.length; i < j; i += 1) {
21101 // separate IFs work whem o and l are the same
21102 if(p[i] === o) {
21103 c = !c;
21104 }
21105 if(p[i] === l) {
21106 c = !c;
21107 }
21108 if(c || p[i] === o || p[i] === l) {
21109 this.select_node(p[i], true, false, e);
21110 }
21111 else {
21112 this.deselect_node(p[i], true, e);
21113 }
21114 }
21115 this.trigger('changed', { 'action' : 'select_node', 'node' : this.get_node(obj), 'selected' : this._data.core.selected, 'event' : e });
21116 }
21117 else {
21118 if(!this.is_selected(obj)) {
21119 this.select_node(obj, false, false, e);
21120 }
21121 else {
21122 this.deselect_node(obj, false, e);
21123 }
21124 }
21125 }
21126 /**
21127 * triggered when an node is clicked or intercated with by the user
21128 * @event
21129 * @name activate_node.jstree
21130 * @param {Object} node
21131 */
21132 this.trigger('activate_node', { 'node' : this.get_node(obj) });
21133 },
21134 /**
21135 * applies the hover state on a node, called when a node is hovered by the user. Used internally.
21136 * @private
21137 * @name hover_node(obj)
21138 * @param {mixed} obj
21139 * @trigger hover_node.jstree
21140 */
21141 hover_node : function (obj) {
21142 obj = this.get_node(obj, true);
21143 if(!obj || !obj.length || obj.children('.jstree-hovered').length) {
21144 return false;
21145 }
21146 var o = this.element.find('.jstree-hovered'), t = this.element;
21147 if(o && o.length) { this.dehover_node(o); }
21148
21149 obj.children('.jstree-anchor').addClass('jstree-hovered');
21150 /**
21151 * triggered when an node is hovered
21152 * @event
21153 * @name hover_node.jstree
21154 * @param {Object} node
21155 */
21156 this.trigger('hover_node', { 'node' : this.get_node(obj) });
21157 setTimeout(function () { t.attr('aria-activedescendant', obj[0].id); }, 0);
21158 },
21159 /**
21160 * removes the hover state from a nodecalled when a node is no longer hovered by the user. Used internally.
21161 * @private
21162 * @name dehover_node(obj)
21163 * @param {mixed} obj
21164 * @trigger dehover_node.jstree
21165 */
21166 dehover_node : function (obj) {
21167 obj = this.get_node(obj, true);
21168 if(!obj || !obj.length || !obj.children('.jstree-hovered').length) {
21169 return false;
21170 }
21171 obj.children('.jstree-anchor').removeClass('jstree-hovered');
21172 /**
21173 * triggered when an node is no longer hovered
21174 * @event
21175 * @name dehover_node.jstree
21176 * @param {Object} node
21177 */
21178 this.trigger('dehover_node', { 'node' : this.get_node(obj) });
21179 },
21180 /**
21181 * select a node
21182 * @name select_node(obj [, supress_event, prevent_open])
21183 * @param {mixed} obj an array can be used to select multiple nodes
21184 * @param {Boolean} supress_event if set to `true` the `changed.jstree` event won't be triggered
21185 * @param {Boolean} prevent_open if set to `true` parents of the selected node won't be opened
21186 * @trigger select_node.jstree, changed.jstree
21187 */
21188 select_node : function (obj, supress_event, prevent_open, e) {
21189 var dom, t1, t2, th;
21190 if($.isArray(obj)) {
21191 obj = obj.slice();
21192 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
21193 this.select_node(obj[t1], supress_event, prevent_open, e);
21194 }
21195 return true;
21196 }
21197 obj = this.get_node(obj);
21198 if(!obj || obj.id === '#') {
21199 return false;
21200 }
21201 dom = this.get_node(obj, true);
21202 if(!obj.state.selected) {
21203 obj.state.selected = true;
21204 this._data.core.selected.push(obj.id);
21205 if(!prevent_open) {
21206 dom = this._open_to(obj);
21207 }
21208 if(dom && dom.length) {
21209 dom.attr('aria-selected', true).children('.jstree-anchor').addClass('jstree-clicked');
21210 }
21211 /**
21212 * triggered when an node is selected
21213 * @event
21214 * @name select_node.jstree
21215 * @param {Object} node
21216 * @param {Array} selected the current selection
21217 * @param {Object} event the event (if any) that triggered this select_node
21218 */
21219 this.trigger('select_node', { 'node' : obj, 'selected' : this._data.core.selected, 'event' : e });
21220 if(!supress_event) {
21221 /**
21222 * triggered when selection changes
21223 * @event
21224 * @name changed.jstree
21225 * @param {Object} node
21226 * @param {Object} action the action that caused the selection to change
21227 * @param {Array} selected the current selection
21228 * @param {Object} event the event (if any) that triggered this changed event
21229 */
21230 this.trigger('changed', { 'action' : 'select_node', 'node' : obj, 'selected' : this._data.core.selected, 'event' : e });
21231 }
21232 }
21233 },
21234 /**
21235 * deselect a node
21236 * @name deselect_node(obj [, supress_event])
21237 * @param {mixed} obj an array can be used to deselect multiple nodes
21238 * @param {Boolean} supress_event if set to `true` the `changed.jstree` event won't be triggered
21239 * @trigger deselect_node.jstree, changed.jstree
21240 */
21241 deselect_node : function (obj, supress_event, e) {
21242 var t1, t2, dom;
21243 if($.isArray(obj)) {
21244 obj = obj.slice();
21245 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
21246 this.deselect_node(obj[t1], supress_event, e);
21247 }
21248 return true;
21249 }
21250 obj = this.get_node(obj);
21251 if(!obj || obj.id === '#') {
21252 return false;
21253 }
21254 dom = this.get_node(obj, true);
21255 if(obj.state.selected) {
21256 obj.state.selected = false;
21257 this._data.core.selected = $.vakata.array_remove_item(this._data.core.selected, obj.id);
21258 if(dom.length) {
21259 dom.attr('aria-selected', false).children('.jstree-anchor').removeClass('jstree-clicked');
21260 }
21261 /**
21262 * triggered when an node is deselected
21263 * @event
21264 * @name deselect_node.jstree
21265 * @param {Object} node
21266 * @param {Array} selected the current selection
21267 * @param {Object} event the event (if any) that triggered this deselect_node
21268 */
21269 this.trigger('deselect_node', { 'node' : obj, 'selected' : this._data.core.selected, 'event' : e });
21270 if(!supress_event) {
21271 this.trigger('changed', { 'action' : 'deselect_node', 'node' : obj, 'selected' : this._data.core.selected, 'event' : e });
21272 }
21273 }
21274 },
21275 /**
21276 * select all nodes in the tree
21277 * @name select_all([supress_event])
21278 * @param {Boolean} supress_event if set to `true` the `changed.jstree` event won't be triggered
21279 * @trigger select_all.jstree, changed.jstree
21280 */
21281 select_all : function (supress_event) {
21282 var tmp = this._data.core.selected.concat([]), i, j;
21283 this._data.core.selected = this._model.data['#'].children_d.concat();
21284 for(i = 0, j = this._data.core.selected.length; i < j; i++) {
21285 if(this._model.data[this._data.core.selected[i]]) {
21286 this._model.data[this._data.core.selected[i]].state.selected = true;
21287 }
21288 }
21289 this.redraw(true);
21290 /**
21291 * triggered when all nodes are selected
21292 * @event
21293 * @name select_all.jstree
21294 * @param {Array} selected the current selection
21295 */
21296 this.trigger('select_all', { 'selected' : this._data.core.selected });
21297 if(!supress_event) {
21298 this.trigger('changed', { 'action' : 'select_all', 'selected' : this._data.core.selected, 'old_selection' : tmp });
21299 }
21300 },
21301 /**
21302 * deselect all selected nodes
21303 * @name deselect_all([supress_event])
21304 * @param {Boolean} supress_event if set to `true` the `changed.jstree` event won't be triggered
21305 * @trigger deselect_all.jstree, changed.jstree
21306 */
21307 deselect_all : function (supress_event) {
21308 var tmp = this._data.core.selected.concat([]), i, j;
21309 for(i = 0, j = this._data.core.selected.length; i < j; i++) {
21310 if(this._model.data[this._data.core.selected[i]]) {
21311 this._model.data[this._data.core.selected[i]].state.selected = false;
21312 }
21313 }
21314 this._data.core.selected = [];
21315 this.element.find('.jstree-clicked').removeClass('jstree-clicked').parent().attr('aria-selected', false);
21316 /**
21317 * triggered when all nodes are deselected
21318 * @event
21319 * @name deselect_all.jstree
21320 * @param {Object} node the previous selection
21321 * @param {Array} selected the current selection
21322 */
21323 this.trigger('deselect_all', { 'selected' : this._data.core.selected, 'node' : tmp });
21324 if(!supress_event) {
21325 this.trigger('changed', { 'action' : 'deselect_all', 'selected' : this._data.core.selected, 'old_selection' : tmp });
21326 }
21327 },
21328 /**
21329 * checks if a node is selected
21330 * @name is_selected(obj)
21331 * @param {mixed} obj
21332 * @return {Boolean}
21333 */
21334 is_selected : function (obj) {
21335 obj = this.get_node(obj);
21336 if(!obj || obj.id === '#') {
21337 return false;
21338 }
21339 return obj.state.selected;
21340 },
21341 /**
21342 * get an array of all selected nodes
21343 * @name get_selected([full])
21344 * @param {mixed} full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned
21345 * @return {Array}
21346 */
21347 get_selected : function (full) {
21348 return full ? $.map(this._data.core.selected, $.proxy(function (i) { return this.get_node(i); }, this)) : this._data.core.selected.slice();
21349 },
21350 /**
21351 * get an array of all top level selected nodes (ignoring children of selected nodes)
21352 * @name get_top_selected([full])
21353 * @param {mixed} full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned
21354 * @return {Array}
21355 */
21356 get_top_selected : function (full) {
21357 var tmp = this.get_selected(true),
21358 obj = {}, i, j, k, l;
21359 for(i = 0, j = tmp.length; i < j; i++) {
21360 obj[tmp[i].id] = tmp[i];
21361 }
21362 for(i = 0, j = tmp.length; i < j; i++) {
21363 for(k = 0, l = tmp[i].children_d.length; k < l; k++) {
21364 if(obj[tmp[i].children_d[k]]) {
21365 delete obj[tmp[i].children_d[k]];
21366 }
21367 }
21368 }
21369 tmp = [];
21370 for(i in obj) {
21371 if(obj.hasOwnProperty(i)) {
21372 tmp.push(i);
21373 }
21374 }
21375 return full ? $.map(tmp, $.proxy(function (i) { return this.get_node(i); }, this)) : tmp;
21376 },
21377 /**
21378 * get an array of all bottom level selected nodes (ignoring selected parents)
21379 * @name get_bottom_selected([full])
21380 * @param {mixed} full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned
21381 * @return {Array}
21382 */
21383 get_bottom_selected : function (full) {
21384 var tmp = this.get_selected(true),
21385 obj = [], i, j;
21386 for(i = 0, j = tmp.length; i < j; i++) {
21387 if(!tmp[i].children.length) {
21388 obj.push(tmp[i].id);
21389 }
21390 }
21391 return full ? $.map(obj, $.proxy(function (i) { return this.get_node(i); }, this)) : obj;
21392 },
21393 /**
21394 * gets the current state of the tree so that it can be restored later with `set_state(state)`. Used internally.
21395 * @name get_state()
21396 * @private
21397 * @return {Object}
21398 */
21399 get_state : function () {
21400 var state = {
21401 'core' : {
21402 'open' : [],
21403 'scroll' : {
21404 'left' : this.element.scrollLeft(),
21405 'top' : this.element.scrollTop()
21406 },
21407 /*!
21408 'themes' : {
21409 'name' : this.get_theme(),
21410 'icons' : this._data.core.themes.icons,
21411 'dots' : this._data.core.themes.dots
21412 },
21413 */
21414 'selected' : []
21415 }
21416 }, i;
21417 for(i in this._model.data) {
21418 if(this._model.data.hasOwnProperty(i)) {
21419 if(i !== '#') {
21420 if(this._model.data[i].state.opened) {
21421 state.core.open.push(i);
21422 }
21423 if(this._model.data[i].state.selected) {
21424 state.core.selected.push(i);
21425 }
21426 }
21427 }
21428 }
21429 return state;
21430 },
21431 /**
21432 * sets the state of the tree. Used internally.
21433 * @name set_state(state [, callback])
21434 * @private
21435 * @param {Object} state the state to restore
21436 * @param {Function} callback an optional function to execute once the state is restored.
21437 * @trigger set_state.jstree
21438 */
21439 set_state : function (state, callback) {
21440 if(state) {
21441 if(state.core) {
21442 var res, n, t, _this;
21443 if(state.core.open) {
21444 if(!$.isArray(state.core.open)) {
21445 delete state.core.open;
21446 this.set_state(state, callback);
21447 return false;
21448 }
21449 res = true;
21450 n = false;
21451 t = this;
21452 $.each(state.core.open.concat([]), function (i, v) {
21453 n = t.get_node(v);
21454 if(n) {
21455 if(t.is_loaded(v)) {
21456 if(t.is_closed(v)) {
21457 t.open_node(v, false, 0);
21458 }
21459 if(state && state.core && state.core.open) {
21460 $.vakata.array_remove_item(state.core.open, v);
21461 }
21462 }
21463 else {
21464 if(!t.is_loading(v)) {
21465 t.open_node(v, $.proxy(function (o, s) {
21466 if(!s && state && state.core && state.core.open) {
21467 $.vakata.array_remove_item(state.core.open, o.id);
21468 }
21469 this.set_state(state, callback);
21470 }, t), 0);
21471 }
21472 // there will be some async activity - so wait for it
21473 res = false;
21474 }
21475 }
21476 });
21477 if(res) {
21478 delete state.core.open;
21479 this.set_state(state, callback);
21480 }
21481 return false;
21482 }
21483 if(state.core.scroll) {
21484 if(state.core.scroll && state.core.scroll.left !== undefined) {
21485 this.element.scrollLeft(state.core.scroll.left);
21486 }
21487 if(state.core.scroll && state.core.scroll.top !== undefined) {
21488 this.element.scrollTop(state.core.scroll.top);
21489 }
21490 delete state.core.scroll;
21491 this.set_state(state, callback);
21492 return false;
21493 }
21494 /*!
21495 if(state.core.themes) {
21496 if(state.core.themes.name) {
21497 this.set_theme(state.core.themes.name);
21498 }
21499 if(typeof state.core.themes.dots !== 'undefined') {
21500 this[ state.core.themes.dots ? "show_dots" : "hide_dots" ]();
21501 }
21502 if(typeof state.core.themes.icons !== 'undefined') {
21503 this[ state.core.themes.icons ? "show_icons" : "hide_icons" ]();
21504 }
21505 delete state.core.themes;
21506 delete state.core.open;
21507 this.set_state(state, callback);
21508 return false;
21509 }
21510 */
21511 if(state.core.selected) {
21512 _this = this;
21513 this.deselect_all();
21514 $.each(state.core.selected, function (i, v) {
21515 _this.select_node(v);
21516 });
21517 delete state.core.selected;
21518 this.set_state(state, callback);
21519 return false;
21520 }
21521 if($.isEmptyObject(state.core)) {
21522 delete state.core;
21523 this.set_state(state, callback);
21524 return false;
21525 }
21526 }
21527 if($.isEmptyObject(state)) {
21528 state = null;
21529 if(callback) { callback.call(this); }
21530 /**
21531 * triggered when a `set_state` call completes
21532 * @event
21533 * @name set_state.jstree
21534 */
21535 this.trigger('set_state');
21536 return false;
21537 }
21538 return true;
21539 }
21540 return false;
21541 },
21542 /**
21543 * refreshes the tree - all nodes are reloaded with calls to `load_node`.
21544 * @name refresh()
21545 * @param {Boolean} skip_loading an option to skip showing the loading indicator
21546 * @param {Mixed} forget_state if set to `true` state will not be reapplied, if set to a function (receiving the current state as argument) the result of that function will be used as state
21547 * @trigger refresh.jstree
21548 */
21549 refresh : function (skip_loading, forget_state) {
21550 this._data.core.state = forget_state === true ? {} : this.get_state();
21551 if(forget_state && $.isFunction(forget_state)) { this._data.core.state = forget_state.call(this, this._data.core.state); }
21552 this._cnt = 0;
21553 this._model.data = {
21554 '#' : {
21555 id : '#',
21556 parent : null,
21557 parents : [],
21558 children : [],
21559 children_d : [],
21560 state : { loaded : false }
21561 }
21562 };
21563 var c = this.get_container_ul()[0].className;
21564 if(!skip_loading) {
21565 this.element.html("<"+"ul class='"+c+"' role='group'><"+"li class='jstree-initial-node jstree-loading jstree-leaf jstree-last' role='treeitem' id='j"+this._id+"_loading'><i class='jstree-icon jstree-ocl'></i><"+"a class='jstree-anchor' href='#'><i class='jstree-icon jstree-themeicon-hidden'></i>" + this.get_string("Loading ...") + "</a></li></ul>");
21566 this.element.attr('aria-activedescendant','j'+this._id+'_loading');
21567 }
21568 this.load_node('#', function (o, s) {
21569 if(s) {
21570 this.get_container_ul()[0].className = c;
21571 if(this._firstChild(this.get_container_ul()[0])) {
21572 this.element.attr('aria-activedescendant',this._firstChild(this.get_container_ul()[0]).id);
21573 }
21574 this.set_state($.extend(true, {}, this._data.core.state), function () {
21575 /**
21576 * triggered when a `refresh` call completes
21577 * @event
21578 * @name refresh.jstree
21579 */
21580 this.trigger('refresh');
21581 });
21582 }
21583 this._data.core.state = null;
21584 });
21585 },
21586 /**
21587 * refreshes a node in the tree (reload its children) all opened nodes inside that node are reloaded with calls to `load_node`.
21588 * @name refresh_node(obj)
21589 * @param {mixed} obj the node
21590 * @trigger refresh_node.jstree
21591 */
21592 refresh_node : function (obj) {
21593 obj = this.get_node(obj);
21594 if(!obj || obj.id === '#') { return false; }
21595 var opened = [], to_load = [], s = this._data.core.selected.concat([]);
21596 to_load.push(obj.id);
21597 if(obj.state.opened === true) { opened.push(obj.id); }
21598 this.get_node(obj, true).find('.jstree-open').each(function() { opened.push(this.id); });
21599 this._load_nodes(to_load, $.proxy(function (nodes) {
21600 this.open_node(opened, false, 0);
21601 this.select_node(this._data.core.selected);
21602 /**
21603 * triggered when a node is refreshed
21604 * @event
21605 * @name refresh_node.jstree
21606 * @param {Object} node - the refreshed node
21607 * @param {Array} nodes - an array of the IDs of the nodes that were reloaded
21608 */
21609 this.trigger('refresh_node', { 'node' : obj, 'nodes' : nodes });
21610 }, this));
21611 },
21612 /**
21613 * set (change) the ID of a node
21614 * @name set_id(obj, id)
21615 * @param {mixed} obj the node
21616 * @param {String} id the new ID
21617 * @return {Boolean}
21618 */
21619 set_id : function (obj, id) {
21620 obj = this.get_node(obj);
21621 if(!obj || obj.id === '#') { return false; }
21622 var i, j, m = this._model.data;
21623 id = id.toString();
21624 // update parents (replace current ID with new one in children and children_d)
21625 m[obj.parent].children[$.inArray(obj.id, m[obj.parent].children)] = id;
21626 for(i = 0, j = obj.parents.length; i < j; i++) {
21627 m[obj.parents[i]].children_d[$.inArray(obj.id, m[obj.parents[i]].children_d)] = id;
21628 }
21629 // update children (replace current ID with new one in parent and parents)
21630 for(i = 0, j = obj.children.length; i < j; i++) {
21631 m[obj.children[i]].parent = id;
21632 }
21633 for(i = 0, j = obj.children_d.length; i < j; i++) {
21634 m[obj.children_d[i]].parents[$.inArray(obj.id, m[obj.children_d[i]].parents)] = id;
21635 }
21636 i = $.inArray(obj.id, this._data.core.selected);
21637 if(i !== -1) { this._data.core.selected[i] = id; }
21638 // update model and obj itself (obj.id, this._model.data[KEY])
21639 i = this.get_node(obj.id, true);
21640 if(i) {
21641 i.attr('id', id);
21642 }
21643 delete m[obj.id];
21644 obj.id = id;
21645 m[id] = obj;
21646 return true;
21647 },
21648 /**
21649 * get the text value of a node
21650 * @name get_text(obj)
21651 * @param {mixed} obj the node
21652 * @return {String}
21653 */
21654 get_text : function (obj) {
21655 obj = this.get_node(obj);
21656 return (!obj || obj.id === '#') ? false : obj.text;
21657 },
21658 /**
21659 * set the text value of a node. Used internally, please use `rename_node(obj, val)`.
21660 * @private
21661 * @name set_text(obj, val)
21662 * @param {mixed} obj the node, you can pass an array to set the text on multiple nodes
21663 * @param {String} val the new text value
21664 * @return {Boolean}
21665 * @trigger set_text.jstree
21666 */
21667 set_text : function (obj, val) {
21668 var t1, t2;
21669 if($.isArray(obj)) {
21670 obj = obj.slice();
21671 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
21672 this.set_text(obj[t1], val);
21673 }
21674 return true;
21675 }
21676 obj = this.get_node(obj);
21677 if(!obj || obj.id === '#') { return false; }
21678 obj.text = val;
21679 if(this.get_node(obj, true).length) {
21680 this.redraw_node(obj.id);
21681 }
21682 /**
21683 * triggered when a node text value is changed
21684 * @event
21685 * @name set_text.jstree
21686 * @param {Object} obj
21687 * @param {String} text the new value
21688 */
21689 this.trigger('set_text',{ "obj" : obj, "text" : val });
21690 return true;
21691 },
21692 /**
21693 * gets a JSON representation of a node (or the whole tree)
21694 * @name get_json([obj, options])
21695 * @param {mixed} obj
21696 * @param {Object} options
21697 * @param {Boolean} options.no_state do not return state information
21698 * @param {Boolean} options.no_id do not return ID
21699 * @param {Boolean} options.no_children do not include children
21700 * @param {Boolean} options.no_data do not include node data
21701 * @param {Boolean} options.flat return flat JSON instead of nested
21702 * @return {Object}
21703 */
21704 get_json : function (obj, options, flat) {
21705 obj = this.get_node(obj || '#');
21706 if(!obj) { return false; }
21707 if(options && options.flat && !flat) { flat = []; }
21708 var tmp = {
21709 'id' : obj.id,
21710 'text' : obj.text,
21711 'icon' : this.get_icon(obj),
21712 'li_attr' : $.extend(true, {}, obj.li_attr),
21713 'a_attr' : $.extend(true, {}, obj.a_attr),
21714 'state' : {},
21715 'data' : options && options.no_data ? false : $.extend(true, {}, obj.data)
21716 //( this.get_node(obj, true).length ? this.get_node(obj, true).data() : obj.data ),
21717 }, i, j;
21718 if(options && options.flat) {
21719 tmp.parent = obj.parent;
21720 }
21721 else {
21722 tmp.children = [];
21723 }
21724 if(!options || !options.no_state) {
21725 for(i in obj.state) {
21726 if(obj.state.hasOwnProperty(i)) {
21727 tmp.state[i] = obj.state[i];
21728 }
21729 }
21730 }
21731 if(options && options.no_id) {
21732 delete tmp.id;
21733 if(tmp.li_attr && tmp.li_attr.id) {
21734 delete tmp.li_attr.id;
21735 }
21736 if(tmp.a_attr && tmp.a_attr.id) {
21737 delete tmp.a_attr.id;
21738 }
21739 }
21740 if(options && options.flat && obj.id !== '#') {
21741 flat.push(tmp);
21742 }
21743 if(!options || !options.no_children) {
21744 for(i = 0, j = obj.children.length; i < j; i++) {
21745 if(options && options.flat) {
21746 this.get_json(obj.children[i], options, flat);
21747 }
21748 else {
21749 tmp.children.push(this.get_json(obj.children[i], options));
21750 }
21751 }
21752 }
21753 return options && options.flat ? flat : (obj.id === '#' ? tmp.children : tmp);
21754 },
21755 /**
21756 * create a new node (do not confuse with load_node)
21757 * @name create_node([obj, node, pos, callback, is_loaded])
21758 * @param {mixed} par the parent node (to create a root node use either "#" (string) or `null`)
21759 * @param {mixed} node the data for the new node (a valid JSON object, or a simple string with the name)
21760 * @param {mixed} pos the index at which to insert the node, "first" and "last" are also supported, default is "last"
21761 * @param {Function} callback a function to be called once the node is created
21762 * @param {Boolean} is_loaded internal argument indicating if the parent node was succesfully loaded
21763 * @return {String} the ID of the newly create node
21764 * @trigger model.jstree, create_node.jstree
21765 */
21766 create_node : function (par, node, pos, callback, is_loaded) {
21767 if(par === null) { par = "#"; }
21768 par = this.get_node(par);
21769 if(!par) { return false; }
21770 pos = pos === undefined ? "last" : pos;
21771 if(!pos.toString().match(/^(before|after)$/) && !is_loaded && !this.is_loaded(par)) {
21772 return this.load_node(par, function () { this.create_node(par, node, pos, callback, true); });
21773 }
21774 if(!node) { node = { "text" : this.get_string('New node') }; }
21775 if(typeof node === "string") { node = { "text" : node }; }
21776 if(node.text === undefined) { node.text = this.get_string('New node'); }
21777 var tmp, dpc, i, j;
21778
21779 if(par.id === '#') {
21780 if(pos === "before") { pos = "first"; }
21781 if(pos === "after") { pos = "last"; }
21782 }
21783 switch(pos) {
21784 case "before":
21785 tmp = this.get_node(par.parent);
21786 pos = $.inArray(par.id, tmp.children);
21787 par = tmp;
21788 break;
21789 case "after" :
21790 tmp = this.get_node(par.parent);
21791 pos = $.inArray(par.id, tmp.children) + 1;
21792 par = tmp;
21793 break;
21794 case "inside":
21795 case "first":
21796 pos = 0;
21797 break;
21798 case "last":
21799 pos = par.children.length;
21800 break;
21801 default:
21802 if(!pos) { pos = 0; }
21803 break;
21804 }
21805 if(pos > par.children.length) { pos = par.children.length; }
21806 if(!node.id) { node.id = true; }
21807 if(!this.check("create_node", node, par, pos)) {
21808 this.settings.core.error.call(this, this._data.core.last_error);
21809 return false;
21810 }
21811 if(node.id === true) { delete node.id; }
21812 node = this._parse_model_from_json(node, par.id, par.parents.concat());
21813 if(!node) { return false; }
21814 tmp = this.get_node(node);
21815 dpc = [];
21816 dpc.push(node);
21817 dpc = dpc.concat(tmp.children_d);
21818 this.trigger('model', { "nodes" : dpc, "parent" : par.id });
21819
21820 par.children_d = par.children_d.concat(dpc);
21821 for(i = 0, j = par.parents.length; i < j; i++) {
21822 this._model.data[par.parents[i]].children_d = this._model.data[par.parents[i]].children_d.concat(dpc);
21823 }
21824 node = tmp;
21825 tmp = [];
21826 for(i = 0, j = par.children.length; i < j; i++) {
21827 tmp[i >= pos ? i+1 : i] = par.children[i];
21828 }
21829 tmp[pos] = node.id;
21830 par.children = tmp;
21831
21832 this.redraw_node(par, true);
21833 if(callback) { callback.call(this, this.get_node(node)); }
21834 /**
21835 * triggered when a node is created
21836 * @event
21837 * @name create_node.jstree
21838 * @param {Object} node
21839 * @param {String} parent the parent's ID
21840 * @param {Number} position the position of the new node among the parent's children
21841 */
21842 this.trigger('create_node', { "node" : this.get_node(node), "parent" : par.id, "position" : pos });
21843 return node.id;
21844 },
21845 /**
21846 * set the text value of a node
21847 * @name rename_node(obj, val)
21848 * @param {mixed} obj the node, you can pass an array to rename multiple nodes to the same name
21849 * @param {String} val the new text value
21850 * @return {Boolean}
21851 * @trigger rename_node.jstree
21852 */
21853 rename_node : function (obj, val) {
21854 var t1, t2, old;
21855 if($.isArray(obj)) {
21856 obj = obj.slice();
21857 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
21858 this.rename_node(obj[t1], val);
21859 }
21860 return true;
21861 }
21862 obj = this.get_node(obj);
21863 if(!obj || obj.id === '#') { return false; }
21864 old = obj.text;
21865 if(!this.check("rename_node", obj, this.get_parent(obj), val)) {
21866 this.settings.core.error.call(this, this._data.core.last_error);
21867 return false;
21868 }
21869 this.set_text(obj, val); // .apply(this, Array.prototype.slice.call(arguments))
21870 /**
21871 * triggered when a node is renamed
21872 * @event
21873 * @name rename_node.jstree
21874 * @param {Object} node
21875 * @param {String} text the new value
21876 * @param {String} old the old value
21877 */
21878 this.trigger('rename_node', { "node" : obj, "text" : val, "old" : old });
21879 return true;
21880 },
21881 /**
21882 * remove a node
21883 * @name delete_node(obj)
21884 * @param {mixed} obj the node, you can pass an array to delete multiple nodes
21885 * @return {Boolean}
21886 * @trigger delete_node.jstree, changed.jstree
21887 */
21888 delete_node : function (obj) {
21889 var t1, t2, par, pos, tmp, i, j, k, l, c;
21890 if($.isArray(obj)) {
21891 obj = obj.slice();
21892 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
21893 this.delete_node(obj[t1]);
21894 }
21895 return true;
21896 }
21897 obj = this.get_node(obj);
21898 if(!obj || obj.id === '#') { return false; }
21899 par = this.get_node(obj.parent);
21900 pos = $.inArray(obj.id, par.children);
21901 c = false;
21902 if(!this.check("delete_node", obj, par, pos)) {
21903 this.settings.core.error.call(this, this._data.core.last_error);
21904 return false;
21905 }
21906 if(pos !== -1) {
21907 par.children = $.vakata.array_remove(par.children, pos);
21908 }
21909 tmp = obj.children_d.concat([]);
21910 tmp.push(obj.id);
21911 for(k = 0, l = tmp.length; k < l; k++) {
21912 for(i = 0, j = obj.parents.length; i < j; i++) {
21913 pos = $.inArray(tmp[k], this._model.data[obj.parents[i]].children_d);
21914 if(pos !== -1) {
21915 this._model.data[obj.parents[i]].children_d = $.vakata.array_remove(this._model.data[obj.parents[i]].children_d, pos);
21916 }
21917 }
21918 if(this._model.data[tmp[k]].state.selected) {
21919 c = true;
21920 pos = $.inArray(tmp[k], this._data.core.selected);
21921 if(pos !== -1) {
21922 this._data.core.selected = $.vakata.array_remove(this._data.core.selected, pos);
21923 }
21924 }
21925 }
21926 /**
21927 * triggered when a node is deleted
21928 * @event
21929 * @name delete_node.jstree
21930 * @param {Object} node
21931 * @param {String} parent the parent's ID
21932 */
21933 this.trigger('delete_node', { "node" : obj, "parent" : par.id });
21934 if(c) {
21935 this.trigger('changed', { 'action' : 'delete_node', 'node' : obj, 'selected' : this._data.core.selected, 'parent' : par.id });
21936 }
21937 for(k = 0, l = tmp.length; k < l; k++) {
21938 delete this._model.data[tmp[k]];
21939 }
21940 this.redraw_node(par, true);
21941 return true;
21942 },
21943 /**
21944 * check if an operation is premitted on the tree. Used internally.
21945 * @private
21946 * @name check(chk, obj, par, pos)
21947 * @param {String} chk the operation to check, can be "create_node", "rename_node", "delete_node", "copy_node" or "move_node"
21948 * @param {mixed} obj the node
21949 * @param {mixed} par the parent
21950 * @param {mixed} pos the position to insert at, or if "rename_node" - the new name
21951 * @param {mixed} more some various additional information, for example if a "move_node" operations is triggered by DND this will be the hovered node
21952 * @return {Boolean}
21953 */
21954 check : function (chk, obj, par, pos, more) {
21955 obj = obj && obj.id ? obj : this.get_node(obj);
21956 par = par && par.id ? par : this.get_node(par);
21957 var tmp = chk.match(/^move_node|copy_node|create_node$/i) ? par : obj,
21958 chc = this.settings.core.check_callback;
21959 if(chk === "move_node" || chk === "copy_node") {
21960 if((!more || !more.is_multi) && (obj.id === par.id || $.inArray(obj.id, par.children) === pos || $.inArray(par.id, obj.children_d) !== -1)) {
21961 this._data.core.last_error = { 'error' : 'check', 'plugin' : 'core', 'id' : 'core_01', 'reason' : 'Moving parent inside child', 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
21962 return false;
21963 }
21964 }
21965 if(tmp && tmp.data) { tmp = tmp.data; }
21966 if(tmp && tmp.functions && (tmp.functions[chk] === false || tmp.functions[chk] === true)) {
21967 if(tmp.functions[chk] === false) {
21968 this._data.core.last_error = { 'error' : 'check', 'plugin' : 'core', 'id' : 'core_02', 'reason' : 'Node data prevents function: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
21969 }
21970 return tmp.functions[chk];
21971 }
21972 if(chc === false || ($.isFunction(chc) && chc.call(this, chk, obj, par, pos, more) === false) || (chc && chc[chk] === false)) {
21973 this._data.core.last_error = { 'error' : 'check', 'plugin' : 'core', 'id' : 'core_03', 'reason' : 'User config for core.check_callback prevents function: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
21974 return false;
21975 }
21976 return true;
21977 },
21978 /**
21979 * get the last error
21980 * @name last_error()
21981 * @return {Object}
21982 */
21983 last_error : function () {
21984 return this._data.core.last_error;
21985 },
21986 /**
21987 * move a node to a new parent
21988 * @name move_node(obj, par [, pos, callback, is_loaded])
21989 * @param {mixed} obj the node to move, pass an array to move multiple nodes
21990 * @param {mixed} par the new parent
21991 * @param {mixed} pos the position to insert at (besides integer values, "first" and "last" are supported, as well as "before" and "after"), defaults to integer `0`
21992 * @param {function} callback a function to call once the move is completed, receives 3 arguments - the node, the new parent and the position
21993 * @param {Boolean} internal parameter indicating if the parent node has been loaded
21994 * @param {Boolean} internal parameter indicating if the tree should be redrawn
21995 * @trigger move_node.jstree
21996 */
21997 move_node : function (obj, par, pos, callback, is_loaded, skip_redraw) {
21998 var t1, t2, old_par, old_pos, new_par, old_ins, is_multi, dpc, tmp, i, j, k, l, p;
21999
22000 par = this.get_node(par);
22001 pos = pos === undefined ? 0 : pos;
22002 if(!par) { return false; }
22003 if(!pos.toString().match(/^(before|after)$/) && !is_loaded && !this.is_loaded(par)) {
22004 return this.load_node(par, function () { this.move_node(obj, par, pos, callback, true); });
22005 }
22006
22007 if($.isArray(obj)) {
22008 obj = obj.slice();
22009 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
22010 if(this.move_node(obj[t1], par, pos, callback, is_loaded, true)) {
22011 par = obj[t1];
22012 pos = "after";
22013 }
22014 }
22015 this.redraw();
22016 return true;
22017 }
22018 obj = obj && obj.id ? obj : this.get_node(obj);
22019
22020 if(!obj || obj.id === '#') { return false; }
22021
22022 old_par = (obj.parent || '#').toString();
22023 new_par = (!pos.toString().match(/^(before|after)$/) || par.id === '#') ? par : this.get_node(par.parent);
22024 old_ins = obj.instance ? obj.instance : (this._model.data[obj.id] ? this : $.jstree.reference(obj.id));
22025 is_multi = !old_ins || !old_ins._id || (this._id !== old_ins._id);
22026 old_pos = old_ins && old_ins._id && old_par && old_ins._model.data[old_par] && old_ins._model.data[old_par].children ? $.inArray(obj.id, old_ins._model.data[old_par].children) : -1;
22027 if(is_multi) {
22028 if(this.copy_node(obj, par, pos, callback, is_loaded)) {
22029 if(old_ins) { old_ins.delete_node(obj); }
22030 return true;
22031 }
22032 return false;
22033 }
22034 //var m = this._model.data;
22035 if(par.id === '#') {
22036 if(pos === "before") { pos = "first"; }
22037 if(pos === "after") { pos = "last"; }
22038 }
22039 switch(pos) {
22040 case "before":
22041 pos = $.inArray(par.id, new_par.children);
22042 break;
22043 case "after" :
22044 pos = $.inArray(par.id, new_par.children) + 1;
22045 break;
22046 case "inside":
22047 case "first":
22048 pos = 0;
22049 break;
22050 case "last":
22051 pos = new_par.children.length;
22052 break;
22053 default:
22054 if(!pos) { pos = 0; }
22055 break;
22056 }
22057 if(pos > new_par.children.length) { pos = new_par.children.length; }
22058 if(!this.check("move_node", obj, new_par, pos, { 'core' : true, 'is_multi' : (old_ins && old_ins._id && old_ins._id !== this._id), 'is_foreign' : (!old_ins || !old_ins._id) })) {
22059 this.settings.core.error.call(this, this._data.core.last_error);
22060 return false;
22061 }
22062 if(obj.parent === new_par.id) {
22063 dpc = new_par.children.concat();
22064 tmp = $.inArray(obj.id, dpc);
22065 if(tmp !== -1) {
22066 dpc = $.vakata.array_remove(dpc, tmp);
22067 if(pos > tmp) { pos--; }
22068 }
22069 tmp = [];
22070 for(i = 0, j = dpc.length; i < j; i++) {
22071 tmp[i >= pos ? i+1 : i] = dpc[i];
22072 }
22073 tmp[pos] = obj.id;
22074 new_par.children = tmp;
22075 this._node_changed(new_par.id);
22076 this.redraw(new_par.id === '#');
22077 }
22078 else {
22079 // clean old parent and up
22080 tmp = obj.children_d.concat();
22081 tmp.push(obj.id);
22082 for(i = 0, j = obj.parents.length; i < j; i++) {
22083 dpc = [];
22084 p = old_ins._model.data[obj.parents[i]].children_d;
22085 for(k = 0, l = p.length; k < l; k++) {
22086 if($.inArray(p[k], tmp) === -1) {
22087 dpc.push(p[k]);
22088 }
22089 }
22090 old_ins._model.data[obj.parents[i]].children_d = dpc;
22091 }
22092 old_ins._model.data[old_par].children = $.vakata.array_remove_item(old_ins._model.data[old_par].children, obj.id);
22093
22094 // insert into new parent and up
22095 for(i = 0, j = new_par.parents.length; i < j; i++) {
22096 this._model.data[new_par.parents[i]].children_d = this._model.data[new_par.parents[i]].children_d.concat(tmp);
22097 }
22098 dpc = [];
22099 for(i = 0, j = new_par.children.length; i < j; i++) {
22100 dpc[i >= pos ? i+1 : i] = new_par.children[i];
22101 }
22102 dpc[pos] = obj.id;
22103 new_par.children = dpc;
22104 new_par.children_d.push(obj.id);
22105 new_par.children_d = new_par.children_d.concat(obj.children_d);
22106
22107 // update object
22108 obj.parent = new_par.id;
22109 tmp = new_par.parents.concat();
22110 tmp.unshift(new_par.id);
22111 p = obj.parents.length;
22112 obj.parents = tmp;
22113
22114 // update object children
22115 tmp = tmp.concat();
22116 for(i = 0, j = obj.children_d.length; i < j; i++) {
22117 this._model.data[obj.children_d[i]].parents = this._model.data[obj.children_d[i]].parents.slice(0,p*-1);
22118 Array.prototype.push.apply(this._model.data[obj.children_d[i]].parents, tmp);
22119 }
22120
22121 if(old_par === '#' || new_par.id === '#') {
22122 this._model.force_full_redraw = true;
22123 }
22124 if(!this._model.force_full_redraw) {
22125 this._node_changed(old_par);
22126 this._node_changed(new_par.id);
22127 }
22128 if(!skip_redraw) {
22129 this.redraw();
22130 }
22131 }
22132 if(callback) { callback.call(this, obj, new_par, pos); }
22133 /**
22134 * triggered when a node is moved
22135 * @event
22136 * @name move_node.jstree
22137 * @param {Object} node
22138 * @param {String} parent the parent's ID
22139 * @param {Number} position the position of the node among the parent's children
22140 * @param {String} old_parent the old parent of the node
22141 * @param {Number} old_position the old position of the node
22142 * @param {Boolean} is_multi do the node and new parent belong to different instances
22143 * @param {jsTree} old_instance the instance the node came from
22144 * @param {jsTree} new_instance the instance of the new parent
22145 */
22146 this.trigger('move_node', { "node" : obj, "parent" : new_par.id, "position" : pos, "old_parent" : old_par, "old_position" : old_pos, 'is_multi' : (old_ins && old_ins._id && old_ins._id !== this._id), 'is_foreign' : (!old_ins || !old_ins._id), 'old_instance' : old_ins, 'new_instance' : this });
22147 return true;
22148 },
22149 /**
22150 * copy a node to a new parent
22151 * @name copy_node(obj, par [, pos, callback, is_loaded])
22152 * @param {mixed} obj the node to copy, pass an array to copy multiple nodes
22153 * @param {mixed} par the new parent
22154 * @param {mixed} pos the position to insert at (besides integer values, "first" and "last" are supported, as well as "before" and "after"), defaults to integer `0`
22155 * @param {function} callback a function to call once the move is completed, receives 3 arguments - the node, the new parent and the position
22156 * @param {Boolean} internal parameter indicating if the parent node has been loaded
22157 * @param {Boolean} internal parameter indicating if the tree should be redrawn
22158 * @trigger model.jstree copy_node.jstree
22159 */
22160 copy_node : function (obj, par, pos, callback, is_loaded, skip_redraw) {
22161 var t1, t2, dpc, tmp, i, j, node, old_par, new_par, old_ins, is_multi;
22162
22163 par = this.get_node(par);
22164 pos = pos === undefined ? 0 : pos;
22165 if(!par) { return false; }
22166 if(!pos.toString().match(/^(before|after)$/) && !is_loaded && !this.is_loaded(par)) {
22167 return this.load_node(par, function () { this.copy_node(obj, par, pos, callback, true); });
22168 }
22169
22170 if($.isArray(obj)) {
22171 obj = obj.slice();
22172 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
22173 tmp = this.copy_node(obj[t1], par, pos, callback, is_loaded, true);
22174 if(tmp) {
22175 par = tmp;
22176 pos = "after";
22177 }
22178 }
22179 this.redraw();
22180 return true;
22181 }
22182 obj = obj && obj.id ? obj : this.get_node(obj);
22183 if(!obj || obj.id === '#') { return false; }
22184
22185 old_par = (obj.parent || '#').toString();
22186 new_par = (!pos.toString().match(/^(before|after)$/) || par.id === '#') ? par : this.get_node(par.parent);
22187 old_ins = obj.instance ? obj.instance : (this._model.data[obj.id] ? this : $.jstree.reference(obj.id));
22188 is_multi = !old_ins || !old_ins._id || (this._id !== old_ins._id);
22189 if(par.id === '#') {
22190 if(pos === "before") { pos = "first"; }
22191 if(pos === "after") { pos = "last"; }
22192 }
22193 switch(pos) {
22194 case "before":
22195 pos = $.inArray(par.id, new_par.children);
22196 break;
22197 case "after" :
22198 pos = $.inArray(par.id, new_par.children) + 1;
22199 break;
22200 case "inside":
22201 case "first":
22202 pos = 0;
22203 break;
22204 case "last":
22205 pos = new_par.children.length;
22206 break;
22207 default:
22208 if(!pos) { pos = 0; }
22209 break;
22210 }
22211 if(pos > new_par.children.length) { pos = new_par.children.length; }
22212 if(!this.check("copy_node", obj, new_par, pos, { 'core' : true, 'is_multi' : (old_ins && old_ins._id && old_ins._id !== this._id), 'is_foreign' : (!old_ins || !old_ins._id) })) {
22213 this.settings.core.error.call(this, this._data.core.last_error);
22214 return false;
22215 }
22216 node = old_ins ? old_ins.get_json(obj, { no_id : true, no_data : true, no_state : true }) : obj;
22217 if(!node) { return false; }
22218 if(node.id === true) { delete node.id; }
22219 node = this._parse_model_from_json(node, new_par.id, new_par.parents.concat());
22220 if(!node) { return false; }
22221 tmp = this.get_node(node);
22222 if(obj && obj.state && obj.state.loaded === false) { tmp.state.loaded = false; }
22223 dpc = [];
22224 dpc.push(node);
22225 dpc = dpc.concat(tmp.children_d);
22226 this.trigger('model', { "nodes" : dpc, "parent" : new_par.id });
22227
22228 // insert into new parent and up
22229 for(i = 0, j = new_par.parents.length; i < j; i++) {
22230 this._model.data[new_par.parents[i]].children_d = this._model.data[new_par.parents[i]].children_d.concat(dpc);
22231 }
22232 dpc = [];
22233 for(i = 0, j = new_par.children.length; i < j; i++) {
22234 dpc[i >= pos ? i+1 : i] = new_par.children[i];
22235 }
22236 dpc[pos] = tmp.id;
22237 new_par.children = dpc;
22238 new_par.children_d.push(tmp.id);
22239 new_par.children_d = new_par.children_d.concat(tmp.children_d);
22240
22241 if(new_par.id === '#') {
22242 this._model.force_full_redraw = true;
22243 }
22244 if(!this._model.force_full_redraw) {
22245 this._node_changed(new_par.id);
22246 }
22247 if(!skip_redraw) {
22248 this.redraw(new_par.id === '#');
22249 }
22250 if(callback) { callback.call(this, tmp, new_par, pos); }
22251 /**
22252 * triggered when a node is copied
22253 * @event
22254 * @name copy_node.jstree
22255 * @param {Object} node the copied node
22256 * @param {Object} original the original node
22257 * @param {String} parent the parent's ID
22258 * @param {Number} position the position of the node among the parent's children
22259 * @param {String} old_parent the old parent of the node
22260 * @param {Number} old_position the position of the original node
22261 * @param {Boolean} is_multi do the node and new parent belong to different instances
22262 * @param {jsTree} old_instance the instance the node came from
22263 * @param {jsTree} new_instance the instance of the new parent
22264 */
22265 this.trigger('copy_node', { "node" : tmp, "original" : obj, "parent" : new_par.id, "position" : pos, "old_parent" : old_par, "old_position" : old_ins && old_ins._id && old_par && old_ins._model.data[old_par] && old_ins._model.data[old_par].children ? $.inArray(obj.id, old_ins._model.data[old_par].children) : -1,'is_multi' : (old_ins && old_ins._id && old_ins._id !== this._id), 'is_foreign' : (!old_ins || !old_ins._id), 'old_instance' : old_ins, 'new_instance' : this });
22266 return tmp.id;
22267 },
22268 /**
22269 * cut a node (a later call to `paste(obj)` would move the node)
22270 * @name cut(obj)
22271 * @param {mixed} obj multiple objects can be passed using an array
22272 * @trigger cut.jstree
22273 */
22274 cut : function (obj) {
22275 if(!obj) { obj = this._data.core.selected.concat(); }
22276 if(!$.isArray(obj)) { obj = [obj]; }
22277 if(!obj.length) { return false; }
22278 var tmp = [], o, t1, t2;
22279 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
22280 o = this.get_node(obj[t1]);
22281 if(o && o.id && o.id !== '#') { tmp.push(o); }
22282 }
22283 if(!tmp.length) { return false; }
22284 ccp_node = tmp;
22285 ccp_inst = this;
22286 ccp_mode = 'move_node';
22287 /**
22288 * triggered when nodes are added to the buffer for moving
22289 * @event
22290 * @name cut.jstree
22291 * @param {Array} node
22292 */
22293 this.trigger('cut', { "node" : obj });
22294 },
22295 /**
22296 * copy a node (a later call to `paste(obj)` would copy the node)
22297 * @name copy(obj)
22298 * @param {mixed} obj multiple objects can be passed using an array
22299 * @trigger copy.jstre
22300 */
22301 copy : function (obj) {
22302 if(!obj) { obj = this._data.core.selected.concat(); }
22303 if(!$.isArray(obj)) { obj = [obj]; }
22304 if(!obj.length) { return false; }
22305 var tmp = [], o, t1, t2;
22306 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
22307 o = this.get_node(obj[t1]);
22308 if(o && o.id && o.id !== '#') { tmp.push(o); }
22309 }
22310 if(!tmp.length) { return false; }
22311 ccp_node = tmp;
22312 ccp_inst = this;
22313 ccp_mode = 'copy_node';
22314 /**
22315 * triggered when nodes are added to the buffer for copying
22316 * @event
22317 * @name copy.jstree
22318 * @param {Array} node
22319 */
22320 this.trigger('copy', { "node" : obj });
22321 },
22322 /**
22323 * get the current buffer (any nodes that are waiting for a paste operation)
22324 * @name get_buffer()
22325 * @return {Object} an object consisting of `mode` ("copy_node" or "move_node"), `node` (an array of objects) and `inst` (the instance)
22326 */
22327 get_buffer : function () {
22328 return { 'mode' : ccp_mode, 'node' : ccp_node, 'inst' : ccp_inst };
22329 },
22330 /**
22331 * check if there is something in the buffer to paste
22332 * @name can_paste()
22333 * @return {Boolean}
22334 */
22335 can_paste : function () {
22336 return ccp_mode !== false && ccp_node !== false; // && ccp_inst._model.data[ccp_node];
22337 },
22338 /**
22339 * copy or move the previously cut or copied nodes to a new parent
22340 * @name paste(obj [, pos])
22341 * @param {mixed} obj the new parent
22342 * @param {mixed} pos the position to insert at (besides integer, "first" and "last" are supported), defaults to integer `0`
22343 * @trigger paste.jstree
22344 */
22345 paste : function (obj, pos) {
22346 obj = this.get_node(obj);
22347 if(!obj || !ccp_mode || !ccp_mode.match(/^(copy_node|move_node)$/) || !ccp_node) { return false; }
22348 if(this[ccp_mode](ccp_node, obj, pos)) {
22349 /**
22350 * triggered when paste is invoked
22351 * @event
22352 * @name paste.jstree
22353 * @param {String} parent the ID of the receiving node
22354 * @param {Array} node the nodes in the buffer
22355 * @param {String} mode the performed operation - "copy_node" or "move_node"
22356 */
22357 this.trigger('paste', { "parent" : obj.id, "node" : ccp_node, "mode" : ccp_mode });
22358 }
22359 ccp_node = false;
22360 ccp_mode = false;
22361 ccp_inst = false;
22362 },
22363 /**
22364 * clear the buffer of previously copied or cut nodes
22365 * @name clear_buffer()
22366 * @trigger clear_buffer.jstree
22367 */
22368 clear_buffer : function () {
22369 ccp_node = false;
22370 ccp_mode = false;
22371 ccp_inst = false;
22372 /**
22373 * triggered when the copy / cut buffer is cleared
22374 * @event
22375 * @name clear_buffer.jstree
22376 */
22377 this.trigger('clear_buffer');
22378 },
22379 /**
22380 * put a node in edit mode (input field to rename the node)
22381 * @name edit(obj [, default_text])
22382 * @param {mixed} obj
22383 * @param {String} default_text the text to populate the input with (if omitted the node text value is used)
22384 */
22385 edit : function (obj, default_text) {
22386 obj = this.get_node(obj);
22387 if(!obj) { return false; }
22388 if(this.settings.core.check_callback === false) {
22389 this._data.core.last_error = { 'error' : 'check', 'plugin' : 'core', 'id' : 'core_07', 'reason' : 'Could not edit node because of check_callback' };
22390 this.settings.core.error.call(this, this._data.core.last_error);
22391 return false;
22392 }
22393 default_text = typeof default_text === 'string' ? default_text : obj.text;
22394 this.set_text(obj, "");
22395 obj = this._open_to(obj);
22396
22397 var rtl = this._data.core.rtl,
22398 w = this.element.width(),
22399 a = obj.children('.jstree-anchor'),
22400 s = $('<span>'),
22401 /*!
22402 oi = obj.children("i:visible"),
22403 ai = a.children("i:visible"),
22404 w1 = oi.width() * oi.length,
22405 w2 = ai.width() * ai.length,
22406 */
22407 t = default_text,
22408 h1 = $("<"+"div />", { css : { "position" : "absolute", "top" : "-200px", "left" : (rtl ? "0px" : "-1000px"), "visibility" : "hidden" } }).appendTo("body"),
22409 h2 = $("<"+"input />", {
22410 "value" : t,
22411 "class" : "jstree-rename-input",
22412 // "size" : t.length,
22413 "css" : {
22414 "padding" : "0",
22415 "border" : "1px solid silver",
22416 "box-sizing" : "border-box",
22417 "display" : "inline-block",
22418 "height" : (this._data.core.li_height) + "px",
22419 "lineHeight" : (this._data.core.li_height) + "px",
22420 "width" : "150px" // will be set a bit further down
22421 },
22422 "blur" : $.proxy(function () {
22423 var i = s.children(".jstree-rename-input"),
22424 v = i.val();
22425 if(v === "") { v = t; }
22426 h1.remove();
22427 s.replaceWith(a);
22428 s.remove();
22429 this.set_text(obj, t);
22430 if(this.rename_node(obj, $('<div></div>').text(v)[this.settings.core.force_text ? 'text' : 'html']()) === false) {
22431 this.set_text(obj, t); // move this up? and fix #483
22432 }
22433 }, this),
22434 "keydown" : function (event) {
22435 var key = event.which;
22436 if(key === 27) {
22437 this.value = t;
22438 }
22439 if(key === 27 || key === 13 || key === 37 || key === 38 || key === 39 || key === 40 || key === 32) {
22440 event.stopImmediatePropagation();
22441 }
22442 if(key === 27 || key === 13) {
22443 event.preventDefault();
22444 this.blur();
22445 }
22446 },
22447 "click" : function (e) { e.stopImmediatePropagation(); },
22448 "mousedown" : function (e) { e.stopImmediatePropagation(); },
22449 "keyup" : function (event) {
22450 h2.width(Math.min(h1.text("pW" + this.value).width(),w));
22451 },
22452 "keypress" : function(event) {
22453 if(event.which === 13) { return false; }
22454 }
22455 }),
22456 fn = {
22457 fontFamily : a.css('fontFamily') || '',
22458 fontSize : a.css('fontSize') || '',
22459 fontWeight : a.css('fontWeight') || '',
22460 fontStyle : a.css('fontStyle') || '',
22461 fontStretch : a.css('fontStretch') || '',
22462 fontVariant : a.css('fontVariant') || '',
22463 letterSpacing : a.css('letterSpacing') || '',
22464 wordSpacing : a.css('wordSpacing') || ''
22465 };
22466 s.attr('class', a.attr('class')).append(a.contents().clone()).append(h2);
22467 a.replaceWith(s);
22468 h1.css(fn);
22469 h2.css(fn).width(Math.min(h1.text("pW" + h2[0].value).width(),w))[0].select();
22470 },
22471
22472
22473 /**
22474 * changes the theme
22475 * @name set_theme(theme_name [, theme_url])
22476 * @param {String} theme_name the name of the new theme to apply
22477 * @param {mixed} theme_url the location of the CSS file for this theme. Omit or set to `false` if you manually included the file. Set to `true` to autoload from the `core.themes.dir` directory.
22478 * @trigger set_theme.jstree
22479 */
22480 set_theme : function (theme_name, theme_url) {
22481 if(!theme_name) { return false; }
22482 if(theme_url === true) {
22483 var dir = this.settings.core.themes.dir;
22484 if(!dir) { dir = $.jstree.path + '/themes'; }
22485 theme_url = dir + '/' + theme_name + '/style.css';
22486 }
22487 if(theme_url && $.inArray(theme_url, themes_loaded) === -1) {
22488 $('head').append('<'+'link rel="stylesheet" href="' + theme_url + '" type="text/css" />');
22489 themes_loaded.push(theme_url);
22490 }
22491 if(this._data.core.themes.name) {
22492 this.element.removeClass('jstree-' + this._data.core.themes.name);
22493 }
22494 this._data.core.themes.name = theme_name;
22495 this.element.addClass('jstree-' + theme_name);
22496 this.element[this.settings.core.themes.responsive ? 'addClass' : 'removeClass' ]('jstree-' + theme_name + '-responsive');
22497 /**
22498 * triggered when a theme is set
22499 * @event
22500 * @name set_theme.jstree
22501 * @param {String} theme the new theme
22502 */
22503 this.trigger('set_theme', { 'theme' : theme_name });
22504 },
22505 /**
22506 * gets the name of the currently applied theme name
22507 * @name get_theme()
22508 * @return {String}
22509 */
22510 get_theme : function () { return this._data.core.themes.name; },
22511 /**
22512 * changes the theme variant (if the theme has variants)
22513 * @name set_theme_variant(variant_name)
22514 * @param {String|Boolean} variant_name the variant to apply (if `false` is used the current variant is removed)
22515 */
22516 set_theme_variant : function (variant_name) {
22517 if(this._data.core.themes.variant) {
22518 this.element.removeClass('jstree-' + this._data.core.themes.name + '-' + this._data.core.themes.variant);
22519 }
22520 this._data.core.themes.variant = variant_name;
22521 if(variant_name) {
22522 this.element.addClass('jstree-' + this._data.core.themes.name + '-' + this._data.core.themes.variant);
22523 }
22524 },
22525 /**
22526 * gets the name of the currently applied theme variant
22527 * @name get_theme()
22528 * @return {String}
22529 */
22530 get_theme_variant : function () { return this._data.core.themes.variant; },
22531 /**
22532 * shows a striped background on the container (if the theme supports it)
22533 * @name show_stripes()
22534 */
22535 show_stripes : function () { this._data.core.themes.stripes = true; this.get_container_ul().addClass("jstree-striped"); },
22536 /**
22537 * hides the striped background on the container
22538 * @name hide_stripes()
22539 */
22540 hide_stripes : function () { this._data.core.themes.stripes = false; this.get_container_ul().removeClass("jstree-striped"); },
22541 /**
22542 * toggles the striped background on the container
22543 * @name toggle_stripes()
22544 */
22545 toggle_stripes : function () { if(this._data.core.themes.stripes) { this.hide_stripes(); } else { this.show_stripes(); } },
22546 /**
22547 * shows the connecting dots (if the theme supports it)
22548 * @name show_dots()
22549 */
22550 show_dots : function () { this._data.core.themes.dots = true; this.get_container_ul().removeClass("jstree-no-dots"); },
22551 /**
22552 * hides the connecting dots
22553 * @name hide_dots()
22554 */
22555 hide_dots : function () { this._data.core.themes.dots = false; this.get_container_ul().addClass("jstree-no-dots"); },
22556 /**
22557 * toggles the connecting dots
22558 * @name toggle_dots()
22559 */
22560 toggle_dots : function () { if(this._data.core.themes.dots) { this.hide_dots(); } else { this.show_dots(); } },
22561 /**
22562 * show the node icons
22563 * @name show_icons()
22564 */
22565 show_icons : function () { this._data.core.themes.icons = true; this.get_container_ul().removeClass("jstree-no-icons"); },
22566 /**
22567 * hide the node icons
22568 * @name hide_icons()
22569 */
22570 hide_icons : function () { this._data.core.themes.icons = false; this.get_container_ul().addClass("jstree-no-icons"); },
22571 /**
22572 * toggle the node icons
22573 * @name toggle_icons()
22574 */
22575 toggle_icons : function () { if(this._data.core.themes.icons) { this.hide_icons(); } else { this.show_icons(); } },
22576 /**
22577 * set the node icon for a node
22578 * @name set_icon(obj, icon)
22579 * @param {mixed} obj
22580 * @param {String} icon the new icon - can be a path to an icon or a className, if using an image that is in the current directory use a `./` prefix, otherwise it will be detected as a class
22581 */
22582 set_icon : function (obj, icon) {
22583 var t1, t2, dom, old;
22584 if($.isArray(obj)) {
22585 obj = obj.slice();
22586 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
22587 this.set_icon(obj[t1], icon);
22588 }
22589 return true;
22590 }
22591 obj = this.get_node(obj);
22592 if(!obj || obj.id === '#') { return false; }
22593 old = obj.icon;
22594 obj.icon = icon;
22595 dom = this.get_node(obj, true).children(".jstree-anchor").children(".jstree-themeicon");
22596 if(icon === false) {
22597 this.hide_icon(obj);
22598 }
22599 else if(icon === true) {
22600 dom.removeClass('jstree-themeicon-custom ' + old).css("background","").removeAttr("rel");
22601 if(old === false) { this.show_icon(obj); }
22602 }
22603 else if(icon.indexOf("/") === -1 && icon.indexOf(".") === -1) {
22604 dom.removeClass(old).css("background","");
22605 dom.addClass(icon + ' jstree-themeicon-custom').attr("rel",icon);
22606 if(old === false) { this.show_icon(obj); }
22607 }
22608 else {
22609 dom.removeClass(old).css("background","");
22610 dom.addClass('jstree-themeicon-custom').css("background", "url('" + icon + "') center center no-repeat").attr("rel",icon);
22611 if(old === false) { this.show_icon(obj); }
22612 }
22613 return true;
22614 },
22615 /**
22616 * get the node icon for a node
22617 * @name get_icon(obj)
22618 * @param {mixed} obj
22619 * @return {String}
22620 */
22621 get_icon : function (obj) {
22622 obj = this.get_node(obj);
22623 return (!obj || obj.id === '#') ? false : obj.icon;
22624 },
22625 /**
22626 * hide the icon on an individual node
22627 * @name hide_icon(obj)
22628 * @param {mixed} obj
22629 */
22630 hide_icon : function (obj) {
22631 var t1, t2;
22632 if($.isArray(obj)) {
22633 obj = obj.slice();
22634 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
22635 this.hide_icon(obj[t1]);
22636 }
22637 return true;
22638 }
22639 obj = this.get_node(obj);
22640 if(!obj || obj === '#') { return false; }
22641 obj.icon = false;
22642 this.get_node(obj, true).children(".jstree-anchor").children(".jstree-themeicon").addClass('jstree-themeicon-hidden');
22643 return true;
22644 },
22645 /**
22646 * show the icon on an individual node
22647 * @name show_icon(obj)
22648 * @param {mixed} obj
22649 */
22650 show_icon : function (obj) {
22651 var t1, t2, dom;
22652 if($.isArray(obj)) {
22653 obj = obj.slice();
22654 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
22655 this.show_icon(obj[t1]);
22656 }
22657 return true;
22658 }
22659 obj = this.get_node(obj);
22660 if(!obj || obj === '#') { return false; }
22661 dom = this.get_node(obj, true);
22662 obj.icon = dom.length ? dom.children(".jstree-anchor").children(".jstree-themeicon").attr('rel') : true;
22663 if(!obj.icon) { obj.icon = true; }
22664 dom.children(".jstree-anchor").children(".jstree-themeicon").removeClass('jstree-themeicon-hidden');
22665 return true;
22666 }
22667 };
22668
22669 // helpers
22670 $.vakata = {};
22671 // collect attributes
22672 $.vakata.attributes = function(node, with_values) {
22673 node = $(node)[0];
22674 var attr = with_values ? {} : [];
22675 if(node && node.attributes) {
22676 $.each(node.attributes, function (i, v) {
22677 if($.inArray(v.name.toLowerCase(),['style','contenteditable','hasfocus','tabindex']) !== -1) { return; }
22678 if(v.value !== null && $.trim(v.value) !== '') {
22679 if(with_values) { attr[v.name] = v.value; }
22680 else { attr.push(v.name); }
22681 }
22682 });
22683 }
22684 return attr;
22685 };
22686 $.vakata.array_unique = function(array) {
22687 var a = [], i, j, l;
22688 for(i = 0, l = array.length; i < l; i++) {
22689 for(j = 0; j <= i; j++) {
22690 if(array[i] === array[j]) {
22691 break;
22692 }
22693 }
22694 if(j === i) { a.push(array[i]); }
22695 }
22696 return a;
22697 };
22698 // remove item from array
22699 $.vakata.array_remove = function(array, from, to) {
22700 var rest = array.slice((to || from) + 1 || array.length);
22701 array.length = from < 0 ? array.length + from : from;
22702 array.push.apply(array, rest);
22703 return array;
22704 };
22705 // remove item from array
22706 $.vakata.array_remove_item = function(array, item) {
22707 var tmp = $.inArray(item, array);
22708 return tmp !== -1 ? $.vakata.array_remove(array, tmp) : array;
22709 };
22710
22711
22712 /**
22713 * ### Checkbox plugin
22714 *
22715 * This plugin renders checkbox icons in front of each node, making multiple selection much easier.
22716 * It also supports tri-state behavior, meaning that if a node has a few of its children checked it will be rendered as undetermined, and state will be propagated up.
22717 */
22718
22719 var _i = document.createElement('I');
22720 _i.className = 'jstree-icon jstree-checkbox';
22721 _i.setAttribute('role', 'presentation');
22722 /**
22723 * stores all defaults for the checkbox plugin
22724 * @name $.jstree.defaults.checkbox
22725 * @plugin checkbox
22726 */
22727 $.jstree.defaults.checkbox = {
22728 /**
22729 * a boolean indicating if checkboxes should be visible (can be changed at a later time using `show_checkboxes()` and `hide_checkboxes`). Defaults to `true`.
22730 * @name $.jstree.defaults.checkbox.visible
22731 * @plugin checkbox
22732 */
22733 visible : true,
22734 /**
22735 * a boolean indicating if checkboxes should cascade down and have an undetermined state. Defaults to `true`.
22736 * @name $.jstree.defaults.checkbox.three_state
22737 * @plugin checkbox
22738 */
22739 three_state : true,
22740 /**
22741 * a boolean indicating if clicking anywhere on the node should act as clicking on the checkbox. Defaults to `true`.
22742 * @name $.jstree.defaults.checkbox.whole_node
22743 * @plugin checkbox
22744 */
22745 whole_node : true,
22746 /**
22747 * a boolean indicating if the selected style of a node should be kept, or removed. Defaults to `true`.
22748 * @name $.jstree.defaults.checkbox.keep_selected_style
22749 * @plugin checkbox
22750 */
22751 keep_selected_style : true,
22752 /**
22753 * This setting controls how cascading and undetermined nodes are applied.
22754 * If 'up' is in the string - cascading up is enabled, if 'down' is in the string - cascading down is enabled, if 'undetermined' is in the string - undetermined nodes will be used.
22755 * If `three_state` is set to `true` this setting is automatically set to 'up+down+undetermined'. Defaults to ''.
22756 * @name $.jstree.defaults.checkbox.cascade
22757 * @plugin checkbox
22758 */
22759 cascade : '',
22760 /**
22761 * This setting controls if checkbox are bound to the general tree selection or to an internal array maintained by the checkbox plugin. Defaults to `true`, only set to `false` if you know exactly what you are doing.
22762 * @name $.jstree.defaults.checkbox.tie_selection
22763 * @plugin checkbox
22764 */
22765 tie_selection : true
22766 };
22767 $.jstree.plugins.checkbox = function (options, parent) {
22768 this.bind = function () {
22769 parent.bind.call(this);
22770 this._data.checkbox.uto = false;
22771 this._data.checkbox.selected = [];
22772 if(this.settings.checkbox.three_state) {
22773 this.settings.checkbox.cascade = 'up+down+undetermined';
22774 }
22775 this.element
22776 .on("init.jstree", $.proxy(function () {
22777 this._data.checkbox.visible = this.settings.checkbox.visible;
22778 if(!this.settings.checkbox.keep_selected_style) {
22779 this.element.addClass('jstree-checkbox-no-clicked');
22780 }
22781 if(this.settings.checkbox.tie_selection) {
22782 this.element.addClass('jstree-checkbox-selection');
22783 }
22784 }, this))
22785 .on("loading.jstree", $.proxy(function () {
22786 this[ this._data.checkbox.visible ? 'show_checkboxes' : 'hide_checkboxes' ]();
22787 }, this));
22788 if(this.settings.checkbox.cascade.indexOf('undetermined') !== -1) {
22789 this.element
22790 .on('changed.jstree uncheck_node.jstree check_node.jstree uncheck_all.jstree check_all.jstree move_node.jstree copy_node.jstree redraw.jstree open_node.jstree', $.proxy(function () {
22791 // only if undetermined is in setting
22792 if(this._data.checkbox.uto) { clearTimeout(this._data.checkbox.uto); }
22793 this._data.checkbox.uto = setTimeout($.proxy(this._undetermined, this), 50);
22794 }, this));
22795 }
22796 if(!this.settings.checkbox.tie_selection) {
22797 this.element
22798 .on('model.jstree', $.proxy(function (e, data) {
22799 var m = this._model.data,
22800 p = m[data.parent],
22801 dpc = data.nodes,
22802 i, j;
22803 for(i = 0, j = dpc.length; i < j; i++) {
22804 m[dpc[i]].state.checked = (m[dpc[i]].original && m[dpc[i]].original.state && m[dpc[i]].original.state.checked);
22805 if(m[dpc[i]].state.checked) {
22806 this._data.checkbox.selected.push(dpc[i]);
22807 }
22808 }
22809 }, this));
22810 }
22811 if(this.settings.checkbox.cascade.indexOf('up') !== -1 || this.settings.checkbox.cascade.indexOf('down') !== -1) {
22812 this.element
22813 .on('model.jstree', $.proxy(function (e, data) {
22814 var m = this._model.data,
22815 p = m[data.parent],
22816 dpc = data.nodes,
22817 chd = [],
22818 c, i, j, k, l, tmp, s = this.settings.checkbox.cascade, t = this.settings.checkbox.tie_selection;
22819
22820 if(s.indexOf('down') !== -1) {
22821 // apply down
22822 if(p.state[ t ? 'selected' : 'checked' ]) {
22823 for(i = 0, j = dpc.length; i < j; i++) {
22824 m[dpc[i]].state[ t ? 'selected' : 'checked' ] = true;
22825 }
22826 this._data[ t ? 'core' : 'checkbox' ].selected = this._data[ t ? 'core' : 'checkbox' ].selected.concat(dpc);
22827 }
22828 else {
22829 for(i = 0, j = dpc.length; i < j; i++) {
22830 if(m[dpc[i]].state[ t ? 'selected' : 'checked' ]) {
22831 for(k = 0, l = m[dpc[i]].children_d.length; k < l; k++) {
22832 m[m[dpc[i]].children_d[k]].state[ t ? 'selected' : 'checked' ] = true;
22833 }
22834 this._data[ t ? 'core' : 'checkbox' ].selected = this._data[ t ? 'core' : 'checkbox' ].selected.concat(m[dpc[i]].children_d);
22835 }
22836 }
22837 }
22838 }
22839
22840 if(s.indexOf('up') !== -1) {
22841 // apply up
22842 for(i = 0, j = p.children_d.length; i < j; i++) {
22843 if(!m[p.children_d[i]].children.length) {
22844 chd.push(m[p.children_d[i]].parent);
22845 }
22846 }
22847 chd = $.vakata.array_unique(chd);
22848 for(k = 0, l = chd.length; k < l; k++) {
22849 p = m[chd[k]];
22850 while(p && p.id !== '#') {
22851 c = 0;
22852 for(i = 0, j = p.children.length; i < j; i++) {
22853 c += m[p.children[i]].state[ t ? 'selected' : 'checked' ];
22854 }
22855 if(c === j) {
22856 p.state[ t ? 'selected' : 'checked' ] = true;
22857 this._data[ t ? 'core' : 'checkbox' ].selected.push(p.id);
22858 tmp = this.get_node(p, true);
22859 if(tmp && tmp.length) {
22860 tmp.attr('aria-selected', true).children('.jstree-anchor').addClass( t ? 'jstree-clicked' : 'jstree-checked');
22861 }
22862 }
22863 else {
22864 break;
22865 }
22866 p = this.get_node(p.parent);
22867 }
22868 }
22869 }
22870
22871 this._data[ t ? 'core' : 'checkbox' ].selected = $.vakata.array_unique(this._data[ t ? 'core' : 'checkbox' ].selected);
22872 }, this))
22873 .on(this.settings.checkbox.tie_selection ? 'select_node.jstree' : 'check_node.jstree', $.proxy(function (e, data) {
22874 var obj = data.node,
22875 m = this._model.data,
22876 par = this.get_node(obj.parent),
22877 dom = this.get_node(obj, true),
22878 i, j, c, tmp, s = this.settings.checkbox.cascade, t = this.settings.checkbox.tie_selection;
22879
22880 // apply down
22881 if(s.indexOf('down') !== -1) {
22882 this._data[ t ? 'core' : 'checkbox' ].selected = $.vakata.array_unique(this._data[ t ? 'core' : 'checkbox' ].selected.concat(obj.children_d));
22883 for(i = 0, j = obj.children_d.length; i < j; i++) {
22884 tmp = m[obj.children_d[i]];
22885 tmp.state[ t ? 'selected' : 'checked' ] = true;
22886 if(tmp && tmp.original && tmp.original.state && tmp.original.state.undetermined) {
22887 tmp.original.state.undetermined = false;
22888 }
22889 }
22890 }
22891
22892 // apply up
22893 if(s.indexOf('up') !== -1) {
22894 while(par && par.id !== '#') {
22895 c = 0;
22896 for(i = 0, j = par.children.length; i < j; i++) {
22897 c += m[par.children[i]].state[ t ? 'selected' : 'checked' ];
22898 }
22899 if(c === j) {
22900 par.state[ t ? 'selected' : 'checked' ] = true;
22901 this._data[ t ? 'core' : 'checkbox' ].selected.push(par.id);
22902 tmp = this.get_node(par, true);
22903 if(tmp && tmp.length) {
22904 tmp.attr('aria-selected', true).children('.jstree-anchor').addClass(t ? 'jstree-clicked' : 'jstree-checked');
22905 }
22906 }
22907 else {
22908 break;
22909 }
22910 par = this.get_node(par.parent);
22911 }
22912 }
22913
22914 // apply down (process .children separately?)
22915 if(s.indexOf('down') !== -1 && dom.length) {
22916 dom.find('.jstree-anchor').addClass(t ? 'jstree-clicked' : 'jstree-checked').parent().attr('aria-selected', true);
22917 }
22918 }, this))
22919 .on(this.settings.checkbox.tie_selection ? 'deselect_all.jstree' : 'uncheck_all.jstree', $.proxy(function (e, data) {
22920 var obj = this.get_node('#'),
22921 m = this._model.data,
22922 i, j, tmp;
22923 for(i = 0, j = obj.children_d.length; i < j; i++) {
22924 tmp = m[obj.children_d[i]];
22925 if(tmp && tmp.original && tmp.original.state && tmp.original.state.undetermined) {
22926 tmp.original.state.undetermined = false;
22927 }
22928 }
22929 }, this))
22930 .on(this.settings.checkbox.tie_selection ? 'deselect_node.jstree' : 'uncheck_node.jstree', $.proxy(function (e, data) {
22931 var obj = data.node,
22932 dom = this.get_node(obj, true),
22933 i, j, tmp, s = this.settings.checkbox.cascade, t = this.settings.checkbox.tie_selection;
22934 if(obj && obj.original && obj.original.state && obj.original.state.undetermined) {
22935 obj.original.state.undetermined = false;
22936 }
22937
22938 // apply down
22939 if(s.indexOf('down') !== -1) {
22940 for(i = 0, j = obj.children_d.length; i < j; i++) {
22941 tmp = this._model.data[obj.children_d[i]];
22942 tmp.state[ t ? 'selected' : 'checked' ] = false;
22943 if(tmp && tmp.original && tmp.original.state && tmp.original.state.undetermined) {
22944 tmp.original.state.undetermined = false;
22945 }
22946 }
22947 }
22948
22949 // apply up
22950 if(s.indexOf('up') !== -1) {
22951 for(i = 0, j = obj.parents.length; i < j; i++) {
22952 tmp = this._model.data[obj.parents[i]];
22953 tmp.state[ t ? 'selected' : 'checked' ] = false;
22954 if(tmp && tmp.original && tmp.original.state && tmp.original.state.undetermined) {
22955 tmp.original.state.undetermined = false;
22956 }
22957 tmp = this.get_node(obj.parents[i], true);
22958 if(tmp && tmp.length) {
22959 tmp.attr('aria-selected', false).children('.jstree-anchor').removeClass(t ? 'jstree-clicked' : 'jstree-checked');
22960 }
22961 }
22962 }
22963 tmp = [];
22964 for(i = 0, j = this._data[ t ? 'core' : 'checkbox' ].selected.length; i < j; i++) {
22965 // apply down + apply up
22966 if(
22967 (s.indexOf('down') === -1 || $.inArray(this._data[ t ? 'core' : 'checkbox' ].selected[i], obj.children_d) === -1) &&
22968 (s.indexOf('up') === -1 || $.inArray(this._data[ t ? 'core' : 'checkbox' ].selected[i], obj.parents) === -1)
22969 ) {
22970 tmp.push(this._data[ t ? 'core' : 'checkbox' ].selected[i]);
22971 }
22972 }
22973 this._data[ t ? 'core' : 'checkbox' ].selected = $.vakata.array_unique(tmp);
22974
22975 // apply down (process .children separately?)
22976 if(s.indexOf('down') !== -1 && dom.length) {
22977 dom.find('.jstree-anchor').removeClass(t ? 'jstree-clicked' : 'jstree-checked').parent().attr('aria-selected', false);
22978 }
22979 }, this));
22980 }
22981 if(this.settings.checkbox.cascade.indexOf('up') !== -1) {
22982 this.element
22983 .on('delete_node.jstree', $.proxy(function (e, data) {
22984 // apply up (whole handler)
22985 var p = this.get_node(data.parent),
22986 m = this._model.data,
22987 i, j, c, tmp, t = this.settings.checkbox.tie_selection;
22988 while(p && p.id !== '#') {
22989 c = 0;
22990 for(i = 0, j = p.children.length; i < j; i++) {
22991 c += m[p.children[i]].state[ t ? 'selected' : 'checked' ];
22992 }
22993 if(c === j) {
22994 p.state[ t ? 'selected' : 'checked' ] = true;
22995 this._data[ t ? 'core' : 'checkbox' ].selected.push(p.id);
22996 tmp = this.get_node(p, true);
22997 if(tmp && tmp.length) {
22998 tmp.attr('aria-selected', true).children('.jstree-anchor').addClass(t ? 'jstree-clicked' : 'jstree-checked');
22999 }
23000 }
23001 else {
23002 break;
23003 }
23004 p = this.get_node(p.parent);
23005 }
23006 }, this))
23007 .on('move_node.jstree', $.proxy(function (e, data) {
23008 // apply up (whole handler)
23009 var is_multi = data.is_multi,
23010 old_par = data.old_parent,
23011 new_par = this.get_node(data.parent),
23012 m = this._model.data,
23013 p, c, i, j, tmp, t = this.settings.checkbox.tie_selection;
23014 if(!is_multi) {
23015 p = this.get_node(old_par);
23016 while(p && p.id !== '#') {
23017 c = 0;
23018 for(i = 0, j = p.children.length; i < j; i++) {
23019 c += m[p.children[i]].state[ t ? 'selected' : 'checked' ];
23020 }
23021 if(c === j) {
23022 p.state[ t ? 'selected' : 'checked' ] = true;
23023 this._data[ t ? 'core' : 'checkbox' ].selected.push(p.id);
23024 tmp = this.get_node(p, true);
23025 if(tmp && tmp.length) {
23026 tmp.attr('aria-selected', true).children('.jstree-anchor').addClass(t ? 'jstree-clicked' : 'jstree-checked');
23027 }
23028 }
23029 else {
23030 break;
23031 }
23032 p = this.get_node(p.parent);
23033 }
23034 }
23035 p = new_par;
23036 while(p && p.id !== '#') {
23037 c = 0;
23038 for(i = 0, j = p.children.length; i < j; i++) {
23039 c += m[p.children[i]].state[ t ? 'selected' : 'checked' ];
23040 }
23041 if(c === j) {
23042 if(!p.state[ t ? 'selected' : 'checked' ]) {
23043 p.state[ t ? 'selected' : 'checked' ] = true;
23044 this._data[ t ? 'core' : 'checkbox' ].selected.push(p.id);
23045 tmp = this.get_node(p, true);
23046 if(tmp && tmp.length) {
23047 tmp.attr('aria-selected', true).children('.jstree-anchor').addClass(t ? 'jstree-clicked' : 'jstree-checked');
23048 }
23049 }
23050 }
23051 else {
23052 if(p.state[ t ? 'selected' : 'checked' ]) {
23053 p.state[ t ? 'selected' : 'checked' ] = false;
23054 this._data[ t ? 'core' : 'checkbox' ].selected = $.vakata.array_remove_item(this._data[ t ? 'core' : 'checkbox' ].selected, p.id);
23055 tmp = this.get_node(p, true);
23056 if(tmp && tmp.length) {
23057 tmp.attr('aria-selected', false).children('.jstree-anchor').removeClass(t ? 'jstree-clicked' : 'jstree-checked');
23058 }
23059 }
23060 else {
23061 break;
23062 }
23063 }
23064 p = this.get_node(p.parent);
23065 }
23066 }, this));
23067 }
23068 };
23069 /**
23070 * set the undetermined state where and if necessary. Used internally.
23071 * @private
23072 * @name _undetermined()
23073 * @plugin checkbox
23074 */
23075 this._undetermined = function () {
23076 var i, j, m = this._model.data, t = this.settings.checkbox.tie_selection, s = this._data[ t ? 'core' : 'checkbox' ].selected, p = [], tt = this;
23077 for(i = 0, j = s.length; i < j; i++) {
23078 if(m[s[i]] && m[s[i]].parents) {
23079 p = p.concat(m[s[i]].parents);
23080 }
23081 }
23082 // attempt for server side undetermined state
23083 this.element.find('.jstree-closed').not(':has(.jstree-children)')
23084 .each(function () {
23085 var tmp = tt.get_node(this), tmp2;
23086 if(!tmp.state.loaded) {
23087 if(tmp.original && tmp.original.state && tmp.original.state.undetermined && tmp.original.state.undetermined === true) {
23088 p.push(tmp.id);
23089 p = p.concat(tmp.parents);
23090 }
23091 }
23092 else {
23093 for(i = 0, j = tmp.children_d.length; i < j; i++) {
23094 tmp2 = m[tmp.children_d[i]];
23095 if(!tmp2.state.loaded && tmp2.original && tmp2.original.state && tmp2.original.state.undetermined && tmp2.original.state.undetermined === true) {
23096 p.push(tmp2.id);
23097 p = p.concat(tmp2.parents);
23098 }
23099 }
23100 }
23101 });
23102 p = $.vakata.array_unique(p);
23103 p = $.vakata.array_remove_item(p,'#');
23104
23105 this.element.find('.jstree-undetermined').removeClass('jstree-undetermined');
23106 for(i = 0, j = p.length; i < j; i++) {
23107 if(!m[p[i]].state[ t ? 'selected' : 'checked' ]) {
23108 s = this.get_node(p[i], true);
23109 if(s && s.length) {
23110 s.children('.jstree-anchor').children('.jstree-checkbox').addClass('jstree-undetermined');
23111 }
23112 }
23113 }
23114 };
23115 this.redraw_node = function(obj, deep, is_callback, force_render) {
23116 obj = parent.redraw_node.apply(this, arguments);
23117 if(obj) {
23118 var i, j, tmp = null;
23119 for(i = 0, j = obj.childNodes.length; i < j; i++) {
23120 if(obj.childNodes[i] && obj.childNodes[i].className && obj.childNodes[i].className.indexOf("jstree-anchor") !== -1) {
23121 tmp = obj.childNodes[i];
23122 break;
23123 }
23124 }
23125 if(tmp) {
23126 if(!this.settings.checkbox.tie_selection && this._model.data[obj.id].state.checked) { tmp.className += ' jstree-checked'; }
23127 tmp.insertBefore(_i.cloneNode(false), tmp.childNodes[0]);
23128 }
23129 }
23130 if(!is_callback && this.settings.checkbox.cascade.indexOf('undetermined') !== -1) {
23131 if(this._data.checkbox.uto) { clearTimeout(this._data.checkbox.uto); }
23132 this._data.checkbox.uto = setTimeout($.proxy(this._undetermined, this), 50);
23133 }
23134 return obj;
23135 };
23136 /**
23137 * show the node checkbox icons
23138 * @name show_checkboxes()
23139 * @plugin checkbox
23140 */
23141 this.show_checkboxes = function () { this._data.core.themes.checkboxes = true; this.get_container_ul().removeClass("jstree-no-checkboxes"); };
23142 /**
23143 * hide the node checkbox icons
23144 * @name hide_checkboxes()
23145 * @plugin checkbox
23146 */
23147 this.hide_checkboxes = function () { this._data.core.themes.checkboxes = false; this.get_container_ul().addClass("jstree-no-checkboxes"); };
23148 /**
23149 * toggle the node icons
23150 * @name toggle_checkboxes()
23151 * @plugin checkbox
23152 */
23153 this.toggle_checkboxes = function () { if(this._data.core.themes.checkboxes) { this.hide_checkboxes(); } else { this.show_checkboxes(); } };
23154 /**
23155 * checks if a node is in an undetermined state
23156 * @name is_undetermined(obj)
23157 * @param {mixed} obj
23158 * @return {Boolean}
23159 */
23160 this.is_undetermined = function (obj) {
23161 obj = this.get_node(obj);
23162 var s = this.settings.checkbox.cascade, i, j, t = this.settings.checkbox.tie_selection, d = this._data[ t ? 'core' : 'checkbox' ].selected, m = this._model.data;
23163 if(!obj || obj.state[ t ? 'selected' : 'checked' ] === true || s.indexOf('undetermined') === -1 || (s.indexOf('down') === -1 && s.indexOf('up') === -1)) {
23164 return false;
23165 }
23166 if(!obj.state.loaded && obj.original.state.undetermined === true) {
23167 return true;
23168 }
23169 for(i = 0, j = obj.children_d.length; i < j; i++) {
23170 if($.inArray(obj.children_d[i], d) !== -1 || (!m[obj.children_d[i]].state.loaded && m[obj.children_d[i]].original.state.undetermined)) {
23171 return true;
23172 }
23173 }
23174 return false;
23175 };
23176
23177 this.activate_node = function (obj, e) {
23178 if(this.settings.checkbox.tie_selection && (this.settings.checkbox.whole_node || $(e.target).hasClass('jstree-checkbox'))) {
23179 e.ctrlKey = true;
23180 }
23181 if(this.settings.checkbox.tie_selection || (!this.settings.checkbox.whole_node && !$(e.target).hasClass('jstree-checkbox'))) {
23182 return parent.activate_node.call(this, obj, e);
23183 }
23184 if(this.is_disabled(obj)) {
23185 return false;
23186 }
23187 if(this.is_checked(obj)) {
23188 this.uncheck_node(obj, e);
23189 }
23190 else {
23191 this.check_node(obj, e);
23192 }
23193 this.trigger('activate_node', { 'node' : this.get_node(obj) });
23194 };
23195
23196 /**
23197 * check a node (only if tie_selection in checkbox settings is false, otherwise select_node will be called internally)
23198 * @name check_node(obj)
23199 * @param {mixed} obj an array can be used to check multiple nodes
23200 * @trigger check_node.jstree
23201 * @plugin checkbox
23202 */
23203 this.check_node = function (obj, e) {
23204 if(this.settings.checkbox.tie_selection) { return this.select_node(obj, false, true, e); }
23205 var dom, t1, t2, th;
23206 if($.isArray(obj)) {
23207 obj = obj.slice();
23208 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
23209 this.check_node(obj[t1], e);
23210 }
23211 return true;
23212 }
23213 obj = this.get_node(obj);
23214 if(!obj || obj.id === '#') {
23215 return false;
23216 }
23217 dom = this.get_node(obj, true);
23218 if(!obj.state.checked) {
23219 obj.state.checked = true;
23220 this._data.checkbox.selected.push(obj.id);
23221 if(dom && dom.length) {
23222 dom.children('.jstree-anchor').addClass('jstree-checked');
23223 }
23224 /**
23225 * triggered when an node is checked (only if tie_selection in checkbox settings is false)
23226 * @event
23227 * @name check_node.jstree
23228 * @param {Object} node
23229 * @param {Array} selected the current selection
23230 * @param {Object} event the event (if any) that triggered this check_node
23231 * @plugin checkbox
23232 */
23233 this.trigger('check_node', { 'node' : obj, 'selected' : this._data.checkbox.selected, 'event' : e });
23234 }
23235 };
23236 /**
23237 * uncheck a node (only if tie_selection in checkbox settings is false, otherwise deselect_node will be called internally)
23238 * @name deselect_node(obj)
23239 * @param {mixed} obj an array can be used to deselect multiple nodes
23240 * @trigger uncheck_node.jstree
23241 * @plugin checkbox
23242 */
23243 this.uncheck_node = function (obj, e) {
23244 if(this.settings.checkbox.tie_selection) { return this.deselect_node(obj, false, e); }
23245 var t1, t2, dom;
23246 if($.isArray(obj)) {
23247 obj = obj.slice();
23248 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
23249 this.uncheck_node(obj[t1], e);
23250 }
23251 return true;
23252 }
23253 obj = this.get_node(obj);
23254 if(!obj || obj.id === '#') {
23255 return false;
23256 }
23257 dom = this.get_node(obj, true);
23258 if(obj.state.checked) {
23259 obj.state.checked = false;
23260 this._data.checkbox.selected = $.vakata.array_remove_item(this._data.checkbox.selected, obj.id);
23261 if(dom.length) {
23262 dom.children('.jstree-anchor').removeClass('jstree-checked');
23263 }
23264 /**
23265 * triggered when an node is unchecked (only if tie_selection in checkbox settings is false)
23266 * @event
23267 * @name uncheck_node.jstree
23268 * @param {Object} node
23269 * @param {Array} selected the current selection
23270 * @param {Object} event the event (if any) that triggered this uncheck_node
23271 * @plugin checkbox
23272 */
23273 this.trigger('uncheck_node', { 'node' : obj, 'selected' : this._data.checkbox.selected, 'event' : e });
23274 }
23275 };
23276 /**
23277 * checks all nodes in the tree (only if tie_selection in checkbox settings is false, otherwise select_all will be called internally)
23278 * @name check_all()
23279 * @trigger check_all.jstree, changed.jstree
23280 * @plugin checkbox
23281 */
23282 this.check_all = function () {
23283 if(this.settings.checkbox.tie_selection) { return this.select_all(); }
23284 var tmp = this._data.checkbox.selected.concat([]), i, j;
23285 this._data.checkbox.selected = this._model.data['#'].children_d.concat();
23286 for(i = 0, j = this._data.checkbox.selected.length; i < j; i++) {
23287 if(this._model.data[this._data.checkbox.selected[i]]) {
23288 this._model.data[this._data.checkbox.selected[i]].state.checked = true;
23289 }
23290 }
23291 this.redraw(true);
23292 /**
23293 * triggered when all nodes are checked (only if tie_selection in checkbox settings is false)
23294 * @event
23295 * @name check_all.jstree
23296 * @param {Array} selected the current selection
23297 * @plugin checkbox
23298 */
23299 this.trigger('check_all', { 'selected' : this._data.checkbox.selected });
23300 };
23301 /**
23302 * uncheck all checked nodes (only if tie_selection in checkbox settings is false, otherwise deselect_all will be called internally)
23303 * @name uncheck_all()
23304 * @trigger uncheck_all.jstree
23305 * @plugin checkbox
23306 */
23307 this.uncheck_all = function () {
23308 if(this.settings.checkbox.tie_selection) { return this.deselect_all(); }
23309 var tmp = this._data.checkbox.selected.concat([]), i, j;
23310 for(i = 0, j = this._data.checkbox.selected.length; i < j; i++) {
23311 if(this._model.data[this._data.checkbox.selected[i]]) {
23312 this._model.data[this._data.checkbox.selected[i]].state.checked = false;
23313 }
23314 }
23315 this._data.checkbox.selected = [];
23316 this.element.find('.jstree-checked').removeClass('jstree-checked');
23317 /**
23318 * triggered when all nodes are unchecked (only if tie_selection in checkbox settings is false)
23319 * @event
23320 * @name uncheck_all.jstree
23321 * @param {Object} node the previous selection
23322 * @param {Array} selected the current selection
23323 * @plugin checkbox
23324 */
23325 this.trigger('uncheck_all', { 'selected' : this._data.checkbox.selected, 'node' : tmp });
23326 };
23327 /**
23328 * checks if a node is checked (if tie_selection is on in the settings this function will return the same as is_selected)
23329 * @name is_checked(obj)
23330 * @param {mixed} obj
23331 * @return {Boolean}
23332 * @plugin checkbox
23333 */
23334 this.is_checked = function (obj) {
23335 if(this.settings.checkbox.tie_selection) { return this.is_selected(obj); }
23336 obj = this.get_node(obj);
23337 if(!obj || obj.id === '#') { return false; }
23338 return obj.state.checked;
23339 };
23340 /**
23341 * get an array of all checked nodes (if tie_selection is on in the settings this function will return the same as get_selected)
23342 * @name get_checked([full])
23343 * @param {mixed} full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned
23344 * @return {Array}
23345 * @plugin checkbox
23346 */
23347 this.get_checked = function (full) {
23348 if(this.settings.checkbox.tie_selection) { return this.get_selected(full); }
23349 return full ? $.map(this._data.checkbox.selected, $.proxy(function (i) { return this.get_node(i); }, this)) : this._data.checkbox.selected;
23350 };
23351 /**
23352 * get an array of all top level checked nodes (ignoring children of checked nodes) (if tie_selection is on in the settings this function will return the same as get_top_selected)
23353 * @name get_top_checked([full])
23354 * @param {mixed} full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned
23355 * @return {Array}
23356 * @plugin checkbox
23357 */
23358 this.get_top_checked = function (full) {
23359 if(this.settings.checkbox.tie_selection) { return this.get_top_selected(full); }
23360 var tmp = this.get_checked(true),
23361 obj = {}, i, j, k, l;
23362 for(i = 0, j = tmp.length; i < j; i++) {
23363 obj[tmp[i].id] = tmp[i];
23364 }
23365 for(i = 0, j = tmp.length; i < j; i++) {
23366 for(k = 0, l = tmp[i].children_d.length; k < l; k++) {
23367 if(obj[tmp[i].children_d[k]]) {
23368 delete obj[tmp[i].children_d[k]];
23369 }
23370 }
23371 }
23372 tmp = [];
23373 for(i in obj) {
23374 if(obj.hasOwnProperty(i)) {
23375 tmp.push(i);
23376 }
23377 }
23378 return full ? $.map(tmp, $.proxy(function (i) { return this.get_node(i); }, this)) : tmp;
23379 };
23380 /**
23381 * get an array of all bottom level checked nodes (ignoring selected parents) (if tie_selection is on in the settings this function will return the same as get_bottom_selected)
23382 * @name get_bottom_checked([full])
23383 * @param {mixed} full if set to `true` the returned array will consist of the full node objects, otherwise - only IDs will be returned
23384 * @return {Array}
23385 * @plugin checkbox
23386 */
23387 this.get_bottom_checked = function (full) {
23388 if(this.settings.checkbox.tie_selection) { return this.get_bottom_selected(full); }
23389 var tmp = this.get_checked(true),
23390 obj = [], i, j;
23391 for(i = 0, j = tmp.length; i < j; i++) {
23392 if(!tmp[i].children.length) {
23393 obj.push(tmp[i].id);
23394 }
23395 }
23396 return full ? $.map(obj, $.proxy(function (i) { return this.get_node(i); }, this)) : obj;
23397 };
23398 this.load_node = function (obj, callback) {
23399 var k, l, i, j, c, tmp;
23400 if(!$.isArray(obj) && !this.settings.checkbox.tie_selection) {
23401 tmp = this.get_node(obj);
23402 if(tmp && tmp.state.loaded) {
23403 for(k = 0, l = tmp.children_d.length; k < l; k++) {
23404 if(this._model.data[tmp.children_d[k]].state.checked) {
23405 c = true;
23406 this._data.checkbox.selected = $.vakata.array_remove_item(this._data.checkbox.selected, tmp.children_d[k]);
23407 }
23408 }
23409 }
23410 }
23411 return parent.load_node.apply(this, arguments);
23412 };
23413 this.get_state = function () {
23414 var state = parent.get_state.apply(this, arguments);
23415 if(this.settings.checkbox.tie_selection) { return state; }
23416 state.checkbox = this._data.checkbox.selected.slice();
23417 return state;
23418 };
23419 this.set_state = function (state, callback) {
23420 var res = parent.set_state.apply(this, arguments);
23421 if(res && state.checkbox) {
23422 if(!this.settings.checkbox.tie_selection) {
23423 this.uncheck_all();
23424 var _this = this;
23425 $.each(state.checkbox, function (i, v) {
23426 _this.check_node(v);
23427 });
23428 }
23429 delete state.checkbox;
23430 return false;
23431 }
23432 return res;
23433 };
23434 };
23435
23436 // include the checkbox plugin by default
23437 // $.jstree.defaults.plugins.push("checkbox");
23438
23439 /**
23440 * ### Contextmenu plugin
23441 *
23442 * Shows a context menu when a node is right-clicked.
23443 */
23444
23445 var cto = null, ex, ey;
23446
23447 /**
23448 * stores all defaults for the contextmenu plugin
23449 * @name $.jstree.defaults.contextmenu
23450 * @plugin contextmenu
23451 */
23452 $.jstree.defaults.contextmenu = {
23453 /**
23454 * a boolean indicating if the node should be selected when the context menu is invoked on it. Defaults to `true`.
23455 * @name $.jstree.defaults.contextmenu.select_node
23456 * @plugin contextmenu
23457 */
23458 select_node : true,
23459 /**
23460 * a boolean indicating if the menu should be shown aligned with the node. Defaults to `true`, otherwise the mouse coordinates are used.
23461 * @name $.jstree.defaults.contextmenu.show_at_node
23462 * @plugin contextmenu
23463 */
23464 show_at_node : true,
23465 /**
23466 * an object of actions, or a function that accepts a node and a callback function and calls the callback function with an object of actions available for that node (you can also return the items too).
23467 *
23468 * Each action consists of a key (a unique name) and a value which is an object with the following properties (only label and action are required):
23469 *
23470 * * `separator_before` - a boolean indicating if there should be a separator before this item
23471 * * `separator_after` - a boolean indicating if there should be a separator after this item
23472 * * `_disabled` - a boolean indicating if this action should be disabled
23473 * * `label` - a string - the name of the action (could be a function returning a string)
23474 * * `action` - a function to be executed if this item is chosen
23475 * * `icon` - a string, can be a path to an icon or a className, if using an image that is in the current directory use a `./` prefix, otherwise it will be detected as a class
23476 * * `shortcut` - keyCode which will trigger the action if the menu is open (for example `113` for rename, which equals F2)
23477 * * `shortcut_label` - shortcut label (like for example `F2` for rename)
23478 *
23479 * @name $.jstree.defaults.contextmenu.items
23480 * @plugin contextmenu
23481 */
23482 items : function (o, cb) { // Could be an object directly
23483 return {
23484 "create" : {
23485 "separator_before" : false,
23486 "separator_after" : true,
23487 "_disabled" : false, //(this.check("create_node", data.reference, {}, "last")),
23488 "label" : "Create",
23489 "action" : function (data) {
23490 var inst = $.jstree.reference(data.reference),
23491 obj = inst.get_node(data.reference);
23492 inst.create_node(obj, {}, "last", function (new_node) {
23493 setTimeout(function () { inst.edit(new_node); },0);
23494 });
23495 }
23496 },
23497 "rename" : {
23498 "separator_before" : false,
23499 "separator_after" : false,
23500 "_disabled" : false, //(this.check("rename_node", data.reference, this.get_parent(data.reference), "")),
23501 "label" : "Rename",
23502 /*
23503 "shortcut" : 113,
23504 "shortcut_label" : 'F2',
23505 "icon" : "glyphicon glyphicon-leaf",
23506 */
23507 "action" : function (data) {
23508 var inst = $.jstree.reference(data.reference),
23509 obj = inst.get_node(data.reference);
23510 inst.edit(obj);
23511 }
23512 },
23513 "remove" : {
23514 "separator_before" : false,
23515 "icon" : false,
23516 "separator_after" : false,
23517 "_disabled" : false, //(this.check("delete_node", data.reference, this.get_parent(data.reference), "")),
23518 "label" : "Delete",
23519 "action" : function (data) {
23520 var inst = $.jstree.reference(data.reference),
23521 obj = inst.get_node(data.reference);
23522 if(inst.is_selected(obj)) {
23523 inst.delete_node(inst.get_selected());
23524 }
23525 else {
23526 inst.delete_node(obj);
23527 }
23528 }
23529 },
23530 "ccp" : {
23531 "separator_before" : true,
23532 "icon" : false,
23533 "separator_after" : false,
23534 "label" : "Edit",
23535 "action" : false,
23536 "submenu" : {
23537 "cut" : {
23538 "separator_before" : false,
23539 "separator_after" : false,
23540 "label" : "Cut",
23541 "action" : function (data) {
23542 var inst = $.jstree.reference(data.reference),
23543 obj = inst.get_node(data.reference);
23544 if(inst.is_selected(obj)) {
23545 inst.cut(inst.get_selected());
23546 }
23547 else {
23548 inst.cut(obj);
23549 }
23550 }
23551 },
23552 "copy" : {
23553 "separator_before" : false,
23554 "icon" : false,
23555 "separator_after" : false,
23556 "label" : "Copy",
23557 "action" : function (data) {
23558 var inst = $.jstree.reference(data.reference),
23559 obj = inst.get_node(data.reference);
23560 if(inst.is_selected(obj)) {
23561 inst.copy(inst.get_selected());
23562 }
23563 else {
23564 inst.copy(obj);
23565 }
23566 }
23567 },
23568 "paste" : {
23569 "separator_before" : false,
23570 "icon" : false,
23571 "_disabled" : function (data) {
23572 return !$.jstree.reference(data.reference).can_paste();
23573 },
23574 "separator_after" : false,
23575 "label" : "Paste",
23576 "action" : function (data) {
23577 var inst = $.jstree.reference(data.reference),
23578 obj = inst.get_node(data.reference);
23579 inst.paste(obj);
23580 }
23581 }
23582 }
23583 }
23584 };
23585 }
23586 };
23587
23588 $.jstree.plugins.contextmenu = function (options, parent) {
23589 this.bind = function () {
23590 parent.bind.call(this);
23591
23592 var last_ts = 0;
23593 this.element
23594 .on("contextmenu.jstree", ".jstree-anchor", $.proxy(function (e, data) {
23595 e.preventDefault();
23596 last_ts = e.ctrlKey ? +new Date() : 0;
23597 if(data || cto) {
23598 last_ts = (+new Date()) + 10000;
23599 }
23600 if(cto) {
23601 clearTimeout(cto);
23602 }
23603 if(!this.is_loading(e.currentTarget)) {
23604 this.show_contextmenu(e.currentTarget, e.pageX, e.pageY, e);
23605 }
23606 }, this))
23607 .on("click.jstree", ".jstree-anchor", $.proxy(function (e) {
23608 if(this._data.contextmenu.visible && (!last_ts || (+new Date()) - last_ts > 250)) { // work around safari & macOS ctrl+click
23609 $.vakata.context.hide();
23610 }
23611 last_ts = 0;
23612 }, this))
23613 .on("touchstart.jstree", ".jstree-anchor", function (e) {
23614 if(!e.originalEvent || !e.originalEvent.changedTouches || !e.originalEvent.changedTouches[0]) {
23615 return;
23616 }
23617 ex = e.pageX;
23618 ey = e.pageY;
23619 cto = setTimeout(function () {
23620 $(e.currentTarget).trigger('contextmenu', true);
23621 }, 750);
23622 });
23623 /*
23624 if(!('oncontextmenu' in document.body) && ('ontouchstart' in document.body)) {
23625 var el = null, tm = null;
23626 this.element
23627 .on("touchstart", ".jstree-anchor", function (e) {
23628 el = e.currentTarget;
23629 tm = +new Date();
23630 $(document).one("touchend", function (e) {
23631 e.target = document.elementFromPoint(e.originalEvent.targetTouches[0].pageX - window.pageXOffset, e.originalEvent.targetTouches[0].pageY - window.pageYOffset);
23632 e.currentTarget = e.target;
23633 tm = ((+(new Date())) - tm);
23634 if(e.target === el && tm > 600 && tm < 1000) {
23635 e.preventDefault();
23636 $(el).trigger('contextmenu', e);
23637 }
23638 el = null;
23639 tm = null;
23640 });
23641 });
23642 }
23643 */
23644 $(document).on("context_hide.vakata.jstree", $.proxy(function () { this._data.contextmenu.visible = false; }, this));
23645 };
23646 this.teardown = function () {
23647 if(this._data.contextmenu.visible) {
23648 $.vakata.context.hide();
23649 }
23650 parent.teardown.call(this);
23651 };
23652
23653 /**
23654 * prepare and show the context menu for a node
23655 * @name show_contextmenu(obj [, x, y])
23656 * @param {mixed} obj the node
23657 * @param {Number} x the x-coordinate relative to the document to show the menu at
23658 * @param {Number} y the y-coordinate relative to the document to show the menu at
23659 * @param {Object} e the event if available that triggered the contextmenu
23660 * @plugin contextmenu
23661 * @trigger show_contextmenu.jstree
23662 */
23663 this.show_contextmenu = function (obj, x, y, e) {
23664 obj = this.get_node(obj);
23665 if(!obj || obj.id === '#') { return false; }
23666 var s = this.settings.contextmenu,
23667 d = this.get_node(obj, true),
23668 a = d.children(".jstree-anchor"),
23669 o = false,
23670 i = false;
23671 if(s.show_at_node || x === undefined || y === undefined) {
23672 o = a.offset();
23673 x = o.left;
23674 y = o.top + this._data.core.li_height;
23675 }
23676 if(this.settings.contextmenu.select_node && !this.is_selected(obj)) {
23677 this.activate_node(obj, e);
23678 }
23679
23680 i = s.items;
23681 if($.isFunction(i)) {
23682 i = i.call(this, obj, $.proxy(function (i) {
23683 this._show_contextmenu(obj, x, y, i);
23684 }, this));
23685 }
23686 if($.isPlainObject(i)) {
23687 this._show_contextmenu(obj, x, y, i);
23688 }
23689 };
23690 /**
23691 * show the prepared context menu for a node
23692 * @name _show_contextmenu(obj, x, y, i)
23693 * @param {mixed} obj the node
23694 * @param {Number} x the x-coordinate relative to the document to show the menu at
23695 * @param {Number} y the y-coordinate relative to the document to show the menu at
23696 * @param {Number} i the object of items to show
23697 * @plugin contextmenu
23698 * @trigger show_contextmenu.jstree
23699 * @private
23700 */
23701 this._show_contextmenu = function (obj, x, y, i) {
23702 var d = this.get_node(obj, true),
23703 a = d.children(".jstree-anchor");
23704 $(document).one("context_show.vakata.jstree", $.proxy(function (e, data) {
23705 var cls = 'jstree-contextmenu jstree-' + this.get_theme() + '-contextmenu';
23706 $(data.element).addClass(cls);
23707 }, this));
23708 this._data.contextmenu.visible = true;
23709 $.vakata.context.show(a, { 'x' : x, 'y' : y }, i);
23710 /**
23711 * triggered when the contextmenu is shown for a node
23712 * @event
23713 * @name show_contextmenu.jstree
23714 * @param {Object} node the node
23715 * @param {Number} x the x-coordinate of the menu relative to the document
23716 * @param {Number} y the y-coordinate of the menu relative to the document
23717 * @plugin contextmenu
23718 */
23719 this.trigger('show_contextmenu', { "node" : obj, "x" : x, "y" : y });
23720 };
23721 };
23722
23723 $(function () {
23724 $(document)
23725 .on('touchmove.vakata.jstree', function (e) {
23726 if(cto && e.originalEvent && e.originalEvent.changedTouches && e.originalEvent.changedTouches[0] && (Math.abs(ex - e.pageX) > 50 || Math.abs(ey - e.pageY) > 50)) {
23727 clearTimeout(cto);
23728 }
23729 })
23730 .on('touchend.vakata.jstree', function (e) {
23731 if(cto) {
23732 clearTimeout(cto);
23733 }
23734 });
23735 });
23736
23737 // contextmenu helper
23738 (function ($) {
23739 var right_to_left = false,
23740 vakata_context = {
23741 element : false,
23742 reference : false,
23743 position_x : 0,
23744 position_y : 0,
23745 items : [],
23746 html : "",
23747 is_visible : false
23748 };
23749
23750 $.vakata.context = {
23751 settings : {
23752 hide_onmouseleave : 0,
23753 icons : true
23754 },
23755 _trigger : function (event_name) {
23756 $(document).triggerHandler("context_" + event_name + ".vakata", {
23757 "reference" : vakata_context.reference,
23758 "element" : vakata_context.element,
23759 "position" : {
23760 "x" : vakata_context.position_x,
23761 "y" : vakata_context.position_y
23762 }
23763 });
23764 },
23765 _execute : function (i) {
23766 i = vakata_context.items[i];
23767 return i && (!i._disabled || ($.isFunction(i._disabled) && !i._disabled({ "item" : i, "reference" : vakata_context.reference, "element" : vakata_context.element }))) && i.action ? i.action.call(null, {
23768 "item" : i,
23769 "reference" : vakata_context.reference,
23770 "element" : vakata_context.element,
23771 "position" : {
23772 "x" : vakata_context.position_x,
23773 "y" : vakata_context.position_y
23774 }
23775 }) : false;
23776 },
23777 _parse : function (o, is_callback) {
23778 if(!o) { return false; }
23779 if(!is_callback) {
23780 vakata_context.html = "";
23781 vakata_context.items = [];
23782 }
23783 var str = "",
23784 sep = false,
23785 tmp;
23786
23787 if(is_callback) { str += "<"+"ul>"; }
23788 $.each(o, function (i, val) {
23789 if(!val) { return true; }
23790 vakata_context.items.push(val);
23791 if(!sep && val.separator_before) {
23792 str += "<"+"li class='vakata-context-separator'><"+"a href='#' " + ($.vakata.context.settings.icons ? '' : 'style="margin-left:0px;"') + ">&#160;<"+"/a><"+"/li>";
23793 }
23794 sep = false;
23795 str += "<"+"li class='" + (val._class || "") + (val._disabled === true || ($.isFunction(val._disabled) && val._disabled({ "item" : val, "reference" : vakata_context.reference, "element" : vakata_context.element })) ? " vakata-contextmenu-disabled " : "") + "' "+(val.shortcut?" data-shortcut='"+val.shortcut+"' ":'')+">";
23796 str += "<"+"a href='#' rel='" + (vakata_context.items.length - 1) + "'>";
23797 if($.vakata.context.settings.icons) {
23798 str += "<"+"i ";
23799 if(val.icon) {
23800 if(val.icon.indexOf("/") !== -1 || val.icon.indexOf(".") !== -1) { str += " style='background:url(\"" + val.icon + "\") center center no-repeat' "; }
23801 else { str += " class='" + val.icon + "' "; }
23802 }
23803 str += "><"+"/i><"+"span class='vakata-contextmenu-sep'>&#160;<"+"/span>";
23804 }
23805 str += ($.isFunction(val.label) ? val.label({ "item" : i, "reference" : vakata_context.reference, "element" : vakata_context.element }) : val.label) + (val.shortcut?' <span class="vakata-contextmenu-shortcut vakata-contextmenu-shortcut-'+val.shortcut+'">'+ (val.shortcut_label || '') +'</span>':'') + "<"+"/a>";
23806 if(val.submenu) {
23807 tmp = $.vakata.context._parse(val.submenu, true);
23808 if(tmp) { str += tmp; }
23809 }
23810 str += "<"+"/li>";
23811 if(val.separator_after) {
23812 str += "<"+"li class='vakata-context-separator'><"+"a href='#' " + ($.vakata.context.settings.icons ? '' : 'style="margin-left:0px;"') + ">&#160;<"+"/a><"+"/li>";
23813 sep = true;
23814 }
23815 });
23816 str = str.replace(/<li class\='vakata-context-separator'\><\/li\>$/,"");
23817 if(is_callback) { str += "</ul>"; }
23818 /**
23819 * triggered on the document when the contextmenu is parsed (HTML is built)
23820 * @event
23821 * @plugin contextmenu
23822 * @name context_parse.vakata
23823 * @param {jQuery} reference the element that was right clicked
23824 * @param {jQuery} element the DOM element of the menu itself
23825 * @param {Object} position the x & y coordinates of the menu
23826 */
23827 if(!is_callback) { vakata_context.html = str; $.vakata.context._trigger("parse"); }
23828 return str.length > 10 ? str : false;
23829 },
23830 _show_submenu : function (o) {
23831 o = $(o);
23832 if(!o.length || !o.children("ul").length) { return; }
23833 var e = o.children("ul"),
23834 x = o.offset().left + o.outerWidth(),
23835 y = o.offset().top,
23836 w = e.width(),
23837 h = e.height(),
23838 dw = $(window).width() + $(window).scrollLeft(),
23839 dh = $(window).height() + $(window).scrollTop();
23840 // може да се спести е една проверка - дали няма някой от класовете вече нагоре
23841 if(right_to_left) {
23842 o[x - (w + 10 + o.outerWidth()) < 0 ? "addClass" : "removeClass"]("vakata-context-left");
23843 }
23844 else {
23845 o[x + w + 10 > dw ? "addClass" : "removeClass"]("vakata-context-right");
23846 }
23847 if(y + h + 10 > dh) {
23848 e.css("bottom","-1px");
23849 }
23850 e.show();
23851 },
23852 show : function (reference, position, data) {
23853 var o, e, x, y, w, h, dw, dh, cond = true;
23854 if(vakata_context.element && vakata_context.element.length) {
23855 vakata_context.element.width('');
23856 }
23857 switch(cond) {
23858 case (!position && !reference):
23859 return false;
23860 case (!!position && !!reference):
23861 vakata_context.reference = reference;
23862 vakata_context.position_x = position.x;
23863 vakata_context.position_y = position.y;
23864 break;
23865 case (!position && !!reference):
23866 vakata_context.reference = reference;
23867 o = reference.offset();
23868 vakata_context.position_x = o.left + reference.outerHeight();
23869 vakata_context.position_y = o.top;
23870 break;
23871 case (!!position && !reference):
23872 vakata_context.position_x = position.x;
23873 vakata_context.position_y = position.y;
23874 break;
23875 }
23876 if(!!reference && !data && $(reference).data('vakata_contextmenu')) {
23877 data = $(reference).data('vakata_contextmenu');
23878 }
23879 if($.vakata.context._parse(data)) {
23880 vakata_context.element.html(vakata_context.html);
23881 }
23882 if(vakata_context.items.length) {
23883 vakata_context.element.appendTo("body");
23884 e = vakata_context.element;
23885 x = vakata_context.position_x;
23886 y = vakata_context.position_y;
23887 w = e.width();
23888 h = e.height();
23889 dw = $(window).width() + $(window).scrollLeft();
23890 dh = $(window).height() + $(window).scrollTop();
23891 if(right_to_left) {
23892 x -= (e.outerWidth() - $(reference).outerWidth());
23893 if(x < $(window).scrollLeft() + 20) {
23894 x = $(window).scrollLeft() + 20;
23895 }
23896 }
23897 if(x + w + 20 > dw) {
23898 x = dw - (w + 20);
23899 }
23900 if(y + h + 20 > dh) {
23901 y = dh - (h + 20);
23902 }
23903
23904 vakata_context.element
23905 .css({ "left" : x, "top" : y })
23906 .show()
23907 .find('a').first().focus().parent().addClass("vakata-context-hover");
23908 vakata_context.is_visible = true;
23909 /**
23910 * triggered on the document when the contextmenu is shown
23911 * @event
23912 * @plugin contextmenu
23913 * @name context_show.vakata
23914 * @param {jQuery} reference the element that was right clicked
23915 * @param {jQuery} element the DOM element of the menu itself
23916 * @param {Object} position the x & y coordinates of the menu
23917 */
23918 $.vakata.context._trigger("show");
23919 }
23920 },
23921 hide : function () {
23922 if(vakata_context.is_visible) {
23923 vakata_context.element.hide().find("ul").hide().end().find(':focus').blur().end().detach();
23924 vakata_context.is_visible = false;
23925 /**
23926 * triggered on the document when the contextmenu is hidden
23927 * @event
23928 * @plugin contextmenu
23929 * @name context_hide.vakata
23930 * @param {jQuery} reference the element that was right clicked
23931 * @param {jQuery} element the DOM element of the menu itself
23932 * @param {Object} position the x & y coordinates of the menu
23933 */
23934 $.vakata.context._trigger("hide");
23935 }
23936 }
23937 };
23938 $(function () {
23939 right_to_left = $("body").css("direction") === "rtl";
23940 var to = false;
23941
23942 vakata_context.element = $("<ul class='vakata-context'></ul>");
23943 vakata_context.element
23944 .on("mouseenter", "li", function (e) {
23945 e.stopImmediatePropagation();
23946
23947 if($.contains(this, e.relatedTarget)) {
23948 // премахнато заради delegate mouseleave по-долу
23949 // $(this).find(".vakata-context-hover").removeClass("vakata-context-hover");
23950 return;
23951 }
23952
23953 if(to) { clearTimeout(to); }
23954 vakata_context.element.find(".vakata-context-hover").removeClass("vakata-context-hover").end();
23955
23956 $(this)
23957 .siblings().find("ul").hide().end().end()
23958 .parentsUntil(".vakata-context", "li").addBack().addClass("vakata-context-hover");
23959 $.vakata.context._show_submenu(this);
23960 })
23961 // тестово - дали не натоварва?
23962 .on("mouseleave", "li", function (e) {
23963 if($.contains(this, e.relatedTarget)) { return; }
23964 $(this).find(".vakata-context-hover").addBack().removeClass("vakata-context-hover");
23965 })
23966 .on("mouseleave", function (e) {
23967 $(this).find(".vakata-context-hover").removeClass("vakata-context-hover");
23968 if($.vakata.context.settings.hide_onmouseleave) {
23969 to = setTimeout(
23970 (function (t) {
23971 return function () { $.vakata.context.hide(); };
23972 }(this)), $.vakata.context.settings.hide_onmouseleave);
23973 }
23974 })
23975 .on("click", "a", function (e) {
23976 e.preventDefault();
23977 //})
23978 //.on("mouseup", "a", function (e) {
23979 if(!$(this).blur().parent().hasClass("vakata-context-disabled") && $.vakata.context._execute($(this).attr("rel")) !== false) {
23980 $.vakata.context.hide();
23981 }
23982 })
23983 .on('keydown', 'a', function (e) {
23984 var o = null;
23985 switch(e.which) {
23986 case 13:
23987 case 32:
23988 e.type = "mouseup";
23989 e.preventDefault();
23990 $(e.currentTarget).trigger(e);
23991 break;
23992 case 37:
23993 if(vakata_context.is_visible) {
23994 vakata_context.element.find(".vakata-context-hover").last().closest("li").first().find("ul").hide().find(".vakata-context-hover").removeClass("vakata-context-hover").end().end().children('a').focus();
23995 e.stopImmediatePropagation();
23996 e.preventDefault();
23997 }
23998 break;
23999 case 38:
24000 if(vakata_context.is_visible) {
24001 o = vakata_context.element.find("ul:visible").addBack().last().children(".vakata-context-hover").removeClass("vakata-context-hover").prevAll("li:not(.vakata-context-separator)").first();
24002 if(!o.length) { o = vakata_context.element.find("ul:visible").addBack().last().children("li:not(.vakata-context-separator)").last(); }
24003 o.addClass("vakata-context-hover").children('a').focus();
24004 e.stopImmediatePropagation();
24005 e.preventDefault();
24006 }
24007 break;
24008 case 39:
24009 if(vakata_context.is_visible) {
24010 vakata_context.element.find(".vakata-context-hover").last().children("ul").show().children("li:not(.vakata-context-separator)").removeClass("vakata-context-hover").first().addClass("vakata-context-hover").children('a').focus();
24011 e.stopImmediatePropagation();
24012 e.preventDefault();
24013 }
24014 break;
24015 case 40:
24016 if(vakata_context.is_visible) {
24017 o = vakata_context.element.find("ul:visible").addBack().last().children(".vakata-context-hover").removeClass("vakata-context-hover").nextAll("li:not(.vakata-context-separator)").first();
24018 if(!o.length) { o = vakata_context.element.find("ul:visible").addBack().last().children("li:not(.vakata-context-separator)").first(); }
24019 o.addClass("vakata-context-hover").children('a').focus();
24020 e.stopImmediatePropagation();
24021 e.preventDefault();
24022 }
24023 break;
24024 case 27:
24025 $.vakata.context.hide();
24026 e.preventDefault();
24027 break;
24028 default:
24029 //console.log(e.which);
24030 break;
24031 }
24032 })
24033 .on('keydown', function (e) {
24034 e.preventDefault();
24035 var a = vakata_context.element.find('.vakata-contextmenu-shortcut-' + e.which).parent();
24036 if(a.parent().not('.vakata-context-disabled')) {
24037 a.click();
24038 }
24039 });
24040
24041 $(document)
24042 .on("mousedown.vakata.jstree", function (e) {
24043 if(vakata_context.is_visible && !$.contains(vakata_context.element[0], e.target)) {
24044 $.vakata.context.hide();
24045 }
24046 })
24047 .on("context_show.vakata.jstree", function (e, data) {
24048 vakata_context.element.find("li:has(ul)").children("a").addClass("vakata-context-parent");
24049 if(right_to_left) {
24050 vakata_context.element.addClass("vakata-context-rtl").css("direction", "rtl");
24051 }
24052 // also apply a RTL class?
24053 vakata_context.element.find("ul").hide().end();
24054 });
24055 });
24056 }($));
24057 // $.jstree.defaults.plugins.push("contextmenu");
24058
24059 /**
24060 * ### Drag'n'drop plugin
24061 *
24062 * Enables dragging and dropping of nodes in the tree, resulting in a move or copy operations.
24063 */
24064
24065 /**
24066 * stores all defaults for the drag'n'drop plugin
24067 * @name $.jstree.defaults.dnd
24068 * @plugin dnd
24069 */
24070 $.jstree.defaults.dnd = {
24071 /**
24072 * a boolean indicating if a copy should be possible while dragging (by pressint the meta key or Ctrl). Defaults to `true`.
24073 * @name $.jstree.defaults.dnd.copy
24074 * @plugin dnd
24075 */
24076 copy : true,
24077 /**
24078 * a number indicating how long a node should remain hovered while dragging to be opened. Defaults to `500`.
24079 * @name $.jstree.defaults.dnd.open_timeout
24080 * @plugin dnd
24081 */
24082 open_timeout : 500,
24083 /**
24084 * a function invoked each time a node is about to be dragged, invoked in the tree's scope and receives the nodes about to be dragged as an argument (array) - return `false` to prevent dragging
24085 * @name $.jstree.defaults.dnd.is_draggable
24086 * @plugin dnd
24087 */
24088 is_draggable : true,
24089 /**
24090 * a boolean indicating if checks should constantly be made while the user is dragging the node (as opposed to checking only on drop), default is `true`
24091 * @name $.jstree.defaults.dnd.check_while_dragging
24092 * @plugin dnd
24093 */
24094 check_while_dragging : true,
24095 /**
24096 * a boolean indicating if nodes from this tree should only be copied with dnd (as opposed to moved), default is `false`
24097 * @name $.jstree.defaults.dnd.always_copy
24098 * @plugin dnd
24099 */
24100 always_copy : false,
24101 /**
24102 * when dropping a node "inside", this setting indicates the position the node should go to - it can be an integer or a string: "first" (same as 0) or "last", default is `0`
24103 * @name $.jstree.defaults.dnd.inside_pos
24104 * @plugin dnd
24105 */
24106 inside_pos : 0,
24107 /**
24108 * when starting the drag on a node that is selected this setting controls if all selected nodes are dragged or only the single node, default is `true`, which means all selected nodes are dragged when the drag is started on a selected node
24109 * @name $.jstree.defaults.dnd.drag_selection
24110 * @plugin dnd
24111 */
24112 drag_selection : true,
24113 /**
24114 * controls whether dnd works on touch devices. If left as boolean true dnd will work the same as in desktop browsers, which in some cases may impair scrolling. If set to boolean false dnd will not work on touch devices. There is a special third option - string "selected" which means only selected nodes can be dragged on touch devices.
24115 * @name $.jstree.defaults.dnd.touch
24116 * @plugin dnd
24117 */
24118 touch : true
24119 };
24120 // TODO: now check works by checking for each node individually, how about max_children, unique, etc?
24121 $.jstree.plugins.dnd = function (options, parent) {
24122 this.bind = function () {
24123 parent.bind.call(this);
24124
24125 this.element
24126 .on('mousedown.jstree touchstart.jstree', '.jstree-anchor', $.proxy(function (e) {
24127 if(e.type === "touchstart" && (!this.settings.dnd.touch || (this.settings.dnd.touch === 'selected' && !$(e.currentTarget).hasClass('jstree-clicked')))) {
24128 return true;
24129 }
24130 var obj = this.get_node(e.target),
24131 mlt = this.is_selected(obj) && this.settings.drag_selection ? this.get_selected().length : 1,
24132 txt = (mlt > 1 ? mlt + ' ' + this.get_string('nodes') : this.get_text(e.currentTarget));
24133 if(this.settings.core.force_text) {
24134 txt = $('<div />').text(txt).html();
24135 }
24136 if(obj && obj.id && obj.id !== "#" && (e.which === 1 || e.type === "touchstart") &&
24137 (this.settings.dnd.is_draggable === true || ($.isFunction(this.settings.dnd.is_draggable) && this.settings.dnd.is_draggable.call(this, (mlt > 1 ? this.get_selected(true) : [obj]))))
24138 ) {
24139 this.element.trigger('mousedown.jstree');
24140 return $.vakata.dnd.start(e, { 'jstree' : true, 'origin' : this, 'obj' : this.get_node(obj,true), 'nodes' : mlt > 1 ? this.get_selected() : [obj.id] }, '<div id="jstree-dnd" class="jstree-' + this.get_theme() + ' jstree-' + this.get_theme() + '-' + this.get_theme_variant() + ' ' + ( this.settings.core.themes.responsive ? ' jstree-dnd-responsive' : '' ) + '"><i class="jstree-icon jstree-er"></i>' + txt + '<ins class="jstree-copy" style="display:none;">+</ins></div>');
24141 }
24142 }, this));
24143 };
24144 };
24145
24146 $(function() {
24147 // bind only once for all instances
24148 var lastmv = false,
24149 laster = false,
24150 opento = false,
24151 marker = $('<div id="jstree-marker">&#160;</div>').hide(); //.appendTo('body');
24152
24153 $(document)
24154 .on('dnd_start.vakata.jstree', function (e, data) {
24155 lastmv = false;
24156 if(!data || !data.data || !data.data.jstree) { return; }
24157 marker.appendTo('body'); //.show();
24158 })
24159 .on('dnd_move.vakata.jstree', function (e, data) {
24160 if(opento) { clearTimeout(opento); }
24161 if(!data || !data.data || !data.data.jstree) { return; }
24162
24163 // if we are hovering the marker image do nothing (can happen on "inside" drags)
24164 if(data.event.target.id && data.event.target.id === 'jstree-marker') {
24165 return;
24166 }
24167
24168 var ins = $.jstree.reference(data.event.target),
24169 ref = false,
24170 off = false,
24171 rel = false,
24172 l, t, h, p, i, o, ok, t1, t2, op, ps, pr, ip, tm;
24173 // if we are over an instance
24174 if(ins && ins._data && ins._data.dnd) {
24175 marker.attr('class', 'jstree-' + ins.get_theme() + ( ins.settings.core.themes.responsive ? ' jstree-dnd-responsive' : '' ));
24176 data.helper
24177 .children().attr('class', 'jstree-' + ins.get_theme() + ' jstree-' + ins.get_theme() + '-' + ins.get_theme_variant() + ' ' + ( ins.settings.core.themes.responsive ? ' jstree-dnd-responsive' : '' ))
24178 .find('.jstree-copy').first()[ data.data.origin && (data.data.origin.settings.dnd.always_copy || (data.data.origin.settings.dnd.copy && (data.event.metaKey || data.event.ctrlKey))) ? 'show' : 'hide' ]();
24179
24180
24181 // if are hovering the container itself add a new root node
24182 if( (data.event.target === ins.element[0] || data.event.target === ins.get_container_ul()[0]) && ins.get_container_ul().children().length === 0) {
24183 ok = true;
24184 for(t1 = 0, t2 = data.data.nodes.length; t1 < t2; t1++) {
24185 ok = ok && ins.check( (data.data.origin && (data.data.origin.settings.dnd.always_copy || (data.data.origin.settings.dnd.copy && (data.event.metaKey || data.event.ctrlKey)) ) ? "copy_node" : "move_node"), (data.data.origin && data.data.origin !== ins ? data.data.origin.get_node(data.data.nodes[t1]) : data.data.nodes[t1]), '#', 'last', { 'dnd' : true, 'ref' : ins.get_node('#'), 'pos' : 'i', 'is_multi' : (data.data.origin && data.data.origin !== ins), 'is_foreign' : (!data.data.origin) });
24186 if(!ok) { break; }
24187 }
24188 if(ok) {
24189 lastmv = { 'ins' : ins, 'par' : '#', 'pos' : 'last' };
24190 marker.hide();
24191 data.helper.find('.jstree-icon').first().removeClass('jstree-er').addClass('jstree-ok');
24192 return;
24193 }
24194 }
24195 else {
24196 // if we are hovering a tree node
24197 ref = $(data.event.target).closest('.jstree-anchor');
24198 if(ref && ref.length && ref.parent().is('.jstree-closed, .jstree-open, .jstree-leaf')) {
24199 off = ref.offset();
24200 rel = data.event.pageY - off.top;
24201 h = ref.height();
24202 if(rel < h / 3) {
24203 o = ['b', 'i', 'a'];
24204 }
24205 else if(rel > h - h / 3) {
24206 o = ['a', 'i', 'b'];
24207 }
24208 else {
24209 o = rel > h / 2 ? ['i', 'a', 'b'] : ['i', 'b', 'a'];
24210 }
24211 $.each(o, function (j, v) {
24212 switch(v) {
24213 case 'b':
24214 l = off.left - 6;
24215 t = off.top;
24216 p = ins.get_parent(ref);
24217 i = ref.parent().index();
24218 break;
24219 case 'i':
24220 ip = ins.settings.dnd.inside_pos;
24221 tm = ins.get_node(ref.parent());
24222 l = off.left - 2;
24223 t = off.top + h / 2 + 1;
24224 p = tm.id;
24225 i = ip === 'first' ? 0 : (ip === 'last' ? tm.children.length : Math.min(ip, tm.children.length));
24226 break;
24227 case 'a':
24228 l = off.left - 6;
24229 t = off.top + h;
24230 p = ins.get_parent(ref);
24231 i = ref.parent().index() + 1;
24232 break;
24233 }
24234 ok = true;
24235 for(t1 = 0, t2 = data.data.nodes.length; t1 < t2; t1++) {
24236 op = data.data.origin && (data.data.origin.settings.dnd.always_copy || (data.data.origin.settings.dnd.copy && (data.event.metaKey || data.event.ctrlKey))) ? "copy_node" : "move_node";
24237 ps = i;
24238 if(op === "move_node" && v === 'a' && (data.data.origin && data.data.origin === ins) && p === ins.get_parent(data.data.nodes[t1])) {
24239 pr = ins.get_node(p);
24240 if(ps > $.inArray(data.data.nodes[t1], pr.children)) {
24241 ps -= 1;
24242 }
24243 }
24244 ok = ok && ( (ins && ins.settings && ins.settings.dnd && ins.settings.dnd.check_while_dragging === false) || ins.check(op, (data.data.origin && data.data.origin !== ins ? data.data.origin.get_node(data.data.nodes[t1]) : data.data.nodes[t1]), p, ps, { 'dnd' : true, 'ref' : ins.get_node(ref.parent()), 'pos' : v, 'is_multi' : (data.data.origin && data.data.origin !== ins), 'is_foreign' : (!data.data.origin) }) );
24245 if(!ok) {
24246 if(ins && ins.last_error) { laster = ins.last_error(); }
24247 break;
24248 }
24249 }
24250 if(v === 'i' && ref.parent().is('.jstree-closed') && ins.settings.dnd.open_timeout) {
24251 opento = setTimeout((function (x, z) { return function () { x.open_node(z); }; }(ins, ref)), ins.settings.dnd.open_timeout);
24252 }
24253 if(ok) {
24254 lastmv = { 'ins' : ins, 'par' : p, 'pos' : v === 'i' && ip === 'last' && i === 0 && !ins.is_loaded(tm) ? 'last' : i };
24255 marker.css({ 'left' : l + 'px', 'top' : t + 'px' }).show();
24256 data.helper.find('.jstree-icon').first().removeClass('jstree-er').addClass('jstree-ok');
24257 laster = {};
24258 o = true;
24259 return false;
24260 }
24261 });
24262 if(o === true) { return; }
24263 }
24264 }
24265 }
24266 lastmv = false;
24267 data.helper.find('.jstree-icon').removeClass('jstree-ok').addClass('jstree-er');
24268 marker.hide();
24269 })
24270 .on('dnd_scroll.vakata.jstree', function (e, data) {
24271 if(!data || !data.data || !data.data.jstree) { return; }
24272 marker.hide();
24273 lastmv = false;
24274 data.helper.find('.jstree-icon').first().removeClass('jstree-ok').addClass('jstree-er');
24275 })
24276 .on('dnd_stop.vakata.jstree', function (e, data) {
24277 if(opento) { clearTimeout(opento); }
24278 if(!data || !data.data || !data.data.jstree) { return; }
24279 marker.hide().detach();
24280 var i, j, nodes = [];
24281 if(lastmv) {
24282 for(i = 0, j = data.data.nodes.length; i < j; i++) {
24283 nodes[i] = data.data.origin ? data.data.origin.get_node(data.data.nodes[i]) : data.data.nodes[i];
24284 if(data.data.origin) {
24285 nodes[i].instance = data.data.origin;
24286 }
24287 }
24288 lastmv.ins[ data.data.origin && (data.data.origin.settings.dnd.always_copy || (data.data.origin.settings.dnd.copy && (data.event.metaKey || data.event.ctrlKey))) ? 'copy_node' : 'move_node' ](nodes, lastmv.par, lastmv.pos);
24289 for(i = 0, j = nodes.length; i < j; i++) {
24290 if(nodes[i].instance) {
24291 nodes[i].instance = null;
24292 }
24293 }
24294 }
24295 else {
24296 i = $(data.event.target).closest('.jstree');
24297 if(i.length && laster && laster.error && laster.error === 'check') {
24298 i = i.jstree(true);
24299 if(i) {
24300 i.settings.core.error.call(this, laster);
24301 }
24302 }
24303 }
24304 })
24305 .on('keyup.jstree keydown.jstree', function (e, data) {
24306 data = $.vakata.dnd._get();
24307 if(data && data.data && data.data.jstree) {
24308 data.helper.find('.jstree-copy').first()[ data.data.origin && (data.data.origin.settings.dnd.always_copy || (data.data.origin.settings.dnd.copy && (e.metaKey || e.ctrlKey))) ? 'show' : 'hide' ]();
24309 }
24310 });
24311 });
24312
24313 // helpers
24314 (function ($) {
24315 // private variable
24316 var vakata_dnd = {
24317 element : false,
24318 target : false,
24319 is_down : false,
24320 is_drag : false,
24321 helper : false,
24322 helper_w: 0,
24323 data : false,
24324 init_x : 0,
24325 init_y : 0,
24326 scroll_l: 0,
24327 scroll_t: 0,
24328 scroll_e: false,
24329 scroll_i: false,
24330 is_touch: false
24331 };
24332 $.vakata.dnd = {
24333 settings : {
24334 scroll_speed : 10,
24335 scroll_proximity : 20,
24336 helper_left : 5,
24337 helper_top : 10,
24338 threshold : 5,
24339 threshold_touch : 50
24340 },
24341 _trigger : function (event_name, e) {
24342 var data = $.vakata.dnd._get();
24343 data.event = e;
24344 $(document).triggerHandler("dnd_" + event_name + ".vakata", data);
24345 },
24346 _get : function () {
24347 return {
24348 "data" : vakata_dnd.data,
24349 "element" : vakata_dnd.element,
24350 "helper" : vakata_dnd.helper
24351 };
24352 },
24353 _clean : function () {
24354 if(vakata_dnd.helper) { vakata_dnd.helper.remove(); }
24355 if(vakata_dnd.scroll_i) { clearInterval(vakata_dnd.scroll_i); vakata_dnd.scroll_i = false; }
24356 vakata_dnd = {
24357 element : false,
24358 target : false,
24359 is_down : false,
24360 is_drag : false,
24361 helper : false,
24362 helper_w: 0,
24363 data : false,
24364 init_x : 0,
24365 init_y : 0,
24366 scroll_l: 0,
24367 scroll_t: 0,
24368 scroll_e: false,
24369 scroll_i: false,
24370 is_touch: false
24371 };
24372 $(document).off("mousemove.vakata.jstree touchmove.vakata.jstree", $.vakata.dnd.drag);
24373 $(document).off("mouseup.vakata.jstree touchend.vakata.jstree", $.vakata.dnd.stop);
24374 },
24375 _scroll : function (init_only) {
24376 if(!vakata_dnd.scroll_e || (!vakata_dnd.scroll_l && !vakata_dnd.scroll_t)) {
24377 if(vakata_dnd.scroll_i) { clearInterval(vakata_dnd.scroll_i); vakata_dnd.scroll_i = false; }
24378 return false;
24379 }
24380 if(!vakata_dnd.scroll_i) {
24381 vakata_dnd.scroll_i = setInterval($.vakata.dnd._scroll, 100);
24382 return false;
24383 }
24384 if(init_only === true) { return false; }
24385
24386 var i = vakata_dnd.scroll_e.scrollTop(),
24387 j = vakata_dnd.scroll_e.scrollLeft();
24388 vakata_dnd.scroll_e.scrollTop(i + vakata_dnd.scroll_t * $.vakata.dnd.settings.scroll_speed);
24389 vakata_dnd.scroll_e.scrollLeft(j + vakata_dnd.scroll_l * $.vakata.dnd.settings.scroll_speed);
24390 if(i !== vakata_dnd.scroll_e.scrollTop() || j !== vakata_dnd.scroll_e.scrollLeft()) {
24391 /**
24392 * triggered on the document when a drag causes an element to scroll
24393 * @event
24394 * @plugin dnd
24395 * @name dnd_scroll.vakata
24396 * @param {Mixed} data any data supplied with the call to $.vakata.dnd.start
24397 * @param {DOM} element the DOM element being dragged
24398 * @param {jQuery} helper the helper shown next to the mouse
24399 * @param {jQuery} event the element that is scrolling
24400 */
24401 $.vakata.dnd._trigger("scroll", vakata_dnd.scroll_e);
24402 }
24403 },
24404 start : function (e, data, html) {
24405 if(e.type === "touchstart" && e.originalEvent && e.originalEvent.changedTouches && e.originalEvent.changedTouches[0]) {
24406 e.pageX = e.originalEvent.changedTouches[0].pageX;
24407 e.pageY = e.originalEvent.changedTouches[0].pageY;
24408 e.target = document.elementFromPoint(e.originalEvent.changedTouches[0].pageX - window.pageXOffset, e.originalEvent.changedTouches[0].pageY - window.pageYOffset);
24409 }
24410 if(vakata_dnd.is_drag) { $.vakata.dnd.stop({}); }
24411 try {
24412 e.currentTarget.unselectable = "on";
24413 e.currentTarget.onselectstart = function() { return false; };
24414 if(e.currentTarget.style) { e.currentTarget.style.MozUserSelect = "none"; }
24415 } catch(ignore) { }
24416 vakata_dnd.init_x = e.pageX;
24417 vakata_dnd.init_y = e.pageY;
24418 vakata_dnd.data = data;
24419 vakata_dnd.is_down = true;
24420 vakata_dnd.element = e.currentTarget;
24421 vakata_dnd.target = e.target;
24422 vakata_dnd.is_touch = e.type === "touchstart";
24423 if(html !== false) {
24424 vakata_dnd.helper = $("<div id='vakata-dnd'></div>").html(html).css({
24425 "display" : "block",
24426 "margin" : "0",
24427 "padding" : "0",
24428 "position" : "absolute",
24429 "top" : "-2000px",
24430 "lineHeight" : "16px",
24431 "zIndex" : "10000"
24432 });
24433 }
24434 $(document).on("mousemove.vakata.jstree touchmove.vakata.jstree", $.vakata.dnd.drag);
24435 $(document).on("mouseup.vakata.jstree touchend.vakata.jstree", $.vakata.dnd.stop);
24436 return false;
24437 },
24438 drag : function (e) {
24439 if(e.type === "touchmove" && e.originalEvent && e.originalEvent.changedTouches && e.originalEvent.changedTouches[0]) {
24440 e.pageX = e.originalEvent.changedTouches[0].pageX;
24441 e.pageY = e.originalEvent.changedTouches[0].pageY;
24442 e.target = document.elementFromPoint(e.originalEvent.changedTouches[0].pageX - window.pageXOffset, e.originalEvent.changedTouches[0].pageY - window.pageYOffset);
24443 }
24444 if(!vakata_dnd.is_down) { return; }
24445 if(!vakata_dnd.is_drag) {
24446 if(
24447 Math.abs(e.pageX - vakata_dnd.init_x) > (vakata_dnd.is_touch ? $.vakata.dnd.settings.threshold_touch : $.vakata.dnd.settings.threshold) ||
24448 Math.abs(e.pageY - vakata_dnd.init_y) > (vakata_dnd.is_touch ? $.vakata.dnd.settings.threshold_touch : $.vakata.dnd.settings.threshold)
24449 ) {
24450 if(vakata_dnd.helper) {
24451 vakata_dnd.helper.appendTo("body");
24452 vakata_dnd.helper_w = vakata_dnd.helper.outerWidth();
24453 }
24454 vakata_dnd.is_drag = true;
24455 /**
24456 * triggered on the document when a drag starts
24457 * @event
24458 * @plugin dnd
24459 * @name dnd_start.vakata
24460 * @param {Mixed} data any data supplied with the call to $.vakata.dnd.start
24461 * @param {DOM} element the DOM element being dragged
24462 * @param {jQuery} helper the helper shown next to the mouse
24463 * @param {Object} event the event that caused the start (probably mousemove)
24464 */
24465 $.vakata.dnd._trigger("start", e);
24466 }
24467 else { return; }
24468 }
24469
24470 var d = false, w = false,
24471 dh = false, wh = false,
24472 dw = false, ww = false,
24473 dt = false, dl = false,
24474 ht = false, hl = false;
24475
24476 vakata_dnd.scroll_t = 0;
24477 vakata_dnd.scroll_l = 0;
24478 vakata_dnd.scroll_e = false;
24479 $($(e.target).parentsUntil("body").addBack().get().reverse())
24480 .filter(function () {
24481 return (/^auto|scroll$/).test($(this).css("overflow")) &&
24482 (this.scrollHeight > this.offsetHeight || this.scrollWidth > this.offsetWidth);
24483 })
24484 .each(function () {
24485 var t = $(this), o = t.offset();
24486 if(this.scrollHeight > this.offsetHeight) {
24487 if(o.top + t.height() - e.pageY < $.vakata.dnd.settings.scroll_proximity) { vakata_dnd.scroll_t = 1; }
24488 if(e.pageY - o.top < $.vakata.dnd.settings.scroll_proximity) { vakata_dnd.scroll_t = -1; }
24489 }
24490 if(this.scrollWidth > this.offsetWidth) {
24491 if(o.left + t.width() - e.pageX < $.vakata.dnd.settings.scroll_proximity) { vakata_dnd.scroll_l = 1; }
24492 if(e.pageX - o.left < $.vakata.dnd.settings.scroll_proximity) { vakata_dnd.scroll_l = -1; }
24493 }
24494 if(vakata_dnd.scroll_t || vakata_dnd.scroll_l) {
24495 vakata_dnd.scroll_e = $(this);
24496 return false;
24497 }
24498 });
24499
24500 if(!vakata_dnd.scroll_e) {
24501 d = $(document); w = $(window);
24502 dh = d.height(); wh = w.height();
24503 dw = d.width(); ww = w.width();
24504 dt = d.scrollTop(); dl = d.scrollLeft();
24505 if(dh > wh && e.pageY - dt < $.vakata.dnd.settings.scroll_proximity) { vakata_dnd.scroll_t = -1; }
24506 if(dh > wh && wh - (e.pageY - dt) < $.vakata.dnd.settings.scroll_proximity) { vakata_dnd.scroll_t = 1; }
24507 if(dw > ww && e.pageX - dl < $.vakata.dnd.settings.scroll_proximity) { vakata_dnd.scroll_l = -1; }
24508 if(dw > ww && ww - (e.pageX - dl) < $.vakata.dnd.settings.scroll_proximity) { vakata_dnd.scroll_l = 1; }
24509 if(vakata_dnd.scroll_t || vakata_dnd.scroll_l) {
24510 vakata_dnd.scroll_e = d;
24511 }
24512 }
24513 if(vakata_dnd.scroll_e) { $.vakata.dnd._scroll(true); }
24514
24515 if(vakata_dnd.helper) {
24516 ht = parseInt(e.pageY + $.vakata.dnd.settings.helper_top, 10);
24517 hl = parseInt(e.pageX + $.vakata.dnd.settings.helper_left, 10);
24518 if(dh && ht + 25 > dh) { ht = dh - 50; }
24519 if(dw && hl + vakata_dnd.helper_w > dw) { hl = dw - (vakata_dnd.helper_w + 2); }
24520 vakata_dnd.helper.css({
24521 left : hl + "px",
24522 top : ht + "px"
24523 });
24524 }
24525 /**
24526 * triggered on the document when a drag is in progress
24527 * @event
24528 * @plugin dnd
24529 * @name dnd_move.vakata
24530 * @param {Mixed} data any data supplied with the call to $.vakata.dnd.start
24531 * @param {DOM} element the DOM element being dragged
24532 * @param {jQuery} helper the helper shown next to the mouse
24533 * @param {Object} event the event that caused this to trigger (most likely mousemove)
24534 */
24535 $.vakata.dnd._trigger("move", e);
24536 return false;
24537 },
24538 stop : function (e) {
24539 if(e.type === "touchend" && e.originalEvent && e.originalEvent.changedTouches && e.originalEvent.changedTouches[0]) {
24540 e.pageX = e.originalEvent.changedTouches[0].pageX;
24541 e.pageY = e.originalEvent.changedTouches[0].pageY;
24542 e.target = document.elementFromPoint(e.originalEvent.changedTouches[0].pageX - window.pageXOffset, e.originalEvent.changedTouches[0].pageY - window.pageYOffset);
24543 }
24544 if(vakata_dnd.is_drag) {
24545 /**
24546 * triggered on the document when a drag stops (the dragged element is dropped)
24547 * @event
24548 * @plugin dnd
24549 * @name dnd_stop.vakata
24550 * @param {Mixed} data any data supplied with the call to $.vakata.dnd.start
24551 * @param {DOM} element the DOM element being dragged
24552 * @param {jQuery} helper the helper shown next to the mouse
24553 * @param {Object} event the event that caused the stop
24554 */
24555 $.vakata.dnd._trigger("stop", e);
24556 }
24557 else {
24558 if(e.type === "touchend" && e.target === vakata_dnd.target) {
24559 var to = setTimeout(function () { $(e.target).click(); }, 100);
24560 $(e.target).one('click', function() { if(to) { clearTimeout(to); } });
24561 }
24562 }
24563 $.vakata.dnd._clean();
24564 return false;
24565 }
24566 };
24567 }($));
24568
24569 // include the dnd plugin by default
24570 // $.jstree.defaults.plugins.push("dnd");
24571
24572
24573 /**
24574 * ### Search plugin
24575 *
24576 * Adds search functionality to jsTree.
24577 */
24578
24579 /**
24580 * stores all defaults for the search plugin
24581 * @name $.jstree.defaults.search
24582 * @plugin search
24583 */
24584 $.jstree.defaults.search = {
24585 /**
24586 * a jQuery-like AJAX config, which jstree uses if a server should be queried for results.
24587 *
24588 * A `str` (which is the search string) parameter will be added with the request. The expected result is a JSON array with nodes that need to be opened so that matching nodes will be revealed.
24589 * Leave this setting as `false` to not query the server. You can also set this to a function, which will be invoked in the instance's scope and receive 2 parameters - the search string and the callback to call with the array of nodes to load.
24590 * @name $.jstree.defaults.search.ajax
24591 * @plugin search
24592 */
24593 ajax : false,
24594 /**
24595 * Indicates if the search should be fuzzy or not (should `chnd3` match `child node 3`). Default is `false`.
24596 * @name $.jstree.defaults.search.fuzzy
24597 * @plugin search
24598 */
24599 fuzzy : false,
24600 /**
24601 * Indicates if the search should be case sensitive. Default is `false`.
24602 * @name $.jstree.defaults.search.case_sensitive
24603 * @plugin search
24604 */
24605 case_sensitive : false,
24606 /**
24607 * Indicates if the tree should be filtered (by default) to show only matching nodes (keep in mind this can be a heavy on large trees in old browsers).
24608 * This setting can be changed at runtime when calling the search method. Default is `false`.
24609 * @name $.jstree.defaults.search.show_only_matches
24610 * @plugin search
24611 */
24612 show_only_matches : false,
24613 /**
24614 * Indicates if all nodes opened to reveal the search result, should be closed when the search is cleared or a new search is performed. Default is `true`.
24615 * @name $.jstree.defaults.search.close_opened_onclear
24616 * @plugin search
24617 */
24618 close_opened_onclear : true,
24619 /**
24620 * Indicates if only leaf nodes should be included in search results. Default is `false`.
24621 * @name $.jstree.defaults.search.search_leaves_only
24622 * @plugin search
24623 */
24624 search_leaves_only : false,
24625 /**
24626 * If set to a function it wil be called in the instance's scope with two arguments - search string and node (where node will be every node in the structure, so use with caution).
24627 * If the function returns a truthy value the node will be considered a match (it might not be displayed if search_only_leaves is set to true and the node is not a leaf). Default is `false`.
24628 * @name $.jstree.defaults.search.search_callback
24629 * @plugin search
24630 */
24631 search_callback : false
24632 };
24633
24634 $.jstree.plugins.search = function (options, parent) {
24635 this.bind = function () {
24636 parent.bind.call(this);
24637
24638 this._data.search.str = "";
24639 this._data.search.dom = $();
24640 this._data.search.res = [];
24641 this._data.search.opn = [];
24642 this._data.search.som = false;
24643
24644 this.element
24645 .on('before_open.jstree', $.proxy(function (e, data) {
24646 var i, j, f, r = this._data.search.res, s = [], o = $();
24647 if(r && r.length) {
24648 this._data.search.dom = $(this.element[0].querySelectorAll('#' + $.map(r, function (v) { return "0123456789".indexOf(v[0]) !== -1 ? '\\3' + v[0] + ' ' + v.substr(1).replace($.jstree.idregex,'\\$&') : v.replace($.jstree.idregex,'\\$&'); }).join(', #')));
24649 this._data.search.dom.children(".jstree-anchor").addClass('jstree-search');
24650 if(this._data.search.som && this._data.search.res.length) {
24651 for(i = 0, j = r.length; i < j; i++) {
24652 s = s.concat(this.get_node(r[i]).parents);
24653 }
24654 s = $.vakata.array_remove_item($.vakata.array_unique(s),'#');
24655 o = s.length ? $(this.element[0].querySelectorAll('#' + $.map(s, function (v) { return "0123456789".indexOf(v[0]) !== -1 ? '\\3' + v[0] + ' ' + v.substr(1).replace($.jstree.idregex,'\\$&') : v.replace($.jstree.idregex,'\\$&'); }).join(', #'))) : $();
24656
24657 this.element.find(".jstree-node").hide().filter('.jstree-last').filter(function() { return this.nextSibling; }).removeClass('jstree-last');
24658 o = o.add(this._data.search.dom);
24659 o.parentsUntil(".jstree").addBack().show()
24660 .filter(".jstree-children").each(function () { $(this).children(".jstree-node:visible").eq(-1).addClass("jstree-last"); });
24661 }
24662 }
24663 }, this))
24664 .on("search.jstree", $.proxy(function (e, data) {
24665 if(this._data.search.som) {
24666 if(data.nodes.length) {
24667 this.element.find(".jstree-node").hide().filter('.jstree-last').filter(function() { return this.nextSibling; }).removeClass('jstree-last');
24668 data.nodes.parentsUntil(".jstree").addBack().show()
24669 .filter(".jstree-children").each(function () { $(this).children(".jstree-node:visible").eq(-1).addClass("jstree-last"); });
24670 }
24671 }
24672 }, this))
24673 .on("clear_search.jstree", $.proxy(function (e, data) {
24674 if(this._data.search.som && data.nodes.length) {
24675 this.element.find(".jstree-node").css("display","").filter('.jstree-last').filter(function() { return this.nextSibling; }).removeClass('jstree-last');
24676 }
24677 }, this));
24678 };
24679 /**
24680 * used to search the tree nodes for a given string
24681 * @name search(str [, skip_async])
24682 * @param {String} str the search string
24683 * @param {Boolean} skip_async if set to true server will not be queried even if configured
24684 * @param {Boolean} show_only_matches if set to true only matching nodes will be shown (keep in mind this can be very slow on large trees or old browsers)
24685 * @plugin search
24686 * @trigger search.jstree
24687 */
24688 this.search = function (str, skip_async, show_only_matches) {
24689 if(str === false || $.trim(str.toString()) === "") {
24690 return this.clear_search();
24691 }
24692 str = str.toString();
24693 var s = this.settings.search,
24694 a = s.ajax ? s.ajax : false,
24695 f = null,
24696 r = [],
24697 p = [], i, j;
24698 if(this._data.search.res.length) {
24699 this.clear_search();
24700 }
24701 if(show_only_matches === undefined) {
24702 show_only_matches = s.show_only_matches;
24703 }
24704 if(!skip_async && a !== false) {
24705 if($.isFunction(a)) {
24706 return a.call(this, str, $.proxy(function (d) {
24707 if(d && d.d) { d = d.d; }
24708 this._load_nodes(!$.isArray(d) ? [] : $.vakata.array_unique(d), function () {
24709 this.search(str, true, show_only_matches);
24710 }, true);
24711 }, this));
24712 }
24713 else {
24714 a = $.extend({}, a);
24715 if(!a.data) { a.data = {}; }
24716 a.data.str = str;
24717 return $.ajax(a)
24718 .fail($.proxy(function () {
24719 this._data.core.last_error = { 'error' : 'ajax', 'plugin' : 'search', 'id' : 'search_01', 'reason' : 'Could not load search parents', 'data' : JSON.stringify(a) };
24720 this.settings.core.error.call(this, this._data.core.last_error);
24721 }, this))
24722 .done($.proxy(function (d) {
24723 if(d && d.d) { d = d.d; }
24724 this._load_nodes(!$.isArray(d) ? [] : $.vakata.array_unique(d), function () {
24725 this.search(str, true, show_only_matches);
24726 }, true);
24727 }, this));
24728 }
24729 }
24730 this._data.search.str = str;
24731 this._data.search.dom = $();
24732 this._data.search.res = [];
24733 this._data.search.opn = [];
24734 this._data.search.som = show_only_matches;
24735
24736 f = new $.vakata.search(str, true, { caseSensitive : s.case_sensitive, fuzzy : s.fuzzy });
24737
24738 $.each(this._model.data, function (i, v) {
24739 if(v.text && ( (s.search_callback && s.search_callback.call(this, str, v)) || (!s.search_callback && f.search(v.text).isMatch) ) && (!s.search_leaves_only || (v.state.loaded && v.children.length === 0)) ) {
24740 r.push(i);
24741 p = p.concat(v.parents);
24742 }
24743 });
24744 if(r.length) {
24745 p = $.vakata.array_unique(p);
24746 this._search_open(p);
24747 this._data.search.dom = $(this.element[0].querySelectorAll('#' + $.map(r, function (v) { return "0123456789".indexOf(v[0]) !== -1 ? '\\3' + v[0] + ' ' + v.substr(1).replace($.jstree.idregex,'\\$&') : v.replace($.jstree.idregex,'\\$&'); }).join(', #')));
24748 this._data.search.res = r;
24749 this._data.search.dom.children(".jstree-anchor").addClass('jstree-search');
24750 }
24751 /**
24752 * triggered after search is complete
24753 * @event
24754 * @name search.jstree
24755 * @param {jQuery} nodes a jQuery collection of matching nodes
24756 * @param {String} str the search string
24757 * @param {Array} res a collection of objects represeing the matching nodes
24758 * @plugin search
24759 */
24760 this.trigger('search', { nodes : this._data.search.dom, str : str, res : this._data.search.res, show_only_matches : show_only_matches });
24761 };
24762 /**
24763 * used to clear the last search (removes classes and shows all nodes if filtering is on)
24764 * @name clear_search()
24765 * @plugin search
24766 * @trigger clear_search.jstree
24767 */
24768 this.clear_search = function () {
24769 this._data.search.dom.children(".jstree-anchor").removeClass("jstree-search");
24770 if(this.settings.search.close_opened_onclear) {
24771 this.close_node(this._data.search.opn, 0);
24772 }
24773 /**
24774 * triggered after search is complete
24775 * @event
24776 * @name clear_search.jstree
24777 * @param {jQuery} nodes a jQuery collection of matching nodes (the result from the last search)
24778 * @param {String} str the search string (the last search string)
24779 * @param {Array} res a collection of objects represeing the matching nodes (the result from the last search)
24780 * @plugin search
24781 */
24782 this.trigger('clear_search', { 'nodes' : this._data.search.dom, str : this._data.search.str, res : this._data.search.res });
24783 this._data.search.str = "";
24784 this._data.search.res = [];
24785 this._data.search.opn = [];
24786 this._data.search.dom = $();
24787 };
24788 /**
24789 * opens nodes that need to be opened to reveal the search results. Used only internally.
24790 * @private
24791 * @name _search_open(d)
24792 * @param {Array} d an array of node IDs
24793 * @plugin search
24794 */
24795 this._search_open = function (d) {
24796 var t = this;
24797 $.each(d.concat([]), function (i, v) {
24798 if(v === "#") { return true; }
24799 try { v = $('#' + v.replace($.jstree.idregex,'\\$&'), t.element); } catch(ignore) { }
24800 if(v && v.length) {
24801 if(t.is_closed(v)) {
24802 t._data.search.opn.push(v[0].id);
24803 t.open_node(v, function () { t._search_open(d); }, 0);
24804 }
24805 }
24806 });
24807 };
24808 };
24809
24810 // helpers
24811 (function ($) {
24812 // from http://kiro.me/projects/fuse.html
24813 $.vakata.search = function(pattern, txt, options) {
24814 options = options || {};
24815 if(options.fuzzy !== false) {
24816 options.fuzzy = true;
24817 }
24818 pattern = options.caseSensitive ? pattern : pattern.toLowerCase();
24819 var MATCH_LOCATION = options.location || 0,
24820 MATCH_DISTANCE = options.distance || 100,
24821 MATCH_THRESHOLD = options.threshold || 0.6,
24822 patternLen = pattern.length,
24823 matchmask, pattern_alphabet, match_bitapScore, search;
24824 if(patternLen > 32) {
24825 options.fuzzy = false;
24826 }
24827 if(options.fuzzy) {
24828 matchmask = 1 << (patternLen - 1);
24829 pattern_alphabet = (function () {
24830 var mask = {},
24831 i = 0;
24832 for (i = 0; i < patternLen; i++) {
24833 mask[pattern.charAt(i)] = 0;
24834 }
24835 for (i = 0; i < patternLen; i++) {
24836 mask[pattern.charAt(i)] |= 1 << (patternLen - i - 1);
24837 }
24838 return mask;
24839 }());
24840 match_bitapScore = function (e, x) {
24841 var accuracy = e / patternLen,
24842 proximity = Math.abs(MATCH_LOCATION - x);
24843 if(!MATCH_DISTANCE) {
24844 return proximity ? 1.0 : accuracy;
24845 }
24846 return accuracy + (proximity / MATCH_DISTANCE);
24847 };
24848 }
24849 search = function (text) {
24850 text = options.caseSensitive ? text : text.toLowerCase();
24851 if(pattern === text || text.indexOf(pattern) !== -1) {
24852 return {
24853 isMatch: true,
24854 score: 0
24855 };
24856 }
24857 if(!options.fuzzy) {
24858 return {
24859 isMatch: false,
24860 score: 1
24861 };
24862 }
24863 var i, j,
24864 textLen = text.length,
24865 scoreThreshold = MATCH_THRESHOLD,
24866 bestLoc = text.indexOf(pattern, MATCH_LOCATION),
24867 binMin, binMid,
24868 binMax = patternLen + textLen,
24869 lastRd, start, finish, rd, charMatch,
24870 score = 1,
24871 locations = [];
24872 if (bestLoc !== -1) {
24873 scoreThreshold = Math.min(match_bitapScore(0, bestLoc), scoreThreshold);
24874 bestLoc = text.lastIndexOf(pattern, MATCH_LOCATION + patternLen);
24875 if (bestLoc !== -1) {
24876 scoreThreshold = Math.min(match_bitapScore(0, bestLoc), scoreThreshold);
24877 }
24878 }
24879 bestLoc = -1;
24880 for (i = 0; i < patternLen; i++) {
24881 binMin = 0;
24882 binMid = binMax;
24883 while (binMin < binMid) {
24884 if (match_bitapScore(i, MATCH_LOCATION + binMid) <= scoreThreshold) {
24885 binMin = binMid;
24886 } else {
24887 binMax = binMid;
24888 }
24889 binMid = Math.floor((binMax - binMin) / 2 + binMin);
24890 }
24891 binMax = binMid;
24892 start = Math.max(1, MATCH_LOCATION - binMid + 1);
24893 finish = Math.min(MATCH_LOCATION + binMid, textLen) + patternLen;
24894 rd = new Array(finish + 2);
24895 rd[finish + 1] = (1 << i) - 1;
24896 for (j = finish; j >= start; j--) {
24897 charMatch = pattern_alphabet[text.charAt(j - 1)];
24898 if (i === 0) {
24899 rd[j] = ((rd[j + 1] << 1) | 1) & charMatch;
24900 } else {
24901 rd[j] = ((rd[j + 1] << 1) | 1) & charMatch | (((lastRd[j + 1] | lastRd[j]) << 1) | 1) | lastRd[j + 1];
24902 }
24903 if (rd[j] & matchmask) {
24904 score = match_bitapScore(i, j - 1);
24905 if (score <= scoreThreshold) {
24906 scoreThreshold = score;
24907 bestLoc = j - 1;
24908 locations.push(bestLoc);
24909 if (bestLoc > MATCH_LOCATION) {
24910 start = Math.max(1, 2 * MATCH_LOCATION - bestLoc);
24911 } else {
24912 break;
24913 }
24914 }
24915 }
24916 }
24917 if (match_bitapScore(i + 1, MATCH_LOCATION) > scoreThreshold) {
24918 break;
24919 }
24920 lastRd = rd;
24921 }
24922 return {
24923 isMatch: bestLoc >= 0,
24924 score: score
24925 };
24926 };
24927 return txt === true ? { 'search' : search } : search(txt);
24928 };
24929 }($));
24930
24931 // include the search plugin by default
24932 // $.jstree.defaults.plugins.push("search");
24933
24934 /**
24935 * ### Sort plugin
24936 *
24937 * Automatically sorts all siblings in the tree according to a sorting function.
24938 */
24939
24940 /**
24941 * the settings function used to sort the nodes.
24942 * It is executed in the tree's context, accepts two nodes as arguments and should return `1` or `-1`.
24943 * @name $.jstree.defaults.sort
24944 * @plugin sort
24945 */
24946 $.jstree.defaults.sort = function (a, b) {
24947 //return this.get_type(a) === this.get_type(b) ? (this.get_text(a) > this.get_text(b) ? 1 : -1) : this.get_type(a) >= this.get_type(b);
24948 return this.get_text(a) > this.get_text(b) ? 1 : -1;
24949 };
24950 $.jstree.plugins.sort = function (options, parent) {
24951 this.bind = function () {
24952 parent.bind.call(this);
24953 this.element
24954 .on("model.jstree", $.proxy(function (e, data) {
24955 this.sort(data.parent, true);
24956 }, this))
24957 .on("rename_node.jstree create_node.jstree", $.proxy(function (e, data) {
24958 this.sort(data.parent || data.node.parent, false);
24959 this.redraw_node(data.parent || data.node.parent, true);
24960 }, this))
24961 .on("move_node.jstree copy_node.jstree", $.proxy(function (e, data) {
24962 this.sort(data.parent, false);
24963 this.redraw_node(data.parent, true);
24964 }, this));
24965 };
24966 /**
24967 * used to sort a node's children
24968 * @private
24969 * @name sort(obj [, deep])
24970 * @param {mixed} obj the node
24971 * @param {Boolean} deep if set to `true` nodes are sorted recursively.
24972 * @plugin sort
24973 * @trigger search.jstree
24974 */
24975 this.sort = function (obj, deep) {
24976 var i, j;
24977 obj = this.get_node(obj);
24978 if(obj && obj.children && obj.children.length) {
24979 obj.children.sort($.proxy(this.settings.sort, this));
24980 if(deep) {
24981 for(i = 0, j = obj.children_d.length; i < j; i++) {
24982 this.sort(obj.children_d[i], false);
24983 }
24984 }
24985 }
24986 };
24987 };
24988
24989 // include the sort plugin by default
24990 // $.jstree.defaults.plugins.push("sort");
24991
24992 /**
24993 * ### State plugin
24994 *
24995 * Saves the state of the tree (selected nodes, opened nodes) on the user's computer using available options (localStorage, cookies, etc)
24996 */
24997
24998 var to = false;
24999 /**
25000 * stores all defaults for the state plugin
25001 * @name $.jstree.defaults.state
25002 * @plugin state
25003 */
25004 $.jstree.defaults.state = {
25005 /**
25006 * A string for the key to use when saving the current tree (change if using multiple trees in your project). Defaults to `jstree`.
25007 * @name $.jstree.defaults.state.key
25008 * @plugin state
25009 */
25010 key : 'jstree',
25011 /**
25012 * A space separated list of events that trigger a state save. Defaults to `changed.jstree open_node.jstree close_node.jstree`.
25013 * @name $.jstree.defaults.state.events
25014 * @plugin state
25015 */
25016 events : 'changed.jstree open_node.jstree close_node.jstree check_node.jstree uncheck_node.jstree',
25017 /**
25018 * Time in milliseconds after which the state will expire. Defaults to 'false' meaning - no expire.
25019 * @name $.jstree.defaults.state.ttl
25020 * @plugin state
25021 */
25022 ttl : false,
25023 /**
25024 * A function that will be executed prior to restoring state with one argument - the state object. Can be used to clear unwanted parts of the state.
25025 * @name $.jstree.defaults.state.filter
25026 * @plugin state
25027 */
25028 filter : false
25029 };
25030 $.jstree.plugins.state = function (options, parent) {
25031 this.bind = function () {
25032 parent.bind.call(this);
25033 var bind = $.proxy(function () {
25034 this.element.on(this.settings.state.events, $.proxy(function () {
25035 if(to) { clearTimeout(to); }
25036 to = setTimeout($.proxy(function () { this.save_state(); }, this), 100);
25037 }, this));
25038 /**
25039 * triggered when the state plugin is finished restoring the state (and immediately after ready if there is no state to restore).
25040 * @event
25041 * @name state_ready.jstree
25042 * @plugin state
25043 */
25044 this.trigger('state_ready');
25045 }, this);
25046 this.element
25047 .on("ready.jstree", $.proxy(function (e, data) {
25048 this.element.one("restore_state.jstree", bind);
25049 if(!this.restore_state()) { bind(); }
25050 }, this));
25051 };
25052 /**
25053 * save the state
25054 * @name save_state()
25055 * @plugin state
25056 */
25057 this.save_state = function () {
25058 var st = { 'state' : this.get_state(), 'ttl' : this.settings.state.ttl, 'sec' : +(new Date()) };
25059 $.vakata.storage.set(this.settings.state.key, JSON.stringify(st));
25060 };
25061 /**
25062 * restore the state from the user's computer
25063 * @name restore_state()
25064 * @plugin state
25065 */
25066 this.restore_state = function () {
25067 var k = $.vakata.storage.get(this.settings.state.key);
25068 if(!!k) { try { k = JSON.parse(k); } catch(ex) { return false; } }
25069 if(!!k && k.ttl && k.sec && +(new Date()) - k.sec > k.ttl) { return false; }
25070 if(!!k && k.state) { k = k.state; }
25071 if(!!k && $.isFunction(this.settings.state.filter)) { k = this.settings.state.filter.call(this, k); }
25072 if(!!k) {
25073 this.element.one("set_state.jstree", function (e, data) { data.instance.trigger('restore_state', { 'state' : $.extend(true, {}, k) }); });
25074 this.set_state(k);
25075 return true;
25076 }
25077 return false;
25078 };
25079 /**
25080 * clear the state on the user's computer
25081 * @name clear_state()
25082 * @plugin state
25083 */
25084 this.clear_state = function () {
25085 return $.vakata.storage.del(this.settings.state.key);
25086 };
25087 };
25088
25089 (function ($, undefined) {
25090 $.vakata.storage = {
25091 // simply specifying the functions in FF throws an error
25092 set : function (key, val) { return window.localStorage.setItem(key, val); },
25093 get : function (key) { return window.localStorage.getItem(key); },
25094 del : function (key) { return window.localStorage.removeItem(key); }
25095 };
25096 }($));
25097
25098 // include the state plugin by default
25099 // $.jstree.defaults.plugins.push("state");
25100
25101 /**
25102 * ### Types plugin
25103 *
25104 * Makes it possible to add predefined types for groups of nodes, which make it possible to easily control nesting rules and icon for each group.
25105 */
25106
25107 /**
25108 * An object storing all types as key value pairs, where the key is the type name and the value is an object that could contain following keys (all optional).
25109 *
25110 * * `max_children` the maximum number of immediate children this node type can have. Do not specify or set to `-1` for unlimited.
25111 * * `max_depth` the maximum number of nesting this node type can have. A value of `1` would mean that the node can have children, but no grandchildren. Do not specify or set to `-1` for unlimited.
25112 * * `valid_children` an array of node type strings, that nodes of this type can have as children. Do not specify or set to `-1` for no limits.
25113 * * `icon` a string - can be a path to an icon or a className, if using an image that is in the current directory use a `./` prefix, otherwise it will be detected as a class. Omit to use the default icon from your theme.
25114 *
25115 * There are two predefined types:
25116 *
25117 * * `#` represents the root of the tree, for example `max_children` would control the maximum number of root nodes.
25118 * * `default` represents the default node - any settings here will be applied to all nodes that do not have a type specified.
25119 *
25120 * @name $.jstree.defaults.types
25121 * @plugin types
25122 */
25123 $.jstree.defaults.types = {
25124 '#' : {},
25125 'default' : {}
25126 };
25127
25128 $.jstree.plugins.types = function (options, parent) {
25129 this.init = function (el, options) {
25130 var i, j;
25131 if(options && options.types && options.types['default']) {
25132 for(i in options.types) {
25133 if(i !== "default" && i !== "#" && options.types.hasOwnProperty(i)) {
25134 for(j in options.types['default']) {
25135 if(options.types['default'].hasOwnProperty(j) && options.types[i][j] === undefined) {
25136 options.types[i][j] = options.types['default'][j];
25137 }
25138 }
25139 }
25140 }
25141 }
25142 parent.init.call(this, el, options);
25143 this._model.data['#'].type = '#';
25144 };
25145 this.refresh = function (skip_loading, forget_state) {
25146 parent.refresh.call(this, skip_loading, forget_state);
25147 this._model.data['#'].type = '#';
25148 };
25149 this.bind = function () {
25150 this.element
25151 .on('model.jstree', $.proxy(function (e, data) {
25152 var m = this._model.data,
25153 dpc = data.nodes,
25154 t = this.settings.types,
25155 i, j, c = 'default';
25156 for(i = 0, j = dpc.length; i < j; i++) {
25157 c = 'default';
25158 if(m[dpc[i]].original && m[dpc[i]].original.type && t[m[dpc[i]].original.type]) {
25159 c = m[dpc[i]].original.type;
25160 }
25161 if(m[dpc[i]].data && m[dpc[i]].data.jstree && m[dpc[i]].data.jstree.type && t[m[dpc[i]].data.jstree.type]) {
25162 c = m[dpc[i]].data.jstree.type;
25163 }
25164 m[dpc[i]].type = c;
25165 if(m[dpc[i]].icon === true && t[c].icon !== undefined) {
25166 m[dpc[i]].icon = t[c].icon;
25167 }
25168 }
25169 m['#'].type = '#';
25170 }, this));
25171 parent.bind.call(this);
25172 };
25173 this.get_json = function (obj, options, flat) {
25174 var i, j,
25175 m = this._model.data,
25176 opt = options ? $.extend(true, {}, options, {no_id:false}) : {},
25177 tmp = parent.get_json.call(this, obj, opt, flat);
25178 if(tmp === false) { return false; }
25179 if($.isArray(tmp)) {
25180 for(i = 0, j = tmp.length; i < j; i++) {
25181 tmp[i].type = tmp[i].id && m[tmp[i].id] && m[tmp[i].id].type ? m[tmp[i].id].type : "default";
25182 if(options && options.no_id) {
25183 delete tmp[i].id;
25184 if(tmp[i].li_attr && tmp[i].li_attr.id) {
25185 delete tmp[i].li_attr.id;
25186 }
25187 if(tmp[i].a_attr && tmp[i].a_attr.id) {
25188 delete tmp[i].a_attr.id;
25189 }
25190 }
25191 }
25192 }
25193 else {
25194 tmp.type = tmp.id && m[tmp.id] && m[tmp.id].type ? m[tmp.id].type : "default";
25195 if(options && options.no_id) {
25196 tmp = this._delete_ids(tmp);
25197 }
25198 }
25199 return tmp;
25200 };
25201 this._delete_ids = function (tmp) {
25202 if($.isArray(tmp)) {
25203 for(var i = 0, j = tmp.length; i < j; i++) {
25204 tmp[i] = this._delete_ids(tmp[i]);
25205 }
25206 return tmp;
25207 }
25208 delete tmp.id;
25209 if(tmp.li_attr && tmp.li_attr.id) {
25210 delete tmp.li_attr.id;
25211 }
25212 if(tmp.a_attr && tmp.a_attr.id) {
25213 delete tmp.a_attr.id;
25214 }
25215 if(tmp.children && $.isArray(tmp.children)) {
25216 tmp.children = this._delete_ids(tmp.children);
25217 }
25218 return tmp;
25219 };
25220 this.check = function (chk, obj, par, pos, more) {
25221 if(parent.check.call(this, chk, obj, par, pos, more) === false) { return false; }
25222 obj = obj && obj.id ? obj : this.get_node(obj);
25223 par = par && par.id ? par : this.get_node(par);
25224 var m = obj && obj.id ? $.jstree.reference(obj.id) : null, tmp, d, i, j;
25225 m = m && m._model && m._model.data ? m._model.data : null;
25226 switch(chk) {
25227 case "create_node":
25228 case "move_node":
25229 case "copy_node":
25230 if(chk !== 'move_node' || $.inArray(obj.id, par.children) === -1) {
25231 tmp = this.get_rules(par);
25232 if(tmp.max_children !== undefined && tmp.max_children !== -1 && tmp.max_children === par.children.length) {
25233 this._data.core.last_error = { 'error' : 'check', 'plugin' : 'types', 'id' : 'types_01', 'reason' : 'max_children prevents function: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
25234 return false;
25235 }
25236 if(tmp.valid_children !== undefined && tmp.valid_children !== -1 && $.inArray((obj.type || 'default'), tmp.valid_children) === -1) {
25237 this._data.core.last_error = { 'error' : 'check', 'plugin' : 'types', 'id' : 'types_02', 'reason' : 'valid_children prevents function: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
25238 return false;
25239 }
25240 if(m && obj.children_d && obj.parents) {
25241 d = 0;
25242 for(i = 0, j = obj.children_d.length; i < j; i++) {
25243 d = Math.max(d, m[obj.children_d[i]].parents.length);
25244 }
25245 d = d - obj.parents.length + 1;
25246 }
25247 if(d <= 0 || d === undefined) { d = 1; }
25248 do {
25249 if(tmp.max_depth !== undefined && tmp.max_depth !== -1 && tmp.max_depth < d) {
25250 this._data.core.last_error = { 'error' : 'check', 'plugin' : 'types', 'id' : 'types_03', 'reason' : 'max_depth prevents function: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
25251 return false;
25252 }
25253 par = this.get_node(par.parent);
25254 tmp = this.get_rules(par);
25255 d++;
25256 } while(par);
25257 }
25258 break;
25259 }
25260 return true;
25261 };
25262 /**
25263 * used to retrieve the type settings object for a node
25264 * @name get_rules(obj)
25265 * @param {mixed} obj the node to find the rules for
25266 * @return {Object}
25267 * @plugin types
25268 */
25269 this.get_rules = function (obj) {
25270 obj = this.get_node(obj);
25271 if(!obj) { return false; }
25272 var tmp = this.get_type(obj, true);
25273 if(tmp.max_depth === undefined) { tmp.max_depth = -1; }
25274 if(tmp.max_children === undefined) { tmp.max_children = -1; }
25275 if(tmp.valid_children === undefined) { tmp.valid_children = -1; }
25276 return tmp;
25277 };
25278 /**
25279 * used to retrieve the type string or settings object for a node
25280 * @name get_type(obj [, rules])
25281 * @param {mixed} obj the node to find the rules for
25282 * @param {Boolean} rules if set to `true` instead of a string the settings object will be returned
25283 * @return {String|Object}
25284 * @plugin types
25285 */
25286 this.get_type = function (obj, rules) {
25287 obj = this.get_node(obj);
25288 return (!obj) ? false : ( rules ? $.extend({ 'type' : obj.type }, this.settings.types[obj.type]) : obj.type);
25289 };
25290 /**
25291 * used to change a node's type
25292 * @name set_type(obj, type)
25293 * @param {mixed} obj the node to change
25294 * @param {String} type the new type
25295 * @plugin types
25296 */
25297 this.set_type = function (obj, type) {
25298 var t, t1, t2, old_type, old_icon;
25299 if($.isArray(obj)) {
25300 obj = obj.slice();
25301 for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
25302 this.set_type(obj[t1], type);
25303 }
25304 return true;
25305 }
25306 t = this.settings.types;
25307 obj = this.get_node(obj);
25308 if(!t[type] || !obj) { return false; }
25309 old_type = obj.type;
25310 old_icon = this.get_icon(obj);
25311 obj.type = type;
25312 if(old_icon === true || (t[old_type] && t[old_type].icon !== undefined && old_icon === t[old_type].icon)) {
25313 this.set_icon(obj, t[type].icon !== undefined ? t[type].icon : true);
25314 }
25315 return true;
25316 };
25317 };
25318 // include the types plugin by default
25319 // $.jstree.defaults.plugins.push("types");
25320
25321 /**
25322 * ### Unique plugin
25323 *
25324 * Enforces that no nodes with the same name can coexist as siblings.
25325 */
25326
25327 /**
25328 * stores all defaults for the unique plugin
25329 * @name $.jstree.defaults.unique
25330 * @plugin unique
25331 */
25332 $.jstree.defaults.unique = {
25333 /**
25334 * Indicates if the comparison should be case sensitive. Default is `false`.
25335 * @name $.jstree.defaults.unique.case_sensitive
25336 * @plugin unique
25337 */
25338 case_sensitive : false,
25339 /**
25340 * A callback executed in the instance's scope when a new node is created and the name is already taken, the two arguments are the conflicting name and the counter. The default will produce results like `New node (2)`.
25341 * @name $.jstree.defaults.unique.duplicate
25342 * @plugin unique
25343 */
25344 duplicate : function (name, counter) {
25345 return name + ' (' + counter + ')';
25346 }
25347 };
25348
25349 $.jstree.plugins.unique = function (options, parent) {
25350 this.check = function (chk, obj, par, pos, more) {
25351 if(parent.check.call(this, chk, obj, par, pos, more) === false) { return false; }
25352 obj = obj && obj.id ? obj : this.get_node(obj);
25353 par = par && par.id ? par : this.get_node(par);
25354 if(!par || !par.children) { return true; }
25355 var n = chk === "rename_node" ? pos : obj.text,
25356 c = [],
25357 s = this.settings.unique.case_sensitive,
25358 m = this._model.data, i, j;
25359 for(i = 0, j = par.children.length; i < j; i++) {
25360 c.push(s ? m[par.children[i]].text : m[par.children[i]].text.toLowerCase());
25361 }
25362 if(!s) { n = n.toLowerCase(); }
25363 switch(chk) {
25364 case "delete_node":
25365 return true;
25366 case "rename_node":
25367 i = ($.inArray(n, c) === -1 || (obj.text && obj.text[ s ? 'toString' : 'toLowerCase']() === n));
25368 if(!i) {
25369 this._data.core.last_error = { 'error' : 'check', 'plugin' : 'unique', 'id' : 'unique_01', 'reason' : 'Child with name ' + n + ' already exists. Preventing: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
25370 }
25371 return i;
25372 case "create_node":
25373 i = ($.inArray(n, c) === -1);
25374 if(!i) {
25375 this._data.core.last_error = { 'error' : 'check', 'plugin' : 'unique', 'id' : 'unique_04', 'reason' : 'Child with name ' + n + ' already exists. Preventing: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
25376 }
25377 return i;
25378 case "copy_node":
25379 i = ($.inArray(n, c) === -1);
25380 if(!i) {
25381 this._data.core.last_error = { 'error' : 'check', 'plugin' : 'unique', 'id' : 'unique_02', 'reason' : 'Child with name ' + n + ' already exists. Preventing: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
25382 }
25383 return i;
25384 case "move_node":
25385 i = (obj.parent === par.id || $.inArray(n, c) === -1);
25386 if(!i) {
25387 this._data.core.last_error = { 'error' : 'check', 'plugin' : 'unique', 'id' : 'unique_03', 'reason' : 'Child with name ' + n + ' already exists. Preventing: ' + chk, 'data' : JSON.stringify({ 'chk' : chk, 'pos' : pos, 'obj' : obj && obj.id ? obj.id : false, 'par' : par && par.id ? par.id : false }) };
25388 }
25389 return i;
25390 }
25391 return true;
25392 };
25393 this.create_node = function (par, node, pos, callback, is_loaded) {
25394 if(!node || node.text === undefined) {
25395 if(par === null) {
25396 par = "#";
25397 }
25398 par = this.get_node(par);
25399 if(!par) {
25400 return parent.create_node.call(this, par, node, pos, callback, is_loaded);
25401 }
25402 pos = pos === undefined ? "last" : pos;
25403 if(!pos.toString().match(/^(before|after)$/) && !is_loaded && !this.is_loaded(par)) {
25404 return parent.create_node.call(this, par, node, pos, callback, is_loaded);
25405 }
25406 if(!node) { node = {}; }
25407 var tmp, n, dpc, i, j, m = this._model.data, s = this.settings.unique.case_sensitive, cb = this.settings.unique.duplicate;
25408 n = tmp = this.get_string('New node');
25409 dpc = [];
25410 for(i = 0, j = par.children.length; i < j; i++) {
25411 dpc.push(s ? m[par.children[i]].text : m[par.children[i]].text.toLowerCase());
25412 }
25413 i = 1;
25414 while($.inArray(s ? n : n.toLowerCase(), dpc) !== -1) {
25415 n = cb.call(this, tmp, (++i)).toString();
25416 }
25417 node.text = n;
25418 }
25419 return parent.create_node.call(this, par, node, pos, callback, is_loaded);
25420 };
25421 };
25422
25423 // include the unique plugin by default
25424 // $.jstree.defaults.plugins.push("unique");
25425
25426
25427 /**
25428 * ### Wholerow plugin
25429 *
25430 * Makes each node appear block level. Making selection easier. May cause slow down for large trees in old browsers.
25431 */
25432
25433 var div = document.createElement('DIV');
25434 div.setAttribute('unselectable','on');
25435 div.setAttribute('role','presentation');
25436 div.className = 'jstree-wholerow';
25437 div.innerHTML = '&#160;';
25438 $.jstree.plugins.wholerow = function (options, parent) {
25439 this.bind = function () {
25440 parent.bind.call(this);
25441
25442 this.element
25443 .on('ready.jstree set_state.jstree', $.proxy(function () {
25444 this.hide_dots();
25445 }, this))
25446 .on("init.jstree loading.jstree ready.jstree", $.proxy(function () {
25447 //div.style.height = this._data.core.li_height + 'px';
25448 this.get_container_ul().addClass('jstree-wholerow-ul');
25449 }, this))
25450 .on("deselect_all.jstree", $.proxy(function (e, data) {
25451 this.element.find('.jstree-wholerow-clicked').removeClass('jstree-wholerow-clicked');
25452 }, this))
25453 .on("changed.jstree", $.proxy(function (e, data) {
25454 this.element.find('.jstree-wholerow-clicked').removeClass('jstree-wholerow-clicked');
25455 var tmp = false, i, j;
25456 for(i = 0, j = data.selected.length; i < j; i++) {
25457 tmp = this.get_node(data.selected[i], true);
25458 if(tmp && tmp.length) {
25459 tmp.children('.jstree-wholerow').addClass('jstree-wholerow-clicked');
25460 }
25461 }
25462 }, this))
25463 .on("open_node.jstree", $.proxy(function (e, data) {
25464 this.get_node(data.node, true).find('.jstree-clicked').parent().children('.jstree-wholerow').addClass('jstree-wholerow-clicked');
25465 }, this))
25466 .on("hover_node.jstree dehover_node.jstree", $.proxy(function (e, data) {
25467 if(e.type === "hover_node" && this.is_disabled(data.node)) { return; }
25468 this.get_node(data.node, true).children('.jstree-wholerow')[e.type === "hover_node"?"addClass":"removeClass"]('jstree-wholerow-hovered');
25469 }, this))
25470 .on("contextmenu.jstree", ".jstree-wholerow", $.proxy(function (e) {
25471 e.preventDefault();
25472 var tmp = $.Event('contextmenu', { metaKey : e.metaKey, ctrlKey : e.ctrlKey, altKey : e.altKey, shiftKey : e.shiftKey, pageX : e.pageX, pageY : e.pageY });
25473 $(e.currentTarget).closest(".jstree-node").children(".jstree-anchor").first().trigger(tmp);
25474 }, this))
25475 .on("click.jstree", ".jstree-wholerow", function (e) {
25476 e.stopImmediatePropagation();
25477 var tmp = $.Event('click', { metaKey : e.metaKey, ctrlKey : e.ctrlKey, altKey : e.altKey, shiftKey : e.shiftKey });
25478 $(e.currentTarget).closest(".jstree-node").children(".jstree-anchor").first().trigger(tmp).focus();
25479 })
25480 .on("click.jstree", ".jstree-leaf > .jstree-ocl", $.proxy(function (e) {
25481 e.stopImmediatePropagation();
25482 var tmp = $.Event('click', { metaKey : e.metaKey, ctrlKey : e.ctrlKey, altKey : e.altKey, shiftKey : e.shiftKey });
25483 $(e.currentTarget).closest(".jstree-node").children(".jstree-anchor").first().trigger(tmp).focus();
25484 }, this))
25485 .on("mouseover.jstree", ".jstree-wholerow, .jstree-icon", $.proxy(function (e) {
25486 e.stopImmediatePropagation();
25487 if(!this.is_disabled(e.currentTarget)) {
25488 this.hover_node(e.currentTarget);
25489 }
25490 return false;
25491 }, this))
25492 .on("mouseleave.jstree", ".jstree-node", $.proxy(function (e) {
25493 this.dehover_node(e.currentTarget);
25494 }, this));
25495 };
25496 this.teardown = function () {
25497 if(this.settings.wholerow) {
25498 this.element.find(".jstree-wholerow").remove();
25499 }
25500 parent.teardown.call(this);
25501 };
25502 this.redraw_node = function(obj, deep, callback, force_render) {
25503 obj = parent.redraw_node.apply(this, arguments);
25504 if(obj) {
25505 var tmp = div.cloneNode(true);
25506 //tmp.style.height = this._data.core.li_height + 'px';
25507 if($.inArray(obj.id, this._data.core.selected) !== -1) { tmp.className += ' jstree-wholerow-clicked'; }
25508 if(this._data.core.focused && this._data.core.focused === obj.id) { tmp.className += ' jstree-wholerow-hovered'; }
25509 obj.insertBefore(tmp, obj.childNodes[0]);
25510 }
25511 return obj;
25512 };
25513 };
25514 // include the wholerow plugin by default
25515 // $.jstree.defaults.plugins.push("wholerow");
25516
25517
25518 (function ($) {
25519 if(document.registerElement && Object && Object.create) {
25520 var proto = Object.create(HTMLElement.prototype);
25521 proto.createdCallback = function () {
25522 var c = { core : {}, plugins : [] }, i;
25523 for(i in $.jstree.plugins) {
25524 if($.jstree.plugins.hasOwnProperty(i) && this.attributes[i]) {
25525 c.plugins.push(i);
25526 if(this.getAttribute(i) && JSON.parse(this.getAttribute(i))) {
25527 c[i] = JSON.parse(this.getAttribute(i));
25528 }
25529 }
25530 }
25531 for(i in $.jstree.defaults.core) {
25532 if($.jstree.defaults.core.hasOwnProperty(i) && this.attributes[i]) {
25533 c.core[i] = JSON.parse(this.getAttribute(i)) || this.getAttribute(i);
25534 }
25535 }
25536 jQuery(this).jstree(c);
25537 };
25538 // proto.attributeChangedCallback = function (name, previous, value) { };
25539 try {
25540 document.registerElement("vakata-jstree", { prototype: proto });
25541 } catch(ignore) { }
25542 }
25543 }(jQuery));
25544 }));
25545 /*!
25546
25547 JSZip - A Javascript class for generating and reading zip files
25548 <http://stuartk.com/jszip>
25549
25550 (c) 2009-2014 Stuart Knightley <stuart [at] stuartk.com>
25551 Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.
25552
25553 JSZip uses the library pako released under the MIT license :
25554 https://github.com/nodeca/pako/blob/master/LICENSE
25555 */
25556 !function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;"undefined"!=typeof window?b=window:"undefined"!=typeof global?b=global:"undefined"!=typeof self&&(b=self),b.JSZip=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);throw new Error("Cannot find module '"+g+"'")}var j=c[g]={exports:{}};b[g][0].call(j.exports,function(a){var c=b[g][1][a];return e(c?c:a)},j,j.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){"use strict";var d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";c.encode=function(a){for(var b,c,e,f,g,h,i,j="",k=0;k<a.length;)b=a.charCodeAt(k++),c=a.charCodeAt(k++),e=a.charCodeAt(k++),f=b>>2,g=(3&b)<<4|c>>4,h=(15&c)<<2|e>>6,i=63&e,isNaN(c)?h=i=64:isNaN(e)&&(i=64),j=j+d.charAt(f)+d.charAt(g)+d.charAt(h)+d.charAt(i);return j},c.decode=function(a){var b,c,e,f,g,h,i,j="",k=0;for(a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");k<a.length;)f=d.indexOf(a.charAt(k++)),g=d.indexOf(a.charAt(k++)),h=d.indexOf(a.charAt(k++)),i=d.indexOf(a.charAt(k++)),b=f<<2|g>>4,c=(15&g)<<4|h>>2,e=(3&h)<<6|i,j+=String.fromCharCode(b),64!=h&&(j+=String.fromCharCode(c)),64!=i&&(j+=String.fromCharCode(e));return j}},{}],2:[function(a,b){"use strict";function c(){this.compressedSize=0,this.uncompressedSize=0,this.crc32=0,this.compressionMethod=null,this.compressedContent=null}c.prototype={getContent:function(){return null},getCompressedContent:function(){return null}},b.exports=c},{}],3:[function(a,b,c){"use strict";c.STORE={magic:"\x00\x00",compress:function(a){return a},uncompress:function(a){return a},compressInputType:null,uncompressInputType:null},c.DEFLATE=a("./flate")},{"./flate":8}],4:[function(a,b){"use strict";var c=a("./utils"),d=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];b.exports=function(a,b){if("undefined"==typeof a||!a.length)return 0;var e="string"!==c.getTypeOf(a);"undefined"==typeof b&&(b=0);var f=0,g=0,h=0;b=-1^b;for(var i=0,j=a.length;j>i;i++)h=e?a[i]:a.charCodeAt(i),g=255&(b^h),f=d[g],b=b>>>8^f;return-1^b}},{"./utils":21}],5:[function(a,b){"use strict";function c(){this.data=null,this.length=0,this.index=0}var d=a("./utils");c.prototype={checkOffset:function(a){this.checkIndex(this.index+a)},checkIndex:function(a){if(this.length<a||0>a)throw new Error("End of data reached (data length = "+this.length+", asked index = "+a+"). Corrupted zip ?")},setIndex:function(a){this.checkIndex(a),this.index=a},skip:function(a){this.setIndex(this.index+a)},byteAt:function(){},readInt:function(a){var b,c=0;for(this.checkOffset(a),b=this.index+a-1;b>=this.index;b--)c=(c<<8)+this.byteAt(b);return this.index+=a,c},readString:function(a){return d.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date((a>>25&127)+1980,(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1)}},b.exports=c},{"./utils":21}],6:[function(a,b,c){"use strict";c.base64=!1,c.binary=!1,c.dir=!1,c.createFolders=!1,c.date=null,c.compression=null,c.comment=null},{}],7:[function(a,b,c){"use strict";var d=a("./utils");c.string2binary=function(a){return d.string2binary(a)},c.string2Uint8Array=function(a){return d.transformTo("uint8array",a)},c.uint8Array2String=function(a){return d.transformTo("string",a)},c.string2Blob=function(a){var b=d.transformTo("arraybuffer",a);return d.arrayBuffer2Blob(b)},c.arrayBuffer2Blob=function(a){return d.arrayBuffer2Blob(a)},c.transformTo=function(a,b){return d.transformTo(a,b)},c.getTypeOf=function(a){return d.getTypeOf(a)},c.checkSupport=function(a){return d.checkSupport(a)},c.MAX_VALUE_16BITS=d.MAX_VALUE_16BITS,c.MAX_VALUE_32BITS=d.MAX_VALUE_32BITS,c.pretty=function(a){return d.pretty(a)},c.findCompression=function(a){return d.findCompression(a)},c.isRegExp=function(a){return d.isRegExp(a)}},{"./utils":21}],8:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,e=a("pako");c.uncompressInputType=d?"uint8array":"array",c.compressInputType=d?"uint8array":"array",c.magic="\b\x00",c.compress=function(a){return e.deflateRaw(a)},c.uncompress=function(a){return e.inflateRaw(a)}},{pako:24}],9:[function(a,b){"use strict";function c(a,b){return this instanceof c?(this.files={},this.comment=null,this.root="",a&&this.load(a,b),void(this.clone=function(){var a=new c;for(var b in this)"function"!=typeof this[b]&&(a[b]=this[b]);return a})):new c(a,b)}var d=a("./base64");c.prototype=a("./object"),c.prototype.load=a("./load"),c.support=a("./support"),c.defaults=a("./defaults"),c.utils=a("./deprecatedPublicUtils"),c.base64={encode:function(a){return d.encode(a)},decode:function(a){return d.decode(a)}},c.compressions=a("./compressions"),b.exports=c},{"./base64":1,"./compressions":3,"./defaults":6,"./deprecatedPublicUtils":7,"./load":10,"./object":13,"./support":17}],10:[function(a,b){"use strict";var c=a("./base64"),d=a("./zipEntries");b.exports=function(a,b){var e,f,g,h;for(b=b||{},b.base64&&(a=c.decode(a)),f=new d(a,b),e=f.files,g=0;g<e.length;g++)h=e[g],this.file(h.fileName,h.decompressed,{binary:!0,optimizedBinaryString:!0,date:h.date,dir:h.dir,comment:h.fileComment.length?h.fileComment:null,createFolders:b.createFolders});return f.zipComment.length&&(this.comment=f.zipComment),this}},{"./base64":1,"./zipEntries":22}],11:[function(a,b){(function(a){"use strict";b.exports=function(b,c){return new a(b,c)},b.exports.test=function(b){return a.isBuffer(b)}}).call(this,"undefined"!=typeof Buffer?Buffer:void 0)},{}],12:[function(a,b){"use strict";function c(a){this.data=a,this.length=this.data.length,this.index=0}var d=a("./uint8ArrayReader");c.prototype=new d,c.prototype.readData=function(a){this.checkOffset(a);var b=this.data.slice(this.index,this.index+a);return this.index+=a,b},b.exports=c},{"./uint8ArrayReader":18}],13:[function(a,b){"use strict";var c=a("./support"),d=a("./utils"),e=a("./crc32"),f=a("./signature"),g=a("./defaults"),h=a("./base64"),i=a("./compressions"),j=a("./compressedObject"),k=a("./nodeBuffer"),l=a("./utf8"),m=a("./stringWriter"),n=a("./uint8ArrayWriter"),o=function(a){if(a._data instanceof j&&(a._data=a._data.getContent(),a.options.binary=!0,a.options.base64=!1,"uint8array"===d.getTypeOf(a._data))){var b=a._data;a._data=new Uint8Array(b.length),0!==b.length&&a._data.set(b,0)}return a._data},p=function(a){var b=o(a),e=d.getTypeOf(b);return"string"===e?!a.options.binary&&c.nodebuffer?k(b,"utf-8"):a.asBinary():b},q=function(a){var b=o(this);return null===b||"undefined"==typeof b?"":(this.options.base64&&(b=h.decode(b)),b=a&&this.options.binary?A.utf8decode(b):d.transformTo("string",b),a||this.options.binary||(b=d.transformTo("string",A.utf8encode(b))),b)},r=function(a,b,c){this.name=a,this.dir=c.dir,this.date=c.date,this.comment=c.comment,this._data=b,this.options=c,this._initialMetadata={dir:c.dir,date:c.date}};r.prototype={asText:function(){return q.call(this,!0)},asBinary:function(){return q.call(this,!1)},asNodeBuffer:function(){var a=p(this);return d.transformTo("nodebuffer",a)},asUint8Array:function(){var a=p(this);return d.transformTo("uint8array",a)},asArrayBuffer:function(){return this.asUint8Array().buffer}};var s=function(a,b){var c,d="";for(c=0;b>c;c++)d+=String.fromCharCode(255&a),a>>>=8;return d},t=function(){var a,b,c={};for(a=0;a<arguments.length;a++)for(b in arguments[a])arguments[a].hasOwnProperty(b)&&"undefined"==typeof c[b]&&(c[b]=arguments[a][b]);return c},u=function(a){return a=a||{},a.base64!==!0||null!==a.binary&&void 0!==a.binary||(a.binary=!0),a=t(a,g),a.date=a.date||new Date,null!==a.compression&&(a.compression=a.compression.toUpperCase()),a},v=function(a,b,c){var e,f=d.getTypeOf(b);if(c=u(c),c.createFolders&&(e=w(a))&&x.call(this,e,!0),c.dir||null===b||"undefined"==typeof b)c.base64=!1,c.binary=!1,b=null;else if("string"===f)c.binary&&!c.base64&&c.optimizedBinaryString!==!0&&(b=d.string2binary(b));else{if(c.base64=!1,c.binary=!0,!(f||b instanceof j))throw new Error("The data of '"+a+"' is in an unsupported format !");"arraybuffer"===f&&(b=d.transformTo("uint8array",b))}var g=new r(a,b,c);return this.files[a]=g,g},w=function(a){"/"==a.slice(-1)&&(a=a.substring(0,a.length-1));var b=a.lastIndexOf("/");return b>0?a.substring(0,b):""},x=function(a,b){return"/"!=a.slice(-1)&&(a+="/"),b="undefined"!=typeof b?b:!1,this.files[a]||v.call(this,a,null,{dir:!0,createFolders:b}),this.files[a]},y=function(a,b){var c,f=new j;return a._data instanceof j?(f.uncompressedSize=a._data.uncompressedSize,f.crc32=a._data.crc32,0===f.uncompressedSize||a.dir?(b=i.STORE,f.compressedContent="",f.crc32=0):a._data.compressionMethod===b.magic?f.compressedContent=a._data.getCompressedContent():(c=a._data.getContent(),f.compressedContent=b.compress(d.transformTo(b.compressInputType,c)))):(c=p(a),(!c||0===c.length||a.dir)&&(b=i.STORE,c=""),f.uncompressedSize=c.length,f.crc32=e(c),f.compressedContent=b.compress(d.transformTo(b.compressInputType,c))),f.compressedSize=f.compressedContent.length,f.compressionMethod=b.magic,f},z=function(a,b,c,g){var h,i,j,k,m=(c.compressedContent,d.transformTo("string",l.utf8encode(b.name))),n=b.comment||"",o=d.transformTo("string",l.utf8encode(n)),p=m.length!==b.name.length,q=o.length!==n.length,r=b.options,t="",u="",v="";j=b._initialMetadata.dir!==b.dir?b.dir:r.dir,k=b._initialMetadata.date!==b.date?b.date:r.date,h=k.getHours(),h<<=6,h|=k.getMinutes(),h<<=5,h|=k.getSeconds()/2,i=k.getFullYear()-1980,i<<=4,i|=k.getMonth()+1,i<<=5,i|=k.getDate(),p&&(u=s(1,1)+s(e(m),4)+m,t+="up"+s(u.length,2)+u),q&&(v=s(1,1)+s(this.crc32(o),4)+o,t+="uc"+s(v.length,2)+v);var w="";w+="\n\x00",w+=p||q?"\x00\b":"\x00\x00",w+=c.compressionMethod,w+=s(h,2),w+=s(i,2),w+=s(c.crc32,4),w+=s(c.compressedSize,4),w+=s(c.uncompressedSize,4),w+=s(m.length,2),w+=s(t.length,2);var x=f.LOCAL_FILE_HEADER+w+m+t,y=f.CENTRAL_FILE_HEADER+"\x00"+w+s(o.length,2)+"\x00\x00\x00\x00"+(j===!0?"\x00\x00\x00":"\x00\x00\x00\x00")+s(g,4)+m+t+o;return{fileRecord:x,dirRecord:y,compressedObject:c}},A={load:function(){throw new Error("Load method is not defined. Is the file jszip-load.js included ?")},filter:function(a){var b,c,d,e,f=[];for(b in this.files)this.files.hasOwnProperty(b)&&(d=this.files[b],e=new r(d.name,d._data,t(d.options)),c=b.slice(this.root.length,b.length),b.slice(0,this.root.length)===this.root&&a(c,e)&&f.push(e));return f},file:function(a,b,c){if(1===arguments.length){if(d.isRegExp(a)){var e=a;return this.filter(function(a,b){return!b.dir&&e.test(a)})}return this.filter(function(b,c){return!c.dir&&b===a})[0]||null}return a=this.root+a,v.call(this,a,b,c),this},folder:function(a){if(!a)return this;if(d.isRegExp(a))return this.filter(function(b,c){return c.dir&&a.test(b)});var b=this.root+a,c=x.call(this,b),e=this.clone();return e.root=c.name,e},remove:function(a){a=this.root+a;var b=this.files[a];if(b||("/"!=a.slice(-1)&&(a+="/"),b=this.files[a]),b&&!b.dir)delete this.files[a];else for(var c=this.filter(function(b,c){return c.name.slice(0,a.length)===a}),d=0;d<c.length;d++)delete this.files[c[d].name];return this},generate:function(a){a=t(a||{},{base64:!0,compression:"STORE",type:"base64",comment:null}),d.checkSupport(a.type);var b,c,e=[],g=0,j=0,k=d.transformTo("string",this.utf8encode(a.comment||this.comment||""));for(var l in this.files)if(this.files.hasOwnProperty(l)){var o=this.files[l],p=o.options.compression||a.compression.toUpperCase(),q=i[p];if(!q)throw new Error(p+" is not a valid compression method !");var r=y.call(this,o,q),u=z.call(this,l,o,r,g);g+=u.fileRecord.length+r.compressedSize,j+=u.dirRecord.length,e.push(u)}var v="";v=f.CENTRAL_DIRECTORY_END+"\x00\x00\x00\x00"+s(e.length,2)+s(e.length,2)+s(j,4)+s(g,4)+s(k.length,2)+k;var w=a.type.toLowerCase();for(b="uint8array"===w||"arraybuffer"===w||"blob"===w||"nodebuffer"===w?new n(g+j+v.length):new m(g+j+v.length),c=0;c<e.length;c++)b.append(e[c].fileRecord),b.append(e[c].compressedObject.compressedContent);for(c=0;c<e.length;c++)b.append(e[c].dirRecord);b.append(v);var x=b.finalize();switch(a.type.toLowerCase()){case"uint8array":case"arraybuffer":case"nodebuffer":return d.transformTo(a.type.toLowerCase(),x);case"blob":return d.arrayBuffer2Blob(d.transformTo("arraybuffer",x));case"base64":return a.base64?h.encode(x):x;default:return x}},crc32:function(a,b){return e(a,b)},utf8encode:function(a){return d.transformTo("string",l.utf8encode(a))},utf8decode:function(a){return l.utf8decode(a)}};b.exports=A},{"./base64":1,"./compressedObject":2,"./compressions":3,"./crc32":4,"./defaults":6,"./nodeBuffer":11,"./signature":14,"./stringWriter":16,"./support":17,"./uint8ArrayWriter":19,"./utf8":20,"./utils":21}],14:[function(a,b,c){"use strict";c.LOCAL_FILE_HEADER="PK",c.CENTRAL_FILE_HEADER="PK",c.CENTRAL_DIRECTORY_END="PK",c.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",c.ZIP64_CENTRAL_DIRECTORY_END="PK",c.DATA_DESCRIPTOR="PK\b"},{}],15:[function(a,b){"use strict";function c(a,b){this.data=a,b||(this.data=e.string2binary(this.data)),this.length=this.data.length,this.index=0}var d=a("./dataReader"),e=a("./utils");c.prototype=new d,c.prototype.byteAt=function(a){return this.data.charCodeAt(a)},c.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)},c.prototype.readData=function(a){this.checkOffset(a);var b=this.data.slice(this.index,this.index+a);return this.index+=a,b},b.exports=c},{"./dataReader":5,"./utils":21}],16:[function(a,b){"use strict";var c=a("./utils"),d=function(){this.data=[]};d.prototype={append:function(a){a=c.transformTo("string",a),this.data.push(a)},finalize:function(){return this.data.join("")}},b.exports=d},{"./utils":21}],17:[function(a,b,c){(function(a){"use strict";if(c.base64=!0,c.array=!0,c.string=!0,c.arraybuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array,c.nodebuffer="undefined"!=typeof a,c.uint8array="undefined"!=typeof Uint8Array,"undefined"==typeof ArrayBuffer)c.blob=!1;else{var b=new ArrayBuffer(0);try{c.blob=0===new Blob([b],{type:"application/zip"}).size}catch(d){try{var e=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder,f=new e;f.append(b),c.blob=0===f.getBlob("application/zip").size}catch(d){c.blob=!1}}}}).call(this,"undefined"!=typeof Buffer?Buffer:void 0)},{}],18:[function(a,b){"use strict";function c(a){a&&(this.data=a,this.length=this.data.length,this.index=0)}var d=a("./dataReader");c.prototype=new d,c.prototype.byteAt=function(a){return this.data[a]},c.prototype.lastIndexOfSignature=function(a){for(var b=a.charCodeAt(0),c=a.charCodeAt(1),d=a.charCodeAt(2),e=a.charCodeAt(3),f=this.length-4;f>=0;--f)if(this.data[f]===b&&this.data[f+1]===c&&this.data[f+2]===d&&this.data[f+3]===e)return f;return-1},c.prototype.readData=function(a){if(this.checkOffset(a),0===a)return new Uint8Array(0);var b=this.data.subarray(this.index,this.index+a);return this.index+=a,b},b.exports=c},{"./dataReader":5}],19:[function(a,b){"use strict";var c=a("./utils"),d=function(a){this.data=new Uint8Array(a),this.index=0};d.prototype={append:function(a){0!==a.length&&(a=c.transformTo("uint8array",a),this.data.set(a,this.index),this.index+=a.length)},finalize:function(){return this.data}},b.exports=d},{"./utils":21}],20:[function(a,b,c){"use strict";for(var d=a("./utils"),e=a("./support"),f=a("./nodeBuffer"),g=new Array(256),h=0;256>h;h++)g[h]=h>=252?6:h>=248?5:h>=240?4:h>=224?3:h>=192?2:1;g[254]=g[254]=1;var i=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=e.uint8array?new Uint8Array(i):new Array(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},j=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+g[a[c]]>b?c:b},k=function(a){var b,c,e,f,h=a.length,i=new Array(2*h);for(c=0,b=0;h>b;)if(e=a[b++],128>e)i[c++]=e;else if(f=g[e],f>4)i[c++]=65533,b+=f-1;else{for(e&=2===f?31:3===f?15:7;f>1&&h>b;)e=e<<6|63&a[b++],f--;f>1?i[c++]=65533:65536>e?i[c++]=e:(e-=65536,i[c++]=55296|e>>10&1023,i[c++]=56320|1023&e)}return i.length!==c&&(i.subarray?i=i.subarray(0,c):i.length=c),d.applyFromCharCode(i)};c.utf8encode=function(a){return e.nodebuffer?f(a,"utf-8"):i(a)},c.utf8decode=function(a){if(e.nodebuffer)return d.transformTo("nodebuffer",a).toString("utf-8");a=d.transformTo(e.uint8array?"uint8array":"array",a);for(var b=[],c=0,f=a.length,g=65536;f>c;){var h=j(a,Math.min(c+g,f));b.push(e.uint8array?k(a.subarray(c,h)):k(a.slice(c,h))),c=h}return b.join("")}},{"./nodeBuffer":11,"./support":17,"./utils":21}],21:[function(a,b,c){"use strict";function d(a){return a}function e(a,b){for(var c=0;c<a.length;++c)b[c]=255&a.charCodeAt(c);return b}function f(a){var b=65536,d=[],e=a.length,f=c.getTypeOf(a),g=0,h=!0;try{switch(f){case"uint8array":String.fromCharCode.apply(null,new Uint8Array(0));break;case"nodebuffer":String.fromCharCode.apply(null,j(0))}}catch(i){h=!1}if(!h){for(var k="",l=0;l<a.length;l++)k+=String.fromCharCode(a[l]);return k}for(;e>g&&b>1;)try{d.push("array"===f||"nodebuffer"===f?String.fromCharCode.apply(null,a.slice(g,Math.min(g+b,e))):String.fromCharCode.apply(null,a.subarray(g,Math.min(g+b,e)))),g+=b}catch(i){b=Math.floor(b/2)}return d.join("")}function g(a,b){for(var c=0;c<a.length;c++)b[c]=a[c];return b}var h=a("./support"),i=a("./compressions"),j=a("./nodeBuffer");c.string2binary=function(a){for(var b="",c=0;c<a.length;c++)b+=String.fromCharCode(255&a.charCodeAt(c));return b},c.arrayBuffer2Blob=function(a){c.checkSupport("blob");try{return new Blob([a],{type:"application/zip"})}catch(b){try{var d=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder,e=new d;return e.append(a),e.getBlob("application/zip")}catch(b){throw new Error("Bug : can't construct the Blob.")}}},c.applyFromCharCode=f;var k={};k.string={string:d,array:function(a){return e(a,new Array(a.length))},arraybuffer:function(a){return k.string.uint8array(a).buffer},uint8array:function(a){return e(a,new Uint8Array(a.length))},nodebuffer:function(a){return e(a,j(a.length))}},k.array={string:f,array:d,arraybuffer:function(a){return new Uint8Array(a).buffer},uint8array:function(a){return new Uint8Array(a)},nodebuffer:function(a){return j(a)}},k.arraybuffer={string:function(a){return f(new Uint8Array(a))},array:function(a){return g(new Uint8Array(a),new Array(a.byteLength))},arraybuffer:d,uint8array:function(a){return new Uint8Array(a)},nodebuffer:function(a){return j(new Uint8Array(a))}},k.uint8array={string:f,array:function(a){return g(a,new Array(a.length))},arraybuffer:function(a){return a.buffer},uint8array:d,nodebuffer:function(a){return j(a)}},k.nodebuffer={string:f,array:function(a){return g(a,new Array(a.length))},arraybuffer:function(a){return k.nodebuffer.uint8array(a).buffer},uint8array:function(a){return g(a,new Uint8Array(a.length))},nodebuffer:d},c.transformTo=function(a,b){if(b||(b=""),!a)return b;c.checkSupport(a);var d=c.getTypeOf(b),e=k[d][a](b);return e},c.getTypeOf=function(a){return"string"==typeof a?"string":"[object Array]"===Object.prototype.toString.call(a)?"array":h.nodebuffer&&j.test(a)?"nodebuffer":h.uint8array&&a instanceof Uint8Array?"uint8array":h.arraybuffer&&a instanceof ArrayBuffer?"arraybuffer":void 0},c.checkSupport=function(a){var b=h[a.toLowerCase()];if(!b)throw new Error(a+" is not supported by this browser")},c.MAX_VALUE_16BITS=65535,c.MAX_VALUE_32BITS=-1,c.pretty=function(a){var b,c,d="";for(c=0;c<(a||"").length;c++)b=a.charCodeAt(c),d+="\\x"+(16>b?"0":"")+b.toString(16).toUpperCase();return d},c.findCompression=function(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b].magic===a)return i[b];return null},c.isRegExp=function(a){return"[object RegExp]"===Object.prototype.toString.call(a)}},{"./compressions":3,"./nodeBuffer":11,"./support":17}],22:[function(a,b){"use strict";function c(a,b){this.files=[],this.loadOptions=b,a&&this.load(a)}var d=a("./stringReader"),e=a("./nodeBufferReader"),f=a("./uint8ArrayReader"),g=a("./utils"),h=a("./signature"),i=a("./zipEntry"),j=a("./support"),k=a("./object");c.prototype={checkSignature:function(a){var b=this.reader.readString(4);if(b!==a)throw new Error("Corrupted zip or bug : unexpected signature ("+g.pretty(b)+", expected "+g.pretty(a)+")")},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2),this.zipComment=this.reader.readString(this.zipCommentLength),this.zipComment=k.utf8decode(this.zipComment)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.versionMadeBy=this.reader.readString(2),this.versionNeeded=this.reader.readInt(2),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var a,b,c,d=this.zip64EndOfCentralSize-44,e=0;d>e;)a=this.reader.readInt(2),b=this.reader.readInt(4),c=this.reader.readString(b),this.zip64ExtensibleData[a]={id:a,length:b,value:c}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),this.disksCount>1)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var a,b;for(a=0;a<this.files.length;a++)b=this.files[a],this.reader.setIndex(b.localHeaderOffset),this.checkSignature(h.LOCAL_FILE_HEADER),b.readLocalPart(this.reader),b.handleUTF8()},readCentralDir:function(){var a;for(this.reader.setIndex(this.centralDirOffset);this.reader.readString(4)===h.CENTRAL_FILE_HEADER;)a=new i({zip64:this.zip64},this.loadOptions),a.readCentralPart(this.reader),this.files.push(a)},readEndOfCentral:function(){var a=this.reader.lastIndexOfSignature(h.CENTRAL_DIRECTORY_END);if(-1===a)throw new Error("Corrupted zip : can't find end of central directory");if(this.reader.setIndex(a),this.checkSignature(h.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===g.MAX_VALUE_16BITS||this.diskWithCentralDirStart===g.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===g.MAX_VALUE_16BITS||this.centralDirRecords===g.MAX_VALUE_16BITS||this.centralDirSize===g.MAX_VALUE_32BITS||this.centralDirOffset===g.MAX_VALUE_32BITS){if(this.zip64=!0,a=this.reader.lastIndexOfSignature(h.ZIP64_CENTRAL_DIRECTORY_LOCATOR),-1===a)throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");this.reader.setIndex(a),this.checkSignature(h.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(h.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}},prepareReader:function(a){var b=g.getTypeOf(a);this.reader="string"!==b||j.uint8array?"nodebuffer"===b?new e(a):new f(g.transformTo("uint8array",a)):new d(a,this.loadOptions.optimizedBinaryString)},load:function(a){this.prepareReader(a),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},b.exports=c},{"./nodeBufferReader":12,"./object":13,"./signature":14,"./stringReader":15,"./support":17,"./uint8ArrayReader":18,"./utils":21,"./zipEntry":23}],23:[function(a,b){"use strict";function c(a,b){this.options=a,this.loadOptions=b}var d=a("./stringReader"),e=a("./utils"),f=a("./compressedObject"),g=a("./object");c.prototype={isEncrypted:function(){return 1===(1&this.bitFlag)},useUTF8:function(){return 2048===(2048&this.bitFlag)},prepareCompressedContent:function(a,b,c){return function(){var d=a.index;a.setIndex(b);var e=a.readData(c);return a.setIndex(d),e}},prepareContent:function(a,b,c,d,f){return function(){var a=e.transformTo(d.uncompressInputType,this.getCompressedContent()),b=d.uncompress(a);if(b.length!==f)throw new Error("Bug : uncompressed data size mismatch");return b}},readLocalPart:function(a){var b,c;if(a.skip(22),this.fileNameLength=a.readInt(2),c=a.readInt(2),this.fileName=a.readString(this.fileNameLength),a.skip(c),-1==this.compressedSize||-1==this.uncompressedSize)throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory (compressedSize == -1 || uncompressedSize == -1)");if(b=e.findCompression(this.compressionMethod),null===b)throw new Error("Corrupted zip : compression "+e.pretty(this.compressionMethod)+" unknown (inner file : "+this.fileName+")");if(this.decompressed=new f,this.decompressed.compressedSize=this.compressedSize,this.decompressed.uncompressedSize=this.uncompressedSize,this.decompressed.crc32=this.crc32,this.decompressed.compressionMethod=this.compressionMethod,this.decompressed.getCompressedContent=this.prepareCompressedContent(a,a.index,this.compressedSize,b),this.decompressed.getContent=this.prepareContent(a,a.index,this.compressedSize,b,this.uncompressedSize),this.loadOptions.checkCRC32&&(this.decompressed=e.transformTo("string",this.decompressed.getContent()),g.crc32(this.decompressed)!==this.crc32))throw new Error("Corrupted zip : CRC32 mismatch")},readCentralPart:function(a){if(this.versionMadeBy=a.readString(2),this.versionNeeded=a.readInt(2),this.bitFlag=a.readInt(2),this.compressionMethod=a.readString(2),this.date=a.readDate(),this.crc32=a.readInt(4),this.compressedSize=a.readInt(4),this.uncompressedSize=a.readInt(4),this.fileNameLength=a.readInt(2),this.extraFieldsLength=a.readInt(2),this.fileCommentLength=a.readInt(2),this.diskNumberStart=a.readInt(2),this.internalFileAttributes=a.readInt(2),this.externalFileAttributes=a.readInt(4),this.localHeaderOffset=a.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");this.fileName=a.readString(this.fileNameLength),this.readExtraFields(a),this.parseZIP64ExtraField(a),this.fileComment=a.readString(this.fileCommentLength),this.dir=16&this.externalFileAttributes?!0:!1},parseZIP64ExtraField:function(){if(this.extraFields[1]){var a=new d(this.extraFields[1].value);this.uncompressedSize===e.MAX_VALUE_32BITS&&(this.uncompressedSize=a.readInt(8)),this.compressedSize===e.MAX_VALUE_32BITS&&(this.compressedSize=a.readInt(8)),this.localHeaderOffset===e.MAX_VALUE_32BITS&&(this.localHeaderOffset=a.readInt(8)),this.diskNumberStart===e.MAX_VALUE_32BITS&&(this.diskNumberStart=a.readInt(4))}},readExtraFields:function(a){var b,c,d,e=a.index;for(this.extraFields=this.extraFields||{};a.index<e+this.extraFieldsLength;)b=a.readInt(2),c=a.readInt(2),d=a.readString(c),this.extraFields[b]={id:b,length:c,value:d}},handleUTF8:function(){if(this.useUTF8())this.fileName=g.utf8decode(this.fileName),this.fileComment=g.utf8decode(this.fileComment);else{var a=this.findExtraFieldUnicodePath();null!==a&&(this.fileName=a);var b=this.findExtraFieldUnicodeComment();null!==b&&(this.fileComment=b)}},findExtraFieldUnicodePath:function(){var a=this.extraFields[28789];if(a){var b=new d(a.value);return 1!==b.readInt(1)?null:g.crc32(this.fileName)!==b.readInt(4)?null:g.utf8decode(b.readString(a.length-5))}return null},findExtraFieldUnicodeComment:function(){var a=this.extraFields[25461];if(a){var b=new d(a.value);return 1!==b.readInt(1)?null:g.crc32(this.fileComment)!==b.readInt(4)?null:g.utf8decode(b.readString(a.length-5))}return null}},b.exports=c},{"./compressedObject":2,"./object":13,"./stringReader":15,"./utils":21}],24:[function(a,b){"use strict";var c=a("./lib/utils/common").assign,d=a("./lib/deflate"),e=a("./lib/inflate"),f=a("./lib/zlib/constants"),g={};c(g,d,e,f),b.exports=g},{"./lib/deflate":25,"./lib/inflate":26,"./lib/utils/common":27,"./lib/zlib/constants":30}],25:[function(a,b,c){"use strict";function d(a,b){var c=new s(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}function f(a,b){return b=b||{},b.gzip=!0,d(a,b)}var g=a("./zlib/deflate.js"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=0,m=4,n=0,o=1,p=-1,q=0,r=8,s=function(a){this.options=h.assign({level:p,method:r,chunkSize:16384,windowBits:15,memLevel:8,strategy:q,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=g.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==n)throw new Error(j[c]);b.header&&g.deflateSetHeader(this.strm,b.header)
25557 };s.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?m:l,e.input="string"==typeof a?i.string2buf(a):a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new h.Buf8(f),e.next_out=0,e.avail_out=f),c=g.deflate(e,d),c!==o&&c!==n)return this.onEnd(c),this.ended=!0,!1;(0===e.avail_out||0===e.avail_in&&d===m)&&this.onData("string"===this.options.to?i.buf2binstring(h.shrinkBuf(e.output,e.next_out)):h.shrinkBuf(e.output,e.next_out))}while((e.avail_in>0||0===e.avail_out)&&c!==o);return d===m?(c=g.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===n):!0},s.prototype.onData=function(a){this.chunks.push(a)},s.prototype.onEnd=function(a){a===n&&(this.result="string"===this.options.to?this.chunks.join(""):h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=s,c.deflate=d,c.deflateRaw=e,c.gzip=f},{"./utils/common":27,"./utils/strings":28,"./zlib/deflate.js":32,"./zlib/messages":37,"./zlib/zstream":39}],26:[function(a,b,c){"use strict";function d(a,b){var c=new m(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}var f=a("./zlib/inflate.js"),g=a("./utils/common"),h=a("./utils/strings"),i=a("./zlib/constants"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=a("./zlib/gzheader"),m=function(a){this.options=g.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=f.inflateInit2(this.strm,b.windowBits);if(c!==i.Z_OK)throw new Error(j[c]);this.header=new l,f.inflateGetHeader(this.strm,this.header)};m.prototype.push=function(a,b){var c,d,e,j,k,l=this.strm,m=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?i.Z_FINISH:i.Z_NO_FLUSH,l.input="string"==typeof a?h.binstring2buf(a):a,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new g.Buf8(m),l.next_out=0,l.avail_out=m),c=f.inflate(l,i.Z_NO_FLUSH),c!==i.Z_STREAM_END&&c!==i.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0===l.avail_out||c===i.Z_STREAM_END||0===l.avail_in&&d===i.Z_FINISH)&&("string"===this.options.to?(e=h.utf8border(l.output,l.next_out),j=l.next_out-e,k=h.buf2string(l.output,e),l.next_out=j,l.avail_out=m-j,j&&g.arraySet(l.output,l.output,e,j,0),this.onData(k)):this.onData(g.shrinkBuf(l.output,l.next_out)))}while(l.avail_in>0&&c!==i.Z_STREAM_END);return c===i.Z_STREAM_END&&(d=i.Z_FINISH),d===i.Z_FINISH?(c=f.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===i.Z_OK):!0},m.prototype.onData=function(a){this.chunks.push(a)},m.prototype.onEnd=function(a){a===i.Z_OK&&(this.result="string"===this.options.to?this.chunks.join(""):g.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=m,c.inflate=d,c.inflateRaw=e,c.ungzip=d},{"./utils/common":27,"./utils/strings":28,"./zlib/constants":30,"./zlib/gzheader":33,"./zlib/inflate.js":35,"./zlib/messages":37,"./zlib/zstream":39}],27:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;c>b;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;c>b;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],28:[function(a,b,c){"use strict";function d(a,b){if(65537>b&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;b>d;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;256>j;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=new e.Buf8(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;d>c;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;h>c;)if(f=a[c++],128>f)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&h>c;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:65536>f?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":27}],29:[function(a,b){"use strict";function c(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=c},{}],30:[function(a,b){b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],31:[function(a,b){"use strict";function c(){for(var a,b=[],c=0;256>c;c++){a=c;for(var d=0;8>d;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function d(a,b,c,d){var f=e,g=d+c;a=-1^a;for(var h=d;g>h;h++)a=a>>>8^f[255&(a^b[h])];return-1^a}var e=c();b.exports=d},{}],32:[function(a,b,c){"use strict";function d(a,b){return a.msg=G[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(C.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){D._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,C.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=E(a.adler,b,e,c):2===a.state.wrap&&(a.adler=F(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-jb?a.strstart-(a.w_size-jb):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ib,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&m>f);if(d=ib-(m-f),f=m-ib,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-jb)){C.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=hb)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+hb-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<hb)););}while(a.lookahead<jb&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===H)return sb;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return sb;if(a.strstart-a.block_start>=a.w_size-jb&&(h(a,!1),0===a.strm.avail_out))return sb}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ub:vb):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?sb:sb}function o(a,b){for(var c,d;;){if(a.lookahead<jb){if(m(a),a.lookahead<jb&&b===H)return sb;if(0===a.lookahead)break}if(c=0,a.lookahead>=hb&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+hb-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-jb&&(a.match_length=l(a,c)),a.match_length>=hb)if(d=D._tr_tally(a,a.strstart-a.match_start,a.match_length-hb),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=hb){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+hb-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return sb}return a.insert=a.strstart<hb-1?a.strstart:hb-1,b===K?(h(a,!0),0===a.strm.avail_out?ub:vb):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sb:tb}function p(a,b){for(var c,d,e;;){if(a.lookahead<jb){if(m(a),a.lookahead<jb&&b===H)return sb;if(0===a.lookahead)break}if(c=0,a.lookahead>=hb&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+hb-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=hb-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-jb&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===S||a.match_length===hb&&a.strstart-a.match_start>4096)&&(a.match_length=hb-1)),a.prev_length>=hb&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-hb,d=D._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-hb),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+hb-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=hb-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return sb}else if(a.match_available){if(d=D._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return sb}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=D._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<hb-1?a.strstart:hb-1,b===K?(h(a,!0),0===a.strm.avail_out?ub:vb):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sb:tb}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ib){if(m(a),a.lookahead<=ib&&b===H)return sb;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=hb&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ib;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&f>e);a.match_length=ib-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=hb?(c=D._tr_tally(a,1,a.match_length-hb),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return sb}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ub:vb):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sb:tb}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===H)return sb;break}if(a.match_length=0,c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return sb}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ub:vb):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sb:tb}function s(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=B[a.level].max_lazy,a.good_match=B[a.level].good_length,a.nice_match=B[a.level].nice_length,a.max_chain_length=B[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=hb-1,a.match_available=0,a.ins_h=0}function t(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Y,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new C.Buf16(2*fb),this.dyn_dtree=new C.Buf16(2*(2*db+1)),this.bl_tree=new C.Buf16(2*(2*eb+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new C.Buf16(gb+1),this.heap=new C.Buf16(2*cb+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new C.Buf16(2*cb+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function u(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=X,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?lb:qb,a.adler=2===b.wrap?0:1,b.last_flush=H,D._tr_init(b),M):d(a,O)}function v(a){var b=u(a);return b===M&&s(a.state),b}function w(a,b){return a&&a.state?2!==a.state.wrap?O:(a.state.gzhead=b,M):O}function x(a,b,c,e,f,g){if(!a)return O;var h=1;if(b===R&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>Z||c!==Y||8>e||e>15||0>b||b>9||0>g||g>V)return d(a,O);8===e&&(e=9);var i=new t;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+hb-1)/hb),i.window=new C.Buf8(2*i.w_size),i.head=new C.Buf16(i.hash_size),i.prev=new C.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new C.Buf8(i.pending_buf_size),i.d_buf=i.lit_bufsize>>1,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,v(a)}function y(a,b){return x(a,b,Y,$,_,W)}function z(a,b){var c,h,k,l;if(!a||!a.state||b>L||0>b)return a?d(a,O):O;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===rb&&b!==K)return d(a,0===a.avail_out?Q:O);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===lb)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=F(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=mb):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,wb),h.status=qb);else{var m=Y+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=T||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=kb),m+=31-m%31,h.status=qb,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===mb)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=nb)}else h.status=nb;if(h.status===nb)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=ob)}else h.status=ob;if(h.status===ob)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=pb)}else h.status=pb;if(h.status===pb&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=qb)):h.status=qb),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,M}else if(0===a.avail_in&&e(b)<=e(c)&&b!==K)return d(a,Q);if(h.status===rb&&0!==a.avail_in)return d(a,Q);if(0!==a.avail_in||0!==h.lookahead||b!==H&&h.status!==rb){var o=h.strategy===T?r(h,b):h.strategy===U?q(h,b):B[h.level].func(h,b);if((o===ub||o===vb)&&(h.status=rb),o===sb||o===ub)return 0===a.avail_out&&(h.last_flush=-1),M;if(o===tb&&(b===I?D._tr_align(h):b!==L&&(D._tr_stored_block(h,0,0,!1),b===J&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,M}return b!==K?M:h.wrap<=0?N:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?M:N)}function A(a){var b;return a&&a.state?(b=a.state.status,b!==lb&&b!==mb&&b!==nb&&b!==ob&&b!==pb&&b!==qb&&b!==rb?d(a,O):(a.state=null,b===qb?d(a,P):M)):O}var B,C=a("../utils/common"),D=a("./trees"),E=a("./adler32"),F=a("./crc32"),G=a("./messages"),H=0,I=1,J=3,K=4,L=5,M=0,N=1,O=-2,P=-3,Q=-5,R=-1,S=1,T=2,U=3,V=4,W=0,X=2,Y=8,Z=9,$=15,_=8,ab=29,bb=256,cb=bb+1+ab,db=30,eb=19,fb=2*cb+1,gb=15,hb=3,ib=258,jb=ib+hb+1,kb=32,lb=42,mb=69,nb=73,ob=91,pb=103,qb=113,rb=666,sb=1,tb=2,ub=3,vb=4,wb=3,xb=function(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e};B=[new xb(0,0,0,0,n),new xb(4,4,8,4,o),new xb(4,5,16,8,o),new xb(4,6,32,32,o),new xb(4,4,16,16,p),new xb(8,16,32,32,p),new xb(8,16,128,128,p),new xb(8,32,128,256,p),new xb(32,128,258,1024,p),new xb(32,258,258,4096,p)],c.deflateInit=y,c.deflateInit2=x,c.deflateReset=v,c.deflateResetKeep=u,c.deflateSetHeader=w,c.deflate=z,c.deflateEnd=A,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":27,"./adler32":29,"./crc32":31,"./messages":37,"./trees":38}],33:[function(a,b){"use strict";function c(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=c},{}],34:[function(a,b){"use strict";var c=30,d=12;b.exports=function(a,b){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;e=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=e.dmax,l=e.wsize,m=e.whave,n=e.wnext,o=e.window,p=e.hold,q=e.bits,r=e.lencode,s=e.distcode,t=(1<<e.lenbits)-1,u=(1<<e.distbits)-1;a:do{15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){e.mode=d;break a}a.msg="invalid literal/length code",e.mode=c;break a}x=65535&v,w&=15,w&&(w>q&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",e.mode=c;break a}if(y=65535&v,w&=15,w>q&&(p+=B[f++]<<q,q+=8,w>q&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",e.mode=c;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&e.sane){a.msg="invalid distance too far back",e.mode=c;break a}if(z=0,A=o,0===n){if(z+=l-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(w>n){if(z+=l+n-w,w-=n,x>w){x-=w;do C[h++]=o[z++];while(--w);if(z=0,x>n){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(g>f&&j>h);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=g>f?5+(g-f):5-(f-g),a.avail_out=j>h?257+(j-h):257-(h-j),e.hold=p,e.bits=q}},{}],35:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=K,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new r.Buf32(ob),b.distcode=b.distdyn=new r.Buf32(pb),b.sane=1,b.back=-1,C):F}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):F}function h(a,b){var c,d;return a&&a.state?(d=a.state,0>b?(c=0,b=-b):(c=(b>>4)+1,48>b&&(b&=15)),b&&(8>b||b>15)?F:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):F}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==C&&(a.state=null),c):F}function j(a){return i(a,rb)}function k(a){if(sb){var b;for(p=new r.Buf32(512),q=new r.Buf32(32),b=0;144>b;)a.lens[b++]=8;for(;256>b;)a.lens[b++]=9;for(;280>b;)a.lens[b++]=7;for(;288>b;)a.lens[b++]=8;for(v(x,a.lens,0,288,p,0,a.work,{bits:9}),b=0;32>b;)a.lens[b++]=5;v(y,a.lens,0,32,q,0,a.work,{bits:5}),sb=!1}a.lencode=p,a.lenbits=9,a.distcode=q,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new r.Buf8(f.wsize)),d>=f.wsize?(r.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),r.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(r.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,ob,pb,qb,rb,sb,tb,ub,vb,wb,xb,yb,zb,Ab=0,Bb=new r.Buf8(4),Cb=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return F;c=a.state,c.mode===V&&(c.mode=W),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xb=C;a:for(;;)switch(c.mode){case K:if(0===c.wrap){c.mode=W;break}for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Bb[0]=255&m,Bb[1]=m>>>8&255,c.check=t(c.check,Bb,2,0),m=0,n=0,c.mode=L;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=lb;break}if((15&m)!==J){a.msg="unknown compression method",c.mode=lb;break}if(m>>>=4,n-=4,wb=(15&m)+8,0===c.wbits)c.wbits=wb;else if(wb>c.wbits){a.msg="invalid window size",c.mode=lb;break}c.dmax=1<<wb,a.adler=c.check=1,c.mode=512&m?T:V,m=0,n=0;break;case L:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==J){a.msg="unknown compression method",c.mode=lb;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=lb;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Bb[0]=255&m,Bb[1]=m>>>8&255,c.check=t(c.check,Bb,2,0)),m=0,n=0,c.mode=M;case M:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Bb[0]=255&m,Bb[1]=m>>>8&255,Bb[2]=m>>>16&255,Bb[3]=m>>>24&255,c.check=t(c.check,Bb,4,0)),m=0,n=0,c.mode=N;case N:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Bb[0]=255&m,Bb[1]=m>>>8&255,c.check=t(c.check,Bb,2,0)),m=0,n=0,c.mode=O;case O:if(1024&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Bb[0]=255&m,Bb[1]=m>>>8&255,c.check=t(c.check,Bb,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=P;case P:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wb=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),r.arraySet(c.head.extra,e,g,q,wb)),512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=Q;case Q:if(2048&c.flags){if(0===i)break a;q=0;do wb=e[g+q++],c.head&&wb&&c.length<65536&&(c.head.name+=String.fromCharCode(wb));while(wb&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wb)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=R;case R:if(4096&c.flags){if(0===i)break a;q=0;do wb=e[g+q++],c.head&&wb&&c.length<65536&&(c.head.comment+=String.fromCharCode(wb));while(wb&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wb)break a}else c.head&&(c.head.comment=null);c.mode=S;case S:if(512&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=lb;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=V;break;case T:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=U;case U:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,E;a.adler=c.check=1,c.mode=V;case V:if(b===A||b===B)break a;case W:if(c.last){m>>>=7&n,n-=7&n,c.mode=ib;break}for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=X;break;case 1:if(k(c),c.mode=bb,b===B){m>>>=2,n-=2;break a}break;case 2:c.mode=$;break;case 3:a.msg="invalid block type",c.mode=lb}m>>>=2,n-=2;break;case X:for(m>>>=7&n,n-=7&n;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=lb;break}if(c.length=65535&m,m=0,n=0,c.mode=Y,b===B)break a;case Y:c.mode=Z;case Z:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;r.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=V;break;case $:for(;14>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=lb;break}c.have=0,c.mode=_;case _:for(;c.have<c.ncode;){for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Cb[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Cb[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,yb={bits:c.lenbits},xb=v(w,c.lens,0,19,c.lencode,0,c.work,yb),c.lenbits=yb.bits,xb){a.msg="invalid code lengths set",c.mode=lb;break}c.have=0,c.mode=ab;case ab:for(;c.have<c.nlen+c.ndist;){for(;Ab=c.lencode[m&(1<<c.lenbits)-1],qb=Ab>>>24,rb=Ab>>>16&255,sb=65535&Ab,!(n>=qb);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(16>sb)m>>>=qb,n-=qb,c.lens[c.have++]=sb;else{if(16===sb){for(zb=qb+2;zb>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qb,n-=qb,0===c.have){a.msg="invalid bit length repeat",c.mode=lb;break}wb=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sb){for(zb=qb+3;zb>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qb,n-=qb,wb=0,q=3+(7&m),m>>>=3,n-=3}else{for(zb=qb+7;zb>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qb,n-=qb,wb=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=lb;break}for(;q--;)c.lens[c.have++]=wb}}if(c.mode===lb)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=lb;break}if(c.lenbits=9,yb={bits:c.lenbits},xb=v(x,c.lens,0,c.nlen,c.lencode,0,c.work,yb),c.lenbits=yb.bits,xb){a.msg="invalid literal/lengths set",c.mode=lb;break}if(c.distbits=6,c.distcode=c.distdyn,yb={bits:c.distbits},xb=v(y,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,yb),c.distbits=yb.bits,xb){a.msg="invalid distances set",c.mode=lb;break}if(c.mode=bb,b===B)break a;case bb:c.mode=cb;case cb:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,u(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===V&&(c.back=-1);break}for(c.back=0;Ab=c.lencode[m&(1<<c.lenbits)-1],qb=Ab>>>24,rb=Ab>>>16&255,sb=65535&Ab,!(n>=qb);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(rb&&0===(240&rb)){for(tb=qb,ub=rb,vb=sb;Ab=c.lencode[vb+((m&(1<<tb+ub)-1)>>tb)],qb=Ab>>>24,rb=Ab>>>16&255,sb=65535&Ab,!(n>=tb+qb);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=tb,n-=tb,c.back+=tb}if(m>>>=qb,n-=qb,c.back+=qb,c.length=sb,0===rb){c.mode=hb;break}if(32&rb){c.back=-1,c.mode=V;break}if(64&rb){a.msg="invalid literal/length code",c.mode=lb;break}c.extra=15&rb,c.mode=db;case db:if(c.extra){for(zb=c.extra;zb>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=eb;case eb:for(;Ab=c.distcode[m&(1<<c.distbits)-1],qb=Ab>>>24,rb=Ab>>>16&255,sb=65535&Ab,!(n>=qb);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&rb)){for(tb=qb,ub=rb,vb=sb;Ab=c.distcode[vb+((m&(1<<tb+ub)-1)>>tb)],qb=Ab>>>24,rb=Ab>>>16&255,sb=65535&Ab,!(n>=tb+qb);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=tb,n-=tb,c.back+=tb}if(m>>>=qb,n-=qb,c.back+=qb,64&rb){a.msg="invalid distance code",c.mode=lb;break}c.offset=sb,c.extra=15&rb,c.mode=fb;case fb:if(c.extra){for(zb=c.extra;zb>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=lb;break}c.mode=gb;case gb:if(0===j)break a;
25558 if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=lb;break}q>c.wnext?(q-=c.wnext,ob=c.wsize-q):ob=c.wnext-q,q>c.length&&(q=c.length),pb=c.window}else pb=f,ob=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pb[ob++];while(--q);0===c.length&&(c.mode=cb);break;case hb:if(0===j)break a;f[h++]=c.length,j--,c.mode=cb;break;case ib:if(c.wrap){for(;32>n;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?t(c.check,f,p,h-p):s(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=lb;break}m=0,n=0}c.mode=jb;case jb:if(c.wrap&&c.flags){for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=lb;break}m=0,n=0}c.mode=kb;case kb:xb=D;break a;case lb:xb=G;break a;case mb:return H;case nb:default:return F}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<lb&&(c.mode<ib||b!==z))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=mb,H):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?t(c.check,f,p,a.next_out-p):s(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===V?128:0)+(c.mode===bb||c.mode===Y?256:0),(0===o&&0===p||b===z)&&xb===C&&(xb=I),xb)}function n(a){if(!a||!a.state)return F;var b=a.state;return b.window&&(b.window=null),a.state=null,C}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?F:(c.head=b,b.done=!1,C)):F}var p,q,r=a("../utils/common"),s=a("./adler32"),t=a("./crc32"),u=a("./inffast"),v=a("./inftrees"),w=0,x=1,y=2,z=4,A=5,B=6,C=0,D=1,E=2,F=-2,G=-3,H=-4,I=-5,J=8,K=1,L=2,M=3,N=4,O=5,P=6,Q=7,R=8,S=9,T=10,U=11,V=12,W=13,X=14,Y=15,Z=16,$=17,_=18,ab=19,bb=20,cb=21,db=22,eb=23,fb=24,gb=25,hb=26,ib=27,jb=28,kb=29,lb=30,mb=31,nb=32,ob=852,pb=592,qb=15,rb=qb,sb=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":27,"./adler32":29,"./crc32":31,"./inffast":34,"./inftrees":36}],36:[function(a,b){"use strict";var c=a("../utils/common"),d=15,e=852,f=592,g=0,h=1,i=2,j=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],k=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],l=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],m=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,n,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new c.Buf16(d+1),Q=new c.Buf16(d+1),R=null,S=0;for(D=0;d>=D;D++)P[D]=0;for(E=0;o>E;E++)P[b[n+E]]++;for(H=C,G=d;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;G>F&&0===P[F];F++);for(F>H&&(H=F),K=1,D=1;d>=D;D++)if(K<<=1,K-=P[D],0>K)return-1;if(K>0&&(a===g||1!==G))return-1;for(Q[1]=0,D=1;d>D;D++)Q[D+1]=Q[D]+P[D];for(E=0;o>E;E++)0!==b[n+E]&&(r[Q[b[n+E]]++]=E);if(a===g?(N=R=r,y=19):a===h?(N=j,O-=257,R=k,S-=257,y=256):(N=l,R=m,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===h&&L>e||a===i&&L>f)return 1;for(var T=0;;){T++,z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[n+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;G>I+J&&(K-=P[I+J],!(0>=K));)I++,K<<=1;if(L+=1<<I,a===h&&L>e||a===i&&L>f)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":27}],37:[function(a,b){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],38:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a){return 256>a?gb[a]:gb[256+(a>>>7)]}function f(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function g(a,b,c){a.bi_valid>V-c?(a.bi_buf|=b<<a.bi_valid&65535,f(a,a.bi_buf),a.bi_buf=b>>V-a.bi_valid,a.bi_valid+=c-V):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function h(a,b,c){g(a,c[2*b],c[2*b+1])}function i(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function j(a){16===a.bi_valid?(f(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function k(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;U>=f;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;T>c;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function l(a,b,c){var d,e,f=new Array(U+1),g=0;for(d=1;U>=d;d++)f[d]=g=g+c[d-1]<<1;for(e=0;b>=e;e++){var h=a[2*e+1];0!==h&&(a[2*e]=i(f[h]++,h))}}function m(){var a,b,c,d,e,f=new Array(U+1);for(c=0,d=0;O-1>d;d++)for(ib[d]=c,a=0;a<1<<_[d];a++)hb[c++]=d;for(hb[c-1]=d,e=0,d=0;16>d;d++)for(jb[d]=e,a=0;a<1<<ab[d];a++)gb[e++]=d;for(e>>=7;R>d;d++)for(jb[d]=e<<7,a=0;a<1<<ab[d]-7;a++)gb[256+e++]=d;for(b=0;U>=b;b++)f[b]=0;for(a=0;143>=a;)eb[2*a+1]=8,a++,f[8]++;for(;255>=a;)eb[2*a+1]=9,a++,f[9]++;for(;279>=a;)eb[2*a+1]=7,a++,f[7]++;for(;287>=a;)eb[2*a+1]=8,a++,f[8]++;for(l(eb,Q+1,f),a=0;R>a;a++)fb[2*a+1]=5,fb[2*a]=i(a,5);kb=new nb(eb,_,P+1,Q,U),lb=new nb(fb,ab,0,R,U),mb=new nb(new Array(0),bb,0,S,W)}function n(a){var b;for(b=0;Q>b;b++)a.dyn_ltree[2*b]=0;for(b=0;R>b;b++)a.dyn_dtree[2*b]=0;for(b=0;S>b;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*X]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function o(a){a.bi_valid>8?f(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function p(a,b,c,d){o(a),d&&(f(a,c),f(a,~c)),E.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function q(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function r(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&q(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!q(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function s(a,b,c){var d,f,i,j,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],f=a.pending_buf[a.l_buf+k],k++,0===d?h(a,f,b):(i=hb[f],h(a,i+P+1,b),j=_[i],0!==j&&(f-=ib[i],g(a,f,j)),d--,i=e(d),h(a,i,c),j=ab[i],0!==j&&(d-=jb[i],g(a,d,j)));while(k<a.last_lit);h(a,X,b)}function t(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=T,c=0;i>c;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=2>j?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)r(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],r(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,r(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],k(a,b),l(f,j,a.bl_count)}function u(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;c>=d;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(j>h?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*Y]++):10>=h?a.bl_tree[2*Z]++:a.bl_tree[2*$]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function v(a,b,c){var d,e,f=-1,i=b[1],j=0,k=7,l=4;for(0===i&&(k=138,l=3),d=0;c>=d;d++)if(e=i,i=b[2*(d+1)+1],!(++j<k&&e===i)){if(l>j){do h(a,e,a.bl_tree);while(0!==--j)}else 0!==e?(e!==f&&(h(a,e,a.bl_tree),j--),h(a,Y,a.bl_tree),g(a,j-3,2)):10>=j?(h(a,Z,a.bl_tree),g(a,j-3,3)):(h(a,$,a.bl_tree),g(a,j-11,7));j=0,f=e,0===i?(k=138,l=3):e===i?(k=6,l=3):(k=7,l=4)}}function w(a){var b;for(u(a,a.dyn_ltree,a.l_desc.max_code),u(a,a.dyn_dtree,a.d_desc.max_code),t(a,a.bl_desc),b=S-1;b>=3&&0===a.bl_tree[2*cb[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function x(a,b,c,d){var e;for(g(a,b-257,5),g(a,c-1,5),g(a,d-4,4),e=0;d>e;e++)g(a,a.bl_tree[2*cb[e]+1],3);v(a,a.dyn_ltree,b-1),v(a,a.dyn_dtree,c-1)}function y(a){var b,c=4093624447;for(b=0;31>=b;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return G;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return H;for(b=32;P>b;b++)if(0!==a.dyn_ltree[2*b])return H;return G}function z(a){pb||(m(),pb=!0),a.l_desc=new ob(a.dyn_ltree,kb),a.d_desc=new ob(a.dyn_dtree,lb),a.bl_desc=new ob(a.bl_tree,mb),a.bi_buf=0,a.bi_valid=0,n(a)}function A(a,b,c,d){g(a,(J<<1)+(d?1:0),3),p(a,b,c,!0)}function B(a){g(a,K<<1,3),h(a,X,eb),j(a)}function C(a,b,c,d){var e,f,h=0;a.level>0?(a.strm.data_type===I&&(a.strm.data_type=y(a)),t(a,a.l_desc),t(a,a.d_desc),h=w(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,e>=f&&(e=f)):e=f=c+5,e>=c+4&&-1!==b?A(a,b,c,d):a.strategy===F||f===e?(g(a,(K<<1)+(d?1:0),3),s(a,eb,fb)):(g(a,(L<<1)+(d?1:0),3),x(a,a.l_desc.max_code+1,a.d_desc.max_code+1,h+1),s(a,a.dyn_ltree,a.dyn_dtree)),n(a),d&&o(a)}function D(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(hb[c]+P+1)]++,a.dyn_dtree[2*e(b)]++),a.last_lit===a.lit_bufsize-1}var E=a("../utils/common"),F=4,G=0,H=1,I=2,J=0,K=1,L=2,M=3,N=258,O=29,P=256,Q=P+1+O,R=30,S=19,T=2*Q+1,U=15,V=16,W=7,X=256,Y=16,Z=17,$=18,_=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],ab=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],bb=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],cb=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],db=512,eb=new Array(2*(Q+2));d(eb);var fb=new Array(2*R);d(fb);var gb=new Array(db);d(gb);var hb=new Array(N-M+1);d(hb);var ib=new Array(O);d(ib);var jb=new Array(R);d(jb);var kb,lb,mb,nb=function(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length},ob=function(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b},pb=!1;c._tr_init=z,c._tr_stored_block=A,c._tr_flush_block=C,c._tr_tally=D,c._tr_align=B},{"../utils/common":27}],39:[function(a,b){"use strict";function c(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=c},{}]},{},[9])(9)});
25559 // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
25560 if (!Object.keys) {
25561 Object.keys = (function () {
25562 var hasOwnProperty = Object.prototype.hasOwnProperty,
25563 hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
25564 dontEnums = [
25565 'toString',
25566 'toLocaleString',
25567 'valueOf',
25568 'hasOwnProperty',
25569 'isPrototypeOf',
25570 'propertyIsEnumerable',
25571 'constructor'
25572 ],
25573 dontEnumsLength = dontEnums.length;
25574
25575 return function (obj) {
25576 if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');
25577
25578 var result = [];
25579
25580 for (var prop in obj) {
25581 if (hasOwnProperty.call(obj, prop)) result.push(prop);
25582 }
25583
25584 if (hasDontEnumBug) {
25585 for (var i=0; i < dontEnumsLength; i++) {
25586 if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
25587 }
25588 }
25589 return result;
25590 };
25591 })();
25592 }
25593
25594 // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
25595 if (!Array.prototype.filter)
25596 {
25597 Array.prototype.filter = function(fun /*, thisp */)
25598 {
25599 "use strict";
25600
25601 if (this == null)
25602 throw new TypeError();
25603
25604 var t = Object(this);
25605 var len = t.length >>> 0;
25606 if (typeof fun != "function")
25607 throw new TypeError();
25608
25609 var res = [];
25610 var thisp = arguments[1];
25611 for (var i = 0; i < len; i++)
25612 {
25613 if (i in t)
25614 {
25615 var val = t[i]; // in case fun mutates this
25616 if (fun.call(thisp, val, i, t))
25617 res.push(val);
25618 }
25619 }
25620
25621 return res;
25622 };
25623 }
25624
25625 // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
25626 if (!String.prototype.trim) {
25627 String.prototype.trim = function () {
25628 return this.replace(/^\s+|\s+$/g, '');
25629 };
25630 }
25631
25632 // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
25633 if (!Array.prototype.forEach)
25634 {
25635 Array.prototype.forEach = function(fun /*, thisArg */)
25636 {
25637 "use strict";
25638
25639 if (this === void 0 || this === null)
25640 throw new TypeError();
25641
25642 var t = Object(this);
25643 var len = t.length >>> 0;
25644 if (typeof fun !== "function")
25645 throw new TypeError();
25646
25647 var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
25648 for (var i = 0; i < len; i++)
25649 {
25650 if (i in t)
25651 fun.call(thisArg, t[i], i, t);
25652 }
25653 };
25654 }
25655
25656 // Production steps of ECMA-262, Edition 5, 15.4.4.19
25657 // Reference: http://es5.github.com/#x15.4.4.19
25658 if (!Array.prototype.map) {
25659 Array.prototype.map = function(callback, thisArg) {
25660
25661 var T, A, k;
25662
25663 if (this == null) {
25664 throw new TypeError(" this is null or not defined");
25665 }
25666
25667 // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
25668 var O = Object(this);
25669
25670 // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
25671 // 3. Let len be ToUint32(lenValue).
25672 var len = O.length >>> 0;
25673
25674 // 4. If IsCallable(callback) is false, throw a TypeError exception.
25675 // See: http://es5.github.com/#x9.11
25676 if (typeof callback !== "function") {
25677 throw new TypeError(callback + " is not a function");
25678 }
25679
25680 // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
25681 if (thisArg) {
25682 T = thisArg;
25683 }
25684
25685 // 6. Let A be a new array created as if by the expression new Array(len) where Array is
25686 // the standard built-in constructor with that name and len is the value of len.
25687 A = new Array(len);
25688
25689 // 7. Let k be 0
25690 k = 0;
25691
25692 // 8. Repeat, while k < len
25693 while(k < len) {
25694
25695 var kValue, mappedValue;
25696
25697 // a. Let Pk be ToString(k).
25698 // This is implicit for LHS operands of the in operator
25699 // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
25700 // This step can be combined with c
25701 // c. If kPresent is true, then
25702 if (k in O) {
25703
25704 // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
25705 kValue = O[ k ];
25706
25707 // ii. Let mappedValue be the result of calling the Call internal method of callback
25708 // with T as the this value and argument list containing kValue, k, and O.
25709 mappedValue = callback.call(T, kValue, k, O);
25710
25711 // iii. Call the DefineOwnProperty internal method of A with arguments
25712 // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
25713 // and false.
25714
25715 // In browsers that support Object.defineProperty, use the following:
25716 // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
25717
25718 // For best browser support, use the following:
25719 A[ k ] = mappedValue;
25720 }
25721 // d. Increase k by 1.
25722 k++;
25723 }
25724
25725 // 9. return A
25726 return A;
25727 };
25728 }
25729
25730 // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
25731 if (!Array.prototype.indexOf) {
25732 Array.prototype.indexOf = function (searchElement, fromIndex) {
25733 if ( this === undefined || this === null ) {
25734 throw new TypeError( '"this" is null or not defined' );
25735 }
25736
25737 var length = this.length >>> 0; // Hack to convert object.length to a UInt32
25738
25739 fromIndex = +fromIndex || 0;
25740
25741 if (Math.abs(fromIndex) === Infinity) {
25742 fromIndex = 0;
25743 }
25744
25745 if (fromIndex < 0) {
25746 fromIndex += length;
25747 if (fromIndex < 0) {
25748 fromIndex = 0;
25749 }
25750 }
25751
25752 for (;fromIndex < length; fromIndex++) {
25753 if (this[fromIndex] === searchElement) {
25754 return fromIndex;
25755 }
25756 }
25757
25758 return -1;
25759 };
25760 }
25761 // Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
25762
25763 if (! Array.isArray) {
25764 Array.isArray = function(obj) {
25765 return Object.prototype.toString.call(obj) === "[object Array]";
25766 };
25767 }
25768
25769 // https://github.com/ttaubert/node-arraybuffer-slice
25770 // (c) 2013 Tim Taubert <tim@timtaubert.de>
25771 // arraybuffer-slice may be freely distributed under the MIT license.
25772
25773 "use strict";
25774
25775 if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
25776 ArrayBuffer.prototype.slice = function (begin, end) {
25777 begin = (begin|0) || 0;
25778 var num = this.byteLength;
25779 end = end === (void 0) ? num : (end|0);
25780
25781 // Handle negative values.
25782 if (begin < 0) begin += num;
25783 if (end < 0) end += num;
25784
25785 if (num === 0 || begin >= num || begin >= end) {
25786 return new ArrayBuffer(0);
25787 }
25788
25789 var length = Math.min(num - begin, end - begin);
25790 var target = new ArrayBuffer(length);
25791 var targetArray = new Uint8Array(target);
25792 targetArray.set(new Uint8Array(this, begin, length));
25793 return target;
25794 };
25795 }
25796 /* xls.js (C) 2013-2014 SheetJS -- http://sheetjs.com */
25797 var XLS={};(function make_xls(XLS){XLS.version="0.7.1";var current_codepage=1252,current_cptable;if(typeof module!=="undefined"&&typeof require!=="undefined"){if(typeof cptable==="undefined")cptable=require("./dist/cpexcel");current_cptable=cptable[current_codepage]}function reset_cp(){set_cp(1252)}function set_cp(cp){current_codepage=cp;if(typeof cptable!=="undefined")current_cptable=cptable[cp]}var _getchar=function _gc1(x){return String.fromCharCode(x)};if(typeof cptable!=="undefined")_getchar=function _gc2(x){if(current_codepage===1200)return String.fromCharCode(x);return cptable.utils.decode(current_codepage,[x&255,x>>8])[0]};var has_buf=typeof Buffer!=="undefined";function new_buf(len){return new(has_buf?Buffer:Array)(len)}var Base64=function make_b64(){var map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";return{decode:function b64_decode(input,utf8){var o="";var c1,c2,c3;var e1,e2,e3,e4;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var i=0;i<input.length;){e1=map.indexOf(input.charAt(i++));e2=map.indexOf(input.charAt(i++));e3=map.indexOf(input.charAt(i++));e4=map.indexOf(input.charAt(i++));c1=e1<<2|e2>>4;c2=(e2&15)<<4|e3>>2;c3=(e3&3)<<6|e4;o+=String.fromCharCode(c1);if(e3!=64){o+=String.fromCharCode(c2)}if(e4!=64){o+=String.fromCharCode(c3)}}return o}}}();function s2a(s){if(has_buf)return new Buffer(s,"binary");var w=s.split("").map(function(x){return x.charCodeAt(0)&255});return w}function readIEEE754(buf,idx,isLE,nl,ml){if(isLE===undefined)isLE=true;if(!nl)nl=8;if(!ml&&nl===8)ml=52;var e,m,el=nl*8-ml-1,eMax=(1<<el)-1,eBias=eMax>>1;var bits=-7,d=isLE?-1:1,i=isLE?nl-1:0,s=buf[idx+i];i+=d;e=s&(1<<-bits)-1;s>>>=-bits;bits+=el;for(;bits>0;e=e*256+buf[idx+i],i+=d,bits-=8);m=e&(1<<-bits)-1;e>>>=-bits;bits+=ml;for(;bits>0;m=m*256+buf[idx+i],i+=d,bits-=8);if(e===eMax)return m?NaN:(s?-1:1)*Infinity;else if(e===0)e=1-eBias;else{m=m+Math.pow(2,ml);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-ml)}var chr0=/\u0000/g,chr1=/[\u0001-\u0006]/;var __toBuffer,___toBuffer;__toBuffer=___toBuffer=function toBuffer_(bufs){var x=[];for(var i=0;i<bufs[0].length;++i){x.push.apply(x,bufs[0][i])}return x};var __utf16le,___utf16le;__utf16le=___utf16le=function utf16le_(b,s,e){var ss=[];for(var i=s;i<e;i+=2)ss.push(String.fromCharCode(__readUInt16LE(b,i)));return ss.join("")};var __hexlify,___hexlify;__hexlify=___hexlify=function hexlify_(b,s,l){return b.slice(s,s+l).map(function(x){return(x<16?"0":"")+x.toString(16)}).join("")};var __utf8,___utf8;__utf8=___utf8=function(b,s,e){var ss=[];for(var i=s;i<e;i++)ss.push(String.fromCharCode(__readUInt8(b,i)));return ss.join("")};var __lpstr,___lpstr;__lpstr=___lpstr=function lpstr_(b,i){var len=__readUInt32LE(b,i);return len>0?__utf8(b,i+4,i+4+len-1):""};var __lpwstr,___lpwstr;__lpwstr=___lpwstr=function lpwstr_(b,i){var len=2*__readUInt32LE(b,i);return len>0?__utf8(b,i+4,i+4+len-1):""};var __double,___double;__double=___double=function(b,idx){return readIEEE754(b,idx)};var bconcat=function(bufs){return[].concat.apply([],bufs)};if(typeof Buffer!=="undefined"){__utf16le=function utf16le_b(b,s,e){if(!Buffer.isBuffer(b))return ___utf16le(b,s,e);return b.toString("utf16le",s,e)};__hexlify=function(b,s,l){return Buffer.isBuffer(b)?b.toString("hex",s,s+l):___hexlify(b,s,l)};__lpstr=function lpstr_b(b,i){if(!Buffer.isBuffer(b))return ___lpstr(b,i);var len=b.readUInt32LE(i);return len>0?b.toString("utf8",i+4,i+4+len-1):""};__lpwstr=function lpwstr_b(b,i){if(!Buffer.isBuffer(b))return ___lpwstr(b,i);var len=2*b.readUInt32LE(i);return b.toString("utf16le",i+4,i+4+len-1)};__utf8=function utf8_b(s,e){return this.toString("utf8",s,e)};__toBuffer=function(bufs){return bufs[0].length>0&&Buffer.isBuffer(bufs[0][0])?Buffer.concat(bufs[0]):___toBuffer(bufs)};bconcat=function(bufs){return Buffer.isBuffer(bufs[0])?Buffer.concat(bufs):[].concat.apply([],bufs)};__double=function double_(b,i){if(Buffer.isBuffer(b))return b.readDoubleLE(i);return ___double(b,i)}}var __readUInt8=function(b,idx){return b[idx]};var __readUInt16LE=function(b,idx){return b[idx+1]*(1<<8)+b[idx]};var __readInt16LE=function(b,idx){var u=b[idx+1]*(1<<8)+b[idx];return u<32768?u:(65535-u+1)*-1};var __readUInt32LE=function(b,idx){return b[idx+3]*(1<<24)+(b[idx+2]<<16)+(b[idx+1]<<8)+b[idx]};var __readInt32LE=function(b,idx){return b[idx+3]<<24|b[idx+2]<<16|b[idx+1]<<8|b[idx]};var ___unhexlify=function(s){return s.match(/../g).map(function(x){return parseInt(x,16)})};var __unhexlify=typeof Buffer!=="undefined"?function(s){return Buffer.isBuffer(s)?new Buffer(s,"hex"):___unhexlify(s)}:___unhexlify;if(typeof cptable!=="undefined"){__utf16le=function(b,s,e){return cptable.utils.decode(1200,b.slice(s,e))};__utf8=function(b,s,e){return cptable.utils.decode(65001,b.slice(s,e))};__lpstr=function(b,i){var len=__readUInt32LE(b,i);return len>0?cptable.utils.decode(current_codepage,b.slice(i+4,i+4+len-1)):""};__lpwstr=function(b,i){var len=2*__readUInt32LE(b,i);return len>0?cptable.utils.decode(1200,b.slice(i+4,i+4+len-1)):""}}function ReadShift(size,t){var o,oI,oR,oo=[],w,vv,i,loc;switch(t){case"lpstr":o=__lpstr(this,this.l);size=5+o.length;break;case"lpwstr":o=__lpwstr(this,this.l);size=5+o.length;if(o[o.length-1]=="\x00")size+=2;break;case"cstr":size=0;o="";while((w=__readUInt8(this,this.l+size++))!==0)oo.push(_getchar(w));o=oo.join("");break;case"wstr":size=0;o="";while((w=__readUInt16LE(this,this.l+size))!==0){oo.push(_getchar(w));size+=2}size+=2;o=oo.join("");break;case"dbcs":o="";loc=this.l;for(i=0;i!=size;++i){if(this.lens&&this.lens.indexOf(loc)!==-1){w=__readUInt8(this,loc);this.l=loc+1;vv=ReadShift.call(this,size-i,w?"dbcs":"sbcs");return oo.join("")+vv}oo.push(_getchar(__readUInt16LE(this,loc)));loc+=2}o=oo.join("");size*=2;break;case"sbcs":o="";loc=this.l;for(i=0;i!=size;++i){if(this.lens&&this.lens.indexOf(loc)!==-1){w=__readUInt8(this,loc);this.l=loc+1;vv=ReadShift.call(this,size-i,w?"dbcs":"sbcs");return oo.join("")+vv}oo.push(_getchar(__readUInt8(this,loc)));loc+=1}o=oo.join("");break;case"utf8":o=__utf8(this,this.l,this.l+size);break;case"utf16le":size*=2;o=__utf16le(this,this.l,this.l+size);break;default:switch(size){case 1:oI=__readUInt8(this,this.l);this.l++;return oI;case 2:oI=t!=="i"?__readUInt16LE(this,this.l):__readInt16LE(this,this.l);this.l+=2;return oI;case 4:if(t==="i"||(this[this.l+3]&128)===0){oI=__readInt32LE(this,this.l);this.l+=4;return oI}else{oR=__readUInt32LE(this,this.l);this.l+=4;return oR}break;case 8:if(t==="f"){oR=__double(this,this.l);this.l+=8;return oR}case 16:o=__hexlify(this,this.l,size);break}}this.l+=size;return o}function CheckField(hexstr,fld){var m=__hexlify(this,this.l,hexstr.length>>1);if(m!==hexstr)throw fld+"Expected "+hexstr+" saw "+m;this.l+=hexstr.length>>1}function prep_blob(blob,pos){blob.l=pos;blob.read_shift=ReadShift;blob.chk=CheckField}var SSF={};var make_ssf=function make_ssf(SSF){SSF.version="0.8.1";function _strrev(x){var o="",i=x.length-1;while(i>=0)o+=x.charAt(i--);return o}function fill(c,l){var o="";while(o.length<l)o+=c;return o}function pad0(v,d){var t=""+v;return t.length>=d?t:fill("0",d-t.length)+t}function pad_(v,d){var t=""+v;return t.length>=d?t:fill(" ",d-t.length)+t}function rpad_(v,d){var t=""+v;return t.length>=d?t:t+fill(" ",d-t.length)}function pad0r1(v,d){var t=""+Math.round(v);return t.length>=d?t:fill("0",d-t.length)+t}function pad0r2(v,d){var t=""+v;return t.length>=d?t:fill("0",d-t.length)+t}var p2_32=Math.pow(2,32);function pad0r(v,d){if(v>p2_32||v<-p2_32)return pad0r1(v,d);var i=Math.round(v);return pad0r2(i,d)}function isgeneral(s,i){return s.length>=7+i&&(s.charCodeAt(i)|32)===103&&(s.charCodeAt(i+1)|32)===101&&(s.charCodeAt(i+2)|32)===110&&(s.charCodeAt(i+3)|32)===101&&(s.charCodeAt(i+4)|32)===114&&(s.charCodeAt(i+5)|32)===97&&(s.charCodeAt(i+6)|32)===108}var opts_fmt=[["date1904",0],["output",""],["WTF",false]];function fixopts(o){for(var y=0;y!=opts_fmt.length;++y)if(o[opts_fmt[y][0]]===undefined)o[opts_fmt[y][0]]=opts_fmt[y][1]}SSF.opts=opts_fmt;var table_fmt={0:"General",1:"0",2:"0.00",3:"#,##0",4:"#,##0.00",9:"0%",10:"0.00%",11:"0.00E+00",12:"# ?/?",13:"# ??/??",14:"m/d/yy",15:"d-mmm-yy",16:"d-mmm",17:"mmm-yy",18:"h:mm AM/PM",19:"h:mm:ss AM/PM",20:"h:mm",21:"h:mm:ss",22:"m/d/yy h:mm",37:"#,##0 ;(#,##0)",38:"#,##0 ;[Red](#,##0)",39:"#,##0.00;(#,##0.00)",40:"#,##0.00;[Red](#,##0.00)",45:"mm:ss",46:"[h]:mm:ss",47:"mmss.0",48:"##0.0E+0",49:"@",56:'"上午/下午 "hh"時"mm"分"ss"秒 "',65535:"General"};var days=[["Sun","Sunday"],["Mon","Monday"],["Tue","Tuesday"],["Wed","Wednesday"],["Thu","Thursday"],["Fri","Friday"],["Sat","Saturday"]];var months=[["J","Jan","January"],["F","Feb","February"],["M","Mar","March"],["A","Apr","April"],["M","May","May"],["J","Jun","June"],["J","Jul","July"],["A","Aug","August"],["S","Sep","September"],["O","Oct","October"],["N","Nov","November"],["D","Dec","December"]];function frac(x,D,mixed){var sgn=x<0?-1:1;var B=x*sgn;var P_2=0,P_1=1,P=0;var Q_2=1,Q_1=0,Q=0;var A=Math.floor(B);while(Q_1<D){A=Math.floor(B);P=A*P_1+P_2;Q=A*Q_1+Q_2;if(B-A<5e-10)break;B=1/(B-A);P_2=P_1;P_1=P;Q_2=Q_1;Q_1=Q}if(Q>D){Q=Q_1;P=P_1}if(Q>D){Q=Q_2;P=P_2}if(!mixed)return[0,sgn*P,Q];if(Q===0)throw"Unexpected state: "+P+" "+P_1+" "+P_2+" "+Q+" "+Q_1+" "+Q_2;var q=Math.floor(sgn*P/Q);return[q,sgn*P-q*Q,Q]}function general_fmt_int(v,opts){return""+v}SSF._general_int=general_fmt_int;var general_fmt_num=function make_general_fmt_num(){var gnr1=/\.(\d*[1-9])0+$/,gnr2=/\.0*$/,gnr4=/\.(\d*[1-9])0+/,gnr5=/\.0*[Ee]/,gnr6=/(E[+-])(\d)$/;function gfn2(v){var w=v<0?12:11;var o=gfn5(v.toFixed(12));if(o.length<=w)return o;o=v.toPrecision(10);if(o.length<=w)return o;return v.toExponential(5)}function gfn3(v){var o=v.toFixed(11).replace(gnr1,".$1");if(o.length>(v<0?12:11))o=v.toPrecision(6);return o}function gfn4(o){for(var i=0;i!=o.length;++i)if((o.charCodeAt(i)|32)===101)return o.replace(gnr4,".$1").replace(gnr5,"E").replace("e","E").replace(gnr6,"$10$2");return o}function gfn5(o){return o.indexOf(".")>-1?o.replace(gnr2,"").replace(gnr1,".$1"):o}return function general_fmt_num(v,opts){var V=Math.floor(Math.log(Math.abs(v))*Math.LOG10E),o;if(V>=-4&&V<=-1)o=v.toPrecision(10+V);else if(Math.abs(V)<=9)o=gfn2(v);else if(V===10)o=v.toFixed(10).substr(0,12);else o=gfn3(v);return gfn5(gfn4(o))}}();SSF._general_num=general_fmt_num;function general_fmt(v,opts){switch(typeof v){case"string":return v;case"boolean":return v?"TRUE":"FALSE";case"number":return(v|0)===v?general_fmt_int(v,opts):general_fmt_num(v,opts)}throw new Error("unsupported value in General format: "+v)}SSF._general=general_fmt;function fix_hijri(date,o){return 0}function parse_date_code(v,opts,b2){if(v>2958465||v<0)return null;var date=v|0,time=Math.floor(86400*(v-date)),dow=0;var dout=[];var out={D:date,T:time,u:86400*(v-date)-time,y:0,m:0,d:0,H:0,M:0,S:0,q:0};if(Math.abs(out.u)<1e-6)out.u=0;fixopts(opts!=null?opts:opts=[]);if(opts.date1904)date+=1462;if(out.u>.999){out.u=0;if(++time==86400){time=0;++date}}if(date===60){dout=b2?[1317,10,29]:[1900,2,29];dow=3}else if(date===0){dout=b2?[1317,8,29]:[1900,1,0];dow=6}else{if(date>60)--date;var d=new Date(1900,0,1);d.setDate(d.getDate()+date-1);dout=[d.getFullYear(),d.getMonth()+1,d.getDate()];dow=d.getDay();if(date<60)dow=(dow+6)%7;if(b2)dow=fix_hijri(d,dout)}out.y=dout[0];out.m=dout[1];out.d=dout[2];out.S=time%60;time=Math.floor(time/60);out.M=time%60;time=Math.floor(time/60);out.H=time;out.q=dow;return out}SSF.parse_date_code=parse_date_code;function write_date(type,fmt,val,ss0){var o="",ss=0,tt=0,y=val.y,out,outl=0;switch(type){case 98:y=val.y+543;case 121:switch(fmt.length){case 1:case 2:out=y%100;outl=2;break;default:out=y%1e4;outl=4;break}break;case 109:switch(fmt.length){case 1:case 2:out=val.m;outl=fmt.length;break;case 3:return months[val.m-1][1];case 5:return months[val.m-1][0];default:return months[val.m-1][2]}break;case 100:switch(fmt.length){case 1:case 2:out=val.d;outl=fmt.length;break;case 3:return days[val.q][0];default:return days[val.q][1]}break;case 104:switch(fmt.length){case 1:case 2:out=1+(val.H+11)%12;outl=fmt.length;break;default:throw"bad hour format: "+fmt}break;case 72:switch(fmt.length){case 1:case 2:out=val.H;outl=fmt.length;break;default:throw"bad hour format: "+fmt}break;case 77:switch(fmt.length){case 1:case 2:out=val.M;outl=fmt.length;break;default:throw"bad minute format: "+fmt}break;case 115:if(val.u===0)switch(fmt){case"s":case"ss":return pad0(val.S,fmt.length);case".0":case".00":case".000":}switch(fmt){case"s":case"ss":case".0":case".00":case".000":if(ss0>=2)tt=ss0===3?1e3:100;else tt=ss0===1?10:1;ss=Math.round(tt*(val.S+val.u));if(ss>=60*tt)ss=0;if(fmt==="s")return ss===0?"0":""+ss/tt;o=pad0(ss,2+ss0);if(fmt==="ss")return o.substr(0,2);return"."+o.substr(2,fmt.length-1);default:throw"bad second format: "+fmt}case 90:switch(fmt){case"[h]":case"[hh]":out=val.D*24+val.H;break;case"[m]":case"[mm]":out=(val.D*24+val.H)*60+val.M;break;case"[s]":case"[ss]":out=((val.D*24+val.H)*60+val.M)*60+Math.round(val.S+val.u);break;default:throw"bad abstime format: "+fmt}outl=fmt.length===3?1:2;break;case 101:out=y;outl=1}if(outl>0)return pad0(out,outl);else return""}function commaify(s){if(s.length<=3)return s;var j=s.length%3,o=s.substr(0,j);for(;j!=s.length;j+=3)o+=(o.length>0?",":"")+s.substr(j,3);return o}var write_num=function make_write_num(){var pct1=/%/g;function write_num_pct(type,fmt,val){var sfmt=fmt.replace(pct1,""),mul=fmt.length-sfmt.length;return write_num(type,sfmt,val*Math.pow(10,2*mul))+fill("%",mul)}function write_num_cm(type,fmt,val){var idx=fmt.length-1;while(fmt.charCodeAt(idx-1)===44)--idx;return write_num(type,fmt.substr(0,idx),val/Math.pow(10,3*(fmt.length-idx)))}function write_num_exp(fmt,val){var o;var idx=fmt.indexOf("E")-fmt.indexOf(".")-1;if(fmt.match(/^#+0.0E\+0$/)){var period=fmt.indexOf(".");if(period===-1)period=fmt.indexOf("E");var ee=Math.floor(Math.log(Math.abs(val))*Math.LOG10E)%period;if(ee<0)ee+=period;o=(val/Math.pow(10,ee)).toPrecision(idx+1+(period+ee)%period);if(o.indexOf("e")===-1){var fakee=Math.floor(Math.log(Math.abs(val))*Math.LOG10E);if(o.indexOf(".")===-1)o=o[0]+"."+o.substr(1)+"E+"+(fakee-o.length+ee);else o+="E+"+(fakee-ee);while(o.substr(0,2)==="0."){o=o[0]+o.substr(2,period)+"."+o.substr(2+period);o=o.replace(/^0+([1-9])/,"$1").replace(/^0+\./,"0.")}o=o.replace(/\+-/,"-")}o=o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function($$,$1,$2,$3){return $1+$2+$3.substr(0,(period+ee)%period)+"."+$3.substr(ee)+"E"})}else o=val.toExponential(idx);if(fmt.match(/E\+00$/)&&o.match(/e[+-]\d$/))o=o.substr(0,o.length-1)+"0"+o[o.length-1];if(fmt.match(/E\-/)&&o.match(/e\+/))o=o.replace(/e\+/,"e");return o.replace("e","E")}var frac1=/# (\?+)( ?)\/( ?)(\d+)/;function write_num_f1(r,aval,sign){var den=parseInt(r[4]),rr=Math.round(aval*den),base=Math.floor(rr/den);var myn=rr-base*den,myd=den;return sign+(base===0?"":""+base)+" "+(myn===0?fill(" ",r[1].length+1+r[4].length):pad_(myn,r[1].length)+r[2]+"/"+r[3]+pad0(myd,r[4].length))}function write_num_f2(r,aval,sign){return sign+(aval===0?"":""+aval)+fill(" ",r[1].length+2+r[4].length)}var dec1=/^#*0*\.(0+)/;var closeparen=/\).*[0#]/;var phone=/\(###\) ###\\?-####/;function hashq(str){var o="",cc;for(var i=0;i!=str.length;++i)switch(cc=str.charCodeAt(i)){case 35:break;case 63:o+=" ";break;case 48:o+="0";break;default:o+=String.fromCharCode(cc)}return o}function rnd(val,d){var dd=Math.pow(10,d);return""+Math.round(val*dd)/dd}function dec(val,d){return Math.round((val-Math.floor(val))*Math.pow(10,d))}function flr(val){if(val<2147483647&&val>-2147483648)return""+(val>=0?val|0:val-1|0);return""+Math.floor(val)}function write_num_flt(type,fmt,val){if(type.charCodeAt(0)===40&&!fmt.match(closeparen)){var ffmt=fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");if(val>=0)return write_num_flt("n",ffmt,val);return"("+write_num_flt("n",ffmt,-val)+")"}if(fmt.charCodeAt(fmt.length-1)===44)return write_num_cm(type,fmt,val);if(fmt.indexOf("%")!==-1)return write_num_pct(type,fmt,val);if(fmt.indexOf("E")!==-1)return write_num_exp(fmt,val);if(fmt.charCodeAt(0)===36)return"$"+write_num_flt(type,fmt.substr(fmt[1]==" "?2:1),val);var o,oo;var r,ri,ff,aval=Math.abs(val),sign=val<0?"-":"";if(fmt.match(/^00+$/))return sign+pad0r(aval,fmt.length);if(fmt.match(/^[#?]+$/)){o=pad0r(val,0);if(o==="0")o="";return o.length>fmt.length?o:hashq(fmt.substr(0,fmt.length-o.length))+o}if((r=fmt.match(frac1))!==null)return write_num_f1(r,aval,sign);if(fmt.match(/^#+0+$/)!==null)return sign+pad0r(aval,fmt.length-fmt.indexOf("0"));if((r=fmt.match(dec1))!==null){o=rnd(val,r[1].length).replace(/^([^\.]+)$/,"$1."+r[1]).replace(/\.$/,"."+r[1]).replace(/\.(\d*)$/,function($$,$1){return"."+$1+fill("0",r[1].length-$1.length)});return fmt.indexOf("0.")!==-1?o:o.replace(/^0\./,".")}fmt=fmt.replace(/^#+([0.])/,"$1");if((r=fmt.match(/^(0*)\.(#*)$/))!==null){return sign+rnd(aval,r[2].length).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,r[1].length?"0.":".")}if((r=fmt.match(/^#,##0(\.?)$/))!==null)return sign+commaify(pad0r(aval,0));if((r=fmt.match(/^#,##0\.([#0]*0)$/))!==null){return val<0?"-"+write_num_flt(type,fmt,-val):commaify(""+Math.floor(val))+"."+pad0(dec(val,r[1].length),r[1].length)}if((r=fmt.match(/^#,#*,#0/))!==null)return write_num_flt(type,fmt.replace(/^#,#*,/,""),val);if((r=fmt.match(/^([0#]+)(\\?-([0#]+))+$/))!==null){o=_strrev(write_num_flt(type,fmt.replace(/[\\-]/g,""),val));ri=0;return _strrev(_strrev(fmt.replace(/\\/g,"")).replace(/[0#]/g,function(x){return ri<o.length?o[ri++]:x==="0"?"0":""}))}if(fmt.match(phone)!==null){o=write_num_flt(type,"##########",val);return"("+o.substr(0,3)+") "+o.substr(3,3)+"-"+o.substr(6)}var oa="";if((r=fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/))!==null){ri=Math.min(r[4].length,7);ff=frac(aval,Math.pow(10,ri)-1,false);o=""+sign;oa=write_num("n",r[1],ff[1]);if(oa[oa.length-1]==" ")oa=oa.substr(0,oa.length-1)+"0";o+=oa+r[2]+"/"+r[3];oa=rpad_(ff[2],ri);if(oa.length<r[4].length)oa=hashq(r[4].substr(r[4].length-oa.length))+oa;o+=oa;return o}if((r=fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/))!==null){ri=Math.min(Math.max(r[1].length,r[4].length),7);ff=frac(aval,Math.pow(10,ri)-1,true);return sign+(ff[0]||(ff[1]?"":"0"))+" "+(ff[1]?pad_(ff[1],ri)+r[2]+"/"+r[3]+rpad_(ff[2],ri):fill(" ",2*ri+1+r[2].length+r[3].length))}if((r=fmt.match(/^[#0?]+$/))!==null){o=pad0r(val,0);if(fmt.length<=o.length)return o;return hashq(fmt.substr(0,fmt.length-o.length))+o}if((r=fmt.match(/^([#0?]+)\.([#0]+)$/))!==null){o=""+val.toFixed(Math.min(r[2].length,10)).replace(/([^0])0+$/,"$1");ri=o.indexOf(".");var lres=fmt.indexOf(".")-ri,rres=fmt.length-o.length-lres;return hashq(fmt.substr(0,lres)+o+fmt.substr(fmt.length-rres))}if((r=fmt.match(/^00,000\.([#0]*0)$/))!==null){ri=dec(val,r[1].length);return val<0?"-"+write_num_flt(type,fmt,-val):commaify(flr(val)).replace(/^\d,\d{3}$/,"0$&").replace(/^\d*$/,function($$){return"00,"+($$.length<3?pad0(0,3-$$.length):"")+$$})+"."+pad0(ri,r[1].length)}switch(fmt){case"#,###":var x=commaify(pad0r(aval,0));return x!=="0"?sign+x:"";default:}throw new Error("unsupported format |"+fmt+"|")}function write_num_cm2(type,fmt,val){var idx=fmt.length-1;while(fmt.charCodeAt(idx-1)===44)--idx;return write_num(type,fmt.substr(0,idx),val/Math.pow(10,3*(fmt.length-idx)))}function write_num_pct2(type,fmt,val){var sfmt=fmt.replace(pct1,""),mul=fmt.length-sfmt.length;return write_num(type,sfmt,val*Math.pow(10,2*mul))+fill("%",mul)}function write_num_exp2(fmt,val){var o;var idx=fmt.indexOf("E")-fmt.indexOf(".")-1;if(fmt.match(/^#+0.0E\+0$/)){var period=fmt.indexOf(".");if(period===-1)period=fmt.indexOf("E");var ee=Math.floor(Math.log(Math.abs(val))*Math.LOG10E)%period;if(ee<0)ee+=period;o=(val/Math.pow(10,ee)).toPrecision(idx+1+(period+ee)%period);if(!o.match(/[Ee]/)){var fakee=Math.floor(Math.log(Math.abs(val))*Math.LOG10E);if(o.indexOf(".")===-1)o=o[0]+"."+o.substr(1)+"E+"+(fakee-o.length+ee);else o+="E+"+(fakee-ee);o=o.replace(/\+-/,"-")}o=o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function($$,$1,$2,$3){return $1+$2+$3.substr(0,(period+ee)%period)+"."+$3.substr(ee)+"E"})}else o=val.toExponential(idx);if(fmt.match(/E\+00$/)&&o.match(/e[+-]\d$/))o=o.substr(0,o.length-1)+"0"+o[o.length-1];if(fmt.match(/E\-/)&&o.match(/e\+/))o=o.replace(/e\+/,"e");return o.replace("e","E")}function write_num_int(type,fmt,val){if(type.charCodeAt(0)===40&&!fmt.match(closeparen)){var ffmt=fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");if(val>=0)return write_num_int("n",ffmt,val);return"("+write_num_int("n",ffmt,-val)+")"}if(fmt.charCodeAt(fmt.length-1)===44)return write_num_cm2(type,fmt,val);if(fmt.indexOf("%")!==-1)return write_num_pct2(type,fmt,val);if(fmt.indexOf("E")!==-1)return write_num_exp2(fmt,val);if(fmt.charCodeAt(0)===36)return"$"+write_num_int(type,fmt.substr(fmt[1]==" "?2:1),val);var o;var r,ri,ff,aval=Math.abs(val),sign=val<0?"-":"";if(fmt.match(/^00+$/))return sign+pad0(aval,fmt.length);if(fmt.match(/^[#?]+$/)){o=""+val;if(val===0)o="";return o.length>fmt.length?o:hashq(fmt.substr(0,fmt.length-o.length))+o}if((r=fmt.match(frac1))!==null)return write_num_f2(r,aval,sign);if(fmt.match(/^#+0+$/)!==null)return sign+pad0(aval,fmt.length-fmt.indexOf("0"));if((r=fmt.match(dec1))!==null){o=(""+val).replace(/^([^\.]+)$/,"$1."+r[1]).replace(/\.$/,"."+r[1]).replace(/\.(\d*)$/,function($$,$1){return"."+$1+fill("0",r[1].length-$1.length)});return fmt.indexOf("0.")!==-1?o:o.replace(/^0\./,".")}fmt=fmt.replace(/^#+([0.])/,"$1");if((r=fmt.match(/^(0*)\.(#*)$/))!==null){return sign+(""+aval).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,r[1].length?"0.":".")}if((r=fmt.match(/^#,##0(\.?)$/))!==null)return sign+commaify(""+aval);if((r=fmt.match(/^#,##0\.([#0]*0)$/))!==null){return val<0?"-"+write_num_int(type,fmt,-val):commaify(""+val)+"."+fill("0",r[1].length)}if((r=fmt.match(/^#,#*,#0/))!==null)return write_num_int(type,fmt.replace(/^#,#*,/,""),val);if((r=fmt.match(/^([0#]+)(\\?-([0#]+))+$/))!==null){o=_strrev(write_num_int(type,fmt.replace(/[\\-]/g,""),val));ri=0;return _strrev(_strrev(fmt.replace(/\\/g,"")).replace(/[0#]/g,function(x){return ri<o.length?o[ri++]:x==="0"?"0":""}))}if(fmt.match(phone)!==null){o=write_num_int(type,"##########",val);return"("+o.substr(0,3)+") "+o.substr(3,3)+"-"+o.substr(6)}var oa="";if((r=fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/))!==null){ri=Math.min(r[4].length,7);ff=frac(aval,Math.pow(10,ri)-1,false);o=""+sign;oa=write_num("n",r[1],ff[1]);if(oa[oa.length-1]==" ")oa=oa.substr(0,oa.length-1)+"0";o+=oa+r[2]+"/"+r[3];oa=rpad_(ff[2],ri);if(oa.length<r[4].length)oa=hashq(r[4].substr(r[4].length-oa.length))+oa;o+=oa;return o}if((r=fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/))!==null){ri=Math.min(Math.max(r[1].length,r[4].length),7);ff=frac(aval,Math.pow(10,ri)-1,true);return sign+(ff[0]||(ff[1]?"":"0"))+" "+(ff[1]?pad_(ff[1],ri)+r[2]+"/"+r[3]+rpad_(ff[2],ri):fill(" ",2*ri+1+r[2].length+r[3].length))}if((r=fmt.match(/^[#0?]+$/))!==null){o=""+val;if(fmt.length<=o.length)return o;return hashq(fmt.substr(0,fmt.length-o.length))+o}if((r=fmt.match(/^([#0]+)\.([#0]+)$/))!==null){o=""+val.toFixed(Math.min(r[2].length,10)).replace(/([^0])0+$/,"$1");ri=o.indexOf(".");var lres=fmt.indexOf(".")-ri,rres=fmt.length-o.length-lres;return hashq(fmt.substr(0,lres)+o+fmt.substr(fmt.length-rres))}if((r=fmt.match(/^00,000\.([#0]*0)$/))!==null){return val<0?"-"+write_num_int(type,fmt,-val):commaify(""+val).replace(/^\d,\d{3}$/,"0$&").replace(/^\d*$/,function($$){return"00,"+($$.length<3?pad0(0,3-$$.length):"")+$$})+"."+pad0(0,r[1].length)}switch(fmt){case"#,###":var x=commaify(""+aval);return x!=="0"?sign+x:"";default:}throw new Error("unsupported format |"+fmt+"|")}return function write_num(type,fmt,val){return(val|0)===val?write_num_int(type,fmt,val):write_num_flt(type,fmt,val)}}();function split_fmt(fmt){var out=[];var in_str=false,cc;for(var i=0,j=0;i<fmt.length;++i)switch(cc=fmt.charCodeAt(i)){case 34:in_str=!in_str;break;case 95:case 42:case 92:++i;break;case 59:out[out.length]=fmt.substr(j,i-j);j=i+1}out[out.length]=fmt.substr(j);if(in_str===true)throw new Error("Format |"+fmt+"| unterminated string ");return out}SSF._split=split_fmt;var abstime=/\[[HhMmSs]*\]/;function eval_fmt(fmt,v,opts,flen){var out=[],o="",i=0,c="",lst="t",q,dt,j,cc;var hr="H";while(i<fmt.length){switch(c=fmt[i]){case"G":if(!isgeneral(fmt,i))throw new Error("unrecognized character "+c+" in "+fmt);out[out.length]={t:"G",v:"General"};i+=7;break;case'"':for(o="";(cc=fmt.charCodeAt(++i))!==34&&i<fmt.length;)o+=String.fromCharCode(cc);out[out.length]={t:"t",v:o};++i;break;case"\\":var w=fmt[++i],t=w==="("||w===")"?w:"t";out[out.length]={t:t,v:w};++i;break;case"_":out[out.length]={t:"t",v:" "};i+=2;break;case"@":out[out.length]={t:"T",v:v};++i;break;case"B":case"b":if(fmt[i+1]==="1"||fmt[i+1]==="2"){if(dt==null){dt=parse_date_code(v,opts,fmt[i+1]==="2");if(dt==null)return""}out[out.length]={t:"X",v:fmt.substr(i,2)};lst=c;i+=2;break}case"M":case"D":case"Y":case"H":case"S":case"E":c=c.toLowerCase();case"m":case"d":case"y":case"h":case"s":case"e":case"g":if(v<0)return"";if(dt==null){dt=parse_date_code(v,opts);if(dt==null)return""}o=c;while(++i<fmt.length&&fmt[i].toLowerCase()===c)o+=c;if(c==="m"&&lst.toLowerCase()==="h")c="M";if(c==="h")c=hr;out[out.length]={t:c,v:o};lst=c;break;case"A":q={t:c,v:"A"};if(dt==null)dt=parse_date_code(v,opts);if(fmt.substr(i,3)==="A/P"){if(dt!=null)q.v=dt.H>=12?"P":"A";q.t="T";hr="h";i+=3}else if(fmt.substr(i,5)==="AM/PM"){if(dt!=null)q.v=dt.H>=12?"PM":"AM";q.t="T";i+=5;hr="h"}else{q.t="t";++i}if(dt==null&&q.t==="T")return"";out[out.length]=q;lst=c;break;case"[":o=c;while(fmt[i++]!=="]"&&i<fmt.length)o+=fmt[i];if(o.substr(-1)!=="]")throw'unterminated "[" block: |'+o+"|";if(o.match(abstime)){if(dt==null){dt=parse_date_code(v,opts);if(dt==null)return""}out[out.length]={t:"Z",v:o.toLowerCase()}}else{o=""}break;case".":if(dt!=null){o=c;while((c=fmt[++i])==="0")o+=c;out[out.length]={t:"s",v:o};break}case"0":case"#":o=c;while("0#?.,E+-%".indexOf(c=fmt[++i])>-1||c=="\\"&&fmt[i+1]=="-"&&"0#".indexOf(fmt[i+2])>-1)o+=c;out[out.length]={t:"n",v:o};break;case"?":o=c;while(fmt[++i]===c)o+=c;q={t:c,v:o};out[out.length]=q;lst=c;break;case"*":++i;if(fmt[i]==" "||fmt[i]=="*")++i;break;case"(":case")":out[out.length]={t:flen===1?"t":c,v:c};++i;break;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":o=c;while("0123456789".indexOf(fmt[++i])>-1)o+=fmt[i];out[out.length]={t:"D",v:o};break;case" ":out[out.length]={t:c,v:c};++i;break;default:if(",$-+/():!^&'~{}<>=€acfijklopqrtuvwxz".indexOf(c)===-1)throw new Error("unrecognized character "+c+" in "+fmt);out[out.length]={t:"t",v:c};++i;break}}var bt=0,ss0=0,ssm;for(i=out.length-1,lst="t";i>=0;--i){switch(out[i].t){case"h":case"H":out[i].t=hr;lst="h";if(bt<1)bt=1;break;case"s":if(ssm=out[i].v.match(/\.0+$/))ss0=Math.max(ss0,ssm[0].length-1);if(bt<3)bt=3;case"d":case"y":case"M":case"e":lst=out[i].t;break;case"m":if(lst==="s"){out[i].t="M";if(bt<2)bt=2}break;case"X":if(out[i].v==="B2");break;case"Z":if(bt<1&&out[i].v.match(/[Hh]/))bt=1;if(bt<2&&out[i].v.match(/[Mm]/))bt=2;if(bt<3&&out[i].v.match(/[Ss]/))bt=3}}switch(bt){case 0:break;case 1:if(dt.u>=.5){dt.u=0;++dt.S}if(dt.S>=60){dt.S=0;++dt.M}if(dt.M>=60){dt.M=0;++dt.H}break;case 2:if(dt.u>=.5){dt.u=0;++dt.S}if(dt.S>=60){dt.S=0;++dt.M}break}var nstr="",jj;for(i=0;i<out.length;++i){switch(out[i].t){case"t":case"T":case" ":case"D":break;case"X":out[i]=undefined;break;case"d":case"m":case"y":case"h":case"H":case"M":case"s":case"e":case"b":case"Z":out[i].v=write_date(out[i].t.charCodeAt(0),out[i].v,dt,ss0);out[i].t="t";break;case"n":case"(":case"?":jj=i+1;while(out[jj]!=null&&((c=out[jj].t)==="?"||c==="D"||(c===" "||c==="t")&&out[jj+1]!=null&&(out[jj+1].t==="?"||out[jj+1].t==="t"&&out[jj+1].v==="/")||out[i].t==="("&&(c===" "||c==="n"||c===")")||c==="t"&&(out[jj].v==="/"||"$€".indexOf(out[jj].v)>-1||out[jj].v===" "&&out[jj+1]!=null&&out[jj+1].t=="?"))){out[i].v+=out[jj].v;out[jj]=undefined;++jj}nstr+=out[i].v;i=jj-1;break;case"G":out[i].t="t";out[i].v=general_fmt(v,opts);break}}var vv="",myv,ostr;if(nstr.length>0){myv=v<0&&nstr.charCodeAt(0)===45?-v:v;ostr=write_num(nstr.charCodeAt(0)===40?"(":"n",nstr,myv);jj=ostr.length-1;var decpt=out.length;for(i=0;i<out.length;++i)if(out[i]!=null&&out[i].v.indexOf(".")>-1){decpt=i;break}var lasti=out.length;if(decpt===out.length&&ostr.indexOf("E")===-1){for(i=out.length-1;i>=0;--i){if(out[i]==null||"n?(".indexOf(out[i].t)===-1)continue;if(jj>=out[i].v.length-1){jj-=out[i].v.length;out[i].v=ostr.substr(jj+1,out[i].v.length)}else if(jj<0)out[i].v="";else{out[i].v=ostr.substr(0,jj+1);jj=-1}out[i].t="t";lasti=i}if(jj>=0&&lasti<out.length)out[lasti].v=ostr.substr(0,jj+1)+out[lasti].v}else if(decpt!==out.length&&ostr.indexOf("E")===-1){jj=ostr.indexOf(".")-1;for(i=decpt;i>=0;--i){if(out[i]==null||"n?(".indexOf(out[i].t)===-1)continue;j=out[i].v.indexOf(".")>-1&&i===decpt?out[i].v.indexOf(".")-1:out[i].v.length-1;vv=out[i].v.substr(j+1);for(;j>=0;--j){if(jj>=0&&(out[i].v[j]==="0"||out[i].v[j]==="#"))vv=ostr[jj--]+vv}out[i].v=vv;out[i].t="t";lasti=i}if(jj>=0&&lasti<out.length)out[lasti].v=ostr.substr(0,jj+1)+out[lasti].v;jj=ostr.indexOf(".")+1;for(i=decpt;i<out.length;++i){if(out[i]==null||"n?(".indexOf(out[i].t)===-1&&i!==decpt)continue;j=out[i].v.indexOf(".")>-1&&i===decpt?out[i].v.indexOf(".")+1:0;vv=out[i].v.substr(0,j);for(;j<out[i].v.length;++j){if(jj<ostr.length)vv+=ostr[jj++]}out[i].v=vv;out[i].t="t";lasti=i}}}for(i=0;i<out.length;++i)if(out[i]!=null&&"n(?".indexOf(out[i].t)>-1){myv=flen>1&&v<0&&i>0&&out[i-1].v==="-"?-v:v;out[i].v=write_num(out[i].t,out[i].v,myv);out[i].t="t"}var retval="";for(i=0;i!==out.length;++i)if(out[i]!=null)retval+=out[i].v;return retval}SSF._eval=eval_fmt;var cfregex=/\[[=<>]/;var cfregex2=/\[([=<>]*)(-?\d+\.?\d*)\]/;function chkcond(v,rr){if(rr==null)return false;var thresh=parseFloat(rr[2]);switch(rr[1]){case"=":if(v==thresh)return true;break;case">":if(v>thresh)return true;break;case"<":if(v<thresh)return true;break;case"<>":if(v!=thresh)return true;break;case">=":if(v>=thresh)return true;break;case"<=":if(v<=thresh)return true;break}return false}function choose_fmt(f,v){var fmt=split_fmt(f);var l=fmt.length,lat=fmt[l-1].indexOf("@");if(l<4&&lat>-1)--l;if(fmt.length>4)throw"cannot find right format for |"+fmt+"|";if(typeof v!=="number")return[4,fmt.length===4||lat>-1?fmt[fmt.length-1]:"@"];switch(fmt.length){case 1:fmt=lat>-1?["General","General","General",fmt[0]]:[fmt[0],fmt[0],fmt[0],"@"];break;case 2:fmt=lat>-1?[fmt[0],fmt[0],fmt[0],fmt[1]]:[fmt[0],fmt[1],fmt[0],"@"];break;case 3:fmt=lat>-1?[fmt[0],fmt[1],fmt[0],fmt[2]]:[fmt[0],fmt[1],fmt[2],"@"];break;case 4:break}var ff=v>0?fmt[0]:v<0?fmt[1]:fmt[2];if(fmt[0].indexOf("[")===-1&&fmt[1].indexOf("[")===-1)return[l,ff];if(fmt[0].match(cfregex)!=null||fmt[1].match(cfregex)!=null){var m1=fmt[0].match(cfregex2);var m2=fmt[1].match(cfregex2);return chkcond(v,m1)?[l,fmt[0]]:chkcond(v,m2)?[l,fmt[1]]:[l,fmt[m1!=null&&m2!=null?2:1]]}return[l,ff]}function format(fmt,v,o){fixopts(o!=null?o:o=[]);var sfmt="";switch(typeof fmt){case"string":sfmt=fmt;break;case"number":sfmt=(o.table!=null?o.table:table_fmt)[fmt];break}if(isgeneral(sfmt,0))return general_fmt(v,o);var f=choose_fmt(sfmt,v);if(isgeneral(f[1]))return general_fmt(v,o);if(v===true)v="TRUE";else if(v===false)v="FALSE";else if(v===""||v==null)return"";return eval_fmt(f[1],v,o,f[0])}SSF._table=table_fmt;SSF.load=function load_entry(fmt,idx){table_fmt[idx]=fmt};SSF.format=format;SSF.get_table=function get_table(){return table_fmt};SSF.load_table=function load_table(tbl){for(var i=0;i!=392;++i)if(tbl[i]!==undefined)SSF.load(tbl[i],i)}};make_ssf(SSF);{var VT_EMPTY=0;var VT_NULL=1;var VT_I2=2;var VT_I4=3;var VT_R4=4;var VT_R8=5;var VT_CY=6;var VT_DATE=7;var VT_BSTR=8;var VT_ERROR=10;var VT_BOOL=11;var VT_VARIANT=12;var VT_DECIMAL=14;var VT_I1=16;var VT_UI1=17;var VT_UI2=18;var VT_UI4=19;var VT_I8=20;var VT_UI8=21;var VT_INT=22;var VT_UINT=23;var VT_LPSTR=30;var VT_LPWSTR=31;var VT_FILETIME=64;var VT_BLOB=65;var VT_STREAM=66;var VT_STORAGE=67;var VT_STREAMED_Object=68;
25798 var VT_STORED_Object=69;var VT_BLOB_Object=70;var VT_CF=71;var VT_CLSID=72;var VT_VERSIONED_STREAM=73;var VT_VECTOR=4096;var VT_ARRAY=8192;var VT_STRING=80;var VT_USTR=81;var VT_CUSTOM=[VT_STRING,VT_USTR]}var DocSummaryPIDDSI={1:{n:"CodePage",t:VT_I2},2:{n:"Category",t:VT_STRING},3:{n:"PresentationFormat",t:VT_STRING},4:{n:"ByteCount",t:VT_I4},5:{n:"LineCount",t:VT_I4},6:{n:"ParagraphCount",t:VT_I4},7:{n:"SlideCount",t:VT_I4},8:{n:"NoteCount",t:VT_I4},9:{n:"HiddenCount",t:VT_I4},10:{n:"MultimediaClipCount",t:VT_I4},11:{n:"Scale",t:VT_BOOL},12:{n:"HeadingPair",t:VT_VECTOR|VT_VARIANT},13:{n:"DocParts",t:VT_VECTOR|VT_LPSTR},14:{n:"Manager",t:VT_STRING},15:{n:"Company",t:VT_STRING},16:{n:"LinksDirty",t:VT_BOOL},17:{n:"CharacterCount",t:VT_I4},19:{n:"SharedDoc",t:VT_BOOL},22:{n:"HLinksChanged",t:VT_BOOL},23:{n:"AppVersion",t:VT_I4,p:"version"},26:{n:"ContentType",t:VT_STRING},27:{n:"ContentStatus",t:VT_STRING},28:{n:"Language",t:VT_STRING},29:{n:"Version",t:VT_STRING},255:{}};var SummaryPIDSI={1:{n:"CodePage",t:VT_I2},2:{n:"Title",t:VT_STRING},3:{n:"Subject",t:VT_STRING},4:{n:"Author",t:VT_STRING},5:{n:"Keywords",t:VT_STRING},6:{n:"Comments",t:VT_STRING},7:{n:"Template",t:VT_STRING},8:{n:"LastAuthor",t:VT_STRING},9:{n:"RevNumber",t:VT_STRING},10:{n:"EditTime",t:VT_FILETIME},11:{n:"LastPrinted",t:VT_FILETIME},12:{n:"CreatedDate",t:VT_FILETIME},13:{n:"ModifiedDate",t:VT_FILETIME},14:{n:"PageCount",t:VT_I4},15:{n:"WordCount",t:VT_I4},16:{n:"CharCount",t:VT_I4},17:{n:"Thumbnail",t:VT_CF},18:{n:"ApplicationName",t:VT_LPSTR},19:{n:"DocumentSecurity",t:VT_I4},255:{}};var SpecialProperties={2147483648:{n:"Locale",t:VT_UI4},2147483651:{n:"Behavior",t:VT_UI4},1768515945:{}};(function(){for(var y in SpecialProperties)if(SpecialProperties.hasOwnProperty(y))DocSummaryPIDDSI[y]=SummaryPIDSI[y]=SpecialProperties[y]})();function parse_FILETIME(blob){var dwLowDateTime=blob.read_shift(4),dwHighDateTime=blob.read_shift(4);return new Date((dwHighDateTime/1e7*Math.pow(2,32)+dwLowDateTime/1e7-11644473600)*1e3).toISOString().replace(/\.000/,"")}function parse_lpstr(blob,type,pad){var str=blob.read_shift(0,"lpstr");if(pad)blob.l+=4-(str.length+1&3)&3;return str}function parse_lpwstr(blob,type,pad){var str=blob.read_shift(0,"lpwstr");if(pad)blob.l+=4-(str.length+1&3)&3;return str}function parse_VtStringBase(blob,stringType,pad){if(stringType===31)return parse_lpwstr(blob);return parse_lpstr(blob,stringType,pad)}function parse_VtString(blob,t,pad){return parse_VtStringBase(blob,t,pad===false?0:4)}function parse_VtUnalignedString(blob,t){if(!t)throw new Error("dafuq?");return parse_VtStringBase(blob,t,0)}function parse_VtVecUnalignedLpstrValue(blob){var length=blob.read_shift(4);var ret=[];for(var i=0;i!=length;++i)ret[i]=blob.read_shift(0,"lpstr");return ret}function parse_VtVecUnalignedLpstr(blob){return parse_VtVecUnalignedLpstrValue(blob)}function parse_VtHeadingPair(blob){var headingString=parse_TypedPropertyValue(blob,VT_USTR);var headerParts=parse_TypedPropertyValue(blob,VT_I4);return[headingString,headerParts]}function parse_VtVecHeadingPairValue(blob){var cElements=blob.read_shift(4);var out=[];for(var i=0;i!=cElements/2;++i)out.push(parse_VtHeadingPair(blob));return out}function parse_VtVecHeadingPair(blob){return parse_VtVecHeadingPairValue(blob)}function parse_dictionary(blob,CodePage){var cnt=blob.read_shift(4);var dict={};for(var j=0;j!=cnt;++j){var pid=blob.read_shift(4);var len=blob.read_shift(4);dict[pid]=blob.read_shift(len,CodePage===1200?"utf16le":"utf8").replace(chr0,"").replace(chr1,"!")}if(blob.l&3)blob.l=blob.l>>2+1<<2;return dict}function parse_BLOB(blob){var size=blob.read_shift(4);var bytes=blob.slice(blob.l,blob.l+size);if(size&3>0)blob.l+=4-(size&3)&3;return bytes}function parse_ClipboardData(blob){var o={};o.Size=blob.read_shift(4);blob.l+=o.Size;return o}function parse_VtVector(blob,cb){}function parse_TypedPropertyValue(blob,type,_opts){var t=blob.read_shift(2),ret,opts=_opts||{};blob.l+=2;if(type!==VT_VARIANT)if(t!==type&&VT_CUSTOM.indexOf(type)===-1)throw new Error("Expected type "+type+" saw "+t);switch(type===VT_VARIANT?t:type){case 2:ret=blob.read_shift(2,"i");if(!opts.raw)blob.l+=2;return ret;case 3:ret=blob.read_shift(4,"i");return ret;case 11:return blob.read_shift(4)!==0;case 19:ret=blob.read_shift(4);return ret;case 30:return parse_lpstr(blob,t,4).replace(chr0,"");case 31:return parse_lpwstr(blob);case 64:return parse_FILETIME(blob);case 65:return parse_BLOB(blob);case 71:return parse_ClipboardData(blob);case 80:return parse_VtString(blob,t,!opts.raw&&4).replace(chr0,"");case 81:return parse_VtUnalignedString(blob,t,4).replace(chr0,"");case 4108:return parse_VtVecHeadingPair(blob);case 4126:return parse_VtVecUnalignedLpstr(blob);default:throw new Error("TypedPropertyValue unrecognized type "+type+" "+t)}}function parse_PropertySet(blob,PIDSI){var start_addr=blob.l;var size=blob.read_shift(4);var NumProps=blob.read_shift(4);var Props=[],i=0;var CodePage=0;var Dictionary=-1,DictObj;for(i=0;i!=NumProps;++i){var PropID=blob.read_shift(4);var Offset=blob.read_shift(4);Props[i]=[PropID,Offset+start_addr]}var PropH={};for(i=0;i!=NumProps;++i){if(blob.l!==Props[i][1]){var fail=true;if(i>0&&PIDSI)switch(PIDSI[Props[i-1][0]].t){case 2:if(blob.l+2===Props[i][1]){blob.l+=2;fail=false}break;case 80:if(blob.l<=Props[i][1]){blob.l=Props[i][1];fail=false}break;case 4108:if(blob.l<=Props[i][1]){blob.l=Props[i][1];fail=false}break}if(!PIDSI&&blob.l<=Props[i][1]){fail=false;blob.l=Props[i][1]}if(fail)throw new Error("Read Error: Expected address "+Props[i][1]+" at "+blob.l+" :"+i)}if(PIDSI){var piddsi=PIDSI[Props[i][0]];PropH[piddsi.n]=parse_TypedPropertyValue(blob,piddsi.t,{raw:true});if(piddsi.p==="version")PropH[piddsi.n]=String(PropH[piddsi.n]>>16)+"."+String(PropH[piddsi.n]&65535);if(piddsi.n=="CodePage")switch(PropH[piddsi.n]){case 0:PropH[piddsi.n]=1252;case 1e4:case 1252:case 874:case 1250:case 1251:case 1253:case 1254:case 1255:case 1256:case 1257:case 1258:case 932:case 936:case 949:case 950:case 1200:case 1201:case 65e3:case-536:case 65001:case-535:set_cp(CodePage=PropH[piddsi.n]);break;default:throw new Error("Unsupported CodePage: "+PropH[piddsi.n])}}else{if(Props[i][0]===1){CodePage=PropH.CodePage=parse_TypedPropertyValue(blob,VT_I2);set_cp(CodePage);if(Dictionary!==-1){var oldpos=blob.l;blob.l=Props[Dictionary][1];DictObj=parse_dictionary(blob,CodePage);blob.l=oldpos}}else if(Props[i][0]===0){if(CodePage===0){Dictionary=i;blob.l=Props[i+1][1];continue}DictObj=parse_dictionary(blob,CodePage)}else{var name=DictObj[Props[i][0]];var val;switch(blob[blob.l]){case 65:blob.l+=4;val=parse_BLOB(blob);break;case 30:blob.l+=4;val=parse_VtString(blob,blob[blob.l-4]);break;case 31:blob.l+=4;val=parse_VtString(blob,blob[blob.l-4]);break;case 3:blob.l+=4;val=blob.read_shift(4,"i");break;case 19:blob.l+=4;val=blob.read_shift(4);break;case 5:blob.l+=4;val=blob.read_shift(8,"f");break;case 11:blob.l+=4;val=parsebool(blob,4);break;case 64:blob.l+=4;val=new Date(parse_FILETIME(blob));break;default:throw new Error("unparsed value: "+blob[blob.l])}PropH[name]=val}}}blob.l=start_addr+size;return PropH}function parse_PropertySetStream(file,PIDSI){var blob=file.content;prep_blob(blob,0);var NumSets,FMTID0,FMTID1,Offset0,Offset1;blob.chk("feff","Byte Order: ");var vers=blob.read_shift(2);var SystemIdentifier=blob.read_shift(4);blob.chk(CFB.utils.consts.HEADER_CLSID,"CLSID: ");NumSets=blob.read_shift(4);if(NumSets!==1&&NumSets!==2)throw"Unrecognized #Sets: "+NumSets;FMTID0=blob.read_shift(16);Offset0=blob.read_shift(4);if(NumSets===1&&Offset0!==blob.l)throw"Length mismatch";else if(NumSets===2){FMTID1=blob.read_shift(16);Offset1=blob.read_shift(4)}var PSet0=parse_PropertySet(blob,PIDSI);var rval={SystemIdentifier:SystemIdentifier};for(var y in PSet0)rval[y]=PSet0[y];rval.FMTID=FMTID0;if(NumSets===1)return rval;if(blob.l!==Offset1)throw"Length mismatch 2: "+blob.l+" !== "+Offset1;var PSet1;try{PSet1=parse_PropertySet(blob,null)}catch(e){}for(y in PSet1)rval[y]=PSet1[y];rval.FMTID=[FMTID0,FMTID1];return rval}var DO_NOT_EXPORT_CFB=true;var CFB=function _CFB(){var exports={};exports.version="0.10.0";function parse(file){var mver=3;var ssz=512;var nmfs=0;var ndfs=0;var dir_start=0;var minifat_start=0;var difat_start=0;var fat_addrs=[];var blob=file.slice(0,512);prep_blob(blob,0);mver=check_get_mver(blob);switch(mver){case 3:ssz=512;break;case 4:ssz=4096;break;default:throw"Major Version: Expected 3 or 4 saw "+mver}if(ssz!==512){blob=file.slice(0,ssz);prep_blob(blob,28)}var header=file.slice(0,ssz);check_shifts(blob,mver);var nds=blob.read_shift(4,"i");if(mver===3&&nds!==0)throw"# Directory Sectors: Expected 0 saw "+nds;blob.l+=4;dir_start=blob.read_shift(4,"i");blob.l+=4;blob.chk("00100000","Mini Stream Cutoff Size: ");minifat_start=blob.read_shift(4,"i");nmfs=blob.read_shift(4,"i");difat_start=blob.read_shift(4,"i");ndfs=blob.read_shift(4,"i");for(var q,j=0;j<109;++j){q=blob.read_shift(4,"i");if(q<0)break;fat_addrs[j]=q}var sectors=sectorify(file,ssz);sleuth_fat(difat_start,ndfs,sectors,ssz,fat_addrs);var sector_list=make_sector_list(sectors,dir_start,fat_addrs,ssz);sector_list[dir_start].name="!Directory";if(nmfs>0&&minifat_start!==ENDOFCHAIN)sector_list[minifat_start].name="!MiniFAT";sector_list[fat_addrs[0]].name="!FAT";var files={},Paths=[],FileIndex=[],FullPaths=[],FullPathDir={};read_directory(dir_start,sector_list,sectors,Paths,nmfs,files,FileIndex);build_full_paths(FileIndex,FullPathDir,FullPaths,Paths);var root_name=Paths.shift();Paths.root=root_name;var find_path=make_find_path(FullPaths,Paths,FileIndex,files,root_name);return{raw:{header:header,sectors:sectors},FileIndex:FileIndex,FullPaths:FullPaths,FullPathDir:FullPathDir,find:find_path}}function check_get_mver(blob){blob.chk(HEADER_SIGNATURE,"Header Signature: ");blob.chk(HEADER_CLSID,"CLSID: ");blob.l+=2;return blob.read_shift(2,"u")}function check_shifts(blob,mver){var shift=9;blob.chk("feff","Byte Order: ");switch(shift=blob.read_shift(2)){case 9:if(mver!==3)throw"MajorVersion/SectorShift Mismatch";break;case 12:if(mver!==4)throw"MajorVersion/SectorShift Mismatch";break;default:throw"Sector Shift: Expected 9 or 12 saw "+shift}blob.chk("0600","Mini Sector Shift: ");blob.chk("000000000000","Reserved: ")}function sectorify(file,ssz){var nsectors=Math.ceil(file.length/ssz)-1;var sectors=new Array(nsectors);for(var i=1;i<nsectors;++i)sectors[i-1]=file.slice(i*ssz,(i+1)*ssz);sectors[nsectors-1]=file.slice(nsectors*ssz);return sectors}function build_full_paths(FI,FPD,FP,Paths){var i=0,L=0,R=0,C=0,j=0,pl=Paths.length;var dad=new Array(pl),q=new Array(pl);for(;i<pl;++i){dad[i]=q[i]=i;FP[i]=Paths[i]}for(;j<q.length;++j){i=q[j];L=FI[i].L;R=FI[i].R;C=FI[i].C;if(dad[i]===i){if(L!==-1&&dad[L]!==L)dad[i]=dad[L];if(R!==-1&&dad[R]!==R)dad[i]=dad[R]}if(C!==-1)dad[C]=i;if(L!==-1){dad[L]=dad[i];q.push(L)}if(R!==-1){dad[R]=dad[i];q.push(R)}}for(i=1;i!==pl;++i)if(dad[i]===i){if(R!==-1&&dad[R]!==R)dad[i]=dad[R];else if(L!==-1&&dad[L]!==L)dad[i]=dad[L]}for(i=1;i<pl;++i){if(FI[i].type===0)continue;j=dad[i];if(j===0)FP[i]=FP[0]+"/"+FP[i];else while(j!==0){FP[i]=FP[j]+"/"+FP[i];j=dad[j]}dad[i]=0}FP[0]+="/";for(i=1;i<pl;++i){if(FI[i].type!==2)FP[i]+="/";FPD[FP[i]]=FI[i]}}function make_find_path(FullPaths,Paths,FileIndex,files,root_name){var UCFullPaths=new Array(FullPaths.length);var UCPaths=new Array(Paths.length),i;for(i=0;i<FullPaths.length;++i)UCFullPaths[i]=FullPaths[i].toUpperCase();for(i=0;i<Paths.length;++i)UCPaths[i]=Paths[i].toUpperCase();return function find_path(path){var k;if(path.charCodeAt(0)===47){k=true;path=root_name+path}else k=path.indexOf("/")!==-1;var UCPath=path.toUpperCase();var w=k===true?UCFullPaths.indexOf(UCPath):UCPaths.indexOf(UCPath);if(w===-1)return null;return k===true?FileIndex[w]:files[Paths[w]]}}function sleuth_fat(idx,cnt,sectors,ssz,fat_addrs){var q;if(idx===ENDOFCHAIN){if(cnt!==0)throw"DIFAT chain shorter than expected"}else if(idx!==-1){var sector=sectors[idx],m=(ssz>>>2)-1;for(var i=0;i<m;++i){if((q=__readInt32LE(sector,i*4))===ENDOFCHAIN)break;fat_addrs.push(q)}sleuth_fat(__readInt32LE(sector,ssz-4),cnt-1,sectors,ssz,fat_addrs)}}function make_sector_list(sectors,dir_start,fat_addrs,ssz){var sl=sectors.length,sector_list=new Array(sl);var chkd=new Array(sl),buf,buf_chain;var modulus=ssz-1,i,j,k,jj;for(i=0;i<sl;++i){buf=[];k=i+dir_start;if(k>=sl)k-=sl;if(chkd[k]===true)continue;buf_chain=[];for(j=k;j>=0;){chkd[j]=true;buf[buf.length]=j;buf_chain.push(sectors[j]);var addr=fat_addrs[Math.floor(j*4/ssz)];jj=j*4&modulus;if(ssz<4+jj)throw"FAT boundary crossed: "+j+" 4 "+ssz;j=__readInt32LE(sectors[addr],jj)}sector_list[k]={nodes:buf,data:__toBuffer([buf_chain])}}return sector_list}function read_directory(dir_start,sector_list,sectors,Paths,nmfs,files,FileIndex){var blob;var minifat_store=0,pl=Paths.length?2:0;var sector=sector_list[dir_start].data;var i=0,namelen=0,name,o,ctime,mtime;for(;i<sector.length;i+=128){blob=sector.slice(i,i+128);prep_blob(blob,64);namelen=blob.read_shift(2);if(namelen===0)continue;name=__utf16le(blob,0,namelen-pl).replace(chr0,"").replace(chr1,"!");Paths.push(name);o={name:name,type:blob.read_shift(1),color:blob.read_shift(1),L:blob.read_shift(4,"i"),R:blob.read_shift(4,"i"),C:blob.read_shift(4,"i"),clsid:blob.read_shift(16),state:blob.read_shift(4,"i")};ctime=blob.read_shift(2)+blob.read_shift(2)+blob.read_shift(2)+blob.read_shift(2);if(ctime!==0){o.ctime=ctime;o.ct=read_date(blob,blob.l-8)}mtime=blob.read_shift(2)+blob.read_shift(2)+blob.read_shift(2)+blob.read_shift(2);if(mtime!==0){o.mtime=mtime;o.mt=read_date(blob,blob.l-8)}o.start=blob.read_shift(4,"i");o.size=blob.read_shift(4,"i");if(o.type===5){minifat_store=o.start;if(nmfs>0&&minifat_store!==ENDOFCHAIN)sector_list[minifat_store].name="!StreamData"}else if(o.size>=4096){o.storage="fat";if(sector_list[o.start]===undefined)if((o.start+=dir_start)>=sectors.length)o.start-=sectors.length;sector_list[o.start].name=o.name;o.content=sector_list[o.start].data.slice(0,o.size);prep_blob(o.content,0)}else{o.storage="minifat";if(minifat_store!==ENDOFCHAIN&&o.start!==ENDOFCHAIN){o.content=sector_list[minifat_store].data.slice(o.start*MSSZ,o.start*MSSZ+o.size);prep_blob(o.content,0)}}files[name]=o;FileIndex.push(o)}}function read_date(blob,offset){return new Date((__readUInt32LE(blob,offset+4)/1e7*Math.pow(2,32)+__readUInt32LE(blob,offset)/1e7-11644473600)*1e3)}var fs;function readFileSync(filename){if(fs===undefined)fs=require("fs");return parse(fs.readFileSync(filename))}function readSync(blob,options){switch(options!==undefined&&options.type!==undefined?options.type:"base64"){case"file":return readFileSync(blob);case"base64":return parse(s2a(Base64.decode(blob)));case"binary":return parse(s2a(blob))}return parse(blob)}var MSSZ=64;var ENDOFCHAIN=-2;var HEADER_SIGNATURE="d0cf11e0a1b11ae1";var HEADER_CLSID="00000000000000000000000000000000";var consts={MAXREGSECT:-6,DIFSECT:-4,FATSECT:-3,ENDOFCHAIN:ENDOFCHAIN,FREESECT:-1,HEADER_SIGNATURE:HEADER_SIGNATURE,HEADER_MINOR_VERSION:"3e00",MAXREGSID:-6,NOSTREAM:-1,HEADER_CLSID:HEADER_CLSID,EntryTypes:["unknown","storage","stream","lockbytes","property","root"]};exports.read=readSync;exports.parse=parse;exports.utils={ReadShift:ReadShift,CheckField:CheckField,prep_blob:prep_blob,bconcat:bconcat,consts:consts};return exports}();if(typeof require!=="undefined"&&typeof module!=="undefined"&&typeof DO_NOT_EXPORT_CFB==="undefined"){module.exports=CFB}function parsenoop(blob,length){blob.read_shift(length);return}function parsenoop2(blob,length){blob.read_shift(length);return null}function parslurp(blob,length,cb){var arr=[],target=blob.l+length;while(blob.l<target)arr.push(cb(blob,target-blob.l));if(target!==blob.l)throw new Error("Slurp error");return arr}function parslurp2(blob,length,cb){var arr=[],target=blob.l+length,len=blob.read_shift(2);while(len--!==0)arr.push(cb(blob,target-blob.l));if(target!==blob.l)throw new Error("Slurp error");return arr}function parsebool(blob,length){return blob.read_shift(length)===1}function parseuint16(blob){return blob.read_shift(2,"u")}function parseuint16a(blob,length){return parslurp(blob,length,parseuint16)}var parse_Boolean=parsebool;function parse_Bes(blob){var v=blob.read_shift(1),t=blob.read_shift(1);return t===1?BERR[v]:v===1}function parse_ShortXLUnicodeString(blob,length,opts){var cch=blob.read_shift(1);var width=1,encoding="sbcs";if(opts===undefined||opts.biff!==5){var fHighByte=blob.read_shift(1);if(fHighByte){width=2;encoding="dbcs"}}return cch?blob.read_shift(cch,encoding):""}function parse_XLUnicodeRichExtendedString(blob){var cch=blob.read_shift(2),flags=blob.read_shift(1);var fHighByte=flags&1,fExtSt=flags&4,fRichSt=flags&8;var width=1+(flags&1);var cRun,cbExtRst;var z={};if(fRichSt)cRun=blob.read_shift(2);if(fExtSt)cbExtRst=blob.read_shift(4);var encoding=flags&1?"dbcs":"sbcs";var msg=cch===0?"":blob.read_shift(cch,encoding);if(fRichSt)blob.l+=4*cRun;if(fExtSt)blob.l+=cbExtRst;z.t=msg;if(!fRichSt){z.raw="<t>"+z.t+"</t>";z.r=z.t}return z}function parse_XLUnicodeStringNoCch(blob,cch,opts){var retval;var fHighByte=blob.read_shift(1);if(fHighByte===0){retval=blob.read_shift(cch,"sbcs")}else{retval=blob.read_shift(cch,"dbcs")}return retval}function parse_XLUnicodeString(blob,length,opts){var cch=blob.read_shift(opts!==undefined&&opts.biff===5?1:2);if(cch===0){blob.l++;return""}return parse_XLUnicodeStringNoCch(blob,cch,opts)}function parse_XLUnicodeString2(blob,length,opts){if(opts.biff!==5)return parse_XLUnicodeString(blob,length,opts);var cch=blob.read_shift(1);if(cch===0){blob.l++;return""}return blob.read_shift(cch,"sbcs")}function parse_Xnum(blob){return blob.read_shift(8,"f")}var parse_ControlInfo=parsenoop;var parse_URLMoniker=function(blob,length){var len=blob.read_shift(4),start=blob.l;var extra=false;if(len>24){blob.l+=len-24;if(blob.read_shift(16)==="795881f43b1d7f48af2c825dc4852763")extra=true;blob.l=start}var url=blob.read_shift((extra?len-24:len)>>1,"utf16le").replace(chr0,"");if(extra)blob.l+=24;return url};var parse_FileMoniker=function(blob,length){var cAnti=blob.read_shift(2);var ansiLength=blob.read_shift(4);var ansiPath=blob.read_shift(ansiLength,"cstr");var endServer=blob.read_shift(2);var versionNumber=blob.read_shift(2);var cbUnicodePathSize=blob.read_shift(4);if(cbUnicodePathSize===0)return ansiPath.replace(/\\/g,"/");var cbUnicodePathBytes=blob.read_shift(4);var usKeyValue=blob.read_shift(2);var unicodePath=blob.read_shift(cbUnicodePathBytes>>1,"utf16le").replace(chr0,"");return unicodePath};var parse_HyperlinkMoniker=function(blob,length){var clsid=blob.read_shift(16);length-=16;switch(clsid){case"e0c9ea79f9bace118c8200aa004ba90b":return parse_URLMoniker(blob,length);case"0303000000000000c000000000000046":return parse_FileMoniker(blob,length);default:throw"unsupported moniker "+clsid}};var parse_HyperlinkString=function(blob,length){var len=blob.read_shift(4);var o=blob.read_shift(len,"utf16le").replace(chr0,"");return o};var parse_Hyperlink=function(blob,length){var end=blob.l+length;var sVer=blob.read_shift(4);if(sVer!==2)throw new Error("Unrecognized streamVersion: "+sVer);var flags=blob.read_shift(2);blob.l+=2;var displayName,targetFrameName,moniker,oleMoniker,location,guid,fileTime;if(flags&16)displayName=parse_HyperlinkString(blob,end-blob.l);if(flags&128)targetFrameName=parse_HyperlinkString(blob,end-blob.l);if((flags&257)===257)moniker=parse_HyperlinkString(blob,end-blob.l);if((flags&257)===1)oleMoniker=parse_HyperlinkMoniker(blob,end-blob.l);if(flags&8)location=parse_HyperlinkString(blob,end-blob.l);if(flags&32)guid=blob.read_shift(16);if(flags&64)fileTime=parse_FILETIME(blob,8);blob.l=end;var target=targetFrameName||moniker||oleMoniker;if(location)target+="#"+location;return{Target:target}};function isval(x){return x!==undefined&&x!==null}function keys(o){return Object.keys(o)}function evert(obj,arr){var o={};var K=keys(obj);for(var i=0;i<K.length;++i){var k=K[i];if(!arr)o[obj[k]]=k;else(o[obj[k]]=o[obj[k]]||[]).push(k)}return o}function parse_Cell(blob,length){var rw=blob.read_shift(2);var col=blob.read_shift(2);var ixfe=blob.read_shift(2);return{r:rw,c:col,ixfe:ixfe}}function parse_frtHeader(blob){var rt=blob.read_shift(2);var flags=blob.read_shift(2);blob.l+=8;return{type:rt,flags:flags}}function parse_OptXLUnicodeString(blob,length,opts){return length===0?"":parse_XLUnicodeString2(blob,length,opts)}var HIDEOBJENUM=["SHOWALL","SHOWPLACEHOLDER","HIDEALL"];var parse_HideObjEnum=parseuint16;function parse_XTI(blob,length){var iSupBook=blob.read_shift(2),itabFirst=blob.read_shift(2,"i"),itabLast=blob.read_shift(2,"i");return[iSupBook,itabFirst,itabLast]}function parse_RkNumber(blob){var b=blob.slice(blob.l,blob.l+4);var fX100=b[0]&1,fInt=b[0]&2;blob.l+=4;b[0]&=~3;var RK=fInt===0?__double([0,0,0,0,b[0],b[1],b[2],b[3]],0):__readInt32LE(b,0)>>2;return fX100?RK/100:RK}function parse_RkRec(blob,length){var ixfe=blob.read_shift(2);var RK=parse_RkNumber(blob);return[ixfe,RK]}function parse_AddinUdf(blob,length){blob.l+=4;length-=4;var l=blob.l+length;var udfName=parse_ShortXLUnicodeString(blob,length);var cb=blob.read_shift(2);l-=blob.l;if(cb!==l)throw"Malformed AddinUdf: padding = "+l+" != "+cb;blob.l+=cb;return udfName}function parse_Ref8U(blob,length){var rwFirst=blob.read_shift(2);var rwLast=blob.read_shift(2);var colFirst=blob.read_shift(2);var colLast=blob.read_shift(2);return{s:{c:colFirst,r:rwFirst},e:{c:colLast,r:rwLast}}}function parse_RefU(blob,length){var rwFirst=blob.read_shift(2);var rwLast=blob.read_shift(2);var colFirst=blob.read_shift(1);var colLast=blob.read_shift(1);return{s:{c:colFirst,r:rwFirst},e:{c:colLast,r:rwLast}}}var parse_Ref=parse_RefU;function parse_FtCmo(blob,length){blob.l+=4;var ot=blob.read_shift(2);var id=blob.read_shift(2);var flags=blob.read_shift(2);blob.l+=12;return[id,ot,flags]}function parse_FtNts(blob,length){var out={};blob.l+=4;blob.l+=16;out.fSharedNote=blob.read_shift(2);blob.l+=4;return out}function parse_FtCf(blob,length){var out={};blob.l+=4;blob.cf=blob.read_shift(2);return out}var FtTab={21:parse_FtCmo,19:parsenoop,18:function(blob,length){blob.l+=12},17:function(blob,length){blob.l+=8},16:parsenoop,15:parsenoop,13:parse_FtNts,12:function(blob,length){blob.l+=24},11:function(blob,length){blob.l+=10},10:function(blob,length){blob.l+=16},9:parsenoop,8:function(blob,length){blob.l+=6},7:parse_FtCf,6:function(blob,length){blob.l+=6},4:parsenoop,0:function(blob,length){blob.l+=4}};function parse_FtArray(blob,length,ot){var s=blob.l;var fts=[];while(blob.l<s+length){var ft=blob.read_shift(2);blob.l-=2;try{fts.push(FtTab[ft](blob,s+length-blob.l))}catch(e){blob.l=s+length;return fts}}if(blob.l!=s+length)blob.l=s+length;return fts}var parse_FontIndex=parseuint16;function parse_BOF(blob,length){var o={};o.BIFFVer=blob.read_shift(2);length-=2;if(o.BIFFVer!==1536&&o.BIFFVer!==1280)throw"Unexpected BIFF Ver "+o.BIFFVer;blob.read_shift(length);return o}function parse_InterfaceHdr(blob,length){if(length===0)return 1200;var q;if((q=blob.read_shift(2))!==1200)throw"InterfaceHdr codePage "+q;return 1200}function parse_WriteAccess(blob,length,opts){if(opts.enc){blob.l+=length;return""}var l=blob.l;var UserName=parse_XLUnicodeString(blob,0,opts);blob.read_shift(length+l-blob.l);return UserName}function parse_BoundSheet8(blob,length,opts){var pos=blob.read_shift(4);var hidden=blob.read_shift(1)>>6;var dt=blob.read_shift(1);switch(dt){case 0:dt="Worksheet";break;case 1:dt="Macrosheet";break;case 2:dt="Chartsheet";break;case 6:dt="VBAModule";break}var name=parse_ShortXLUnicodeString(blob,0,opts);return{pos:pos,hs:hidden,dt:dt,name:name}}function parse_SST(blob,length){var cnt=blob.read_shift(4);var ucnt=blob.read_shift(4);var strs=[];for(var i=0;i!=ucnt;++i){strs.push(parse_XLUnicodeRichExtendedString(blob))}strs.Count=cnt;strs.Unique=ucnt;return strs}function parse_ExtSST(blob,length){var extsst={};extsst.dsst=blob.read_shift(2);blob.l+=length-2;return extsst}function parse_Row(blob,length){var rw=blob.read_shift(2),col=blob.read_shift(2),Col=blob.read_shift(2),rht=blob.read_shift(2);blob.read_shift(4);var flags=blob.read_shift(1);blob.read_shift(1);blob.read_shift(2);return{r:rw,c:col,cnt:Col-col}}function parse_ForceFullCalculation(blob,length){var header=parse_frtHeader(blob);if(header.type!=2211)throw"Invalid Future Record "+header.type;var fullcalc=blob.read_shift(4);return fullcalc!==0}var parse_CompressPictures=parsenoop2;function parse_RecalcId(blob,length){blob.read_shift(2);return blob.read_shift(4)}function parse_DefaultRowHeight(blob,length){var f=blob.read_shift(2),miyRw;miyRw=blob.read_shift(2);var fl={Unsynced:f&1,DyZero:(f&2)>>1,ExAsc:(f&4)>>2,ExDsc:(f&8)>>3};return[fl,miyRw]}function parse_Window1(blob,length){var xWn=blob.read_shift(2),yWn=blob.read_shift(2),dxWn=blob.read_shift(2),dyWn=blob.read_shift(2);var flags=blob.read_shift(2),iTabCur=blob.read_shift(2),iTabFirst=blob.read_shift(2);var ctabSel=blob.read_shift(2),wTabRatio=blob.read_shift(2);return{Pos:[xWn,yWn],Dim:[dxWn,dyWn],Flags:flags,CurTab:iTabCur,FirstTab:iTabFirst,Selected:ctabSel,TabRatio:wTabRatio}}function parse_Font(blob,length,opts){blob.l+=14;var name=parse_ShortXLUnicodeString(blob,0,opts);return name}function parse_LabelSst(blob,length){var cell=parse_Cell(blob);cell.isst=blob.read_shift(4);return cell}function parse_Label(blob,length,opts){var cell=parse_Cell(blob,6);var str=parse_XLUnicodeString(blob,length-6,opts);cell.val=str;return cell}function parse_Format(blob,length,opts){var ifmt=blob.read_shift(2);var fmtstr=parse_XLUnicodeString2(blob,0,opts);return[ifmt,fmtstr]}function parse_Dimensions(blob,length){var w=length===10?2:4;var r=blob.read_shift(w),R=blob.read_shift(w),c=blob.read_shift(2),C=blob.read_shift(2);blob.l+=2;return{s:{r:r,c:c},e:{r:R,c:C}}}function parse_RK(blob,length){var rw=blob.read_shift(2),col=blob.read_shift(2);var rkrec=parse_RkRec(blob);return{r:rw,c:col,ixfe:rkrec[0],rknum:rkrec[1]}}function parse_MulRk(blob,length){var target=blob.l+length-2;var rw=blob.read_shift(2),col=blob.read_shift(2);var rkrecs=[];while(blob.l<target)rkrecs.push(parse_RkRec(blob));if(blob.l!==target)throw"MulRK read error";var lastcol=blob.read_shift(2);if(rkrecs.length!=lastcol-col+1)throw"MulRK length mismatch";return{r:rw,c:col,C:lastcol,rkrec:rkrecs}}var parse_CellXF=parsenoop;var parse_StyleXF=parsenoop;function parse_XF(blob,length){var o={};o.ifnt=blob.read_shift(2);o.ifmt=blob.read_shift(2);o.flags=blob.read_shift(2);o.fStyle=o.flags>>2&1;length-=6;o.data=o.fStyle?parse_StyleXF(blob,length):parse_CellXF(blob,length);return o}function parse_Guts(blob,length){blob.l+=4;var out=[blob.read_shift(2),blob.read_shift(2)];if(out[0]!==0)out[0]--;if(out[1]!==0)out[1]--;if(out[0]>7||out[1]>7)throw"Bad Gutters: "+out;return out}function parse_BoolErr(blob,length){var cell=parse_Cell(blob,6);var val=parse_Bes(blob,2);cell.val=val;cell.t=val===true||val===false?"b":"e";return cell}function parse_Number(blob,length){var cell=parse_Cell(blob,6);var xnum=parse_Xnum(blob,8);cell.val=xnum;return cell}var parse_XLHeaderFooter=parse_OptXLUnicodeString;function parse_SupBook(blob,length,opts){var end=blob.l+length;var ctab=blob.read_shift(2);var cch=blob.read_shift(2);var virtPath;if(cch>=1&&cch<=255)virtPath=parse_XLUnicodeStringNoCch(blob,cch);var rgst=blob.read_shift(end-blob.l);opts.sbcch=cch;return[cch,ctab,virtPath,rgst]}function parse_ExternName(blob,length,opts){var flags=blob.read_shift(2);var body;var o={fBuiltIn:flags&1,fWantAdvise:flags>>>1&1,fWantPict:flags>>>2&1,fOle:flags>>>3&1,fOleLink:flags>>>4&1,cf:flags>>>5&1023,fIcon:flags>>>15&1};if(opts.sbcch===14849)body=parse_AddinUdf(blob,length-2);o.body=body||blob.read_shift(length-2);return o}function parse_Lbl(blob,length,opts){if(opts.biff<8)return parse_Label(blob,length,opts);var target=blob.l+length;var flags=blob.read_shift(2);var chKey=blob.read_shift(1);var cch=blob.read_shift(1);var cce=blob.read_shift(2);blob.l+=2;var itab=blob.read_shift(2);blob.l+=4;var name=parse_XLUnicodeStringNoCch(blob,cch,opts);var rgce=parse_NameParsedFormula(blob,target-blob.l,opts,cce);return{chKey:chKey,Name:name,rgce:rgce}}function parse_ExternSheet(blob,length,opts){if(opts.biff<8)return parse_ShortXLUnicodeString(blob,length,opts);var o=parslurp2(blob,length,parse_XTI);var oo=[];if(opts.sbcch===1025){for(var i=0;i!=o.length;++i)oo.push(opts.snames[o[i][1]]);return oo}else return o}function parse_ShrFmla(blob,length,opts){var ref=parse_RefU(blob,6);blob.l++;var cUse=blob.read_shift(1);length-=8;return[parse_SharedParsedFormula(blob,length,opts),cUse]}function parse_Array(blob,length,opts){var ref=parse_Ref(blob,6);blob.l+=6;length-=12;return[ref,parse_ArrayParsedFormula(blob,length,opts,ref)]}function parse_MTRSettings(blob,length){var fMTREnabled=blob.read_shift(4)!==0;var fUserSetThreadCount=blob.read_shift(4)!==0;var cUserThreadCount=blob.read_shift(4);return[fMTREnabled,fUserSetThreadCount,cUserThreadCount]}function parse_NoteSh(blob,length,opts){if(opts.biff<8)return;var row=blob.read_shift(2),col=blob.read_shift(2);var flags=blob.read_shift(2),idObj=blob.read_shift(2);var stAuthor=parse_XLUnicodeString2(blob,0,opts);if(opts.biff<8)blob.read_shift(1);return[{r:row,c:col},stAuthor,idObj,flags]}function parse_Note(blob,length,opts){return parse_NoteSh(blob,length,opts)}function parse_MergeCells(blob,length){var merges=[];var cmcs=blob.read_shift(2);while(cmcs--)merges.push(parse_Ref8U(blob,length));return merges}function parse_Obj(blob,length){var cmo=parse_FtCmo(blob,22);var fts=parse_FtArray(blob,length-22,cmo[1]);return{cmo:cmo,ft:fts}}function parse_TxO(blob,length,opts){var s=blob.l;try{blob.l+=4;var ot=(opts.lastobj||{cmo:[0,0]}).cmo[1];var controlInfo;if([0,5,7,11,12,14].indexOf(ot)==-1)blob.l+=6;else controlInfo=parse_ControlInfo(blob,6,opts);var cchText=blob.read_shift(2);var cbRuns=blob.read_shift(2);var ifntEmpty=parse_FontIndex(blob,2);var len=blob.read_shift(2);blob.l+=len;var texts="";for(var i=1;i<blob.lens.length-1;++i){if(blob.l-s!=blob.lens[i])throw"TxO: bad continue record";var hdr=blob[blob.l];var t=parse_XLUnicodeStringNoCch(blob,blob.lens[i+1]-blob.lens[i]-1);texts+=t;if(texts.length>=(hdr?cchText:2*cchText))break}if(texts.length!==cchText&&texts.length!==cchText*2){throw"cchText: "+cchText+" != "+texts.length}blob.l=s+length;return{t:texts}}catch(e){blob.l=s+length;return{t:texts||""}}}var parse_HLink=function(blob,length){var ref=parse_Ref8U(blob,8);blob.l+=16;var hlink=parse_Hyperlink(blob,length-24);return[ref,hlink]};var parse_HLinkTooltip=function(blob,length){var end=blob.l+length;blob.read_shift(2);var ref=parse_Ref8U(blob,8);var wzTooltip=blob.read_shift((length-10)/2,"dbcs");wzTooltip=wzTooltip.replace(chr0,"");return[ref,wzTooltip]};function parse_Country(blob,length){var o=[],d;d=blob.read_shift(2);o[0]=CountryEnum[d]||d;d=blob.read_shift(2);o[1]=CountryEnum[d]||d;return o}var parse_Backup=parsebool;var parse_Blank=parse_Cell;var parse_BottomMargin=parse_Xnum;var parse_BuiltInFnGroupCount=parseuint16;var parse_CalcCount=parseuint16;var parse_CalcDelta=parse_Xnum;var parse_CalcIter=parsebool;var parse_CalcMode=parseuint16;var parse_CalcPrecision=parsebool;var parse_CalcRefMode=parsenoop2;var parse_CalcSaveRecalc=parsebool;var parse_CodePage=parseuint16;var parse_Compat12=parsebool;var parse_Date1904=parsebool;var parse_DefColWidth=parseuint16;var parse_DSF=parsenoop2;var parse_EntExU2=parsenoop2;var parse_EOF=parsenoop2;var parse_Excel9File=parsenoop2;var parse_FeatHdr=parsenoop2;var parse_FontX=parseuint16;var parse_Footer=parse_XLHeaderFooter;var parse_GridSet=parseuint16;var parse_HCenter=parsebool;var parse_Header=parse_XLHeaderFooter;var parse_HideObj=parse_HideObjEnum;var parse_InterfaceEnd=parsenoop2;var parse_LeftMargin=parse_Xnum;var parse_Mms=parsenoop2;var parse_ObjProtect=parsebool;var parse_Password=parseuint16;var parse_PrintGrid=parsebool;var parse_PrintRowCol=parsebool;var parse_PrintSize=parseuint16;var parse_Prot4Rev=parsebool;var parse_Prot4RevPass=parseuint16;var parse_Protect=parsebool;var parse_RefreshAll=parsebool;var parse_RightMargin=parse_Xnum;
25799 var parse_RRTabId=parseuint16a;var parse_ScenarioProtect=parsebool;var parse_Scl=parseuint16a;var parse_String=parse_XLUnicodeString;var parse_SxBool=parsebool;var parse_TopMargin=parse_Xnum;var parse_UsesELFs=parsebool;var parse_VCenter=parsebool;var parse_WinProtect=parsebool;var parse_WriteProtect=parsenoop;var parse_VerticalPageBreaks=parsenoop;var parse_HorizontalPageBreaks=parsenoop;var parse_Selection=parsenoop;var parse_Continue=parsenoop;var parse_Pane=parsenoop;var parse_Pls=parsenoop;var parse_DCon=parsenoop;var parse_DConRef=parsenoop;var parse_DConName=parsenoop;var parse_XCT=parsenoop;var parse_CRN=parsenoop;var parse_FileSharing=parsenoop;var parse_Uncalced=parsenoop;var parse_Template=parsenoop;var parse_Intl=parsenoop;var parse_ColInfo=parsenoop;var parse_WsBool=parsenoop;var parse_Sort=parsenoop;var parse_Palette=parsenoop;var parse_Sync=parsenoop;var parse_LPr=parsenoop;var parse_DxGCol=parsenoop;var parse_FnGroupName=parsenoop;var parse_FilterMode=parsenoop;var parse_AutoFilterInfo=parsenoop;var parse_AutoFilter=parsenoop;var parse_Setup=parsenoop;var parse_ScenMan=parsenoop;var parse_SCENARIO=parsenoop;var parse_SxView=parsenoop;var parse_Sxvd=parsenoop;var parse_SXVI=parsenoop;var parse_SxIvd=parsenoop;var parse_SXLI=parsenoop;var parse_SXPI=parsenoop;var parse_DocRoute=parsenoop;var parse_RecipName=parsenoop;var parse_MulBlank=parsenoop;var parse_SXDI=parsenoop;var parse_SXDB=parsenoop;var parse_SXFDB=parsenoop;var parse_SXDBB=parsenoop;var parse_SXNum=parsenoop;var parse_SxErr=parsenoop;var parse_SXInt=parsenoop;var parse_SXString=parsenoop;var parse_SXDtr=parsenoop;var parse_SxNil=parsenoop;var parse_SXTbl=parsenoop;var parse_SXTBRGIITM=parsenoop;var parse_SxTbpg=parsenoop;var parse_ObProj=parsenoop;var parse_SXStreamID=parsenoop;var parse_DBCell=parsenoop;var parse_SXRng=parsenoop;var parse_SxIsxoper=parsenoop;var parse_BookBool=parsenoop;var parse_DbOrParamQry=parsenoop;var parse_OleObjectSize=parsenoop;var parse_SXVS=parsenoop;var parse_BkHim=parsenoop;var parse_MsoDrawingGroup=parsenoop;var parse_MsoDrawing=parsenoop;var parse_MsoDrawingSelection=parsenoop;var parse_PhoneticInfo=parsenoop;var parse_SxRule=parsenoop;var parse_SXEx=parsenoop;var parse_SxFilt=parsenoop;var parse_SxDXF=parsenoop;var parse_SxItm=parsenoop;var parse_SxName=parsenoop;var parse_SxSelect=parsenoop;var parse_SXPair=parsenoop;var parse_SxFmla=parsenoop;var parse_SxFormat=parsenoop;var parse_SXVDEx=parsenoop;var parse_SXFormula=parsenoop;var parse_SXDBEx=parsenoop;var parse_RRDInsDel=parsenoop;var parse_RRDHead=parsenoop;var parse_RRDChgCell=parsenoop;var parse_RRDRenSheet=parsenoop;var parse_RRSort=parsenoop;var parse_RRDMove=parsenoop;var parse_RRFormat=parsenoop;var parse_RRAutoFmt=parsenoop;var parse_RRInsertSh=parsenoop;var parse_RRDMoveBegin=parsenoop;var parse_RRDMoveEnd=parsenoop;var parse_RRDInsDelBegin=parsenoop;var parse_RRDInsDelEnd=parsenoop;var parse_RRDConflict=parsenoop;var parse_RRDDefName=parsenoop;var parse_RRDRstEtxp=parsenoop;var parse_LRng=parsenoop;var parse_CUsr=parsenoop;var parse_CbUsr=parsenoop;var parse_UsrInfo=parsenoop;var parse_UsrExcl=parsenoop;var parse_FileLock=parsenoop;var parse_RRDInfo=parsenoop;var parse_BCUsrs=parsenoop;var parse_UsrChk=parsenoop;var parse_UserBView=parsenoop;var parse_UserSViewBegin=parsenoop;var parse_UserSViewEnd=parsenoop;var parse_RRDUserView=parsenoop;var parse_Qsi=parsenoop;var parse_CondFmt=parsenoop;var parse_CF=parsenoop;var parse_DVal=parsenoop;var parse_DConBin=parsenoop;var parse_Lel=parsenoop;var parse_CodeName=parse_XLUnicodeString;var parse_SXFDBType=parsenoop;var parse_ObNoMacros=parsenoop;var parse_Dv=parsenoop;var parse_Index=parsenoop;var parse_Table=parsenoop;var parse_Window2=parsenoop;var parse_Style=parsenoop;var parse_BigName=parsenoop;var parse_ContinueBigName=parsenoop;var parse_WebPub=parsenoop;var parse_QsiSXTag=parsenoop;var parse_DBQueryExt=parsenoop;var parse_ExtString=parsenoop;var parse_TxtQry=parsenoop;var parse_Qsir=parsenoop;var parse_Qsif=parsenoop;var parse_RRDTQSIF=parsenoop;var parse_OleDbConn=parsenoop;var parse_WOpt=parsenoop;var parse_SXViewEx=parsenoop;var parse_SXTH=parsenoop;var parse_SXPIEx=parsenoop;var parse_SXVDTEx=parsenoop;var parse_SXViewEx9=parsenoop;var parse_ContinueFrt=parsenoop;var parse_RealTimeData=parsenoop;var parse_ChartFrtInfo=parsenoop;var parse_FrtWrapper=parsenoop;var parse_StartBlock=parsenoop;var parse_EndBlock=parsenoop;var parse_StartObject=parsenoop;var parse_EndObject=parsenoop;var parse_CatLab=parsenoop;var parse_YMult=parsenoop;var parse_SXViewLink=parsenoop;var parse_PivotChartBits=parsenoop;var parse_FrtFontList=parsenoop;var parse_SheetExt=parsenoop;var parse_BookExt=parsenoop;var parse_SXAddl=parsenoop;var parse_CrErr=parsenoop;var parse_HFPicture=parsenoop;var parse_Feat=parsenoop;var parse_DataLabExt=parsenoop;var parse_DataLabExtContents=parsenoop;var parse_CellWatch=parsenoop;var parse_FeatHdr11=parsenoop;var parse_Feature11=parsenoop;var parse_DropDownObjIds=parsenoop;var parse_ContinueFrt11=parsenoop;var parse_DConn=parsenoop;var parse_List12=parsenoop;var parse_Feature12=parsenoop;var parse_CondFmt12=parsenoop;var parse_CF12=parsenoop;var parse_CFEx=parsenoop;var parse_XFCRC=parsenoop;var parse_XFExt=parsenoop;var parse_AutoFilter12=parsenoop;var parse_ContinueFrt12=parsenoop;var parse_MDTInfo=parsenoop;var parse_MDXStr=parsenoop;var parse_MDXTuple=parsenoop;var parse_MDXSet=parsenoop;var parse_MDXProp=parsenoop;var parse_MDXKPI=parsenoop;var parse_MDB=parsenoop;var parse_PLV=parsenoop;var parse_DXF=parsenoop;var parse_TableStyles=parsenoop;var parse_TableStyle=parsenoop;var parse_TableStyleElement=parsenoop;var parse_StyleExt=parsenoop;var parse_NamePublish=parsenoop;var parse_NameCmt=parsenoop;var parse_SortData=parsenoop;var parse_Theme=parsenoop;var parse_GUIDTypeLib=parsenoop;var parse_FnGrp12=parsenoop;var parse_NameFnGrp12=parsenoop;var parse_HeaderFooter=parsenoop;var parse_CrtLayout12=parsenoop;var parse_CrtMlFrt=parsenoop;var parse_CrtMlFrtContinue=parsenoop;var parse_ShapePropsStream=parsenoop;var parse_TextPropsStream=parsenoop;var parse_RichTextStream=parsenoop;var parse_CrtLayout12A=parsenoop;var parse_Units=parsenoop;var parse_Chart=parsenoop;var parse_Series=parsenoop;var parse_DataFormat=parsenoop;var parse_LineFormat=parsenoop;var parse_MarkerFormat=parsenoop;var parse_AreaFormat=parsenoop;var parse_PieFormat=parsenoop;var parse_AttachedLabel=parsenoop;var parse_SeriesText=parsenoop;var parse_ChartFormat=parsenoop;var parse_Legend=parsenoop;var parse_SeriesList=parsenoop;var parse_Bar=parsenoop;var parse_Line=parsenoop;var parse_Pie=parsenoop;var parse_Area=parsenoop;var parse_Scatter=parsenoop;var parse_CrtLine=parsenoop;var parse_Axis=parsenoop;var parse_Tick=parsenoop;var parse_ValueRange=parsenoop;var parse_CatSerRange=parsenoop;var parse_AxisLine=parsenoop;var parse_CrtLink=parsenoop;var parse_DefaultText=parsenoop;var parse_Text=parsenoop;var parse_ObjectLink=parsenoop;var parse_Frame=parsenoop;var parse_Begin=parsenoop;var parse_End=parsenoop;var parse_PlotArea=parsenoop;var parse_Chart3d=parsenoop;var parse_PicF=parsenoop;var parse_DropBar=parsenoop;var parse_Radar=parsenoop;var parse_Surf=parsenoop;var parse_RadarArea=parsenoop;var parse_AxisParent=parsenoop;var parse_LegendException=parsenoop;var parse_ShtProps=parsenoop;var parse_SerToCrt=parsenoop;var parse_AxesUsed=parsenoop;var parse_SBaseRef=parsenoop;var parse_SerParent=parsenoop;var parse_SerAuxTrend=parsenoop;var parse_IFmtRecord=parsenoop;var parse_Pos=parsenoop;var parse_AlRuns=parsenoop;var parse_BRAI=parsenoop;var parse_SerAuxErrBar=parsenoop;var parse_ClrtClient=parsenoop;var parse_SerFmt=parsenoop;var parse_Chart3DBarShape=parsenoop;var parse_Fbi=parsenoop;var parse_BopPop=parsenoop;var parse_AxcExt=parsenoop;var parse_Dat=parsenoop;var parse_PlotGrowth=parsenoop;var parse_SIIndex=parsenoop;var parse_GelFrame=parsenoop;var parse_BopPopCustom=parsenoop;var parse_Fbi2=parsenoop;function parse_BIFF5String(blob){var len=blob.read_shift(1);return blob.read_shift(len,"sbcs")}var _chr=function(c){return String.fromCharCode(c)};var attregexg=/([\w:]+)=((?:")([^"]*)(?:")|(?:')([^']*)(?:'))/g;var attregex=/([\w:]+)=((?:")(?:[^"]*)(?:")|(?:')(?:[^']*)(?:'))/;function parsexmltag(tag,skip_root){var words=tag.split(/\s+/);var z=[];if(!skip_root)z[0]=words[0];if(words.length===1)return z;var m=tag.match(attregexg),y,j,w,i;if(m)for(i=0;i!=m.length;++i){y=m[i].match(attregex);if((j=y[1].indexOf(":"))===-1)z[y[1]]=y[2].substr(1,y[2].length-2);else{if(y[1].substr(0,6)==="xmlns:")w="xmlns"+y[1].substr(6);else w=y[1].substr(j+1);z[w]=y[2].substr(1,y[2].length-2)}}return z}function parsexmltagobj(tag){var words=tag.split(/\s+/);var z={};if(words.length===1)return z;var m=tag.match(attregexg),y,j,w,i;if(m)for(i=0;i!=m.length;++i){y=m[i].match(attregex);if((j=y[1].indexOf(":"))===-1)z[y[1]]=y[2].substr(1,y[2].length-2);else{if(y[1].substr(0,6)==="xmlns:")w="xmlns"+y[1].substr(6);else w=y[1].substr(j+1);z[w]=y[2].substr(1,y[2].length-2)}}return z}var encodings={"&quot;":'"',"&apos;":"'","&gt;":">","&lt;":"<","&amp;":"&"};var rencoding=evert(encodings);var rencstr="&<>'\"".split("");var XML_HEADER='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n';var OFFCRYPTO={};var make_offcrypto=function(O,_crypto){var crypto;if(typeof _crypto!=="undefined")crypto=_crypto;else if(typeof require!=="undefined"){try{crypto=require("cry"+"pto")}catch(e){crypto=null}}O.rc4=function(key,data){var S=new Array(256);var c=0,i=0,j=0,t=0;for(i=0;i!=256;++i)S[i]=i;for(i=0;i!=256;++i){j=j+S[i]+key[i%key.length].charCodeAt(0)&255;t=S[i];S[i]=S[j];S[j]=t}i=j=0;out=Buffer(data.length);for(c=0;c!=data.length;++c){i=i+1&255;j=(j+S[i])%256;t=S[i];S[i]=S[j];S[j]=t;out[c]=data[c]^S[S[i]+S[j]&255]}return out};if(crypto){O.md5=function(hex){return crypto.createHash("md5").update(hex).digest("hex")}}else{O.md5=function(hex){throw"unimplemented"}}};make_offcrypto(OFFCRYPTO,typeof crypto!=="undefined"?crypto:undefined);function _JS2ANSI(str){if(typeof cptable!=="undefined")return cptable.utils.encode(1252,str);return str.split("").map(function(x){return x.charCodeAt(0)})}function parse_Version(blob,length){var o={};o.Major=blob.read_shift(2);o.Minor=blob.read_shift(2);return o}function parse_EncryptionHeader(blob,length){var o={};o.Flags=blob.read_shift(4);var tmp=blob.read_shift(4);if(tmp!==0)throw"Unrecognized SizeExtra: "+tmp;o.AlgID=blob.read_shift(4);switch(o.AlgID){case 0:case 26625:case 26126:case 26127:case 26128:break;default:throw"Unrecognized encryption algorithm: "+o.AlgID}parsenoop(blob,length-12);return o}function parse_EncryptionVerifier(blob,length){return parsenoop(blob,length)}function parse_RC4CryptoHeader(blob,length){var o={};var vers=o.EncryptionVersionInfo=parse_Version(blob,4);length-=4;if(vers.Minor!=2)throw"unrecognized minor version code: "+vers.Minor;if(vers.Major>4||vers.Major<2)throw"unrecognized major version code: "+vers.Major;o.Flags=blob.read_shift(4);length-=4;var sz=blob.read_shift(4);length-=4;o.EncryptionHeader=parse_EncryptionHeader(blob,sz);length-=sz;o.EncryptionVerifier=parse_EncryptionVerifier(blob,length);return o}function parse_RC4Header(blob,length){var o={};var vers=o.EncryptionVersionInfo=parse_Version(blob,4);length-=4;if(vers.Major!=1||vers.Minor!=1)throw"unrecognized version code "+vers.Major+" : "+vers.Minor;o.Salt=blob.read_shift(16);o.EncryptedVerifier=blob.read_shift(16);o.EncryptedVerifierHash=blob.read_shift(16);return o}function crypto_CreatePasswordVerifier_Method1(Password){var Verifier=0,PasswordArray;var PasswordDecoded=_JS2ANSI(Password);var len=PasswordDecoded.length+1,i,PasswordByte;var Intermediate1,Intermediate2,Intermediate3;PasswordArray=new_buf(len);PasswordArray[0]=PasswordDecoded.length;for(i=1;i!=len;++i)PasswordArray[i]=PasswordDecoded[i-1];for(i=len-1;i>=0;--i){PasswordByte=PasswordArray[i];Intermediate1=(Verifier&16384)===0?0:1;Intermediate2=Verifier<<1&32767;Intermediate3=Intermediate1|Intermediate2;Verifier=Intermediate3^PasswordByte}return Verifier^52811}var crypto_CreateXorArray_Method1=function(){var PadArray=[187,255,255,186,255,255,185,128,0,190,15,0,191,15,0];var InitialCode=[57840,7439,52380,33984,4364,3600,61902,12606,6258,57657,54287,34041,10252,43370,20163];var XorMatrix=[44796,19929,39858,10053,20106,40212,10761,31585,63170,64933,60267,50935,40399,11199,17763,35526,1453,2906,5812,11624,23248,885,1770,3540,7080,14160,28320,56640,55369,41139,20807,41614,21821,43642,17621,28485,56970,44341,19019,38038,14605,29210,60195,50791,40175,10751,21502,43004,24537,18387,36774,3949,7898,15796,31592,63184,47201,24803,49606,37805,14203,28406,56812,17824,35648,1697,3394,6788,13576,27152,43601,17539,35078,557,1114,2228,4456,30388,60776,51953,34243,7079,14158,28316,14128,28256,56512,43425,17251,34502,7597,13105,26210,52420,35241,883,1766,3532,4129,8258,16516,33032,4657,9314,18628];var Ror=function(Byte){return(Byte/2|Byte*128)&255};var XorRor=function(byte1,byte2){return Ror(byte1^byte2)};var CreateXorKey_Method1=function(Password){var XorKey=InitialCode[Password.length-1];var CurrentElement=104;for(var i=Password.length-1;i>=0;--i){var Char=Password[i];for(var j=0;j!=7;++j){if(Char&64)XorKey^=XorMatrix[CurrentElement];Char*=2;--CurrentElement}}return XorKey};return function(password){var Password=_JS2ANSI(password);var XorKey=CreateXorKey_Method1(Password);var Index=Password.length;var ObfuscationArray=new_buf(16);for(var i=0;i!=16;++i)ObfuscationArray[i]=0;var Temp,PasswordLastChar,PadIndex;if((Index&1)===1){Temp=XorKey>>8;ObfuscationArray[Index]=XorRor(PadArray[0],Temp);--Index;Temp=XorKey&255;PasswordLastChar=Password[Password.length-1];ObfuscationArray[Index]=XorRor(PasswordLastChar,Temp)}while(Index>0){--Index;Temp=XorKey>>8;ObfuscationArray[Index]=XorRor(Password[Index],Temp);--Index;Temp=XorKey&255;ObfuscationArray[Index]=XorRor(Password[Index],Temp)}Index=15;PadIndex=15-Password.length;while(PadIndex>0){Temp=XorKey>>8;ObfuscationArray[Index]=XorRor(PadArray[PadIndex],Temp);--Index;--PadIndex;Temp=XorKey&255;ObfuscationArray[Index]=XorRor(Password[Index],Temp);--Index;--PadIndex}return ObfuscationArray}}();var crypto_DecryptData_Method1=function(password,Data,XorArrayIndex,XorArray,O){if(!O)O=Data;if(!XorArray)XorArray=crypto_CreateXorArray_Method1(password);var Index,Value;for(Index=0;Index!=Data.length;++Index){Value=Data[Index];Value^=XorArray[XorArrayIndex];Value=(Value>>5|Value<<3)&255;O[Index]=Value;++XorArrayIndex}return[O,XorArrayIndex,XorArray]};var crypto_MakeXorDecryptor=function(password){var XorArrayIndex=0,XorArray=crypto_CreateXorArray_Method1(password);return function(Data){var O=crypto_DecryptData_Method1(null,Data,XorArrayIndex,XorArray);XorArrayIndex=O[1];return O[0]}};function parse_XORObfuscation(blob,length,opts,out){var o={key:parseuint16(blob),verificationBytes:parseuint16(blob)};if(opts.password)o.verifier=crypto_CreatePasswordVerifier_Method1(opts.password);out.valid=o.verificationBytes===o.verifier;if(out.valid)out.insitu_decrypt=crypto_MakeXorDecryptor(opts.password);return o}function parse_FilePassHeader(blob,length,oo){var o=oo||{};o.Info=blob.read_shift(2);blob.l-=2;if(o.Info===1)o.Data=parse_RC4Header(blob,length);else o.Data=parse_RC4CryptoHeader(blob,length);return o}function parse_FilePass(blob,length,opts){var o={Type:blob.read_shift(2)};if(o.Type)parse_FilePassHeader(blob,length-2,o);else parse_XORObfuscation(blob,length-2,opts,o);return o}function parseread(l){return function(blob,length){blob.l+=l;return}}function parseread1(blob,length){blob.l+=1;return}function parse_ColRelU(blob,length){var c=blob.read_shift(2);return[c&16383,c>>14&1,c>>15&1]}function parse_RgceArea(blob,length){var r=blob.read_shift(2),R=blob.read_shift(2);var c=parse_ColRelU(blob,2);var C=parse_ColRelU(blob,2);return{s:{r:r,c:c[0],cRel:c[1],rRel:c[2]},e:{r:R,c:C[0],cRel:C[1],rRel:C[2]}}}function parse_RgceAreaRel(blob,length){var r=blob.read_shift(2),R=blob.read_shift(2);var c=parse_ColRelU(blob,2);var C=parse_ColRelU(blob,2);return{s:{r:r,c:c[0],cRel:c[1],rRel:c[2]},e:{r:R,c:C[0],cRel:C[1],rRel:C[2]}}}function parse_RgceLoc(blob,length){var r=blob.read_shift(2);var c=parse_ColRelU(blob,2);return{r:r,c:c[0],cRel:c[1],rRel:c[2]}}function parse_RgceLocRel(blob,length){var r=blob.read_shift(2);var cl=blob.read_shift(2);var cRel=(cl&32768)>>15,rRel=(cl&16384)>>14;cl&=16383;if(cRel!==0)while(cl>=256)cl-=256;return{r:r,c:cl,cRel:cRel,rRel:rRel}}function parse_PtgArea(blob,length){var type=(blob[blob.l++]&96)>>5;var area=parse_RgceArea(blob,8);return[type,area]}function parse_PtgArea3d(blob,length){var type=(blob[blob.l++]&96)>>5;var ixti=blob.read_shift(2);var area=parse_RgceArea(blob,8);return[type,ixti,area]}function parse_PtgAreaErr(blob,length){var type=(blob[blob.l++]&96)>>5;blob.l+=8;return[type]}function parse_PtgAreaErr3d(blob,length){var type=(blob[blob.l++]&96)>>5;var ixti=blob.read_shift(2);blob.l+=8;return[type,ixti]}function parse_PtgAreaN(blob,length){var type=(blob[blob.l++]&96)>>5;var area=parse_RgceAreaRel(blob,8);return[type,area]}function parse_PtgArray(blob,length){var type=(blob[blob.l++]&96)>>5;blob.l+=7;return[type]}function parse_PtgAttrBaxcel(blob,length){var bitSemi=blob[blob.l+1]&1;var bitBaxcel=1;blob.l+=4;return[bitSemi,bitBaxcel]}function parse_PtgAttrChoose(blob,length){blob.l+=2;var offset=blob.read_shift(2);var o=[];for(var i=0;i<=offset;++i)o.push(blob.read_shift(2));return o}function parse_PtgAttrGoto(blob,length){var bitGoto=blob[blob.l+1]&255?1:0;blob.l+=2;return[bitGoto,blob.read_shift(2)]}function parse_PtgAttrIf(blob,length){var bitIf=blob[blob.l+1]&255?1:0;blob.l+=2;return[bitIf,blob.read_shift(2)]}function parse_PtgAttrSemi(blob,length){var bitSemi=blob[blob.l+1]&255?1:0;blob.l+=4;return[bitSemi]}function parse_PtgAttrSpaceType(blob,length){var type=blob.read_shift(1),cch=blob.read_shift(1);return[type,cch]}function parse_PtgAttrSpace(blob,length){blob.read_shift(2);return parse_PtgAttrSpaceType(blob,2)}function parse_PtgAttrSpaceSemi(blob,length){blob.read_shift(2);return parse_PtgAttrSpaceType(blob,2)}function parse_PtgRef(blob,length){var ptg=blob[blob.l]&31;var type=(blob[blob.l]&96)>>5;blob.l+=1;var loc=parse_RgceLoc(blob,4);return[type,loc]}function parse_PtgRefN(blob,length){var ptg=blob[blob.l]&31;var type=(blob[blob.l]&96)>>5;blob.l+=1;var loc=parse_RgceLocRel(blob,4);return[type,loc]}function parse_PtgRef3d(blob,length){var ptg=blob[blob.l]&31;var type=(blob[blob.l]&96)>>5;blob.l+=1;var ixti=blob.read_shift(2);var loc=parse_RgceLoc(blob,4);return[type,ixti,loc]}function parse_PtgFunc(blob,length){var ptg=blob[blob.l]&31;var type=(blob[blob.l]&96)>>5;blob.l+=1;var iftab=blob.read_shift(2);return[FtabArgc[iftab],Ftab[iftab]]}function parse_PtgFuncVar(blob,length){blob.l++;var cparams=blob.read_shift(1),tab=parsetab(blob);return[cparams,(tab[0]===0?Ftab:Cetab)[tab[1]]]}function parsetab(blob,length){return[blob[blob.l+1]>>7,blob.read_shift(2)&32767]}var parse_PtgAttrSum=parseread(4);var parse_PtgConcat=parseread1;function parse_PtgExp(blob,length){blob.l++;var row=blob.read_shift(2);var col=blob.read_shift(2);return[row,col]}function parse_PtgErr(blob,length){blob.l++;return BERR[blob.read_shift(1)]}function parse_PtgInt(blob,length){blob.l++;return blob.read_shift(2)}function parse_PtgBool(blob,length){blob.l++;return blob.read_shift(1)!==0}function parse_PtgNum(blob,length){blob.l++;return parse_Xnum(blob,8)}function parse_PtgStr(blob,length){blob.l++;return parse_ShortXLUnicodeString(blob)}function parse_SerAr(blob){var val=[];switch(val[0]=blob.read_shift(1)){case 4:val[1]=parsebool(blob,1)?"TRUE":"FALSE";blob.l+=7;break;case 16:val[1]=BERR[blob[blob.l]];blob.l+=8;break;case 0:blob.l+=8;break;case 1:val[1]=parse_Xnum(blob,8);break;case 2:val[1]=parse_XLUnicodeString(blob);break}return val}function parse_PtgExtraMem(blob,cce){var count=blob.read_shift(2);var out=[];for(var i=0;i!=count;++i)out.push(parse_Ref8U(blob,8));return out}function parse_PtgExtraArray(blob){var cols=1+blob.read_shift(1);var rows=1+blob.read_shift(2);for(var i=0,o=[];i!=rows&&(o[i]=[]);++i)for(var j=0;j!=cols;++j)o[i][j]=parse_SerAr(blob);return o}function parse_PtgName(blob,length){var type=blob.read_shift(1)>>>5&3;var nameindex=blob.read_shift(4);return[type,0,nameindex]}function parse_PtgNameX(blob,length){var type=blob.read_shift(1)>>>5&3;var ixti=blob.read_shift(2);var nameindex=blob.read_shift(4);return[type,ixti,nameindex]}function parse_PtgMemArea(blob,length){var type=blob.read_shift(1)>>>5&3;blob.l+=4;var cce=blob.read_shift(2);return[type,cce]}function parse_PtgMemFunc(blob,length){var type=blob.read_shift(1)>>>5&3;var cce=blob.read_shift(2);return[type,cce]}function parse_PtgRefErr(blob,length){var type=blob.read_shift(1)>>>5&3;blob.l+=4;return[type]}var parse_PtgAdd=parseread1;var parse_PtgDiv=parseread1;var parse_PtgEq=parseread1;var parse_PtgGe=parseread1;var parse_PtgGt=parseread1;var parse_PtgIsect=parseread1;var parse_PtgLe=parseread1;var parse_PtgLt=parseread1;var parse_PtgMissArg=parseread1;var parse_PtgMul=parseread1;var parse_PtgNe=parseread1;var parse_PtgParen=parseread1;var parse_PtgPercent=parseread1;var parse_PtgPower=parseread1;var parse_PtgRange=parseread1;var parse_PtgSub=parseread1;var parse_PtgUminus=parseread1;var parse_PtgUnion=parseread1;var parse_PtgUplus=parseread1;var parse_PtgMemErr=parsenoop;var parse_PtgMemNoMem=parsenoop;var parse_PtgRefErr3d=parsenoop;var parse_PtgTbl=parsenoop;var PtgTypes={1:{n:"PtgExp",f:parse_PtgExp},2:{n:"PtgTbl",f:parse_PtgTbl},3:{n:"PtgAdd",f:parse_PtgAdd},4:{n:"PtgSub",f:parse_PtgSub},5:{n:"PtgMul",f:parse_PtgMul},6:{n:"PtgDiv",f:parse_PtgDiv},7:{n:"PtgPower",f:parse_PtgPower},8:{n:"PtgConcat",f:parse_PtgConcat},9:{n:"PtgLt",f:parse_PtgLt},10:{n:"PtgLe",f:parse_PtgLe},11:{n:"PtgEq",f:parse_PtgEq},12:{n:"PtgGe",f:parse_PtgGe},13:{n:"PtgGt",f:parse_PtgGt},14:{n:"PtgNe",f:parse_PtgNe},15:{n:"PtgIsect",f:parse_PtgIsect},16:{n:"PtgUnion",f:parse_PtgUnion},17:{n:"PtgRange",f:parse_PtgRange},18:{n:"PtgUplus",f:parse_PtgUplus},19:{n:"PtgUminus",f:parse_PtgUminus},20:{n:"PtgPercent",f:parse_PtgPercent},21:{n:"PtgParen",f:parse_PtgParen},22:{n:"PtgMissArg",f:parse_PtgMissArg},23:{n:"PtgStr",f:parse_PtgStr},28:{n:"PtgErr",f:parse_PtgErr},29:{n:"PtgBool",f:parse_PtgBool},30:{n:"PtgInt",f:parse_PtgInt},31:{n:"PtgNum",f:parse_PtgNum},32:{n:"PtgArray",f:parse_PtgArray},33:{n:"PtgFunc",f:parse_PtgFunc},34:{n:"PtgFuncVar",f:parse_PtgFuncVar},35:{n:"PtgName",f:parse_PtgName},36:{n:"PtgRef",f:parse_PtgRef},37:{n:"PtgArea",f:parse_PtgArea},38:{n:"PtgMemArea",f:parse_PtgMemArea},39:{n:"PtgMemErr",f:parse_PtgMemErr},40:{n:"PtgMemNoMem",f:parse_PtgMemNoMem},41:{n:"PtgMemFunc",f:parse_PtgMemFunc},42:{n:"PtgRefErr",f:parse_PtgRefErr},43:{n:"PtgAreaErr",f:parse_PtgAreaErr},44:{n:"PtgRefN",f:parse_PtgRefN},45:{n:"PtgAreaN",f:parse_PtgAreaN},57:{n:"PtgNameX",f:parse_PtgNameX},58:{n:"PtgRef3d",f:parse_PtgRef3d},59:{n:"PtgArea3d",f:parse_PtgArea3d},60:{n:"PtgRefErr3d",f:parse_PtgRefErr3d},61:{n:"PtgAreaErr3d",f:parse_PtgAreaErr3d},255:{}};var PtgDupes={64:32,96:32,65:33,97:33,66:34,98:34,67:35,99:35,68:36,100:36,69:37,101:37,70:38,102:38,71:39,103:39,72:40,104:40,73:41,105:41,74:42,106:42,75:43,107:43,76:44,108:44,77:45,109:45,89:57,121:57,90:58,122:58,91:59,123:59,92:60,124:60,93:61,125:61};(function(){for(var y in PtgDupes)PtgTypes[y]=PtgTypes[PtgDupes[y]]})();var Ptg18={};var Ptg19={1:{n:"PtgAttrSemi",f:parse_PtgAttrSemi},2:{n:"PtgAttrIf",f:parse_PtgAttrIf},4:{n:"PtgAttrChoose",f:parse_PtgAttrChoose},8:{n:"PtgAttrGoto",f:parse_PtgAttrGoto},16:{n:"PtgAttrSum",f:parse_PtgAttrSum},32:{n:"PtgAttrBaxcel",f:parse_PtgAttrBaxcel},64:{n:"PtgAttrSpace",f:parse_PtgAttrSpace},65:{n:"PtgAttrSpaceSemi",f:parse_PtgAttrSpaceSemi},255:{}};var rcregex=/(^|[^A-Za-z])R(\[?)(-?\d+|)\]?C(\[?)(-?\d+|)\]?/g;var rcbase;function rcfunc($$,$1,$2,$3,$4,$5){var R=$3.length>0?parseInt($3,10)|0:0,C=$5.length>0?parseInt($5,10)|0:0;if(C<0&&$4.length===0)C=0;if($4.length>0)C+=rcbase.c;if($2.length>0)R+=rcbase.r;return $1+encode_col(C)+encode_row(R)}function rc_to_a1(fstr,base){rcbase=base;return fstr.replace(rcregex,rcfunc)}function parse_Formula(blob,length,opts){var cell=parse_Cell(blob,6);var val=parse_FormulaValue(blob,8);var flags=blob.read_shift(1);blob.read_shift(1);var chn=blob.read_shift(4);var cbf="";if(opts.biff===5)blob.l+=length-20;else cbf=parse_CellParsedFormula(blob,length-20,opts);return{cell:cell,val:val[0],formula:cbf,shared:flags>>3&1,tt:val[1]}}function parse_FormulaValue(blob){var b;if(__readUInt16LE(blob,blob.l+6)!==65535)return[parse_Xnum(blob),"n"];switch(blob[blob.l]){case 0:blob.l+=8;return["String","s"];case 1:b=blob[blob.l+2]===1;blob.l+=8;return[b,"b"];case 2:b=BERR[blob[blob.l+2]];blob.l+=8;return[b,"e"];case 3:blob.l+=8;return["","s"]}}function parse_RgbExtra(blob,length,rgce,opts){if(opts.biff<8)return parsenoop(blob,length);var target=blob.l+length;var o=[];for(var i=0;i!==rgce.length;++i){switch(rgce[i][0]){case"PtgArray":rgce[i][1]=parse_PtgExtraArray(blob);o.push(rgce[i][1]);break;case"PtgMemArea":rgce[i][2]=parse_PtgExtraMem(blob,rgce[i][1]);o.push(rgce[i][2]);break;default:break}}length=target-blob.l;if(length!==0)o.push(parsenoop(blob,length));return o}function parse_NameParsedFormula(blob,length,opts,cce){var target=blob.l+length;var rgce=parse_Rgce(blob,cce);var rgcb;if(target!==blob.l)rgcb=parse_RgbExtra(blob,target-blob.l,rgce,opts);return[rgce,rgcb]}function parse_CellParsedFormula(blob,length,opts){var target=blob.l+length;var rgcb,cce=blob.read_shift(2);if(cce==65535)return[[],parsenoop(blob,length-2)];var rgce=parse_Rgce(blob,cce);if(length!==cce+2)rgcb=parse_RgbExtra(blob,length-cce-2,rgce,opts);return[rgce,rgcb]}function parse_SharedParsedFormula(blob,length,opts){var target=blob.l+length;var rgcb,cce=blob.read_shift(2);var rgce=parse_Rgce(blob,cce);if(cce==65535)return[[],parsenoop(blob,length-2)];if(length!==cce+2)rgcb=parse_RgbExtra(blob,target-cce-2,rgce,opts);return[rgce,rgcb]}function parse_ArrayParsedFormula(blob,length,opts,ref){var target=blob.l+length;var rgcb,cce=blob.read_shift(2);if(cce==65535)return[[],parsenoop(blob,length-2)];var rgce=parse_Rgce(blob,cce);if(length!==cce+2)rgcb=parse_RgbExtra(blob,target-cce-2,rgce,opts);return[rgce,rgcb]}function parse_Rgce(blob,length){var target=blob.l+length;var R,id,ptgs=[];while(target!=blob.l){length=target-blob.l;id=blob[blob.l];R=PtgTypes[id];if(id===24||id===25){id=blob[blob.l+1];R=(id===24?Ptg18:Ptg19)[id]}if(!R||!R.f){ptgs.push(parsenoop(blob,length))}else{ptgs.push([R.n,R.f(blob,length)])}}return ptgs}function mapper(x){return x.map(function f2(y){return y[1]}).join(",")}function stringify_formula(formula,range,cell,supbooks,opts){if(opts!==undefined&&opts.biff===5)return"BIFF5??";var _range=range!==undefined?range:{s:{c:0,r:0}};var stack=[],e1,e2,type,c,ixti,nameidx,r;if(!formula[0]||!formula[0][0])return"";for(var ff=0,fflen=formula[0].length;ff<fflen;++ff){var f=formula[0][ff];switch(f[0]){case"PtgUminus":stack.push("-"+stack.pop());break;case"PtgUplus":stack.push("+"+stack.pop());break;case"PtgPercent":stack.push(stack.pop()+"%");break;case"PtgAdd":e1=stack.pop();e2=stack.pop();stack.push(e2+"+"+e1);break;case"PtgSub":e1=stack.pop();e2=stack.pop();stack.push(e2+"-"+e1);break;case"PtgMul":e1=stack.pop();e2=stack.pop();stack.push(e2+"*"+e1);break;case"PtgDiv":e1=stack.pop();e2=stack.pop();stack.push(e2+"/"+e1);break;case"PtgPower":e1=stack.pop();e2=stack.pop();stack.push(e2+"^"+e1);break;case"PtgConcat":e1=stack.pop();e2=stack.pop();stack.push(e2+"&"+e1);break;case"PtgLt":e1=stack.pop();e2=stack.pop();stack.push(e2+"<"+e1);break;case"PtgLe":e1=stack.pop();e2=stack.pop();stack.push(e2+"<="+e1);break;case"PtgEq":e1=stack.pop();e2=stack.pop();stack.push(e2+"="+e1);break;case"PtgGe":e1=stack.pop();e2=stack.pop();stack.push(e2+">="+e1);break;case"PtgGt":e1=stack.pop();e2=stack.pop();stack.push(e2+">"+e1);break;case"PtgNe":e1=stack.pop();e2=stack.pop();stack.push(e2+"<>"+e1);break;case"PtgIsect":e1=stack.pop();e2=stack.pop();stack.push(e2+" "+e1);break;case"PtgUnion":e1=stack.pop();e2=stack.pop();stack.push(e2+","+e1);break;case"PtgRange":break;case"PtgAttrChoose":break;case"PtgAttrGoto":break;case"PtgAttrIf":break;case"PtgRef":type=f[1][0];c=shift_cell(decode_cell(encode_cell(f[1][1])),_range);stack.push(encode_cell(c));break;case"PtgRefN":type=f[1][0];c=shift_cell(decode_cell(encode_cell(f[1][1])),cell);stack.push(encode_cell(c));break;case"PtgRef3d":type=f[1][0];ixti=f[1][1];c=shift_cell(f[1][2],_range);stack.push(supbooks[1][ixti+1]+"!"+encode_cell(c));break;case"PtgFunc":case"PtgFuncVar":var argc=f[1][0],func=f[1][1];if(!argc)argc=0;var args=stack.slice(-argc);stack.length-=argc;if(func==="User")func=args.shift();stack.push(func+"("+args.join(",")+")");break;case"PtgBool":stack.push(f[1]?"TRUE":"FALSE");break;case"PtgInt":stack.push(f[1]);break;case"PtgNum":stack.push(String(f[1]));break;case"PtgStr":stack.push('"'+f[1]+'"');break;case"PtgErr":stack.push(f[1]);break;case"PtgArea":type=f[1][0];r=shift_range(f[1][1],_range);stack.push(encode_range(r));break;case"PtgArea3d":type=f[1][0];ixti=f[1][1];r=f[1][2];stack.push(supbooks[1][ixti+1]+"!"+encode_range(r));break;case"PtgAttrSum":stack.push("SUM("+stack.pop()+")");break;case"PtgAttrSemi":break;case"PtgName":nameidx=f[1][2];var lbl=supbooks[0][nameidx];var name=lbl.Name;if(name in XLSXFutureFunctions)name=XLSXFutureFunctions[name];stack.push(name);break;case"PtgNameX":var bookidx=f[1][1];nameidx=f[1][2];var externbook;if(supbooks[bookidx+1])externbook=supbooks[bookidx+1][nameidx];else if(supbooks[bookidx-1])externbook=supbooks[bookidx-1][nameidx];if(!externbook)externbook={body:"??NAMEX??"};stack.push(externbook.body);break;case"PtgParen":stack.push("("+stack.pop()+")");break;case"PtgRefErr":stack.push("#REF!");break;case"PtgExp":c={c:f[1][1],r:f[1][0]};var q={c:cell.c,r:cell.r};if(supbooks.sharedf[encode_cell(c)]){var parsedf=supbooks.sharedf[encode_cell(c)];stack.push(stringify_formula(parsedf,_range,q,supbooks,opts))}else{var fnd=false;for(e1=0;e1!=supbooks.arrayf.length;++e1){e2=supbooks.arrayf[e1];if(c.c<e2[0].s.c||c.c>e2[0].e.c)continue;if(c.r<e2[0].s.r||c.r>e2[0].e.r)continue;stack.push(stringify_formula(e2[1],_range,q,supbooks,opts))}if(!fnd)stack.push(f[1])}break;case"PtgArray":stack.push("{"+f[1].map(mapper).join(";")+"}");break;case"PtgMemArea":break;case"PtgAttrSpace":break;case"PtgTbl":break;case"PtgMemErr":break;case"PtgMissArg":stack.push("");break;case"PtgAreaErr":break;case"PtgAreaN":stack.push("");break;case"PtgRefErr3d":break;case"PtgMemFunc":break;default:throw"Unrecognized Formula Token: "+f}}return stack[0]}var PtgDataType={1:"REFERENCE",2:"VALUE",3:"ARRAY"};var BERR={0:"#NULL!",7:"#DIV/0!",15:"#VALUE!",23:"#REF!",29:"#NAME?",36:"#NUM!",42:"#N/A",43:"#GETTING_DATA",255:"#WTF?"};var Cetab={0:"BEEP",1:"OPEN",2:"OPEN.LINKS",3:"CLOSE.ALL",4:"SAVE",5:"SAVE.AS",6:"FILE.DELETE",7:"PAGE.SETUP",8:"PRINT",9:"PRINTER.SETUP",10:"QUIT",11:"NEW.WINDOW",12:"ARRANGE.ALL",13:"WINDOW.SIZE",14:"WINDOW.MOVE",15:"FULL",16:"CLOSE",17:"RUN",22:"SET.PRINT.AREA",23:"SET.PRINT.TITLES",24:"SET.PAGE.BREAK",25:"REMOVE.PAGE.BREAK",26:"FONT",27:"DISPLAY",28:"PROTECT.DOCUMENT",29:"PRECISION",30:"A1.R1C1",31:"CALCULATE.NOW",32:"CALCULATION",34:"DATA.FIND",35:"EXTRACT",36:"DATA.DELETE",37:"SET.DATABASE",38:"SET.CRITERIA",39:"SORT",40:"DATA.SERIES",41:"TABLE",42:"FORMAT.NUMBER",43:"ALIGNMENT",44:"STYLE",45:"BORDER",46:"CELL.PROTECTION",47:"COLUMN.WIDTH",48:"UNDO",49:"CUT",50:"COPY",51:"PASTE",52:"CLEAR",53:"PASTE.SPECIAL",54:"EDIT.DELETE",55:"INSERT",56:"FILL.RIGHT",57:"FILL.DOWN",61:"DEFINE.NAME",62:"CREATE.NAMES",63:"FORMULA.GOTO",64:"FORMULA.FIND",65:"SELECT.LAST.CELL",66:"SHOW.ACTIVE.CELL",67:"GALLERY.AREA",68:"GALLERY.BAR",69:"GALLERY.COLUMN",70:"GALLERY.LINE",71:"GALLERY.PIE",72:"GALLERY.SCATTER",73:"COMBINATION",74:"PREFERRED",75:"ADD.OVERLAY",76:"GRIDLINES",77:"SET.PREFERRED",78:"AXES",79:"LEGEND",80:"ATTACH.TEXT",81:"ADD.ARROW",82:"SELECT.CHART",83:"SELECT.PLOT.AREA",84:"PATTERNS",85:"MAIN.CHART",86:"OVERLAY",87:"SCALE",88:"FORMAT.LEGEND",89:"FORMAT.TEXT",90:"EDIT.REPEAT",91:"PARSE",92:"JUSTIFY",93:"HIDE",94:"UNHIDE",95:"WORKSPACE",96:"FORMULA",97:"FORMULA.FILL",98:"FORMULA.ARRAY",99:"DATA.FIND.NEXT",100:"DATA.FIND.PREV",101:"FORMULA.FIND.NEXT",102:"FORMULA.FIND.PREV",103:"ACTIVATE",104:"ACTIVATE.NEXT",105:"ACTIVATE.PREV",106:"UNLOCKED.NEXT",107:"UNLOCKED.PREV",108:"COPY.PICTURE",109:"SELECT",110:"DELETE.NAME",111:"DELETE.FORMAT",112:"VLINE",113:"HLINE",114:"VPAGE",115:"HPAGE",116:"VSCROLL",117:"HSCROLL",118:"ALERT",119:"NEW",120:"CANCEL.COPY",121:"SHOW.CLIPBOARD",122:"MESSAGE",124:"PASTE.LINK",125:"APP.ACTIVATE",126:"DELETE.ARROW",127:"ROW.HEIGHT",128:"FORMAT.MOVE",129:"FORMAT.SIZE",130:"FORMULA.REPLACE",131:"SEND.KEYS",132:"SELECT.SPECIAL",133:"APPLY.NAMES",134:"REPLACE.FONT",135:"FREEZE.PANES",136:"SHOW.INFO",137:"SPLIT",138:"ON.WINDOW",139:"ON.DATA",140:"DISABLE.INPUT",142:"OUTLINE",143:"LIST.NAMES",144:"FILE.CLOSE",145:"SAVE.WORKBOOK",146:"DATA.FORM",147:"COPY.CHART",148:"ON.TIME",149:"WAIT",150:"FORMAT.FONT",151:"FILL.UP",152:"FILL.LEFT",153:"DELETE.OVERLAY",155:"SHORT.MENUS",159:"SET.UPDATE.STATUS",161:"COLOR.PALETTE",162:"DELETE.STYLE",163:"WINDOW.RESTORE",164:"WINDOW.MAXIMIZE",166:"CHANGE.LINK",167:"CALCULATE.DOCUMENT",168:"ON.KEY",169:"APP.RESTORE",170:"APP.MOVE",171:"APP.SIZE",172:"APP.MINIMIZE",173:"APP.MAXIMIZE",174:"BRING.TO.FRONT",175:"SEND.TO.BACK",185:"MAIN.CHART.TYPE",186:"OVERLAY.CHART.TYPE",187:"SELECT.END",188:"OPEN.MAIL",189:"SEND.MAIL",190:"STANDARD.FONT",191:"CONSOLIDATE",192:"SORT.SPECIAL",193:"GALLERY.3D.AREA",194:"GALLERY.3D.COLUMN",195:"GALLERY.3D.LINE",196:"GALLERY.3D.PIE",197:"VIEW.3D",198:"GOAL.SEEK",199:"WORKGROUP",200:"FILL.GROUP",201:"UPDATE.LINK",202:"PROMOTE",203:"DEMOTE",204:"SHOW.DETAIL",206:"UNGROUP",207:"OBJECT.PROPERTIES",208:"SAVE.NEW.OBJECT",209:"SHARE",210:"SHARE.NAME",211:"DUPLICATE",212:"APPLY.STYLE",213:"ASSIGN.TO.OBJECT",214:"OBJECT.PROTECTION",215:"HIDE.OBJECT",216:"SET.EXTRACT",217:"CREATE.PUBLISHER",218:"SUBSCRIBE.TO",219:"ATTRIBUTES",220:"SHOW.TOOLBAR",222:"PRINT.PREVIEW",223:"EDIT.COLOR",224:"SHOW.LEVELS",225:"FORMAT.MAIN",226:"FORMAT.OVERLAY",227:"ON.RECALC",228:"EDIT.SERIES",229:"DEFINE.STYLE",240:"LINE.PRINT",243:"ENTER.DATA",249:"GALLERY.RADAR",250:"MERGE.STYLES",251:"EDITION.OPTIONS",252:"PASTE.PICTURE",253:"PASTE.PICTURE.LINK",254:"SPELLING",256:"ZOOM",259:"INSERT.OBJECT",260:"WINDOW.MINIMIZE",265:"SOUND.NOTE",266:"SOUND.PLAY",267:"FORMAT.SHAPE",268:"EXTEND.POLYGON",269:"FORMAT.AUTO",272:"GALLERY.3D.BAR",273:"GALLERY.3D.SURFACE",274:"FILL.AUTO",276:"CUSTOMIZE.TOOLBAR",277:"ADD.TOOL",278:"EDIT.OBJECT",279:"ON.DOUBLECLICK",280:"ON.ENTRY",281:"WORKBOOK.ADD",282:"WORKBOOK.MOVE",283:"WORKBOOK.COPY",284:"WORKBOOK.OPTIONS",285:"SAVE.WORKSPACE",288:"CHART.WIZARD",289:"DELETE.TOOL",290:"MOVE.TOOL",291:"WORKBOOK.SELECT",292:"WORKBOOK.ACTIVATE",293:"ASSIGN.TO.TOOL",295:"COPY.TOOL",296:"RESET.TOOL",297:"CONSTRAIN.NUMERIC",298:"PASTE.TOOL",302:"WORKBOOK.NEW",305:"SCENARIO.CELLS",306:"SCENARIO.DELETE",307:"SCENARIO.ADD",308:"SCENARIO.EDIT",309:"SCENARIO.SHOW",310:"SCENARIO.SHOW.NEXT",311:"SCENARIO.SUMMARY",312:"PIVOT.TABLE.WIZARD",313:"PIVOT.FIELD.PROPERTIES",314:"PIVOT.FIELD",315:"PIVOT.ITEM",316:"PIVOT.ADD.FIELDS",318:"OPTIONS.CALCULATION",319:"OPTIONS.EDIT",320:"OPTIONS.VIEW",321:"ADDIN.MANAGER",322:"MENU.EDITOR",323:"ATTACH.TOOLBARS",324:"VBAActivate",325:"OPTIONS.CHART",328:"VBA.INSERT.FILE",330:"VBA.PROCEDURE.DEFINITION",336:"ROUTING.SLIP",338:"ROUTE.DOCUMENT",339:"MAIL.LOGON",342:"INSERT.PICTURE",343:"EDIT.TOOL",344:"GALLERY.DOUGHNUT",350:"CHART.TREND",352:"PIVOT.ITEM.PROPERTIES",354:"WORKBOOK.INSERT",355:"OPTIONS.TRANSITION",356:"OPTIONS.GENERAL",370:"FILTER.ADVANCED",373:"MAIL.ADD.MAILER",374:"MAIL.DELETE.MAILER",375:"MAIL.REPLY",376:"MAIL.REPLY.ALL",377:"MAIL.FORWARD",378:"MAIL.NEXT.LETTER",379:"DATA.LABEL",380:"INSERT.TITLE",381:"FONT.PROPERTIES",382:"MACRO.OPTIONS",383:"WORKBOOK.HIDE",384:"WORKBOOK.UNHIDE",385:"WORKBOOK.DELETE",386:"WORKBOOK.NAME",388:"GALLERY.CUSTOM",390:"ADD.CHART.AUTOFORMAT",391:"DELETE.CHART.AUTOFORMAT",392:"CHART.ADD.DATA",393:"AUTO.OUTLINE",394:"TAB.ORDER",395:"SHOW.DIALOG",396:"SELECT.ALL",397:"UNGROUP.SHEETS",398:"SUBTOTAL.CREATE",399:"SUBTOTAL.REMOVE",400:"RENAME.OBJECT",412:"WORKBOOK.SCROLL",413:"WORKBOOK.NEXT",414:"WORKBOOK.PREV",415:"WORKBOOK.TAB.SPLIT",416:"FULL.SCREEN",417:"WORKBOOK.PROTECT",420:"SCROLLBAR.PROPERTIES",421:"PIVOT.SHOW.PAGES",422:"TEXT.TO.COLUMNS",423:"FORMAT.CHARTTYPE",424:"LINK.FORMAT",425:"TRACER.DISPLAY",430:"TRACER.NAVIGATE",431:"TRACER.CLEAR",432:"TRACER.ERROR",433:"PIVOT.FIELD.GROUP",434:"PIVOT.FIELD.UNGROUP",435:"CHECKBOX.PROPERTIES",436:"LABEL.PROPERTIES",437:"LISTBOX.PROPERTIES",438:"EDITBOX.PROPERTIES",439:"PIVOT.REFRESH",440:"LINK.COMBO",441:"OPEN.TEXT",442:"HIDE.DIALOG",443:"SET.DIALOG.FOCUS",444:"ENABLE.OBJECT",445:"PUSHBUTTON.PROPERTIES",446:"SET.DIALOG.DEFAULT",447:"FILTER",448:"FILTER.SHOW.ALL",449:"CLEAR.OUTLINE",450:"FUNCTION.WIZARD",451:"ADD.LIST.ITEM",452:"SET.LIST.ITEM",453:"REMOVE.LIST.ITEM",454:"SELECT.LIST.ITEM",455:"SET.CONTROL.VALUE",456:"SAVE.COPY.AS",458:"OPTIONS.LISTS.ADD",459:"OPTIONS.LISTS.DELETE",460:"SERIES.AXES",461:"SERIES.X",462:"SERIES.Y",463:"ERRORBAR.X",464:"ERRORBAR.Y",465:"FORMAT.CHART",466:"SERIES.ORDER",467:"MAIL.LOGOFF",468:"CLEAR.ROUTING.SLIP",469:"APP.ACTIVATE.MICROSOFT",470:"MAIL.EDIT.MAILER",471:"ON.SHEET",472:"STANDARD.WIDTH",473:"SCENARIO.MERGE",474:"SUMMARY.INFO",475:"FIND.FILE",476:"ACTIVE.CELL.FONT",477:"ENABLE.TIPWIZARD",478:"VBA.MAKE.ADDIN",480:"INSERTDATATABLE",481:"WORKGROUP.OPTIONS",482:"MAIL.SEND.MAILER",485:"AUTOCORRECT",489:"POST.DOCUMENT",491:"PICKLIST",493:"VIEW.SHOW",494:"VIEW.DEFINE",495:"VIEW.DELETE",509:"SHEET.BACKGROUND",510:"INSERT.MAP.OBJECT",511:"OPTIONS.MENONO",517:"MSOCHECKS",518:"NORMAL",519:"LAYOUT",520:"RM.PRINT.AREA",521:"CLEAR.PRINT.AREA",522:"ADD.PRINT.AREA",523:"MOVE.BRK",545:"HIDECURR.NOTE",546:"HIDEALL.NOTES",547:"DELETE.NOTE",548:"TRAVERSE.NOTES",549:"ACTIVATE.NOTES",620:"PROTECT.REVISIONS",621:"UNPROTECT.REVISIONS",647:"OPTIONS.ME",653:"WEB.PUBLISH",667:"NEWWEBQUERY",673:"PIVOT.TABLE.CHART",753:"OPTIONS.SAVE",755:"OPTIONS.SPELL",808:"HIDEALL.INKANNOTS"};
25800 var Ftab={0:"COUNT",1:"IF",2:"ISNA",3:"ISERROR",4:"SUM",5:"AVERAGE",6:"MIN",7:"MAX",8:"ROW",9:"COLUMN",10:"NA",11:"NPV",12:"STDEV",13:"DOLLAR",14:"FIXED",15:"SIN",16:"COS",17:"TAN",18:"ATAN",19:"PI",20:"SQRT",21:"EXP",22:"LN",23:"LOG10",24:"ABS",25:"INT",26:"SIGN",27:"ROUND",28:"LOOKUP",29:"INDEX",30:"REPT",31:"MID",32:"LEN",33:"VALUE",34:"TRUE",35:"FALSE",36:"AND",37:"OR",38:"NOT",39:"MOD",40:"DCOUNT",41:"DSUM",42:"DAVERAGE",43:"DMIN",44:"DMAX",45:"DSTDEV",46:"VAR",47:"DVAR",48:"TEXT",49:"LINEST",50:"TREND",51:"LOGEST",52:"GROWTH",53:"GOTO",54:"HALT",55:"RETURN",56:"PV",57:"FV",58:"NPER",59:"PMT",60:"RATE",61:"MIRR",62:"IRR",63:"RAND",64:"MATCH",65:"DATE",66:"TIME",67:"DAY",68:"MONTH",69:"YEAR",70:"WEEKDAY",71:"HOUR",72:"MINUTE",73:"SECOND",74:"NOW",75:"AREAS",76:"ROWS",77:"COLUMNS",78:"OFFSET",79:"ABSREF",80:"RELREF",81:"ARGUMENT",82:"SEARCH",83:"TRANSPOSE",84:"ERROR",85:"STEP",86:"TYPE",87:"ECHO",88:"SET.NAME",89:"CALLER",90:"DEREF",91:"WINDOWS",92:"SERIES",93:"DOCUMENTS",94:"ACTIVE.CELL",95:"SELECTION",96:"RESULT",97:"ATAN2",98:"ASIN",99:"ACOS",100:"CHOOSE",101:"HLOOKUP",102:"VLOOKUP",103:"LINKS",104:"INPUT",105:"ISREF",106:"GET.FORMULA",107:"GET.NAME",108:"SET.VALUE",109:"LOG",110:"EXEC",111:"CHAR",112:"LOWER",113:"UPPER",114:"PROPER",115:"LEFT",116:"RIGHT",117:"EXACT",118:"TRIM",119:"REPLACE",120:"SUBSTITUTE",121:"CODE",122:"NAMES",123:"DIRECTORY",124:"FIND",125:"CELL",126:"ISERR",127:"ISTEXT",128:"ISNUMBER",129:"ISBLANK",130:"T",131:"N",132:"FOPEN",133:"FCLOSE",134:"FSIZE",135:"FREADLN",136:"FREAD",137:"FWRITELN",138:"FWRITE",139:"FPOS",140:"DATEVALUE",141:"TIMEVALUE",142:"SLN",143:"SYD",144:"DDB",145:"GET.DEF",146:"REFTEXT",147:"TEXTREF",148:"INDIRECT",149:"REGISTER",150:"CALL",151:"ADD.BAR",152:"ADD.MENU",153:"ADD.COMMAND",154:"ENABLE.COMMAND",155:"CHECK.COMMAND",156:"RENAME.COMMAND",157:"SHOW.BAR",158:"DELETE.MENU",159:"DELETE.COMMAND",160:"GET.CHART.ITEM",161:"DIALOG.BOX",162:"CLEAN",163:"MDETERM",164:"MINVERSE",165:"MMULT",166:"FILES",167:"IPMT",168:"PPMT",169:"COUNTA",170:"CANCEL.KEY",171:"FOR",172:"WHILE",173:"BREAK",174:"NEXT",175:"INITIATE",176:"REQUEST",177:"POKE",178:"EXECUTE",179:"TERMINATE",180:"RESTART",181:"HELP",182:"GET.BAR",183:"PRODUCT",184:"FACT",185:"GET.CELL",186:"GET.WORKSPACE",187:"GET.WINDOW",188:"GET.DOCUMENT",189:"DPRODUCT",190:"ISNONTEXT",191:"GET.NOTE",192:"NOTE",193:"STDEVP",194:"VARP",195:"DSTDEVP",196:"DVARP",197:"TRUNC",198:"ISLOGICAL",199:"DCOUNTA",200:"DELETE.BAR",201:"UNREGISTER",204:"USDOLLAR",205:"FINDB",206:"SEARCHB",207:"REPLACEB",208:"LEFTB",209:"RIGHTB",210:"MIDB",211:"LENB",212:"ROUNDUP",213:"ROUNDDOWN",214:"ASC",215:"DBCS",216:"RANK",219:"ADDRESS",220:"DAYS360",221:"TODAY",222:"VDB",223:"ELSE",224:"ELSE.IF",225:"END.IF",226:"FOR.CELL",227:"MEDIAN",228:"SUMPRODUCT",229:"SINH",230:"COSH",231:"TANH",232:"ASINH",233:"ACOSH",234:"ATANH",235:"DGET",236:"CREATE.OBJECT",237:"VOLATILE",238:"LAST.ERROR",239:"CUSTOM.UNDO",240:"CUSTOM.REPEAT",241:"FORMULA.CONVERT",242:"GET.LINK.INFO",243:"TEXT.BOX",244:"INFO",245:"GROUP",246:"GET.OBJECT",247:"DB",248:"PAUSE",251:"RESUME",252:"FREQUENCY",253:"ADD.TOOLBAR",254:"DELETE.TOOLBAR",255:"User",256:"RESET.TOOLBAR",257:"EVALUATE",258:"GET.TOOLBAR",259:"GET.TOOL",260:"SPELLING.CHECK",261:"ERROR.TYPE",262:"APP.TITLE",263:"WINDOW.TITLE",264:"SAVE.TOOLBAR",265:"ENABLE.TOOL",266:"PRESS.TOOL",267:"REGISTER.ID",268:"GET.WORKBOOK",269:"AVEDEV",270:"BETADIST",271:"GAMMALN",272:"BETAINV",273:"BINOMDIST",274:"CHIDIST",275:"CHIINV",276:"COMBIN",277:"CONFIDENCE",278:"CRITBINOM",279:"EVEN",280:"EXPONDIST",281:"FDIST",282:"FINV",283:"FISHER",284:"FISHERINV",285:"FLOOR",286:"GAMMADIST",287:"GAMMAINV",288:"CEILING",289:"HYPGEOMDIST",290:"LOGNORMDIST",291:"LOGINV",292:"NEGBINOMDIST",293:"NORMDIST",294:"NORMSDIST",295:"NORMINV",296:"NORMSINV",297:"STANDARDIZE",298:"ODD",299:"PERMUT",300:"POISSON",301:"TDIST",302:"WEIBULL",303:"SUMXMY2",304:"SUMX2MY2",305:"SUMX2PY2",306:"CHITEST",307:"CORREL",308:"COVAR",309:"FORECAST",310:"FTEST",311:"INTERCEPT",312:"PEARSON",313:"RSQ",314:"STEYX",315:"SLOPE",316:"TTEST",317:"PROB",318:"DEVSQ",319:"GEOMEAN",320:"HARMEAN",321:"SUMSQ",322:"KURT",323:"SKEW",324:"ZTEST",325:"LARGE",326:"SMALL",327:"QUARTILE",328:"PERCENTILE",329:"PERCENTRANK",330:"MODE",331:"TRIMMEAN",332:"TINV",334:"MOVIE.COMMAND",335:"GET.MOVIE",336:"CONCATENATE",337:"POWER",338:"PIVOT.ADD.DATA",339:"GET.PIVOT.TABLE",340:"GET.PIVOT.FIELD",341:"GET.PIVOT.ITEM",342:"RADIANS",343:"DEGREES",344:"SUBTOTAL",345:"SUMIF",346:"COUNTIF",347:"COUNTBLANK",348:"SCENARIO.GET",349:"OPTIONS.LISTS.GET",350:"ISPMT",351:"DATEDIF",352:"DATESTRING",353:"NUMBERSTRING",354:"ROMAN",355:"OPEN.DIALOG",356:"SAVE.DIALOG",357:"VIEW.GET",358:"GETPIVOTDATA",359:"HYPERLINK",360:"PHONETIC",361:"AVERAGEA",362:"MAXA",363:"MINA",364:"STDEVPA",365:"VARPA",366:"STDEVA",367:"VARA",368:"BAHTTEXT",369:"THAIDAYOFWEEK",370:"THAIDIGIT",371:"THAIMONTHOFYEAR",372:"THAINUMSOUND",373:"THAINUMSTRING",374:"THAISTRINGLENGTH",375:"ISTHAIDIGIT",376:"ROUNDBAHTDOWN",377:"ROUNDBAHTUP",378:"THAIYEAR",379:"RTD"};var FtabArgc={2:1,3:1,15:1,16:1,17:1,18:1,20:1,21:1,22:1,23:1,24:1,25:1,26:1,27:2,30:2,31:3,32:1,33:1,38:1,39:2,40:3,41:3,42:3,43:3,44:3,45:3,47:3,48:2,53:1,61:3,65:3,66:3,67:1,68:1,69:1,71:1,72:1,73:1,75:1,76:1,77:1,79:2,80:2,83:1,86:1,90:1,97:2,98:1,99:1,105:1,111:1,112:1,113:1,114:1,117:2,118:1,119:4,121:1,126:1,127:1,128:1,129:1,130:1,131:1,133:1,134:1,135:1,136:2,137:2,138:2,140:1,141:1,142:3,143:4,162:1,163:1,164:1,165:2,172:1,175:2,176:2,177:3,178:2,179:1,184:1,189:3,190:1,195:3,196:3,198:1,199:3,201:1,207:4,210:3,211:1,212:2,213:2,214:1,215:1,229:1,230:1,231:1,232:1,233:1,234:1,235:3,244:1,252:2,257:1,261:1,271:1,273:4,274:2,275:2,276:2,277:3,278:3,279:1,280:3,281:3,282:3,283:1,284:1,285:2,286:4,287:3,288:2,289:4,290:3,291:3,292:3,293:4,294:1,295:3,296:1,297:3,298:1,299:2,300:3,301:3,302:4,303:2,304:2,305:2,306:2,307:2,308:2,309:3,310:2,311:2,312:2,313:2,314:2,315:2,316:4,325:2,326:2,327:2,328:2,331:2,332:2,337:2,342:1,343:1,346:2,347:1,350:4,351:3,352:1,353:2,360:1,368:1,369:1,370:1,371:1,372:1,373:1,374:1,375:1,376:1,377:1,378:1,65535:0};var XLSXFutureFunctions={"_xlfn.ACOT":"ACOT","_xlfn.ACOTH":"ACOTH","_xlfn.AGGREGATE":"AGGREGATE","_xlfn.ARABIC":"ARABIC","_xlfn.AVERAGEIF":"AVERAGEIF","_xlfn.AVERAGEIFS":"AVERAGEIFS","_xlfn.BASE":"BASE","_xlfn.BETA.DIST":"BETA.DIST","_xlfn.BETA.INV":"BETA.INV","_xlfn.BINOM.DIST":"BINOM.DIST","_xlfn.BINOM.DIST.RANGE":"BINOM.DIST.RANGE","_xlfn.BINOM.INV":"BINOM.INV","_xlfn.BITAND":"BITAND","_xlfn.BITLSHIFT":"BITLSHIFT","_xlfn.BITOR":"BITOR","_xlfn.BITRSHIFT":"BITRSHIFT","_xlfn.BITXOR":"BITXOR","_xlfn.CEILING.MATH":"CEILING.MATH","_xlfn.CEILING.PRECISE":"CEILING.PRECISE","_xlfn.CHISQ.DIST":"CHISQ.DIST","_xlfn.CHISQ.DIST.RT":"CHISQ.DIST.RT","_xlfn.CHISQ.INV":"CHISQ.INV","_xlfn.CHISQ.INV.RT":"CHISQ.INV.RT","_xlfn.CHISQ.TEST":"CHISQ.TEST","_xlfn.COMBINA":"COMBINA","_xlfn.CONFIDENCE.NORM":"CONFIDENCE.NORM","_xlfn.CONFIDENCE.T":"CONFIDENCE.T","_xlfn.COT":"COT","_xlfn.COTH":"COTH","_xlfn.COUNTIFS":"COUNTIFS","_xlfn.COVARIANCE.P":"COVARIANCE.P","_xlfn.COVARIANCE.S":"COVARIANCE.S","_xlfn.CSC":"CSC","_xlfn.CSCH":"CSCH","_xlfn.DAYS":"DAYS","_xlfn.DECIMAL":"DECIMAL","_xlfn.ECMA.CEILING":"ECMA.CEILING","_xlfn.ERF.PRECISE":"ERF.PRECISE","_xlfn.ERFC.PRECISE":"ERFC.PRECISE","_xlfn.EXPON.DIST":"EXPON.DIST","_xlfn.F.DIST":"F.DIST","_xlfn.F.DIST.RT":"F.DIST.RT","_xlfn.F.INV":"F.INV","_xlfn.F.INV.RT":"F.INV.RT","_xlfn.F.TEST":"F.TEST","_xlfn.FILTERXML":"FILTERXML","_xlfn.FLOOR.MATH":"FLOOR.MATH","_xlfn.FLOOR.PRECISE":"FLOOR.PRECISE","_xlfn.FORMULATEXT":"FORMULATEXT","_xlfn.GAMMA":"GAMMA","_xlfn.GAMMA.DIST":"GAMMA.DIST","_xlfn.GAMMA.INV":"GAMMA.INV","_xlfn.GAMMALN.PRECISE":"GAMMALN.PRECISE","_xlfn.GAUSS":"GAUSS","_xlfn.HYPGEOM.DIST":"HYPGEOM.DIST","_xlfn.IFNA":"IFNA","_xlfn.IFERROR":"IFERROR","_xlfn.IMCOSH":"IMCOSH","_xlfn.IMCOT":"IMCOT","_xlfn.IMCSC":"IMCSC","_xlfn.IMCSCH":"IMCSCH","_xlfn.IMSEC":"IMSEC","_xlfn.IMSECH":"IMSECH","_xlfn.IMSINH":"IMSINH","_xlfn.IMTAN":"IMTAN","_xlfn.ISFORMULA":"ISFORMULA","_xlfn.ISO.CEILING":"ISO.CEILING","_xlfn.ISOWEEKNUM":"ISOWEEKNUM","_xlfn.LOGNORM.DIST":"LOGNORM.DIST","_xlfn.LOGNORM.INV":"LOGNORM.INV","_xlfn.MODE.MULT":"MODE.MULT","_xlfn.MODE.SNGL":"MODE.SNGL","_xlfn.MUNIT":"MUNIT","_xlfn.NEGBINOM.DIST":"NEGBINOM.DIST","_xlfn.NETWORKDAYS.INTL":"NETWORKDAYS.INTL","_xlfn.NIGBINOM":"NIGBINOM","_xlfn.NORM.DIST":"NORM.DIST","_xlfn.NORM.INV":"NORM.INV","_xlfn.NORM.S.DIST":"NORM.S.DIST","_xlfn.NORM.S.INV":"NORM.S.INV","_xlfn.NUMBERVALUE":"NUMBERVALUE","_xlfn.PDURATION":"PDURATION","_xlfn.PERCENTILE.EXC":"PERCENTILE.EXC","_xlfn.PERCENTILE.INC":"PERCENTILE.INC","_xlfn.PERCENTRANK.EXC":"PERCENTRANK.EXC","_xlfn.PERCENTRANK.INC":"PERCENTRANK.INC","_xlfn.PERMUTATIONA":"PERMUTATIONA","_xlfn.PHI":"PHI","_xlfn.POISSON.DIST":"POISSON.DIST","_xlfn.QUARTILE.EXC":"QUARTILE.EXC","_xlfn.QUARTILE.INC":"QUARTILE.INC","_xlfn.QUERYSTRING":"QUERYSTRING","_xlfn.RANK.AVG":"RANK.AVG","_xlfn.RANK.EQ":"RANK.EQ","_xlfn.RRI":"RRI","_xlfn.SEC":"SEC","_xlfn.SECH":"SECH","_xlfn.SHEET":"SHEET","_xlfn.SHEETS":"SHEETS","_xlfn.SKEW.P":"SKEW.P","_xlfn.STDEV.P":"STDEV.P","_xlfn.STDEV.S":"STDEV.S","_xlfn.SUMIFS":"SUMIFS","_xlfn.T.DIST":"T.DIST","_xlfn.T.DIST.2T":"T.DIST.2T","_xlfn.T.DIST.RT":"T.DIST.RT","_xlfn.T.INV":"T.INV","_xlfn.T.INV.2T":"T.INV.2T","_xlfn.T.TEST":"T.TEST","_xlfn.UNICHAR":"UNICHAR","_xlfn.UNICODE":"UNICODE","_xlfn.VAR.P":"VAR.P","_xlfn.VAR.S":"VAR.S","_xlfn.WEBSERVICE":"WEBSERVICE","_xlfn.WEIBULL.DIST":"WEIBULL.DIST","_xlfn.WORKDAY.INTL":"WORKDAY.INTL","_xlfn.XOR":"XOR","_xlfn.Z.TEST":"Z.TEST"};var RecordEnum={6:{n:"Formula",f:parse_Formula},10:{n:"EOF",f:parse_EOF},12:{n:"CalcCount",f:parse_CalcCount},13:{n:"CalcMode",f:parse_CalcMode},14:{n:"CalcPrecision",f:parse_CalcPrecision},15:{n:"CalcRefMode",f:parse_CalcRefMode},16:{n:"CalcDelta",f:parse_CalcDelta},17:{n:"CalcIter",f:parse_CalcIter},18:{n:"Protect",f:parse_Protect},19:{n:"Password",f:parse_Password},20:{n:"Header",f:parse_Header},21:{n:"Footer",f:parse_Footer},23:{n:"ExternSheet",f:parse_ExternSheet},24:{n:"Lbl",f:parse_Lbl},25:{n:"WinProtect",f:parse_WinProtect},26:{n:"VerticalPageBreaks",f:parse_VerticalPageBreaks},27:{n:"HorizontalPageBreaks",f:parse_HorizontalPageBreaks},28:{n:"Note",f:parse_Note},29:{n:"Selection",f:parse_Selection},34:{n:"Date1904",f:parse_Date1904},35:{n:"ExternName",f:parse_ExternName},38:{n:"LeftMargin",f:parse_LeftMargin},39:{n:"RightMargin",f:parse_RightMargin},40:{n:"TopMargin",f:parse_TopMargin},41:{n:"BottomMargin",f:parse_BottomMargin},42:{n:"PrintRowCol",f:parse_PrintRowCol},43:{n:"PrintGrid",f:parse_PrintGrid},47:{n:"FilePass",f:parse_FilePass},49:{n:"Font",f:parse_Font},51:{n:"PrintSize",f:parse_PrintSize},60:{n:"Continue",f:parse_Continue},61:{n:"Window1",f:parse_Window1},64:{n:"Backup",f:parse_Backup},65:{n:"Pane",f:parse_Pane},66:{n:"CodePage",f:parse_CodePage},77:{n:"Pls",f:parse_Pls},80:{n:"DCon",f:parse_DCon},81:{n:"DConRef",f:parse_DConRef},82:{n:"DConName",f:parse_DConName},85:{n:"DefColWidth",f:parse_DefColWidth},89:{n:"XCT",f:parse_XCT},90:{n:"CRN",f:parse_CRN},91:{n:"FileSharing",f:parse_FileSharing},92:{n:"WriteAccess",f:parse_WriteAccess},93:{n:"Obj",f:parse_Obj},94:{n:"Uncalced",f:parse_Uncalced},95:{n:"CalcSaveRecalc",f:parse_CalcSaveRecalc},96:{n:"Template",f:parse_Template},97:{n:"Intl",f:parse_Intl},99:{n:"ObjProtect",f:parse_ObjProtect},125:{n:"ColInfo",f:parse_ColInfo},128:{n:"Guts",f:parse_Guts},129:{n:"WsBool",f:parse_WsBool},130:{n:"GridSet",f:parse_GridSet},131:{n:"HCenter",f:parse_HCenter},132:{n:"VCenter",f:parse_VCenter},133:{n:"BoundSheet8",f:parse_BoundSheet8},134:{n:"WriteProtect",f:parse_WriteProtect},140:{n:"Country",f:parse_Country},141:{n:"HideObj",f:parse_HideObj},144:{n:"Sort",f:parse_Sort},146:{n:"Palette",f:parse_Palette},151:{n:"Sync",f:parse_Sync},152:{n:"LPr",f:parse_LPr},153:{n:"DxGCol",f:parse_DxGCol},154:{n:"FnGroupName",f:parse_FnGroupName},155:{n:"FilterMode",f:parse_FilterMode},156:{n:"BuiltInFnGroupCount",f:parse_BuiltInFnGroupCount},157:{n:"AutoFilterInfo",f:parse_AutoFilterInfo},158:{n:"AutoFilter",f:parse_AutoFilter},160:{n:"Scl",f:parse_Scl},161:{n:"Setup",f:parse_Setup},174:{n:"ScenMan",f:parse_ScenMan},175:{n:"SCENARIO",f:parse_SCENARIO},176:{n:"SxView",f:parse_SxView},177:{n:"Sxvd",f:parse_Sxvd},178:{n:"SXVI",f:parse_SXVI},180:{n:"SxIvd",f:parse_SxIvd},181:{n:"SXLI",f:parse_SXLI},182:{n:"SXPI",f:parse_SXPI},184:{n:"DocRoute",f:parse_DocRoute},185:{n:"RecipName",f:parse_RecipName},189:{n:"MulRk",f:parse_MulRk},190:{n:"MulBlank",f:parse_MulBlank},193:{n:"Mms",f:parse_Mms},197:{n:"SXDI",f:parse_SXDI},198:{n:"SXDB",f:parse_SXDB},199:{n:"SXFDB",f:parse_SXFDB},200:{n:"SXDBB",f:parse_SXDBB},201:{n:"SXNum",f:parse_SXNum},202:{n:"SxBool",f:parse_SxBool},203:{n:"SxErr",f:parse_SxErr},204:{n:"SXInt",f:parse_SXInt},205:{n:"SXString",f:parse_SXString},206:{n:"SXDtr",f:parse_SXDtr},207:{n:"SxNil",f:parse_SxNil},208:{n:"SXTbl",f:parse_SXTbl},209:{n:"SXTBRGIITM",f:parse_SXTBRGIITM},210:{n:"SxTbpg",f:parse_SxTbpg},211:{n:"ObProj",f:parse_ObProj},213:{n:"SXStreamID",f:parse_SXStreamID},215:{n:"DBCell",f:parse_DBCell},216:{n:"SXRng",f:parse_SXRng},217:{n:"SxIsxoper",f:parse_SxIsxoper},218:{n:"BookBool",f:parse_BookBool},220:{n:"DbOrParamQry",f:parse_DbOrParamQry},221:{n:"ScenarioProtect",f:parse_ScenarioProtect},222:{n:"OleObjectSize",f:parse_OleObjectSize},224:{n:"XF",f:parse_XF},225:{n:"InterfaceHdr",f:parse_InterfaceHdr},226:{n:"InterfaceEnd",f:parse_InterfaceEnd},227:{n:"SXVS",f:parse_SXVS},229:{n:"MergeCells",f:parse_MergeCells},233:{n:"BkHim",f:parse_BkHim},235:{n:"MsoDrawingGroup",f:parse_MsoDrawingGroup},236:{n:"MsoDrawing",f:parse_MsoDrawing},237:{n:"MsoDrawingSelection",f:parse_MsoDrawingSelection},239:{n:"PhoneticInfo",f:parse_PhoneticInfo},240:{n:"SxRule",f:parse_SxRule},241:{n:"SXEx",f:parse_SXEx},242:{n:"SxFilt",f:parse_SxFilt},244:{n:"SxDXF",f:parse_SxDXF},245:{n:"SxItm",f:parse_SxItm},246:{n:"SxName",f:parse_SxName},247:{n:"SxSelect",f:parse_SxSelect},248:{n:"SXPair",f:parse_SXPair},249:{n:"SxFmla",f:parse_SxFmla},251:{n:"SxFormat",f:parse_SxFormat},252:{n:"SST",f:parse_SST},253:{n:"LabelSst",f:parse_LabelSst},255:{n:"ExtSST",f:parse_ExtSST},256:{n:"SXVDEx",f:parse_SXVDEx},259:{n:"SXFormula",f:parse_SXFormula},290:{n:"SXDBEx",f:parse_SXDBEx},311:{n:"RRDInsDel",f:parse_RRDInsDel},312:{n:"RRDHead",f:parse_RRDHead},315:{n:"RRDChgCell",f:parse_RRDChgCell},317:{n:"RRTabId",f:parse_RRTabId},318:{n:"RRDRenSheet",f:parse_RRDRenSheet},319:{n:"RRSort",f:parse_RRSort},320:{n:"RRDMove",f:parse_RRDMove},330:{n:"RRFormat",f:parse_RRFormat},331:{n:"RRAutoFmt",f:parse_RRAutoFmt},333:{n:"RRInsertSh",f:parse_RRInsertSh},334:{n:"RRDMoveBegin",f:parse_RRDMoveBegin},335:{n:"RRDMoveEnd",f:parse_RRDMoveEnd},336:{n:"RRDInsDelBegin",f:parse_RRDInsDelBegin},337:{n:"RRDInsDelEnd",f:parse_RRDInsDelEnd},338:{n:"RRDConflict",f:parse_RRDConflict},339:{n:"RRDDefName",f:parse_RRDDefName},340:{n:"RRDRstEtxp",f:parse_RRDRstEtxp},351:{n:"LRng",f:parse_LRng},352:{n:"UsesELFs",f:parse_UsesELFs},353:{n:"DSF",f:parse_DSF},401:{n:"CUsr",f:parse_CUsr},402:{n:"CbUsr",f:parse_CbUsr},403:{n:"UsrInfo",f:parse_UsrInfo},404:{n:"UsrExcl",f:parse_UsrExcl},405:{n:"FileLock",f:parse_FileLock},406:{n:"RRDInfo",f:parse_RRDInfo},407:{n:"BCUsrs",f:parse_BCUsrs},408:{n:"UsrChk",f:parse_UsrChk},425:{n:"UserBView",f:parse_UserBView},426:{n:"UserSViewBegin",f:parse_UserSViewBegin},427:{n:"UserSViewEnd",f:parse_UserSViewEnd},428:{n:"RRDUserView",f:parse_RRDUserView},429:{n:"Qsi",f:parse_Qsi},430:{n:"SupBook",f:parse_SupBook},431:{n:"Prot4Rev",f:parse_Prot4Rev},432:{n:"CondFmt",f:parse_CondFmt},433:{n:"CF",f:parse_CF},434:{n:"DVal",f:parse_DVal},437:{n:"DConBin",f:parse_DConBin},438:{n:"TxO",f:parse_TxO},439:{n:"RefreshAll",f:parse_RefreshAll},440:{n:"HLink",f:parse_HLink},441:{n:"Lel",f:parse_Lel},442:{n:"CodeName",f:parse_CodeName},443:{n:"SXFDBType",f:parse_SXFDBType},444:{n:"Prot4RevPass",f:parse_Prot4RevPass},445:{n:"ObNoMacros",f:parse_ObNoMacros},446:{n:"Dv",f:parse_Dv},448:{n:"Excel9File",f:parse_Excel9File},449:{n:"RecalcId",f:parse_RecalcId,r:2},450:{n:"EntExU2",f:parse_EntExU2},512:{n:"Dimensions",f:parse_Dimensions},513:{n:"Blank",f:parse_Blank},515:{n:"Number",f:parse_Number},516:{n:"Label",f:parse_Label},517:{n:"BoolErr",f:parse_BoolErr},519:{n:"String",f:parse_String},520:{n:"Row",f:parse_Row},523:{n:"Index",f:parse_Index},545:{n:"Array",f:parse_Array},549:{n:"DefaultRowHeight",f:parse_DefaultRowHeight},566:{n:"Table",f:parse_Table},574:{n:"Window2",f:parse_Window2},638:{n:"RK",f:parse_RK},659:{n:"Style",f:parse_Style},1048:{n:"BigName",f:parse_BigName},1054:{n:"Format",f:parse_Format},1084:{n:"ContinueBigName",f:parse_ContinueBigName},1212:{n:"ShrFmla",f:parse_ShrFmla},2048:{n:"HLinkTooltip",f:parse_HLinkTooltip},2049:{n:"WebPub",f:parse_WebPub},2050:{n:"QsiSXTag",f:parse_QsiSXTag},2051:{n:"DBQueryExt",f:parse_DBQueryExt},2052:{n:"ExtString",f:parse_ExtString},2053:{n:"TxtQry",f:parse_TxtQry},2054:{n:"Qsir",f:parse_Qsir},2055:{n:"Qsif",f:parse_Qsif},2056:{n:"RRDTQSIF",f:parse_RRDTQSIF},2057:{n:"BOF",f:parse_BOF},2058:{n:"OleDbConn",f:parse_OleDbConn},2059:{n:"WOpt",f:parse_WOpt},2060:{n:"SXViewEx",f:parse_SXViewEx},2061:{n:"SXTH",f:parse_SXTH},2062:{n:"SXPIEx",f:parse_SXPIEx},2063:{n:"SXVDTEx",f:parse_SXVDTEx},2064:{n:"SXViewEx9",f:parse_SXViewEx9},2066:{n:"ContinueFrt",f:parse_ContinueFrt},2067:{n:"RealTimeData",f:parse_RealTimeData},2128:{n:"ChartFrtInfo",f:parse_ChartFrtInfo},2129:{n:"FrtWrapper",f:parse_FrtWrapper},2130:{n:"StartBlock",f:parse_StartBlock},2131:{n:"EndBlock",f:parse_EndBlock},2132:{n:"StartObject",f:parse_StartObject},2133:{n:"EndObject",f:parse_EndObject},2134:{n:"CatLab",f:parse_CatLab},2135:{n:"YMult",f:parse_YMult},2136:{n:"SXViewLink",f:parse_SXViewLink},2137:{n:"PivotChartBits",f:parse_PivotChartBits},2138:{n:"FrtFontList",f:parse_FrtFontList},2146:{n:"SheetExt",f:parse_SheetExt},2147:{n:"BookExt",f:parse_BookExt,r:12},2148:{n:"SXAddl",f:parse_SXAddl},2149:{n:"CrErr",f:parse_CrErr},2150:{n:"HFPicture",f:parse_HFPicture},2151:{n:"FeatHdr",f:parse_FeatHdr},2152:{n:"Feat",f:parse_Feat},2154:{n:"DataLabExt",f:parse_DataLabExt},2155:{n:"DataLabExtContents",f:parse_DataLabExtContents},2156:{n:"CellWatch",f:parse_CellWatch},2161:{n:"FeatHdr11",f:parse_FeatHdr11},2162:{n:"Feature11",f:parse_Feature11},2164:{n:"DropDownObjIds",f:parse_DropDownObjIds},2165:{n:"ContinueFrt11",f:parse_ContinueFrt11},2166:{n:"DConn",f:parse_DConn},2167:{n:"List12",f:parse_List12},2168:{n:"Feature12",f:parse_Feature12},2169:{n:"CondFmt12",f:parse_CondFmt12},2170:{n:"CF12",f:parse_CF12},2171:{n:"CFEx",f:parse_CFEx},2172:{n:"XFCRC",f:parse_XFCRC},2173:{n:"XFExt",f:parse_XFExt},2174:{n:"AutoFilter12",f:parse_AutoFilter12},2175:{n:"ContinueFrt12",f:parse_ContinueFrt12},2180:{n:"MDTInfo",f:parse_MDTInfo},2181:{n:"MDXStr",f:parse_MDXStr},2182:{n:"MDXTuple",f:parse_MDXTuple},2183:{n:"MDXSet",f:parse_MDXSet},2184:{n:"MDXProp",f:parse_MDXProp},2185:{n:"MDXKPI",f:parse_MDXKPI},2186:{n:"MDB",f:parse_MDB},2187:{n:"PLV",f:parse_PLV},2188:{n:"Compat12",f:parse_Compat12,r:12},2189:{n:"DXF",f:parse_DXF},2190:{n:"TableStyles",f:parse_TableStyles,r:12},2191:{n:"TableStyle",f:parse_TableStyle},2192:{n:"TableStyleElement",f:parse_TableStyleElement},2194:{n:"StyleExt",f:parse_StyleExt},2195:{n:"NamePublish",f:parse_NamePublish},2196:{n:"NameCmt",f:parse_NameCmt},2197:{n:"SortData",f:parse_SortData},2198:{n:"Theme",f:parse_Theme},2199:{n:"GUIDTypeLib",f:parse_GUIDTypeLib},2200:{n:"FnGrp12",f:parse_FnGrp12},2201:{n:"NameFnGrp12",f:parse_NameFnGrp12},2202:{n:"MTRSettings",f:parse_MTRSettings,r:12},2203:{n:"CompressPictures",f:parse_CompressPictures},2204:{n:"HeaderFooter",f:parse_HeaderFooter},2205:{n:"CrtLayout12",f:parse_CrtLayout12},2206:{n:"CrtMlFrt",f:parse_CrtMlFrt},2207:{n:"CrtMlFrtContinue",f:parse_CrtMlFrtContinue},2211:{n:"ForceFullCalculation",f:parse_ForceFullCalculation},2212:{n:"ShapePropsStream",f:parse_ShapePropsStream},2213:{n:"TextPropsStream",f:parse_TextPropsStream},2214:{n:"RichTextStream",f:parse_RichTextStream},2215:{n:"CrtLayout12A",f:parse_CrtLayout12A},4097:{n:"Units",f:parse_Units},4098:{n:"Chart",f:parse_Chart},4099:{n:"Series",f:parse_Series},4102:{n:"DataFormat",f:parse_DataFormat},4103:{n:"LineFormat",f:parse_LineFormat},4105:{n:"MarkerFormat",f:parse_MarkerFormat},4106:{n:"AreaFormat",f:parse_AreaFormat},4107:{n:"PieFormat",f:parse_PieFormat},4108:{n:"AttachedLabel",f:parse_AttachedLabel},4109:{n:"SeriesText",f:parse_SeriesText},4116:{n:"ChartFormat",f:parse_ChartFormat},4117:{n:"Legend",f:parse_Legend},4118:{n:"SeriesList",f:parse_SeriesList},4119:{n:"Bar",f:parse_Bar},4120:{n:"Line",f:parse_Line},4121:{n:"Pie",f:parse_Pie},4122:{n:"Area",f:parse_Area},4123:{n:"Scatter",f:parse_Scatter},4124:{n:"CrtLine",f:parse_CrtLine},4125:{n:"Axis",f:parse_Axis},4126:{n:"Tick",f:parse_Tick},4127:{n:"ValueRange",f:parse_ValueRange},4128:{n:"CatSerRange",f:parse_CatSerRange},4129:{n:"AxisLine",f:parse_AxisLine},4130:{n:"CrtLink",f:parse_CrtLink},4132:{n:"DefaultText",f:parse_DefaultText},4133:{n:"Text",f:parse_Text},4134:{n:"FontX",f:parse_FontX},4135:{n:"ObjectLink",f:parse_ObjectLink},4146:{n:"Frame",f:parse_Frame},4147:{n:"Begin",f:parse_Begin},4148:{n:"End",f:parse_End},4149:{n:"PlotArea",f:parse_PlotArea},4154:{n:"Chart3d",f:parse_Chart3d},4156:{n:"PicF",f:parse_PicF},4157:{n:"DropBar",f:parse_DropBar},4158:{n:"Radar",f:parse_Radar},4159:{n:"Surf",f:parse_Surf},4160:{n:"RadarArea",f:parse_RadarArea},4161:{n:"AxisParent",f:parse_AxisParent},4163:{n:"LegendException",f:parse_LegendException},4164:{n:"ShtProps",f:parse_ShtProps},4165:{n:"SerToCrt",f:parse_SerToCrt},4166:{n:"AxesUsed",f:parse_AxesUsed},4168:{n:"SBaseRef",f:parse_SBaseRef},4170:{n:"SerParent",f:parse_SerParent},4171:{n:"SerAuxTrend",f:parse_SerAuxTrend},4174:{n:"IFmtRecord",f:parse_IFmtRecord},4175:{n:"Pos",f:parse_Pos},4176:{n:"AlRuns",f:parse_AlRuns},4177:{n:"BRAI",f:parse_BRAI},4187:{n:"SerAuxErrBar",f:parse_SerAuxErrBar},4188:{n:"ClrtClient",f:parse_ClrtClient},4189:{n:"SerFmt",f:parse_SerFmt},4191:{n:"Chart3DBarShape",f:parse_Chart3DBarShape},4192:{n:"Fbi",f:parse_Fbi},4193:{n:"BopPop",f:parse_BopPop},4194:{n:"AxcExt",f:parse_AxcExt},4195:{n:"Dat",f:parse_Dat},4196:{n:"PlotGrowth",f:parse_PlotGrowth},4197:{n:"SIIndex",f:parse_SIIndex},4198:{n:"GelFrame",f:parse_GelFrame},4199:{n:"BopPopCustom",f:parse_BopPopCustom},4200:{n:"Fbi2",f:parse_Fbi2},22:{n:"ExternCount",f:parsenoop},126:{n:"RK",f:parsenoop},127:{n:"ImData",f:parsenoop},135:{n:"Addin",f:parsenoop},136:{n:"Edg",f:parsenoop},137:{n:"Pub",f:parsenoop},145:{n:"Sub",f:parsenoop},148:{n:"LHRecord",f:parsenoop},149:{n:"LHNGraph",f:parsenoop},150:{n:"Sound",f:parsenoop},169:{n:"CoordList",f:parsenoop},171:{n:"GCW",f:parsenoop},188:{n:"ShrFmla",f:parsenoop},194:{n:"AddMenu",f:parsenoop},195:{n:"DelMenu",f:parsenoop},214:{n:"RString",f:parsenoop},223:{n:"UDDesc",f:parsenoop},234:{n:"TabIdConf",f:parsenoop},354:{n:"XL5Modify",f:parsenoop},421:{n:"FileSharing2",f:parsenoop},536:{n:"Name",f:parsenoop},547:{n:"ExternName",f:parse_ExternName},561:{n:"Font",f:parsenoop},1030:{n:"Formula",f:parse_Formula},2157:{n:"FeatInfo",f:parsenoop},2163:{n:"FeatInfo11",f:parsenoop},2177:{n:"SXAddl12",f:parsenoop},2240:{n:"AutoWebPub",f:parsenoop},2241:{n:"ListObj",f:parsenoop},2242:{n:"ListField",f:parsenoop},2243:{n:"ListDV",f:parsenoop},2244:{n:"ListCondFmt",f:parsenoop},2245:{n:"ListCF",f:parsenoop},2246:{n:"FMQry",f:parsenoop},2247:{n:"FMSQry",f:parsenoop},2248:{n:"PLV",f:parsenoop},2249:{n:"LnExt",f:parsenoop},2250:{n:"MkrExt",f:parsenoop},2251:{n:"CrtCoopt",f:parsenoop},0:{}};var CountryEnum={1:"US",2:"CA",3:"",7:"RU",20:"EG",30:"GR",31:"NL",32:"BE",33:"FR",34:"ES",36:"HU",39:"IT",41:"CH",43:"AT",44:"GB",45:"DK",46:"SE",47:"NO",48:"PL",49:"DE",52:"MX",55:"BR",61:"AU",64:"NZ",66:"TH",81:"JP",82:"KR",84:"VN",86:"CN",90:"TR",105:"JS",213:"DZ",216:"MA",218:"LY",351:"PT",354:"IS",358:"FI",420:"CZ",886:"TW",961:"LB",962:"JO",963:"SY",964:"IQ",965:"KW",966:"SA",971:"AE",972:"IL",974:"QA",981:"IR",65535:"US"};function fix_opts_func(defaults){return function fix_opts(opts){for(var i=0;i!=defaults.length;++i){var d=defaults[i];if(typeof opts[d[0]]==="undefined")opts[d[0]]=d[1];if(d[2]==="n")opts[d[0]]=Number(opts[d[0]])}}}var fixopts=fix_opts_func([["cellNF",false],["cellFormula",true],["sheetRows",0,"n"],["bookSheets",false],["bookProps",false],["bookFiles",false],["password",""],["WTF",false]]);function parse_compobj(obj){var v={};var o=obj.content;var l=28,m;m=__lpstr(o,l);l+=4+__readUInt32LE(o,l);v.UserType=m;m=__readUInt32LE(o,l);l+=4;switch(m){case 0:break;case 4294967295:case 4294967294:l+=4;break;default:if(m>400)throw new Error("Unsupported Clipboard: "+m.toString(16));l+=m}m=__lpstr(o,l);l+=m.length===0?0:5+m.length;v.Reserved1=m;if((m=__readUInt32LE(o,l))!==1907550708)return v;throw"Unsupported Unicode Extension"}function parse_xlscfb(cfb,options){if(!options)options={};fixopts(options);reset_cp();var CompObj=cfb.find("!CompObj");var Summary=cfb.find("!SummaryInformation");var Workbook=cfb.find("/Workbook");if(!Workbook)Workbook=cfb.find("/Book");var CompObjP,SummaryP,WorkbookP;function slurp(R,blob,length,opts){var l=length;var bufs=[];var d=blob.slice(blob.l,blob.l+l);if(opts.enc&&opts.enc.insitu_decrypt)switch(R.n){case"BOF":case"FilePass":case"FileLock":case"InterfaceHdr":case"RRDInfo":case"RRDHead":case"UsrExcl":break;default:if(d.length===0)break;opts.enc.insitu_decrypt(d)}bufs.push(d);blob.l+=l;var next=RecordEnum[__readUInt16LE(blob,blob.l)];while(next!=null&&next.n==="Continue"){l=__readUInt16LE(blob,blob.l+2);bufs.push(blob.slice(blob.l+4,blob.l+4+l));blob.l+=4+l;next=RecordEnum[__readUInt16LE(blob,blob.l)]}var b=bconcat(bufs);prep_blob(b,0);var ll=0;b.lens=[];for(var j=0;j<bufs.length;++j){b.lens.push(ll);ll+=bufs[j].length}return R.f(b,b.length,opts)}function safe_format_xf(p,opts){if(!p.XF)return;try{var fmtid=p.XF.ifmt||0;if(fmtid===0){if(p.t==="n"){if((p.v|0)===p.v)p.w=SSF._general_int(p.v);else p.w=SSF._general_num(p.v)}else p.w=SSF._general(p.v)}else p.w=SSF.format(fmtid,p.v);if(opts.cellNF)p.z=SSF._table[fmtid]}catch(e){if(opts.WTF)throw e}}function make_cell(val,ixfe,t){return{v:val,ixfe:ixfe,t:t}}function parse_workbook(blob,options){var wb={opts:{}};var Sheets={};var out={};var Directory={};var found_sheet=false;var range={};var last_formula=null;var sst=[];var cur_sheet="";var Preamble={};var lastcell,last_cell,cc,cmnt,rng,rngC,rngR;var shared_formulae={};var array_formulae=[];var temp_val;var country;var cell_valid=true;var XFs=[];var addline=function addline(cell,line,options){if(!cell_valid)return;lastcell=cell;last_cell=encode_cell(cell);if(range.s){if(cell.r<range.s.r)range.s.r=cell.r;if(cell.c<range.s.c)range.s.c=cell.c}if(range.e){if(cell.r+1>range.e.r)range.e.r=cell.r+1;if(cell.c+1>range.e.c)range.e.c=cell.c+1}if(options.sheetRows&&lastcell.r>=options.sheetRows)cell_valid=false;else out[last_cell]=line};var opts={enc:false,sbcch:0,snames:[],sharedf:shared_formulae,arrayf:array_formulae,rrtabid:[],lastuser:"",biff:8,codepage:0,winlocked:0,wtf:false};if(options.password)opts.password=options.password;var mergecells=[];var objects=[];var supbooks=[[]];var sbc=0,sbci=0,sbcli=0;supbooks.SheetNames=opts.snames;supbooks.sharedf=opts.sharedf;supbooks.arrayf=opts.arrayf;var last_Rn="";var file_depth=0;while(blob.l<blob.length-1){var s=blob.l;var RecordType=blob.read_shift(2);if(RecordType===0&&last_Rn==="EOF")break;var length=blob.l===blob.length?0:blob.read_shift(2),y;var R=RecordEnum[RecordType];if(R&&R.f){if(options.bookSheets){if(last_Rn==="BoundSheet8"&&R.n!=="BoundSheet8")break}last_Rn=R.n;if(R.r===2||R.r==12){var rt=blob.read_shift(2);length-=2;if(!opts.enc&&rt!==RecordType)throw"rt mismatch";if(R.r==12){blob.l+=10;length-=10}}var val;if(R.n==="EOF")val=R.f(blob,length,opts);else val=slurp(R,blob,length,opts);var Rn=R.n;if(opts.biff===5)switch(Rn){case"Lbl":Rn="Label";break}switch(Rn){case"Date1904":wb.opts.Date1904=val;break;case"WriteProtect":wb.opts.WriteProtect=true;break;case"FilePass":if(!opts.enc)blob.l=0;opts.enc=val;if(opts.WTF)console.error(val);if(!options.password)throw new Error("File is password-protected");if(val.Type!==0)throw new Error("Encryption scheme unsupported");if(!val.valid)throw new Error("Password is incorrect");break;case"WriteAccess":opts.lastuser=val;break;case"FileSharing":break;case"CodePage":if(val===21010)val=1200;opts.codepage=val;set_cp(val);break;case"RRTabId":opts.rrtabid=val;break;case"WinProtect":opts.winlocked=val;break;case"Template":break;case"RefreshAll":wb.opts.RefreshAll=val;break;case"BookBool":break;case"UsesELFs":break;case"MTRSettings":{if(val[0]&&val[1])throw"Unsupported threads: "+val}break;case"CalcCount":wb.opts.CalcCount=val;break;case"CalcDelta":wb.opts.CalcDelta=val;break;case"CalcIter":wb.opts.CalcIter=val;break;case"CalcMode":wb.opts.CalcMode=val;break;case"CalcPrecision":wb.opts.CalcPrecision=val;break;case"CalcSaveRecalc":wb.opts.CalcSaveRecalc=val;break;case"CalcRefMode":opts.CalcRefMode=val;break;case"Uncalced":break;case"ForceFullCalculation":wb.opts.FullCalc=val;break;case"WsBool":break;case"XF":XFs.push(val);break;case"ExtSST":break;case"BookExt":break;case"RichTextStream":break;case"BkHim":break;case"SupBook":supbooks[++sbc]=[val];sbci=0;break;case"ExternName":supbooks[sbc][++sbci]=val;break;case"Index":break;case"Lbl":supbooks[0][++sbcli]=val;break;case"ExternSheet":supbooks[sbc]=supbooks[sbc].concat(val);sbci+=val.length;break;case"Protect":out["!protect"]=val;break;case"Password":if(val!==0&&opts.WTF)console.error("Password verifier: "+val);break;case"Prot4Rev":case"Prot4RevPass":break;case"BoundSheet8":{Directory[val.pos]=val;opts.snames.push(val.name)}break;case"EOF":{if(--file_depth)break;if(range.e){out["!range"]=range;if(range.e.r>0&&range.e.c>0){range.e.r--;range.e.c--;out["!ref"]=encode_range(range);range.e.r++;range.e.c++}if(mergecells.length>0)out["!merges"]=mergecells;if(objects.length>0)out["!objects"]=objects}if(cur_sheet==="")Preamble=out;else Sheets[cur_sheet]=out;out={}}break;case"BOF":{if(val.BIFFVer===1280)opts.biff=5;if(file_depth++)break;cell_valid=true;out={};cur_sheet=(Directory[s]||{name:""}).name;mergecells=[];objects=[]}break;case"Number":{temp_val={ixfe:val.ixfe,XF:XFs[val.ixfe],v:val.val,t:"n"};if(temp_val.XF)safe_format_xf(temp_val,options);addline({c:val.c,r:val.r},temp_val,options)}break;case"BoolErr":{temp_val={ixfe:val.ixfe,XF:XFs[val.ixfe],v:val.val,t:val.t};if(temp_val.XF)safe_format_xf(temp_val,options);addline({c:val.c,r:val.r},temp_val,options)}break;case"RK":{temp_val={ixfe:val.ixfe,XF:XFs[val.ixfe],v:val.rknum,t:"n"};if(temp_val.XF)safe_format_xf(temp_val,options);addline({c:val.c,r:val.r},temp_val,options)}break;case"MulRk":{for(var j=val.c;j<=val.C;++j){var ixfe=val.rkrec[j-val.c][0];temp_val={ixfe:ixfe,XF:XFs[ixfe],v:val.rkrec[j-val.c][1],t:"n"};if(temp_val.XF)safe_format_xf(temp_val,options);addline({c:j,r:val.r},temp_val,options)}}break;case"Formula":{switch(val.val){case"String":last_formula=val;break;case"Array Formula":throw"Array Formula unsupported";default:temp_val={v:val.val,ixfe:val.cell.ixfe,t:val.tt};temp_val.XF=XFs[temp_val.ixfe];if(options.cellFormula)temp_val.f="="+stringify_formula(val.formula,range,val.cell,supbooks,opts);if(temp_val.XF)safe_format_xf(temp_val,options);addline(val.cell,temp_val,options);last_formula=val}}break;case"String":{if(last_formula){last_formula.val=val;temp_val={v:last_formula.val,ixfe:last_formula.cell.ixfe,t:"s"};temp_val.XF=XFs[temp_val.ixfe];if(options.cellFormula)temp_val.f="="+stringify_formula(last_formula.formula,range,last_formula.cell,supbooks,opts);if(temp_val.XF)safe_format_xf(temp_val,options);addline(last_formula.cell,temp_val,options);last_formula=null}}break;case"Array":{array_formulae.push(val)}break;case"ShrFmla":{if(!cell_valid)break;shared_formulae[encode_cell(last_formula.cell)]=val[0]}break;case"LabelSst":temp_val=make_cell(sst[val.isst].t,val.ixfe,"s");temp_val.XF=XFs[temp_val.ixfe];if(temp_val.XF)safe_format_xf(temp_val,options);addline({c:val.c,r:val.r},temp_val,options);break;case"Label":temp_val=make_cell(val.val,val.ixfe,"s");temp_val.XF=XFs[temp_val.ixfe];
25801 if(temp_val.XF)safe_format_xf(temp_val,options);addline({c:val.c,r:val.r},temp_val,options);break;case"Dimensions":{if(file_depth===1)range=val}break;case"SST":{sst=val}break;case"Format":{SSF.load(val[1],val[0])}break;case"MergeCells":mergecells=mergecells.concat(val);break;case"Obj":objects[val.cmo[0]]=opts.lastobj=val;break;case"TxO":opts.lastobj.TxO=val;break;case"HLink":{for(rngR=val[0].s.r;rngR<=val[0].e.r;++rngR)for(rngC=val[0].s.c;rngC<=val[0].e.c;++rngC)if(out[encode_cell({c:rngC,r:rngR})])out[encode_cell({c:rngC,r:rngR})].l=val[1]}break;case"HLinkTooltip":{for(rngR=val[0].s.r;rngR<=val[0].e.r;++rngR)for(rngC=val[0].s.c;rngC<=val[0].e.c;++rngC)if(out[encode_cell({c:rngC,r:rngR})])out[encode_cell({c:rngC,r:rngR})].l.tooltip=val[1]}break;case"Note":{if(opts.biff===5)break;cc=out[encode_cell(val[0])];var noteobj=objects[val[2]];if(!cc)break;if(!cc.c)cc.c=[];cmnt={a:val[1],t:noteobj.TxO.t};cc.c.push(cmnt)}break;case"NameCmt":break;default:switch(R.n){case"Header":break;case"Footer":break;case"HCenter":break;case"VCenter":break;case"Pls":break;case"Setup":break;case"DefColWidth":break;case"GCW":break;case"LHRecord":break;case"ColInfo":break;case"Row":break;case"DBCell":break;case"MulBlank":break;case"EntExU2":break;case"SxView":break;case"Sxvd":break;case"SXVI":break;case"SXVDEx":break;case"SxIvd":break;case"SXDI":break;case"SXLI":break;case"SXEx":break;case"QsiSXTag":break;case"Selection":break;case"Feat":break;case"FeatHdr":case"FeatHdr11":break;case"Feature11":case"Feature12":case"List12":break;case"Blank":break;case"Country":country=val;break;case"RecalcId":break;case"DefaultRowHeight":case"DxGCol":break;case"Fbi":case"Fbi2":case"GelFrame":break;case"Font":break;case"XFCRC":break;case"XFExt":break;case"Style":break;case"StyleExt":break;case"Palette":break;case"ClrtClient":break;case"Theme":break;case"ScenarioProtect":break;case"ObjProtect":break;case"CondFmt12":break;case"Table":break;case"TableStyles":break;case"TableStyle":break;case"TableStyleElement":break;case"SXStreamID":break;case"SXVS":break;case"DConRef":break;case"SXAddl":break;case"DConName":break;case"SXPI":break;case"SxFormat":break;case"SxSelect":break;case"SxRule":break;case"SxFilt":break;case"SxItm":break;case"SxDXF":break;case"ScenMan":break;case"DCon":break;case"CellWatch":break;case"PrintRowCol":break;case"PrintGrid":break;case"PrintSize":break;case"XCT":break;case"CRN":break;case"Scl":{}break;case"SheetExt":{}break;case"SheetExtOptional":{}break;case"ObNoMacros":{}break;case"ObProj":{}break;case"CodeName":{}break;case"GUIDTypeLib":{}break;case"WOpt":break;case"PhoneticInfo":break;case"OleObjectSize":break;case"DXF":case"DXFN":case"DXFN12":case"DXFN12List":case"DXFN12NoCB":break;case"Dv":case"DVal":break;case"BRAI":case"Series":case"SeriesText":break;case"DConn":break;case"DbOrParamQry":break;case"DBQueryExt":break;case"IFmtRecord":break;case"CondFmt":case"CF":case"CF12":case"CFEx":break;case"Excel9File":break;case"Units":break;case"InterfaceHdr":case"Mms":case"InterfaceEnd":case"DSF":case"BuiltInFnGroupCount":case"Window1":case"Window2":case"HideObj":case"GridSet":case"Guts":case"UserBView":case"UserSViewBegin":case"UserSViewEnd":case"Pane":break;default:switch(R.n){case"Dat":case"Begin":case"End":case"StartBlock":case"EndBlock":case"Frame":case"Area":case"Axis":case"AxisLine":case"Tick":break;case"AxesUsed":case"CrtLayout12":case"CrtLayout12A":case"CrtLink":case"CrtLine":case"CrtMlFrt":break;case"LineFormat":case"AreaFormat":case"Chart":case"Chart3d":case"Chart3DBarShape":case"ChartFormat":case"ChartFrtInfo":break;case"PlotArea":case"PlotGrowth":break;case"SeriesList":case"SerParent":case"SerAuxTrend":break;case"DataFormat":case"SerToCrt":case"FontX":break;case"CatSerRange":case"AxcExt":case"SerFmt":break;case"ShtProps":break;case"DefaultText":case"Text":case"CatLab":break;case"DataLabExtContents":break;case"Legend":case"LegendException":break;case"Pie":case"Scatter":break;case"PieFormat":case"MarkerFormat":break;case"StartObject":case"EndObject":break;case"AlRuns":case"ObjectLink":break;case"SIIndex":break;case"AttachedLabel":break;case"Line":case"Bar":break;case"Surf":break;case"AxisParent":break;case"Pos":break;case"ValueRange":break;case"SXViewEx9":break;case"SXViewLink":break;case"PivotChartBits":break;case"SBaseRef":break;case"TextPropsStream":break;case"LnExt":break;case"MkrExt":break;case"CrtCoopt":break;case"Qsi":case"Qsif":case"Qsir":case"QsiSXTag":break;case"TxtQry":break;case"FilterMode":break;case"AutoFilter":case"AutoFilterInfo":break;case"AutoFilter12":break;case"DropDownObjIds":break;case"Sort":break;case"SortData":break;case"ShapePropsStream":break;case"MsoDrawing":case"MsoDrawingGroup":case"MsoDrawingSelection":break;case"ImData":break;case"WebPub":case"AutoWebPub":case"RightMargin":case"LeftMargin":case"TopMargin":case"BottomMargin":case"HeaderFooter":case"HFPicture":case"PLV":case"HorizontalPageBreaks":case"VerticalPageBreaks":case"Backup":case"CompressPictures":case"Compat12":break;case"Continue":case"ContinueFrt12":break;case"ExternCount":break;case"RString":break;case"TabIdConf":case"Radar":case"RadarArea":case"DropBar":case"Intl":case"CoordList":case"SerAuxErrBar":break;default:if(options.WTF)throw"Unrecognized Record "+R.n}}}}else blob.l+=length}var sheetnamesraw=Object.keys(Directory).sort(function(a,b){return Number(a)-Number(b)}).map(function(x){return Directory[x].name});var sheetnames=sheetnamesraw.slice();wb.Directory=sheetnamesraw;wb.SheetNames=sheetnamesraw;if(!options.bookSheets)wb.Sheets=Sheets;wb.Preamble=Preamble;wb.Strings=sst;wb.SSF=SSF.get_table();if(opts.enc)wb.Encryption=opts.enc;wb.Metadata={};if(country!==undefined)wb.Metadata.Country=country;return wb}if(CompObj)CompObjP=parse_compobj(CompObj);if(options.bookProps&&!options.bookSheets)WorkbookP={};else{if(Workbook)WorkbookP=parse_workbook(Workbook.content,options);else throw new Error("Cannot find Workbook stream")}parse_props(cfb);var props={};for(var y in cfb.Summary)props[y]=cfb.Summary[y];for(y in cfb.DocSummary)props[y]=cfb.DocSummary[y];WorkbookP.Props=WorkbookP.Custprops=props;if(options.bookFiles)WorkbookP.cfb=cfb;WorkbookP.CompObjP=CompObjP;return WorkbookP}function parse_props(cfb){var DSI=cfb.find("!DocumentSummaryInformation");if(DSI)try{cfb.DocSummary=parse_PropertySetStream(DSI,DocSummaryPIDDSI)}catch(e){}var SI=cfb.find("!SummaryInformation");if(SI)try{cfb.Summary=parse_PropertySetStream(SI,SummaryPIDSI)}catch(e){}}var encregex=/&[a-z]*;/g,coderegex=/_x([0-9a-fA-F]+)_/g;function coderepl(m,c){return _chr(parseInt(c,16))}function encrepl($$){return encodings[$$]}function unescapexml(s){if(s.indexOf("&")>-1)s=s.replace(encregex,encrepl);return s.indexOf("_")===-1?s:s.replace(coderegex,coderepl)}function parsexmlbool(value,tag){switch(value){case"1":case"true":case"TRUE":return true;default:return false}}function matchtag(f,g){return new RegExp("<"+f+'(?: xml:space="preserve")?>([^☃]*)</'+f+">",(g||"")+"m")}var entregex=/&#(\d+);/g;function entrepl($$,$1){return String.fromCharCode(parseInt($1,10))}function fixstr(str){return str.replace(entregex,entrepl)}var everted_BERR=evert(BERR);var magic_formats={"General Number":"General","General Date":SSF._table[22],"Long Date":"dddd, mmmm dd, yyyy","Medium Date":SSF._table[15],"Short Date":SSF._table[14],"Long Time":SSF._table[19],"Medium Time":SSF._table[18],"Short Time":SSF._table[20],Currency:'"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',Fixed:SSF._table[2],Standard:SSF._table[4],Percent:SSF._table[10],Scientific:SSF._table[11],"Yes/No":'"Yes";"Yes";"No";@',"True/False":'"True";"True";"False";@',"On/Off":'"Yes";"Yes";"No";@'};function xlml_format(format,value){var fmt=magic_formats[format]||unescapexml(format);if(fmt==="General")return SSF._general(value);return SSF.format(fmt,value)}function xlml_set_prop(Props,tag,val){switch(tag){case"Description":tag="Comments";break}Props[tag]=val}function xlml_set_custprop(Custprops,Rn,cp,val){switch((cp[0].match(/dt:dt="([\w.]+)"/)||["",""])[1]){case"boolean":val=parsexmlbool(val);break;case"i2":case"int":val=parseInt(val,10);break;case"r4":case"float":val=parseFloat(val);break;case"date":case"dateTime.tz":val=new Date(val);break;case"i8":case"string":case"fixed":case"uuid":case"bin.base64":break;default:throw"bad custprop:"+cp[0]}Custprops[unescapexml(Rn[3])]=val}function safe_format_xlml(cell,nf,o){try{if(nf==="General"){if(cell.t==="n"){if((cell.v|0)===cell.v)cell.w=SSF._general_int(cell.v);else cell.w=SSF._general_num(cell.v)}else cell.w=SSF._general(cell.v)}else cell.w=xlml_format(nf||"General",cell.v);if(o.cellNF)cell.z=magic_formats[nf]||nf||"General"}catch(e){if(o.WTF)throw e}}function parse_xlml_data(xml,ss,data,cell,base,styles,csty,o){var nf="General",sid=cell.StyleID;o=o||{};if(sid===undefined&&csty)sid=csty.StyleID;while(styles[sid]!==undefined){if(styles[sid].nf)nf=styles[sid].nf;if(!styles[sid].Parent)break;sid=styles[sid].Parent}switch(data.Type){case"Boolean":cell.t="b";cell.v=parsexmlbool(xml);break;case"String":cell.t="str";cell.r=fixstr(unescapexml(xml));cell.v=xml.indexOf("<")>-1?ss:cell.r;break;case"DateTime":cell.v=(Date.parse(xml)-new Date(Date.UTC(1899,11,30)))/(24*60*60*1e3);if(cell.v!==cell.v)cell.v=unescapexml(xml);else if(cell.v>=1&&cell.v<60)cell.v=cell.v-1;if(!nf||nf=="General")nf="yyyy-mm-dd";case"Number":if(cell.v===undefined)cell.v=+xml;if(!cell.t)cell.t="n";break;case"Error":cell.t="e";cell.v=xml;cell.w=xml;break;default:cell.t="s";cell.v=fixstr(ss);break}if(cell.t!=="e")safe_format_xlml(cell,nf,o);if(o.cellFormula!=null&&cell.Formula){cell.f=rc_to_a1(unescapexml(cell.Formula),base);cell.Formula=undefined}cell.ixfe=cell.StyleID!==undefined?cell.StyleID:"Default"}function xlml_clean_comment(comment){comment.t=comment.v;comment.v=comment.w=comment.ixfe=undefined}function xlml_normalize(d){if(has_buf&&Buffer.isBuffer(d))return d.toString("utf8");if(typeof d==="string")return d;throw"badf"}var xlmlregex=/<(\/?)([a-z0-9]*:|)(\w+)[^>]*>/gm;function parse_xlml_xml(d,opts){var str=xlml_normalize(d);var Rn;var state=[],tmp;var sheets={},sheetnames=[],cursheet={},sheetname="";var table={},cell={},row={},dtag,didx;var c=0,r=0;var refguess={s:{r:1e6,c:1e6},e:{r:0,c:0}};var styles={},stag={};var ss="",fidx=0;var mergecells=[];var Props={},Custprops={},pidx=0,cp={};var comments=[],comment={};var cstys=[],csty;while(Rn=xlmlregex.exec(str))switch(Rn[3]){case"Data":if(state[state.length-1][1])break;if(Rn[1]==="/")parse_xlml_data(str.slice(didx,Rn.index),ss,dtag,state[state.length-1][0]=="Comment"?comment:cell,{c:c,r:r},styles,cstys[c],opts);else{ss="";dtag=parsexmltag(Rn[0]);didx=Rn.index+Rn[0].length}break;case"Cell":if(Rn[1]==="/"){if(comments.length>0)cell.c=comments;if((!opts.sheetRows||opts.sheetRows>r)&&cell.v!==undefined)cursheet[encode_col(c)+encode_row(r)]=cell;if(cell.HRef){cell.l={Target:cell.HRef,tooltip:cell.HRefScreenTip};cell.HRef=cell.HRefScreenTip=undefined}if(cell.MergeAcross||cell.MergeDown){var cc=c+(parseInt(cell.MergeAcross,10)|0);var rr=r+(parseInt(cell.MergeDown,10)|0);mergecells.push({s:{c:c,r:r},e:{c:cc,r:rr}})}++c;if(cell.MergeAcross)c+=+cell.MergeAcross}else{cell=parsexmltagobj(Rn[0]);if(cell.Index)c=+cell.Index-1;if(c<refguess.s.c)refguess.s.c=c;if(c>refguess.e.c)refguess.e.c=c;if(Rn[0].substr(-2)==="/>")++c;comments=[]}break;case"Row":if(Rn[1]==="/"||Rn[0].substr(-2)==="/>"){if(r<refguess.s.r)refguess.s.r=r;if(r>refguess.e.r)refguess.e.r=r;if(Rn[0].substr(-2)==="/>"){row=parsexmltag(Rn[0]);if(row.Index)r=+row.Index-1}c=0;++r}else{row=parsexmltag(Rn[0]);if(row.Index)r=+row.Index-1}break;case"Worksheet":if(Rn[1]==="/"){if((tmp=state.pop())[0]!==Rn[3])throw"Bad state: "+tmp;sheetnames.push(sheetname);if(refguess.s.r<=refguess.e.r&&refguess.s.c<=refguess.e.c)cursheet["!ref"]=encode_range(refguess);if(mergecells.length)cursheet["!merges"]=mergecells;sheets[sheetname]=cursheet}else{refguess={s:{r:1e6,c:1e6},e:{r:0,c:0}};r=c=0;state.push([Rn[3],false]);tmp=parsexmltag(Rn[0]);sheetname=tmp.Name;cursheet={};mergecells=[]}break;case"Table":if(Rn[1]==="/"){if((tmp=state.pop())[0]!==Rn[3])throw"Bad state: "+tmp}else if(Rn[0].slice(-2)=="/>")break;else{table=parsexmltag(Rn[0]);state.push([Rn[3],false]);cstys=[]}break;case"Style":if(Rn[1]==="/")styles[stag.ID]=stag;else stag=parsexmltag(Rn[0]);break;case"NumberFormat":stag.nf=parsexmltag(Rn[0]).Format||"General";break;case"Column":if(state[state.length-1][0]!=="Table")break;csty=parsexmltag(Rn[0]);cstys[csty.Index-1||cstys.length]=csty;for(var i=0;i<+csty.Span;++i)cstys[cstys.length]=csty;break;case"NamedRange":break;case"NamedCell":break;case"B":break;case"I":break;case"U":break;case"S":break;case"Sub":break;case"Sup":break;case"Span":break;case"Border":break;case"Alignment":break;case"Borders":break;case"Font":if(Rn[0].substr(-2)==="/>")break;else if(Rn[1]==="/")ss+=str.slice(fidx,Rn.index);else fidx=Rn.index+Rn[0].length;break;case"Interior":break;case"Protection":break;case"Author":case"Title":case"Description":case"Created":case"Keywords":case"Subject":case"Category":case"Company":case"LastAuthor":case"LastSaved":case"LastPrinted":case"Version":case"Revision":case"TotalTime":case"HyperlinkBase":case"Manager":if(Rn[0].substr(-2)==="/>")break;else if(Rn[1]==="/")xlml_set_prop(Props,Rn[3],str.slice(pidx,Rn.index));else pidx=Rn.index+Rn[0].length;break;case"Paragraphs":break;case"Styles":case"Workbook":if(Rn[1]==="/"){if((tmp=state.pop())[0]!==Rn[3])throw"Bad state: "+tmp}else state.push([Rn[3],false]);break;case"Comment":if(Rn[1]==="/"){if((tmp=state.pop())[0]!==Rn[3])throw"Bad state: "+tmp;xlml_clean_comment(comment);comments.push(comment)}else{state.push([Rn[3],false]);tmp=parsexmltag(Rn[0]);comment={a:tmp.Author}}break;case"Name":break;case"ComponentOptions":case"DocumentProperties":case"CustomDocumentProperties":case"OfficeDocumentSettings":case"PivotTable":case"PivotCache":case"Names":case"MapInfo":case"PageBreaks":case"QueryTable":case"DataValidation":case"AutoFilter":case"Sorting":case"Schema":case"data":case"ConditionalFormatting":case"SmartTagType":case"SmartTags":case"ExcelWorkbook":case"WorkbookOptions":case"WorksheetOptions":if(Rn[1]==="/"){if((tmp=state.pop())[0]!==Rn[3])throw"Bad state: "+tmp}else if(Rn[0].charAt(Rn[0].length-2)!=="/")state.push([Rn[3],true]);break;default:var seen=true;switch(state[state.length-1][0]){case"OfficeDocumentSettings":switch(Rn[3]){case"AllowPNG":break;case"RemovePersonalInformation":break;case"DownloadComponents":break;case"LocationOfComponents":break;case"Colors":break;case"Color":break;case"Index":break;case"RGB":break;case"PixelsPerInch":break;case"TargetScreenSize":break;case"ReadOnlyRecommended":break;default:seen=false}break;case"ComponentOptions":switch(Rn[3]){case"Toolbar":break;case"HideOfficeLogo":break;case"SpreadsheetAutoFit":break;case"Label":break;case"Caption":break;case"MaxHeight":break;case"MaxWidth":break;case"NextSheetNumber":break;default:seen=false}break;case"ExcelWorkbook":switch(Rn[3]){case"WindowHeight":break;case"WindowWidth":break;case"WindowTopX":break;case"WindowTopY":break;case"TabRatio":break;case"ProtectStructure":break;case"ProtectWindows":break;case"ActiveSheet":break;case"DisplayInkNotes":break;case"FirstVisibleSheet":break;case"SupBook":break;case"SheetName":break;case"SheetIndex":break;case"SheetIndexFirst":break;case"SheetIndexLast":break;case"Dll":break;case"AcceptLabelsInFormulas":break;case"DoNotSaveLinkValues":break;case"Date1904":break;case"Iteration":break;case"MaxIterations":break;case"MaxChange":break;case"Path":break;case"Xct":break;case"Count":break;case"SelectedSheets":break;case"Calculation":break;case"Uncalced":break;case"StartupPrompt":break;case"Crn":break;case"ExternName":break;case"Formula":break;case"ColFirst":break;case"ColLast":break;case"WantAdvise":break;case"Boolean":break;case"Error":break;case"Text":break;case"OLE":break;case"NoAutoRecover":break;case"PublishObjects":break;case"DoNotCalculateBeforeSave":break;case"Number":break;case"RefModeR1C1":break;case"EmbedSaveSmartTags":break;default:seen=false}break;case"WorkbookOptions":switch(Rn[3]){case"OWCVersion":break;case"Height":break;case"Width":break;default:seen=false}break;case"WorksheetOptions":switch(Rn[3]){case"Unsynced":break;case"Visible":break;case"Print":break;case"Panes":break;case"Scale":break;case"Pane":break;case"Number":break;case"Layout":break;case"Header":break;case"Footer":break;case"PageSetup":break;case"PageMargins":break;case"Selected":break;case"ProtectObjects":break;case"EnableSelection":break;case"ProtectScenarios":break;case"ValidPrinterInfo":break;case"HorizontalResolution":break;case"VerticalResolution":break;case"NumberofCopies":break;case"ActiveRow":break;case"ActiveCol":break;case"ActivePane":break;case"TopRowVisible":break;case"TopRowBottomPane":break;case"LeftColumnVisible":break;case"LeftColumnRightPane":break;case"FitToPage":break;case"RangeSelection":break;case"PaperSizeIndex":break;case"PageLayoutZoom":break;case"PageBreakZoom":break;case"FilterOn":break;case"DoNotDisplayGridlines":break;case"SplitHorizontal":break;case"SplitVertical":break;case"FreezePanes":break;case"FrozenNoSplit":break;case"FitWidth":break;case"FitHeight":break;case"CommentsLayout":break;case"Zoom":break;case"LeftToRight":break;case"Gridlines":break;case"AllowSort":break;case"AllowFilter":break;case"AllowInsertRows":break;case"AllowDeleteRows":break;case"AllowInsertCols":break;case"AllowDeleteCols":break;case"AllowInsertHyperlinks":break;case"AllowFormatCells":break;case"AllowSizeCols":break;case"AllowSizeRows":break;case"NoSummaryRowsBelowDetail":break;case"TabColorIndex":break;case"DoNotDisplayHeadings":break;case"ShowPageLayoutZoom":break;case"NoSummaryColumnsRightDetail":break;case"BlackAndWhite":break;case"DoNotDisplayZeros":break;case"DisplayPageBreak":break;case"RowColHeadings":break;case"DoNotDisplayOutline":break;case"NoOrientation":break;case"AllowUsePivotTables":break;case"ZeroHeight":break;case"ViewableRange":break;case"Selection":break;case"ProtectContents":break;default:seen=false}break;case"PivotTable":case"PivotCache":switch(Rn[3]){case"ImmediateItemsOnDrop":break;case"ShowPageMultipleItemLabel":break;case"CompactRowIndent":break;case"Location":break;case"PivotField":break;case"Orientation":break;case"LayoutForm":break;case"LayoutSubtotalLocation":break;case"LayoutCompactRow":break;case"Position":break;case"PivotItem":break;case"DataType":break;case"DataField":break;case"SourceName":break;case"ParentField":break;case"PTLineItems":break;case"PTLineItem":break;case"CountOfSameItems":break;case"Item":break;case"ItemType":break;case"PTSource":break;case"CacheIndex":break;case"ConsolidationReference":break;case"FileName":break;case"Reference":break;case"NoColumnGrand":break;case"NoRowGrand":break;case"BlankLineAfterItems":break;case"Hidden":break;case"Subtotal":break;case"BaseField":break;case"MapChildItems":break;case"Function":break;case"RefreshOnFileOpen":break;case"PrintSetTitles":break;case"MergeLabels":break;case"DefaultVersion":break;case"RefreshName":break;case"RefreshDate":break;case"RefreshDateCopy":break;case"VersionLastRefresh":break;case"VersionLastUpdate":break;case"VersionUpdateableMin":break;case"VersionRefreshableMin":break;case"Calculation":break;default:seen=false}break;case"PageBreaks":switch(Rn[3]){case"ColBreaks":break;case"ColBreak":break;case"RowBreaks":break;case"RowBreak":break;case"ColStart":break;case"ColEnd":break;case"RowEnd":break;default:seen=false}break;case"AutoFilter":switch(Rn[3]){case"AutoFilterColumn":break;case"AutoFilterCondition":break;case"AutoFilterAnd":break;case"AutoFilterOr":break;default:seen=false}break;case"QueryTable":switch(Rn[3]){case"Id":break;case"AutoFormatFont":break;case"AutoFormatPattern":break;case"QuerySource":break;case"QueryType":break;case"EnableRedirections":break;case"RefreshedInXl9":break;case"URLString":break;case"HTMLTables":break;case"Connection":break;case"CommandText":break;case"RefreshInfo":break;case"NoTitles":break;case"NextId":break;case"ColumnInfo":break;case"OverwriteCells":break;case"DoNotPromptForFile":break;case"TextWizardSettings":break;case"Source":break;case"Number":break;case"Decimal":break;case"ThousandSeparator":break;case"TrailingMinusNumbers":break;case"FormatSettings":break;case"FieldType":break;case"Delimiters":break;case"Tab":break;case"Comma":break;case"AutoFormatName":break;case"VersionLastEdit":break;case"VersionLastRefresh":break;default:seen=false}break;case"Sorting":case"ConditionalFormatting":case"DataValidation":switch(Rn[3]){case"Range":break;case"Type":break;case"Min":break;case"Max":break;case"Sort":break;case"Descending":break;case"Order":break;case"CaseSensitive":break;case"Value":break;case"ErrorStyle":break;case"ErrorMessage":break;case"ErrorTitle":break;case"CellRangeList":break;case"InputMessage":break;case"InputTitle":break;case"ComboHide":break;case"InputHide":break;case"Condition":break;case"Qualifier":break;case"UseBlank":break;case"Value1":break;case"Value2":break;case"Format":break;default:seen=false}break;case"MapInfo":case"Schema":case"data":switch(Rn[3]){case"Map":break;case"Entry":break;case"Range":break;case"XPath":break;case"Field":break;case"XSDType":break;case"FilterOn":break;case"Aggregate":break;case"ElementType":break;case"AttributeType":break;case"schema":case"element":case"complexType":case"datatype":case"all":case"attribute":case"extends":break;case"row":break;default:seen=false}break;case"SmartTags":break;default:seen=false;break}if(seen)break;if(!state[state.length-1][1])throw"Unrecognized tag: "+Rn[3]+"|"+state.join("|");if(state[state.length-1][0]==="CustomDocumentProperties"){if(Rn[0].substr(-2)==="/>")break;else if(Rn[1]==="/")xlml_set_custprop(Custprops,Rn,cp,str.slice(pidx,Rn.index));else{cp=Rn;pidx=Rn.index+Rn[0].length}break}if(opts.WTF)throw"Unrecognized tag: "+Rn[3]+"|"+state.join("|")}var out={};if(!opts.bookSheets&&!opts.bookProps)out.Sheets=sheets;out.SheetNames=sheetnames;out.SSF=SSF.get_table();out.Props=Props;out.Custprops=Custprops;return out}function parse_xlml(data,opts){fixopts(opts=opts||{});switch(opts.type||"base64"){case"base64":return parse_xlml_xml(Base64.decode(data),opts);case"binary":case"buffer":case"file":return parse_xlml_xml(data,opts);case"array":return parse_xlml_xml(data.map(_chr).join(""),opts)}}function write_xlml(wb,opts){}var fs;if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports){fs=require("fs")}}function firstbyte(f,o){switch((o||{}).type||"base64"){case"buffer":return f[0];case"base64":return Base64.decode(f.substr(0,12)).charCodeAt(0);case"binary":return f.charCodeAt(0);case"array":return f[0];default:throw new Error("Unrecognized type "+o.type)}}function xlsread(f,o){if(!o)o={};if(!o.type)o.type=has_buf&&Buffer.isBuffer(f)?"buffer":"base64";switch(firstbyte(f,o)){case 208:return parse_xlscfb(CFB.read(f,o),o);case 60:return parse_xlml(f,o);default:throw"Unsupported file"}}var readFile=function(f,o){var d=fs.readFileSync(f);if(!o)o={};switch(firstbyte(d,{type:"buffer"})){case 208:return parse_xlscfb(CFB.read(d,{type:"buffer"}),o);case 60:return parse_xlml(d,(o.type="buffer",o));default:throw"Unsupported file"}};function writeSync(wb,opts){var o=opts||{};switch(o.bookType){case"xml":return write_xlml(wb,o);default:throw"unsupported output format "+o.bookType}}function writeFileSync(wb,filename,opts){var o=opts|{};o.type="file";o.file=filename;switch(o.file.substr(-4).toLowerCase()){case".xls":o.bookType="xls";break;case".xml":o.bookType="xml";break}return writeSync(wb,o)}function shift_cell(cell,tgt){if(tgt.s){if(cell.cRel)cell.c+=tgt.s.c;if(cell.rRel)cell.r+=tgt.s.r}else{cell.c+=tgt.c;cell.r+=tgt.r}cell.cRel=cell.rRel=0;while(cell.c>=256)cell.c-=256;while(cell.r>=65536)cell.r-=65536;return cell}function shift_range(cell,range){cell.s=shift_cell(cell.s,range.s);cell.e=shift_cell(cell.e,range.s);return cell}function decode_row(rowstr){return parseInt(unfix_row(rowstr),10)-1}function encode_row(row){return""+(row+1)}function fix_row(cstr){return cstr.replace(/([A-Z]|^)(\d+)$/,"$1$$$2")}function unfix_row(cstr){return cstr.replace(/\$(\d+)$/,"$1")}function decode_col(colstr){var c=unfix_col(colstr),d=0,i=0;for(;i!==c.length;++i)d=26*d+c.charCodeAt(i)-64;return d-1}function encode_col(col){var s="";for(++col;col;col=Math.floor((col-1)/26))s=String.fromCharCode((col-1)%26+65)+s;return s}function fix_col(cstr){return cstr.replace(/^([A-Z])/,"$$$1")}function unfix_col(cstr){return cstr.replace(/^\$([A-Z])/,"$1")}function split_cell(cstr){return cstr.replace(/(\$?[A-Z]*)(\$?\d*)/,"$1,$2").split(",")}function decode_cell(cstr){var splt=split_cell(cstr);return{c:decode_col(splt[0]),r:decode_row(splt[1])}}function encode_cell(cell){return encode_col(cell.c)+encode_row(cell.r)}function fix_cell(cstr){return fix_col(fix_row(cstr))}function unfix_cell(cstr){return unfix_col(unfix_row(cstr))}function decode_range(range){var x=range.split(":").map(decode_cell);return{s:x[0],e:x[x.length-1]}}function encode_range(cs,ce){if(ce===undefined||typeof ce==="number")return encode_range(cs.s,cs.e);if(typeof cs!=="string")cs=encode_cell(cs);if(typeof ce!=="string")ce=encode_cell(ce);return cs==ce?cs:cs+":"+ce}function safe_decode_range(range){var o={s:{c:0,r:0},e:{c:0,r:0}};var idx=0,i=0,cc=0;var len=range.length;for(idx=0;i<len;++i){if((cc=range.charCodeAt(i)-64)<1||cc>26)break;idx=26*idx+cc}o.s.c=--idx;for(idx=0;i<len;++i){if((cc=range.charCodeAt(i)-48)<0||cc>9)break;idx=10*idx+cc}o.s.r=--idx;if(i===len||range.charCodeAt(++i)===58){o.e.c=o.s.c;o.e.r=o.s.r;return o}for(idx=0;i!=len;++i){if((cc=range.charCodeAt(i)-64)<1||cc>26)break;idx=26*idx+cc}o.e.c=--idx;for(idx=0;i!=len;++i){if((cc=range.charCodeAt(i)-48)<0||cc>9)break;idx=10*idx+cc}o.e.r=--idx;return o}function safe_format_cell(cell,v){if(cell.z!==undefined)try{return cell.w=SSF.format(cell.z,v)}catch(e){}if(!cell.XF)return v;try{return cell.w=SSF.format(cell.XF.ifmt||0,v)}catch(e){return""+v}}function format_cell(cell,v){if(cell==null||cell.t==null)return"";if(cell.w!==undefined)return cell.w;if(v===undefined)return safe_format_cell(cell,cell.v);return safe_format_cell(cell,v)}function sheet_to_json(sheet,opts){var val,row,range,header=0,offset=1,r,hdr=[],isempty,R,C,v;var o=opts!=null?opts:{};var raw=o.raw;if(sheet==null||sheet["!ref"]==null)return[];range=o.range!==undefined?o.range:sheet["!ref"];if(o.header===1)header=1;else if(o.header==="A")header=2;else if(Array.isArray(o.header))header=3;switch(typeof range){case"string":r=safe_decode_range(range);break;case"number":r=safe_decode_range(sheet["!ref"]);r.s.r=range;break;default:r=range}if(header>0)offset=0;var rr=encode_row(r.s.r);var cols=new Array(r.e.c-r.s.c+1);var out=new Array(r.e.r-r.s.r-offset+1);var outi=0;for(C=r.s.c;C<=r.e.c;++C){cols[C]=encode_col(C);val=sheet[cols[C]+rr];switch(header){case 1:hdr[C]=C;break;case 2:hdr[C]=cols[C];break;case 3:hdr[C]=o.header[C-r.s.c];break;default:if(val===undefined)continue;hdr[C]=format_cell(val)}}for(R=r.s.r+offset;R<=r.e.r;++R){rr=encode_row(R);isempty=true;row=header===1?[]:Object.create({__rowNum__:R});for(C=r.s.c;C<=r.e.c;++C){val=sheet[cols[C]+rr];if(val===undefined||val.t===undefined)continue;v=val.v;switch(val.t){case"e":continue;case"s":case"str":break;case"b":case"n":break;default:throw"unrecognized type "+val.t}if(v!==undefined){row[hdr[C]]=raw?v:format_cell(val,v);isempty=false}}if(isempty===false)out[outi++]=row}out.length=outi;return out}function sheet_to_row_object_array(sheet,opts){return sheet_to_json(sheet,opts!=null?opts:{})}function sheet_to_csv(sheet,opts){var out="",txt="",qreg=/"/g;var o=opts==null?{}:opts;if(sheet==null||sheet["!ref"]==null)return"";var r=safe_decode_range(sheet["!ref"]);var FS=o.FS!==undefined?o.FS:",",fs=FS.charCodeAt(0);var RS=o.RS!==undefined?o.RS:"\n",rs=RS.charCodeAt(0);var row="",rr="",cols=[];var i=0,cc=0,val;var R=0,C=0;for(C=r.s.c;C<=r.e.c;++C)cols[C]=encode_col(C);for(R=r.s.r;R<=r.e.r;++R){row="";rr=encode_row(R);for(C=r.s.c;C<=r.e.c;++C){val=sheet[cols[C]+rr];txt=val!==undefined?""+format_cell(val):"";for(i=0,cc=0;i!==txt.length;++i)if((cc=txt.charCodeAt(i))===fs||cc===rs||cc===34){txt='"'+txt.replace(qreg,'""')+'"';break}row+=(C===r.s.c?"":FS)+txt}out+=row+RS}return out}var make_csv=sheet_to_csv;function sheet_to_formulae(sheet){var cmds,y="",x,val="";if(sheet==null||sheet["!ref"]==null)return"";var r=safe_decode_range(sheet["!ref"]),rr="",cols=[],C;cmds=new Array((r.e.r-r.s.r+1)*(r.e.c-r.s.c+1));var i=0;for(C=r.s.c;C<=r.e.c;++C)cols[C]=encode_col(C);for(var R=r.s.r;R<=r.e.r;++R){rr=encode_row(R);for(C=r.s.c;C<=r.e.c;++C){y=cols[C]+rr;x=sheet[y];val="";if(x===undefined)continue;if(x.f!=null)val=x.f;else if(x.w!==undefined)val="'"+x.w;else if(x.v===undefined)continue;else val=""+x.v;cmds[i++]=y+"="+val}}cmds.length=i;return cmds}var utils={encode_col:encode_col,encode_row:encode_row,encode_cell:encode_cell,encode_range:encode_range,decode_col:decode_col,decode_row:decode_row,split_cell:split_cell,decode_cell:decode_cell,decode_range:decode_range,format_cell:format_cell,get_formulae:sheet_to_formulae,make_csv:sheet_to_csv,make_json:sheet_to_json,make_formulae:sheet_to_formulae,sheet_to_csv:sheet_to_csv,sheet_to_json:sheet_to_json,sheet_to_formulae:sheet_to_formulae,sheet_to_row_object_array:sheet_to_row_object_array};XLS.parse_xlscfb=parse_xlscfb;XLS.read=xlsread;XLS.readFile=readFile;XLS.utils=utils;XLS.CFB=CFB;XLS.SSF=SSF})(typeof exports!=="undefined"?exports:XLS);
25802 //@ sourceMappingURL=dist/xls.min.map
25803 /* xlsx.js (C) 2013-2014 SheetJS -- http://sheetjs.com */
25804 /* vim: set ts=2: */
25805 /*jshint -W041 */
25806 var XLSX = {};
25807 (function(XLSX){
25808 XLSX.version = '0.7.8';
25809 var current_codepage = 1252, current_cptable;
25810 if(typeof module !== "undefined" && typeof require !== 'undefined') {
25811 if(typeof cptable === 'undefined') cptable = require('./dist/cpexcel');
25812 current_cptable = cptable[current_codepage];
25813 }
25814 function reset_cp() { set_cp(1252); }
25815 var set_cp = function(cp) { current_codepage = cp; };
25816
25817 function char_codes(data) { var o = []; for(var i = 0, len = data.length; i < len; ++i) o[i] = data.charCodeAt(i); return o; }
25818 var debom_xml = function(data) { return data; };
25819
25820 if(typeof cptable !== 'undefined') {
25821 set_cp = function(cp) { current_codepage = cp; current_cptable = cptable[cp]; };
25822 debom_xml = function(data) {
25823 if(data.charCodeAt(0) === 0xFF && data.charCodeAt(1) === 0xFE) { return cptable.utils.decode(1200, char_codes(data.substr(2))); }
25824 return data;
25825 };
25826 }
25827 /* ssf.js (C) 2013-2014 SheetJS -- http://sheetjs.com */
25828 /*jshint -W041 */
25829 var SSF = {};
25830 var make_ssf = function make_ssf(SSF){
25831 SSF.version = '0.8.1';
25832 function _strrev(x) { var o = "", i = x.length-1; while(i>=0) o += x.charAt(i--); return o; }
25833 function fill(c,l) { var o = ""; while(o.length < l) o+=c; return o; }
25834 function pad0(v,d){var t=""+v; return t.length>=d?t:fill('0',d-t.length)+t;}
25835 function pad_(v,d){var t=""+v;return t.length>=d?t:fill(' ',d-t.length)+t;}
25836 function rpad_(v,d){var t=""+v; return t.length>=d?t:t+fill(' ',d-t.length);}
25837 function pad0r1(v,d){var t=""+Math.round(v); return t.length>=d?t:fill('0',d-t.length)+t;}
25838 function pad0r2(v,d){var t=""+v; return t.length>=d?t:fill('0',d-t.length)+t;}
25839 var p2_32 = Math.pow(2,32);
25840 function pad0r(v,d){if(v>p2_32||v<-p2_32) return pad0r1(v,d); var i = Math.round(v); return pad0r2(i,d); }
25841 function isgeneral(s, i) { return s.length >= 7 + i && (s.charCodeAt(i)|32) === 103 && (s.charCodeAt(i+1)|32) === 101 && (s.charCodeAt(i+2)|32) === 110 && (s.charCodeAt(i+3)|32) === 101 && (s.charCodeAt(i+4)|32) === 114 && (s.charCodeAt(i+5)|32) === 97 && (s.charCodeAt(i+6)|32) === 108; }
25842 /* Options */
25843 var opts_fmt = [
25844 ["date1904", 0],
25845 ["output", ""],
25846 ["WTF", false]
25847 ];
25848 function fixopts(o){
25849 for(var y = 0; y != opts_fmt.length; ++y) if(o[opts_fmt[y][0]]===undefined) o[opts_fmt[y][0]]=opts_fmt[y][1];
25850 }
25851 SSF.opts = opts_fmt;
25852 var table_fmt = {
25853 0: 'General',
25854 1: '0',
25855 2: '0.00',
25856 3: '#,##0',
25857 4: '#,##0.00',
25858 9: '0%',
25859 10: '0.00%',
25860 11: '0.00E+00',
25861 12: '# ?/?',
25862 13: '# ??/??',
25863 14: 'm/d/yy',
25864 15: 'd-mmm-yy',
25865 16: 'd-mmm',
25866 17: 'mmm-yy',
25867 18: 'h:mm AM/PM',
25868 19: 'h:mm:ss AM/PM',
25869 20: 'h:mm',
25870 21: 'h:mm:ss',
25871 22: 'm/d/yy h:mm',
25872 37: '#,##0 ;(#,##0)',
25873 38: '#,##0 ;[Red](#,##0)',
25874 39: '#,##0.00;(#,##0.00)',
25875 40: '#,##0.00;[Red](#,##0.00)',
25876 45: 'mm:ss',
25877 46: '[h]:mm:ss',
25878 47: 'mmss.0',
25879 48: '##0.0E+0',
25880 49: '@',
25881 56: '"上午/下午 "hh"時"mm"分"ss"秒 "',
25882 65535: 'General'
25883 };
25884 var days = [
25885 ['Sun', 'Sunday'],
25886 ['Mon', 'Monday'],
25887 ['Tue', 'Tuesday'],
25888 ['Wed', 'Wednesday'],
25889 ['Thu', 'Thursday'],
25890 ['Fri', 'Friday'],
25891 ['Sat', 'Saturday']
25892 ];
25893 var months = [
25894 ['J', 'Jan', 'January'],
25895 ['F', 'Feb', 'February'],
25896 ['M', 'Mar', 'March'],
25897 ['A', 'Apr', 'April'],
25898 ['M', 'May', 'May'],
25899 ['J', 'Jun', 'June'],
25900 ['J', 'Jul', 'July'],
25901 ['A', 'Aug', 'August'],
25902 ['S', 'Sep', 'September'],
25903 ['O', 'Oct', 'October'],
25904 ['N', 'Nov', 'November'],
25905 ['D', 'Dec', 'December']
25906 ];
25907 function frac(x, D, mixed) {
25908 var sgn = x < 0 ? -1 : 1;
25909 var B = x * sgn;
25910 var P_2 = 0, P_1 = 1, P = 0;
25911 var Q_2 = 1, Q_1 = 0, Q = 0;
25912 var A = Math.floor(B);
25913 while(Q_1 < D) {
25914 A = Math.floor(B);
25915 P = A * P_1 + P_2;
25916 Q = A * Q_1 + Q_2;
25917 if((B - A) < 0.0000000005) break;
25918 B = 1 / (B - A);
25919 P_2 = P_1; P_1 = P;
25920 Q_2 = Q_1; Q_1 = Q;
25921 }
25922 if(Q > D) { Q = Q_1; P = P_1; }
25923 if(Q > D) { Q = Q_2; P = P_2; }
25924 if(!mixed) return [0, sgn * P, Q];
25925 if(Q===0) throw "Unexpected state: "+P+" "+P_1+" "+P_2+" "+Q+" "+Q_1+" "+Q_2;
25926 var q = Math.floor(sgn * P/Q);
25927 return [q, sgn*P - q*Q, Q];
25928 }
25929 function general_fmt_int(v, opts) { return ""+v; }
25930 SSF._general_int = general_fmt_int;
25931 var general_fmt_num = (function make_general_fmt_num() {
25932 var gnr1 = /\.(\d*[1-9])0+$/, gnr2 = /\.0*$/, gnr4 = /\.(\d*[1-9])0+/, gnr5 = /\.0*[Ee]/, gnr6 = /(E[+-])(\d)$/;
25933 function gfn2(v) {
25934 var w = (v<0?12:11);
25935 var o = gfn5(v.toFixed(12)); if(o.length <= w) return o;
25936 o = v.toPrecision(10); if(o.length <= w) return o;
25937 return v.toExponential(5);
25938 }
25939 function gfn3(v) {
25940 var o = v.toFixed(11).replace(gnr1,".$1");
25941 if(o.length > (v<0?12:11)) o = v.toPrecision(6);
25942 return o;
25943 }
25944 function gfn4(o) {
25945 for(var i = 0; i != o.length; ++i) if((o.charCodeAt(i) | 0x20) === 101) return o.replace(gnr4,".$1").replace(gnr5,"E").replace("e","E").replace(gnr6,"$10$2");
25946 return o;
25947 }
25948 function gfn5(o) {
25949 //for(var i = 0; i != o.length; ++i) if(o.charCodeAt(i) === 46) return o.replace(gnr2,"").replace(gnr1,".$1");
25950 //return o;
25951 return o.indexOf(".") > -1 ? o.replace(gnr2,"").replace(gnr1,".$1") : o;
25952 }
25953 return function general_fmt_num(v, opts) {
25954 var V = Math.floor(Math.log(Math.abs(v))*Math.LOG10E), o;
25955 if(V >= -4 && V <= -1) o = v.toPrecision(10+V);
25956 else if(Math.abs(V) <= 9) o = gfn2(v);
25957 else if(V === 10) o = v.toFixed(10).substr(0,12);
25958 else o = gfn3(v);
25959 return gfn5(gfn4(o));
25960 };})();
25961 SSF._general_num = general_fmt_num;
25962 function general_fmt(v, opts) {
25963 switch(typeof v) {
25964 case 'string': return v;
25965 case 'boolean': return v ? "TRUE" : "FALSE";
25966 case 'number': return (v|0) === v ? general_fmt_int(v, opts) : general_fmt_num(v, opts);
25967 }
25968 throw new Error("unsupported value in General format: " + v);
25969 }
25970 SSF._general = general_fmt;
25971 function fix_hijri(date, o) { return 0; }
25972 function parse_date_code(v,opts,b2) {
25973 if(v > 2958465 || v < 0) return null;
25974 var date = (v|0), time = Math.floor(86400 * (v - date)), dow=0;
25975 var dout=[];
25976 var out={D:date, T:time, u:86400*(v-date)-time,y:0,m:0,d:0,H:0,M:0,S:0,q:0};
25977 if(Math.abs(out.u) < 1e-6) out.u = 0;
25978 fixopts(opts != null ? opts : (opts=[]));
25979 if(opts.date1904) date += 1462;
25980 if(out.u > 0.999) {
25981 out.u = 0;
25982 if(++time == 86400) { time = 0; ++date; }
25983 }
25984 if(date === 60) {dout = b2 ? [1317,10,29] : [1900,2,29]; dow=3;}
25985 else if(date === 0) {dout = b2 ? [1317,8,29] : [1900,1,0]; dow=6;}
25986 else {
25987 if(date > 60) --date;
25988 /* 1 = Jan 1 1900 */
25989 var d = new Date(1900,0,1);
25990 d.setDate(d.getDate() + date - 1);
25991 dout = [d.getFullYear(), d.getMonth()+1,d.getDate()];
25992 dow = d.getDay();
25993 if(date < 60) dow = (dow + 6) % 7;
25994 if(b2) dow = fix_hijri(d, dout);
25995 }
25996 out.y = dout[0]; out.m = dout[1]; out.d = dout[2];
25997 out.S = time % 60; time = Math.floor(time / 60);
25998 out.M = time % 60; time = Math.floor(time / 60);
25999 out.H = time;
26000 out.q = dow;
26001 return out;
26002 }
26003 SSF.parse_date_code = parse_date_code;
26004 /*jshint -W086 */
26005 function write_date(type, fmt, val, ss0) {
26006 var o="", ss=0, tt=0, y = val.y, out, outl = 0;
26007 switch(type) {
26008 case 98: /* 'b' buddhist year */
26009 y = val.y + 543;
26010 /* falls through */
26011 case 121: /* 'y' year */
26012 switch(fmt.length) {
26013 case 1: case 2: out = y % 100; outl = 2; break;
26014 default: out = y % 10000; outl = 4; break;
26015 } break;
26016 case 109: /* 'm' month */
26017 switch(fmt.length) {
26018 case 1: case 2: out = val.m; outl = fmt.length; break;
26019 case 3: return months[val.m-1][1];
26020 case 5: return months[val.m-1][0];
26021 default: return months[val.m-1][2];
26022 } break;
26023 case 100: /* 'd' day */
26024 switch(fmt.length) {
26025 case 1: case 2: out = val.d; outl = fmt.length; break;
26026 case 3: return days[val.q][0];
26027 default: return days[val.q][1];
26028 } break;
26029 case 104: /* 'h' 12-hour */
26030 switch(fmt.length) {
26031 case 1: case 2: out = 1+(val.H+11)%12; outl = fmt.length; break;
26032 default: throw 'bad hour format: ' + fmt;
26033 } break;
26034 case 72: /* 'H' 24-hour */
26035 switch(fmt.length) {
26036 case 1: case 2: out = val.H; outl = fmt.length; break;
26037 default: throw 'bad hour format: ' + fmt;
26038 } break;
26039 case 77: /* 'M' minutes */
26040 switch(fmt.length) {
26041 case 1: case 2: out = val.M; outl = fmt.length; break;
26042 default: throw 'bad minute format: ' + fmt;
26043 } break;
26044 case 115: /* 's' seconds */
26045 if(val.u === 0) switch(fmt) {
26046 case 's': case 'ss': return pad0(val.S, fmt.length);
26047 case '.0': case '.00': case '.000':
26048 }
26049 switch(fmt) {
26050 case 's': case 'ss': case '.0': case '.00': case '.000':
26051 if(ss0 >= 2) tt = ss0 === 3 ? 1000 : 100;
26052 else tt = ss0 === 1 ? 10 : 1;
26053 ss = Math.round((tt)*(val.S + val.u));
26054 if(ss >= 60*tt) ss = 0;
26055 if(fmt === 's') return ss === 0 ? "0" : ""+ss/tt;
26056 o = pad0(ss,2 + ss0);
26057 if(fmt === 'ss') return o.substr(0,2);
26058 return "." + o.substr(2,fmt.length-1);
26059 default: throw 'bad second format: ' + fmt;
26060 }
26061 case 90: /* 'Z' absolute time */
26062 switch(fmt) {
26063 case '[h]': case '[hh]': out = val.D*24+val.H; break;
26064 case '[m]': case '[mm]': out = (val.D*24+val.H)*60+val.M; break;
26065 case '[s]': case '[ss]': out = ((val.D*24+val.H)*60+val.M)*60+Math.round(val.S+val.u); break;
26066 default: throw 'bad abstime format: ' + fmt;
26067 } outl = fmt.length === 3 ? 1 : 2; break;
26068 case 101: /* 'e' era */
26069 out = y; outl = 1;
26070 }
26071 if(outl > 0) return pad0(out, outl); else return "";
26072 }
26073 /*jshint +W086 */
26074 function commaify(s) {
26075 if(s.length <= 3) return s;
26076 var j = (s.length % 3), o = s.substr(0,j);
26077 for(; j!=s.length; j+=3) o+=(o.length > 0 ? "," : "") + s.substr(j,3);
26078 return o;
26079 }
26080 var write_num = (function make_write_num(){
26081 var pct1 = /%/g;
26082 function write_num_pct(type, fmt, val){
26083 var sfmt = fmt.replace(pct1,""), mul = fmt.length - sfmt.length;
26084 return write_num(type, sfmt, val * Math.pow(10,2*mul)) + fill("%",mul);
26085 }
26086 function write_num_cm(type, fmt, val){
26087 var idx = fmt.length - 1;
26088 while(fmt.charCodeAt(idx-1) === 44) --idx;
26089 return write_num(type, fmt.substr(0,idx), val / Math.pow(10,3*(fmt.length-idx)));
26090 }
26091 function write_num_exp(fmt, val){
26092 var o;
26093 var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
26094 if(fmt.match(/^#+0.0E\+0$/)) {
26095 var period = fmt.indexOf("."); if(period === -1) period=fmt.indexOf('E');
26096 var ee = Math.floor(Math.log(Math.abs(val))*Math.LOG10E)%period;
26097 if(ee < 0) ee += period;
26098 o = (val/Math.pow(10,ee)).toPrecision(idx+1+(period+ee)%period);
26099 if(o.indexOf("e") === -1) {
26100 var fakee = Math.floor(Math.log(Math.abs(val))*Math.LOG10E);
26101 if(o.indexOf(".") === -1) o = o[0] + "." + o.substr(1) + "E+" + (fakee - o.length+ee);
26102 else o += "E+" + (fakee - ee);
26103 while(o.substr(0,2) === "0.") {
26104 o = o[0] + o.substr(2,period) + "." + o.substr(2+period);
26105 o = o.replace(/^0+([1-9])/,"$1").replace(/^0+\./,"0.");
26106 }
26107 o = o.replace(/\+-/,"-");
26108 }
26109 o = o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function($$,$1,$2,$3) { return $1 + $2 + $3.substr(0,(period+ee)%period) + "." + $3.substr(ee) + "E"; });
26110 } else o = val.toExponential(idx);
26111 if(fmt.match(/E\+00$/) && o.match(/e[+-]\d$/)) o = o.substr(0,o.length-1) + "0" + o[o.length-1];
26112 if(fmt.match(/E\-/) && o.match(/e\+/)) o = o.replace(/e\+/,"e");
26113 return o.replace("e","E");
26114 }
26115 var frac1 = /# (\?+)( ?)\/( ?)(\d+)/;
26116 function write_num_f1(r, aval, sign) {
26117 var den = parseInt(r[4]), rr = Math.round(aval * den), base = Math.floor(rr/den);
26118 var myn = (rr - base*den), myd = den;
26119 return sign + (base === 0 ? "" : ""+base) + " " + (myn === 0 ? fill(" ", r[1].length + 1 + r[4].length) : pad_(myn,r[1].length) + r[2] + "/" + r[3] + pad0(myd,r[4].length));
26120 }
26121 function write_num_f2(r, aval, sign) {
26122 return sign + (aval === 0 ? "" : ""+aval) + fill(" ", r[1].length + 2 + r[4].length);
26123 }
26124 var dec1 = /^#*0*\.(0+)/;
26125 var closeparen = /\).*[0#]/;
26126 var phone = /\(###\) ###\\?-####/;
26127 function hashq(str) {
26128 var o = "", cc;
26129 for(var i = 0; i != str.length; ++i) switch((cc=str.charCodeAt(i))) {
26130 case 35: break;
26131 case 63: o+= " "; break;
26132 case 48: o+= "0"; break;
26133 default: o+= String.fromCharCode(cc);
26134 }
26135 return o;
26136 }
26137 function rnd(val, d) { var dd = Math.pow(10,d); return ""+(Math.round(val * dd)/dd); }
26138 function dec(val, d) { return Math.round((val-Math.floor(val))*Math.pow(10,d)); }
26139 function flr(val) { if(val < 2147483647 && val > -2147483648) return ""+(val >= 0 ? (val|0) : (val-1|0)); return ""+Math.floor(val); }
26140 function write_num_flt(type, fmt, val) {
26141 if(type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
26142 var ffmt = fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");
26143 if(val >= 0) return write_num_flt('n', ffmt, val);
26144 return '(' + write_num_flt('n', ffmt, -val) + ')';
26145 }
26146 if(fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm(type, fmt, val);
26147 if(fmt.indexOf('%') !== -1) return write_num_pct(type, fmt, val);
26148 if(fmt.indexOf('E') !== -1) return write_num_exp(fmt, val);
26149 if(fmt.charCodeAt(0) === 36) return "$"+write_num_flt(type,fmt.substr(fmt[1]==' '?2:1),val);
26150 var o, oo;
26151 var r, ri, ff, aval = Math.abs(val), sign = val < 0 ? "-" : "";
26152 if(fmt.match(/^00+$/)) return sign + pad0r(aval,fmt.length);
26153 if(fmt.match(/^[#?]+$/)) {
26154 o = pad0r(val,0); if(o === "0") o = "";
26155 return o.length > fmt.length ? o : hashq(fmt.substr(0,fmt.length-o.length)) + o;
26156 }
26157 if((r = fmt.match(frac1)) !== null) return write_num_f1(r, aval, sign);
26158 if(fmt.match(/^#+0+$/) !== null) return sign + pad0r(aval,fmt.length - fmt.indexOf("0"));
26159 if((r = fmt.match(dec1)) !== null) {
26160 o = rnd(val, r[1].length).replace(/^([^\.]+)$/,"$1."+r[1]).replace(/\.$/,"."+r[1]).replace(/\.(\d*)$/,function($$, $1) { return "." + $1 + fill("0", r[1].length-$1.length); });
26161 return fmt.indexOf("0.") !== -1 ? o : o.replace(/^0\./,".");
26162 }
26163 fmt = fmt.replace(/^#+([0.])/, "$1");
26164 if((r = fmt.match(/^(0*)\.(#*)$/)) !== null) {
26165 return sign + rnd(aval, r[2].length).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,r[1].length?"0.":".");
26166 }
26167 if((r = fmt.match(/^#,##0(\.?)$/)) !== null) return sign + commaify(pad0r(aval,0));
26168 if((r = fmt.match(/^#,##0\.([#0]*0)$/)) !== null) {
26169 return val < 0 ? "-" + write_num_flt(type, fmt, -val) : commaify(""+(Math.floor(val))) + "." + pad0(dec(val, r[1].length),r[1].length);
26170 }
26171 if((r = fmt.match(/^#,#*,#0/)) !== null) return write_num_flt(type,fmt.replace(/^#,#*,/,""),val);
26172 if((r = fmt.match(/^([0#]+)(\\?-([0#]+))+$/)) !== null) {
26173 o = _strrev(write_num_flt(type, fmt.replace(/[\\-]/g,""), val));
26174 ri = 0;
26175 return _strrev(_strrev(fmt.replace(/\\/g,"")).replace(/[0#]/g,function(x){return ri<o.length?o[ri++]:x==='0'?'0':"";}));
26176 }
26177 if(fmt.match(phone) !== null) {
26178 o = write_num_flt(type, "##########", val);
26179 return "(" + o.substr(0,3) + ") " + o.substr(3, 3) + "-" + o.substr(6);
26180 }
26181 var oa = "";
26182 if((r = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/)) !== null) {
26183 ri = Math.min(r[4].length,7);
26184 ff = frac(aval, Math.pow(10,ri)-1, false);
26185 o = "" + sign;
26186 oa = write_num("n", r[1], ff[1]);
26187 if(oa[oa.length-1] == " ") oa = oa.substr(0,oa.length-1) + "0";
26188 o += oa + r[2] + "/" + r[3];
26189 oa = rpad_(ff[2],ri);
26190 if(oa.length < r[4].length) oa = hashq(r[4].substr(r[4].length-oa.length)) + oa;
26191 o += oa;
26192 return o;
26193 }
26194 if((r = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/)) !== null) {
26195 ri = Math.min(Math.max(r[1].length, r[4].length),7);
26196 ff = frac(aval, Math.pow(10,ri)-1, true);
26197 return sign + (ff[0]||(ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1],ri) + r[2] + "/" + r[3] + rpad_(ff[2],ri): fill(" ", 2*ri+1 + r[2].length + r[3].length));
26198 }
26199 if((r = fmt.match(/^[#0?]+$/)) !== null) {
26200 o = pad0r(val, 0);
26201 if(fmt.length <= o.length) return o;
26202 return hashq(fmt.substr(0,fmt.length-o.length)) + o;
26203 }
26204 if((r = fmt.match(/^([#0?]+)\.([#0]+)$/)) !== null) {
26205 o = "" + val.toFixed(Math.min(r[2].length,10)).replace(/([^0])0+$/,"$1");
26206 ri = o.indexOf(".");
26207 var lres = fmt.indexOf(".") - ri, rres = fmt.length - o.length - lres;
26208 return hashq(fmt.substr(0,lres) + o + fmt.substr(fmt.length-rres));
26209 }
26210 if((r = fmt.match(/^00,000\.([#0]*0)$/)) !== null) {
26211 ri = dec(val, r[1].length);
26212 return val < 0 ? "-" + write_num_flt(type, fmt, -val) : commaify(flr(val)).replace(/^\d,\d{3}$/,"0$&").replace(/^\d*$/,function($$) { return "00," + ($$.length < 3 ? pad0(0,3-$$.length) : "") + $$; }) + "." + pad0(ri,r[1].length);
26213 }
26214 switch(fmt) {
26215 case "#,###": var x = commaify(pad0r(aval,0)); return x !== "0" ? sign + x : "";
26216 default:
26217 }
26218 throw new Error("unsupported format |" + fmt + "|");
26219 }
26220 function write_num_cm2(type, fmt, val){
26221 var idx = fmt.length - 1;
26222 while(fmt.charCodeAt(idx-1) === 44) --idx;
26223 return write_num(type, fmt.substr(0,idx), val / Math.pow(10,3*(fmt.length-idx)));
26224 }
26225 function write_num_pct2(type, fmt, val){
26226 var sfmt = fmt.replace(pct1,""), mul = fmt.length - sfmt.length;
26227 return write_num(type, sfmt, val * Math.pow(10,2*mul)) + fill("%",mul);
26228 }
26229 function write_num_exp2(fmt, val){
26230 var o;
26231 var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
26232 if(fmt.match(/^#+0.0E\+0$/)) {
26233 var period = fmt.indexOf("."); if(period === -1) period=fmt.indexOf('E');
26234 var ee = Math.floor(Math.log(Math.abs(val))*Math.LOG10E)%period;
26235 if(ee < 0) ee += period;
26236 o = (val/Math.pow(10,ee)).toPrecision(idx+1+(period+ee)%period);
26237 if(!o.match(/[Ee]/)) {
26238 var fakee = Math.floor(Math.log(Math.abs(val))*Math.LOG10E);
26239 if(o.indexOf(".") === -1) o = o[0] + "." + o.substr(1) + "E+" + (fakee - o.length+ee);
26240 else o += "E+" + (fakee - ee);
26241 o = o.replace(/\+-/,"-");
26242 }
26243 o = o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function($$,$1,$2,$3) { return $1 + $2 + $3.substr(0,(period+ee)%period) + "." + $3.substr(ee) + "E"; });
26244 } else o = val.toExponential(idx);
26245 if(fmt.match(/E\+00$/) && o.match(/e[+-]\d$/)) o = o.substr(0,o.length-1) + "0" + o[o.length-1];
26246 if(fmt.match(/E\-/) && o.match(/e\+/)) o = o.replace(/e\+/,"e");
26247 return o.replace("e","E");
26248 }
26249 function write_num_int(type, fmt, val) {
26250 if(type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
26251 var ffmt = fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");
26252 if(val >= 0) return write_num_int('n', ffmt, val);
26253 return '(' + write_num_int('n', ffmt, -val) + ')';
26254 }
26255 if(fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm2(type, fmt, val);
26256 if(fmt.indexOf('%') !== -1) return write_num_pct2(type, fmt, val);
26257 if(fmt.indexOf('E') !== -1) return write_num_exp2(fmt, val);
26258 if(fmt.charCodeAt(0) === 36) return "$"+write_num_int(type,fmt.substr(fmt[1]==' '?2:1),val);
26259 var o;
26260 var r, ri, ff, aval = Math.abs(val), sign = val < 0 ? "-" : "";
26261 if(fmt.match(/^00+$/)) return sign + pad0(aval,fmt.length);
26262 if(fmt.match(/^[#?]+$/)) {
26263 o = (""+val); if(val === 0) o = "";
26264 return o.length > fmt.length ? o : hashq(fmt.substr(0,fmt.length-o.length)) + o;
26265 }
26266 if((r = fmt.match(frac1)) !== null) return write_num_f2(r, aval, sign);
26267 if(fmt.match(/^#+0+$/) !== null) return sign + pad0(aval,fmt.length - fmt.indexOf("0"));
26268 if((r = fmt.match(dec1)) !== null) {
26269 o = (""+val).replace(/^([^\.]+)$/,"$1."+r[1]).replace(/\.$/,"."+r[1]).replace(/\.(\d*)$/,function($$, $1) { return "." + $1 + fill("0", r[1].length-$1.length); });
26270 return fmt.indexOf("0.") !== -1 ? o : o.replace(/^0\./,".");
26271 }
26272 fmt = fmt.replace(/^#+([0.])/, "$1");
26273 if((r = fmt.match(/^(0*)\.(#*)$/)) !== null) {
26274 return sign + (""+aval).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,r[1].length?"0.":".");
26275 }
26276 if((r = fmt.match(/^#,##0(\.?)$/)) !== null) return sign + commaify((""+aval));
26277 if((r = fmt.match(/^#,##0\.([#0]*0)$/)) !== null) {
26278 return val < 0 ? "-" + write_num_int(type, fmt, -val) : commaify((""+val)) + "." + fill('0',r[1].length);
26279 }
26280 if((r = fmt.match(/^#,#*,#0/)) !== null) return write_num_int(type,fmt.replace(/^#,#*,/,""),val);
26281 if((r = fmt.match(/^([0#]+)(\\?-([0#]+))+$/)) !== null) {
26282 o = _strrev(write_num_int(type, fmt.replace(/[\\-]/g,""), val));
26283 ri = 0;
26284 return _strrev(_strrev(fmt.replace(/\\/g,"")).replace(/[0#]/g,function(x){return ri<o.length?o[ri++]:x==='0'?'0':"";}));
26285 }
26286 if(fmt.match(phone) !== null) {
26287 o = write_num_int(type, "##########", val);
26288 return "(" + o.substr(0,3) + ") " + o.substr(3, 3) + "-" + o.substr(6);
26289 }
26290 var oa = "";
26291 if((r = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/)) !== null) {
26292 ri = Math.min(r[4].length,7);
26293 ff = frac(aval, Math.pow(10,ri)-1, false);
26294 o = "" + sign;
26295 oa = write_num("n", r[1], ff[1]);
26296 if(oa[oa.length-1] == " ") oa = oa.substr(0,oa.length-1) + "0";
26297 o += oa + r[2] + "/" + r[3];
26298 oa = rpad_(ff[2],ri);
26299 if(oa.length < r[4].length) oa = hashq(r[4].substr(r[4].length-oa.length)) + oa;
26300 o += oa;
26301 return o;
26302 }
26303 if((r = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/)) !== null) {
26304 ri = Math.min(Math.max(r[1].length, r[4].length),7);
26305 ff = frac(aval, Math.pow(10,ri)-1, true);
26306 return sign + (ff[0]||(ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1],ri) + r[2] + "/" + r[3] + rpad_(ff[2],ri): fill(" ", 2*ri+1 + r[2].length + r[3].length));
26307 }
26308 if((r = fmt.match(/^[#0?]+$/)) !== null) {
26309 o = "" + val;
26310 if(fmt.length <= o.length) return o;
26311 return hashq(fmt.substr(0,fmt.length-o.length)) + o;
26312 }
26313 if((r = fmt.match(/^([#0]+)\.([#0]+)$/)) !== null) {
26314 o = "" + val.toFixed(Math.min(r[2].length,10)).replace(/([^0])0+$/,"$1");
26315 ri = o.indexOf(".");
26316 var lres = fmt.indexOf(".") - ri, rres = fmt.length - o.length - lres;
26317 return hashq(fmt.substr(0,lres) + o + fmt.substr(fmt.length-rres));
26318 }
26319 if((r = fmt.match(/^00,000\.([#0]*0)$/)) !== null) {
26320 return val < 0 ? "-" + write_num_int(type, fmt, -val) : commaify(""+val).replace(/^\d,\d{3}$/,"0$&").replace(/^\d*$/,function($$) { return "00," + ($$.length < 3 ? pad0(0,3-$$.length) : "") + $$; }) + "." + pad0(0,r[1].length);
26321 }
26322 switch(fmt) {
26323 case "#,###": var x = commaify(""+aval); return x !== "0" ? sign + x : "";
26324 default:
26325 }
26326 throw new Error("unsupported format |" + fmt + "|");
26327 }
26328 return function write_num(type, fmt, val) {
26329 return (val|0) === val ? write_num_int(type, fmt, val) : write_num_flt(type, fmt, val);
26330 };})();
26331 function split_fmt(fmt) {
26332 var out = [];
26333 var in_str = false, cc;
26334 for(var i = 0, j = 0; i < fmt.length; ++i) switch((cc=fmt.charCodeAt(i))) {
26335 case 34: /* '"' */
26336 in_str = !in_str; break;
26337 case 95: case 42: case 92: /* '_' '*' '\\' */
26338 ++i; break;
26339 case 59: /* ';' */
26340 out[out.length] = fmt.substr(j,i-j);
26341 j = i+1;
26342 }
26343 out[out.length] = fmt.substr(j);
26344 if(in_str === true) throw new Error("Format |" + fmt + "| unterminated string ");
26345 return out;
26346 }
26347 SSF._split = split_fmt;
26348 var abstime = /\[[HhMmSs]*\]/;
26349 function eval_fmt(fmt, v, opts, flen) {
26350 var out = [], o = "", i = 0, c = "", lst='t', q, dt, j, cc;
26351 var hr='H';
26352 /* Tokenize */
26353 while(i < fmt.length) {
26354 switch((c = fmt[i])) {
26355 case 'G': /* General */
26356 if(!isgeneral(fmt, i)) throw new Error('unrecognized character ' + c + ' in ' +fmt);
26357 out[out.length] = {t:'G', v:'General'}; i+=7; break;
26358 case '"': /* Literal text */
26359 for(o="";(cc=fmt.charCodeAt(++i)) !== 34 && i < fmt.length;) o += String.fromCharCode(cc);
26360 out[out.length] = {t:'t', v:o}; ++i; break;
26361 case '\\': var w = fmt[++i], t = (w === "(" || w === ")") ? w : 't';
26362 out[out.length] = {t:t, v:w}; ++i; break;
26363 case '_': out[out.length] = {t:'t', v:" "}; i+=2; break;
26364 case '@': /* Text Placeholder */
26365 out[out.length] = {t:'T', v:v}; ++i; break;
26366 case 'B': case 'b':
26367 if(fmt[i+1] === "1" || fmt[i+1] === "2") {
26368 if(dt==null) { dt=parse_date_code(v, opts, fmt[i+1] === "2"); if(dt==null) return ""; }
26369 out[out.length] = {t:'X', v:fmt.substr(i,2)}; lst = c; i+=2; break;
26370 }
26371 /* falls through */
26372 case 'M': case 'D': case 'Y': case 'H': case 'S': case 'E':
26373 c = c.toLowerCase();
26374 /* falls through */
26375 case 'm': case 'd': case 'y': case 'h': case 's': case 'e': case 'g':
26376 if(v < 0) return "";
26377 if(dt==null) { dt=parse_date_code(v, opts); if(dt==null) return ""; }
26378 o = c; while(++i<fmt.length && fmt[i].toLowerCase() === c) o+=c;
26379 if(c === 'm' && lst.toLowerCase() === 'h') c = 'M'; /* m = minute */
26380 if(c === 'h') c = hr;
26381 out[out.length] = {t:c, v:o}; lst = c; break;
26382 case 'A':
26383 q={t:c, v:"A"};
26384 if(dt==null) dt=parse_date_code(v, opts);
26385 if(fmt.substr(i, 3) === "A/P") { if(dt!=null) q.v = dt.H >= 12 ? "P" : "A"; q.t = 'T'; hr='h';i+=3;}
26386 else if(fmt.substr(i,5) === "AM/PM") { if(dt!=null) q.v = dt.H >= 12 ? "PM" : "AM"; q.t = 'T'; i+=5; hr='h'; }
26387 else { q.t = "t"; ++i; }
26388 if(dt==null && q.t === 'T') return "";
26389 out[out.length] = q; lst = c; break;
26390 case '[':
26391 o = c;
26392 while(fmt[i++] !== ']' && i < fmt.length) o += fmt[i];
26393 if(o.substr(-1) !== ']') throw 'unterminated "[" block: |' + o + '|';
26394 if(o.match(abstime)) {
26395 if(dt==null) { dt=parse_date_code(v, opts); if(dt==null) return ""; }
26396 out[out.length] = {t:'Z', v:o.toLowerCase()};
26397 } else { o=""; }
26398 break;
26399 /* Numbers */
26400 case '.':
26401 if(dt != null) {
26402 o = c; while((c=fmt[++i]) === "0") o += c;
26403 out[out.length] = {t:'s', v:o}; break;
26404 }
26405 /* falls through */
26406 case '0': case '#':
26407 o = c; while("0#?.,E+-%".indexOf(c=fmt[++i]) > -1 || c=='\\' && fmt[i+1] == "-" && "0#".indexOf(fmt[i+2])>-1) o += c;
26408 out[out.length] = {t:'n', v:o}; break;
26409 case '?':
26410 o = c; while(fmt[++i] === c) o+=c;
26411 q={t:c, v:o}; out[out.length] = q; lst = c; break;
26412 case '*': ++i; if(fmt[i] == ' ' || fmt[i] == '*') ++i; break; // **
26413 case '(': case ')': out[out.length] = {t:(flen===1?'t':c), v:c}; ++i; break;
26414 case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
26415 o = c; while("0123456789".indexOf(fmt[++i]) > -1) o+=fmt[i];
26416 out[out.length] = {t:'D', v:o}; break;
26417 case ' ': out[out.length] = {t:c, v:c}; ++i; break;
26418 default:
26419 if(",$-+/():!^&'~{}<>=€acfijklopqrtuvwxz".indexOf(c) === -1) throw new Error('unrecognized character ' + c + ' in ' + fmt);
26420 out[out.length] = {t:'t', v:c}; ++i; break;
26421 }
26422 }
26423 var bt = 0, ss0 = 0, ssm;
26424 for(i=out.length-1, lst='t'; i >= 0; --i) {
26425 switch(out[i].t) {
26426 case 'h': case 'H': out[i].t = hr; lst='h'; if(bt < 1) bt = 1; break;
26427 case 's':
26428 if((ssm=out[i].v.match(/\.0+$/))) ss0=Math.max(ss0,ssm[0].length-1);
26429 if(bt < 3) bt = 3;
26430 /* falls through */
26431 case 'd': case 'y': case 'M': case 'e': lst=out[i].t; break;
26432 case 'm': if(lst === 's') { out[i].t = 'M'; if(bt < 2) bt = 2; } break;
26433 case 'X': if(out[i].v === "B2");
26434 break;
26435 case 'Z':
26436 if(bt < 1 && out[i].v.match(/[Hh]/)) bt = 1;
26437 if(bt < 2 && out[i].v.match(/[Mm]/)) bt = 2;
26438 if(bt < 3 && out[i].v.match(/[Ss]/)) bt = 3;
26439 }
26440 }
26441 switch(bt) {
26442 case 0: break;
26443 case 1:
26444 if(dt.u >= 0.5) { dt.u = 0; ++dt.S; }
26445 if(dt.S >= 60) { dt.S = 0; ++dt.M; }
26446 if(dt.M >= 60) { dt.M = 0; ++dt.H; }
26447 break;
26448 case 2:
26449 if(dt.u >= 0.5) { dt.u = 0; ++dt.S; }
26450 if(dt.S >= 60) { dt.S = 0; ++dt.M; }
26451 break;
26452 }
26453 /* replace fields */
26454 var nstr = "", jj;
26455 for(i=0; i < out.length; ++i) {
26456 switch(out[i].t) {
26457 case 't': case 'T': case ' ': case 'D': break;
26458 case 'X': out[i] = undefined; break;
26459 case 'd': case 'm': case 'y': case 'h': case 'H': case 'M': case 's': case 'e': case 'b': case 'Z':
26460 out[i].v = write_date(out[i].t.charCodeAt(0), out[i].v, dt, ss0);
26461 out[i].t = 't'; break;
26462 case 'n': case '(': case '?':
26463 jj = i+1;
26464 while(out[jj] != null && (
26465 (c=out[jj].t) === "?" || c === "D" ||
26466 (c === " " || c === "t") && out[jj+1] != null && (out[jj+1].t === '?' || out[jj+1].t === "t" && out[jj+1].v === '/') ||
26467 out[i].t === '(' && (c === ' ' || c === 'n' || c === ')') ||
26468 c === 't' && (out[jj].v === '/' || '$€'.indexOf(out[jj].v) > -1 || out[jj].v === ' ' && out[jj+1] != null && out[jj+1].t == '?')
26469 )) {
26470 out[i].v += out[jj].v;
26471 out[jj] = undefined; ++jj;
26472 }
26473 nstr += out[i].v;
26474 i = jj-1; break;
26475 case 'G': out[i].t = 't'; out[i].v = general_fmt(v,opts); break;
26476 }
26477 }
26478 var vv = "", myv, ostr;
26479 if(nstr.length > 0) {
26480 myv = (v<0&&nstr.charCodeAt(0) === 45 ? -v : v); /* '-' */
26481 ostr = write_num(nstr.charCodeAt(0) === 40 ? '(' : 'n', nstr, myv); /* '(' */
26482 jj=ostr.length-1;
26483 var decpt = out.length;
26484 for(i=0; i < out.length; ++i) if(out[i] != null && out[i].v.indexOf(".") > -1) { decpt = i; break; }
26485 var lasti=out.length;
26486 if(decpt === out.length && ostr.indexOf("E") === -1) {
26487 for(i=out.length-1; i>= 0;--i) {
26488 if(out[i] == null || 'n?('.indexOf(out[i].t) === -1) continue;
26489 if(jj>=out[i].v.length-1) { jj -= out[i].v.length; out[i].v = ostr.substr(jj+1, out[i].v.length); }
26490 else if(jj < 0) out[i].v = "";
26491 else { out[i].v = ostr.substr(0, jj+1); jj = -1; }
26492 out[i].t = 't';
26493 lasti = i;
26494 }
26495 if(jj>=0 && lasti<out.length) out[lasti].v = ostr.substr(0,jj+1) + out[lasti].v;
26496 }
26497 else if(decpt !== out.length && ostr.indexOf("E") === -1) {
26498 jj = ostr.indexOf(".")-1;
26499 for(i=decpt; i>= 0; --i) {
26500 if(out[i] == null || 'n?('.indexOf(out[i].t) === -1) continue;
26501 j=out[i].v.indexOf(".")>-1&&i===decpt?out[i].v.indexOf(".")-1:out[i].v.length-1;
26502 vv = out[i].v.substr(j+1);
26503 for(; j>=0; --j) {
26504 if(jj>=0 && (out[i].v[j] === "0" || out[i].v[j] === "#")) vv = ostr[jj--] + vv;
26505 }
26506 out[i].v = vv;
26507 out[i].t = 't';
26508 lasti = i;
26509 }
26510 if(jj>=0 && lasti<out.length) out[lasti].v = ostr.substr(0,jj+1) + out[lasti].v;
26511 jj = ostr.indexOf(".")+1;
26512 for(i=decpt; i<out.length; ++i) {
26513 if(out[i] == null || 'n?('.indexOf(out[i].t) === -1 && i !== decpt ) continue;
26514 j=out[i].v.indexOf(".")>-1&&i===decpt?out[i].v.indexOf(".")+1:0;
26515 vv = out[i].v.substr(0,j);
26516 for(; j<out[i].v.length; ++j) {
26517 if(jj<ostr.length) vv += ostr[jj++];
26518 }
26519 out[i].v = vv;
26520 out[i].t = 't';
26521 lasti = i;
26522 }
26523 }
26524 }
26525 for(i=0; i<out.length; ++i) if(out[i] != null && 'n(?'.indexOf(out[i].t)>-1) {
26526 myv = (flen >1 && v < 0 && i>0 && out[i-1].v === "-" ? -v:v);
26527 out[i].v = write_num(out[i].t, out[i].v, myv);
26528 out[i].t = 't';
26529 }
26530 var retval = "";
26531 for(i=0; i !== out.length; ++i) if(out[i] != null) retval += out[i].v;
26532 return retval;
26533 }
26534 SSF._eval = eval_fmt;
26535 var cfregex = /\[[=<>]/;
26536 var cfregex2 = /\[([=<>]*)(-?\d+\.?\d*)\]/;
26537 function chkcond(v, rr) {
26538 if(rr == null) return false;
26539 var thresh = parseFloat(rr[2]);
26540 switch(rr[1]) {
26541 case "=": if(v == thresh) return true; break;
26542 case ">": if(v > thresh) return true; break;
26543 case "<": if(v < thresh) return true; break;
26544 case "<>": if(v != thresh) return true; break;
26545 case ">=": if(v >= thresh) return true; break;
26546 case "<=": if(v <= thresh) return true; break;
26547 }
26548 return false;
26549 }
26550 function choose_fmt(f, v) {
26551 var fmt = split_fmt(f);
26552 var l = fmt.length, lat = fmt[l-1].indexOf("@");
26553 if(l<4 && lat>-1) --l;
26554 if(fmt.length > 4) throw "cannot find right format for |" + fmt + "|";
26555 if(typeof v !== "number") return [4, fmt.length === 4 || lat>-1?fmt[fmt.length-1]:"@"];
26556 switch(fmt.length) {
26557 case 1: fmt = lat>-1 ? ["General", "General", "General", fmt[0]] : [fmt[0], fmt[0], fmt[0], "@"]; break;
26558 case 2: fmt = lat>-1 ? [fmt[0], fmt[0], fmt[0], fmt[1]] : [fmt[0], fmt[1], fmt[0], "@"]; break;
26559 case 3: fmt = lat>-1 ? [fmt[0], fmt[1], fmt[0], fmt[2]] : [fmt[0], fmt[1], fmt[2], "@"]; break;
26560 case 4: break;
26561 }
26562 var ff = v > 0 ? fmt[0] : v < 0 ? fmt[1] : fmt[2];
26563 if(fmt[0].indexOf("[") === -1 && fmt[1].indexOf("[") === -1) return [l, ff];
26564 if(fmt[0].match(cfregex) != null || fmt[1].match(cfregex) != null) {
26565 var m1 = fmt[0].match(cfregex2);
26566 var m2 = fmt[1].match(cfregex2);
26567 return chkcond(v, m1) ? [l, fmt[0]] : chkcond(v, m2) ? [l, fmt[1]] : [l, fmt[m1 != null && m2 != null ? 2 : 1]];
26568 }
26569 return [l, ff];
26570 }
26571 function format(fmt,v,o) {
26572 fixopts(o != null ? o : (o=[]));
26573 var sfmt = "";
26574 switch(typeof fmt) {
26575 case "string": sfmt = fmt; break;
26576 case "number": sfmt = (o.table != null ? o.table : table_fmt)[fmt]; break;
26577 }
26578 if(isgeneral(sfmt,0)) return general_fmt(v, o);
26579 var f = choose_fmt(sfmt, v);
26580 if(isgeneral(f[1])) return general_fmt(v, o);
26581 if(v === true) v = "TRUE"; else if(v === false) v = "FALSE";
26582 else if(v === "" || v == null) return "";
26583 return eval_fmt(f[1], v, o, f[0]);
26584 }
26585 SSF._table = table_fmt;
26586 SSF.load = function load_entry(fmt, idx) { table_fmt[idx] = fmt; };
26587 SSF.format = format;
26588 SSF.get_table = function get_table() { return table_fmt; };
26589 SSF.load_table = function load_table(tbl) { for(var i=0; i!=0x0188; ++i) if(tbl[i] !== undefined) SSF.load(tbl[i], i); };
26590 };
26591 make_ssf(SSF);
26592 function isval(x) { return x !== undefined && x !== null; }
26593
26594 function keys(o) { return Object.keys(o); }
26595
26596 function evert_key(obj, key) {
26597 var o = [], K = keys(obj);
26598 for(var i = 0; i !== K.length; ++i) o[obj[K[i]][key]] = K[i];
26599 return o;
26600 }
26601
26602 function evert(obj) {
26603 var o = [], K = keys(obj);
26604 for(var i = 0; i !== K.length; ++i) o[obj[K[i]]] = K[i];
26605 return o;
26606 }
26607
26608 function evert_num(obj) {
26609 var o = [], K = keys(obj);
26610 for(var i = 0; i !== K.length; ++i) o[obj[K[i]]] = parseInt(K[i],10);
26611 return o;
26612 }
26613
26614 function evert_arr(obj) {
26615 var o = [], K = keys(obj);
26616 for(var i = 0; i !== K.length; ++i) {
26617 if(o[obj[K[i]]] == null) o[obj[K[i]]] = [];
26618 o[obj[K[i]]].push(K[i]);
26619 }
26620 return o;
26621 }
26622
26623 /* TODO: date1904 logic */
26624 function datenum(v, date1904) {
26625 if(date1904) v+=1462;
26626 var epoch = Date.parse(v);
26627 return (epoch + 2209161600000) / (24 * 60 * 60 * 1000);
26628 }
26629
26630 function cc2str(arr) {
26631 var o = "";
26632 for(var i = 0; i != arr.length; ++i) o += String.fromCharCode(arr[i]);
26633 return o;
26634 }
26635
26636 var has_buf = (typeof Buffer !== 'undefined');
26637 function getdata(data) {
26638 if(!data) return null;
26639 if(data.name.substr(-4) === ".bin") {
26640 if(data.data) return char_codes(data.data);
26641 if(data.asNodeBuffer && has_buf) return data.asNodeBuffer();
26642 if(data._data && data._data.getContent) return Array.prototype.slice.call(data._data.getContent());
26643 } else {
26644 if(data.data) return data.name.substr(-4) !== ".bin" ? debom_xml(data.data) : char_codes(data.data);
26645 if(data.asNodeBuffer && has_buf) return debom_xml(data.asNodeBuffer().toString('binary'));
26646 if(data.asBinary) return debom_xml(data.asBinary());
26647 if(data._data && data._data.getContent) return debom_xml(cc2str(Array.prototype.slice.call(data._data.getContent(),0)));
26648 }
26649 return null;
26650 }
26651
26652 function getzipfile(zip, file) {
26653 var f = file; if(zip.files[f]) return zip.files[f];
26654 f = file.toLowerCase(); if(zip.files[f]) return zip.files[f];
26655 f = f.replace(/\//g,'\\'); if(zip.files[f]) return zip.files[f];
26656 throw new Error("Cannot find file " + file + " in zip");
26657 }
26658
26659 function getzipdata(zip, file, safe) {
26660 if(!safe) return getdata(getzipfile(zip, file));
26661 if(!file) return null;
26662 try { return getzipdata(zip, file); } catch(e) { return null; }
26663 }
26664
26665 var _fs, jszip;
26666 if(typeof JSZip !== 'undefined') jszip = JSZip;
26667 if (typeof exports !== 'undefined') {
26668 if (typeof module !== 'undefined' && module.exports) {
26669 if(has_buf && typeof jszip === 'undefined') jszip = require('js'+'zip');
26670 if(typeof jszip === 'undefined') jszip = require('./js'+'zip').JSZip;
26671 _fs = require('f'+'s');
26672 }
26673 }
26674 var attregexg=/\b[\w:]+=["'][^"]*['"]/g;
26675 var tagregex=/<[^>]*>/g;
26676 var nsregex=/<\w*:/, nsregex2 = /<(\/?)\w+:/;
26677 function parsexmltag(tag, skip_root) {
26678 var z = [];
26679 var eq = 0, c = 0;
26680 for(; eq !== tag.length; ++eq) if((c = tag.charCodeAt(eq)) === 32 || c === 10 || c === 13) break;
26681 if(!skip_root) z[0] = tag.substr(0, eq);
26682 if(eq === tag.length) return z;
26683 var m = tag.match(attregexg), j=0, w="", v="", i=0, q="", cc="";
26684 if(m) for(i = 0; i != m.length; ++i) {
26685 cc = m[i];
26686 for(c=0; c != cc.length; ++c) if(cc.charCodeAt(c) === 61) break;
26687 q = cc.substr(0,c); v = cc.substring(c+2, cc.length-1);
26688 for(j=0;j!=q.length;++j) if(q.charCodeAt(j) === 58) break;
26689 if(j===q.length) z[q] = v;
26690 else z[(j===5 && q.substr(0,5)==="xmlns"?"xmlns":"")+q.substr(j+1)] = v;
26691 }
26692 return z;
26693 }
26694 function strip_ns(x) { return x.replace(nsregex2, "<$1"); }
26695
26696 var encodings = {
26697 '&quot;': '"',
26698 '&apos;': "'",
26699 '&gt;': '>',
26700 '&lt;': '<',
26701 '&amp;': '&'
26702 };
26703 var rencoding = evert(encodings);
26704 var rencstr = "&<>'\"".split("");
26705
26706 // TODO: CP remap (need to read file version to determine OS)
26707 var encregex = /&[a-z]*;/g, coderegex = /_x([\da-fA-F]+)_/g;
26708 function unescapexml(text){
26709 var s = text + '';
26710 return s.replace(encregex, function($$) { return encodings[$$]; }).replace(coderegex,function(m,c) {return String.fromCharCode(parseInt(c,16));});
26711 }
26712 var decregex=/[&<>'"]/g, charegex = /[\u0000-\u0008\u000b-\u001f]/g;
26713 function escapexml(text){
26714 var s = text + '';
26715 return s.replace(decregex, function(y) { return rencoding[y]; }).replace(charegex,function(s) { return "_x" + ("000"+s.charCodeAt(0).toString(16)).substr(-4) + "_";});
26716 }
26717
26718 function parsexmlbool(value, tag) {
26719 switch(value) {
26720 case '1': case 'true': case 'TRUE': return true;
26721 /* case '0': case 'false': case 'FALSE':*/
26722 default: return false;
26723 }
26724 }
26725
26726 var utf8read = function utf8reada(orig) {
26727 var out = "", i = 0, c = 0, d = 0, e = 0, f = 0, w = 0;
26728 while (i < orig.length) {
26729 c = orig.charCodeAt(i++);
26730 if (c < 128) { out += String.fromCharCode(c); continue; }
26731 d = orig.charCodeAt(i++);
26732 if (c>191 && c<224) { out += String.fromCharCode(((c & 31) << 6) | (d & 63)); continue; }
26733 e = orig.charCodeAt(i++);
26734 if (c < 240) { out += String.fromCharCode(((c & 15) << 12) | ((d & 63) << 6) | (e & 63)); continue; }
26735 f = orig.charCodeAt(i++);
26736 w = (((c & 7) << 18) | ((d & 63) << 12) | ((e & 63) << 6) | (f & 63))-65536;
26737 out += String.fromCharCode(0xD800 + ((w>>>10)&1023));
26738 out += String.fromCharCode(0xDC00 + (w&1023));
26739 }
26740 return out;
26741 };
26742
26743
26744 if(has_buf) {
26745 var utf8readb = function utf8readb(data) {
26746 var out = new Buffer(2*data.length), w, i, j = 1, k = 0, ww=0, c;
26747 for(i = 0; i < data.length; i+=j) {
26748 j = 1;
26749 if((c=data.charCodeAt(i)) < 128) w = c;
26750 else if(c < 224) { w = (c&31)*64+(data.charCodeAt(i+1)&63); j=2; }
26751 else if(c < 240) { w=(c&15)*4096+(data.charCodeAt(i+1)&63)*64+(data.charCodeAt(i+2)&63); j=3; }
26752 else { j = 4;
26753 w = (c & 7)*262144+(data.charCodeAt(i+1)&63)*4096+(data.charCodeAt(i+2)&63)*64+(data.charCodeAt(i+3)&63);
26754 w -= 65536; ww = 0xD800 + ((w>>>10)&1023); w = 0xDC00 + (w&1023);
26755 }
26756 if(ww !== 0) { out[k++] = ww&255; out[k++] = ww>>>8; ww = 0; }
26757 out[k++] = w%256; out[k++] = w>>>8;
26758 }
26759 out.length = k;
26760 return out.toString('ucs2');
26761 };
26762 var corpus = "foo bar baz\u00e2\u0098\u0083\u00f0\u009f\u008d\u00a3";
26763 if(utf8read(corpus) == utf8readb(corpus)) utf8read = utf8readb;
26764 var utf8readc = function utf8readc(data) { return Buffer(data, 'binary').toString('utf8'); };
26765 if(utf8read(corpus) == utf8readc(corpus)) utf8read = utf8readc;
26766 }
26767
26768 // matches <foo>...</foo> extracts content
26769 var matchtag = (function() {
26770 var mtcache = {};
26771 return function matchtag(f,g) {
26772 var t = f+"|"+g;
26773 if(mtcache[t] !== undefined) return mtcache[t];
26774 return (mtcache[t] = new RegExp('<(?:\\w+:)?'+f+'(?: xml:space="preserve")?(?:[^>]*)>([^\u2603]*)</(?:\\w+:)?'+f+'>',(g||"")));
26775 };
26776 })();
26777
26778 var vtregex = (function(){ var vt_cache = {};
26779 return function vt_regex(bt) {
26780 if(vt_cache[bt] !== undefined) return vt_cache[bt];
26781 return (vt_cache[bt] = new RegExp("<vt:" + bt + ">(.*?)</vt:" + bt + ">", 'g') );
26782 };})();
26783 var vtvregex = /<\/?vt:variant>/g, vtmregex = /<vt:([^>]*)>(.*)</;
26784 function parseVector(data) {
26785 var h = parsexmltag(data);
26786
26787 var matches = data.match(vtregex(h.baseType))||[];
26788 if(matches.length != h.size) throw "unexpected vector length " + matches.length + " != " + h.size;
26789 var res = [];
26790 matches.forEach(function(x) {
26791 var v = x.replace(vtvregex,"").match(vtmregex);
26792 res.push({v:v[2], t:v[1]});
26793 });
26794 return res;
26795 }
26796
26797 var wtregex = /(^\s|\s$|\n)/;
26798 function writetag(f,g) {return '<' + f + (g.match(wtregex)?' xml:space="preserve"' : "") + '>' + g + '</' + f + '>';}
26799
26800 function wxt_helper(h) { return keys(h).map(function(k) { return " " + k + '="' + h[k] + '"';}).join(""); }
26801 function writextag(f,g,h) { return '<' + f + (isval(h) ? wxt_helper(h) : "") + (isval(g) ? (g.match(wtregex)?' xml:space="preserve"' : "") + '>' + g + '</' + f : "/") + '>';}
26802
26803 function write_w3cdtf(d, t) { try { return d.toISOString().replace(/\.\d*/,""); } catch(e) { if(t) throw e; } }
26804
26805 function write_vt(s) {
26806 switch(typeof s) {
26807 case 'string': return writextag('vt:lpwstr', s);
26808 case 'number': return writextag((s|0)==s?'vt:i4':'vt:r8', String(s));
26809 case 'boolean': return writextag('vt:bool',s?'true':'false');
26810 }
26811 if(s instanceof Date) return writextag('vt:filetime', write_w3cdtf(s));
26812 throw new Error("Unable to serialize " + s);
26813 }
26814
26815 var XML_HEADER = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n';
26816 var XMLNS = {
26817 'dc': 'http://purl.org/dc/elements/1.1/',
26818 'dcterms': 'http://purl.org/dc/terms/',
26819 'dcmitype': 'http://purl.org/dc/dcmitype/',
26820 'mx': 'http://schemas.microsoft.com/office/mac/excel/2008/main',
26821 'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
26822 'sjs': 'http://schemas.openxmlformats.org/package/2006/sheetjs/core-properties',
26823 'vt': 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes',
26824 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
26825 'xsd': 'http://www.w3.org/2001/XMLSchema'
26826 };
26827
26828 XMLNS.main = [
26829 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
26830 'http://purl.oclc.org/ooxml/spreadsheetml/main',
26831 'http://schemas.microsoft.com/office/excel/2006/main',
26832 'http://schemas.microsoft.com/office/excel/2006/2'
26833 ];
26834 function readIEEE754(buf, idx, isLE, nl, ml) {
26835 if(isLE === undefined) isLE = true;
26836 if(!nl) nl = 8;
26837 if(!ml && nl === 8) ml = 52;
26838 var e, m, el = nl * 8 - ml - 1, eMax = (1 << el) - 1, eBias = eMax >> 1;
26839 var bits = -7, d = isLE ? -1 : 1, i = isLE ? (nl - 1) : 0, s = buf[idx + i];
26840
26841 i += d;
26842 e = s & ((1 << (-bits)) - 1); s >>>= (-bits); bits += el;
26843 for (; bits > 0; e = e * 256 + buf[idx + i], i += d, bits -= 8);
26844 m = e & ((1 << (-bits)) - 1); e >>>= (-bits); bits += ml;
26845 for (; bits > 0; m = m * 256 + buf[idx + i], i += d, bits -= 8);
26846 if (e === eMax) return m ? NaN : ((s ? -1 : 1) * Infinity);
26847 else if (e === 0) e = 1 - eBias;
26848 else { m = m + Math.pow(2, ml); e = e - eBias; }
26849 return (s ? -1 : 1) * m * Math.pow(2, e - ml);
26850 }
26851
26852 var __toBuffer, ___toBuffer;
26853 __toBuffer = ___toBuffer = function toBuffer_(bufs) { var x = []; for(var i = 0; i < bufs[0].length; ++i) { x.push.apply(x, bufs[0][i]); } return x; };
26854 var __double, ___double;
26855 __double = ___double = function(b, idx) { return readIEEE754(b, idx);};
26856
26857 var is_buf = function is_buf_a(a) { return Array.isArray(a); };
26858 if(has_buf) {
26859 __toBuffer = function(bufs) { return (bufs[0].length > 0 && Buffer.isBuffer(bufs[0][0])) ? Buffer.concat(bufs[0]) : ___toBuffer(bufs);};
26860 __double = function double_(b,i) { if(Buffer.isBuffer(b)) return b.readDoubleLE(i); return ___double(b,i); };
26861 is_buf = function is_buf_b(a) { return Buffer.isBuffer(a) || Array.isArray(a); };
26862 }
26863
26864
26865 var __readUInt8 = function(b, idx) { return b[idx]; };
26866 var __readUInt16LE = function(b, idx) { return b[idx+1]*(1<<8)+b[idx]; };
26867 var __readInt16LE = function(b, idx) { var u = b[idx+1]*(1<<8)+b[idx]; return (u < 0x8000) ? u : (0xffff - u + 1) * -1; };
26868 var __readUInt32LE = function(b, idx) { return b[idx+3]*(1<<24)+(b[idx+2]<<16)+(b[idx+1]<<8)+b[idx]; };
26869 var __readInt32LE = function(b, idx) { return (b[idx+3]<<24)|(b[idx+2]<<16)|(b[idx+1]<<8)|b[idx]; };
26870
26871
26872 function ReadShift(size, t) {
26873 var o="", oo=[], w, vv, i, loc;
26874 if(t === 'dbcs') {
26875 loc = this.l;
26876 if(has_buf && Buffer.isBuffer(this)) o = this.slice(this.l, this.l+2*size).toString("utf16le");
26877 else for(i = 0; i != size; ++i) { o+=String.fromCharCode(__readUInt16LE(this, loc)); loc+=2; }
26878 size *= 2;
26879 } else switch(size) {
26880 case 1: o = __readUInt8(this, this.l); break;
26881 case 2: o = (t === 'i' ? __readInt16LE : __readUInt16LE)(this, this.l); break;
26882 case 4: o = __readUInt32LE(this, this.l); break;
26883 case 8: if(t === 'f') { o = __double(this, this.l); break; }
26884 }
26885 this.l+=size; return o;
26886 }
26887
26888 function WriteShift(t, val, f) {
26889 var size, i;
26890 if(f === 'dbcs') {
26891 for(i = 0; i != val.length; ++i) this.writeUInt16LE(val.charCodeAt(i), this.l + 2 * i);
26892 size = 2 * val.length;
26893 } else switch(t) {
26894 case 1: size = 1; this[this.l] = val&255; break;
26895 case 3: size = 3; this[this.l+2] = val & 255; val >>>= 8; this[this.l+1] = val&255; val >>>= 8; this[this.l] = val&255; break;
26896 case 4: size = 4; this.writeUInt32LE(val, this.l); break;
26897 case 8: size = 8; if(f === 'f') { this.writeDoubleLE(val, this.l); break; }
26898 /* falls through */
26899 case 16: break;
26900 case -4: size = 4; this.writeInt32LE(val, this.l); break;
26901 }
26902 this.l += size; return this;
26903 }
26904
26905 function prep_blob(blob, pos) {
26906 blob.l = pos;
26907 blob.read_shift = ReadShift;
26908 blob.write_shift = WriteShift;
26909 }
26910
26911 function parsenoop(blob, length) { blob.l += length; }
26912
26913 function writenoop(blob, length) { blob.l += length; }
26914
26915 function new_buf(sz) {
26916 var o = has_buf ? new Buffer(sz) : new Array(sz);
26917 prep_blob(o, 0);
26918 return o;
26919 }
26920
26921 /* [MS-XLSB] 2.1.4 Record */
26922 function recordhopper(data, cb, opts) {
26923 var tmpbyte, cntbyte, length;
26924 prep_blob(data, data.l || 0);
26925 while(data.l < data.length) {
26926 var RT = data.read_shift(1);
26927 if(RT & 0x80) RT = (RT & 0x7F) + ((data.read_shift(1) & 0x7F)<<7);
26928 var R = RecordEnum[RT] || RecordEnum[0xFFFF];
26929 tmpbyte = data.read_shift(1);
26930 length = tmpbyte & 0x7F;
26931 for(cntbyte = 1; cntbyte <4 && (tmpbyte & 0x80); ++cntbyte) length += ((tmpbyte = data.read_shift(1)) & 0x7F)<<(7*cntbyte);
26932 var d = R.f(data, length, opts);
26933 if(cb(d, R, RT)) return;
26934 }
26935 }
26936
26937 /* control buffer usage for fixed-length buffers */
26938 function buf_array() {
26939 var bufs = [], blksz = 2048;
26940 var newblk = function ba_newblk(sz) {
26941 var o = new_buf(sz);
26942 prep_blob(o, 0);
26943 return o;
26944 };
26945
26946 var curbuf = newblk(blksz);
26947
26948 var endbuf = function ba_endbuf() {
26949 curbuf.length = curbuf.l;
26950 if(curbuf.length > 0) bufs.push(curbuf);
26951 curbuf = null;
26952 };
26953
26954 var next = function ba_next(sz) {
26955 if(sz < curbuf.length - curbuf.l) return curbuf;
26956 endbuf();
26957 return (curbuf = newblk(Math.max(sz+1, blksz)));
26958 };
26959
26960 var end = function ba_end() {
26961 endbuf();
26962 return __toBuffer([bufs]);
26963 };
26964
26965 var push = function ba_push(buf) { endbuf(); curbuf = buf; next(blksz); };
26966
26967 return { next:next, push:push, end:end, _bufs:bufs };
26968 }
26969
26970 function write_record(ba, type, payload, length) {
26971 var t = evert_RE[type], l;
26972 if(!length) length = RecordEnum[t].p || (payload||[]).length || 0;
26973 l = 1 + (t >= 0x80 ? 1 : 0) + 1 + length;
26974 if(length >= 0x80) ++l; if(length >= 0x4000) ++l; if(length >= 0x200000) ++l;
26975 var o = ba.next(l);
26976 if(t <= 0x7F) o.write_shift(1, t);
26977 else {
26978 o.write_shift(1, (t & 0x7F) + 0x80);
26979 o.write_shift(1, (t >> 7));
26980 }
26981 for(var i = 0; i != 4; ++i) {
26982 if(length >= 0x80) { o.write_shift(1, (length & 0x7F)+0x80); length >>= 7; }
26983 else { o.write_shift(1, length); break; }
26984 }
26985 if(length > 0 && is_buf(payload)) ba.push(payload);
26986 }
26987
26988 /* [MS-XLSB] 2.5.143 */
26989 function parse_StrRun(data, length) {
26990 return { ich: data.read_shift(2), ifnt: data.read_shift(2) };
26991 }
26992
26993 /* [MS-XLSB] 2.1.7.121 */
26994 function parse_RichStr(data, length) {
26995 var start = data.l;
26996 var flags = data.read_shift(1);
26997 var str = parse_XLWideString(data);
26998 var rgsStrRun = [];
26999 var z = { t: str, h: str };
27000 if((flags & 1) !== 0) { /* fRichStr */
27001 /* TODO: formatted string */
27002 var dwSizeStrRun = data.read_shift(4);
27003 for(var i = 0; i != dwSizeStrRun; ++i) rgsStrRun.push(parse_StrRun(data));
27004 z.r = rgsStrRun;
27005 }
27006 else z.r = "<t>" + escapexml(str) + "</t>";
27007 if((flags & 2) !== 0) { /* fExtStr */
27008 /* TODO: phonetic string */
27009 }
27010 data.l = start + length;
27011 return z;
27012 }
27013 function write_RichStr(str, o) {
27014 /* TODO: formatted string */
27015 if(o == null) o = new_buf(5+2*str.t.length);
27016 o.write_shift(1,0);
27017 write_XLWideString(str.t, o);
27018 return o;
27019 }
27020
27021 /* [MS-XLSB] 2.5.9 */
27022 function parse_Cell(data) {
27023 var col = data.read_shift(4);
27024 var iStyleRef = data.read_shift(2);
27025 iStyleRef += data.read_shift(1) <<16;
27026 var fPhShow = data.read_shift(1);
27027 return { c:col, iStyleRef: iStyleRef };
27028 }
27029 function write_Cell(cell, o) {
27030 if(o == null) o = new_buf(8);
27031 o.write_shift(-4, cell.c);
27032 o.write_shift(3, cell.iStyleRef === undefined ? cell.iStyleRef : cell.s);
27033 o.write_shift(1, 0); /* fPhShow */
27034 return o;
27035 }
27036
27037
27038 /* [MS-XLSB] 2.5.21 */
27039 function parse_CodeName (data, length) { return parse_XLWideString(data, length); }
27040
27041 /* [MS-XLSB] 2.5.166 */
27042 function parse_XLNullableWideString(data) {
27043 var cchCharacters = data.read_shift(4);
27044 return cchCharacters === 0 || cchCharacters === 0xFFFFFFFF ? "" : data.read_shift(cchCharacters, 'dbcs');
27045 }
27046 function write_XLNullableWideString(data, o) {
27047 if(!o) o = new_buf(127);
27048 o.write_shift(4, data.length > 0 ? data.length : 0xFFFFFFFF);
27049 if(data.length > 0) o.write_shift(0, data, 'dbcs');
27050 return o;
27051 }
27052
27053 /* [MS-XLSB] 2.5.168 */
27054 function parse_XLWideString(data) {
27055 var cchCharacters = data.read_shift(4);
27056 return cchCharacters === 0 ? "" : data.read_shift(cchCharacters, 'dbcs');
27057 }
27058 function write_XLWideString(data, o) {
27059 if(o == null) o = new_buf(4+2*data.length);
27060 o.write_shift(4, data.length);
27061 if(data.length > 0) o.write_shift(0, data, 'dbcs');
27062 return o;
27063 }
27064
27065 /* [MS-XLSB] 2.5.114 */
27066 var parse_RelID = parse_XLNullableWideString;
27067 var write_RelID = write_XLNullableWideString;
27068
27069
27070 /* [MS-XLSB] 2.5.122 */
27071 function parse_RkNumber(data) {
27072 var b = data.slice(data.l, data.l+4);
27073 var fX100 = b[0] & 1, fInt = b[0] & 2;
27074 data.l+=4;
27075 b[0] &= 0xFC;
27076 var RK = fInt === 0 ? __double([0,0,0,0,b[0],b[1],b[2],b[3]],0) : __readInt32LE(b,0)>>2;
27077 return fX100 ? RK/100 : RK;
27078 }
27079
27080 /* [MS-XLSB] 2.5.153 */
27081 function parse_UncheckedRfX(data) {
27082 var cell = {s: {}, e: {}};
27083 cell.s.r = data.read_shift(4);
27084 cell.e.r = data.read_shift(4);
27085 cell.s.c = data.read_shift(4);
27086 cell.e.c = data.read_shift(4);
27087 return cell;
27088 }
27089
27090 function write_UncheckedRfX(r, o) {
27091 if(!o) o = new_buf(16);
27092 o.write_shift(4, r.s.r);
27093 o.write_shift(4, r.e.r);
27094 o.write_shift(4, r.s.c);
27095 o.write_shift(4, r.e.c);
27096 return o;
27097 }
27098
27099 /* [MS-XLSB] 2.5.171 */
27100 function parse_Xnum(data, length) { return data.read_shift(8, 'f'); }
27101 function write_Xnum(data, o) { return (o || new_buf(8)).write_shift(8, 'f', data); }
27102
27103 /* [MS-XLSB] 2.5.198.2 */
27104 var BErr = {
27105 0x00: "#NULL!",
27106 0x07: "#DIV/0!",
27107 0x0F: "#VALUE!",
27108 0x17: "#REF!",
27109 0x1D: "#NAME?",
27110 0x24: "#NUM!",
27111 0x2A: "#N/A",
27112 0x2B: "#GETTING_DATA",
27113 0xFF: "#WTF?"
27114 };
27115 var RBErr = evert_num(BErr);
27116
27117 /* [MS-XLSB] 2.4.321 BrtColor */
27118 function parse_BrtColor(data, length) {
27119 var out = {};
27120 var d = data.read_shift(1);
27121 out.fValidRGB = d & 1;
27122 out.xColorType = d >>> 1;
27123 out.index = data.read_shift(1);
27124 out.nTintAndShade = data.read_shift(2, 'i');
27125 out.bRed = data.read_shift(1);
27126 out.bGreen = data.read_shift(1);
27127 out.bBlue = data.read_shift(1);
27128 out.bAlpha = data.read_shift(1);
27129 }
27130
27131 /* [MS-XLSB] 2.5.52 */
27132 function parse_FontFlags(data, length) {
27133 var d = data.read_shift(1);
27134 data.l++;
27135 var out = {
27136 fItalic: d & 0x2,
27137 fStrikeout: d & 0x8,
27138 fOutline: d & 0x10,
27139 fShadow: d & 0x20,
27140 fCondense: d & 0x40,
27141 fExtend: d & 0x80
27142 };
27143 return out;
27144 }
27145 /* Parts enumerated in OPC spec, MS-XLSB and MS-XLSX */
27146 /* 12.3 Part Summary <SpreadsheetML> */
27147 /* 14.2 Part Summary <DrawingML> */
27148 /* [MS-XLSX] 2.1 Part Enumerations */
27149 /* [MS-XLSB] 2.1.7 Part Enumeration */
27150 var ct2type = {
27151 /* Workbook */
27152 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": "workbooks",
27153
27154 /* Worksheet */
27155 "application/vnd.ms-excel.binIndexWs": "TODO", /* Binary Index */
27156
27157 /* Chartsheet */
27158 "application/vnd.ms-excel.chartsheet": "TODO",
27159 "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": "TODO",
27160
27161 /* Dialogsheet */
27162 "application/vnd.ms-excel.dialogsheet": "TODO",
27163 "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": "TODO",
27164
27165 /* Macrosheet */
27166 "application/vnd.ms-excel.macrosheet": "TODO",
27167 "application/vnd.ms-excel.macrosheet+xml": "TODO",
27168 "application/vnd.ms-excel.intlmacrosheet": "TODO",
27169 "application/vnd.ms-excel.binIndexMs": "TODO", /* Binary Index */
27170
27171 /* File Properties */
27172 "application/vnd.openxmlformats-package.core-properties+xml": "coreprops",
27173 "application/vnd.openxmlformats-officedocument.custom-properties+xml": "custprops",
27174 "application/vnd.openxmlformats-officedocument.extended-properties+xml": "extprops",
27175
27176 /* Custom Data Properties */
27177 "application/vnd.openxmlformats-officedocument.customXmlProperties+xml": "TODO",
27178
27179 /* Comments */
27180 "application/vnd.ms-excel.comments": "comments",
27181 "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": "comments",
27182
27183 /* PivotTable */
27184 "application/vnd.ms-excel.pivotTable": "TODO",
27185 "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml": "TODO",
27186
27187 /* Calculation Chain */
27188 "application/vnd.ms-excel.calcChain": "calcchains",
27189 "application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml": "calcchains",
27190
27191 /* Printer Settings */
27192 "application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings": "TODO",
27193
27194 /* ActiveX */
27195 "application/vnd.ms-office.activeX": "TODO",
27196 "application/vnd.ms-office.activeX+xml": "TODO",
27197
27198 /* Custom Toolbars */
27199 "application/vnd.ms-excel.attachedToolbars": "TODO",
27200
27201 /* External Data Connections */
27202 "application/vnd.ms-excel.connections": "TODO",
27203 "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": "TODO",
27204
27205 /* External Links */
27206 "application/vnd.ms-excel.externalLink": "TODO",
27207 "application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml": "TODO",
27208
27209 /* Metadata */
27210 "application/vnd.ms-excel.sheetMetadata": "TODO",
27211 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml": "TODO",
27212
27213 /* PivotCache */
27214 "application/vnd.ms-excel.pivotCacheDefinition": "TODO",
27215 "application/vnd.ms-excel.pivotCacheRecords": "TODO",
27216 "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml": "TODO",
27217 "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml": "TODO",
27218
27219 /* Query Table */
27220 "application/vnd.ms-excel.queryTable": "TODO",
27221 "application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml": "TODO",
27222
27223 /* Shared Workbook */
27224 "application/vnd.ms-excel.userNames": "TODO",
27225 "application/vnd.ms-excel.revisionHeaders": "TODO",
27226 "application/vnd.ms-excel.revisionLog": "TODO",
27227 "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionHeaders+xml": "TODO",
27228 "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionLog+xml": "TODO",
27229 "application/vnd.openxmlformats-officedocument.spreadsheetml.userNames+xml": "TODO",
27230
27231 /* Single Cell Table */
27232 "application/vnd.ms-excel.tableSingleCells": "TODO",
27233 "application/vnd.openxmlformats-officedocument.spreadsheetml.tableSingleCells+xml": "TODO",
27234
27235 /* Slicer */
27236 "application/vnd.ms-excel.slicer": "TODO",
27237 "application/vnd.ms-excel.slicerCache": "TODO",
27238 "application/vnd.ms-excel.slicer+xml": "TODO",
27239 "application/vnd.ms-excel.slicerCache+xml": "TODO",
27240
27241 /* Sort Map */
27242 "application/vnd.ms-excel.wsSortMap": "TODO",
27243
27244 /* Table */
27245 "application/vnd.ms-excel.table": "TODO",
27246 "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": "TODO",
27247
27248 /* Themes */
27249 "application/vnd.openxmlformats-officedocument.theme+xml": "themes",
27250
27251 /* Timeline */
27252 "application/vnd.ms-excel.Timeline+xml": "TODO", /* verify */
27253 "application/vnd.ms-excel.TimelineCache+xml": "TODO", /* verify */
27254
27255 /* VBA */
27256 "application/vnd.ms-office.vbaProject": "vba",
27257 "application/vnd.ms-office.vbaProjectSignature": "vba",
27258
27259 /* Volatile Dependencies */
27260 "application/vnd.ms-office.volatileDependencies": "TODO",
27261 "application/vnd.openxmlformats-officedocument.spreadsheetml.volatileDependencies+xml": "TODO",
27262
27263 /* Control Properties */
27264 "application/vnd.ms-excel.controlproperties+xml": "TODO",
27265
27266 /* Data Model */
27267 "application/vnd.openxmlformats-officedocument.model+data": "TODO",
27268
27269 /* Survey */
27270 "application/vnd.ms-excel.Survey+xml": "TODO",
27271
27272 /* Drawing */
27273 "application/vnd.openxmlformats-officedocument.drawing+xml": "TODO",
27274 "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": "TODO",
27275 "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": "TODO",
27276 "application/vnd.openxmlformats-officedocument.drawingml.diagramColors+xml": "TODO",
27277 "application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml": "TODO",
27278 "application/vnd.openxmlformats-officedocument.drawingml.diagramLayout+xml": "TODO",
27279 "application/vnd.openxmlformats-officedocument.drawingml.diagramStyle+xml": "TODO",
27280
27281 /* VML */
27282 "application/vnd.openxmlformats-officedocument.vmlDrawing": "TODO",
27283
27284 "application/vnd.openxmlformats-package.relationships+xml": "rels",
27285 "application/vnd.openxmlformats-officedocument.oleObject": "TODO",
27286
27287 "sheet": "js"
27288 };
27289
27290 var CT_LIST = (function(){
27291 var o = {
27292 workbooks: {
27293 xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
27294 xlsm: "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
27295 xlsb: "application/vnd.ms-excel.sheet.binary.macroEnabled.main",
27296 xltx: "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml"
27297 },
27298 strs: { /* Shared Strings */
27299 xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml",
27300 xlsb: "application/vnd.ms-excel.sharedStrings"
27301 },
27302 sheets: {
27303 xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
27304 xlsb: "application/vnd.ms-excel.worksheet"
27305 },
27306 styles: {/* Styles */
27307 xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml",
27308 xlsb: "application/vnd.ms-excel.styles"
27309 }
27310 };
27311 keys(o).forEach(function(k) { if(!o[k].xlsm) o[k].xlsm = o[k].xlsx; });
27312 keys(o).forEach(function(k){ keys(o[k]).forEach(function(v) { ct2type[o[k][v]] = k; }); });
27313 return o;
27314 })();
27315
27316 var type2ct = evert_arr(ct2type);
27317
27318 XMLNS.CT = 'http://schemas.openxmlformats.org/package/2006/content-types';
27319
27320 function parse_ct(data, opts) {
27321 var ctext = {};
27322 if(!data || !data.match) return data;
27323 var ct = { workbooks: [], sheets: [], calcchains: [], themes: [], styles: [],
27324 coreprops: [], extprops: [], custprops: [], strs:[], comments: [], vba: [],
27325 TODO:[], rels:[], xmlns: "" };
27326 (data.match(tagregex)||[]).forEach(function(x) {
27327 var y = parsexmltag(x);
27328 switch(y[0].replace(nsregex,"<")) {
27329 case '<?xml': break;
27330 case '<Types': ct.xmlns = y['xmlns' + (y[0].match(/<(\w+):/)||["",""])[1] ]; break;
27331 case '<Default': ctext[y.Extension] = y.ContentType; break;
27332 case '<Override':
27333 if(ct[ct2type[y.ContentType]] !== undefined) ct[ct2type[y.ContentType]].push(y.PartName);
27334 else if(opts.WTF) console.error(y);
27335 break;
27336 }
27337 });
27338 if(ct.xmlns !== XMLNS.CT) throw new Error("Unknown Namespace: " + ct.xmlns);
27339 ct.calcchain = ct.calcchains.length > 0 ? ct.calcchains[0] : "";
27340 ct.sst = ct.strs.length > 0 ? ct.strs[0] : "";
27341 ct.style = ct.styles.length > 0 ? ct.styles[0] : "";
27342 ct.defaults = ctext;
27343 delete ct.calcchains;
27344 return ct;
27345 }
27346
27347 var CTYPE_XML_ROOT = writextag('Types', null, {
27348 'xmlns': XMLNS.CT,
27349 'xmlns:xsd': XMLNS.xsd,
27350 'xmlns:xsi': XMLNS.xsi
27351 });
27352
27353 var CTYPE_DEFAULTS = [
27354 ['xml', 'application/xml'],
27355 ['bin', 'application/vnd.ms-excel.sheet.binary.macroEnabled.main'],
27356 ['rels', type2ct.rels[0]]
27357 ].map(function(x) {
27358 return writextag('Default', null, {'Extension':x[0], 'ContentType': x[1]});
27359 });
27360
27361 function write_ct(ct, opts) {
27362 var o = [], v;
27363 o[o.length] = (XML_HEADER);
27364 o[o.length] = (CTYPE_XML_ROOT);
27365 o = o.concat(CTYPE_DEFAULTS);
27366 var f1 = function(w) {
27367 if(ct[w] && ct[w].length > 0) {
27368 v = ct[w][0];
27369 o[o.length] = (writextag('Override', null, {
27370 'PartName': (v[0] == '/' ? "":"/") + v,
27371 'ContentType': CT_LIST[w][opts.bookType || 'xlsx']
27372 }));
27373 }
27374 };
27375 var f2 = function(w) {
27376 ct[w].forEach(function(v) {
27377 o[o.length] = (writextag('Override', null, {
27378 'PartName': (v[0] == '/' ? "":"/") + v,
27379 'ContentType': CT_LIST[w][opts.bookType || 'xlsx']
27380 }));
27381 });
27382 };
27383 var f3 = function(t) {
27384 (ct[t]||[]).forEach(function(v) {
27385 o[o.length] = (writextag('Override', null, {
27386 'PartName': (v[0] == '/' ? "":"/") + v,
27387 'ContentType': type2ct[t][0]
27388 }));
27389 });
27390 };
27391 f1('workbooks');
27392 f2('sheets');
27393 f3('themes');
27394 ['strs', 'styles'].forEach(f1);
27395 ['coreprops', 'extprops', 'custprops'].forEach(f3);
27396 if(o.length>2){ o[o.length] = ('</Types>'); o[1]=o[1].replace("/>",">"); }
27397 return o.join("");
27398 }
27399 /* 9.3.2 OPC Relationships Markup */
27400 var RELS = {
27401 WB: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
27402 SHEET: "http://sheetjs.openxmlformats.org/officeDocument/2006/relationships/officeDocument"
27403 };
27404
27405 function parse_rels(data, currentFilePath) {
27406 if (!data) return data;
27407 if (currentFilePath.charAt(0) !== '/') {
27408 currentFilePath = '/'+currentFilePath;
27409 }
27410 var rels = {};
27411 var hash = {};
27412 var resolveRelativePathIntoAbsolute = function (to) {
27413 var toksFrom = currentFilePath.split('/');
27414 toksFrom.pop(); // folder path
27415 var toksTo = to.split('/');
27416 var reversed = [];
27417 while (toksTo.length !== 0) {
27418 var tokTo = toksTo.shift();
27419 if (tokTo === '..') {
27420 toksFrom.pop();
27421 } else if (tokTo !== '.') {
27422 toksFrom.push(tokTo);
27423 }
27424 }
27425 return toksFrom.join('/');
27426 };
27427
27428 data.match(tagregex).forEach(function(x) {
27429 var y = parsexmltag(x);
27430 /* 9.3.2.2 OPC_Relationships */
27431 if (y[0] === '<Relationship') {
27432 var rel = {}; rel.Type = y.Type; rel.Target = y.Target; rel.Id = y.Id; rel.TargetMode = y.TargetMode;
27433 var canonictarget = y.TargetMode === 'External' ? y.Target : resolveRelativePathIntoAbsolute(y.Target);
27434 rels[canonictarget] = rel;
27435 hash[y.Id] = rel;
27436 }
27437 });
27438 rels["!id"] = hash;
27439 return rels;
27440 }
27441
27442 XMLNS.RELS = 'http://schemas.openxmlformats.org/package/2006/relationships';
27443
27444 var RELS_ROOT = writextag('Relationships', null, {
27445 //'xmlns:ns0': XMLNS.RELS,
27446 'xmlns': XMLNS.RELS
27447 });
27448
27449 /* TODO */
27450 function write_rels(rels) {
27451 var o = [];
27452 o[o.length] = (XML_HEADER);
27453 o[o.length] = (RELS_ROOT);
27454 keys(rels['!id']).forEach(function(rid) { var rel = rels['!id'][rid];
27455 o[o.length] = (writextag('Relationship', null, rel));
27456 });
27457 if(o.length>2){ o[o.length] = ('</Relationships>'); o[1]=o[1].replace("/>",">"); }
27458 return o.join("");
27459 }
27460 /* ECMA-376 Part II 11.1 Core Properties Part */
27461 /* [MS-OSHARED] 2.3.3.2.[1-2].1 (PIDSI/PIDDSI) */
27462 var CORE_PROPS = [
27463 ["cp:category", "Category"],
27464 ["cp:contentStatus", "ContentStatus"],
27465 ["cp:keywords", "Keywords"],
27466 ["cp:lastModifiedBy", "LastAuthor"],
27467 ["cp:lastPrinted", "LastPrinted"],
27468 ["cp:revision", "RevNumber"],
27469 ["cp:version", "Version"],
27470 ["dc:creator", "Author"],
27471 ["dc:description", "Comments"],
27472 ["dc:identifier", "Identifier"],
27473 ["dc:language", "Language"],
27474 ["dc:subject", "Subject"],
27475 ["dc:title", "Title"],
27476 ["dcterms:created", "CreatedDate", 'date'],
27477 ["dcterms:modified", "ModifiedDate", 'date']
27478 ];
27479
27480 XMLNS.CORE_PROPS = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
27481 RELS.CORE_PROPS = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties';
27482
27483 var CORE_PROPS_REGEX = (function() {
27484 var r = new Array(CORE_PROPS.length);
27485 for(var i = 0; i < CORE_PROPS.length; ++i) {
27486 var f = CORE_PROPS[i];
27487 var g = "(?:"+ f[0].substr(0,f[0].indexOf(":")) +":)"+ f[0].substr(f[0].indexOf(":")+1);
27488 r[i] = new RegExp("<" + g + "[^>]*>(.*)<\/" + g + ">");
27489 }
27490 return r;
27491 })();
27492
27493 function parse_core_props(data) {
27494 var p = {};
27495
27496 for(var i = 0; i < CORE_PROPS.length; ++i) {
27497 var f = CORE_PROPS[i], cur = data.match(CORE_PROPS_REGEX[i]);
27498 if(cur != null && cur.length > 0) p[f[1]] = cur[1];
27499 if(f[2] === 'date' && p[f[1]]) p[f[1]] = new Date(p[f[1]]);
27500 }
27501
27502 return p;
27503 }
27504
27505 var CORE_PROPS_XML_ROOT = writextag('cp:coreProperties', null, {
27506 //'xmlns': XMLNS.CORE_PROPS,
27507 'xmlns:cp': XMLNS.CORE_PROPS,
27508 'xmlns:dc': XMLNS.dc,
27509 'xmlns:dcterms': XMLNS.dcterms,
27510 'xmlns:dcmitype': XMLNS.dcmitype,
27511 'xmlns:xsi': XMLNS.xsi
27512 });
27513
27514 function cp_doit(f, g, h, o, p) {
27515 if(p[f] != null || g == null || g === "") return;
27516 p[f] = g;
27517 o[o.length] = (h ? writextag(f,g,h) : writetag(f,g));
27518 }
27519
27520 function write_core_props(cp, opts) {
27521 var o = [XML_HEADER, CORE_PROPS_XML_ROOT], p = {};
27522 if(!cp) return o.join("");
27523
27524
27525 if(cp.CreatedDate != null) cp_doit("dcterms:created", typeof cp.CreatedDate === "string" ? cp.CreatedDate : write_w3cdtf(cp.CreatedDate, opts.WTF), {"xsi:type":"dcterms:W3CDTF"}, o, p);
27526 if(cp.ModifiedDate != null) cp_doit("dcterms:modified", typeof cp.ModifiedDate === "string" ? cp.ModifiedDate : write_w3cdtf(cp.ModifiedDate, opts.WTF), {"xsi:type":"dcterms:W3CDTF"}, o, p);
27527
27528 for(var i = 0; i != CORE_PROPS.length; ++i) { var f = CORE_PROPS[i]; cp_doit(f[0], cp[f[1]], null, o, p); }
27529 if(o.length>2){ o[o.length] = ('</cp:coreProperties>'); o[1]=o[1].replace("/>",">"); }
27530 return o.join("");
27531 }
27532 /* 15.2.12.3 Extended File Properties Part */
27533 /* [MS-OSHARED] 2.3.3.2.[1-2].1 (PIDSI/PIDDSI) */
27534 var EXT_PROPS = [
27535 ["Application", "Application", "string"],
27536 ["AppVersion", "AppVersion", "string"],
27537 ["Company", "Company", "string"],
27538 ["DocSecurity", "DocSecurity", "string"],
27539 ["Manager", "Manager", "string"],
27540 ["HyperlinksChanged", "HyperlinksChanged", "bool"],
27541 ["SharedDoc", "SharedDoc", "bool"],
27542 ["LinksUpToDate", "LinksUpToDate", "bool"],
27543 ["ScaleCrop", "ScaleCrop", "bool"],
27544 ["HeadingPairs", "HeadingPairs", "raw"],
27545 ["TitlesOfParts", "TitlesOfParts", "raw"]
27546 ];
27547
27548 XMLNS.EXT_PROPS = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties";
27549 RELS.EXT_PROPS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties';
27550
27551 function parse_ext_props(data, p) {
27552 var q = {}; if(!p) p = {};
27553
27554 EXT_PROPS.forEach(function(f) {
27555 switch(f[2]) {
27556 case "string": p[f[1]] = (data.match(matchtag(f[0]))||[])[1]; break;
27557 case "bool": p[f[1]] = (data.match(matchtag(f[0]))||[])[1] === "true"; break;
27558 case "raw":
27559 var cur = data.match(new RegExp("<" + f[0] + "[^>]*>(.*)<\/" + f[0] + ">"));
27560 if(cur && cur.length > 0) q[f[1]] = cur[1];
27561 break;
27562 }
27563 });
27564
27565 if(q.HeadingPairs && q.TitlesOfParts) {
27566 var v = parseVector(q.HeadingPairs);
27567 var j = 0, widx = 0;
27568 for(var i = 0; i !== v.length; ++i) {
27569 switch(v[i].v) {
27570 case "Worksheets": widx = j; p.Worksheets = +(v[++i].v); break;
27571 case "Named Ranges": ++i; break; // TODO: Handle Named Ranges
27572 }
27573 }
27574 var parts = parseVector(q.TitlesOfParts).map(function(x) { return utf8read(x.v); });
27575 p.SheetNames = parts.slice(widx, widx + p.Worksheets);
27576 }
27577 return p;
27578 }
27579
27580 var EXT_PROPS_XML_ROOT = writextag('Properties', null, {
27581 'xmlns': XMLNS.EXT_PROPS,
27582 'xmlns:vt': XMLNS.vt
27583 });
27584
27585 function write_ext_props(cp, opts) {
27586 var o = [], p = {}, W = writextag;
27587 if(!cp) cp = {};
27588 cp.Application = "SheetJS";
27589 o[o.length] = (XML_HEADER);
27590 o[o.length] = (EXT_PROPS_XML_ROOT);
27591
27592 EXT_PROPS.forEach(function(f) {
27593 if(cp[f[1]] === undefined) return;
27594 var v;
27595 switch(f[2]) {
27596 case 'string': v = cp[f[1]]; break;
27597 case 'bool': v = cp[f[1]] ? 'true' : 'false'; break;
27598 }
27599 if(v !== undefined) o[o.length] = (W(f[0], v));
27600 });
27601
27602 /* TODO: HeadingPairs, TitlesOfParts */
27603 o[o.length] = (W('HeadingPairs', W('vt:vector', W('vt:variant', '<vt:lpstr>Worksheets</vt:lpstr>')+W('vt:variant', W('vt:i4', String(cp.Worksheets))), {size:2, baseType:"variant"})));
27604 o[o.length] = (W('TitlesOfParts', W('vt:vector', cp.SheetNames.map(function(s) { return "<vt:lpstr>" + s + "</vt:lpstr>"; }).join(""), {size: cp.Worksheets, baseType:"lpstr"})));
27605 if(o.length>2){ o[o.length] = ('</Properties>'); o[1]=o[1].replace("/>",">"); }
27606 return o.join("");
27607 }
27608 /* 15.2.12.2 Custom File Properties Part */
27609 XMLNS.CUST_PROPS = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties";
27610 RELS.CUST_PROPS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties';
27611
27612 var custregex = /<[^>]+>[^<]*/g;
27613 function parse_cust_props(data, opts) {
27614 var p = {}, name;
27615 var m = data.match(custregex);
27616 if(m) for(var i = 0; i != m.length; ++i) {
27617 var x = m[i], y = parsexmltag(x);
27618 switch(y[0]) {
27619 case '<?xml': break;
27620 case '<Properties':
27621 if(y.xmlns !== XMLNS.CUST_PROPS) throw "unrecognized xmlns " + y.xmlns;
27622 if(y.xmlnsvt && y.xmlnsvt !== XMLNS.vt) throw "unrecognized vt " + y.xmlnsvt;
27623 break;
27624 case '<property': name = y.name; break;
27625 case '</property>': name = null; break;
27626 default: if (x.indexOf('<vt:') === 0) {
27627 var toks = x.split('>');
27628 var type = toks[0].substring(4), text = toks[1];
27629 /* 22.4.2.32 (CT_Variant). Omit the binary types from 22.4 (Variant Types) */
27630 switch(type) {
27631 case 'lpstr': case 'lpwstr': case 'bstr': case 'lpwstr':
27632 p[name] = unescapexml(text);
27633 break;
27634 case 'bool':
27635 p[name] = parsexmlbool(text, '<vt:bool>');
27636 break;
27637 case 'i1': case 'i2': case 'i4': case 'i8': case 'int': case 'uint':
27638 p[name] = parseInt(text, 10);
27639 break;
27640 case 'r4': case 'r8': case 'decimal':
27641 p[name] = parseFloat(text);
27642 break;
27643 case 'filetime': case 'date':
27644 p[name] = new Date(text);
27645 break;
27646 case 'cy': case 'error':
27647 p[name] = unescapexml(text);
27648 break;
27649 default:
27650 if(typeof console !== 'undefined') console.warn('Unexpected', x, type, toks);
27651 }
27652 } else if(x.substr(0,2) === "</") {
27653 } else if(opts.WTF) throw new Error(x);
27654 }
27655 }
27656 return p;
27657 }
27658
27659 var CUST_PROPS_XML_ROOT = writextag('Properties', null, {
27660 'xmlns': XMLNS.CUST_PROPS,
27661 'xmlns:vt': XMLNS.vt
27662 });
27663
27664 function write_cust_props(cp, opts) {
27665 var o = [XML_HEADER, CUST_PROPS_XML_ROOT];
27666 if(!cp) return o.join("");
27667 var pid = 1;
27668 keys(cp).forEach(function custprop(k) { ++pid;
27669 o[o.length] = (writextag('property', write_vt(cp[k]), {
27670 'fmtid': '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}',
27671 'pid': pid,
27672 'name': k
27673 }));
27674 });
27675 if(o.length>2){ o[o.length] = '</Properties>'; o[1]=o[1].replace("/>",">"); }
27676 return o.join("");
27677 }
27678 /* 18.4.1 charset to codepage mapping */
27679 var CS2CP = {
27680 0: 1252, /* ANSI */
27681 1: 65001, /* DEFAULT */
27682 2: 65001, /* SYMBOL */
27683 77: 10000, /* MAC */
27684 128: 932, /* SHIFTJIS */
27685 129: 949, /* HANGUL */
27686 130: 1361, /* JOHAB */
27687 134: 936, /* GB2312 */
27688 136: 950, /* CHINESEBIG5 */
27689 161: 1253, /* GREEK */
27690 162: 1254, /* TURKISH */
27691 163: 1258, /* VIETNAMESE */
27692 177: 1255, /* HEBREW */
27693 178: 1256, /* ARABIC */
27694 186: 1257, /* BALTIC */
27695 204: 1251, /* RUSSIAN */
27696 222: 874, /* THAI */
27697 238: 1250, /* EASTEUROPE */
27698 255: 1252, /* OEM */
27699 69: 6969 /* MISC */
27700 };
27701
27702 /* Parse a list of <r> tags */
27703 var parse_rs = (function parse_rs_factory() {
27704 var tregex = matchtag("t"), rpregex = matchtag("rPr"), rregex = /<r>/g, rend = /<\/r>/, nlregex = /\r\n/g;
27705 /* 18.4.7 rPr CT_RPrElt */
27706 var parse_rpr = function parse_rpr(rpr, intro, outro) {
27707 var font = {}, cp = 65001;
27708 var m = rpr.match(tagregex), i = 0;
27709 if(m) for(;i!=m.length; ++i) {
27710 var y = parsexmltag(m[i]);
27711 switch(y[0]) {
27712 /* 18.8.12 condense CT_BooleanProperty */
27713 /* ** not required . */
27714 case '<condense': break;
27715 /* 18.8.17 extend CT_BooleanProperty */
27716 /* ** not required . */
27717 case '<extend': break;
27718 /* 18.8.36 shadow CT_BooleanProperty */
27719 /* ** not required . */
27720 case '<shadow':
27721 /* falls through */
27722 case '<shadow/>': break;
27723
27724 /* 18.4.1 charset CT_IntProperty TODO */
27725 case '<charset':
27726 if(y.val == '1') break;
27727 cp = CS2CP[parseInt(y.val, 10)];
27728 break;
27729
27730 /* 18.4.2 outline CT_BooleanProperty TODO */
27731 case '<outline':
27732 /* falls through */
27733 case '<outline/>': break;
27734
27735 /* 18.4.5 rFont CT_FontName */
27736 case '<rFont': font.name = y.val; break;
27737
27738 /* 18.4.11 sz CT_FontSize */
27739 case '<sz': font.sz = y.val; break;
27740
27741 /* 18.4.10 strike CT_BooleanProperty */
27742 case '<strike':
27743 if(!y.val) break;
27744 /* falls through */
27745 case '<strike/>': font.strike = 1; break;
27746 case '</strike>': break;
27747
27748 /* 18.4.13 u CT_UnderlineProperty */
27749 case '<u':
27750 if(!y.val) break;
27751 /* falls through */
27752 case '<u/>': font.u = 1; break;
27753 case '</u>': break;
27754
27755 /* 18.8.2 b */
27756 case '<b':
27757 if(!y.val) break;
27758 /* falls through */
27759 case '<b/>': font.b = 1; break;
27760 case '</b>': break;
27761
27762 /* 18.8.26 i */
27763 case '<i':
27764 if(!y.val) break;
27765 /* falls through */
27766 case '<i/>': font.i = 1; break;
27767 case '</i>': break;
27768
27769 /* 18.3.1.15 color CT_Color TODO: tint, theme, auto, indexed */
27770 case '<color':
27771 if(y.rgb) font.color = y.rgb.substr(2,6);
27772 break;
27773
27774 /* 18.8.18 family ST_FontFamily */
27775 case '<family': font.family = y.val; break;
27776
27777 /* 18.4.14 vertAlign CT_VerticalAlignFontProperty TODO */
27778 case '<vertAlign': break;
27779
27780 /* 18.8.35 scheme CT_FontScheme TODO */
27781 case '<scheme': break;
27782
27783 default:
27784 if(y[0].charCodeAt(1) !== 47) throw 'Unrecognized rich format ' + y[0];
27785 }
27786 }
27787 /* TODO: These should be generated styles, not inline */
27788 var style = [];
27789 if(font.b) style.push("font-weight: bold;");
27790 if(font.i) style.push("font-style: italic;");
27791 intro.push('<span style="' + style.join("") + '">');
27792 outro.push("</span>");
27793 return cp;
27794 };
27795
27796 /* 18.4.4 r CT_RElt */
27797 function parse_r(r) {
27798 var terms = [[],"",[]];
27799 /* 18.4.12 t ST_Xstring */
27800 var t = r.match(tregex), cp = 65001;
27801 if(!isval(t)) return "";
27802 terms[1] = t[1];
27803
27804 var rpr = r.match(rpregex);
27805 if(isval(rpr)) cp = parse_rpr(rpr[1], terms[0], terms[2]);
27806
27807 return terms[0].join("") + terms[1].replace(nlregex,'<br/>') + terms[2].join("");
27808 }
27809 return function parse_rs(rs) {
27810 return rs.replace(rregex,"").split(rend).map(parse_r).join("");
27811 };
27812 })();
27813
27814 /* 18.4.8 si CT_Rst */
27815 var sitregex = /<t[^>]*>([^<]*)<\/t>/g, sirregex = /<r>/;
27816 function parse_si(x, opts) {
27817 var html = opts ? opts.cellHTML : true;
27818 var z = {};
27819 if(!x) return null;
27820 var y;
27821 /* 18.4.12 t ST_Xstring (Plaintext String) */
27822 if(x.charCodeAt(1) === 116) {
27823 z.t = utf8read(unescapexml(x.substr(x.indexOf(">")+1).split(/<\/t>/)[0]));
27824 z.r = x;
27825 if(html) z.h = z.t;
27826 }
27827 /* 18.4.4 r CT_RElt (Rich Text Run) */
27828 else if((y = x.match(sirregex))) {
27829 z.r = x;
27830 z.t = utf8read(unescapexml(x.match(sitregex).join("").replace(tagregex,"")));
27831 if(html) z.h = parse_rs(x);
27832 }
27833 /* 18.4.3 phoneticPr CT_PhoneticPr (TODO: needed for Asian support) */
27834 /* 18.4.6 rPh CT_PhoneticRun (TODO: needed for Asian support) */
27835 return z;
27836 }
27837
27838 /* 18.4 Shared String Table */
27839 var sstr0 = /<sst([^>]*)>([\s\S]*)<\/sst>/;
27840 var sstr1 = /<(?:si|sstItem)>/g;
27841 var sstr2 = /<\/(?:si|sstItem)>/;
27842 function parse_sst_xml(data, opts) {
27843 var s = [], ss;
27844 /* 18.4.9 sst CT_Sst */
27845 var sst = data.match(sstr0);
27846 if(isval(sst)) {
27847 ss = sst[2].replace(sstr1,"").split(sstr2);
27848 for(var i = 0; i != ss.length; ++i) {
27849 var o = parse_si(ss[i], opts);
27850 if(o != null) s[s.length] = o;
27851 }
27852 sst = parsexmltag(sst[1]); s.Count = sst.count; s.Unique = sst.uniqueCount;
27853 }
27854 return s;
27855 }
27856
27857 RELS.SST = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings";
27858 var straywsregex = /^\s|\s$|[\t\n\r]/;
27859 function write_sst_xml(sst, opts) {
27860 if(!opts.bookSST) return "";
27861 var o = [XML_HEADER];
27862 o[o.length] = (writextag('sst', null, {
27863 xmlns: XMLNS.main[0],
27864 count: sst.Count,
27865 uniqueCount: sst.Unique
27866 }));
27867 for(var i = 0; i != sst.length; ++i) { if(sst[i] == null) continue;
27868 var s = sst[i];
27869 var sitag = "<si>";
27870 if(s.r) sitag += s.r;
27871 else {
27872 sitag += "<t";
27873 if(s.t.match(straywsregex)) sitag += ' xml:space="preserve"';
27874 sitag += ">" + escapexml(s.t) + "</t>";
27875 }
27876 sitag += "</si>";
27877 o[o.length] = (sitag);
27878 }
27879 if(o.length>2){ o[o.length] = ('</sst>'); o[1]=o[1].replace("/>",">"); }
27880 return o.join("");
27881 }
27882 /* [MS-XLSB] 2.4.219 BrtBeginSst */
27883 function parse_BrtBeginSst(data, length) {
27884 return [data.read_shift(4), data.read_shift(4)];
27885 }
27886
27887 /* [MS-XLSB] 2.1.7.45 Shared Strings */
27888 function parse_sst_bin(data, opts) {
27889 var s = [];
27890 var pass = false;
27891 recordhopper(data, function hopper_sst(val, R, RT) {
27892 switch(R.n) {
27893 case 'BrtBeginSst': s.Count = val[0]; s.Unique = val[1]; break;
27894 case 'BrtSSTItem': s.push(val); break;
27895 case 'BrtEndSst': return true;
27896 /* TODO: produce a test case with a future record */
27897 case 'BrtFRTBegin': pass = true; break;
27898 case 'BrtFRTEnd': pass = false; break;
27899 default: if(!pass || opts.WTF) throw new Error("Unexpected record " + RT + " " + R.n);
27900 }
27901 });
27902 return s;
27903 }
27904
27905 function write_BrtBeginSst(sst, o) {
27906 if(!o) o = new_buf(8);
27907 o.write_shift(4, sst.Count);
27908 o.write_shift(4, sst.Unique);
27909 return o;
27910 }
27911
27912 var write_BrtSSTItem = write_RichStr;
27913
27914 function write_sst_bin(sst, opts) {
27915 var ba = buf_array();
27916 write_record(ba, "BrtBeginSst", write_BrtBeginSst(sst));
27917 for(var i = 0; i < sst.length; ++i) write_record(ba, "BrtSSTItem", write_BrtSSTItem(sst[i]));
27918 write_record(ba, "BrtEndSst");
27919 return ba.end();
27920 }
27921 function hex2RGB(h) {
27922 var o = h.substr(h[0]==="#"?1:0,6);
27923 return [parseInt(o.substr(0,2),16),parseInt(o.substr(0,2),16),parseInt(o.substr(0,2),16)];
27924 }
27925 function rgb2Hex(rgb) {
27926 for(var i=0,o=1; i!=3; ++i) o = o*256 + (rgb[i]>255?255:rgb[i]<0?0:rgb[i]);
27927 return o.toString(16).toUpperCase().substr(1);
27928 }
27929
27930 function rgb2HSL(rgb) {
27931 var R = rgb[0]/255, G = rgb[1]/255, B=rgb[2]/255;
27932 var M = Math.max(R, G, B), m = Math.min(R, G, B), C = M - m;
27933 if(C === 0) return [0, 0, R];
27934
27935 var H6 = 0, S = 0, L2 = (M + m);
27936 S = C / (L2 > 1 ? 2 - L2 : L2);
27937 switch(M){
27938 case R: H6 = ((G - B) / C + 6)%6; break;
27939 case G: H6 = ((B - R) / C + 2); break;
27940 case B: H6 = ((R - G) / C + 4); break;
27941 }
27942 return [H6 / 6, S, L2 / 2];
27943 }
27944
27945 function hsl2RGB(hsl){
27946 var H = hsl[0], S = hsl[1], L = hsl[2];
27947 var C = S * 2 * (L < 0.5 ? L : 1 - L), m = L - C/2;
27948 var rgb = [m,m,m], h6 = 6*H;
27949
27950 var X;
27951 if(S !== 0) switch(h6|0) {
27952 case 0: case 6: X = C * h6; rgb[0] += C; rgb[1] += X; break;
27953 case 1: X = C * (2 - h6); rgb[0] += X; rgb[1] += C; break;
27954 case 2: X = C * (h6 - 2); rgb[1] += C; rgb[2] += X; break;
27955 case 3: X = C * (4 - h6); rgb[1] += X; rgb[2] += C; break;
27956 case 4: X = C * (h6 - 4); rgb[2] += C; rgb[0] += X; break;
27957 case 5: X = C * (6 - h6); rgb[2] += X; rgb[0] += C; break;
27958 }
27959 for(var i = 0; i != 3; ++i) rgb[i] = Math.round(rgb[i]*255);
27960 return rgb;
27961 }
27962
27963 /* 18.8.3 bgColor tint algorithm */
27964 function rgb_tint(hex, tint) {
27965 if(tint === 0) return hex;
27966 var hsl = rgb2HSL(hex2RGB(hex));
27967 if (tint < 0) hsl[2] = hsl[2] * (1 + tint);
27968 else hsl[2] = 1 - (1 - hsl[2]) * (1 - tint);
27969 return rgb2Hex(hsl2RGB(hsl));
27970 }
27971
27972 /* 18.3.1.13 width calculations */
27973 var DEF_MDW = 7, MAX_MDW = 15, MIN_MDW = 1, MDW = DEF_MDW;
27974 function width2px(width) { return (( width + ((128/MDW)|0)/256 )* MDW )|0; }
27975 function px2char(px) { return (((px - 5)/MDW * 100 + 0.5)|0)/100; }
27976 function char2width(chr) { return (((chr * MDW + 5)/MDW*256)|0)/256; }
27977 function cycle_width(collw) { return char2width(px2char(width2px(collw))); }
27978 function find_mdw(collw, coll) {
27979 if(cycle_width(collw) != collw) {
27980 for(MDW=DEF_MDW; MDW>MIN_MDW; --MDW) if(cycle_width(collw) === collw) break;
27981 if(MDW === MIN_MDW) for(MDW=DEF_MDW+1; MDW<MAX_MDW; ++MDW) if(cycle_width(collw) === collw) break;
27982 if(MDW === MAX_MDW) MDW = DEF_MDW;
27983 }
27984 }
27985 var styles = {}; // shared styles
27986
27987 var themes = {}; // shared themes
27988
27989 /* 18.8.21 fills CT_Fills */
27990 function parse_fills(t, opts) {
27991 styles.Fills = [];
27992 var fill = {};
27993 t[0].match(tagregex).forEach(function(x) {
27994 var y = parsexmltag(x);
27995 switch(y[0]) {
27996 case '<fills': case '<fills>': case '</fills>': break;
27997
27998 /* 18.8.20 fill CT_Fill */
27999 case '<fill>': break;
28000 case '</fill>': styles.Fills.push(fill); fill = {}; break;
28001
28002 /* 18.8.32 patternFill CT_PatternFill */
28003 case '<patternFill':
28004 if(y.patternType) fill.patternType = y.patternType;
28005 break;
28006 case '<patternFill/>': case '</patternFill>': break;
28007
28008 /* 18.8.3 bgColor CT_Color */
28009 case '<bgColor':
28010 if(!fill.bgColor) fill.bgColor = {};
28011 if(y.indexed) fill.bgColor.indexed = parseInt(y.indexed, 10);
28012 if(y.theme) fill.bgColor.theme = parseInt(y.theme, 10);
28013 if(y.tint) fill.bgColor.tint = parseFloat(y.tint);
28014 /* Excel uses ARGB strings */
28015 if(y.rgb) fill.bgColor.rgb = y.rgb.substring(y.rgb.length - 6);
28016 break;
28017 case '<bgColor/>': case '</bgColor>': break;
28018
28019 /* 18.8.19 fgColor CT_Color */
28020 case '<fgColor':
28021 if(!fill.fgColor) fill.fgColor = {};
28022 if(y.theme) fill.fgColor.theme = parseInt(y.theme, 10);
28023 if(y.tint) fill.fgColor.tint = parseFloat(y.tint);
28024 /* Excel uses ARGB strings */
28025 if(y.rgb) fill.fgColor.rgb = y.rgb.substring(y.rgb.length - 6);
28026 break;
28027 case '<bgColor/>': case '</fgColor>': break;
28028
28029 default: if(opts.WTF) throw 'unrecognized ' + y[0] + ' in fills';
28030 }
28031 });
28032 }
28033
28034 /* 18.8.31 numFmts CT_NumFmts */
28035 function parse_numFmts(t, opts) {
28036 styles.NumberFmt = [];
28037 var k = keys(SSF._table);
28038 for(var i=0; i < k.length; ++i) styles.NumberFmt[k[i]] = SSF._table[k[i]];
28039 var m = t[0].match(tagregex);
28040 for(i=0; i < m.length; ++i) {
28041 var y = parsexmltag(m[i]);
28042 switch(y[0]) {
28043 case '<numFmts': case '</numFmts>': case '<numFmts/>': case '<numFmts>': break;
28044 case '<numFmt': {
28045 var f=unescapexml(utf8read(y.formatCode)), j=parseInt(y.numFmtId,10);
28046 styles.NumberFmt[j] = f; if(j>0) SSF.load(f,j);
28047 } break;
28048 default: if(opts.WTF) throw 'unrecognized ' + y[0] + ' in numFmts';
28049 }
28050 }
28051 }
28052
28053 function write_numFmts(NF, opts) {
28054 var o = ["<numFmts>"];
28055 [[5,8],[23,26],[41,44],[63,66],[164,392]].forEach(function(r) {
28056 for(var i = r[0]; i <= r[1]; ++i) if(NF[i] !== undefined) o[o.length] = (writextag('numFmt',null,{numFmtId:i,formatCode:escapexml(NF[i])}));
28057 });
28058 if(o.length === 1) return "";
28059 o[o.length] = ("</numFmts>");
28060 o[0] = writextag('numFmts', null, { count:o.length-2 }).replace("/>", ">");
28061 return o.join("");
28062 }
28063
28064 /* 18.8.10 cellXfs CT_CellXfs */
28065 function parse_cellXfs(t, opts) {
28066 styles.CellXf = [];
28067 t[0].match(tagregex).forEach(function(x) {
28068 var y = parsexmltag(x);
28069 switch(y[0]) {
28070 case '<cellXfs': case '<cellXfs>': case '<cellXfs/>': case '</cellXfs>': break;
28071
28072 /* 18.8.45 xf CT_Xf */
28073 case '<xf': delete y[0];
28074 if(y.numFmtId) y.numFmtId = parseInt(y.numFmtId, 10);
28075 if(y.fillId) y.fillId = parseInt(y.fillId, 10);
28076 styles.CellXf.push(y); break;
28077 case '</xf>': break;
28078
28079 /* 18.8.1 alignment CT_CellAlignment */
28080 case '<alignment': case '<alignment/>': break;
28081
28082 /* 18.8.33 protection CT_CellProtection */
28083 case '<protection': case '</protection>': case '<protection/>': break;
28084
28085 case '<extLst': case '</extLst>': break;
28086 case '<ext': break;
28087 default: if(opts.WTF) throw 'unrecognized ' + y[0] + ' in cellXfs';
28088 }
28089 });
28090 }
28091
28092 function write_cellXfs(cellXfs) {
28093 var o = [];
28094 o[o.length] = (writextag('cellXfs',null));
28095 cellXfs.forEach(function(c) { o[o.length] = (writextag('xf', null, c)); });
28096 o[o.length] = ("</cellXfs>");
28097 if(o.length === 2) return "";
28098 o[0] = writextag('cellXfs',null, {count:o.length-2}).replace("/>",">");
28099 return o.join("");
28100 }
28101
28102 /* 18.8 Styles CT_Stylesheet*/
28103 var parse_sty_xml= (function make_pstyx() {
28104 var numFmtRegex = /<numFmts([^>]*)>.*<\/numFmts>/;
28105 var cellXfRegex = /<cellXfs([^>]*)>.*<\/cellXfs>/;
28106 var fillsRegex = /<fills([^>]*)>.*<\/fills>/;
28107
28108 return function parse_sty_xml(data, opts) {
28109 /* 18.8.39 styleSheet CT_Stylesheet */
28110 var t;
28111
28112 /* numFmts CT_NumFmts ? */
28113 if((t=data.match(numFmtRegex))) parse_numFmts(t, opts);
28114
28115 /* fonts CT_Fonts ? */
28116 // if((t=data.match(/<fonts([^>]*)>.*<\/fonts>/))) parse_fonts(t, opts);
28117
28118 /* fills CT_Fills */
28119 if((t=data.match(fillsRegex))) parse_fills(t, opts);
28120
28121 /* borders CT_Borders ? */
28122 /* cellStyleXfs CT_CellStyleXfs ? */
28123
28124 /* cellXfs CT_CellXfs ? */
28125 if((t=data.match(cellXfRegex))) parse_cellXfs(t, opts);
28126
28127 /* dxfs CT_Dxfs ? */
28128 /* tableStyles CT_TableStyles ? */
28129 /* colors CT_Colors ? */
28130 /* extLst CT_ExtensionList ? */
28131
28132 return styles;
28133 };
28134 })();
28135
28136 var STYLES_XML_ROOT = writextag('styleSheet', null, {
28137 'xmlns': XMLNS.main[0],
28138 'xmlns:vt': XMLNS.vt
28139 });
28140
28141 RELS.STY = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles";
28142
28143 function write_sty_xml(wb, opts) {
28144 var o = [XML_HEADER, STYLES_XML_ROOT], w;
28145 if((w = write_numFmts(wb.SSF)) != null) o[o.length] = w;
28146 o[o.length] = ('<fonts count="1"><font><sz val="12"/><color theme="1"/><name val="Calibri"/><family val="2"/><scheme val="minor"/></font></fonts>');
28147 o[o.length] = ('<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>');
28148 o[o.length] = ('<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>');
28149 o[o.length] = ('<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>');
28150 if((w = write_cellXfs(opts.cellXfs))) o[o.length] = (w);
28151 o[o.length] = ('<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>');
28152 o[o.length] = ('<dxfs count="0"/>');
28153 o[o.length] = ('<tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleMedium4"/>');
28154
28155 if(o.length>2){ o[o.length] = ('</styleSheet>'); o[1]=o[1].replace("/>",">"); }
28156 return o.join("");
28157 }
28158 /* [MS-XLSB] 2.4.651 BrtFmt */
28159 function parse_BrtFmt(data, length) {
28160 var ifmt = data.read_shift(2);
28161 var stFmtCode = parse_XLWideString(data,length-2);
28162 return [ifmt, stFmtCode];
28163 }
28164
28165 /* [MS-XLSB] 2.4.653 BrtFont TODO */
28166 function parse_BrtFont(data, length) {
28167 var out = {flags:{}};
28168 out.dyHeight = data.read_shift(2);
28169 out.grbit = parse_FontFlags(data, 2);
28170 out.bls = data.read_shift(2);
28171 out.sss = data.read_shift(2);
28172 out.uls = data.read_shift(1);
28173 out.bFamily = data.read_shift(1);
28174 out.bCharSet = data.read_shift(1);
28175 data.l++;
28176 out.brtColor = parse_BrtColor(data, 8);
28177 out.bFontScheme = data.read_shift(1);
28178 out.name = parse_XLWideString(data, length - 21);
28179
28180 out.flags.Bold = out.bls === 0x02BC;
28181 out.flags.Italic = out.grbit.fItalic;
28182 out.flags.Strikeout = out.grbit.fStrikeout;
28183 out.flags.Outline = out.grbit.fOutline;
28184 out.flags.Shadow = out.grbit.fShadow;
28185 out.flags.Condense = out.grbit.fCondense;
28186 out.flags.Extend = out.grbit.fExtend;
28187 out.flags.Sub = out.sss & 0x2;
28188 out.flags.Sup = out.sss & 0x1;
28189 return out;
28190 }
28191
28192 /* [MS-XLSB] 2.4.816 BrtXF */
28193 function parse_BrtXF(data, length) {
28194 var ixfeParent = data.read_shift(2);
28195 var ifmt = data.read_shift(2);
28196 parsenoop(data, length-4);
28197 return {ixfe:ixfeParent, ifmt:ifmt };
28198 }
28199
28200 /* [MS-XLSB] 2.1.7.50 Styles */
28201 function parse_sty_bin(data, opts) {
28202 styles.NumberFmt = [];
28203 for(var y in SSF._table) styles.NumberFmt[y] = SSF._table[y];
28204
28205 styles.CellXf = [];
28206 var state = ""; /* TODO: this should be a stack */
28207 var pass = false;
28208 recordhopper(data, function hopper_sty(val, R, RT) {
28209 switch(R.n) {
28210 case 'BrtFmt':
28211 styles.NumberFmt[val[0]] = val[1]; SSF.load(val[1], val[0]);
28212 break;
28213 case 'BrtFont': break; /* TODO */
28214 case 'BrtKnownFonts': break; /* TODO */
28215 case 'BrtFill': break; /* TODO */
28216 case 'BrtBorder': break; /* TODO */
28217 case 'BrtXF':
28218 if(state === "CELLXFS") {
28219 styles.CellXf.push(val);
28220 }
28221 break; /* TODO */
28222 case 'BrtStyle': break; /* TODO */
28223 case 'BrtDXF': break; /* TODO */
28224 case 'BrtMRUColor': break; /* TODO */
28225 case 'BrtIndexedColor': break; /* TODO */
28226 case 'BrtBeginStyleSheet': break;
28227 case 'BrtEndStyleSheet': break;
28228 case 'BrtBeginTableStyle': break;
28229 case 'BrtTableStyleElement': break;
28230 case 'BrtEndTableStyle': break;
28231 case 'BrtBeginFmts': state = "FMTS"; break;
28232 case 'BrtEndFmts': state = ""; break;
28233 case 'BrtBeginFonts': state = "FONTS"; break;
28234 case 'BrtEndFonts': state = ""; break;
28235 case 'BrtACBegin': state = "ACFONTS"; break;
28236 case 'BrtACEnd': state = ""; break;
28237 case 'BrtBeginFills': state = "FILLS"; break;
28238 case 'BrtEndFills': state = ""; break;
28239 case 'BrtBeginBorders': state = "BORDERS"; break;
28240 case 'BrtEndBorders': state = ""; break;
28241 case 'BrtBeginCellStyleXFs': state = "CELLSTYLEXFS"; break;
28242 case 'BrtEndCellStyleXFs': state = ""; break;
28243 case 'BrtBeginCellXFs': state = "CELLXFS"; break;
28244 case 'BrtEndCellXFs': state = ""; break;
28245 case 'BrtBeginStyles': state = "STYLES"; break;
28246 case 'BrtEndStyles': state = ""; break;
28247 case 'BrtBeginDXFs': state = "DXFS"; break;
28248 case 'BrtEndDXFs': state = ""; break;
28249 case 'BrtBeginTableStyles': state = "TABLESTYLES"; break;
28250 case 'BrtEndTableStyles': state = ""; break;
28251 case 'BrtBeginColorPalette': state = "COLORPALETTE"; break;
28252 case 'BrtEndColorPalette': state = ""; break;
28253 case 'BrtBeginIndexedColors': state = "INDEXEDCOLORS"; break;
28254 case 'BrtEndIndexedColors': state = ""; break;
28255 case 'BrtBeginMRUColors': state = "MRUCOLORS"; break;
28256 case 'BrtEndMRUColors': state = ""; break;
28257 case 'BrtFRTBegin': pass = true; break;
28258 case 'BrtFRTEnd': pass = false; break;
28259 case 'BrtBeginStyleSheetExt14': break;
28260 case 'BrtBeginSlicerStyles': break;
28261 case 'BrtEndSlicerStyles': break;
28262 case 'BrtBeginTimelineStylesheetExt15': break;
28263 case 'BrtEndTimelineStylesheetExt15': break;
28264 case 'BrtBeginTimelineStyles': break;
28265 case 'BrtEndTimelineStyles': break;
28266 case 'BrtEndStyleSheetExt14': break;
28267 default: if(!pass || opts.WTF) throw new Error("Unexpected record " + RT + " " + R.n);
28268 }
28269 });
28270 return styles;
28271 }
28272
28273 /* [MS-XLSB] 2.1.7.50 Styles */
28274 function write_sty_bin(data, opts) {
28275 var ba = buf_array();
28276 write_record(ba, "BrtBeginStyleSheet");
28277 /* [FMTS] */
28278 /* [FONTS] */
28279 /* [FILLS] */
28280 /* [BORDERS] */
28281 /* CELLSTYLEXFS */
28282 /* CELLXFS*/
28283 /* STYLES */
28284 /* DXFS */
28285 /* TABLESTYLES */
28286 /* [COLORPALETTE] */
28287 /* FRTSTYLESHEET*/
28288 write_record(ba, "BrtEndStyleSheet");
28289 return ba.end();
28290 }
28291 RELS.THEME = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme";
28292
28293 /* 20.1.6.2 clrScheme CT_ColorScheme */
28294 function parse_clrScheme(t, opts) {
28295 themes.themeElements.clrScheme = [];
28296 var color = {};
28297 t[0].match(tagregex).forEach(function(x) {
28298 var y = parsexmltag(x);
28299 switch(y[0]) {
28300 case '<a:clrScheme': case '</a:clrScheme>': break;
28301
28302 /* 20.1.2.3.32 srgbClr CT_SRgbColor */
28303 case '<a:srgbClr': color.rgb = y.val; break;
28304
28305 /* 20.1.2.3.33 sysClr CT_SystemColor */
28306 case '<a:sysClr': color.rgb = y.lastClr; break;
28307
28308 /* 20.1.4.1.9 dk1 (Dark 1) */
28309 case '<a:dk1>':
28310 case '</a:dk1>':
28311 /* 20.1.4.1.10 dk2 (Dark 2) */
28312 case '<a:dk2>':
28313 case '</a:dk2>':
28314 /* 20.1.4.1.22 lt1 (Light 1) */
28315 case '<a:lt1>':
28316 case '</a:lt1>':
28317 /* 20.1.4.1.23 lt2 (Light 2) */
28318 case '<a:lt2>':
28319 case '</a:lt2>':
28320 /* 20.1.4.1.1 accent1 (Accent 1) */
28321 case '<a:accent1>':
28322 case '</a:accent1>':
28323 /* 20.1.4.1.2 accent2 (Accent 2) */
28324 case '<a:accent2>':
28325 case '</a:accent2>':
28326 /* 20.1.4.1.3 accent3 (Accent 3) */
28327 case '<a:accent3>':
28328 case '</a:accent3>':
28329 /* 20.1.4.1.4 accent4 (Accent 4) */
28330 case '<a:accent4>':
28331 case '</a:accent4>':
28332 /* 20.1.4.1.5 accent5 (Accent 5) */
28333 case '<a:accent5>':
28334 case '</a:accent5>':
28335 /* 20.1.4.1.6 accent6 (Accent 6) */
28336 case '<a:accent6>':
28337 case '</a:accent6>':
28338 /* 20.1.4.1.19 hlink (Hyperlink) */
28339 case '<a:hlink>':
28340 case '</a:hlink>':
28341 /* 20.1.4.1.15 folHlink (Followed Hyperlink) */
28342 case '<a:folHlink>':
28343 case '</a:folHlink>':
28344 if (y[0][1] === '/') {
28345 themes.themeElements.clrScheme.push(color);
28346 color = {};
28347 } else {
28348 color.name = y[0].substring(3, y[0].length - 1);
28349 }
28350 break;
28351
28352 default: if(opts.WTF) throw 'unrecognized ' + y[0] + ' in clrScheme';
28353 }
28354 });
28355 }
28356
28357 var clrsregex = /<a:clrScheme([^>]*)>.*<\/a:clrScheme>/;
28358 /* 14.2.7 Theme Part */
28359 function parse_theme_xml(data, opts) {
28360 if(!data || data.length === 0) return themes;
28361 themes.themeElements = {};
28362
28363 var t;
28364
28365 /* clrScheme CT_ColorScheme */
28366 if((t=data.match(clrsregex))) parse_clrScheme(t, opts);
28367
28368 return themes;
28369 }
28370
28371 function write_theme() { return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme"><a:themeElements><a:clrScheme name="Office"><a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1><a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1><a:dk2><a:srgbClr val="1F497D"/></a:dk2><a:lt2><a:srgbClr val="EEECE1"/></a:lt2><a:accent1><a:srgbClr val="4F81BD"/></a:accent1><a:accent2><a:srgbClr val="C0504D"/></a:accent2><a:accent3><a:srgbClr val="9BBB59"/></a:accent3><a:accent4><a:srgbClr val="8064A2"/></a:accent4><a:accent5><a:srgbClr val="4BACC6"/></a:accent5><a:accent6><a:srgbClr val="F79646"/></a:accent6><a:hlink><a:srgbClr val="0000FF"/></a:hlink><a:folHlink><a:srgbClr val="800080"/></a:folHlink></a:clrScheme><a:fontScheme name="Office"><a:majorFont><a:latin typeface="Cambria"/><a:ea typeface=""/><a:cs typeface=""/><a:font script="Jpan" typeface="MS Pゴシック"/><a:font script="Hang" typeface="맑은 고딕"/><a:font script="Hans" typeface="宋体"/><a:font script="Hant" typeface="新細明體"/><a:font script="Arab" typeface="Times New Roman"/><a:font script="Hebr" typeface="Times New Roman"/><a:font script="Thai" typeface="Tahoma"/><a:font script="Ethi" typeface="Nyala"/><a:font script="Beng" typeface="Vrinda"/><a:font script="Gujr" typeface="Shruti"/><a:font script="Khmr" typeface="MoolBoran"/><a:font script="Knda" typeface="Tunga"/><a:font script="Guru" typeface="Raavi"/><a:font script="Cans" typeface="Euphemia"/><a:font script="Cher" typeface="Plantagenet Cherokee"/><a:font script="Yiii" typeface="Microsoft Yi Baiti"/><a:font script="Tibt" typeface="Microsoft Himalaya"/><a:font script="Thaa" typeface="MV Boli"/><a:font script="Deva" typeface="Mangal"/><a:font script="Telu" typeface="Gautami"/><a:font script="Taml" typeface="Latha"/><a:font script="Syrc" typeface="Estrangelo Edessa"/><a:font script="Orya" typeface="Kalinga"/><a:font script="Mlym" typeface="Kartika"/><a:font script="Laoo" typeface="DokChampa"/><a:font script="Sinh" typeface="Iskoola Pota"/><a:font script="Mong" typeface="Mongolian Baiti"/><a:font script="Viet" typeface="Times New Roman"/><a:font script="Uigh" typeface="Microsoft Uighur"/><a:font script="Geor" typeface="Sylfaen"/></a:majorFont><a:minorFont><a:latin typeface="Calibri"/><a:ea typeface=""/><a:cs typeface=""/><a:font script="Jpan" typeface="MS Pゴシック"/><a:font script="Hang" typeface="맑은 고딕"/><a:font script="Hans" typeface="宋体"/><a:font script="Hant" typeface="新細明體"/><a:font script="Arab" typeface="Arial"/><a:font script="Hebr" typeface="Arial"/><a:font script="Thai" typeface="Tahoma"/><a:font script="Ethi" typeface="Nyala"/><a:font script="Beng" typeface="Vrinda"/><a:font script="Gujr" typeface="Shruti"/><a:font script="Khmr" typeface="DaunPenh"/><a:font script="Knda" typeface="Tunga"/><a:font script="Guru" typeface="Raavi"/><a:font script="Cans" typeface="Euphemia"/><a:font script="Cher" typeface="Plantagenet Cherokee"/><a:font script="Yiii" typeface="Microsoft Yi Baiti"/><a:font script="Tibt" typeface="Microsoft Himalaya"/><a:font script="Thaa" typeface="MV Boli"/><a:font script="Deva" typeface="Mangal"/><a:font script="Telu" typeface="Gautami"/><a:font script="Taml" typeface="Latha"/><a:font script="Syrc" typeface="Estrangelo Edessa"/><a:font script="Orya" typeface="Kalinga"/><a:font script="Mlym" typeface="Kartika"/><a:font script="Laoo" typeface="DokChampa"/><a:font script="Sinh" typeface="Iskoola Pota"/><a:font script="Mong" typeface="Mongolian Baiti"/><a:font script="Viet" typeface="Arial"/><a:font script="Uigh" typeface="Microsoft Uighur"/><a:font script="Geor" typeface="Sylfaen"/></a:minorFont></a:fontScheme><a:fmtScheme name="Office"><a:fillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:gradFill rotWithShape="1"><a:gsLst><a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="50000"/><a:satMod val="300000"/></a:schemeClr></a:gs><a:gs pos="35000"><a:schemeClr val="phClr"><a:tint val="37000"/><a:satMod val="300000"/></a:schemeClr></a:gs><a:gs pos="100000"><a:schemeClr val="phClr"><a:tint val="15000"/><a:satMod val="350000"/></a:schemeClr></a:gs></a:gsLst><a:lin ang="16200000" scaled="1"/></a:gradFill><a:gradFill rotWithShape="1"><a:gsLst><a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="100000"/><a:shade val="100000"/><a:satMod val="130000"/></a:schemeClr></a:gs><a:gs pos="100000"><a:schemeClr val="phClr"><a:tint val="50000"/><a:shade val="100000"/><a:satMod val="350000"/></a:schemeClr></a:gs></a:gsLst><a:lin ang="16200000" scaled="0"/></a:gradFill></a:fillStyleLst><a:lnStyleLst><a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"><a:shade val="95000"/><a:satMod val="105000"/></a:schemeClr></a:solidFill><a:prstDash val="solid"/></a:ln><a:ln w="25400" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln><a:ln w="38100" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln></a:lnStyleLst><a:effectStyleLst><a:effectStyle><a:effectLst><a:outerShdw blurRad="40000" dist="20000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="38000"/></a:srgbClr></a:outerShdw></a:effectLst></a:effectStyle><a:effectStyle><a:effectLst><a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="35000"/></a:srgbClr></a:outerShdw></a:effectLst></a:effectStyle><a:effectStyle><a:effectLst><a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="35000"/></a:srgbClr></a:outerShdw></a:effectLst><a:scene3d><a:camera prst="orthographicFront"><a:rot lat="0" lon="0" rev="0"/></a:camera><a:lightRig rig="threePt" dir="t"><a:rot lat="0" lon="0" rev="1200000"/></a:lightRig></a:scene3d><a:sp3d><a:bevelT w="63500" h="25400"/></a:sp3d></a:effectStyle></a:effectStyleLst><a:bgFillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:gradFill rotWithShape="1"><a:gsLst><a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="40000"/><a:satMod val="350000"/></a:schemeClr></a:gs><a:gs pos="40000"><a:schemeClr val="phClr"><a:tint val="45000"/><a:shade val="99000"/><a:satMod val="350000"/></a:schemeClr></a:gs><a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="20000"/><a:satMod val="255000"/></a:schemeClr></a:gs></a:gsLst><a:path path="circle"><a:fillToRect l="50000" t="-80000" r="50000" b="180000"/></a:path></a:gradFill><a:gradFill rotWithShape="1"><a:gsLst><a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="80000"/><a:satMod val="300000"/></a:schemeClr></a:gs><a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="30000"/><a:satMod val="200000"/></a:schemeClr></a:gs></a:gsLst><a:path path="circle"><a:fillToRect l="50000" t="50000" r="50000" b="50000"/></a:path></a:gradFill></a:bgFillStyleLst></a:fmtScheme></a:themeElements><a:objectDefaults><a:spDef><a:spPr/><a:bodyPr/><a:lstStyle/><a:style><a:lnRef idx="1"><a:schemeClr val="accent1"/></a:lnRef><a:fillRef idx="3"><a:schemeClr val="accent1"/></a:fillRef><a:effectRef idx="2"><a:schemeClr val="accent1"/></a:effectRef><a:fontRef idx="minor"><a:schemeClr val="lt1"/></a:fontRef></a:style></a:spDef><a:lnDef><a:spPr/><a:bodyPr/><a:lstStyle/><a:style><a:lnRef idx="2"><a:schemeClr val="accent1"/></a:lnRef><a:fillRef idx="0"><a:schemeClr val="accent1"/></a:fillRef><a:effectRef idx="1"><a:schemeClr val="accent1"/></a:effectRef><a:fontRef idx="minor"><a:schemeClr val="tx1"/></a:fontRef></a:style></a:lnDef></a:objectDefaults><a:extraClrSchemeLst/></a:theme>'; }
28372 /* 18.6 Calculation Chain */
28373 function parse_cc_xml(data, opts) {
28374 var d = [];
28375 var l = 0, i = 1;
28376 (data.match(tagregex)||[]).forEach(function(x) {
28377 var y = parsexmltag(x);
28378 switch(y[0]) {
28379 case '<?xml': break;
28380 /* 18.6.2 calcChain CT_CalcChain 1 */
28381 case '<calcChain': case '<calcChain>': case '</calcChain>': break;
28382 /* 18.6.1 c CT_CalcCell 1 */
28383 case '<c': delete y[0]; if(y.i) i = y.i; else y.i = i; d.push(y); break;
28384 }
28385 });
28386 return d;
28387 }
28388
28389 function write_cc_xml(data, opts) { }
28390 /* [MS-XLSB] 2.6.4.1 */
28391 function parse_BrtCalcChainItem$(data, length) {
28392 var out = {};
28393 out.i = data.read_shift(4);
28394 var cell = {};
28395 cell.r = data.read_shift(4);
28396 cell.c = data.read_shift(4);
28397 out.r = encode_cell(cell);
28398 var flags = data.read_shift(1);
28399 if(flags & 0x2) out.l = '1';
28400 if(flags & 0x8) out.a = '1';
28401 return out;
28402 }
28403
28404 /* 18.6 Calculation Chain */
28405 function parse_cc_bin(data, opts) {
28406 var out = [];
28407 var pass = false;
28408 recordhopper(data, function hopper_cc(val, R, RT) {
28409 switch(R.n) {
28410 case 'BrtCalcChainItem$': out.push(val); break;
28411 case 'BrtBeginCalcChain$': break;
28412 case 'BrtEndCalcChain$': break;
28413 default: if(!pass || opts.WTF) throw new Error("Unexpected record " + RT + " " + R.n);
28414 }
28415 });
28416 return out;
28417 }
28418
28419 function write_cc_bin(data, opts) { }
28420
28421 function parse_comments(zip, dirComments, sheets, sheetRels, opts) {
28422 for(var i = 0; i != dirComments.length; ++i) {
28423 var canonicalpath=dirComments[i];
28424 var comments=parse_cmnt(getzipdata(zip, canonicalpath.replace(/^\//,''), true), canonicalpath, opts);
28425 if(!comments || !comments.length) continue;
28426 // find the sheets targeted by these comments
28427 var sheetNames = keys(sheets);
28428 for(var j = 0; j != sheetNames.length; ++j) {
28429 var sheetName = sheetNames[j];
28430 var rels = sheetRels[sheetName];
28431 if(rels) {
28432 var rel = rels[canonicalpath];
28433 if(rel) insertCommentsIntoSheet(sheetName, sheets[sheetName], comments);
28434 }
28435 }
28436 }
28437 }
28438
28439 function insertCommentsIntoSheet(sheetName, sheet, comments) {
28440 comments.forEach(function(comment) {
28441 var cell = sheet[comment.ref];
28442 if (!cell) {
28443 cell = {};
28444 sheet[comment.ref] = cell;
28445 var range = safe_decode_range(sheet["!ref"]||"BDWGO1000001:A1");
28446 var thisCell = decode_cell(comment.ref);
28447 if(range.s.r > thisCell.r) range.s.r = thisCell.r;
28448 if(range.e.r < thisCell.r) range.e.r = thisCell.r;
28449 if(range.s.c > thisCell.c) range.s.c = thisCell.c;
28450 if(range.e.c < thisCell.c) range.e.c = thisCell.c;
28451 var encoded = encode_range(range);
28452 if (encoded !== sheet["!ref"]) sheet["!ref"] = encoded;
28453 }
28454
28455 if (!cell.c) cell.c = [];
28456 var o = {a: comment.author, t: comment.t, r: comment.r};
28457 if(comment.h) o.h = comment.h;
28458 cell.c.push(o);
28459 });
28460 }
28461
28462 /* 18.7.3 CT_Comment */
28463 function parse_comments_xml(data, opts) {
28464 if(data.match(/<(?:\w+:)?comments *\/>/)) return [];
28465 var authors = [];
28466 var commentList = [];
28467 data.match(/<(?:\w+:)?authors>([^\u2603]*)<\/(?:\w+:)?authors>/)[1].split(/<\/\w*:?author>/).forEach(function(x) {
28468 if(x === "" || x.trim() === "") return;
28469 authors.push(x.match(/<(?:\w+:)?author[^>]*>(.*)/)[1]);
28470 });
28471 (data.match(/<(?:\w+:)?commentList>([^\u2603]*)<\/(?:\w+:)?commentList>/)||["",""])[1].split(/<\/\w*:?comment>/).forEach(function(x, index) {
28472 if(x === "" || x.trim() === "") return;
28473 var y = parsexmltag(x.match(/<(?:\w+:)?comment[^>]*>/)[0]);
28474 var comment = { author: y.authorId && authors[y.authorId] ? authors[y.authorId] : undefined, ref: y.ref, guid: y.guid };
28475 var cell = decode_cell(y.ref);
28476 if(opts.sheetRows && opts.sheetRows <= cell.r) return;
28477 var textMatch = x.match(/<text>([^\u2603]*)<\/text>/);
28478 if (!textMatch || !textMatch[1]) return; // a comment may contain an empty text tag.
28479 var rt = parse_si(textMatch[1]);
28480 comment.r = rt.r;
28481 comment.t = rt.t;
28482 if(opts.cellHTML) comment.h = rt.h;
28483 commentList.push(comment);
28484 });
28485 return commentList;
28486 }
28487
28488 function write_comments_xml(data, opts) { }
28489 /* [MS-XLSB] 2.4.28 BrtBeginComment */
28490 function parse_BrtBeginComment(data, length) {
28491 var out = {};
28492 out.iauthor = data.read_shift(4);
28493 var rfx = parse_UncheckedRfX(data, 16);
28494 out.rfx = rfx.s;
28495 out.ref = encode_cell(rfx.s);
28496 data.l += 16; /*var guid = parse_GUID(data); */
28497 return out;
28498 }
28499
28500 /* [MS-XLSB] 2.4.324 BrtCommentAuthor */
28501 var parse_BrtCommentAuthor = parse_XLWideString;
28502
28503 /* [MS-XLSB] 2.4.325 BrtCommentText */
28504 var parse_BrtCommentText = parse_RichStr;
28505
28506 /* [MS-XLSB] 2.1.7.8 Comments */
28507 function parse_comments_bin(data, opts) {
28508 var out = [];
28509 var authors = [];
28510 var c = {};
28511 var pass = false;
28512 recordhopper(data, function hopper_cmnt(val, R, RT) {
28513 switch(R.n) {
28514 case 'BrtCommentAuthor': authors.push(val); break;
28515 case 'BrtBeginComment': c = val; break;
28516 case 'BrtCommentText': c.t = val.t; c.h = val.h; c.r = val.r; break;
28517 case 'BrtEndComment':
28518 c.author = authors[c.iauthor];
28519 delete c.iauthor;
28520 if(opts.sheetRows && opts.sheetRows <= c.rfx.r) break;
28521 delete c.rfx; out.push(c); break;
28522 case 'BrtBeginComments': break;
28523 case 'BrtEndComments': break;
28524 case 'BrtBeginCommentAuthors': break;
28525 case 'BrtEndCommentAuthors': break;
28526 case 'BrtBeginCommentList': break;
28527 case 'BrtEndCommentList': break;
28528 default: if(!pass || opts.WTF) throw new Error("Unexpected record " + RT + " " + R.n);
28529 }
28530 });
28531 return out;
28532 }
28533
28534 function write_comments_bin(data, opts) { }
28535 /* [MS-XLSB] 2.5.97.4 CellParsedFormula TODO: use similar logic to js-xls */
28536 function parse_CellParsedFormula(data, length) {
28537 var cce = data.read_shift(4);
28538 return parsenoop(data, length-4);
28539 }
28540 var strs = {}; // shared strings
28541 var _ssfopts = {}; // spreadsheet formatting options
28542
28543 RELS.WS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet";
28544
28545 function get_sst_id(sst, str) {
28546 for(var i = 0, len = sst.length; i < len; ++i) if(sst[i].t === str) { sst.Count ++; return i; }
28547 sst[len] = {t:str}; sst.Count ++; sst.Unique ++; return len;
28548 }
28549
28550 function get_cell_style(styles, cell, opts) {
28551 var z = opts.revssf[cell.z != null ? cell.z : "General"];
28552 for(var i = 0, len = styles.length; i != len; ++i) if(styles[i].numFmtId === z) return i;
28553 styles[len] = {
28554 numFmtId:z,
28555 fontId:0,
28556 fillId:0,
28557 borderId:0,
28558 xfId:0,
28559 applyNumberFormat:1
28560 };
28561 return len;
28562 }
28563
28564 function safe_format(p, fmtid, fillid, opts) {
28565 try {
28566 if(fmtid === 0) {
28567 if(p.t === 'n') {
28568 if((p.v|0) === p.v) p.w = SSF._general_int(p.v,_ssfopts);
28569 else p.w = SSF._general_num(p.v,_ssfopts);
28570 }
28571 else if(p.v === undefined) return "";
28572 else p.w = SSF._general(p.v,_ssfopts);
28573 }
28574 else p.w = SSF.format(fmtid,p.v,_ssfopts);
28575 if(opts.cellNF) p.z = SSF._table[fmtid];
28576 } catch(e) { if(opts.WTF) throw e; }
28577 if(fillid) try {
28578 p.s = styles.Fills[fillid];
28579 if (p.s.fgColor && p.s.fgColor.theme) {
28580 p.s.fgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p.s.fgColor.theme].rgb, p.s.fgColor.tint || 0);
28581 if(opts.WTF) p.s.fgColor.raw_rgb = themes.themeElements.clrScheme[p.s.fgColor.theme].rgb;
28582 }
28583 if (p.s.bgColor && p.s.bgColor.theme) {
28584 p.s.bgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p.s.bgColor.theme].rgb, p.s.bgColor.tint || 0);
28585 if(opts.WTF) p.s.bgColor.raw_rgb = themes.themeElements.clrScheme[p.s.bgColor.theme].rgb;
28586 }
28587 } catch(e) { if(opts.WTF) throw e; }
28588 }
28589 function parse_ws_xml_dim(ws, s) {
28590 var d = safe_decode_range(s);
28591 if(d.s.r<=d.e.r && d.s.c<=d.e.c && d.s.r>=0 && d.s.c>=0) ws["!ref"] = encode_range(d);
28592 }
28593 var mergecregex = /<mergeCell ref="[A-Z0-9:]+"\s*\/>/g;
28594 var sheetdataregex = /<(?:\w+:)?sheetData>([^\u2603]*)<\/(?:\w+:)?sheetData>/;
28595 var hlinkregex = /<hyperlink[^>]*\/>/g;
28596 var dimregex = /"(\w*:\w*)"/;
28597 var colregex = /<col[^>]*\/>/g;
28598 /* 18.3 Worksheets */
28599 function parse_ws_xml(data, opts, rels) {
28600 if(!data) return data;
28601 /* 18.3.1.99 worksheet CT_Worksheet */
28602 var s = {};
28603
28604 /* 18.3.1.35 dimension CT_SheetDimension ? */
28605 var ridx = data.indexOf("<dimension");
28606 if(ridx > 0) {
28607 var ref = data.substr(ridx,50).match(dimregex);
28608 if(ref != null) parse_ws_xml_dim(s, ref[1]);
28609 }
28610
28611 /* 18.3.1.55 mergeCells CT_MergeCells */
28612 var mergecells = [];
28613 if(data.indexOf("</mergeCells>")!==-1) {
28614 var merges = data.match(mergecregex);
28615 for(ridx = 0; ridx != merges.length; ++ridx)
28616 mergecells[ridx] = safe_decode_range(merges[ridx].substr(merges[ridx].indexOf("\"")+1));
28617 }
28618
28619 /* 18.3.1.17 cols CT_Cols */
28620 var columns = [];
28621 if(opts.cellStyles && data.indexOf("</cols>")!==-1) {
28622 /* 18.3.1.13 col CT_Col */
28623 var cols = data.match(colregex);
28624 parse_ws_xml_cols(columns, cols);
28625 }
28626
28627 var refguess = {s: {r:1000000, c:1000000}, e: {r:0, c:0} };
28628
28629 /* 18.3.1.80 sheetData CT_SheetData ? */
28630 var mtch=data.match(sheetdataregex);
28631 if(mtch) parse_ws_xml_data(mtch[1], s, opts, refguess);
28632
28633 /* 18.3.1.48 hyperlinks CT_Hyperlinks */
28634 if(data.indexOf("</hyperlinks>")!==-1) parse_ws_xml_hlinks(s, data.match(hlinkregex), rels);
28635
28636 if(!s["!ref"] && refguess.e.c >= refguess.s.c && refguess.e.r >= refguess.s.r) s["!ref"] = encode_range(refguess);
28637 if(opts.sheetRows > 0 && s["!ref"]) {
28638 var tmpref = safe_decode_range(s["!ref"]);
28639 if(opts.sheetRows < +tmpref.e.r) {
28640 tmpref.e.r = opts.sheetRows - 1;
28641 if(tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
28642 if(tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
28643 if(tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
28644 if(tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
28645 s["!fullref"] = s["!ref"];
28646 s["!ref"] = encode_range(tmpref);
28647 }
28648 }
28649 if(mergecells.length > 0) s["!merges"] = mergecells;
28650 if(columns.length > 0) s["!cols"] = columns;
28651 return s;
28652 }
28653
28654
28655 function parse_ws_xml_hlinks(s, data, rels) {
28656 for(var i = 0; i != data.length; ++i) {
28657 var val = parsexmltag(data[i], true);
28658 if(!val.ref) return;
28659 var rel = rels['!id'][val.id];
28660 if(rel) {
28661 val.Target = rel.Target;
28662 if(val.location) val.Target += "#"+val.location;
28663 val.Rel = rel;
28664 }
28665 var rng = safe_decode_range(val.ref);
28666 for(var R=rng.s.r;R<=rng.e.r;++R) for(var C=rng.s.c;C<=rng.e.c;++C) {
28667 var addr = encode_cell({c:C,r:R});
28668 if(!s[addr]) s[addr] = {t:"str",v:undefined};
28669 s[addr].l = val;
28670 }
28671 }
28672 }
28673
28674 function parse_ws_xml_cols(columns, cols) {
28675 var seencol = false;
28676 for(var coli = 0; coli != cols.length; ++coli) {
28677 var coll = parsexmltag(cols[coli], true);
28678 var colm=parseInt(coll.min, 10)-1, colM=parseInt(coll.max,10)-1;
28679 delete coll.min; delete coll.max;
28680 if(!seencol && coll.width) { seencol = true; find_mdw(+coll.width, coll); }
28681 if(coll.width) {
28682 coll.wpx = width2px(+coll.width);
28683 coll.wch = px2char(coll.wpx);
28684 coll.MDW = MDW;
28685 }
28686 while(colm <= colM) columns[colm++] = coll;
28687 }
28688 }
28689
28690 function write_ws_xml_cols(ws, cols) {
28691 var o = ["<cols>"], col, width;
28692 for(var i = 0; i != cols.length; ++i) {
28693 if(!(col = cols[i])) continue;
28694 var p = {min:i+1,max:i+1};
28695 /* wch (chars), wpx (pixels) */
28696 width = -1;
28697 if(col.wpx) width = px2char(col.wpx);
28698 else if(col.wch) width = col.wch;
28699 if(width > -1) { p.width = char2width(width); p.customWidth= 1; }
28700 o[o.length] = (writextag('col', null, p));
28701 }
28702 o[o.length] = "</cols>";
28703 return o.join("");
28704 }
28705
28706 function write_ws_xml_cell(cell, ref, ws, opts, idx, wb) {
28707 if(cell.v === undefined) return "";
28708 var vv = "";
28709 switch(cell.t) {
28710 case 'b': vv = cell.v ? "1" : "0"; break;
28711 case 'n': case 'e': vv = ''+cell.v; break;
28712 default: vv = cell.v; break;
28713 }
28714 var v = writetag('v', escapexml(vv)), o = {r:ref};
28715 /* TODO: cell style */
28716 var os = get_cell_style(opts.cellXfs, cell, opts);
28717 if(os !== 0) o.s = os;
28718 switch(cell.t) {
28719 case 'n': break;
28720 case 'b': o.t = "b"; break;
28721 case 'e': o.t = "e"; break;
28722 default:
28723 if(opts.bookSST) {
28724 v = writetag('v', ''+get_sst_id(opts.Strings, cell.v));
28725 o.t = "s"; break;
28726 }
28727 o.t = "str"; break;
28728 }
28729 return writextag('c', v, o);
28730 }
28731
28732 var parse_ws_xml_data = (function parse_ws_xml_data_factory() {
28733 var cellregex = /<(?:\w+:)?c /, rowregex = /<\/(?:\w+:)?row>/;
28734 var rregex = /r=["']([^"']*)["']/, isregex = /<is>([\S\s]*?)<\/is>/;
28735 var match_v = matchtag("v"), match_f = matchtag("f");
28736
28737 return function parse_ws_xml_data(sdata, s, opts, guess) {
28738 var ri = 0, x = "", cells = [], cref = [], idx = 0, i=0, cc=0, d="", p;
28739 var tag;
28740 var sstr;
28741 var fmtid = 0, fillid = 0, do_format = Array.isArray(styles.CellXf), cf;
28742 for(var marr = sdata.split(rowregex), mt = 0, marrlen = marr.length; mt != marrlen; ++mt) {
28743 x = marr[mt].trim();
28744 var xlen = x.length;
28745 if(xlen === 0) continue;
28746
28747 /* 18.3.1.73 row CT_Row */
28748 for(ri = 0; ri < xlen; ++ri) if(x.charCodeAt(ri) === 62) break; ++ri;
28749 tag = parsexmltag(x.substr(0,ri), true);
28750 var tagr = parseInt(tag.r, 10);
28751 if(opts.sheetRows && opts.sheetRows < tagr) continue;
28752 if(guess.s.r > tagr - 1) guess.s.r = tagr - 1;
28753 if(guess.e.r < tagr - 1) guess.e.r = tagr - 1;
28754
28755 /* 18.3.1.4 c CT_Cell */
28756 cells = x.substr(ri).split(cellregex);
28757 for(ri = 1, cellen = cells.length; ri != cellen; ++ri) {
28758 x = cells[ri].trim();
28759 if(x.length === 0) continue;
28760 cref = x.match(rregex); idx = ri; i=0; cc=0;
28761 x = "<c " + x;
28762 if(cref !== null && cref.length === 2) {
28763 idx = 0; d=cref[1];
28764 for(i=0; i != d.length; ++i) {
28765 if((cc=d.charCodeAt(i)-64) < 1 || cc > 26) break;
28766 idx = 26*idx + cc;
28767 }
28768 --idx;
28769 }
28770
28771 for(i = 0; i != x.length; ++i) if(x.charCodeAt(i) === 62) break; ++i;
28772 tag = parsexmltag(x.substr(0,i), true);
28773 d = x.substr(i);
28774 p = {t:""};
28775
28776 if((cref=d.match(match_v))!== null) p.v=unescapexml(cref[1]);
28777 if(opts.cellFormula && (cref=d.match(match_f))!== null) p.f=unescapexml(cref[1]);
28778
28779 /* SCHEMA IS ACTUALLY INCORRECT HERE. IF A CELL HAS NO T, EMIT "" */
28780 if(tag.t === undefined && p.v === undefined) {
28781 if(!opts.sheetStubs) continue;
28782 p.t = "str";
28783 }
28784 else p.t = tag.t || "n";
28785 if(guess.s.c > idx) guess.s.c = idx;
28786 if(guess.e.c < idx) guess.e.c = idx;
28787 /* 18.18.11 t ST_CellType */
28788 switch(p.t) {
28789 case 'n': p.v = parseFloat(p.v); break;
28790 case 's':
28791 sstr = strs[parseInt(p.v, 10)];
28792 p.v = sstr.t;
28793 p.r = sstr.r;
28794 if(opts.cellHTML) p.h = sstr.h;
28795 break;
28796 case 'str': if(p.v != null) p.v = utf8read(p.v); else p.v = ""; break;
28797 case 'inlineStr':
28798 cref = d.match(isregex);
28799 p.t = 'str';
28800 if(cref !== null) { sstr = parse_si(cref[1]); p.v = sstr.t; } else p.v = "";
28801 break; // inline string
28802 case 'b': p.v = parsexmlbool(p.v); break;
28803 case 'd':
28804 p.v = datenum(p.v);
28805 p.t = 'n';
28806 break;
28807 /* in case of error, stick value in .raw */
28808 case 'e': p.raw = RBErr[p.v]; break;
28809 }
28810 /* formatting */
28811 fmtid = fillid = 0;
28812 if(do_format && tag.s !== undefined) {
28813 cf = styles.CellXf[tag.s];
28814 if(cf != null) {
28815 if(cf.numFmtId != null) fmtid = cf.numFmtId;
28816 if(opts.cellStyles && cf.fillId != null) fillid = cf.fillId;
28817 }
28818 }
28819 safe_format(p, fmtid, fillid, opts);
28820 s[tag.r] = p;
28821 }
28822 }
28823 }; })();
28824
28825 function write_ws_xml_data(ws, opts, idx, wb) {
28826 var o = [], r = [], range = safe_decode_range(ws['!ref']), cell, ref, rr = "", cols = [], R, C;
28827 for(C = range.s.c; C <= range.e.c; ++C) cols[C] = encode_col(C);
28828 for(R = range.s.r; R <= range.e.r; ++R) {
28829 r = [];
28830 rr = encode_row(R);
28831 for(C = range.s.c; C <= range.e.c; ++C) {
28832 ref = cols[C] + rr;
28833 if(ws[ref] === undefined) continue;
28834 if((cell = write_ws_xml_cell(ws[ref], ref, ws, opts, idx, wb)) != null) r.push(cell);
28835 }
28836 if(r.length > 0) o[o.length] = (writextag('row', r.join(""), {r:rr}));
28837 }
28838 return o.join("");
28839 }
28840
28841 var WS_XML_ROOT = writextag('worksheet', null, {
28842 'xmlns': XMLNS.main[0],
28843 'xmlns:r': XMLNS.r
28844 });
28845
28846 function write_ws_xml(idx, opts, wb) {
28847 var o = [XML_HEADER, WS_XML_ROOT];
28848 var s = wb.SheetNames[idx], sidx = 0, rdata = "";
28849 var ws = wb.Sheets[s];
28850 if(ws === undefined) ws = {};
28851 var ref = ws['!ref']; if(ref === undefined) ref = 'A1';
28852 o[o.length] = (writextag('dimension', null, {'ref': ref}));
28853
28854 if(ws['!cols'] !== undefined && ws['!cols'].length > 0) o[o.length] = (write_ws_xml_cols(ws, ws['!cols']));
28855 o[sidx = o.length] = '<sheetData/>';
28856 if(ws['!ref'] !== undefined) {
28857 rdata = write_ws_xml_data(ws, opts, idx, wb);
28858 if(rdata.length > 0) o[o.length] = (rdata);
28859 }
28860 if(o.length>sidx+1) { o[o.length] = ('</sheetData>'); o[sidx]=o[sidx].replace("/>",">"); }
28861
28862 if(o.length>2) { o[o.length] = ('</worksheet>'); o[1]=o[1].replace("/>",">"); }
28863 return o.join("");
28864 }
28865
28866 /* [MS-XLSB] 2.4.718 BrtRowHdr */
28867 function parse_BrtRowHdr(data, length) {
28868 var z = [];
28869 z.r = data.read_shift(4);
28870 data.l += length-4;
28871 return z;
28872 }
28873
28874 /* [MS-XLSB] 2.4.812 BrtWsDim */
28875 var parse_BrtWsDim = parse_UncheckedRfX;
28876 var write_BrtWsDim = write_UncheckedRfX;
28877
28878 /* [MS-XLSB] 2.4.815 BrtWsProp */
28879 function parse_BrtWsProp(data, length) {
28880 var z = {};
28881 /* TODO: pull flags */
28882 data.l += 19;
28883 z.name = parse_CodeName(data, length - 19);
28884 return z;
28885 }
28886
28887 /* [MS-XLSB] 2.4.303 BrtCellBlank */
28888 function parse_BrtCellBlank(data, length) {
28889 var cell = parse_Cell(data);
28890 return [cell];
28891 }
28892 function write_BrtCellBlank(cell, val, o) {
28893 if(o == null) o = new_buf(8);
28894 return write_Cell(val, o);
28895 }
28896
28897
28898 /* [MS-XLSB] 2.4.304 BrtCellBool */
28899 function parse_BrtCellBool(data, length) {
28900 var cell = parse_Cell(data);
28901 var fBool = data.read_shift(1);
28902 return [cell, fBool, 'b'];
28903 }
28904
28905 /* [MS-XLSB] 2.4.305 BrtCellError */
28906 function parse_BrtCellError(data, length) {
28907 var cell = parse_Cell(data);
28908 var fBool = data.read_shift(1);
28909 return [cell, fBool, 'e'];
28910 }
28911
28912 /* [MS-XLSB] 2.4.308 BrtCellIsst */
28913 function parse_BrtCellIsst(data, length) {
28914 var cell = parse_Cell(data);
28915 var isst = data.read_shift(4);
28916 return [cell, isst, 's'];
28917 }
28918
28919 /* [MS-XLSB] 2.4.310 BrtCellReal */
28920 function parse_BrtCellReal(data, length) {
28921 var cell = parse_Cell(data);
28922 var value = parse_Xnum(data);
28923 return [cell, value, 'n'];
28924 }
28925
28926 /* [MS-XLSB] 2.4.311 BrtCellRk */
28927 function parse_BrtCellRk(data, length) {
28928 var cell = parse_Cell(data);
28929 var value = parse_RkNumber(data);
28930 return [cell, value, 'n'];
28931 }
28932
28933 /* [MS-XLSB] 2.4.314 BrtCellSt */
28934 function parse_BrtCellSt(data, length) {
28935 var cell = parse_Cell(data);
28936 var value = parse_XLWideString(data);
28937 return [cell, value, 'str'];
28938 }
28939
28940 /* [MS-XLSB] 2.4.647 BrtFmlaBool */
28941 function parse_BrtFmlaBool(data, length, opts) {
28942 var cell = parse_Cell(data);
28943 var value = data.read_shift(1);
28944 var o = [cell, value, 'b'];
28945 if(opts.cellFormula) {
28946 var formula = parse_CellParsedFormula(data, length-9);
28947 o[3] = ""; /* TODO */
28948 }
28949 else data.l += length-9;
28950 return o;
28951 }
28952
28953 /* [MS-XLSB] 2.4.648 BrtFmlaError */
28954 function parse_BrtFmlaError(data, length, opts) {
28955 var cell = parse_Cell(data);
28956 var value = data.read_shift(1);
28957 var o = [cell, value, 'e'];
28958 if(opts.cellFormula) {
28959 var formula = parse_CellParsedFormula(data, length-9);
28960 o[3] = ""; /* TODO */
28961 }
28962 else data.l += length-9;
28963 return o;
28964 }
28965
28966 /* [MS-XLSB] 2.4.649 BrtFmlaNum */
28967 function parse_BrtFmlaNum(data, length, opts) {
28968 var cell = parse_Cell(data);
28969 var value = parse_Xnum(data);
28970 var o = [cell, value, 'n'];
28971 if(opts.cellFormula) {
28972 var formula = parse_CellParsedFormula(data, length - 16);
28973 o[3] = ""; /* TODO */
28974 }
28975 else data.l += length-16;
28976 return o;
28977 }
28978
28979 /* [MS-XLSB] 2.4.650 BrtFmlaString */
28980 function parse_BrtFmlaString(data, length, opts) {
28981 var start = data.l;
28982 var cell = parse_Cell(data);
28983 var value = parse_XLWideString(data);
28984 var o = [cell, value, 'str'];
28985 if(opts.cellFormula) {
28986 var formula = parse_CellParsedFormula(data, start + length - data.l);
28987 }
28988 else data.l = start + length;
28989 return o;
28990 }
28991
28992 /* [MS-XLSB] 2.4.676 BrtMergeCell */
28993 var parse_BrtMergeCell = parse_UncheckedRfX;
28994
28995 /* [MS-XLSB] 2.4.656 BrtHLink */
28996 function parse_BrtHLink(data, length, opts) {
28997 var end = data.l + length;
28998 var rfx = parse_UncheckedRfX(data, 16);
28999 var relId = parse_XLNullableWideString(data);
29000 var loc = parse_XLWideString(data);
29001 var tooltip = parse_XLWideString(data);
29002 var display = parse_XLWideString(data);
29003 data.l = end;
29004 return {rfx:rfx, relId:relId, loc:loc, tooltip:tooltip, display:display};
29005 }
29006
29007 /* [MS-XLSB] 2.1.7.61 Worksheet */
29008 function parse_ws_bin(data, opts, rels) {
29009 if(!data) return data;
29010 if(!rels) rels = {'!id':{}};
29011 var s = {};
29012
29013 var ref;
29014 var refguess = {s: {r:1000000, c:1000000}, e: {r:0, c:0} };
29015
29016 var pass = false, end = false;
29017 var row, p, cf, R, C, addr, sstr, rr;
29018 var mergecells = [];
29019 recordhopper(data, function ws_parse(val, R) {
29020 if(end) return;
29021 switch(R.n) {
29022 case 'BrtWsDim': ref = val; break;
29023 case 'BrtRowHdr':
29024 row = val;
29025 if(opts.sheetRows && opts.sheetRows <= row.r) end=true;
29026 rr = encode_row(row.r);
29027 break;
29028
29029 case 'BrtFmlaBool':
29030 case 'BrtFmlaError':
29031 case 'BrtFmlaNum':
29032 case 'BrtFmlaString':
29033 case 'BrtCellBool':
29034 case 'BrtCellError':
29035 case 'BrtCellIsst':
29036 case 'BrtCellReal':
29037 case 'BrtCellRk':
29038 case 'BrtCellSt':
29039 p = {t:val[2]};
29040 switch(val[2]) {
29041 case 'n': p.v = val[1]; break;
29042 case 's': sstr = strs[val[1]]; p.v = sstr.t; p.r = sstr.r; break;
29043 case 'b': p.v = val[1] ? true : false; break;
29044 case 'e': p.raw = val[1]; p.v = BErr[p.raw]; break;
29045 case 'str': p.v = utf8read(val[1]); break;
29046 }
29047 if(opts.cellFormula && val.length > 3) p.f = val[3];
29048 if((cf = styles.CellXf[val[0].iStyleRef])) safe_format(p,cf.ifmt,null,opts);
29049 s[encode_col(C=val[0].c) + rr] = p;
29050 if(refguess.s.r > row.r) refguess.s.r = row.r;
29051 if(refguess.s.c > C) refguess.s.c = C;
29052 if(refguess.e.r < row.r) refguess.e.r = row.r;
29053 if(refguess.e.c < C) refguess.e.c = C;
29054 break;
29055
29056 case 'BrtCellBlank': if(!opts.sheetStubs) break;
29057 p = {t:'str',v:undefined};
29058 s[encode_col(C=val[0].c) + rr] = p;
29059 if(refguess.s.r > row.r) refguess.s.r = row.r;
29060 if(refguess.s.c > C) refguess.s.c = C;
29061 if(refguess.e.r < row.r) refguess.e.r = row.r;
29062 if(refguess.e.c < C) refguess.e.c = C;
29063 break;
29064
29065 /* Merge Cells */
29066 case 'BrtBeginMergeCells': break;
29067 case 'BrtEndMergeCells': break;
29068 case 'BrtMergeCell': mergecells.push(val); break;
29069
29070 case 'BrtHLink':
29071 var rel = rels['!id'][val.relId];
29072 if(rel) {
29073 val.Target = rel.Target;
29074 if(val.loc) val.Target += "#"+val.loc;
29075 val.Rel = rel;
29076 }
29077 for(R=val.rfx.s.r;R<=val.rfx.e.r;++R) for(C=val.rfx.s.c;C<=val.rfx.e.c;++C) {
29078 addr = encode_cell({c:C,r:R});
29079 if(!s[addr]) s[addr] = {t:"str",v:undefined};
29080 s[addr].l = val;
29081 }
29082 break;
29083
29084 case 'BrtArrFmla': break; // TODO
29085 case 'BrtShrFmla': break; // TODO
29086 case 'BrtBeginSheet': break;
29087 case 'BrtWsProp': break; // TODO
29088 case 'BrtSheetCalcProp': break; // TODO
29089 case 'BrtBeginWsViews': break; // TODO
29090 case 'BrtBeginWsView': break; // TODO
29091 case 'BrtPane': break; // TODO
29092 case 'BrtSel': break; // TODO
29093 case 'BrtEndWsView': break; // TODO
29094 case 'BrtEndWsViews': break; // TODO
29095 case 'BrtACBegin': break; // TODO
29096 case 'BrtRwDescent': break; // TODO
29097 case 'BrtACEnd': break; // TODO
29098 case 'BrtWsFmtInfoEx14': break; // TODO
29099 case 'BrtWsFmtInfo': break; // TODO
29100 case 'BrtBeginColInfos': break; // TODO
29101 case 'BrtColInfo': break; // TODO
29102 case 'BrtEndColInfos': break; // TODO
29103 case 'BrtBeginSheetData': break; // TODO
29104 case 'BrtEndSheetData': break; // TODO
29105 case 'BrtSheetProtection': break; // TODO
29106 case 'BrtPrintOptions': break; // TODO
29107 case 'BrtMargins': break; // TODO
29108 case 'BrtPageSetup': break; // TODO
29109 case 'BrtFRTBegin': pass = true; break;
29110 case 'BrtFRTEnd': pass = false; break;
29111 case 'BrtEndSheet': break; // TODO
29112 case 'BrtDrawing': break; // TODO
29113 case 'BrtLegacyDrawing': break; // TODO
29114 case 'BrtLegacyDrawingHF': break; // TODO
29115 case 'BrtPhoneticInfo': break; // TODO
29116 case 'BrtBeginHeaderFooter': break; // TODO
29117 case 'BrtEndHeaderFooter': break; // TODO
29118 case 'BrtBrk': break; // TODO
29119 case 'BrtBeginRwBrk': break; // TODO
29120 case 'BrtEndRwBrk': break; // TODO
29121 case 'BrtBeginColBrk': break; // TODO
29122 case 'BrtEndColBrk': break; // TODO
29123 case 'BrtBeginUserShViews': break; // TODO
29124 case 'BrtBeginUserShView': break; // TODO
29125 case 'BrtEndUserShView': break; // TODO
29126 case 'BrtEndUserShViews': break; // TODO
29127 case 'BrtBkHim': break; // TODO
29128 case 'BrtBeginOleObjects': break; // TODO
29129 case 'BrtOleObject': break; // TODO
29130 case 'BrtEndOleObjects': break; // TODO
29131 case 'BrtBeginListParts': break; // TODO
29132 case 'BrtListPart': break; // TODO
29133 case 'BrtEndListParts': break; // TODO
29134 case 'BrtBeginSortState': break; // TODO
29135 case 'BrtBeginSortCond': break; // TODO
29136 case 'BrtEndSortCond': break; // TODO
29137 case 'BrtEndSortState': break; // TODO
29138 case 'BrtBeginConditionalFormatting': break; // TODO
29139 case 'BrtEndConditionalFormatting': break; // TODO
29140 case 'BrtBeginCFRule': break; // TODO
29141 case 'BrtEndCFRule': break; // TODO
29142 case 'BrtBeginDVals': break; // TODO
29143 case 'BrtDVal': break; // TODO
29144 case 'BrtEndDVals': break; // TODO
29145 case 'BrtRangeProtection': break; // TODO
29146 case 'BrtBeginDCon': break; // TODO
29147 case 'BrtEndDCon': break; // TODO
29148 case 'BrtBeginDRefs': break;
29149 case 'BrtDRef': break;
29150 case 'BrtEndDRefs': break;
29151
29152 /* ActiveX */
29153 case 'BrtBeginActiveXControls': break;
29154 case 'BrtActiveX': break;
29155 case 'BrtEndActiveXControls': break;
29156
29157 /* AutoFilter */
29158 case 'BrtBeginAFilter': break;
29159 case 'BrtEndAFilter': break;
29160 case 'BrtBeginFilterColumn': break;
29161 case 'BrtBeginFilters': break;
29162 case 'BrtFilter': break;
29163 case 'BrtEndFilters': break;
29164 case 'BrtEndFilterColumn': break;
29165 case 'BrtDynamicFilter': break;
29166 case 'BrtTop10Filter': break;
29167 case 'BrtBeginCustomFilters': break;
29168 case 'BrtCustomFilter': break;
29169 case 'BrtEndCustomFilters': break;
29170
29171 /* Smart Tags */
29172 case 'BrtBeginSmartTags': break;
29173 case 'BrtBeginCellSmartTags': break;
29174 case 'BrtBeginCellSmartTag': break;
29175 case 'BrtCellSmartTagProperty': break;
29176 case 'BrtEndCellSmartTag': break;
29177 case 'BrtEndCellSmartTags': break;
29178 case 'BrtEndSmartTags': break;
29179
29180 /* Cell Watch */
29181 case 'BrtBeginCellWatches': break;
29182 case 'BrtCellWatch': break;
29183 case 'BrtEndCellWatches': break;
29184
29185 /* Table */
29186 case 'BrtTable': break;
29187
29188 /* Ignore Cell Errors */
29189 case 'BrtBeginCellIgnoreECs': break;
29190 case 'BrtCellIgnoreEC': break;
29191 case 'BrtEndCellIgnoreECs': break;
29192
29193 default: if(!pass || opts.WTF) throw new Error("Unexpected record " + R.n);
29194 }
29195 }, opts);
29196 if(!s["!ref"] && (refguess.s.r < 1000000 || ref.e.r > 0 || ref.e.c > 0 || ref.s.r > 0 || ref.s.c > 0)) s["!ref"] = encode_range(ref);
29197 if(opts.sheetRows && s["!ref"]) {
29198 var tmpref = safe_decode_range(s["!ref"]);
29199 if(opts.sheetRows < +tmpref.e.r) {
29200 tmpref.e.r = opts.sheetRows - 1;
29201 if(tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
29202 if(tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
29203 if(tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
29204 if(tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
29205 s["!fullref"] = s["!ref"];
29206 s["!ref"] = encode_range(tmpref);
29207 }
29208 }
29209 if(mergecells.length > 0) s["!merges"] = mergecells;
29210 return s;
29211 }
29212
29213 /* TODO: something useful -- this is a stub */
29214 function write_ws_bin_cell(ba, cell, R, C, opts) {
29215 if(cell.v === undefined) return "";
29216 var vv = "";
29217 switch(cell.t) {
29218 case 'b': vv = cell.v ? "1" : "0"; break;
29219 case 'n': case 'e': vv = ''+cell.v; break;
29220 default: vv = cell.v; break;
29221 }
29222 var o = {r:R, c:C};
29223 /* TODO: cell style */
29224 o.s = get_cell_style(opts.cellXfs, cell, opts);
29225 switch(cell.t) {
29226 case 's': case 'str':
29227 if(opts.bookSST) {
29228 vv = get_sst_id(opts.Strings, cell.v);
29229 o.t = "s"; break;
29230 }
29231 o.t = "str"; break;
29232 case 'n': break;
29233 case 'b': o.t = "b"; break;
29234 case 'e': o.t = "e"; break;
29235 }
29236 write_record(ba, "BrtCellBlank", write_BrtCellBlank(cell, o));
29237 }
29238
29239 function write_CELLTABLE(ba, ws, idx, opts, wb) {
29240 var range = safe_decode_range(ws['!ref'] || "A1"), ref, rr = "", cols = [];
29241 write_record(ba, 'BrtBeginSheetData');
29242 for(var R = range.s.r; R <= range.e.r; ++R) {
29243 rr = encode_row(R);
29244 /* [ACCELLTABLE] */
29245 /* BrtRowHdr */
29246 for(var C = range.s.c; C <= range.e.c; ++C) {
29247 /* *16384CELL */
29248 if(R === range.s.r) cols[C] = encode_col(C);
29249 ref = cols[C] + rr;
29250 if(!ws[ref]) continue;
29251 /* write cell */
29252 write_ws_bin_cell(ba, ws[ref], R, C, opts);
29253 }
29254 }
29255 write_record(ba, 'BrtEndSheetData');
29256 }
29257
29258 function write_ws_bin(idx, opts, wb) {
29259 var ba = buf_array();
29260 var s = wb.SheetNames[idx], ws = wb.Sheets[s] || {};
29261 var r = safe_decode_range(ws['!ref'] || "A1");
29262 write_record(ba, "BrtBeginSheet");
29263 /* [BrtWsProp] */
29264 write_record(ba, "BrtWsDim", write_BrtWsDim(r));
29265 /* [WSVIEWS2] */
29266 /* [WSFMTINFO] */
29267 /* *COLINFOS */
29268 write_CELLTABLE(ba, ws, idx, opts, wb);
29269 /* [BrtSheetCalcProp] */
29270 /* [[BrtSheetProtectionIso] BrtSheetProtection] */
29271 /* *([BrtRangeProtectionIso] BrtRangeProtection) */
29272 /* [SCENMAN] */
29273 /* [AUTOFILTER] */
29274 /* [SORTSTATE] */
29275 /* [DCON] */
29276 /* [USERSHVIEWS] */
29277 /* [MERGECELLS] */
29278 /* [BrtPhoneticInfo] */
29279 /* *CONDITIONALFORMATTING */
29280 /* [DVALS] */
29281 /* *BrtHLink */
29282 /* [BrtPrintOptions] */
29283 /* [BrtMargins] */
29284 /* [BrtPageSetup] */
29285 /* [HEADERFOOTER] */
29286 /* [RWBRK] */
29287 /* [COLBRK] */
29288 /* *BrtBigName */
29289 /* [CELLWATCHES] */
29290 /* [IGNOREECS] */
29291 /* [SMARTTAGS] */
29292 /* [BrtDrawing] */
29293 /* [BrtLegacyDrawing] */
29294 /* [BrtLegacyDrawingHF] */
29295 /* [BrtBkHim] */
29296 /* [OLEOBJECTS] */
29297 /* [ACTIVEXCONTROLS] */
29298 /* [WEBPUBITEMS] */
29299 /* [LISTPARTS] */
29300 /* FRTWORKSHEET */
29301 write_record(ba, "BrtEndSheet");
29302 return ba.end();
29303 }
29304 /* 18.2.28 (CT_WorkbookProtection) Defaults */
29305 var WBPropsDef = [
29306 ['allowRefreshQuery', '0'],
29307 ['autoCompressPictures', '1'],
29308 ['backupFile', '0'],
29309 ['checkCompatibility', '0'],
29310 ['codeName', ''],
29311 ['date1904', '0'],
29312 ['dateCompatibility', '1'],
29313 //['defaultThemeVersion', '0'],
29314 ['filterPrivacy', '0'],
29315 ['hidePivotFieldList', '0'],
29316 ['promptedSolutions', '0'],
29317 ['publishItems', '0'],
29318 ['refreshAllConnections', false],
29319 ['saveExternalLinkValues', '1'],
29320 ['showBorderUnselectedTables', '1'],
29321 ['showInkAnnotation', '1'],
29322 ['showObjects', 'all'],
29323 ['showPivotChartFilter', '0']
29324 //['updateLinks', 'userSet']
29325 ];
29326
29327 /* 18.2.30 (CT_BookView) Defaults */
29328 var WBViewDef = [
29329 ['activeTab', '0'],
29330 ['autoFilterDateGrouping', '1'],
29331 ['firstSheet', '0'],
29332 ['minimized', '0'],
29333 ['showHorizontalScroll', '1'],
29334 ['showSheetTabs', '1'],
29335 ['showVerticalScroll', '1'],
29336 ['tabRatio', '600'],
29337 ['visibility', 'visible']
29338 //window{Height,Width}, {x,y}Window
29339 ];
29340
29341 /* 18.2.19 (CT_Sheet) Defaults */
29342 var SheetDef = [
29343 ['state', 'visible']
29344 ];
29345
29346 /* 18.2.2 (CT_CalcPr) Defaults */
29347 var CalcPrDef = [
29348 ['calcCompleted', 'true'],
29349 ['calcMode', 'auto'],
29350 ['calcOnSave', 'true'],
29351 ['concurrentCalc', 'true'],
29352 ['fullCalcOnLoad', 'false'],
29353 ['fullPrecision', 'true'],
29354 ['iterate', 'false'],
29355 ['iterateCount', '100'],
29356 ['iterateDelta', '0.001'],
29357 ['refMode', 'A1']
29358 ];
29359
29360 /* 18.2.3 (CT_CustomWorkbookView) Defaults */
29361 var CustomWBViewDef = [
29362 ['autoUpdate', 'false'],
29363 ['changesSavedWin', 'false'],
29364 ['includeHiddenRowCol', 'true'],
29365 ['includePrintSettings', 'true'],
29366 ['maximized', 'false'],
29367 ['minimized', 'false'],
29368 ['onlySync', 'false'],
29369 ['personalView', 'false'],
29370 ['showComments', 'commIndicator'],
29371 ['showFormulaBar', 'true'],
29372 ['showHorizontalScroll', 'true'],
29373 ['showObjects', 'all'],
29374 ['showSheetTabs', 'true'],
29375 ['showStatusbar', 'true'],
29376 ['showVerticalScroll', 'true'],
29377 ['tabRatio', '600'],
29378 ['xWindow', '0'],
29379 ['yWindow', '0']
29380 ];
29381
29382 function push_defaults_array(target, defaults) {
29383 for(var j = 0; j != target.length; ++j) { var w = target[j];
29384 for(var i=0; i != defaults.length; ++i) { var z = defaults[i];
29385 if(w[z[0]] == null) w[z[0]] = z[1];
29386 }
29387 }
29388 }
29389 function push_defaults(target, defaults) {
29390 for(var i = 0; i != defaults.length; ++i) { var z = defaults[i];
29391 if(target[z[0]] == null) target[z[0]] = z[1];
29392 }
29393 }
29394
29395 function parse_wb_defaults(wb) {
29396 push_defaults(wb.WBProps, WBPropsDef);
29397 push_defaults(wb.CalcPr, CalcPrDef);
29398
29399 push_defaults_array(wb.WBView, WBViewDef);
29400 push_defaults_array(wb.Sheets, SheetDef);
29401
29402 _ssfopts.date1904 = parsexmlbool(wb.WBProps.date1904, 'date1904');
29403 }
29404 /* 18.2 Workbook */
29405 var wbnsregex = /<\w+:workbook/;
29406 function parse_wb_xml(data, opts) {
29407 var wb = { AppVersion:{}, WBProps:{}, WBView:[], Sheets:[], CalcPr:{}, xmlns: "" };
29408 var pass = false, xmlns = "xmlns";
29409 data.match(tagregex).forEach(function xml_wb(x) {
29410 var y = parsexmltag(x);
29411 switch(strip_ns(y[0])) {
29412 case '<?xml': break;
29413
29414 /* 18.2.27 workbook CT_Workbook 1 */
29415 case '<workbook':
29416 if(x.match(wbnsregex)) xmlns = "xmlns" + x.match(/<(\w+):/)[1];
29417 wb.xmlns = y[xmlns];
29418 break;
29419 case '</workbook>': break;
29420
29421 /* 18.2.13 fileVersion CT_FileVersion ? */
29422 case '<fileVersion': delete y[0]; wb.AppVersion = y; break;
29423 case '<fileVersion/>': break;
29424
29425 /* 18.2.12 fileSharing CT_FileSharing ? */
29426 case '<fileSharing': case '<fileSharing/>': break;
29427
29428 /* 18.2.28 workbookPr CT_WorkbookPr ? */
29429 case '<workbookPr': delete y[0]; wb.WBProps = y; break;
29430 case '<workbookPr/>': delete y[0]; wb.WBProps = y; break;
29431
29432 /* 18.2.29 workbookProtection CT_WorkbookProtection ? */
29433 case '<workbookProtection': break;
29434 case '<workbookProtection/>': break;
29435
29436 /* 18.2.1 bookViews CT_BookViews ? */
29437 case '<bookViews>': case '</bookViews>': break;
29438 /* 18.2.30 workbookView CT_BookView + */
29439 case '<workbookView': delete y[0]; wb.WBView.push(y); break;
29440
29441 /* 18.2.20 sheets CT_Sheets 1 */
29442 case '<sheets>': case '</sheets>': break; // aggregate sheet
29443 /* 18.2.19 sheet CT_Sheet + */
29444 case '<sheet': delete y[0]; y.name = utf8read(y.name); wb.Sheets.push(y); break;
29445
29446 /* 18.2.15 functionGroups CT_FunctionGroups ? */
29447 case '<functionGroups': case '<functionGroups/>': break;
29448 /* 18.2.14 functionGroup CT_FunctionGroup + */
29449 case '<functionGroup': break;
29450
29451 /* 18.2.9 externalReferences CT_ExternalReferences ? */
29452 case '<externalReferences': case '</externalReferences>': case '<externalReferences>': break;
29453 /* 18.2.8 externalReference CT_ExternalReference + */
29454 case '<externalReference': break;
29455
29456 /* 18.2.6 definedNames CT_DefinedNames ? */
29457 case '<definedNames/>': break;
29458 case '<definedNames>': case '<definedNames': pass=true; break;
29459 case '</definedNames>': pass=false; break;
29460 /* 18.2.5 definedName CT_DefinedName + */
29461 case '<definedName': case '<definedName/>': case '</definedName>': break;
29462
29463 /* 18.2.2 calcPr CT_CalcPr ? */
29464 case '<calcPr': delete y[0]; wb.CalcPr = y; break;
29465 case '<calcPr/>': delete y[0]; wb.CalcPr = y; break;
29466
29467 /* 18.2.16 oleSize CT_OleSize ? (ref required) */
29468 case '<oleSize': break;
29469
29470 /* 18.2.4 customWorkbookViews CT_CustomWorkbookViews ? */
29471 case '<customWorkbookViews>': case '</customWorkbookViews>': case '<customWorkbookViews': break;
29472 /* 18.2.3 customWorkbookView CT_CustomWorkbookView + */
29473 case '<customWorkbookView': case '</customWorkbookView>': break;
29474
29475 /* 18.2.18 pivotCaches CT_PivotCaches ? */
29476 case '<pivotCaches>': case '</pivotCaches>': case '<pivotCaches': break;
29477 /* 18.2.17 pivotCache CT_PivotCache ? */
29478 case '<pivotCache': break;
29479
29480 /* 18.2.21 smartTagPr CT_SmartTagPr ? */
29481 case '<smartTagPr': case '<smartTagPr/>': break;
29482
29483 /* 18.2.23 smartTagTypes CT_SmartTagTypes ? */
29484 case '<smartTagTypes': case '<smartTagTypes>': case '</smartTagTypes>': break;
29485 /* 18.2.22 smartTagType CT_SmartTagType ? */
29486 case '<smartTagType': break;
29487
29488 /* 18.2.24 webPublishing CT_WebPublishing ? */
29489 case '<webPublishing': case '<webPublishing/>': break;
29490
29491 /* 18.2.11 fileRecoveryPr CT_FileRecoveryPr ? */
29492 case '<fileRecoveryPr': case '<fileRecoveryPr/>': break;
29493
29494 /* 18.2.26 webPublishObjects CT_WebPublishObjects ? */
29495 case '<webPublishObjects>': case '<webPublishObjects': case '</webPublishObjects>': break;
29496 /* 18.2.25 webPublishObject CT_WebPublishObject ? */
29497 case '<webPublishObject': break;
29498
29499 /* 18.2.10 extLst CT_ExtensionList ? */
29500 case '<extLst>': case '</extLst>': case '<extLst/>': break;
29501 /* 18.2.7 ext CT_Extension + */
29502 case '<ext': pass=true; break; //TODO: check with versions of excel
29503 case '</ext>': pass=false; break;
29504
29505 /* Others */
29506 case '<ArchID': break;
29507 case '<AlternateContent': pass=true; break;
29508 case '</AlternateContent>': pass=false; break;
29509
29510 default: if(!pass && opts.WTF) throw 'unrecognized ' + y[0] + ' in workbook';
29511 }
29512 });
29513 if(XMLNS.main.indexOf(wb.xmlns) === -1) throw new Error("Unknown Namespace: " + wb.xmlns);
29514
29515 parse_wb_defaults(wb);
29516
29517 return wb;
29518 }
29519
29520 var WB_XML_ROOT = writextag('workbook', null, {
29521 'xmlns': XMLNS.main[0],
29522 //'xmlns:mx': XMLNS.mx,
29523 //'xmlns:s': XMLNS.main[0],
29524 'xmlns:r': XMLNS.r
29525 });
29526
29527 function safe1904(wb) {
29528 /* TODO: store date1904 somewhere else */
29529 try { return parsexmlbool(wb.Workbook.WBProps.date1904) ? "true" : "false"; } catch(e) { return "false"; }
29530 }
29531
29532 function write_wb_xml(wb, opts) {
29533 var o = [XML_HEADER];
29534 o[o.length] = WB_XML_ROOT;
29535 o[o.length] = (writextag('workbookPr', null, {date1904:safe1904(wb)}));
29536 o[o.length] = "<sheets>";
29537 for(var i = 0; i != wb.SheetNames.length; ++i)
29538 o[o.length] = (writextag('sheet',null,{name:wb.SheetNames[i].substr(0,31), sheetId:""+(i+1), "r:id":"rId"+(i+1)}));
29539 o[o.length] = "</sheets>";
29540 if(o.length>2){ o[o.length] = '</workbook>'; o[1]=o[1].replace("/>",">"); }
29541 return o.join("");
29542 }
29543 /* [MS-XLSB] 2.4.301 BrtBundleSh */
29544 function parse_BrtBundleSh(data, length) {
29545 var z = {};
29546 z.hsState = data.read_shift(4); //ST_SheetState
29547 z.iTabID = data.read_shift(4);
29548 z.strRelID = parse_RelID(data,length-8);
29549 z.name = parse_XLWideString(data);
29550 return z;
29551 }
29552 function write_BrtBundleSh(data, o) {
29553 if(!o) o = new_buf(127);
29554 o.write_shift(4, data.hsState);
29555 o.write_shift(4, data.iTabID);
29556 write_RelID(data.strRelID, o);
29557 write_XLWideString(data.name.substr(0,31), o);
29558 return o;
29559 }
29560
29561 /* [MS-XLSB] 2.4.807 BrtWbProp */
29562 function parse_BrtWbProp(data, length) {
29563 data.read_shift(4);
29564 var dwThemeVersion = data.read_shift(4);
29565 var strName = (length > 8) ? parse_XLWideString(data) : "";
29566 return [dwThemeVersion, strName];
29567 }
29568 function write_BrtWbProp(data, o) {
29569 if(!o) o = new_buf(8);
29570 o.write_shift(4, 0);
29571 o.write_shift(4, 0);
29572 return o;
29573 }
29574
29575 function parse_BrtFRTArchID$(data, length) {
29576 var o = {};
29577 data.read_shift(4);
29578 o.ArchID = data.read_shift(4);
29579 data.l += length - 8;
29580 return o;
29581 }
29582
29583 /* [MS-XLSB] 2.1.7.60 Workbook */
29584 function parse_wb_bin(data, opts) {
29585 var wb = { AppVersion:{}, WBProps:{}, WBView:[], Sheets:[], CalcPr:{}, xmlns: "" };
29586 var pass = false, z;
29587
29588 recordhopper(data, function hopper_wb(val, R) {
29589 switch(R.n) {
29590 case 'BrtBundleSh': wb.Sheets.push(val); break;
29591
29592 case 'BrtBeginBook': break;
29593 case 'BrtFileVersion': break;
29594 case 'BrtWbProp': break;
29595 case 'BrtACBegin': break;
29596 case 'BrtAbsPath15': break;
29597 case 'BrtACEnd': break;
29598 case 'BrtWbFactoid': break;
29599 /*case 'BrtBookProtectionIso': break;*/
29600 case 'BrtBookProtection': break;
29601 case 'BrtBeginBookViews': break;
29602 case 'BrtBookView': break;
29603 case 'BrtEndBookViews': break;
29604 case 'BrtBeginBundleShs': break;
29605 case 'BrtEndBundleShs': break;
29606 case 'BrtBeginFnGroup': break;
29607 case 'BrtEndFnGroup': break;
29608 case 'BrtBeginExternals': break;
29609 case 'BrtSupSelf': break;
29610 case 'BrtSupBookSrc': break;
29611 case 'BrtExternSheet': break;
29612 case 'BrtEndExternals': break;
29613 case 'BrtName': break;
29614 case 'BrtCalcProp': break;
29615 case 'BrtUserBookView': break;
29616 case 'BrtBeginPivotCacheIDs': break;
29617 case 'BrtBeginPivotCacheID': break;
29618 case 'BrtEndPivotCacheID': break;
29619 case 'BrtEndPivotCacheIDs': break;
29620 case 'BrtWebOpt': break;
29621 case 'BrtFileRecover': break;
29622 case 'BrtFileSharing': break;
29623 /*case 'BrtBeginWebPubItems': break;
29624 case 'BrtBeginWebPubItem': break;
29625 case 'BrtEndWebPubItem': break;
29626 case 'BrtEndWebPubItems': break;*/
29627
29628 /* Smart Tags */
29629 case 'BrtBeginSmartTagTypes': break;
29630 case 'BrtSmartTagType': break;
29631 case 'BrtEndSmartTagTypes': break;
29632
29633 case 'BrtFRTBegin': pass = true; break;
29634 case 'BrtFRTArchID$': break;
29635 case 'BrtWorkBookPr15': break;
29636 case 'BrtFRTEnd': pass = false; break;
29637 case 'BrtEndBook': break;
29638 default: if(!pass || opts.WTF) throw new Error("Unexpected record " + R.n);
29639 }
29640 });
29641
29642 parse_wb_defaults(wb);
29643
29644 return wb;
29645 }
29646
29647 /* [MS-XLSB] 2.1.7.60 Workbook */
29648 function write_BUNDLESHS(ba, wb, opts) {
29649 write_record(ba, "BrtBeginBundleShs");
29650 for(var idx = 0; idx != wb.SheetNames.length; ++idx) {
29651 var d = { hsState: 0, iTabID: idx+1, strRelID: 'rId' + (idx+1), name: wb.SheetNames[idx] };
29652 write_record(ba, "BrtBundleSh", write_BrtBundleSh(d));
29653 }
29654 write_record(ba, "BrtEndBundleShs");
29655 }
29656
29657 /* [MS-XLSB] 2.4.643 BrtFileVersion */
29658 function write_BrtFileVersion(data, o) {
29659 if(!o) o = new_buf(127);
29660 for(var i = 0; i != 4; ++i) o.write_shift(4, 0);
29661 write_XLWideString("SheetJS", o);
29662 write_XLWideString(XLSX.version, o);
29663 write_XLWideString(XLSX.version, o);
29664 write_XLWideString("7262", o);
29665 o.length = o.l;
29666 return o;
29667 }
29668
29669 /* [MS-XLSB] 2.1.7.60 Workbook */
29670 function write_BOOKVIEWS(ba, wb, opts) {
29671 write_record(ba, "BrtBeginBookViews");
29672 /* 1*(BrtBookView *FRT) */
29673 write_record(ba, "BrtEndBookViews");
29674 }
29675
29676 /* [MS-XLSB] 2.4.302 BrtCalcProp */
29677 function write_BrtCalcProp(data, o) {
29678 if(!o) o = new_buf(26);
29679 o.write_shift(4,0); /* force recalc */
29680 o.write_shift(4,1);
29681 o.write_shift(4,0);
29682 write_Xnum(0, o);
29683 o.write_shift(-4, 1023);
29684 o.write_shift(1, 0x33);
29685 o.write_shift(1, 0x00);
29686 return o;
29687 }
29688
29689 function write_BrtFileRecover(data, o) {
29690 if(!o) o = new_buf(1);
29691 o.write_shift(1,0);
29692 return o;
29693 }
29694
29695 /* [MS-XLSB] 2.1.7.60 Workbook */
29696 function write_wb_bin(wb, opts) {
29697 var ba = buf_array();
29698 write_record(ba, "BrtBeginBook");
29699 write_record(ba, "BrtFileVersion", write_BrtFileVersion());
29700 /* [[BrtFileSharingIso] BrtFileSharing] */
29701 write_record(ba, "BrtWbProp", write_BrtWbProp());
29702 /* [ACABSPATH] */
29703 /* [[BrtBookProtectionIso] BrtBookProtection] */
29704 write_BOOKVIEWS(ba, wb, opts);
29705 write_BUNDLESHS(ba, wb, opts);
29706 /* [FNGROUP] */
29707 /* [EXTERNALS] */
29708 /* *BrtName */
29709 write_record(ba, "BrtCalcProp", write_BrtCalcProp());
29710 /* [BrtOleSize] */
29711 /* *(BrtUserBookView *FRT) */
29712 /* [PIVOTCACHEIDS] */
29713 /* [BrtWbFactoid] */
29714 /* [SMARTTAGTYPES] */
29715 /* [BrtWebOpt] */
29716 write_record(ba, "BrtFileRecover", write_BrtFileRecover());
29717 /* [WEBPUBITEMS] */
29718 /* [CRERRS] */
29719 /* FRTWORKBOOK */
29720 write_record(ba, "BrtEndBook");
29721
29722 return ba.end();
29723 }
29724 function parse_wb(data, name, opts) {
29725 return (name.substr(-4)===".bin" ? parse_wb_bin : parse_wb_xml)(data, opts);
29726 }
29727
29728 function parse_ws(data, name, opts, rels) {
29729 return (name.substr(-4)===".bin" ? parse_ws_bin : parse_ws_xml)(data, opts, rels);
29730 }
29731
29732 function parse_sty(data, name, opts) {
29733 return (name.substr(-4)===".bin" ? parse_sty_bin : parse_sty_xml)(data, opts);
29734 }
29735
29736 function parse_theme(data, name, opts) {
29737 return parse_theme_xml(data, opts);
29738 }
29739
29740 function parse_sst(data, name, opts) {
29741 return (name.substr(-4)===".bin" ? parse_sst_bin : parse_sst_xml)(data, opts);
29742 }
29743
29744 function parse_cmnt(data, name, opts) {
29745 return (name.substr(-4)===".bin" ? parse_comments_bin : parse_comments_xml)(data, opts);
29746 }
29747
29748 function parse_cc(data, name, opts) {
29749 return (name.substr(-4)===".bin" ? parse_cc_bin : parse_cc_xml)(data, opts);
29750 }
29751
29752 function write_wb(wb, name, opts) {
29753 return (name.substr(-4)===".bin" ? write_wb_bin : write_wb_xml)(wb, opts);
29754 }
29755
29756 function write_ws(data, name, opts, wb) {
29757 return (name.substr(-4)===".bin" ? write_ws_bin : write_ws_xml)(data, opts, wb);
29758 }
29759
29760 function write_sty(data, name, opts) {
29761 return (name.substr(-4)===".bin" ? write_sty_bin : write_sty_xml)(data, opts);
29762 }
29763
29764 function write_sst(data, name, opts) {
29765 return (name.substr(-4)===".bin" ? write_sst_bin : write_sst_xml)(data, opts);
29766 }
29767 /*
29768 function write_cmnt(data, name, opts) {
29769 return (name.substr(-4)===".bin" ? write_comments_bin : write_comments_xml)(data, opts);
29770 }
29771
29772 function write_cc(data, name, opts) {
29773 return (name.substr(-4)===".bin" ? write_cc_bin : write_cc_xml)(data, opts);
29774 }
29775 */
29776 /* [MS-XLSB] 2.3 Record Enumeration */
29777 var RecordEnum = {
29778 0x0000: { n:"BrtRowHdr", f:parse_BrtRowHdr },
29779 0x0001: { n:"BrtCellBlank", f:parse_BrtCellBlank },
29780 0x0002: { n:"BrtCellRk", f:parse_BrtCellRk },
29781 0x0003: { n:"BrtCellError", f:parse_BrtCellError },
29782 0x0004: { n:"BrtCellBool", f:parse_BrtCellBool },
29783 0x0005: { n:"BrtCellReal", f:parse_BrtCellReal },
29784 0x0006: { n:"BrtCellSt", f:parse_BrtCellSt },
29785 0x0007: { n:"BrtCellIsst", f:parse_BrtCellIsst },
29786 0x0008: { n:"BrtFmlaString", f:parse_BrtFmlaString },
29787 0x0009: { n:"BrtFmlaNum", f:parse_BrtFmlaNum },
29788 0x000A: { n:"BrtFmlaBool", f:parse_BrtFmlaBool },
29789 0x000B: { n:"BrtFmlaError", f:parse_BrtFmlaError },
29790 0x0010: { n:"BrtFRTArchID$", f:parse_BrtFRTArchID$ },
29791 0x0013: { n:"BrtSSTItem", f:parse_RichStr },
29792 0x0014: { n:"BrtPCDIMissing", f:parsenoop },
29793 0x0015: { n:"BrtPCDINumber", f:parsenoop },
29794 0x0016: { n:"BrtPCDIBoolean", f:parsenoop },
29795 0x0017: { n:"BrtPCDIError", f:parsenoop },
29796 0x0018: { n:"BrtPCDIString", f:parsenoop },
29797 0x0019: { n:"BrtPCDIDatetime", f:parsenoop },
29798 0x001A: { n:"BrtPCDIIndex", f:parsenoop },
29799 0x001B: { n:"BrtPCDIAMissing", f:parsenoop },
29800 0x001C: { n:"BrtPCDIANumber", f:parsenoop },
29801 0x001D: { n:"BrtPCDIABoolean", f:parsenoop },
29802 0x001E: { n:"BrtPCDIAError", f:parsenoop },
29803 0x001F: { n:"BrtPCDIAString", f:parsenoop },
29804 0x0020: { n:"BrtPCDIADatetime", f:parsenoop },
29805 0x0021: { n:"BrtPCRRecord", f:parsenoop },
29806 0x0022: { n:"BrtPCRRecordDt", f:parsenoop },
29807 0x0023: { n:"BrtFRTBegin", f:parsenoop },
29808 0x0024: { n:"BrtFRTEnd", f:parsenoop },
29809 0x0025: { n:"BrtACBegin", f:parsenoop },
29810 0x0026: { n:"BrtACEnd", f:parsenoop },
29811 0x0027: { n:"BrtName", f:parsenoop },
29812 0x0028: { n:"BrtIndexRowBlock", f:parsenoop },
29813 0x002A: { n:"BrtIndexBlock", f:parsenoop },
29814 0x002B: { n:"BrtFont", f:parse_BrtFont },
29815 0x002C: { n:"BrtFmt", f:parse_BrtFmt },
29816 0x002D: { n:"BrtFill", f:parsenoop },
29817 0x002E: { n:"BrtBorder", f:parsenoop },
29818 0x002F: { n:"BrtXF", f:parse_BrtXF },
29819 0x0030: { n:"BrtStyle", f:parsenoop },
29820 0x0031: { n:"BrtCellMeta", f:parsenoop },
29821 0x0032: { n:"BrtValueMeta", f:parsenoop },
29822 0x0033: { n:"BrtMdb", f:parsenoop },
29823 0x0034: { n:"BrtBeginFmd", f:parsenoop },
29824 0x0035: { n:"BrtEndFmd", f:parsenoop },
29825 0x0036: { n:"BrtBeginMdx", f:parsenoop },
29826 0x0037: { n:"BrtEndMdx", f:parsenoop },
29827 0x0038: { n:"BrtBeginMdxTuple", f:parsenoop },
29828 0x0039: { n:"BrtEndMdxTuple", f:parsenoop },
29829 0x003A: { n:"BrtMdxMbrIstr", f:parsenoop },
29830 0x003B: { n:"BrtStr", f:parsenoop },
29831 0x003C: { n:"BrtColInfo", f:parsenoop },
29832 0x003E: { n:"BrtCellRString", f:parsenoop },
29833 0x003F: { n:"BrtCalcChainItem$", f:parse_BrtCalcChainItem$ },
29834 0x0040: { n:"BrtDVal", f:parsenoop },
29835 0x0041: { n:"BrtSxvcellNum", f:parsenoop },
29836 0x0042: { n:"BrtSxvcellStr", f:parsenoop },
29837 0x0043: { n:"BrtSxvcellBool", f:parsenoop },
29838 0x0044: { n:"BrtSxvcellErr", f:parsenoop },
29839 0x0045: { n:"BrtSxvcellDate", f:parsenoop },
29840 0x0046: { n:"BrtSxvcellNil", f:parsenoop },
29841 0x0080: { n:"BrtFileVersion", f:parsenoop },
29842 0x0081: { n:"BrtBeginSheet", f:parsenoop },
29843 0x0082: { n:"BrtEndSheet", f:parsenoop },
29844 0x0083: { n:"BrtBeginBook", f:parsenoop, p:0 },
29845 0x0084: { n:"BrtEndBook", f:parsenoop },
29846 0x0085: { n:"BrtBeginWsViews", f:parsenoop },
29847 0x0086: { n:"BrtEndWsViews", f:parsenoop },
29848 0x0087: { n:"BrtBeginBookViews", f:parsenoop },
29849 0x0088: { n:"BrtEndBookViews", f:parsenoop },
29850 0x0089: { n:"BrtBeginWsView", f:parsenoop },
29851 0x008A: { n:"BrtEndWsView", f:parsenoop },
29852 0x008B: { n:"BrtBeginCsViews", f:parsenoop },
29853 0x008C: { n:"BrtEndCsViews", f:parsenoop },
29854 0x008D: { n:"BrtBeginCsView", f:parsenoop },
29855 0x008E: { n:"BrtEndCsView", f:parsenoop },
29856 0x008F: { n:"BrtBeginBundleShs", f:parsenoop },
29857 0x0090: { n:"BrtEndBundleShs", f:parsenoop },
29858 0x0091: { n:"BrtBeginSheetData", f:parsenoop },
29859 0x0092: { n:"BrtEndSheetData", f:parsenoop },
29860 0x0093: { n:"BrtWsProp", f:parse_BrtWsProp },
29861 0x0094: { n:"BrtWsDim", f:parse_BrtWsDim, p:16 },
29862 0x0097: { n:"BrtPane", f:parsenoop },
29863 0x0098: { n:"BrtSel", f:parsenoop },
29864 0x0099: { n:"BrtWbProp", f:parse_BrtWbProp },
29865 0x009A: { n:"BrtWbFactoid", f:parsenoop },
29866 0x009B: { n:"BrtFileRecover", f:parsenoop },
29867 0x009C: { n:"BrtBundleSh", f:parse_BrtBundleSh },
29868 0x009D: { n:"BrtCalcProp", f:parsenoop },
29869 0x009E: { n:"BrtBookView", f:parsenoop },
29870 0x009F: { n:"BrtBeginSst", f:parse_BrtBeginSst },
29871 0x00A0: { n:"BrtEndSst", f:parsenoop },
29872 0x00A1: { n:"BrtBeginAFilter", f:parsenoop },
29873 0x00A2: { n:"BrtEndAFilter", f:parsenoop },
29874 0x00A3: { n:"BrtBeginFilterColumn", f:parsenoop },
29875 0x00A4: { n:"BrtEndFilterColumn", f:parsenoop },
29876 0x00A5: { n:"BrtBeginFilters", f:parsenoop },
29877 0x00A6: { n:"BrtEndFilters", f:parsenoop },
29878 0x00A7: { n:"BrtFilter", f:parsenoop },
29879 0x00A8: { n:"BrtColorFilter", f:parsenoop },
29880 0x00A9: { n:"BrtIconFilter", f:parsenoop },
29881 0x00AA: { n:"BrtTop10Filter", f:parsenoop },
29882 0x00AB: { n:"BrtDynamicFilter", f:parsenoop },
29883 0x00AC: { n:"BrtBeginCustomFilters", f:parsenoop },
29884 0x00AD: { n:"BrtEndCustomFilters", f:parsenoop },
29885 0x00AE: { n:"BrtCustomFilter", f:parsenoop },
29886 0x00AF: { n:"BrtAFilterDateGroupItem", f:parsenoop },
29887 0x00B0: { n:"BrtMergeCell", f:parse_BrtMergeCell },
29888 0x00B1: { n:"BrtBeginMergeCells", f:parsenoop },
29889 0x00B2: { n:"BrtEndMergeCells", f:parsenoop },
29890 0x00B3: { n:"BrtBeginPivotCacheDef", f:parsenoop },
29891 0x00B4: { n:"BrtEndPivotCacheDef", f:parsenoop },
29892 0x00B5: { n:"BrtBeginPCDFields", f:parsenoop },
29893 0x00B6: { n:"BrtEndPCDFields", f:parsenoop },
29894 0x00B7: { n:"BrtBeginPCDField", f:parsenoop },
29895 0x00B8: { n:"BrtEndPCDField", f:parsenoop },
29896 0x00B9: { n:"BrtBeginPCDSource", f:parsenoop },
29897 0x00BA: { n:"BrtEndPCDSource", f:parsenoop },
29898 0x00BB: { n:"BrtBeginPCDSRange", f:parsenoop },
29899 0x00BC: { n:"BrtEndPCDSRange", f:parsenoop },
29900 0x00BD: { n:"BrtBeginPCDFAtbl", f:parsenoop },
29901 0x00BE: { n:"BrtEndPCDFAtbl", f:parsenoop },
29902 0x00BF: { n:"BrtBeginPCDIRun", f:parsenoop },
29903 0x00C0: { n:"BrtEndPCDIRun", f:parsenoop },
29904 0x00C1: { n:"BrtBeginPivotCacheRecords", f:parsenoop },
29905 0x00C2: { n:"BrtEndPivotCacheRecords", f:parsenoop },
29906 0x00C3: { n:"BrtBeginPCDHierarchies", f:parsenoop },
29907 0x00C4: { n:"BrtEndPCDHierarchies", f:parsenoop },
29908 0x00C5: { n:"BrtBeginPCDHierarchy", f:parsenoop },
29909 0x00C6: { n:"BrtEndPCDHierarchy", f:parsenoop },
29910 0x00C7: { n:"BrtBeginPCDHFieldsUsage", f:parsenoop },
29911 0x00C8: { n:"BrtEndPCDHFieldsUsage", f:parsenoop },
29912 0x00C9: { n:"BrtBeginExtConnection", f:parsenoop },
29913 0x00CA: { n:"BrtEndExtConnection", f:parsenoop },
29914 0x00CB: { n:"BrtBeginECDbProps", f:parsenoop },
29915 0x00CC: { n:"BrtEndECDbProps", f:parsenoop },
29916 0x00CD: { n:"BrtBeginECOlapProps", f:parsenoop },
29917 0x00CE: { n:"BrtEndECOlapProps", f:parsenoop },
29918 0x00CF: { n:"BrtBeginPCDSConsol", f:parsenoop },
29919 0x00D0: { n:"BrtEndPCDSConsol", f:parsenoop },
29920 0x00D1: { n:"BrtBeginPCDSCPages", f:parsenoop },
29921 0x00D2: { n:"BrtEndPCDSCPages", f:parsenoop },
29922 0x00D3: { n:"BrtBeginPCDSCPage", f:parsenoop },
29923 0x00D4: { n:"BrtEndPCDSCPage", f:parsenoop },
29924 0x00D5: { n:"BrtBeginPCDSCPItem", f:parsenoop },
29925 0x00D6: { n:"BrtEndPCDSCPItem", f:parsenoop },
29926 0x00D7: { n:"BrtBeginPCDSCSets", f:parsenoop },
29927 0x00D8: { n:"BrtEndPCDSCSets", f:parsenoop },
29928 0x00D9: { n:"BrtBeginPCDSCSet", f:parsenoop },
29929 0x00DA: { n:"BrtEndPCDSCSet", f:parsenoop },
29930 0x00DB: { n:"BrtBeginPCDFGroup", f:parsenoop },
29931 0x00DC: { n:"BrtEndPCDFGroup", f:parsenoop },
29932 0x00DD: { n:"BrtBeginPCDFGItems", f:parsenoop },
29933 0x00DE: { n:"BrtEndPCDFGItems", f:parsenoop },
29934 0x00DF: { n:"BrtBeginPCDFGRange", f:parsenoop },
29935 0x00E0: { n:"BrtEndPCDFGRange", f:parsenoop },
29936 0x00E1: { n:"BrtBeginPCDFGDiscrete", f:parsenoop },
29937 0x00E2: { n:"BrtEndPCDFGDiscrete", f:parsenoop },
29938 0x00E3: { n:"BrtBeginPCDSDTupleCache", f:parsenoop },
29939 0x00E4: { n:"BrtEndPCDSDTupleCache", f:parsenoop },
29940 0x00E5: { n:"BrtBeginPCDSDTCEntries", f:parsenoop },
29941 0x00E6: { n:"BrtEndPCDSDTCEntries", f:parsenoop },
29942 0x00E7: { n:"BrtBeginPCDSDTCEMembers", f:parsenoop },
29943 0x00E8: { n:"BrtEndPCDSDTCEMembers", f:parsenoop },
29944 0x00E9: { n:"BrtBeginPCDSDTCEMember", f:parsenoop },
29945 0x00EA: { n:"BrtEndPCDSDTCEMember", f:parsenoop },
29946 0x00EB: { n:"BrtBeginPCDSDTCQueries", f:parsenoop },
29947 0x00EC: { n:"BrtEndPCDSDTCQueries", f:parsenoop },
29948 0x00ED: { n:"BrtBeginPCDSDTCQuery", f:parsenoop },
29949 0x00EE: { n:"BrtEndPCDSDTCQuery", f:parsenoop },
29950 0x00EF: { n:"BrtBeginPCDSDTCSets", f:parsenoop },
29951 0x00F0: { n:"BrtEndPCDSDTCSets", f:parsenoop },
29952 0x00F1: { n:"BrtBeginPCDSDTCSet", f:parsenoop },
29953 0x00F2: { n:"BrtEndPCDSDTCSet", f:parsenoop },
29954 0x00F3: { n:"BrtBeginPCDCalcItems", f:parsenoop },
29955 0x00F4: { n:"BrtEndPCDCalcItems", f:parsenoop },
29956 0x00F5: { n:"BrtBeginPCDCalcItem", f:parsenoop },
29957 0x00F6: { n:"BrtEndPCDCalcItem", f:parsenoop },
29958 0x00F7: { n:"BrtBeginPRule", f:parsenoop },
29959 0x00F8: { n:"BrtEndPRule", f:parsenoop },
29960 0x00F9: { n:"BrtBeginPRFilters", f:parsenoop },
29961 0x00FA: { n:"BrtEndPRFilters", f:parsenoop },
29962 0x00FB: { n:"BrtBeginPRFilter", f:parsenoop },
29963 0x00FC: { n:"BrtEndPRFilter", f:parsenoop },
29964 0x00FD: { n:"BrtBeginPNames", f:parsenoop },
29965 0x00FE: { n:"BrtEndPNames", f:parsenoop },
29966 0x00FF: { n:"BrtBeginPName", f:parsenoop },
29967 0x0100: { n:"BrtEndPName", f:parsenoop },
29968 0x0101: { n:"BrtBeginPNPairs", f:parsenoop },
29969 0x0102: { n:"BrtEndPNPairs", f:parsenoop },
29970 0x0103: { n:"BrtBeginPNPair", f:parsenoop },
29971 0x0104: { n:"BrtEndPNPair", f:parsenoop },
29972 0x0105: { n:"BrtBeginECWebProps", f:parsenoop },
29973 0x0106: { n:"BrtEndECWebProps", f:parsenoop },
29974 0x0107: { n:"BrtBeginEcWpTables", f:parsenoop },
29975 0x0108: { n:"BrtEndECWPTables", f:parsenoop },
29976 0x0109: { n:"BrtBeginECParams", f:parsenoop },
29977 0x010A: { n:"BrtEndECParams", f:parsenoop },
29978 0x010B: { n:"BrtBeginECParam", f:parsenoop },
29979 0x010C: { n:"BrtEndECParam", f:parsenoop },
29980 0x010D: { n:"BrtBeginPCDKPIs", f:parsenoop },
29981 0x010E: { n:"BrtEndPCDKPIs", f:parsenoop },
29982 0x010F: { n:"BrtBeginPCDKPI", f:parsenoop },
29983 0x0110: { n:"BrtEndPCDKPI", f:parsenoop },
29984 0x0111: { n:"BrtBeginDims", f:parsenoop },
29985 0x0112: { n:"BrtEndDims", f:parsenoop },
29986 0x0113: { n:"BrtBeginDim", f:parsenoop },
29987 0x0114: { n:"BrtEndDim", f:parsenoop },
29988 0x0115: { n:"BrtIndexPartEnd", f:parsenoop },
29989 0x0116: { n:"BrtBeginStyleSheet", f:parsenoop },
29990 0x0117: { n:"BrtEndStyleSheet", f:parsenoop },
29991 0x0118: { n:"BrtBeginSXView", f:parsenoop },
29992 0x0119: { n:"BrtEndSXVI", f:parsenoop },
29993 0x011A: { n:"BrtBeginSXVI", f:parsenoop },
29994 0x011B: { n:"BrtBeginSXVIs", f:parsenoop },
29995 0x011C: { n:"BrtEndSXVIs", f:parsenoop },
29996 0x011D: { n:"BrtBeginSXVD", f:parsenoop },
29997 0x011E: { n:"BrtEndSXVD", f:parsenoop },
29998 0x011F: { n:"BrtBeginSXVDs", f:parsenoop },
29999 0x0120: { n:"BrtEndSXVDs", f:parsenoop },
30000 0x0121: { n:"BrtBeginSXPI", f:parsenoop },
30001 0x0122: { n:"BrtEndSXPI", f:parsenoop },
30002 0x0123: { n:"BrtBeginSXPIs", f:parsenoop },
30003 0x0124: { n:"BrtEndSXPIs", f:parsenoop },
30004 0x0125: { n:"BrtBeginSXDI", f:parsenoop },
30005 0x0126: { n:"BrtEndSXDI", f:parsenoop },
30006 0x0127: { n:"BrtBeginSXDIs", f:parsenoop },
30007 0x0128: { n:"BrtEndSXDIs", f:parsenoop },
30008 0x0129: { n:"BrtBeginSXLI", f:parsenoop },
30009 0x012A: { n:"BrtEndSXLI", f:parsenoop },
30010 0x012B: { n:"BrtBeginSXLIRws", f:parsenoop },
30011 0x012C: { n:"BrtEndSXLIRws", f:parsenoop },
30012 0x012D: { n:"BrtBeginSXLICols", f:parsenoop },
30013 0x012E: { n:"BrtEndSXLICols", f:parsenoop },
30014 0x012F: { n:"BrtBeginSXFormat", f:parsenoop },
30015 0x0130: { n:"BrtEndSXFormat", f:parsenoop },
30016 0x0131: { n:"BrtBeginSXFormats", f:parsenoop },
30017 0x0132: { n:"BrtEndSxFormats", f:parsenoop },
30018 0x0133: { n:"BrtBeginSxSelect", f:parsenoop },
30019 0x0134: { n:"BrtEndSxSelect", f:parsenoop },
30020 0x0135: { n:"BrtBeginISXVDRws", f:parsenoop },
30021 0x0136: { n:"BrtEndISXVDRws", f:parsenoop },
30022 0x0137: { n:"BrtBeginISXVDCols", f:parsenoop },
30023 0x0138: { n:"BrtEndISXVDCols", f:parsenoop },
30024 0x0139: { n:"BrtEndSXLocation", f:parsenoop },
30025 0x013A: { n:"BrtBeginSXLocation", f:parsenoop },
30026 0x013B: { n:"BrtEndSXView", f:parsenoop },
30027 0x013C: { n:"BrtBeginSXTHs", f:parsenoop },
30028 0x013D: { n:"BrtEndSXTHs", f:parsenoop },
30029 0x013E: { n:"BrtBeginSXTH", f:parsenoop },
30030 0x013F: { n:"BrtEndSXTH", f:parsenoop },
30031 0x0140: { n:"BrtBeginISXTHRws", f:parsenoop },
30032 0x0141: { n:"BrtEndISXTHRws", f:parsenoop },
30033 0x0142: { n:"BrtBeginISXTHCols", f:parsenoop },
30034 0x0143: { n:"BrtEndISXTHCols", f:parsenoop },
30035 0x0144: { n:"BrtBeginSXTDMPS", f:parsenoop },
30036 0x0145: { n:"BrtEndSXTDMPs", f:parsenoop },
30037 0x0146: { n:"BrtBeginSXTDMP", f:parsenoop },
30038 0x0147: { n:"BrtEndSXTDMP", f:parsenoop },
30039 0x0148: { n:"BrtBeginSXTHItems", f:parsenoop },
30040 0x0149: { n:"BrtEndSXTHItems", f:parsenoop },
30041 0x014A: { n:"BrtBeginSXTHItem", f:parsenoop },
30042 0x014B: { n:"BrtEndSXTHItem", f:parsenoop },
30043 0x014C: { n:"BrtBeginMetadata", f:parsenoop },
30044 0x014D: { n:"BrtEndMetadata", f:parsenoop },
30045 0x014E: { n:"BrtBeginEsmdtinfo", f:parsenoop },
30046 0x014F: { n:"BrtMdtinfo", f:parsenoop },
30047 0x0150: { n:"BrtEndEsmdtinfo", f:parsenoop },
30048 0x0151: { n:"BrtBeginEsmdb", f:parsenoop },
30049 0x0152: { n:"BrtEndEsmdb", f:parsenoop },
30050 0x0153: { n:"BrtBeginEsfmd", f:parsenoop },
30051 0x0154: { n:"BrtEndEsfmd", f:parsenoop },
30052 0x0155: { n:"BrtBeginSingleCells", f:parsenoop },
30053 0x0156: { n:"BrtEndSingleCells", f:parsenoop },
30054 0x0157: { n:"BrtBeginList", f:parsenoop },
30055 0x0158: { n:"BrtEndList", f:parsenoop },
30056 0x0159: { n:"BrtBeginListCols", f:parsenoop },
30057 0x015A: { n:"BrtEndListCols", f:parsenoop },
30058 0x015B: { n:"BrtBeginListCol", f:parsenoop },
30059 0x015C: { n:"BrtEndListCol", f:parsenoop },
30060 0x015D: { n:"BrtBeginListXmlCPr", f:parsenoop },
30061 0x015E: { n:"BrtEndListXmlCPr", f:parsenoop },
30062 0x015F: { n:"BrtListCCFmla", f:parsenoop },
30063 0x0160: { n:"BrtListTrFmla", f:parsenoop },
30064 0x0161: { n:"BrtBeginExternals", f:parsenoop },
30065 0x0162: { n:"BrtEndExternals", f:parsenoop },
30066 0x0163: { n:"BrtSupBookSrc", f:parsenoop },
30067 0x0165: { n:"BrtSupSelf", f:parsenoop },
30068 0x0166: { n:"BrtSupSame", f:parsenoop },
30069 0x0167: { n:"BrtSupTabs", f:parsenoop },
30070 0x0168: { n:"BrtBeginSupBook", f:parsenoop },
30071 0x0169: { n:"BrtPlaceholderName", f:parsenoop },
30072 0x016A: { n:"BrtExternSheet", f:parsenoop },
30073 0x016B: { n:"BrtExternTableStart", f:parsenoop },
30074 0x016C: { n:"BrtExternTableEnd", f:parsenoop },
30075 0x016E: { n:"BrtExternRowHdr", f:parsenoop },
30076 0x016F: { n:"BrtExternCellBlank", f:parsenoop },
30077 0x0170: { n:"BrtExternCellReal", f:parsenoop },
30078 0x0171: { n:"BrtExternCellBool", f:parsenoop },
30079 0x0172: { n:"BrtExternCellError", f:parsenoop },
30080 0x0173: { n:"BrtExternCellString", f:parsenoop },
30081 0x0174: { n:"BrtBeginEsmdx", f:parsenoop },
30082 0x0175: { n:"BrtEndEsmdx", f:parsenoop },
30083 0x0176: { n:"BrtBeginMdxSet", f:parsenoop },
30084 0x0177: { n:"BrtEndMdxSet", f:parsenoop },
30085 0x0178: { n:"BrtBeginMdxMbrProp", f:parsenoop },
30086 0x0179: { n:"BrtEndMdxMbrProp", f:parsenoop },
30087 0x017A: { n:"BrtBeginMdxKPI", f:parsenoop },
30088 0x017B: { n:"BrtEndMdxKPI", f:parsenoop },
30089 0x017C: { n:"BrtBeginEsstr", f:parsenoop },
30090 0x017D: { n:"BrtEndEsstr", f:parsenoop },
30091 0x017E: { n:"BrtBeginPRFItem", f:parsenoop },
30092 0x017F: { n:"BrtEndPRFItem", f:parsenoop },
30093 0x0180: { n:"BrtBeginPivotCacheIDs", f:parsenoop },
30094 0x0181: { n:"BrtEndPivotCacheIDs", f:parsenoop },
30095 0x0182: { n:"BrtBeginPivotCacheID", f:parsenoop },
30096 0x0183: { n:"BrtEndPivotCacheID", f:parsenoop },
30097 0x0184: { n:"BrtBeginISXVIs", f:parsenoop },
30098 0x0185: { n:"BrtEndISXVIs", f:parsenoop },
30099 0x0186: { n:"BrtBeginColInfos", f:parsenoop },
30100 0x0187: { n:"BrtEndColInfos", f:parsenoop },
30101 0x0188: { n:"BrtBeginRwBrk", f:parsenoop },
30102 0x0189: { n:"BrtEndRwBrk", f:parsenoop },
30103 0x018A: { n:"BrtBeginColBrk", f:parsenoop },
30104 0x018B: { n:"BrtEndColBrk", f:parsenoop },
30105 0x018C: { n:"BrtBrk", f:parsenoop },
30106 0x018D: { n:"BrtUserBookView", f:parsenoop },
30107 0x018E: { n:"BrtInfo", f:parsenoop },
30108 0x018F: { n:"BrtCUsr", f:parsenoop },
30109 0x0190: { n:"BrtUsr", f:parsenoop },
30110 0x0191: { n:"BrtBeginUsers", f:parsenoop },
30111 0x0193: { n:"BrtEOF", f:parsenoop },
30112 0x0194: { n:"BrtUCR", f:parsenoop },
30113 0x0195: { n:"BrtRRInsDel", f:parsenoop },
30114 0x0196: { n:"BrtRREndInsDel", f:parsenoop },
30115 0x0197: { n:"BrtRRMove", f:parsenoop },
30116 0x0198: { n:"BrtRREndMove", f:parsenoop },
30117 0x0199: { n:"BrtRRChgCell", f:parsenoop },
30118 0x019A: { n:"BrtRREndChgCell", f:parsenoop },
30119 0x019B: { n:"BrtRRHeader", f:parsenoop },
30120 0x019C: { n:"BrtRRUserView", f:parsenoop },
30121 0x019D: { n:"BrtRRRenSheet", f:parsenoop },
30122 0x019E: { n:"BrtRRInsertSh", f:parsenoop },
30123 0x019F: { n:"BrtRRDefName", f:parsenoop },
30124 0x01A0: { n:"BrtRRNote", f:parsenoop },
30125 0x01A1: { n:"BrtRRConflict", f:parsenoop },
30126 0x01A2: { n:"BrtRRTQSIF", f:parsenoop },
30127 0x01A3: { n:"BrtRRFormat", f:parsenoop },
30128 0x01A4: { n:"BrtRREndFormat", f:parsenoop },
30129 0x01A5: { n:"BrtRRAutoFmt", f:parsenoop },
30130 0x01A6: { n:"BrtBeginUserShViews", f:parsenoop },
30131 0x01A7: { n:"BrtBeginUserShView", f:parsenoop },
30132 0x01A8: { n:"BrtEndUserShView", f:parsenoop },
30133 0x01A9: { n:"BrtEndUserShViews", f:parsenoop },
30134 0x01AA: { n:"BrtArrFmla", f:parsenoop },
30135 0x01AB: { n:"BrtShrFmla", f:parsenoop },
30136 0x01AC: { n:"BrtTable", f:parsenoop },
30137 0x01AD: { n:"BrtBeginExtConnections", f:parsenoop },
30138 0x01AE: { n:"BrtEndExtConnections", f:parsenoop },
30139 0x01AF: { n:"BrtBeginPCDCalcMems", f:parsenoop },
30140 0x01B0: { n:"BrtEndPCDCalcMems", f:parsenoop },
30141 0x01B1: { n:"BrtBeginPCDCalcMem", f:parsenoop },
30142 0x01B2: { n:"BrtEndPCDCalcMem", f:parsenoop },
30143 0x01B3: { n:"BrtBeginPCDHGLevels", f:parsenoop },
30144 0x01B4: { n:"BrtEndPCDHGLevels", f:parsenoop },
30145 0x01B5: { n:"BrtBeginPCDHGLevel", f:parsenoop },
30146 0x01B6: { n:"BrtEndPCDHGLevel", f:parsenoop },
30147 0x01B7: { n:"BrtBeginPCDHGLGroups", f:parsenoop },
30148 0x01B8: { n:"BrtEndPCDHGLGroups", f:parsenoop },
30149 0x01B9: { n:"BrtBeginPCDHGLGroup", f:parsenoop },
30150 0x01BA: { n:"BrtEndPCDHGLGroup", f:parsenoop },
30151 0x01BB: { n:"BrtBeginPCDHGLGMembers", f:parsenoop },
30152 0x01BC: { n:"BrtEndPCDHGLGMembers", f:parsenoop },
30153 0x01BD: { n:"BrtBeginPCDHGLGMember", f:parsenoop },
30154 0x01BE: { n:"BrtEndPCDHGLGMember", f:parsenoop },
30155 0x01BF: { n:"BrtBeginQSI", f:parsenoop },
30156 0x01C0: { n:"BrtEndQSI", f:parsenoop },
30157 0x01C1: { n:"BrtBeginQSIR", f:parsenoop },
30158 0x01C2: { n:"BrtEndQSIR", f:parsenoop },
30159 0x01C3: { n:"BrtBeginDeletedNames", f:parsenoop },
30160 0x01C4: { n:"BrtEndDeletedNames", f:parsenoop },
30161 0x01C5: { n:"BrtBeginDeletedName", f:parsenoop },
30162 0x01C6: { n:"BrtEndDeletedName", f:parsenoop },
30163 0x01C7: { n:"BrtBeginQSIFs", f:parsenoop },
30164 0x01C8: { n:"BrtEndQSIFs", f:parsenoop },
30165 0x01C9: { n:"BrtBeginQSIF", f:parsenoop },
30166 0x01CA: { n:"BrtEndQSIF", f:parsenoop },
30167 0x01CB: { n:"BrtBeginAutoSortScope", f:parsenoop },
30168 0x01CC: { n:"BrtEndAutoSortScope", f:parsenoop },
30169 0x01CD: { n:"BrtBeginConditionalFormatting", f:parsenoop },
30170 0x01CE: { n:"BrtEndConditionalFormatting", f:parsenoop },
30171 0x01CF: { n:"BrtBeginCFRule", f:parsenoop },
30172 0x01D0: { n:"BrtEndCFRule", f:parsenoop },
30173 0x01D1: { n:"BrtBeginIconSet", f:parsenoop },
30174 0x01D2: { n:"BrtEndIconSet", f:parsenoop },
30175 0x01D3: { n:"BrtBeginDatabar", f:parsenoop },
30176 0x01D4: { n:"BrtEndDatabar", f:parsenoop },
30177 0x01D5: { n:"BrtBeginColorScale", f:parsenoop },
30178 0x01D6: { n:"BrtEndColorScale", f:parsenoop },
30179 0x01D7: { n:"BrtCFVO", f:parsenoop },
30180 0x01D8: { n:"BrtExternValueMeta", f:parsenoop },
30181 0x01D9: { n:"BrtBeginColorPalette", f:parsenoop },
30182 0x01DA: { n:"BrtEndColorPalette", f:parsenoop },
30183 0x01DB: { n:"BrtIndexedColor", f:parsenoop },
30184 0x01DC: { n:"BrtMargins", f:parsenoop },
30185 0x01DD: { n:"BrtPrintOptions", f:parsenoop },
30186 0x01DE: { n:"BrtPageSetup", f:parsenoop },
30187 0x01DF: { n:"BrtBeginHeaderFooter", f:parsenoop },
30188 0x01E0: { n:"BrtEndHeaderFooter", f:parsenoop },
30189 0x01E1: { n:"BrtBeginSXCrtFormat", f:parsenoop },
30190 0x01E2: { n:"BrtEndSXCrtFormat", f:parsenoop },
30191 0x01E3: { n:"BrtBeginSXCrtFormats", f:parsenoop },
30192 0x01E4: { n:"BrtEndSXCrtFormats", f:parsenoop },
30193 0x01E5: { n:"BrtWsFmtInfo", f:parsenoop },
30194 0x01E6: { n:"BrtBeginMgs", f:parsenoop },
30195 0x01E7: { n:"BrtEndMGs", f:parsenoop },
30196 0x01E8: { n:"BrtBeginMGMaps", f:parsenoop },
30197 0x01E9: { n:"BrtEndMGMaps", f:parsenoop },
30198 0x01EA: { n:"BrtBeginMG", f:parsenoop },
30199 0x01EB: { n:"BrtEndMG", f:parsenoop },
30200 0x01EC: { n:"BrtBeginMap", f:parsenoop },
30201 0x01ED: { n:"BrtEndMap", f:parsenoop },
30202 0x01EE: { n:"BrtHLink", f:parse_BrtHLink },
30203 0x01EF: { n:"BrtBeginDCon", f:parsenoop },
30204 0x01F0: { n:"BrtEndDCon", f:parsenoop },
30205 0x01F1: { n:"BrtBeginDRefs", f:parsenoop },
30206 0x01F2: { n:"BrtEndDRefs", f:parsenoop },
30207 0x01F3: { n:"BrtDRef", f:parsenoop },
30208 0x01F4: { n:"BrtBeginScenMan", f:parsenoop },
30209 0x01F5: { n:"BrtEndScenMan", f:parsenoop },
30210 0x01F6: { n:"BrtBeginSct", f:parsenoop },
30211 0x01F7: { n:"BrtEndSct", f:parsenoop },
30212 0x01F8: { n:"BrtSlc", f:parsenoop },
30213 0x01F9: { n:"BrtBeginDXFs", f:parsenoop },
30214 0x01FA: { n:"BrtEndDXFs", f:parsenoop },
30215 0x01FB: { n:"BrtDXF", f:parsenoop },
30216 0x01FC: { n:"BrtBeginTableStyles", f:parsenoop },
30217 0x01FD: { n:"BrtEndTableStyles", f:parsenoop },
30218 0x01FE: { n:"BrtBeginTableStyle", f:parsenoop },
30219 0x01FF: { n:"BrtEndTableStyle", f:parsenoop },
30220 0x0200: { n:"BrtTableStyleElement", f:parsenoop },
30221 0x0201: { n:"BrtTableStyleClient", f:parsenoop },
30222 0x0202: { n:"BrtBeginVolDeps", f:parsenoop },
30223 0x0203: { n:"BrtEndVolDeps", f:parsenoop },
30224 0x0204: { n:"BrtBeginVolType", f:parsenoop },
30225 0x0205: { n:"BrtEndVolType", f:parsenoop },
30226 0x0206: { n:"BrtBeginVolMain", f:parsenoop },
30227 0x0207: { n:"BrtEndVolMain", f:parsenoop },
30228 0x0208: { n:"BrtBeginVolTopic", f:parsenoop },
30229 0x0209: { n:"BrtEndVolTopic", f:parsenoop },
30230 0x020A: { n:"BrtVolSubtopic", f:parsenoop },
30231 0x020B: { n:"BrtVolRef", f:parsenoop },
30232 0x020C: { n:"BrtVolNum", f:parsenoop },
30233 0x020D: { n:"BrtVolErr", f:parsenoop },
30234 0x020E: { n:"BrtVolStr", f:parsenoop },
30235 0x020F: { n:"BrtVolBool", f:parsenoop },
30236 0x0210: { n:"BrtBeginCalcChain$", f:parsenoop },
30237 0x0211: { n:"BrtEndCalcChain$", f:parsenoop },
30238 0x0212: { n:"BrtBeginSortState", f:parsenoop },
30239 0x0213: { n:"BrtEndSortState", f:parsenoop },
30240 0x0214: { n:"BrtBeginSortCond", f:parsenoop },
30241 0x0215: { n:"BrtEndSortCond", f:parsenoop },
30242 0x0216: { n:"BrtBookProtection", f:parsenoop },
30243 0x0217: { n:"BrtSheetProtection", f:parsenoop },
30244 0x0218: { n:"BrtRangeProtection", f:parsenoop },
30245 0x0219: { n:"BrtPhoneticInfo", f:parsenoop },
30246 0x021A: { n:"BrtBeginECTxtWiz", f:parsenoop },
30247 0x021B: { n:"BrtEndECTxtWiz", f:parsenoop },
30248 0x021C: { n:"BrtBeginECTWFldInfoLst", f:parsenoop },
30249 0x021D: { n:"BrtEndECTWFldInfoLst", f:parsenoop },
30250 0x021E: { n:"BrtBeginECTwFldInfo", f:parsenoop },
30251 0x0224: { n:"BrtFileSharing", f:parsenoop },
30252 0x0225: { n:"BrtOleSize", f:parsenoop },
30253 0x0226: { n:"BrtDrawing", f:parsenoop },
30254 0x0227: { n:"BrtLegacyDrawing", f:parsenoop },
30255 0x0228: { n:"BrtLegacyDrawingHF", f:parsenoop },
30256 0x0229: { n:"BrtWebOpt", f:parsenoop },
30257 0x022A: { n:"BrtBeginWebPubItems", f:parsenoop },
30258 0x022B: { n:"BrtEndWebPubItems", f:parsenoop },
30259 0x022C: { n:"BrtBeginWebPubItem", f:parsenoop },
30260 0x022D: { n:"BrtEndWebPubItem", f:parsenoop },
30261 0x022E: { n:"BrtBeginSXCondFmt", f:parsenoop },
30262 0x022F: { n:"BrtEndSXCondFmt", f:parsenoop },
30263 0x0230: { n:"BrtBeginSXCondFmts", f:parsenoop },
30264 0x0231: { n:"BrtEndSXCondFmts", f:parsenoop },
30265 0x0232: { n:"BrtBkHim", f:parsenoop },
30266 0x0234: { n:"BrtColor", f:parsenoop },
30267 0x0235: { n:"BrtBeginIndexedColors", f:parsenoop },
30268 0x0236: { n:"BrtEndIndexedColors", f:parsenoop },
30269 0x0239: { n:"BrtBeginMRUColors", f:parsenoop },
30270 0x023A: { n:"BrtEndMRUColors", f:parsenoop },
30271 0x023C: { n:"BrtMRUColor", f:parsenoop },
30272 0x023D: { n:"BrtBeginDVals", f:parsenoop },
30273 0x023E: { n:"BrtEndDVals", f:parsenoop },
30274 0x0241: { n:"BrtSupNameStart", f:parsenoop },
30275 0x0242: { n:"BrtSupNameValueStart", f:parsenoop },
30276 0x0243: { n:"BrtSupNameValueEnd", f:parsenoop },
30277 0x0244: { n:"BrtSupNameNum", f:parsenoop },
30278 0x0245: { n:"BrtSupNameErr", f:parsenoop },
30279 0x0246: { n:"BrtSupNameSt", f:parsenoop },
30280 0x0247: { n:"BrtSupNameNil", f:parsenoop },
30281 0x0248: { n:"BrtSupNameBool", f:parsenoop },
30282 0x0249: { n:"BrtSupNameFmla", f:parsenoop },
30283 0x024A: { n:"BrtSupNameBits", f:parsenoop },
30284 0x024B: { n:"BrtSupNameEnd", f:parsenoop },
30285 0x024C: { n:"BrtEndSupBook", f:parsenoop },
30286 0x024D: { n:"BrtCellSmartTagProperty", f:parsenoop },
30287 0x024E: { n:"BrtBeginCellSmartTag", f:parsenoop },
30288 0x024F: { n:"BrtEndCellSmartTag", f:parsenoop },
30289 0x0250: { n:"BrtBeginCellSmartTags", f:parsenoop },
30290 0x0251: { n:"BrtEndCellSmartTags", f:parsenoop },
30291 0x0252: { n:"BrtBeginSmartTags", f:parsenoop },
30292 0x0253: { n:"BrtEndSmartTags", f:parsenoop },
30293 0x0254: { n:"BrtSmartTagType", f:parsenoop },
30294 0x0255: { n:"BrtBeginSmartTagTypes", f:parsenoop },
30295 0x0256: { n:"BrtEndSmartTagTypes", f:parsenoop },
30296 0x0257: { n:"BrtBeginSXFilters", f:parsenoop },
30297 0x0258: { n:"BrtEndSXFilters", f:parsenoop },
30298 0x0259: { n:"BrtBeginSXFILTER", f:parsenoop },
30299 0x025A: { n:"BrtEndSXFilter", f:parsenoop },
30300 0x025B: { n:"BrtBeginFills", f:parsenoop },
30301 0x025C: { n:"BrtEndFills", f:parsenoop },
30302 0x025D: { n:"BrtBeginCellWatches", f:parsenoop },
30303 0x025E: { n:"BrtEndCellWatches", f:parsenoop },
30304 0x025F: { n:"BrtCellWatch", f:parsenoop },
30305 0x0260: { n:"BrtBeginCRErrs", f:parsenoop },
30306 0x0261: { n:"BrtEndCRErrs", f:parsenoop },
30307 0x0262: { n:"BrtCrashRecErr", f:parsenoop },
30308 0x0263: { n:"BrtBeginFonts", f:parsenoop },
30309 0x0264: { n:"BrtEndFonts", f:parsenoop },
30310 0x0265: { n:"BrtBeginBorders", f:parsenoop },
30311 0x0266: { n:"BrtEndBorders", f:parsenoop },
30312 0x0267: { n:"BrtBeginFmts", f:parsenoop },
30313 0x0268: { n:"BrtEndFmts", f:parsenoop },
30314 0x0269: { n:"BrtBeginCellXFs", f:parsenoop },
30315 0x026A: { n:"BrtEndCellXFs", f:parsenoop },
30316 0x026B: { n:"BrtBeginStyles", f:parsenoop },
30317 0x026C: { n:"BrtEndStyles", f:parsenoop },
30318 0x0271: { n:"BrtBigName", f:parsenoop },
30319 0x0272: { n:"BrtBeginCellStyleXFs", f:parsenoop },
30320 0x0273: { n:"BrtEndCellStyleXFs", f:parsenoop },
30321 0x0274: { n:"BrtBeginComments", f:parsenoop },
30322 0x0275: { n:"BrtEndComments", f:parsenoop },
30323 0x0276: { n:"BrtBeginCommentAuthors", f:parsenoop },
30324 0x0277: { n:"BrtEndCommentAuthors", f:parsenoop },
30325 0x0278: { n:"BrtCommentAuthor", f:parse_BrtCommentAuthor },
30326 0x0279: { n:"BrtBeginCommentList", f:parsenoop },
30327 0x027A: { n:"BrtEndCommentList", f:parsenoop },
30328 0x027B: { n:"BrtBeginComment", f:parse_BrtBeginComment},
30329 0x027C: { n:"BrtEndComment", f:parsenoop },
30330 0x027D: { n:"BrtCommentText", f:parse_BrtCommentText },
30331 0x027E: { n:"BrtBeginOleObjects", f:parsenoop },
30332 0x027F: { n:"BrtOleObject", f:parsenoop },
30333 0x0280: { n:"BrtEndOleObjects", f:parsenoop },
30334 0x0281: { n:"BrtBeginSxrules", f:parsenoop },
30335 0x0282: { n:"BrtEndSxRules", f:parsenoop },
30336 0x0283: { n:"BrtBeginActiveXControls", f:parsenoop },
30337 0x0284: { n:"BrtActiveX", f:parsenoop },
30338 0x0285: { n:"BrtEndActiveXControls", f:parsenoop },
30339 0x0286: { n:"BrtBeginPCDSDTCEMembersSortBy", f:parsenoop },
30340 0x0288: { n:"BrtBeginCellIgnoreECs", f:parsenoop },
30341 0x0289: { n:"BrtCellIgnoreEC", f:parsenoop },
30342 0x028A: { n:"BrtEndCellIgnoreECs", f:parsenoop },
30343 0x028B: { n:"BrtCsProp", f:parsenoop },
30344 0x028C: { n:"BrtCsPageSetup", f:parsenoop },
30345 0x028D: { n:"BrtBeginUserCsViews", f:parsenoop },
30346 0x028E: { n:"BrtEndUserCsViews", f:parsenoop },
30347 0x028F: { n:"BrtBeginUserCsView", f:parsenoop },
30348 0x0290: { n:"BrtEndUserCsView", f:parsenoop },
30349 0x0291: { n:"BrtBeginPcdSFCIEntries", f:parsenoop },
30350 0x0292: { n:"BrtEndPCDSFCIEntries", f:parsenoop },
30351 0x0293: { n:"BrtPCDSFCIEntry", f:parsenoop },
30352 0x0294: { n:"BrtBeginListParts", f:parsenoop },
30353 0x0295: { n:"BrtListPart", f:parsenoop },
30354 0x0296: { n:"BrtEndListParts", f:parsenoop },
30355 0x0297: { n:"BrtSheetCalcProp", f:parsenoop },
30356 0x0298: { n:"BrtBeginFnGroup", f:parsenoop },
30357 0x0299: { n:"BrtFnGroup", f:parsenoop },
30358 0x029A: { n:"BrtEndFnGroup", f:parsenoop },
30359 0x029B: { n:"BrtSupAddin", f:parsenoop },
30360 0x029C: { n:"BrtSXTDMPOrder", f:parsenoop },
30361 0x029D: { n:"BrtCsProtection", f:parsenoop },
30362 0x029F: { n:"BrtBeginWsSortMap", f:parsenoop },
30363 0x02A0: { n:"BrtEndWsSortMap", f:parsenoop },
30364 0x02A1: { n:"BrtBeginRRSort", f:parsenoop },
30365 0x02A2: { n:"BrtEndRRSort", f:parsenoop },
30366 0x02A3: { n:"BrtRRSortItem", f:parsenoop },
30367 0x02A4: { n:"BrtFileSharingIso", f:parsenoop },
30368 0x02A5: { n:"BrtBookProtectionIso", f:parsenoop },
30369 0x02A6: { n:"BrtSheetProtectionIso", f:parsenoop },
30370 0x02A7: { n:"BrtCsProtectionIso", f:parsenoop },
30371 0x02A8: { n:"BrtRangeProtectionIso", f:parsenoop },
30372 0x0400: { n:"BrtRwDescent", f:parsenoop },
30373 0x0401: { n:"BrtKnownFonts", f:parsenoop },
30374 0x0402: { n:"BrtBeginSXTupleSet", f:parsenoop },
30375 0x0403: { n:"BrtEndSXTupleSet", f:parsenoop },
30376 0x0404: { n:"BrtBeginSXTupleSetHeader", f:parsenoop },
30377 0x0405: { n:"BrtEndSXTupleSetHeader", f:parsenoop },
30378 0x0406: { n:"BrtSXTupleSetHeaderItem", f:parsenoop },
30379 0x0407: { n:"BrtBeginSXTupleSetData", f:parsenoop },
30380 0x0408: { n:"BrtEndSXTupleSetData", f:parsenoop },
30381 0x0409: { n:"BrtBeginSXTupleSetRow", f:parsenoop },
30382 0x040A: { n:"BrtEndSXTupleSetRow", f:parsenoop },
30383 0x040B: { n:"BrtSXTupleSetRowItem", f:parsenoop },
30384 0x040C: { n:"BrtNameExt", f:parsenoop },
30385 0x040D: { n:"BrtPCDH14", f:parsenoop },
30386 0x040E: { n:"BrtBeginPCDCalcMem14", f:parsenoop },
30387 0x040F: { n:"BrtEndPCDCalcMem14", f:parsenoop },
30388 0x0410: { n:"BrtSXTH14", f:parsenoop },
30389 0x0411: { n:"BrtBeginSparklineGroup", f:parsenoop },
30390 0x0412: { n:"BrtEndSparklineGroup", f:parsenoop },
30391 0x0413: { n:"BrtSparkline", f:parsenoop },
30392 0x0414: { n:"BrtSXDI14", f:parsenoop },
30393 0x0415: { n:"BrtWsFmtInfoEx14", f:parsenoop },
30394 0x0416: { n:"BrtBeginConditionalFormatting14", f:parsenoop },
30395 0x0417: { n:"BrtEndConditionalFormatting14", f:parsenoop },
30396 0x0418: { n:"BrtBeginCFRule14", f:parsenoop },
30397 0x0419: { n:"BrtEndCFRule14", f:parsenoop },
30398 0x041A: { n:"BrtCFVO14", f:parsenoop },
30399 0x041B: { n:"BrtBeginDatabar14", f:parsenoop },
30400 0x041C: { n:"BrtBeginIconSet14", f:parsenoop },
30401 0x041D: { n:"BrtDVal14", f:parsenoop },
30402 0x041E: { n:"BrtBeginDVals14", f:parsenoop },
30403 0x041F: { n:"BrtColor14", f:parsenoop },
30404 0x0420: { n:"BrtBeginSparklines", f:parsenoop },
30405 0x0421: { n:"BrtEndSparklines", f:parsenoop },
30406 0x0422: { n:"BrtBeginSparklineGroups", f:parsenoop },
30407 0x0423: { n:"BrtEndSparklineGroups", f:parsenoop },
30408 0x0425: { n:"BrtSXVD14", f:parsenoop },
30409 0x0426: { n:"BrtBeginSxview14", f:parsenoop },
30410 0x0427: { n:"BrtEndSxview14", f:parsenoop },
30411 0x042A: { n:"BrtBeginPCD14", f:parsenoop },
30412 0x042B: { n:"BrtEndPCD14", f:parsenoop },
30413 0x042C: { n:"BrtBeginExtConn14", f:parsenoop },
30414 0x042D: { n:"BrtEndExtConn14", f:parsenoop },
30415 0x042E: { n:"BrtBeginSlicerCacheIDs", f:parsenoop },
30416 0x042F: { n:"BrtEndSlicerCacheIDs", f:parsenoop },
30417 0x0430: { n:"BrtBeginSlicerCacheID", f:parsenoop },
30418 0x0431: { n:"BrtEndSlicerCacheID", f:parsenoop },
30419 0x0433: { n:"BrtBeginSlicerCache", f:parsenoop },
30420 0x0434: { n:"BrtEndSlicerCache", f:parsenoop },
30421 0x0435: { n:"BrtBeginSlicerCacheDef", f:parsenoop },
30422 0x0436: { n:"BrtEndSlicerCacheDef", f:parsenoop },
30423 0x0437: { n:"BrtBeginSlicersEx", f:parsenoop },
30424 0x0438: { n:"BrtEndSlicersEx", f:parsenoop },
30425 0x0439: { n:"BrtBeginSlicerEx", f:parsenoop },
30426 0x043A: { n:"BrtEndSlicerEx", f:parsenoop },
30427 0x043B: { n:"BrtBeginSlicer", f:parsenoop },
30428 0x043C: { n:"BrtEndSlicer", f:parsenoop },
30429 0x043D: { n:"BrtSlicerCachePivotTables", f:parsenoop },
30430 0x043E: { n:"BrtBeginSlicerCacheOlapImpl", f:parsenoop },
30431 0x043F: { n:"BrtEndSlicerCacheOlapImpl", f:parsenoop },
30432 0x0440: { n:"BrtBeginSlicerCacheLevelsData", f:parsenoop },
30433 0x0441: { n:"BrtEndSlicerCacheLevelsData", f:parsenoop },
30434 0x0442: { n:"BrtBeginSlicerCacheLevelData", f:parsenoop },
30435 0x0443: { n:"BrtEndSlicerCacheLevelData", f:parsenoop },
30436 0x0444: { n:"BrtBeginSlicerCacheSiRanges", f:parsenoop },
30437 0x0445: { n:"BrtEndSlicerCacheSiRanges", f:parsenoop },
30438 0x0446: { n:"BrtBeginSlicerCacheSiRange", f:parsenoop },
30439 0x0447: { n:"BrtEndSlicerCacheSiRange", f:parsenoop },
30440 0x0448: { n:"BrtSlicerCacheOlapItem", f:parsenoop },
30441 0x0449: { n:"BrtBeginSlicerCacheSelections", f:parsenoop },
30442 0x044A: { n:"BrtSlicerCacheSelection", f:parsenoop },
30443 0x044B: { n:"BrtEndSlicerCacheSelections", f:parsenoop },
30444 0x044C: { n:"BrtBeginSlicerCacheNative", f:parsenoop },
30445 0x044D: { n:"BrtEndSlicerCacheNative", f:parsenoop },
30446 0x044E: { n:"BrtSlicerCacheNativeItem", f:parsenoop },
30447 0x044F: { n:"BrtRangeProtection14", f:parsenoop },
30448 0x0450: { n:"BrtRangeProtectionIso14", f:parsenoop },
30449 0x0451: { n:"BrtCellIgnoreEC14", f:parsenoop },
30450 0x0457: { n:"BrtList14", f:parsenoop },
30451 0x0458: { n:"BrtCFIcon", f:parsenoop },
30452 0x0459: { n:"BrtBeginSlicerCachesPivotCacheIDs", f:parsenoop },
30453 0x045A: { n:"BrtEndSlicerCachesPivotCacheIDs", f:parsenoop },
30454 0x045B: { n:"BrtBeginSlicers", f:parsenoop },
30455 0x045C: { n:"BrtEndSlicers", f:parsenoop },
30456 0x045D: { n:"BrtWbProp14", f:parsenoop },
30457 0x045E: { n:"BrtBeginSXEdit", f:parsenoop },
30458 0x045F: { n:"BrtEndSXEdit", f:parsenoop },
30459 0x0460: { n:"BrtBeginSXEdits", f:parsenoop },
30460 0x0461: { n:"BrtEndSXEdits", f:parsenoop },
30461 0x0462: { n:"BrtBeginSXChange", f:parsenoop },
30462 0x0463: { n:"BrtEndSXChange", f:parsenoop },
30463 0x0464: { n:"BrtBeginSXChanges", f:parsenoop },
30464 0x0465: { n:"BrtEndSXChanges", f:parsenoop },
30465 0x0466: { n:"BrtSXTupleItems", f:parsenoop },
30466 0x0468: { n:"BrtBeginSlicerStyle", f:parsenoop },
30467 0x0469: { n:"BrtEndSlicerStyle", f:parsenoop },
30468 0x046A: { n:"BrtSlicerStyleElement", f:parsenoop },
30469 0x046B: { n:"BrtBeginStyleSheetExt14", f:parsenoop },
30470 0x046C: { n:"BrtEndStyleSheetExt14", f:parsenoop },
30471 0x046D: { n:"BrtBeginSlicerCachesPivotCacheID", f:parsenoop },
30472 0x046E: { n:"BrtEndSlicerCachesPivotCacheID", f:parsenoop },
30473 0x046F: { n:"BrtBeginConditionalFormattings", f:parsenoop },
30474 0x0470: { n:"BrtEndConditionalFormattings", f:parsenoop },
30475 0x0471: { n:"BrtBeginPCDCalcMemExt", f:parsenoop },
30476 0x0472: { n:"BrtEndPCDCalcMemExt", f:parsenoop },
30477 0x0473: { n:"BrtBeginPCDCalcMemsExt", f:parsenoop },
30478 0x0474: { n:"BrtEndPCDCalcMemsExt", f:parsenoop },
30479 0x0475: { n:"BrtPCDField14", f:parsenoop },
30480 0x0476: { n:"BrtBeginSlicerStyles", f:parsenoop },
30481 0x0477: { n:"BrtEndSlicerStyles", f:parsenoop },
30482 0x0478: { n:"BrtBeginSlicerStyleElements", f:parsenoop },
30483 0x0479: { n:"BrtEndSlicerStyleElements", f:parsenoop },
30484 0x047A: { n:"BrtCFRuleExt", f:parsenoop },
30485 0x047B: { n:"BrtBeginSXCondFmt14", f:parsenoop },
30486 0x047C: { n:"BrtEndSXCondFmt14", f:parsenoop },
30487 0x047D: { n:"BrtBeginSXCondFmts14", f:parsenoop },
30488 0x047E: { n:"BrtEndSXCondFmts14", f:parsenoop },
30489 0x0480: { n:"BrtBeginSortCond14", f:parsenoop },
30490 0x0481: { n:"BrtEndSortCond14", f:parsenoop },
30491 0x0482: { n:"BrtEndDVals14", f:parsenoop },
30492 0x0483: { n:"BrtEndIconSet14", f:parsenoop },
30493 0x0484: { n:"BrtEndDatabar14", f:parsenoop },
30494 0x0485: { n:"BrtBeginColorScale14", f:parsenoop },
30495 0x0486: { n:"BrtEndColorScale14", f:parsenoop },
30496 0x0487: { n:"BrtBeginSxrules14", f:parsenoop },
30497 0x0488: { n:"BrtEndSxrules14", f:parsenoop },
30498 0x0489: { n:"BrtBeginPRule14", f:parsenoop },
30499 0x048A: { n:"BrtEndPRule14", f:parsenoop },
30500 0x048B: { n:"BrtBeginPRFilters14", f:parsenoop },
30501 0x048C: { n:"BrtEndPRFilters14", f:parsenoop },
30502 0x048D: { n:"BrtBeginPRFilter14", f:parsenoop },
30503 0x048E: { n:"BrtEndPRFilter14", f:parsenoop },
30504 0x048F: { n:"BrtBeginPRFItem14", f:parsenoop },
30505 0x0490: { n:"BrtEndPRFItem14", f:parsenoop },
30506 0x0491: { n:"BrtBeginCellIgnoreECs14", f:parsenoop },
30507 0x0492: { n:"BrtEndCellIgnoreECs14", f:parsenoop },
30508 0x0493: { n:"BrtDxf14", f:parsenoop },
30509 0x0494: { n:"BrtBeginDxF14s", f:parsenoop },
30510 0x0495: { n:"BrtEndDxf14s", f:parsenoop },
30511 0x0499: { n:"BrtFilter14", f:parsenoop },
30512 0x049A: { n:"BrtBeginCustomFilters14", f:parsenoop },
30513 0x049C: { n:"BrtCustomFilter14", f:parsenoop },
30514 0x049D: { n:"BrtIconFilter14", f:parsenoop },
30515 0x049E: { n:"BrtPivotCacheConnectionName", f:parsenoop },
30516 0x0800: { n:"BrtBeginDecoupledPivotCacheIDs", f:parsenoop },
30517 0x0801: { n:"BrtEndDecoupledPivotCacheIDs", f:parsenoop },
30518 0x0802: { n:"BrtDecoupledPivotCacheID", f:parsenoop },
30519 0x0803: { n:"BrtBeginPivotTableRefs", f:parsenoop },
30520 0x0804: { n:"BrtEndPivotTableRefs", f:parsenoop },
30521 0x0805: { n:"BrtPivotTableRef", f:parsenoop },
30522 0x0806: { n:"BrtSlicerCacheBookPivotTables", f:parsenoop },
30523 0x0807: { n:"BrtBeginSxvcells", f:parsenoop },
30524 0x0808: { n:"BrtEndSxvcells", f:parsenoop },
30525 0x0809: { n:"BrtBeginSxRow", f:parsenoop },
30526 0x080A: { n:"BrtEndSxRow", f:parsenoop },
30527 0x080C: { n:"BrtPcdCalcMem15", f:parsenoop },
30528 0x0813: { n:"BrtQsi15", f:parsenoop },
30529 0x0814: { n:"BrtBeginWebExtensions", f:parsenoop },
30530 0x0815: { n:"BrtEndWebExtensions", f:parsenoop },
30531 0x0816: { n:"BrtWebExtension", f:parsenoop },
30532 0x0817: { n:"BrtAbsPath15", f:parsenoop },
30533 0x0818: { n:"BrtBeginPivotTableUISettings", f:parsenoop },
30534 0x0819: { n:"BrtEndPivotTableUISettings", f:parsenoop },
30535 0x081B: { n:"BrtTableSlicerCacheIDs", f:parsenoop },
30536 0x081C: { n:"BrtTableSlicerCacheID", f:parsenoop },
30537 0x081D: { n:"BrtBeginTableSlicerCache", f:parsenoop },
30538 0x081E: { n:"BrtEndTableSlicerCache", f:parsenoop },
30539 0x081F: { n:"BrtSxFilter15", f:parsenoop },
30540 0x0820: { n:"BrtBeginTimelineCachePivotCacheIDs", f:parsenoop },
30541 0x0821: { n:"BrtEndTimelineCachePivotCacheIDs", f:parsenoop },
30542 0x0822: { n:"BrtTimelineCachePivotCacheID", f:parsenoop },
30543 0x0823: { n:"BrtBeginTimelineCacheIDs", f:parsenoop },
30544 0x0824: { n:"BrtEndTimelineCacheIDs", f:parsenoop },
30545 0x0825: { n:"BrtBeginTimelineCacheID", f:parsenoop },
30546 0x0826: { n:"BrtEndTimelineCacheID", f:parsenoop },
30547 0x0827: { n:"BrtBeginTimelinesEx", f:parsenoop },
30548 0x0828: { n:"BrtEndTimelinesEx", f:parsenoop },
30549 0x0829: { n:"BrtBeginTimelineEx", f:parsenoop },
30550 0x082A: { n:"BrtEndTimelineEx", f:parsenoop },
30551 0x082B: { n:"BrtWorkBookPr15", f:parsenoop },
30552 0x082C: { n:"BrtPCDH15", f:parsenoop },
30553 0x082D: { n:"BrtBeginTimelineStyle", f:parsenoop },
30554 0x082E: { n:"BrtEndTimelineStyle", f:parsenoop },
30555 0x082F: { n:"BrtTimelineStyleElement", f:parsenoop },
30556 0x0830: { n:"BrtBeginTimelineStylesheetExt15", f:parsenoop },
30557 0x0831: { n:"BrtEndTimelineStylesheetExt15", f:parsenoop },
30558 0x0832: { n:"BrtBeginTimelineStyles", f:parsenoop },
30559 0x0833: { n:"BrtEndTimelineStyles", f:parsenoop },
30560 0x0834: { n:"BrtBeginTimelineStyleElements", f:parsenoop },
30561 0x0835: { n:"BrtEndTimelineStyleElements", f:parsenoop },
30562 0x0836: { n:"BrtDxf15", f:parsenoop },
30563 0x0837: { n:"BrtBeginDxfs15", f:parsenoop },
30564 0x0838: { n:"brtEndDxfs15", f:parsenoop },
30565 0x0839: { n:"BrtSlicerCacheHideItemsWithNoData", f:parsenoop },
30566 0x083A: { n:"BrtBeginItemUniqueNames", f:parsenoop },
30567 0x083B: { n:"BrtEndItemUniqueNames", f:parsenoop },
30568 0x083C: { n:"BrtItemUniqueName", f:parsenoop },
30569 0x083D: { n:"BrtBeginExtConn15", f:parsenoop },
30570 0x083E: { n:"BrtEndExtConn15", f:parsenoop },
30571 0x083F: { n:"BrtBeginOledbPr15", f:parsenoop },
30572 0x0840: { n:"BrtEndOledbPr15", f:parsenoop },
30573 0x0841: { n:"BrtBeginDataFeedPr15", f:parsenoop },
30574 0x0842: { n:"BrtEndDataFeedPr15", f:parsenoop },
30575 0x0843: { n:"BrtTextPr15", f:parsenoop },
30576 0x0844: { n:"BrtRangePr15", f:parsenoop },
30577 0x0845: { n:"BrtDbCommand15", f:parsenoop },
30578 0x0846: { n:"BrtBeginDbTables15", f:parsenoop },
30579 0x0847: { n:"BrtEndDbTables15", f:parsenoop },
30580 0x0848: { n:"BrtDbTable15", f:parsenoop },
30581 0x0849: { n:"BrtBeginDataModel", f:parsenoop },
30582 0x084A: { n:"BrtEndDataModel", f:parsenoop },
30583 0x084B: { n:"BrtBeginModelTables", f:parsenoop },
30584 0x084C: { n:"BrtEndModelTables", f:parsenoop },
30585 0x084D: { n:"BrtModelTable", f:parsenoop },
30586 0x084E: { n:"BrtBeginModelRelationships", f:parsenoop },
30587 0x084F: { n:"BrtEndModelRelationships", f:parsenoop },
30588 0x0850: { n:"BrtModelRelationship", f:parsenoop },
30589 0x0851: { n:"BrtBeginECTxtWiz15", f:parsenoop },
30590 0x0852: { n:"BrtEndECTxtWiz15", f:parsenoop },
30591 0x0853: { n:"BrtBeginECTWFldInfoLst15", f:parsenoop },
30592 0x0854: { n:"BrtEndECTWFldInfoLst15", f:parsenoop },
30593 0x0855: { n:"BrtBeginECTWFldInfo15", f:parsenoop },
30594 0x0856: { n:"BrtFieldListActiveItem", f:parsenoop },
30595 0x0857: { n:"BrtPivotCacheIdVersion", f:parsenoop },
30596 0x0858: { n:"BrtSXDI15", f:parsenoop },
30597 0xFFFF: { n:"", f:parsenoop }
30598 };
30599
30600 var evert_RE = evert_key(RecordEnum, 'n');
30601 function fix_opts_func(defaults) {
30602 return function fix_opts(opts) {
30603 for(var i = 0; i != defaults.length; ++i) {
30604 var d = defaults[i];
30605 if(opts[d[0]] === undefined) opts[d[0]] = d[1];
30606 if(d[2] === 'n') opts[d[0]] = Number(opts[d[0]]);
30607 }
30608 };
30609 }
30610
30611 var fix_read_opts = fix_opts_func([
30612 ['cellNF', false], /* emit cell number format string as .z */
30613 ['cellHTML', true], /* emit html string as .h */
30614 ['cellFormula', true], /* emit formulae as .f */
30615 ['cellStyles', false], /* emits style/theme as .s */
30616
30617 ['sheetStubs', false], /* emit empty cells */
30618 ['sheetRows', 0, 'n'], /* read n rows (0 = read all rows) */
30619
30620 ['bookDeps', false], /* parse calculation chains */
30621 ['bookSheets', false], /* only try to get sheet names (no Sheets) */
30622 ['bookProps', false], /* only try to get properties (no Sheets) */
30623 ['bookFiles', false], /* include raw file structure (keys, files) */
30624 ['bookVBA', false], /* include vba raw data (vbaraw) */
30625
30626 ['WTF', false] /* WTF mode (throws errors) */
30627 ]);
30628
30629
30630 var fix_write_opts = fix_opts_func([
30631 ['bookSST', false], /* Generate Shared String Table */
30632
30633 ['bookType', 'xlsx'], /* Type of workbook (xlsx/m/b) */
30634
30635 ['WTF', false] /* WTF mode (throws errors) */
30636 ]);
30637 function safe_parse_wbrels(wbrels, sheets) {
30638 if(!wbrels) return 0;
30639 try {
30640 wbrels = sheets.map(function pwbr(w) { return [w.name, wbrels['!id'][w.id].Target]; });
30641 } catch(e) { return null; }
30642 return !wbrels || wbrels.length === 0 ? null : wbrels;
30643 }
30644
30645 function safe_parse_ws(zip, path, relsPath, sheet, sheetRels, sheets, opts) {
30646 try {
30647 sheetRels[sheet]=parse_rels(getzipdata(zip, relsPath, true), path);
30648 sheets[sheet]=parse_ws(getzipdata(zip, path),path,opts,sheetRels[sheet]);
30649 } catch(e) { if(opts.WTF) throw e; }
30650 }
30651
30652 var nodirs = function nodirs(x){return x.substr(-1) != '/';};
30653 function parse_zip(zip, opts) {
30654 make_ssf(SSF);
30655 opts = opts || {};
30656 fix_read_opts(opts);
30657 reset_cp();
30658 var entries = keys(zip.files).filter(nodirs).sort();
30659 var dir = parse_ct(getzipdata(zip, '[Content_Types].xml'), opts);
30660 var xlsb = false;
30661 var sheets, binname;
30662 if(dir.workbooks.length === 0) {
30663 binname = "xl/workbook.xml";
30664 if(getzipdata(zip,binname, true)) dir.workbooks.push(binname);
30665 }
30666 if(dir.workbooks.length === 0) {
30667 binname = "xl/workbook.bin";
30668 if(!getzipfile(zip,binname,true)) throw new Error("Could not find workbook");
30669 dir.workbooks.push(binname);
30670 xlsb = true;
30671 }
30672 if(dir.workbooks[0].substr(-3) == "bin") xlsb = true;
30673 if(xlsb) set_cp(1200);
30674
30675 if(!opts.bookSheets && !opts.bookProps) {
30676 strs = [];
30677 if(dir.sst) strs=parse_sst(getzipdata(zip, dir.sst.replace(/^\//,'')), dir.sst, opts);
30678
30679 styles = {};
30680 if(dir.style) styles = parse_sty(getzipdata(zip, dir.style.replace(/^\//,'')),dir.style, opts);
30681
30682 themes = {};
30683 if(opts.cellStyles && dir.themes.length) themes = parse_theme(getzipdata(zip, dir.themes[0].replace(/^\//,''), true),dir.themes[0], opts);
30684 }
30685
30686 var wb = parse_wb(getzipdata(zip, dir.workbooks[0].replace(/^\//,'')), dir.workbooks[0], opts);
30687
30688 var props = {}, propdata = "";
30689
30690 if(dir.coreprops.length !== 0) {
30691 propdata = getzipdata(zip, dir.coreprops[0].replace(/^\//,''), true);
30692 if(propdata) props = parse_core_props(propdata);
30693 if(dir.extprops.length !== 0) {
30694 propdata = getzipdata(zip, dir.extprops[0].replace(/^\//,''), true);
30695 if(propdata) parse_ext_props(propdata, props);
30696 }
30697 }
30698
30699 var custprops = {};
30700 if(!opts.bookSheets || opts.bookProps) {
30701 if (dir.custprops.length !== 0) {
30702 propdata = getzipdata(zip, dir.custprops[0].replace(/^\//,''), true);
30703 if(propdata) custprops = parse_cust_props(propdata, opts);
30704 }
30705 }
30706
30707 var out = {};
30708 if(opts.bookSheets || opts.bookProps) {
30709 if(props.Worksheets && props.SheetNames.length > 0) sheets=props.SheetNames;
30710 else if(wb.Sheets) sheets = wb.Sheets.map(function pluck(x){ return x.name; });
30711 if(opts.bookProps) { out.Props = props; out.Custprops = custprops; }
30712 if(typeof sheets !== 'undefined') out.SheetNames = sheets;
30713 if(opts.bookSheets ? out.SheetNames : opts.bookProps) return out;
30714 }
30715 sheets = {};
30716
30717 var deps = {};
30718 if(opts.bookDeps && dir.calcchain) deps=parse_cc(getzipdata(zip, dir.calcchain.replace(/^\//,'')),dir.calcchain,opts);
30719
30720 var i=0;
30721 var sheetRels = {};
30722 var path, relsPath;
30723 if(!props.Worksheets) {
30724 var wbsheets = wb.Sheets;
30725 props.Worksheets = wbsheets.length;
30726 props.SheetNames = [];
30727 for(var j = 0; j != wbsheets.length; ++j) {
30728 props.SheetNames[j] = wbsheets[j].name;
30729 }
30730 }
30731
30732 var wbext = xlsb ? "bin" : "xml";
30733 var wbrelsfile = 'xl/_rels/workbook.' + wbext + '.rels';
30734 var wbrels = parse_rels(getzipdata(zip, wbrelsfile, true), wbrelsfile);
30735 if(wbrels) wbrels = safe_parse_wbrels(wbrels, wb.Sheets);
30736 /* Numbers iOS hack */
30737 var nmode = (getzipdata(zip,"xl/worksheets/sheet.xml",true))?1:0;
30738 for(i = 0; i != props.Worksheets; ++i) {
30739 if(wbrels) path = 'xl/' + (wbrels[i][1]).replace(/[\/]?xl\//, "");
30740 else {
30741 path = 'xl/worksheets/sheet'+(i+1-nmode)+"." + wbext;
30742 path = path.replace(/sheet0\./,"sheet.");
30743 }
30744 relsPath = path.replace(/^(.*)(\/)([^\/]*)$/, "$1/_rels/$3.rels");
30745 safe_parse_ws(zip, path, relsPath, props.SheetNames[i], sheetRels, sheets, opts);
30746 }
30747
30748 if(dir.comments) parse_comments(zip, dir.comments, sheets, sheetRels, opts);
30749
30750 out = {
30751 Directory: dir,
30752 Workbook: wb,
30753 Props: props,
30754 Custprops: custprops,
30755 Deps: deps,
30756 Sheets: sheets,
30757 SheetNames: props.SheetNames,
30758 Strings: strs,
30759 Styles: styles,
30760 Themes: themes,
30761 SSF: SSF.get_table()
30762 };
30763 if(opts.bookFiles) {
30764 out.keys = entries;
30765 out.files = zip.files;
30766 }
30767 if(opts.bookVBA) {
30768 if(dir.vba.length > 0) out.vbaraw = getzipdata(zip,dir.vba[0],true);
30769 else if(dir.defaults.bin === 'application/vnd.ms-office.vbaProject') out.vbaraw = getzipdata(zip,'xl/vbaProject.bin',true);
30770 }
30771 return out;
30772 }
30773 function add_rels(rels, rId, f, type, relobj) {
30774 if(!relobj) relobj = {};
30775 if(!rels['!id']) rels['!id'] = {};
30776 relobj.Id = 'rId' + rId;
30777 relobj.Type = type;
30778 relobj.Target = f;
30779 if(rels['!id'][relobj.Id]) throw new Error("Cannot rewrite rId " + rId);
30780 rels['!id'][relobj.Id] = relobj;
30781 rels[('/' + relobj.Target).replace("//","/")] = relobj;
30782 }
30783
30784 function write_zip(wb, opts) {
30785 if(wb && !wb.SSF) {
30786 wb.SSF = SSF.get_table();
30787 }
30788 if(wb && wb.SSF) {
30789 make_ssf(SSF); SSF.load_table(wb.SSF);
30790 opts.revssf = evert_num(wb.SSF); opts.revssf[wb.SSF[65535]] = 0;
30791 }
30792 opts.rels = {}; opts.wbrels = {};
30793 opts.Strings = []; opts.Strings.Count = 0; opts.Strings.Unique = 0;
30794 var wbext = opts.bookType == "xlsb" ? "bin" : "xml";
30795 var ct = { workbooks: [], sheets: [], calcchains: [], themes: [], styles: [],
30796 coreprops: [], extprops: [], custprops: [], strs:[], comments: [], vba: [],
30797 TODO:[], rels:[], xmlns: "" };
30798 fix_write_opts(opts = opts || {});
30799 var zip = new jszip();
30800 var f = "", rId = 0;
30801
30802 opts.cellXfs = [];
30803 get_cell_style(opts.cellXfs, {}, {revssf:{"General":0}});
30804
30805 f = "docProps/core.xml";
30806 zip.file(f, write_core_props(wb.Props, opts));
30807 ct.coreprops.push(f);
30808 add_rels(opts.rels, 2, f, RELS.CORE_PROPS);
30809
30810 f = "docProps/app.xml";
30811 if(!wb.Props) wb.Props = {};
30812 wb.Props.SheetNames = wb.SheetNames;
30813 wb.Props.Worksheets = wb.SheetNames.length;
30814 zip.file(f, write_ext_props(wb.Props, opts));
30815 ct.extprops.push(f);
30816 add_rels(opts.rels, 3, f, RELS.EXT_PROPS);
30817
30818 if(wb.Custprops !== wb.Props && keys(wb.Custprops||{}).length > 0) {
30819 f = "docProps/custom.xml";
30820 zip.file(f, write_cust_props(wb.Custprops, opts));
30821 ct.custprops.push(f);
30822 add_rels(opts.rels, 4, f, RELS.CUST_PROPS);
30823 }
30824
30825 f = "xl/workbook." + wbext;
30826 zip.file(f, write_wb(wb, f, opts));
30827 ct.workbooks.push(f);
30828 add_rels(opts.rels, 1, f, RELS.WB);
30829
30830 for(rId=1;rId <= wb.SheetNames.length; ++rId) {
30831 f = "xl/worksheets/sheet" + rId + "." + wbext;
30832 zip.file(f, write_ws(rId-1, f, opts, wb));
30833 ct.sheets.push(f);
30834 add_rels(opts.wbrels, rId, "worksheets/sheet" + rId + "." + wbext, RELS.WS);
30835 }
30836
30837 if(opts.Strings != null && opts.Strings.length > 0) {
30838 f = "xl/sharedStrings." + wbext;
30839 zip.file(f, write_sst(opts.Strings, f, opts));
30840 ct.strs.push(f);
30841 add_rels(opts.wbrels, ++rId, "sharedStrings." + wbext, RELS.SST);
30842 }
30843
30844 /* TODO: something more intelligent with themes */
30845
30846 f = "xl/theme/theme1.xml";
30847 zip.file(f, write_theme());
30848 ct.themes.push(f);
30849 add_rels(opts.wbrels, ++rId, "theme/theme1.xml", RELS.THEME);
30850
30851 /* TODO: something more intelligent with styles */
30852
30853 f = "xl/styles." + wbext;
30854 zip.file(f, write_sty(wb, f, opts));
30855 ct.styles.push(f);
30856 add_rels(opts.wbrels, ++rId, "styles." + wbext, RELS.STY);
30857
30858 zip.file("[Content_Types].xml", write_ct(ct, opts));
30859 zip.file('_rels/.rels', write_rels(opts.rels));
30860 zip.file('xl/_rels/workbook.' + wbext + '.rels', write_rels(opts.wbrels));
30861 return zip;
30862 }
30863 function readSync(data, opts) {
30864 var zip, d = data;
30865 var o = opts||{};
30866 if(!o.type) o.type = (has_buf && Buffer.isBuffer(data)) ? "buffer" : "base64";
30867 switch(o.type) {
30868 case "base64": zip = new jszip(d, { base64:true }); break;
30869 case "binary": zip = new jszip(d, { base64:false }); break;
30870 case "buffer": zip = new jszip(d); break;
30871 case "file": zip=new jszip(d=_fs.readFileSync(data)); break;
30872 default: throw new Error("Unrecognized type " + o.type);
30873 }
30874 return parse_zip(zip, o);
30875 }
30876
30877 function readFileSync(data, opts) {
30878 var o = opts||{}; o.type = 'file';
30879 return readSync(data, o);
30880 }
30881
30882 function writeSync(wb, opts) {
30883 var o = opts||{};
30884 var z = write_zip(wb, o);
30885 switch(o.type) {
30886 case "base64": return z.generate({type:"base64"});
30887 case "binary": return z.generate({type:"string"});
30888 case "buffer": return z.generate({type:"nodebuffer"});
30889 case "file": return _fs.writeFileSync(o.file, z.generate({type:"nodebuffer"}));
30890 default: throw new Error("Unrecognized type " + o.type);
30891 }
30892 }
30893
30894 function writeFileSync(wb, filename, opts) {
30895 var o = opts||{}; o.type = 'file';
30896 o.file = filename;
30897 switch(o.file.substr(-5).toLowerCase()) {
30898 case '.xlsm': o.bookType = 'xlsm'; break;
30899 case '.xlsb': o.bookType = 'xlsb'; break;
30900 }
30901 return writeSync(wb, o);
30902 }
30903
30904 function decode_row(rowstr) { return parseInt(unfix_row(rowstr),10) - 1; }
30905 function encode_row(row) { return "" + (row + 1); }
30906 function fix_row(cstr) { return cstr.replace(/([A-Z]|^)(\d+)$/,"$1$$$2"); }
30907 function unfix_row(cstr) { return cstr.replace(/\$(\d+)$/,"$1"); }
30908
30909 function decode_col(colstr) { var c = unfix_col(colstr), d = 0, i = 0; for(; i !== c.length; ++i) d = 26*d + c.charCodeAt(i) - 64; return d - 1; }
30910 function encode_col(col) { var s=""; for(++col; col; col=Math.floor((col-1)/26)) s = String.fromCharCode(((col-1)%26) + 65) + s; return s; }
30911 function fix_col(cstr) { return cstr.replace(/^([A-Z])/,"$$$1"); }
30912 function unfix_col(cstr) { return cstr.replace(/^\$([A-Z])/,"$1"); }
30913
30914 function split_cell(cstr) { return cstr.replace(/(\$?[A-Z]*)(\$?\d*)/,"$1,$2").split(","); }
30915 function decode_cell(cstr) { var splt = split_cell(cstr); return { c:decode_col(splt[0]), r:decode_row(splt[1]) }; }
30916 function encode_cell(cell) { return encode_col(cell.c) + encode_row(cell.r); }
30917 function fix_cell(cstr) { return fix_col(fix_row(cstr)); }
30918 function unfix_cell(cstr) { return unfix_col(unfix_row(cstr)); }
30919 function decode_range(range) { var x =range.split(":").map(decode_cell); return {s:x[0],e:x[x.length-1]}; }
30920 function encode_range(cs,ce) {
30921 if(ce === undefined || typeof ce === 'number') return encode_range(cs.s, cs.e);
30922 if(typeof cs !== 'string') cs = encode_cell(cs); if(typeof ce !== 'string') ce = encode_cell(ce);
30923 return cs == ce ? cs : cs + ":" + ce;
30924 }
30925
30926 function safe_decode_range(range) {
30927 var o = {s:{c:0,r:0},e:{c:0,r:0}};
30928 var idx = 0, i = 0, cc = 0;
30929 var len = range.length;
30930 for(idx = 0; i < len; ++i) {
30931 if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
30932 idx = 26*idx + cc;
30933 }
30934 o.s.c = --idx;
30935
30936 for(idx = 0; i < len; ++i) {
30937 if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
30938 idx = 10*idx + cc;
30939 }
30940 o.s.r = --idx;
30941
30942 if(i === len || range.charCodeAt(++i) === 58) { o.e.c=o.s.c; o.e.r=o.s.r; return o; }
30943
30944 for(idx = 0; i != len; ++i) {
30945 if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
30946 idx = 26*idx + cc;
30947 }
30948 o.e.c = --idx;
30949
30950 for(idx = 0; i != len; ++i) {
30951 if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
30952 idx = 10*idx + cc;
30953 }
30954 o.e.r = --idx;
30955 return o;
30956 }
30957
30958 function safe_format_cell(cell, v) {
30959 if(cell.z !== undefined) try { return (cell.w = SSF.format(cell.z, v)); } catch(e) { }
30960 if(!cell.XF) return v;
30961 try { return (cell.w = SSF.format(cell.XF.ifmt||0, v)); } catch(e) { return ''+v; }
30962 }
30963
30964 function format_cell(cell, v) {
30965 if(cell == null || cell.t == null) return "";
30966 if(cell.w !== undefined) return cell.w;
30967 if(v === undefined) return safe_format_cell(cell, cell.v);
30968 return safe_format_cell(cell, v);
30969 }
30970
30971 function sheet_to_json(sheet, opts){
30972 var val, row, range, header = 0, offset = 1, r, hdr = [], isempty, R, C, v;
30973 var o = opts != null ? opts : {};
30974 var raw = o.raw;
30975 if(sheet == null || sheet["!ref"] == null) return [];
30976 range = o.range !== undefined ? o.range : sheet["!ref"];
30977 if(o.header === 1) header = 1;
30978 else if(o.header === "A") header = 2;
30979 else if(Array.isArray(o.header)) header = 3;
30980 switch(typeof range) {
30981 case 'string': r = safe_decode_range(range); break;
30982 case 'number': r = safe_decode_range(sheet["!ref"]); r.s.r = range; break;
30983 default: r = range;
30984 }
30985 if(header > 0) offset = 0;
30986 var rr = encode_row(r.s.r);
30987 var cols = new Array(r.e.c-r.s.c+1);
30988 var out = new Array(r.e.r-r.s.r-offset+1);
30989 var outi = 0;
30990 for(C = r.s.c; C <= r.e.c; ++C) {
30991 cols[C] = encode_col(C);
30992 val = sheet[cols[C] + rr];
30993 switch(header) {
30994 case 1: hdr[C] = C; break;
30995 case 2: hdr[C] = cols[C]; break;
30996 case 3: hdr[C] = o.header[C - r.s.c]; break;
30997 default:
30998 if(val === undefined) continue;
30999 hdr[C] = format_cell(val);
31000 }
31001 }
31002
31003 for (R = r.s.r + offset; R <= r.e.r; ++R) {
31004 rr = encode_row(R);
31005 isempty = true;
31006 row = header === 1 ? [] : Object.create({ __rowNum__ : R });
31007 for (C = r.s.c; C <= r.e.c; ++C) {
31008 val = sheet[cols[C] + rr];
31009 if(val === undefined || val.t === undefined) continue;
31010 v = val.v;
31011 switch(val.t){
31012 case 'e': continue;
31013 case 's': case 'str': break;
31014 case 'b': case 'n': break;
31015 default: throw 'unrecognized type ' + val.t;
31016 }
31017 if(v !== undefined) {
31018 row[hdr[C]] = raw ? v : format_cell(val,v);
31019 isempty = false;
31020 }
31021 }
31022 if(isempty === false) out[outi++] = row;
31023 }
31024 out.length = outi;
31025 return out;
31026 }
31027
31028 function sheet_to_row_object_array(sheet, opts) { return sheet_to_json(sheet, opts != null ? opts : {}); }
31029
31030 function sheet_to_csv(sheet, opts) {
31031 var out = "", txt = "", qreg = /"/g;
31032 var o = opts == null ? {} : opts;
31033 if(sheet == null || sheet["!ref"] == null) return "";
31034 var r = safe_decode_range(sheet["!ref"]);
31035 var FS = o.FS !== undefined ? o.FS : ",", fs = FS.charCodeAt(0);
31036 var RS = o.RS !== undefined ? o.RS : "\n", rs = RS.charCodeAt(0);
31037 var row = "", rr = "", cols = [];
31038 var i = 0, cc = 0, val;
31039 var R = 0, C = 0;
31040 for(C = r.s.c; C <= r.e.c; ++C) cols[C] = encode_col(C);
31041 for(R = r.s.r; R <= r.e.r; ++R) {
31042 row = "";
31043 rr = encode_row(R);
31044 for(C = r.s.c; C <= r.e.c; ++C) {
31045 val = sheet[cols[C] + rr];
31046 txt = val !== undefined ? ''+format_cell(val) : "";
31047 for(i = 0, cc = 0; i !== txt.length; ++i) if((cc = txt.charCodeAt(i)) === fs || cc === rs || cc === 34) {
31048 txt = "\"" + txt.replace(qreg, '""') + "\""; break; }
31049 row += (C === r.s.c ? "" : FS) + txt;
31050 }
31051 out += row + RS;
31052 }
31053 return out;
31054 }
31055 var make_csv = sheet_to_csv;
31056
31057 function sheet_to_formulae(sheet) {
31058 var cmds, y = "", x, val="";
31059 if(sheet == null || sheet["!ref"] == null) return "";
31060 var r = safe_decode_range(sheet['!ref']), rr = "", cols = [], C;
31061 cmds = new Array((r.e.r-r.s.r+1)*(r.e.c-r.s.c+1));
31062 var i = 0;
31063 for(C = r.s.c; C <= r.e.c; ++C) cols[C] = encode_col(C);
31064 for(var R = r.s.r; R <= r.e.r; ++R) {
31065 rr = encode_row(R);
31066 for(C = r.s.c; C <= r.e.c; ++C) {
31067 y = cols[C] + rr;
31068 x = sheet[y];
31069 val = "";
31070 if(x === undefined) continue;
31071 if(x.f != null) val = x.f;
31072 else if(x.w !== undefined) val = "'" + x.w;
31073 else if(x.v === undefined) continue;
31074 else val = ""+x.v;
31075 cmds[i++] = y + "=" + val;
31076 }
31077 }
31078 cmds.length = i;
31079 return cmds;
31080 }
31081
31082 var utils = {
31083 encode_col: encode_col,
31084 encode_row: encode_row,
31085 encode_cell: encode_cell,
31086 encode_range: encode_range,
31087 decode_col: decode_col,
31088 decode_row: decode_row,
31089 split_cell: split_cell,
31090 decode_cell: decode_cell,
31091 decode_range: decode_range,
31092 format_cell: format_cell,
31093 get_formulae: sheet_to_formulae,
31094 make_csv: sheet_to_csv,
31095 make_json: sheet_to_json,
31096 make_formulae: sheet_to_formulae,
31097 sheet_to_csv: sheet_to_csv,
31098 sheet_to_json: sheet_to_json,
31099 sheet_to_formulae: sheet_to_formulae,
31100 sheet_to_row_object_array: sheet_to_row_object_array
31101 };
31102 XLSX.parseZip = parse_zip;
31103 XLSX.read = readSync;
31104 XLSX.readFile = readFileSync;
31105 XLSX.write = writeSync;
31106 XLSX.writeFile = writeFileSync;
31107 XLSX.utils = utils;
31108 XLSX.SSF = SSF;
31109 })(typeof exports !== 'undefined' ? exports : XLSX);
31110 //! moment.js
31111 //! version : 2.5.1
31112 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
31113 //! license : MIT
31114 //! momentjs.com
31115
31116 (function (undefined) {
31117
31118 /************************************
31119 Constants
31120 ************************************/
31121
31122 var moment,
31123 VERSION = "2.5.1",
31124 global = this,
31125 round = Math.round,
31126 i,
31127
31128 YEAR = 0,
31129 MONTH = 1,
31130 DATE = 2,
31131 HOUR = 3,
31132 MINUTE = 4,
31133 SECOND = 5,
31134 MILLISECOND = 6,
31135
31136 // internal storage for language config files
31137 languages = {},
31138
31139 // moment internal properties
31140 momentProperties = {
31141 _isAMomentObject: null,
31142 _i : null,
31143 _f : null,
31144 _l : null,
31145 _strict : null,
31146 _isUTC : null,
31147 _offset : null, // optional. Combine with _isUTC
31148 _pf : null,
31149 _lang : null // optional
31150 },
31151
31152 // check for nodeJS
31153 hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'),
31154
31155 // ASP.NET json date format regex
31156 aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
31157 aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,
31158
31159 // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
31160 // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
31161 isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,
31162
31163 // format tokens
31164 formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g,
31165 localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
31166
31167 // parsing token regexes
31168 parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
31169 parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
31170 parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999
31171 parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
31172 parseTokenDigits = /\d+/, // nonzero number of digits
31173 parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic.
31174 parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
31175 parseTokenT = /T/i, // T (ISO separator)
31176 parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
31177
31178 //strict parsing regexes
31179 parseTokenOneDigit = /\d/, // 0 - 9
31180 parseTokenTwoDigits = /\d\d/, // 00 - 99
31181 parseTokenThreeDigits = /\d{3}/, // 000 - 999
31182 parseTokenFourDigits = /\d{4}/, // 0000 - 9999
31183 parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999
31184 parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf
31185
31186 // iso 8601 regex
31187 // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
31188 isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
31189
31190 isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
31191
31192 isoDates = [
31193 ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/],
31194 ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
31195 ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
31196 ['GGGG-[W]WW', /\d{4}-W\d{2}/],
31197 ['YYYY-DDD', /\d{4}-\d{3}/]
31198 ],
31199
31200 // iso time formats and regexes
31201 isoTimes = [
31202 ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
31203 ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
31204 ['HH:mm', /(T| )\d\d:\d\d/],
31205 ['HH', /(T| )\d\d/]
31206 ],
31207
31208 // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
31209 parseTimezoneChunker = /([\+\-]|\d\d)/gi,
31210
31211 // getter and setter names
31212 proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
31213 unitMillisecondFactors = {
31214 'Milliseconds' : 1,
31215 'Seconds' : 1e3,
31216 'Minutes' : 6e4,
31217 'Hours' : 36e5,
31218 'Days' : 864e5,
31219 'Months' : 2592e6,
31220 'Years' : 31536e6
31221 },
31222
31223 unitAliases = {
31224 ms : 'millisecond',
31225 s : 'second',
31226 m : 'minute',
31227 h : 'hour',
31228 d : 'day',
31229 D : 'date',
31230 w : 'week',
31231 W : 'isoWeek',
31232 M : 'month',
31233 y : 'year',
31234 DDD : 'dayOfYear',
31235 e : 'weekday',
31236 E : 'isoWeekday',
31237 gg: 'weekYear',
31238 GG: 'isoWeekYear'
31239 },
31240
31241 camelFunctions = {
31242 dayofyear : 'dayOfYear',
31243 isoweekday : 'isoWeekday',
31244 isoweek : 'isoWeek',
31245 weekyear : 'weekYear',
31246 isoweekyear : 'isoWeekYear'
31247 },
31248
31249 // format function strings
31250 formatFunctions = {},
31251
31252 // tokens to ordinalize and pad
31253 ordinalizeTokens = 'DDD w W M D d'.split(' '),
31254 paddedTokens = 'M D H h m s w W'.split(' '),
31255
31256 formatTokenFunctions = {
31257 M : function () {
31258 return this.month() + 1;
31259 },
31260 MMM : function (format) {
31261 return this.lang().monthsShort(this, format);
31262 },
31263 MMMM : function (format) {
31264 return this.lang().months(this, format);
31265 },
31266 D : function () {
31267 return this.date();
31268 },
31269 DDD : function () {
31270 return this.dayOfYear();
31271 },
31272 d : function () {
31273 return this.day();
31274 },
31275 dd : function (format) {
31276 return this.lang().weekdaysMin(this, format);
31277 },
31278 ddd : function (format) {
31279 return this.lang().weekdaysShort(this, format);
31280 },
31281 dddd : function (format) {
31282 return this.lang().weekdays(this, format);
31283 },
31284 w : function () {
31285 return this.week();
31286 },
31287 W : function () {
31288 return this.isoWeek();
31289 },
31290 YY : function () {
31291 return leftZeroFill(this.year() % 100, 2);
31292 },
31293 YYYY : function () {
31294 return leftZeroFill(this.year(), 4);
31295 },
31296 YYYYY : function () {
31297 return leftZeroFill(this.year(), 5);
31298 },
31299 YYYYYY : function () {
31300 var y = this.year(), sign = y >= 0 ? '+' : '-';
31301 return sign + leftZeroFill(Math.abs(y), 6);
31302 },
31303 gg : function () {
31304 return leftZeroFill(this.weekYear() % 100, 2);
31305 },
31306 gggg : function () {
31307 return leftZeroFill(this.weekYear(), 4);
31308 },
31309 ggggg : function () {
31310 return leftZeroFill(this.weekYear(), 5);
31311 },
31312 GG : function () {
31313 return leftZeroFill(this.isoWeekYear() % 100, 2);
31314 },
31315 GGGG : function () {
31316 return leftZeroFill(this.isoWeekYear(), 4);
31317 },
31318 GGGGG : function () {
31319 return leftZeroFill(this.isoWeekYear(), 5);
31320 },
31321 e : function () {
31322 return this.weekday();
31323 },
31324 E : function () {
31325 return this.isoWeekday();
31326 },
31327 a : function () {
31328 return this.lang().meridiem(this.hours(), this.minutes(), true);
31329 },
31330 A : function () {
31331 return this.lang().meridiem(this.hours(), this.minutes(), false);
31332 },
31333 H : function () {
31334 return this.hours();
31335 },
31336 h : function () {
31337 return this.hours() % 12 || 12;
31338 },
31339 m : function () {
31340 return this.minutes();
31341 },
31342 s : function () {
31343 return this.seconds();
31344 },
31345 S : function () {
31346 return toInt(this.milliseconds() / 100);
31347 },
31348 SS : function () {
31349 return leftZeroFill(toInt(this.milliseconds() / 10), 2);
31350 },
31351 SSS : function () {
31352 return leftZeroFill(this.milliseconds(), 3);
31353 },
31354 SSSS : function () {
31355 return leftZeroFill(this.milliseconds(), 3);
31356 },
31357 Z : function () {
31358 var a = -this.zone(),
31359 b = "+";
31360 if (a < 0) {
31361 a = -a;
31362 b = "-";
31363 }
31364 return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2);
31365 },
31366 ZZ : function () {
31367 var a = -this.zone(),
31368 b = "+";
31369 if (a < 0) {
31370 a = -a;
31371 b = "-";
31372 }
31373 return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2);
31374 },
31375 z : function () {
31376 return this.zoneAbbr();
31377 },
31378 zz : function () {
31379 return this.zoneName();
31380 },
31381 X : function () {
31382 return this.unix();
31383 },
31384 Q : function () {
31385 return this.quarter();
31386 }
31387 },
31388
31389 lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin'];
31390
31391 function defaultParsingFlags() {
31392 // We need to deep clone this object, and es5 standard is not very
31393 // helpful.
31394 return {
31395 empty : false,
31396 unusedTokens : [],
31397 unusedInput : [],
31398 overflow : -2,
31399 charsLeftOver : 0,
31400 nullInput : false,
31401 invalidMonth : null,
31402 invalidFormat : false,
31403 userInvalidated : false,
31404 iso: false
31405 };
31406 }
31407
31408 function padToken(func, count) {
31409 return function (a) {
31410 return leftZeroFill(func.call(this, a), count);
31411 };
31412 }
31413 function ordinalizeToken(func, period) {
31414 return function (a) {
31415 return this.lang().ordinal(func.call(this, a), period);
31416 };
31417 }
31418
31419 while (ordinalizeTokens.length) {
31420 i = ordinalizeTokens.pop();
31421 formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i);
31422 }
31423 while (paddedTokens.length) {
31424 i = paddedTokens.pop();
31425 formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
31426 }
31427 formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
31428
31429
31430 /************************************
31431 Constructors
31432 ************************************/
31433
31434 function Language() {
31435
31436 }
31437
31438 // Moment prototype object
31439 function Moment(config) {
31440 checkOverflow(config);
31441 extend(this, config);
31442 }
31443
31444 // Duration Constructor
31445 function Duration(duration) {
31446 var normalizedInput = normalizeObjectUnits(duration),
31447 years = normalizedInput.year || 0,
31448 months = normalizedInput.month || 0,
31449 weeks = normalizedInput.week || 0,
31450 days = normalizedInput.day || 0,
31451 hours = normalizedInput.hour || 0,
31452 minutes = normalizedInput.minute || 0,
31453 seconds = normalizedInput.second || 0,
31454 milliseconds = normalizedInput.millisecond || 0;
31455
31456 // representation for dateAddRemove
31457 this._milliseconds = +milliseconds +
31458 seconds * 1e3 + // 1000
31459 minutes * 6e4 + // 1000 * 60
31460 hours * 36e5; // 1000 * 60 * 60
31461 // Because of dateAddRemove treats 24 hours as different from a
31462 // day when working around DST, we need to store them separately
31463 this._days = +days +
31464 weeks * 7;
31465 // It is impossible translate months into days without knowing
31466 // which months you are are talking about, so we have to store
31467 // it separately.
31468 this._months = +months +
31469 years * 12;
31470
31471 this._data = {};
31472
31473 this._bubble();
31474 }
31475
31476 /************************************
31477 Helpers
31478 ************************************/
31479
31480
31481 function extend(a, b) {
31482 for (var i in b) {
31483 if (b.hasOwnProperty(i)) {
31484 a[i] = b[i];
31485 }
31486 }
31487
31488 if (b.hasOwnProperty("toString")) {
31489 a.toString = b.toString;
31490 }
31491
31492 if (b.hasOwnProperty("valueOf")) {
31493 a.valueOf = b.valueOf;
31494 }
31495
31496 return a;
31497 }
31498
31499 function cloneMoment(m) {
31500 var result = {}, i;
31501 for (i in m) {
31502 if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) {
31503 result[i] = m[i];
31504 }
31505 }
31506
31507 return result;
31508 }
31509
31510 function absRound(number) {
31511 if (number < 0) {
31512 return Math.ceil(number);
31513 } else {
31514 return Math.floor(number);
31515 }
31516 }
31517
31518 // left zero fill a number
31519 // see http://jsperf.com/left-zero-filling for performance comparison
31520 function leftZeroFill(number, targetLength, forceSign) {
31521 var output = '' + Math.abs(number),
31522 sign = number >= 0;
31523
31524 while (output.length < targetLength) {
31525 output = '0' + output;
31526 }
31527 return (sign ? (forceSign ? '+' : '') : '-') + output;
31528 }
31529
31530 // helper function for _.addTime and _.subtractTime
31531 function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) {
31532 var milliseconds = duration._milliseconds,
31533 days = duration._days,
31534 months = duration._months,
31535 minutes,
31536 hours;
31537
31538 if (milliseconds) {
31539 mom._d.setTime(+mom._d + milliseconds * isAdding);
31540 }
31541 // store the minutes and hours so we can restore them
31542 if (days || months) {
31543 minutes = mom.minute();
31544 hours = mom.hour();
31545 }
31546 if (days) {
31547 mom.date(mom.date() + days * isAdding);
31548 }
31549 if (months) {
31550 mom.month(mom.month() + months * isAdding);
31551 }
31552 if (milliseconds && !ignoreUpdateOffset) {
31553 moment.updateOffset(mom);
31554 }
31555 // restore the minutes and hours after possibly changing dst
31556 if (days || months) {
31557 mom.minute(minutes);
31558 mom.hour(hours);
31559 }
31560 }
31561
31562 // check if is an array
31563 function isArray(input) {
31564 return Object.prototype.toString.call(input) === '[object Array]';
31565 }
31566
31567 function isDate(input) {
31568 return Object.prototype.toString.call(input) === '[object Date]' ||
31569 input instanceof Date;
31570 }
31571
31572 // compare two arrays, return the number of differences
31573 function compareArrays(array1, array2, dontConvert) {
31574 var len = Math.min(array1.length, array2.length),
31575 lengthDiff = Math.abs(array1.length - array2.length),
31576 diffs = 0,
31577 i;
31578 for (i = 0; i < len; i++) {
31579 if ((dontConvert && array1[i] !== array2[i]) ||
31580 (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
31581 diffs++;
31582 }
31583 }
31584 return diffs + lengthDiff;
31585 }
31586
31587 function normalizeUnits(units) {
31588 if (units) {
31589 var lowered = units.toLowerCase().replace(/(.)s$/, '$1');
31590 units = unitAliases[units] || camelFunctions[lowered] || lowered;
31591 }
31592 return units;
31593 }
31594
31595 function normalizeObjectUnits(inputObject) {
31596 var normalizedInput = {},
31597 normalizedProp,
31598 prop;
31599
31600 for (prop in inputObject) {
31601 if (inputObject.hasOwnProperty(prop)) {
31602 normalizedProp = normalizeUnits(prop);
31603 if (normalizedProp) {
31604 normalizedInput[normalizedProp] = inputObject[prop];
31605 }
31606 }
31607 }
31608
31609 return normalizedInput;
31610 }
31611
31612 function makeList(field) {
31613 var count, setter;
31614
31615 if (field.indexOf('week') === 0) {
31616 count = 7;
31617 setter = 'day';
31618 }
31619 else if (field.indexOf('month') === 0) {
31620 count = 12;
31621 setter = 'month';
31622 }
31623 else {
31624 return;
31625 }
31626
31627 moment[field] = function (format, index) {
31628 var i, getter,
31629 method = moment.fn._lang[field],
31630 results = [];
31631
31632 if (typeof format === 'number') {
31633 index = format;
31634 format = undefined;
31635 }
31636
31637 getter = function (i) {
31638 var m = moment().utc().set(setter, i);
31639 return method.call(moment.fn._lang, m, format || '');
31640 };
31641
31642 if (index != null) {
31643 return getter(index);
31644 }
31645 else {
31646 for (i = 0; i < count; i++) {
31647 results.push(getter(i));
31648 }
31649 return results;
31650 }
31651 };
31652 }
31653
31654 function toInt(argumentForCoercion) {
31655 var coercedNumber = +argumentForCoercion,
31656 value = 0;
31657
31658 if (coercedNumber !== 0 && isFinite(coercedNumber)) {
31659 if (coercedNumber >= 0) {
31660 value = Math.floor(coercedNumber);
31661 } else {
31662 value = Math.ceil(coercedNumber);
31663 }
31664 }
31665
31666 return value;
31667 }
31668
31669 function daysInMonth(year, month) {
31670 return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
31671 }
31672
31673 function daysInYear(year) {
31674 return isLeapYear(year) ? 366 : 365;
31675 }
31676
31677 function isLeapYear(year) {
31678 return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
31679 }
31680
31681 function checkOverflow(m) {
31682 var overflow;
31683 if (m._a && m._pf.overflow === -2) {
31684 overflow =
31685 m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH :
31686 m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE :
31687 m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR :
31688 m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE :
31689 m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND :
31690 m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND :
31691 -1;
31692
31693 if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
31694 overflow = DATE;
31695 }
31696
31697 m._pf.overflow = overflow;
31698 }
31699 }
31700
31701 function isValid(m) {
31702 if (m._isValid == null) {
31703 m._isValid = !isNaN(m._d.getTime()) &&
31704 m._pf.overflow < 0 &&
31705 !m._pf.empty &&
31706 !m._pf.invalidMonth &&
31707 !m._pf.nullInput &&
31708 !m._pf.invalidFormat &&
31709 !m._pf.userInvalidated;
31710
31711 if (m._strict) {
31712 m._isValid = m._isValid &&
31713 m._pf.charsLeftOver === 0 &&
31714 m._pf.unusedTokens.length === 0;
31715 }
31716 }
31717 return m._isValid;
31718 }
31719
31720 function normalizeLanguage(key) {
31721 return key ? key.toLowerCase().replace('_', '-') : key;
31722 }
31723
31724 // Return a moment from input, that is local/utc/zone equivalent to model.
31725 function makeAs(input, model) {
31726 return model._isUTC ? moment(input).zone(model._offset || 0) :
31727 moment(input).local();
31728 }
31729
31730 /************************************
31731 Languages
31732 ************************************/
31733
31734
31735 extend(Language.prototype, {
31736
31737 set : function (config) {
31738 var prop, i;
31739 for (i in config) {
31740 prop = config[i];
31741 if (typeof prop === 'function') {
31742 this[i] = prop;
31743 } else {
31744 this['_' + i] = prop;
31745 }
31746 }
31747 },
31748
31749 _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
31750 months : function (m) {
31751 return this._months[m.month()];
31752 },
31753
31754 _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
31755 monthsShort : function (m) {
31756 return this._monthsShort[m.month()];
31757 },
31758
31759 monthsParse : function (monthName) {
31760 var i, mom, regex;
31761
31762 if (!this._monthsParse) {
31763 this._monthsParse = [];
31764 }
31765
31766 for (i = 0; i < 12; i++) {
31767 // make the regex if we don't have it already
31768 if (!this._monthsParse[i]) {
31769 mom = moment.utc([2000, i]);
31770 regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
31771 this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
31772 }
31773 // test the regex
31774 if (this._monthsParse[i].test(monthName)) {
31775 return i;
31776 }
31777 }
31778 },
31779
31780 _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
31781 weekdays : function (m) {
31782 return this._weekdays[m.day()];
31783 },
31784
31785 _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
31786 weekdaysShort : function (m) {
31787 return this._weekdaysShort[m.day()];
31788 },
31789
31790 _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
31791 weekdaysMin : function (m) {
31792 return this._weekdaysMin[m.day()];
31793 },
31794
31795 weekdaysParse : function (weekdayName) {
31796 var i, mom, regex;
31797
31798 if (!this._weekdaysParse) {
31799 this._weekdaysParse = [];
31800 }
31801
31802 for (i = 0; i < 7; i++) {
31803 // make the regex if we don't have it already
31804 if (!this._weekdaysParse[i]) {
31805 mom = moment([2000, 1]).day(i);
31806 regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
31807 this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
31808 }
31809 // test the regex
31810 if (this._weekdaysParse[i].test(weekdayName)) {
31811 return i;
31812 }
31813 }
31814 },
31815
31816 _longDateFormat : {
31817 LT : "h:mm A",
31818 L : "MM/DD/YYYY",
31819 LL : "MMMM D YYYY",
31820 LLL : "MMMM D YYYY LT",
31821 LLLL : "dddd, MMMM D YYYY LT"
31822 },
31823 longDateFormat : function (key) {
31824 var output = this._longDateFormat[key];
31825 if (!output && this._longDateFormat[key.toUpperCase()]) {
31826 output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
31827 return val.slice(1);
31828 });
31829 this._longDateFormat[key] = output;
31830 }
31831 return output;
31832 },
31833
31834 isPM : function (input) {
31835 // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
31836 // Using charAt should be more compatible.
31837 return ((input + '').toLowerCase().charAt(0) === 'p');
31838 },
31839
31840 _meridiemParse : /[ap]\.?m?\.?/i,
31841 meridiem : function (hours, minutes, isLower) {
31842 if (hours > 11) {
31843 return isLower ? 'pm' : 'PM';
31844 } else {
31845 return isLower ? 'am' : 'AM';
31846 }
31847 },
31848
31849 _calendar : {
31850 sameDay : '[Today at] LT',
31851 nextDay : '[Tomorrow at] LT',
31852 nextWeek : 'dddd [at] LT',
31853 lastDay : '[Yesterday at] LT',
31854 lastWeek : '[Last] dddd [at] LT',
31855 sameElse : 'L'
31856 },
31857 calendar : function (key, mom) {
31858 var output = this._calendar[key];
31859 return typeof output === 'function' ? output.apply(mom) : output;
31860 },
31861
31862 _relativeTime : {
31863 future : "in %s",
31864 past : "%s ago",
31865 s : "a few seconds",
31866 m : "a minute",
31867 mm : "%d minutes",
31868 h : "an hour",
31869 hh : "%d hours",
31870 d : "a day",
31871 dd : "%d days",
31872 M : "a month",
31873 MM : "%d months",
31874 y : "a year",
31875 yy : "%d years"
31876 },
31877 relativeTime : function (number, withoutSuffix, string, isFuture) {
31878 var output = this._relativeTime[string];
31879 return (typeof output === 'function') ?
31880 output(number, withoutSuffix, string, isFuture) :
31881 output.replace(/%d/i, number);
31882 },
31883 pastFuture : function (diff, output) {
31884 var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
31885 return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
31886 },
31887
31888 ordinal : function (number) {
31889 return this._ordinal.replace("%d", number);
31890 },
31891 _ordinal : "%d",
31892
31893 preparse : function (string) {
31894 return string;
31895 },
31896
31897 postformat : function (string) {
31898 return string;
31899 },
31900
31901 week : function (mom) {
31902 return weekOfYear(mom, this._week.dow, this._week.doy).week;
31903 },
31904
31905 _week : {
31906 dow : 0, // Sunday is the first day of the week.
31907 doy : 6 // The week that contains Jan 1st is the first week of the year.
31908 },
31909
31910 _invalidDate: 'Invalid date',
31911 invalidDate: function () {
31912 return this._invalidDate;
31913 }
31914 });
31915
31916 // Loads a language definition into the `languages` cache. The function
31917 // takes a key and optionally values. If not in the browser and no values
31918 // are provided, it will load the language file module. As a convenience,
31919 // this function also returns the language values.
31920 function loadLang(key, values) {
31921 values.abbr = key;
31922 if (!languages[key]) {
31923 languages[key] = new Language();
31924 }
31925 languages[key].set(values);
31926 return languages[key];
31927 }
31928
31929 // Remove a language from the `languages` cache. Mostly useful in tests.
31930 function unloadLang(key) {
31931 delete languages[key];
31932 }
31933
31934 // Determines which language definition to use and returns it.
31935 //
31936 // With no parameters, it will return the global language. If you
31937 // pass in a language key, such as 'en', it will return the
31938 // definition for 'en', so long as 'en' has already been loaded using
31939 // moment.lang.
31940 function getLangDefinition(key) {
31941 var i = 0, j, lang, next, split,
31942 get = function (k) {
31943 if (!languages[k] && hasModule) {
31944 try {
31945 require('./lang/' + k);
31946 } catch (e) { }
31947 }
31948 return languages[k];
31949 };
31950
31951 if (!key) {
31952 return moment.fn._lang;
31953 }
31954
31955 if (!isArray(key)) {
31956 //short-circuit everything else
31957 lang = get(key);
31958 if (lang) {
31959 return lang;
31960 }
31961 key = [key];
31962 }
31963
31964 //pick the language from the array
31965 //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
31966 //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
31967 while (i < key.length) {
31968 split = normalizeLanguage(key[i]).split('-');
31969 j = split.length;
31970 next = normalizeLanguage(key[i + 1]);
31971 next = next ? next.split('-') : null;
31972 while (j > 0) {
31973 lang = get(split.slice(0, j).join('-'));
31974 if (lang) {
31975 return lang;
31976 }
31977 if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
31978 //the next array item is better than a shallower substring of this one
31979 break;
31980 }
31981 j--;
31982 }
31983 i++;
31984 }
31985 return moment.fn._lang;
31986 }
31987
31988 /************************************
31989 Formatting
31990 ************************************/
31991
31992
31993 function removeFormattingTokens(input) {
31994 if (input.match(/\[[\s\S]/)) {
31995 return input.replace(/^\[|\]$/g, "");
31996 }
31997 return input.replace(/\\/g, "");
31998 }
31999
32000 function makeFormatFunction(format) {
32001 var array = format.match(formattingTokens), i, length;
32002
32003 for (i = 0, length = array.length; i < length; i++) {
32004 if (formatTokenFunctions[array[i]]) {
32005 array[i] = formatTokenFunctions[array[i]];
32006 } else {
32007 array[i] = removeFormattingTokens(array[i]);
32008 }
32009 }
32010
32011 return function (mom) {
32012 var output = "";
32013 for (i = 0; i < length; i++) {
32014 output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
32015 }
32016 return output;
32017 };
32018 }
32019
32020 // format date using native date object
32021 function formatMoment(m, format) {
32022
32023 if (!m.isValid()) {
32024 return m.lang().invalidDate();
32025 }
32026
32027 format = expandFormat(format, m.lang());
32028
32029 if (!formatFunctions[format]) {
32030 formatFunctions[format] = makeFormatFunction(format);
32031 }
32032
32033 return formatFunctions[format](m);
32034 }
32035
32036 function expandFormat(format, lang) {
32037 var i = 5;
32038
32039 function replaceLongDateFormatTokens(input) {
32040 return lang.longDateFormat(input) || input;
32041 }
32042
32043 localFormattingTokens.lastIndex = 0;
32044 while (i >= 0 && localFormattingTokens.test(format)) {
32045 format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
32046 localFormattingTokens.lastIndex = 0;
32047 i -= 1;
32048 }
32049
32050 return format;
32051 }
32052
32053
32054 /************************************
32055 Parsing
32056 ************************************/
32057
32058
32059 // get the regex to find the next token
32060 function getParseRegexForToken(token, config) {
32061 var a, strict = config._strict;
32062 switch (token) {
32063 case 'DDDD':
32064 return parseTokenThreeDigits;
32065 case 'YYYY':
32066 case 'GGGG':
32067 case 'gggg':
32068 return strict ? parseTokenFourDigits : parseTokenOneToFourDigits;
32069 case 'Y':
32070 case 'G':
32071 case 'g':
32072 return parseTokenSignedNumber;
32073 case 'YYYYYY':
32074 case 'YYYYY':
32075 case 'GGGGG':
32076 case 'ggggg':
32077 return strict ? parseTokenSixDigits : parseTokenOneToSixDigits;
32078 case 'S':
32079 if (strict) { return parseTokenOneDigit; }
32080 /* falls through */
32081 case 'SS':
32082 if (strict) { return parseTokenTwoDigits; }
32083 /* falls through */
32084 case 'SSS':
32085 if (strict) { return parseTokenThreeDigits; }
32086 /* falls through */
32087 case 'DDD':
32088 return parseTokenOneToThreeDigits;
32089 case 'MMM':
32090 case 'MMMM':
32091 case 'dd':
32092 case 'ddd':
32093 case 'dddd':
32094 return parseTokenWord;
32095 case 'a':
32096 case 'A':
32097 return getLangDefinition(config._l)._meridiemParse;
32098 case 'X':
32099 return parseTokenTimestampMs;
32100 case 'Z':
32101 case 'ZZ':
32102 return parseTokenTimezone;
32103 case 'T':
32104 return parseTokenT;
32105 case 'SSSS':
32106 return parseTokenDigits;
32107 case 'MM':
32108 case 'DD':
32109 case 'YY':
32110 case 'GG':
32111 case 'gg':
32112 case 'HH':
32113 case 'hh':
32114 case 'mm':
32115 case 'ss':
32116 case 'ww':
32117 case 'WW':
32118 return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits;
32119 case 'M':
32120 case 'D':
32121 case 'd':
32122 case 'H':
32123 case 'h':
32124 case 'm':
32125 case 's':
32126 case 'w':
32127 case 'W':
32128 case 'e':
32129 case 'E':
32130 return parseTokenOneOrTwoDigits;
32131 default :
32132 a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i"));
32133 return a;
32134 }
32135 }
32136
32137 function timezoneMinutesFromString(string) {
32138 string = string || "";
32139 var possibleTzMatches = (string.match(parseTokenTimezone) || []),
32140 tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [],
32141 parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0],
32142 minutes = +(parts[1] * 60) + toInt(parts[2]);
32143
32144 return parts[0] === '+' ? -minutes : minutes;
32145 }
32146
32147 // function to convert string input to date
32148 function addTimeToArrayFromToken(token, input, config) {
32149 var a, datePartArray = config._a;
32150
32151 switch (token) {
32152 // MONTH
32153 case 'M' : // fall through to MM
32154 case 'MM' :
32155 if (input != null) {
32156 datePartArray[MONTH] = toInt(input) - 1;
32157 }
32158 break;
32159 case 'MMM' : // fall through to MMMM
32160 case 'MMMM' :
32161 a = getLangDefinition(config._l).monthsParse(input);
32162 // if we didn't find a month name, mark the date as invalid.
32163 if (a != null) {
32164 datePartArray[MONTH] = a;
32165 } else {
32166 config._pf.invalidMonth = input;
32167 }
32168 break;
32169 // DAY OF MONTH
32170 case 'D' : // fall through to DD
32171 case 'DD' :
32172 if (input != null) {
32173 datePartArray[DATE] = toInt(input);
32174 }
32175 break;
32176 // DAY OF YEAR
32177 case 'DDD' : // fall through to DDDD
32178 case 'DDDD' :
32179 if (input != null) {
32180 config._dayOfYear = toInt(input);
32181 }
32182
32183 break;
32184 // YEAR
32185 case 'YY' :
32186 datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
32187 break;
32188 case 'YYYY' :
32189 case 'YYYYY' :
32190 case 'YYYYYY' :
32191 datePartArray[YEAR] = toInt(input);
32192 break;
32193 // AM / PM
32194 case 'a' : // fall through to A
32195 case 'A' :
32196 config._isPm = getLangDefinition(config._l).isPM(input);
32197 break;
32198 // 24 HOUR
32199 case 'H' : // fall through to hh
32200 case 'HH' : // fall through to hh
32201 case 'h' : // fall through to hh
32202 case 'hh' :
32203 datePartArray[HOUR] = toInt(input);
32204 break;
32205 // MINUTE
32206 case 'm' : // fall through to mm
32207 case 'mm' :
32208 datePartArray[MINUTE] = toInt(input);
32209 break;
32210 // SECOND
32211 case 's' : // fall through to ss
32212 case 'ss' :
32213 datePartArray[SECOND] = toInt(input);
32214 break;
32215 // MILLISECOND
32216 case 'S' :
32217 case 'SS' :
32218 case 'SSS' :
32219 case 'SSSS' :
32220 datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000);
32221 break;
32222 // UNIX TIMESTAMP WITH MS
32223 case 'X':
32224 config._d = new Date(parseFloat(input) * 1000);
32225 break;
32226 // TIMEZONE
32227 case 'Z' : // fall through to ZZ
32228 case 'ZZ' :
32229 config._useUTC = true;
32230 config._tzm = timezoneMinutesFromString(input);
32231 break;
32232 case 'w':
32233 case 'ww':
32234 case 'W':
32235 case 'WW':
32236 case 'd':
32237 case 'dd':
32238 case 'ddd':
32239 case 'dddd':
32240 case 'e':
32241 case 'E':
32242 token = token.substr(0, 1);
32243 /* falls through */
32244 case 'gg':
32245 case 'gggg':
32246 case 'GG':
32247 case 'GGGG':
32248 case 'GGGGG':
32249 token = token.substr(0, 2);
32250 if (input) {
32251 config._w = config._w || {};
32252 config._w[token] = input;
32253 }
32254 break;
32255 }
32256 }
32257
32258 // convert an array to a date.
32259 // the array should mirror the parameters below
32260 // note: all values past the year are optional and will default to the lowest possible value.
32261 // [year, month, day , hour, minute, second, millisecond]
32262 function dateFromConfig(config) {
32263 var i, date, input = [], currentDate,
32264 yearToUse, fixYear, w, temp, lang, weekday, week;
32265
32266 if (config._d) {
32267 return;
32268 }
32269
32270 currentDate = currentDateArray(config);
32271
32272 //compute day of the year from weeks and weekdays
32273 if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
32274 fixYear = function (val) {
32275 var int_val = parseInt(val, 10);
32276 return val ?
32277 (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) :
32278 (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
32279 };
32280
32281 w = config._w;
32282 if (w.GG != null || w.W != null || w.E != null) {
32283 temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1);
32284 }
32285 else {
32286 lang = getLangDefinition(config._l);
32287 weekday = w.d != null ? parseWeekday(w.d, lang) :
32288 (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0);
32289
32290 week = parseInt(w.w, 10) || 1;
32291
32292 //if we're parsing 'd', then the low day numbers may be next week
32293 if (w.d != null && weekday < lang._week.dow) {
32294 week++;
32295 }
32296
32297 temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow);
32298 }
32299
32300 config._a[YEAR] = temp.year;
32301 config._dayOfYear = temp.dayOfYear;
32302 }
32303
32304 //if the day of the year is set, figure out what it is
32305 if (config._dayOfYear) {
32306 yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR];
32307
32308 if (config._dayOfYear > daysInYear(yearToUse)) {
32309 config._pf._overflowDayOfYear = true;
32310 }
32311
32312 date = makeUTCDate(yearToUse, 0, config._dayOfYear);
32313 config._a[MONTH] = date.getUTCMonth();
32314 config._a[DATE] = date.getUTCDate();
32315 }
32316
32317 // Default to current date.
32318 // * if no year, month, day of month are given, default to today
32319 // * if day of month is given, default month and year
32320 // * if month is given, default only year
32321 // * if year is given, don't default anything
32322 for (i = 0; i < 3 && config._a[i] == null; ++i) {
32323 config._a[i] = input[i] = currentDate[i];
32324 }
32325
32326 // Zero out whatever was not defaulted, including time
32327 for (; i < 7; i++) {
32328 config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
32329 }
32330
32331 // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
32332 input[HOUR] += toInt((config._tzm || 0) / 60);
32333 input[MINUTE] += toInt((config._tzm || 0) % 60);
32334
32335 config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input);
32336 }
32337
32338 function dateFromObject(config) {
32339 var normalizedInput;
32340
32341 if (config._d) {
32342 return;
32343 }
32344
32345 normalizedInput = normalizeObjectUnits(config._i);
32346 config._a = [
32347 normalizedInput.year,
32348 normalizedInput.month,
32349 normalizedInput.day,
32350 normalizedInput.hour,
32351 normalizedInput.minute,
32352 normalizedInput.second,
32353 normalizedInput.millisecond
32354 ];
32355
32356 dateFromConfig(config);
32357 }
32358
32359 function currentDateArray(config) {
32360 var now = new Date();
32361 if (config._useUTC) {
32362 return [
32363 now.getUTCFullYear(),
32364 now.getUTCMonth(),
32365 now.getUTCDate()
32366 ];
32367 } else {
32368 return [now.getFullYear(), now.getMonth(), now.getDate()];
32369 }
32370 }
32371
32372 // date from string and format string
32373 function makeDateFromStringAndFormat(config) {
32374
32375 config._a = [];
32376 config._pf.empty = true;
32377
32378 // This array is used to make a Date, either with `new Date` or `Date.UTC`
32379 var lang = getLangDefinition(config._l),
32380 string = '' + config._i,
32381 i, parsedInput, tokens, token, skipped,
32382 stringLength = string.length,
32383 totalParsedInputLength = 0;
32384
32385 tokens = expandFormat(config._f, lang).match(formattingTokens) || [];
32386
32387 for (i = 0; i < tokens.length; i++) {
32388 token = tokens[i];
32389 parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
32390 if (parsedInput) {
32391 skipped = string.substr(0, string.indexOf(parsedInput));
32392 if (skipped.length > 0) {
32393 config._pf.unusedInput.push(skipped);
32394 }
32395 string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
32396 totalParsedInputLength += parsedInput.length;
32397 }
32398 // don't parse if it's not a known token
32399 if (formatTokenFunctions[token]) {
32400 if (parsedInput) {
32401 config._pf.empty = false;
32402 }
32403 else {
32404 config._pf.unusedTokens.push(token);
32405 }
32406 addTimeToArrayFromToken(token, parsedInput, config);
32407 }
32408 else if (config._strict && !parsedInput) {
32409 config._pf.unusedTokens.push(token);
32410 }
32411 }
32412
32413 // add remaining unparsed input length to the string
32414 config._pf.charsLeftOver = stringLength - totalParsedInputLength;
32415 if (string.length > 0) {
32416 config._pf.unusedInput.push(string);
32417 }
32418
32419 // handle am pm
32420 if (config._isPm && config._a[HOUR] < 12) {
32421 config._a[HOUR] += 12;
32422 }
32423 // if is 12 am, change hours to 0
32424 if (config._isPm === false && config._a[HOUR] === 12) {
32425 config._a[HOUR] = 0;
32426 }
32427
32428 dateFromConfig(config);
32429 checkOverflow(config);
32430 }
32431
32432 function unescapeFormat(s) {
32433 return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
32434 return p1 || p2 || p3 || p4;
32435 });
32436 }
32437
32438 // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
32439 function regexpEscape(s) {
32440 return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
32441 }
32442
32443 // date from string and array of format strings
32444 function makeDateFromStringAndArray(config) {
32445 var tempConfig,
32446 bestMoment,
32447
32448 scoreToBeat,
32449 i,
32450 currentScore;
32451
32452 if (config._f.length === 0) {
32453 config._pf.invalidFormat = true;
32454 config._d = new Date(NaN);
32455 return;
32456 }
32457
32458 for (i = 0; i < config._f.length; i++) {
32459 currentScore = 0;
32460 tempConfig = extend({}, config);
32461 tempConfig._pf = defaultParsingFlags();
32462 tempConfig._f = config._f[i];
32463 makeDateFromStringAndFormat(tempConfig);
32464
32465 if (!isValid(tempConfig)) {
32466 continue;
32467 }
32468
32469 // if there is any input that was not parsed add a penalty for that format
32470 currentScore += tempConfig._pf.charsLeftOver;
32471
32472 //or tokens
32473 currentScore += tempConfig._pf.unusedTokens.length * 10;
32474
32475 tempConfig._pf.score = currentScore;
32476
32477 if (scoreToBeat == null || currentScore < scoreToBeat) {
32478 scoreToBeat = currentScore;
32479 bestMoment = tempConfig;
32480 }
32481 }
32482
32483 extend(config, bestMoment || tempConfig);
32484 }
32485
32486 // date from iso format
32487 function makeDateFromString(config) {
32488 var i, l,
32489 string = config._i,
32490 match = isoRegex.exec(string);
32491
32492 if (match) {
32493 config._pf.iso = true;
32494 for (i = 0, l = isoDates.length; i < l; i++) {
32495 if (isoDates[i][1].exec(string)) {
32496 // match[5] should be "T" or undefined
32497 config._f = isoDates[i][0] + (match[6] || " ");
32498 break;
32499 }
32500 }
32501 for (i = 0, l = isoTimes.length; i < l; i++) {
32502 if (isoTimes[i][1].exec(string)) {
32503 config._f += isoTimes[i][0];
32504 break;
32505 }
32506 }
32507 if (string.match(parseTokenTimezone)) {
32508 config._f += "Z";
32509 }
32510 makeDateFromStringAndFormat(config);
32511 }
32512 else {
32513 config._d = new Date(string);
32514 }
32515 }
32516
32517 function makeDateFromInput(config) {
32518 var input = config._i,
32519 matched = aspNetJsonRegex.exec(input);
32520
32521 if (input === undefined) {
32522 config._d = new Date();
32523 } else if (matched) {
32524 config._d = new Date(+matched[1]);
32525 } else if (typeof input === 'string') {
32526 makeDateFromString(config);
32527 } else if (isArray(input)) {
32528 config._a = input.slice(0);
32529 dateFromConfig(config);
32530 } else if (isDate(input)) {
32531 config._d = new Date(+input);
32532 } else if (typeof(input) === 'object') {
32533 dateFromObject(config);
32534 } else {
32535 config._d = new Date(input);
32536 }
32537 }
32538
32539 function makeDate(y, m, d, h, M, s, ms) {
32540 //can't just apply() to create a date:
32541 //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
32542 var date = new Date(y, m, d, h, M, s, ms);
32543
32544 //the date constructor doesn't accept years < 1970
32545 if (y < 1970) {
32546 date.setFullYear(y);
32547 }
32548 return date;
32549 }
32550
32551 function makeUTCDate(y) {
32552 var date = new Date(Date.UTC.apply(null, arguments));
32553 if (y < 1970) {
32554 date.setUTCFullYear(y);
32555 }
32556 return date;
32557 }
32558
32559 function parseWeekday(input, language) {
32560 if (typeof input === 'string') {
32561 if (!isNaN(input)) {
32562 input = parseInt(input, 10);
32563 }
32564 else {
32565 input = language.weekdaysParse(input);
32566 if (typeof input !== 'number') {
32567 return null;
32568 }
32569 }
32570 }
32571 return input;
32572 }
32573
32574 /************************************
32575 Relative Time
32576 ************************************/
32577
32578
32579 // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
32580 function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
32581 return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
32582 }
32583
32584 function relativeTime(milliseconds, withoutSuffix, lang) {
32585 var seconds = round(Math.abs(milliseconds) / 1000),
32586 minutes = round(seconds / 60),
32587 hours = round(minutes / 60),
32588 days = round(hours / 24),
32589 years = round(days / 365),
32590 args = seconds < 45 && ['s', seconds] ||
32591 minutes === 1 && ['m'] ||
32592 minutes < 45 && ['mm', minutes] ||
32593 hours === 1 && ['h'] ||
32594 hours < 22 && ['hh', hours] ||
32595 days === 1 && ['d'] ||
32596 days <= 25 && ['dd', days] ||
32597 days <= 45 && ['M'] ||
32598 days < 345 && ['MM', round(days / 30)] ||
32599 years === 1 && ['y'] || ['yy', years];
32600 args[2] = withoutSuffix;
32601 args[3] = milliseconds > 0;
32602 args[4] = lang;
32603 return substituteTimeAgo.apply({}, args);
32604 }
32605
32606
32607 /************************************
32608 Week of Year
32609 ************************************/
32610
32611
32612 // firstDayOfWeek 0 = sun, 6 = sat
32613 // the day of the week that starts the week
32614 // (usually sunday or monday)
32615 // firstDayOfWeekOfYear 0 = sun, 6 = sat
32616 // the first week is the week that contains the first
32617 // of this day of the week
32618 // (eg. ISO weeks use thursday (4))
32619 function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
32620 var end = firstDayOfWeekOfYear - firstDayOfWeek,
32621 daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(),
32622 adjustedMoment;
32623
32624
32625 if (daysToDayOfWeek > end) {
32626 daysToDayOfWeek -= 7;
32627 }
32628
32629 if (daysToDayOfWeek < end - 7) {
32630 daysToDayOfWeek += 7;
32631 }
32632
32633 adjustedMoment = moment(mom).add('d', daysToDayOfWeek);
32634 return {
32635 week: Math.ceil(adjustedMoment.dayOfYear() / 7),
32636 year: adjustedMoment.year()
32637 };
32638 }
32639
32640 //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
32641 function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
32642 var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
32643
32644 weekday = weekday != null ? weekday : firstDayOfWeek;
32645 daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0);
32646 dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1;
32647
32648 return {
32649 year: dayOfYear > 0 ? year : year - 1,
32650 dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear
32651 };
32652 }
32653
32654 /************************************
32655 Top Level Functions
32656 ************************************/
32657
32658 function makeMoment(config) {
32659 var input = config._i,
32660 format = config._f;
32661
32662 if (input === null) {
32663 return moment.invalid({nullInput: true});
32664 }
32665
32666 if (typeof input === 'string') {
32667 config._i = input = getLangDefinition().preparse(input);
32668 }
32669
32670 if (moment.isMoment(input)) {
32671 config = cloneMoment(input);
32672
32673 config._d = new Date(+input._d);
32674 } else if (format) {
32675 if (isArray(format)) {
32676 makeDateFromStringAndArray(config);
32677 } else {
32678 makeDateFromStringAndFormat(config);
32679 }
32680 } else {
32681 makeDateFromInput(config);
32682 }
32683
32684 return new Moment(config);
32685 }
32686
32687 moment = function (input, format, lang, strict) {
32688 var c;
32689
32690 if (typeof(lang) === "boolean") {
32691 strict = lang;
32692 lang = undefined;
32693 }
32694 // object construction must be done this way.
32695 // https://github.com/moment/moment/issues/1423
32696 c = {};
32697 c._isAMomentObject = true;
32698 c._i = input;
32699 c._f = format;
32700 c._l = lang;
32701 c._strict = strict;
32702 c._isUTC = false;
32703 c._pf = defaultParsingFlags();
32704
32705 return makeMoment(c);
32706 };
32707
32708 // creating with utc
32709 moment.utc = function (input, format, lang, strict) {
32710 var c;
32711
32712 if (typeof(lang) === "boolean") {
32713 strict = lang;
32714 lang = undefined;
32715 }
32716 // object construction must be done this way.
32717 // https://github.com/moment/moment/issues/1423
32718 c = {};
32719 c._isAMomentObject = true;
32720 c._useUTC = true;
32721 c._isUTC = true;
32722 c._l = lang;
32723 c._i = input;
32724 c._f = format;
32725 c._strict = strict;
32726 c._pf = defaultParsingFlags();
32727
32728 return makeMoment(c).utc();
32729 };
32730
32731 // creating with unix timestamp (in seconds)
32732 moment.unix = function (input) {
32733 return moment(input * 1000);
32734 };
32735
32736 // duration
32737 moment.duration = function (input, key) {
32738 var duration = input,
32739 // matching against regexp is expensive, do it on demand
32740 match = null,
32741 sign,
32742 ret,
32743 parseIso;
32744
32745 if (moment.isDuration(input)) {
32746 duration = {
32747 ms: input._milliseconds,
32748 d: input._days,
32749 M: input._months
32750 };
32751 } else if (typeof input === 'number') {
32752 duration = {};
32753 if (key) {
32754 duration[key] = input;
32755 } else {
32756 duration.milliseconds = input;
32757 }
32758 } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) {
32759 sign = (match[1] === "-") ? -1 : 1;
32760 duration = {
32761 y: 0,
32762 d: toInt(match[DATE]) * sign,
32763 h: toInt(match[HOUR]) * sign,
32764 m: toInt(match[MINUTE]) * sign,
32765 s: toInt(match[SECOND]) * sign,
32766 ms: toInt(match[MILLISECOND]) * sign
32767 };
32768 } else if (!!(match = isoDurationRegex.exec(input))) {
32769 sign = (match[1] === "-") ? -1 : 1;
32770 parseIso = function (inp) {
32771 // We'd normally use ~~inp for this, but unfortunately it also
32772 // converts floats to ints.
32773 // inp may be undefined, so careful calling replace on it.
32774 var res = inp && parseFloat(inp.replace(',', '.'));
32775 // apply sign while we're at it
32776 return (isNaN(res) ? 0 : res) * sign;
32777 };
32778 duration = {
32779 y: parseIso(match[2]),
32780 M: parseIso(match[3]),
32781 d: parseIso(match[4]),
32782 h: parseIso(match[5]),
32783 m: parseIso(match[6]),
32784 s: parseIso(match[7]),
32785 w: parseIso(match[8])
32786 };
32787 }
32788
32789 ret = new Duration(duration);
32790
32791 if (moment.isDuration(input) && input.hasOwnProperty('_lang')) {
32792 ret._lang = input._lang;
32793 }
32794
32795 return ret;
32796 };
32797
32798 // version number
32799 moment.version = VERSION;
32800
32801 // default format
32802 moment.defaultFormat = isoFormat;
32803
32804 // This function will be called whenever a moment is mutated.
32805 // It is intended to keep the offset in sync with the timezone.
32806 moment.updateOffset = function () {};
32807
32808 // This function will load languages and then set the global language. If
32809 // no arguments are passed in, it will simply return the current global
32810 // language key.
32811 moment.lang = function (key, values) {
32812 var r;
32813 if (!key) {
32814 return moment.fn._lang._abbr;
32815 }
32816 if (values) {
32817 loadLang(normalizeLanguage(key), values);
32818 } else if (values === null) {
32819 unloadLang(key);
32820 key = 'en';
32821 } else if (!languages[key]) {
32822 getLangDefinition(key);
32823 }
32824 r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
32825 return r._abbr;
32826 };
32827
32828 // returns language data
32829 moment.langData = function (key) {
32830 if (key && key._lang && key._lang._abbr) {
32831 key = key._lang._abbr;
32832 }
32833 return getLangDefinition(key);
32834 };
32835
32836 // compare moment object
32837 moment.isMoment = function (obj) {
32838 return obj instanceof Moment ||
32839 (obj != null && obj.hasOwnProperty('_isAMomentObject'));
32840 };
32841
32842 // for typechecking Duration objects
32843 moment.isDuration = function (obj) {
32844 return obj instanceof Duration;
32845 };
32846
32847 for (i = lists.length - 1; i >= 0; --i) {
32848 makeList(lists[i]);
32849 }
32850
32851 moment.normalizeUnits = function (units) {
32852 return normalizeUnits(units);
32853 };
32854
32855 moment.invalid = function (flags) {
32856 var m = moment.utc(NaN);
32857 if (flags != null) {
32858 extend(m._pf, flags);
32859 }
32860 else {
32861 m._pf.userInvalidated = true;
32862 }
32863
32864 return m;
32865 };
32866
32867 moment.parseZone = function (input) {
32868 return moment(input).parseZone();
32869 };
32870
32871 /************************************
32872 Moment Prototype
32873 ************************************/
32874
32875
32876 extend(moment.fn = Moment.prototype, {
32877
32878 clone : function () {
32879 return moment(this);
32880 },
32881
32882 valueOf : function () {
32883 return +this._d + ((this._offset || 0) * 60000);
32884 },
32885
32886 unix : function () {
32887 return Math.floor(+this / 1000);
32888 },
32889
32890 toString : function () {
32891 return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
32892 },
32893
32894 toDate : function () {
32895 return this._offset ? new Date(+this) : this._d;
32896 },
32897
32898 toISOString : function () {
32899 var m = moment(this).utc();
32900 if (0 < m.year() && m.year() <= 9999) {
32901 return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
32902 } else {
32903 return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
32904 }
32905 },
32906
32907 toArray : function () {
32908 var m = this;
32909 return [
32910 m.year(),
32911 m.month(),
32912 m.date(),
32913 m.hours(),
32914 m.minutes(),
32915 m.seconds(),
32916 m.milliseconds()
32917 ];
32918 },
32919
32920 isValid : function () {
32921 return isValid(this);
32922 },
32923
32924 isDSTShifted : function () {
32925
32926 if (this._a) {
32927 return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0;
32928 }
32929
32930 return false;
32931 },
32932
32933 parsingFlags : function () {
32934 return extend({}, this._pf);
32935 },
32936
32937 invalidAt: function () {
32938 return this._pf.overflow;
32939 },
32940
32941 utc : function () {
32942 return this.zone(0);
32943 },
32944
32945 local : function () {
32946 this.zone(0);
32947 this._isUTC = false;
32948 return this;
32949 },
32950
32951 format : function (inputString) {
32952 var output = formatMoment(this, inputString || moment.defaultFormat);
32953 return this.lang().postformat(output);
32954 },
32955
32956 add : function (input, val) {
32957 var dur;
32958 // switch args to support add('s', 1) and add(1, 's')
32959 if (typeof input === 'string') {
32960 dur = moment.duration(+val, input);
32961 } else {
32962 dur = moment.duration(input, val);
32963 }
32964 addOrSubtractDurationFromMoment(this, dur, 1);
32965 return this;
32966 },
32967
32968 subtract : function (input, val) {
32969 var dur;
32970 // switch args to support subtract('s', 1) and subtract(1, 's')
32971 if (typeof input === 'string') {
32972 dur = moment.duration(+val, input);
32973 } else {
32974 dur = moment.duration(input, val);
32975 }
32976 addOrSubtractDurationFromMoment(this, dur, -1);
32977 return this;
32978 },
32979
32980 diff : function (input, units, asFloat) {
32981 var that = makeAs(input, this),
32982 zoneDiff = (this.zone() - that.zone()) * 6e4,
32983 diff, output;
32984
32985 units = normalizeUnits(units);
32986
32987 if (units === 'year' || units === 'month') {
32988 // average number of days in the months in the given dates
32989 diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
32990 // difference in months
32991 output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
32992 // adjust by taking difference in days, average number of days
32993 // and dst in the given months.
32994 output += ((this - moment(this).startOf('month')) -
32995 (that - moment(that).startOf('month'))) / diff;
32996 // same as above but with zones, to negate all dst
32997 output -= ((this.zone() - moment(this).startOf('month').zone()) -
32998 (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff;
32999 if (units === 'year') {
33000 output = output / 12;
33001 }
33002 } else {
33003 diff = (this - that);
33004 output = units === 'second' ? diff / 1e3 : // 1000
33005 units === 'minute' ? diff / 6e4 : // 1000 * 60
33006 units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
33007 units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
33008 units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
33009 diff;
33010 }
33011 return asFloat ? output : absRound(output);
33012 },
33013
33014 from : function (time, withoutSuffix) {
33015 return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
33016 },
33017
33018 fromNow : function (withoutSuffix) {
33019 return this.from(moment(), withoutSuffix);
33020 },
33021
33022 calendar : function () {
33023 // We want to compare the start of today, vs this.
33024 // Getting start-of-today depends on whether we're zone'd or not.
33025 var sod = makeAs(moment(), this).startOf('day'),
33026 diff = this.diff(sod, 'days', true),
33027 format = diff < -6 ? 'sameElse' :
33028 diff < -1 ? 'lastWeek' :
33029 diff < 0 ? 'lastDay' :
33030 diff < 1 ? 'sameDay' :
33031 diff < 2 ? 'nextDay' :
33032 diff < 7 ? 'nextWeek' : 'sameElse';
33033 return this.format(this.lang().calendar(format, this));
33034 },
33035
33036 isLeapYear : function () {
33037 return isLeapYear(this.year());
33038 },
33039
33040 isDST : function () {
33041 return (this.zone() < this.clone().month(0).zone() ||
33042 this.zone() < this.clone().month(5).zone());
33043 },
33044
33045 day : function (input) {
33046 var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
33047 if (input != null) {
33048 input = parseWeekday(input, this.lang());
33049 return this.add({ d : input - day });
33050 } else {
33051 return day;
33052 }
33053 },
33054
33055 month : function (input) {
33056 var utc = this._isUTC ? 'UTC' : '',
33057 dayOfMonth;
33058
33059 if (input != null) {
33060 if (typeof input === 'string') {
33061 input = this.lang().monthsParse(input);
33062 if (typeof input !== 'number') {
33063 return this;
33064 }
33065 }
33066
33067 dayOfMonth = this.date();
33068 this.date(1);
33069 this._d['set' + utc + 'Month'](input);
33070 this.date(Math.min(dayOfMonth, this.daysInMonth()));
33071
33072 moment.updateOffset(this);
33073 return this;
33074 } else {
33075 return this._d['get' + utc + 'Month']();
33076 }
33077 },
33078
33079 startOf: function (units) {
33080 units = normalizeUnits(units);
33081 // the following switch intentionally omits break keywords
33082 // to utilize falling through the cases.
33083 switch (units) {
33084 case 'year':
33085 this.month(0);
33086 /* falls through */
33087 case 'month':
33088 this.date(1);
33089 /* falls through */
33090 case 'week':
33091 case 'isoWeek':
33092 case 'day':
33093 this.hours(0);
33094 /* falls through */
33095 case 'hour':
33096 this.minutes(0);
33097 /* falls through */
33098 case 'minute':
33099 this.seconds(0);
33100 /* falls through */
33101 case 'second':
33102 this.milliseconds(0);
33103 /* falls through */
33104 }
33105
33106 // weeks are a special case
33107 if (units === 'week') {
33108 this.weekday(0);
33109 } else if (units === 'isoWeek') {
33110 this.isoWeekday(1);
33111 }
33112
33113 return this;
33114 },
33115
33116 endOf: function (units) {
33117 units = normalizeUnits(units);
33118 return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1);
33119 },
33120
33121 isAfter: function (input, units) {
33122 units = typeof units !== 'undefined' ? units : 'millisecond';
33123 return +this.clone().startOf(units) > +moment(input).startOf(units);
33124 },
33125
33126 isBefore: function (input, units) {
33127 units = typeof units !== 'undefined' ? units : 'millisecond';
33128 return +this.clone().startOf(units) < +moment(input).startOf(units);
33129 },
33130
33131 isSame: function (input, units) {
33132 units = units || 'ms';
33133 return +this.clone().startOf(units) === +makeAs(input, this).startOf(units);
33134 },
33135
33136 min: function (other) {
33137 other = moment.apply(null, arguments);
33138 return other < this ? this : other;
33139 },
33140
33141 max: function (other) {
33142 other = moment.apply(null, arguments);
33143 return other > this ? this : other;
33144 },
33145
33146 zone : function (input) {
33147 var offset = this._offset || 0;
33148 if (input != null) {
33149 if (typeof input === "string") {
33150 input = timezoneMinutesFromString(input);
33151 }
33152 if (Math.abs(input) < 16) {
33153 input = input * 60;
33154 }
33155 this._offset = input;
33156 this._isUTC = true;
33157 if (offset !== input) {
33158 addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true);
33159 }
33160 } else {
33161 return this._isUTC ? offset : this._d.getTimezoneOffset();
33162 }
33163 return this;
33164 },
33165
33166 zoneAbbr : function () {
33167 return this._isUTC ? "UTC" : "";
33168 },
33169
33170 zoneName : function () {
33171 return this._isUTC ? "Coordinated Universal Time" : "";
33172 },
33173
33174 parseZone : function () {
33175 if (this._tzm) {
33176 this.zone(this._tzm);
33177 } else if (typeof this._i === 'string') {
33178 this.zone(this._i);
33179 }
33180 return this;
33181 },
33182
33183 hasAlignedHourOffset : function (input) {
33184 if (!input) {
33185 input = 0;
33186 }
33187 else {
33188 input = moment(input).zone();
33189 }
33190
33191 return (this.zone() - input) % 60 === 0;
33192 },
33193
33194 daysInMonth : function () {
33195 return daysInMonth(this.year(), this.month());
33196 },
33197
33198 dayOfYear : function (input) {
33199 var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
33200 return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
33201 },
33202
33203 quarter : function () {
33204 return Math.ceil((this.month() + 1.0) / 3.0);
33205 },
33206
33207 weekYear : function (input) {
33208 var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year;
33209 return input == null ? year : this.add("y", (input - year));
33210 },
33211
33212 isoWeekYear : function (input) {
33213 var year = weekOfYear(this, 1, 4).year;
33214 return input == null ? year : this.add("y", (input - year));
33215 },
33216
33217 week : function (input) {
33218 var week = this.lang().week(this);
33219 return input == null ? week : this.add("d", (input - week) * 7);
33220 },
33221
33222 isoWeek : function (input) {
33223 var week = weekOfYear(this, 1, 4).week;
33224 return input == null ? week : this.add("d", (input - week) * 7);
33225 },
33226
33227 weekday : function (input) {
33228 var weekday = (this.day() + 7 - this.lang()._week.dow) % 7;
33229 return input == null ? weekday : this.add("d", input - weekday);
33230 },
33231
33232 isoWeekday : function (input) {
33233 // behaves the same as moment#day except
33234 // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
33235 // as a setter, sunday should belong to the previous week.
33236 return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
33237 },
33238
33239 get : function (units) {
33240 units = normalizeUnits(units);
33241 return this[units]();
33242 },
33243
33244 set : function (units, value) {
33245 units = normalizeUnits(units);
33246 if (typeof this[units] === 'function') {
33247 this[units](value);
33248 }
33249 return this;
33250 },
33251
33252 // If passed a language key, it will set the language for this
33253 // instance. Otherwise, it will return the language configuration
33254 // variables for this instance.
33255 lang : function (key) {
33256 if (key === undefined) {
33257 return this._lang;
33258 } else {
33259 this._lang = getLangDefinition(key);
33260 return this;
33261 }
33262 }
33263 });
33264
33265 // helper for adding shortcuts
33266 function makeGetterAndSetter(name, key) {
33267 moment.fn[name] = moment.fn[name + 's'] = function (input) {
33268 var utc = this._isUTC ? 'UTC' : '';
33269 if (input != null) {
33270 this._d['set' + utc + key](input);
33271 moment.updateOffset(this);
33272 return this;
33273 } else {
33274 return this._d['get' + utc + key]();
33275 }
33276 };
33277 }
33278
33279 // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
33280 for (i = 0; i < proxyGettersAndSetters.length; i ++) {
33281 makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
33282 }
33283
33284 // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
33285 makeGetterAndSetter('year', 'FullYear');
33286
33287 // add plural methods
33288 moment.fn.days = moment.fn.day;
33289 moment.fn.months = moment.fn.month;
33290 moment.fn.weeks = moment.fn.week;
33291 moment.fn.isoWeeks = moment.fn.isoWeek;
33292
33293 // add aliased format methods
33294 moment.fn.toJSON = moment.fn.toISOString;
33295
33296 /************************************
33297 Duration Prototype
33298 ************************************/
33299
33300
33301 extend(moment.duration.fn = Duration.prototype, {
33302
33303 _bubble : function () {
33304 var milliseconds = this._milliseconds,
33305 days = this._days,
33306 months = this._months,
33307 data = this._data,
33308 seconds, minutes, hours, years;
33309
33310 // The following code bubbles up values, see the tests for
33311 // examples of what that means.
33312 data.milliseconds = milliseconds % 1000;
33313
33314 seconds = absRound(milliseconds / 1000);
33315 data.seconds = seconds % 60;
33316
33317 minutes = absRound(seconds / 60);
33318 data.minutes = minutes % 60;
33319
33320 hours = absRound(minutes / 60);
33321 data.hours = hours % 24;
33322
33323 days += absRound(hours / 24);
33324 data.days = days % 30;
33325
33326 months += absRound(days / 30);
33327 data.months = months % 12;
33328
33329 years = absRound(months / 12);
33330 data.years = years;
33331 },
33332
33333 weeks : function () {
33334 return absRound(this.days() / 7);
33335 },
33336
33337 valueOf : function () {
33338 return this._milliseconds +
33339 this._days * 864e5 +
33340 (this._months % 12) * 2592e6 +
33341 toInt(this._months / 12) * 31536e6;
33342 },
33343
33344 humanize : function (withSuffix) {
33345 var difference = +this,
33346 output = relativeTime(difference, !withSuffix, this.lang());
33347
33348 if (withSuffix) {
33349 output = this.lang().pastFuture(difference, output);
33350 }
33351
33352 return this.lang().postformat(output);
33353 },
33354
33355 add : function (input, val) {
33356 // supports only 2.0-style add(1, 's') or add(moment)
33357 var dur = moment.duration(input, val);
33358
33359 this._milliseconds += dur._milliseconds;
33360 this._days += dur._days;
33361 this._months += dur._months;
33362
33363 this._bubble();
33364
33365 return this;
33366 },
33367
33368 subtract : function (input, val) {
33369 var dur = moment.duration(input, val);
33370
33371 this._milliseconds -= dur._milliseconds;
33372 this._days -= dur._days;
33373 this._months -= dur._months;
33374
33375 this._bubble();
33376
33377 return this;
33378 },
33379
33380 get : function (units) {
33381 units = normalizeUnits(units);
33382 return this[units.toLowerCase() + 's']();
33383 },
33384
33385 as : function (units) {
33386 units = normalizeUnits(units);
33387 return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's']();
33388 },
33389
33390 lang : moment.fn.lang,
33391
33392 toIsoString : function () {
33393 // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
33394 var years = Math.abs(this.years()),
33395 months = Math.abs(this.months()),
33396 days = Math.abs(this.days()),
33397 hours = Math.abs(this.hours()),
33398 minutes = Math.abs(this.minutes()),
33399 seconds = Math.abs(this.seconds() + this.milliseconds() / 1000);
33400
33401 if (!this.asSeconds()) {
33402 // this is the same as C#'s (Noda) and python (isodate)...
33403 // but not other JS (goog.date)
33404 return 'P0D';
33405 }
33406
33407 return (this.asSeconds() < 0 ? '-' : '') +
33408 'P' +
33409 (years ? years + 'Y' : '') +
33410 (months ? months + 'M' : '') +
33411 (days ? days + 'D' : '') +
33412 ((hours || minutes || seconds) ? 'T' : '') +
33413 (hours ? hours + 'H' : '') +
33414 (minutes ? minutes + 'M' : '') +
33415 (seconds ? seconds + 'S' : '');
33416 }
33417 });
33418
33419 function makeDurationGetter(name) {
33420 moment.duration.fn[name] = function () {
33421 return this._data[name];
33422 };
33423 }
33424
33425 function makeDurationAsGetter(name, factor) {
33426 moment.duration.fn['as' + name] = function () {
33427 return +this / factor;
33428 };
33429 }
33430
33431 for (i in unitMillisecondFactors) {
33432 if (unitMillisecondFactors.hasOwnProperty(i)) {
33433 makeDurationAsGetter(i, unitMillisecondFactors[i]);
33434 makeDurationGetter(i.toLowerCase());
33435 }
33436 }
33437
33438 makeDurationAsGetter('Weeks', 6048e5);
33439 moment.duration.fn.asMonths = function () {
33440 return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12;
33441 };
33442
33443
33444 /************************************
33445 Default Lang
33446 ************************************/
33447
33448
33449 // Set default language, other languages will inherit from English.
33450 moment.lang('en', {
33451 ordinal : function (number) {
33452 var b = number % 10,
33453 output = (toInt(number % 100 / 10) === 1) ? 'th' :
33454 (b === 1) ? 'st' :
33455 (b === 2) ? 'nd' :
33456 (b === 3) ? 'rd' : 'th';
33457 return number + output;
33458 }
33459 });
33460
33461 /* EMBED_LANGUAGES */
33462
33463 /************************************
33464 Exposing Moment
33465 ************************************/
33466
33467 function makeGlobal(deprecate) {
33468 var warned = false, local_moment = moment;
33469 /*global ender:false */
33470 if (typeof ender !== 'undefined') {
33471 return;
33472 }
33473 // here, `this` means `window` in the browser, or `global` on the server
33474 // add `moment` as a global object via a string identifier,
33475 // for Closure Compiler "advanced" mode
33476 if (deprecate) {
33477 global.moment = function () {
33478 if (!warned && console && console.warn) {
33479 warned = true;
33480 console.warn(
33481 "Accessing Moment through the global scope is " +
33482 "deprecated, and will be removed in an upcoming " +
33483 "release.");
33484 }
33485 return local_moment.apply(null, arguments);
33486 };
33487 extend(global.moment, local_moment);
33488 } else {
33489 global['moment'] = moment;
33490 }
33491 }
33492
33493 // CommonJS module is defined
33494 if (hasModule) {
33495 module.exports = moment;
33496 makeGlobal(true);
33497 } else if (typeof define === "function" && define.amd) {
33498 define("moment", function (require, exports, module) {
33499 if (module.config && module.config() && module.config().noGlobal !== true) {
33500 // If user provided noGlobal, he is aware of global
33501 makeGlobal(module.config().noGlobal === undefined);
33502 }
33503
33504 return moment;
33505 });
33506 } else {
33507 makeGlobal();
33508 }
33509 }).call(this);
33510 /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
33511 var saveAs=saveAs||function(e){"use strict";if("undefined"==typeof navigator||!/MSIE [1-9]\./.test(navigator.userAgent)){var t=e.document,n=function(){return e.URL||e.webkitURL||e},o=t.createElementNS("http://www.w3.org/1999/xhtml","a"),r="download"in o,i=function(n){var o=t.createEvent("MouseEvents");o.initMouseEvent("click",!0,!1,e,0,0,0,0,0,!1,!1,!1,!1,0,null),n.dispatchEvent(o)},a=e.webkitRequestFileSystem,c=e.requestFileSystem||a||e.mozRequestFileSystem,u=function(t){(e.setImmediate||e.setTimeout)(function(){throw t},0)},f="application/octet-stream",s=0,d=500,l=function(t){var o=function(){"string"==typeof t?n().revokeObjectURL(t):t.remove()};e.chrome?o():setTimeout(o,d)},v=function(e,t,n){t=[].concat(t);for(var o=t.length;o--;){var r=e["on"+t[o]];if("function"==typeof r)try{r.call(e,n||e)}catch(i){u(i)}}},p=function(e){return/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob(["\ufeff",e],{type:e.type}):e},w=function(t,u){t=p(t);var d,w,y,m=this,S=t.type,h=!1,O=function(){v(m,"writestart progress write writeend".split(" "))},E=function(){if((h||!d)&&(d=n().createObjectURL(t)),w)w.location.href=d;else{var o=e.open(d,"_blank");void 0==o&&"undefined"!=typeof safari&&(e.location.href=d)}m.readyState=m.DONE,O(),l(d)},R=function(e){return function(){return m.readyState!==m.DONE?e.apply(this,arguments):void 0}},b={create:!0,exclusive:!1};return m.readyState=m.INIT,u||(u="download"),r?(d=n().createObjectURL(t),o.href=d,o.download=u,i(o),m.readyState=m.DONE,O(),void l(d)):(e.chrome&&S&&S!==f&&(y=t.slice||t.webkitSlice,t=y.call(t,0,t.size,f),h=!0),a&&"download"!==u&&(u+=".download"),(S===f||a)&&(w=e),c?(s+=t.size,void c(e.TEMPORARY,s,R(function(e){e.root.getDirectory("saved",b,R(function(e){var n=function(){e.getFile(u,b,R(function(e){e.createWriter(R(function(n){n.onwriteend=function(t){w.location.href=e.toURL(),m.readyState=m.DONE,v(m,"writeend",t),l(e)},n.onerror=function(){var e=n.error;e.code!==e.ABORT_ERR&&E()},"writestart progress write abort".split(" ").forEach(function(e){n["on"+e]=m["on"+e]}),n.write(t),m.abort=function(){n.abort(),m.readyState=m.DONE},m.readyState=m.WRITING}),E)}),E)};e.getFile(u,{create:!1},R(function(e){e.remove(),n()}),R(function(e){e.code===e.NOT_FOUND_ERR?n():E()}))}),E)}),E)):void E())},y=w.prototype,m=function(e,t){return new w(e,t)};return"undefined"!=typeof navigator&&navigator.msSaveOrOpenBlob?function(e,t){return navigator.msSaveOrOpenBlob(p(e),t)}:(y.abort=function(){var e=this;e.readyState=e.DONE,v(e,"abort")},y.readyState=y.INIT=0,y.WRITING=1,y.DONE=2,y.error=y.onwritestart=y.onprogress=y.onwrite=y.onabort=y.onerror=y.onwriteend=null,m)}}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||this.content);"undefined"!=typeof module&&module.exports?module.exports.saveAs=saveAs:"undefined"!=typeof define&&null!==define&&null!=define.amd&&define([],function(){return saveAs});
33512 /*!
33513 * UCSV 1.1.0
33514 * Provided under MIT License.
33515 *
33516 * Copyright 2010-2012, Peter Johnson
33517 * http://www.uselesscode.org/javascript/csv/
33518 */
33519 var CSV=(function(){var f=/^\d+$/,g=/^\d*\.\d+$|^\d+\.\d*$/,i=/^\s|\s$|,|"|\n/,b=(function(){if(String.prototype.trim){return function(j){return j.trim()}}else{return function(j){return j.replace(/^\s*/,"").replace(/\s*$/,"")}}}());function h(j){return Object.prototype.toString.apply(j)==="[object Number]"}function a(j){return Object.prototype.toString.apply(j)==="[object String]"}function d(j){if(j.charAt(j.length-1)!=="\n"){return j}else{return j.substring(0,j.length-1)}}function e(k){var p,m="",o,n,l;for(n=0;n<k.length;n+=1){o=k[n];for(l=0;l<o.length;l+=1){p=o[l];if(a(p)){p=p.replace(/"/g,'""');if(i.test(p)||f.test(p)||g.test(p)){p='"'+p+'"'}else{if(p===""){p='""'}}}else{if(h(p)){p=p.toString(10)}else{if(p===null){p=""}else{p=p.toString()}}}m+=l<o.length-1?p+",":p}m+="\n"}return m}function c(t,p){t=d(t);var q="",l=false,m=false,o="",r=[],j=[],k,n;n=function(s){if(m!==true){if(s===""){s=null}else{if(p===true){s=b(s)}}if(f.test(s)){s=parseInt(s,10)}else{if(g.test(s)){s=parseFloat(s,10)}}}return s};for(k=0;k<t.length;k+=1){q=t.charAt(k);if(l===false&&(q===","||q==="\n")){o=n(o);r.push(o);if(q==="\n"){j.push(r);r=[]}o="";m=false}else{if(q!=='"'){o+=q}else{if(!l){l=true;m=true}else{if(t.charAt(k+1)==='"'){o+='"';k+=1}else{l=false}}}}}o=n(o);r.push(o);j.push(r);return j}if(typeof exports==="object"){exports.arrayToCsv=e;exports.csvToArray=c}return{arrayToCsv:e,csvToArray:c}}());
33520 /* Javascript plotting library for jQuery, version 0.8.3-alpha.
33521
33522 Copyright (c) 2007-2013 IOLA and Ole Laursen.
33523 Licensed under the MIT license.
33524
33525 */
33526
33527 // first an inline dependency, jquery.colorhelpers.js, we inline it here
33528 // for convenience
33529
33530 /* Plugin for jQuery for working with colors.
33531 *
33532 * Version 1.1.
33533 *
33534 * Inspiration from jQuery color animation plugin by John Resig.
33535 *
33536 * Released under the MIT license by Ole Laursen, October 2009.
33537 *
33538 * Examples:
33539 *
33540 * $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
33541 * var c = $.color.extract($("#mydiv"), 'background-color');
33542 * console.log(c.r, c.g, c.b, c.a);
33543 * $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
33544 *
33545 * Note that .scale() and .add() return the same modified object
33546 * instead of making a new one.
33547 *
33548 * V. 1.1: Fix error handling so e.g. parsing an empty string does
33549 * produce a color rather than just crashing.
33550 */
33551 (function($){$.color={};$.color.make=function(r,g,b,a){var o={};o.r=r||0;o.g=g||0;o.b=b||0;o.a=a!=null?a:1;o.add=function(c,d){for(var i=0;i<c.length;++i)o[c.charAt(i)]+=d;return o.normalize()};o.scale=function(c,f){for(var i=0;i<c.length;++i)o[c.charAt(i)]*=f;return o.normalize()};o.toString=function(){if(o.a>=1){return"rgb("+[o.r,o.g,o.b].join(",")+")"}else{return"rgba("+[o.r,o.g,o.b,o.a].join(",")+")"}};o.normalize=function(){function clamp(min,value,max){return value<min?min:value>max?max:value}o.r=clamp(0,parseInt(o.r),255);o.g=clamp(0,parseInt(o.g),255);o.b=clamp(0,parseInt(o.b),255);o.a=clamp(0,o.a,1);return o};o.clone=function(){return $.color.make(o.r,o.b,o.g,o.a)};return o.normalize()};$.color.extract=function(elem,css){var c;do{c=elem.css(css).toLowerCase();if(c!=""&&c!="transparent")break;elem=elem.parent()}while(elem.length&&!$.nodeName(elem.get(0),"body"));if(c=="rgba(0, 0, 0, 0)")c="transparent";return $.color.parse(c)};$.color.parse=function(str){var res,m=$.color.make;if(res=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10));if(res=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10),parseFloat(res[4]));if(res=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55);if(res=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55,parseFloat(res[4]));if(res=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))return m(parseInt(res[1],16),parseInt(res[2],16),parseInt(res[3],16));if(res=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))return m(parseInt(res[1]+res[1],16),parseInt(res[2]+res[2],16),parseInt(res[3]+res[3],16));var name=$.trim(str).toLowerCase();if(name=="transparent")return m(255,255,255,0);else{res=lookupColors[name]||[0,0,0];return m(res[0],res[1],res[2])}};var lookupColors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);
33552
33553 // the actual Flot code
33554 (function($) {
33555
33556 // Cache the prototype hasOwnProperty for faster access
33557
33558 var hasOwnProperty = Object.prototype.hasOwnProperty;
33559
33560 ///////////////////////////////////////////////////////////////////////////
33561 // The Canvas object is a wrapper around an HTML5 <canvas> tag.
33562 //
33563 // @constructor
33564 // @param {string} cls List of classes to apply to the canvas.
33565 // @param {element} container Element onto which to append the canvas.
33566 //
33567 // Requiring a container is a little iffy, but unfortunately canvas
33568 // operations don't work unless the canvas is attached to the DOM.
33569
33570 function Canvas(cls, container) {
33571
33572 var element = container.children("." + cls)[0];
33573
33574 if (element == null) {
33575
33576 element = document.createElement("canvas");
33577 element.className = cls;
33578
33579 $(element).css({ direction: "ltr", position: "absolute", left: 0, top: 0 })
33580 .appendTo(container);
33581
33582 // If HTML5 Canvas isn't available, fall back to [Ex|Flash]canvas
33583
33584 if (!element.getContext) {
33585 if (window.G_vmlCanvasManager) {
33586 element = window.G_vmlCanvasManager.initElement(element);
33587 } else {
33588 throw new Error("Canvas is not available. If you're using IE with a fall-back such as Excanvas, then there's either a mistake in your conditional include, or the page has no DOCTYPE and is rendering in Quirks Mode.");
33589 }
33590 }
33591 }
33592
33593 this.element = element;
33594
33595 var context = this.context = element.getContext("2d");
33596
33597 // Determine the screen's ratio of physical to device-independent
33598 // pixels. This is the ratio between the canvas width that the browser
33599 // advertises and the number of pixels actually present in that space.
33600
33601 // The iPhone 4, for example, has a device-independent width of 320px,
33602 // but its screen is actually 640px wide. It therefore has a pixel
33603 // ratio of 2, while most normal devices have a ratio of 1.
33604
33605 var devicePixelRatio = window.devicePixelRatio || 1,
33606 backingStoreRatio =
33607 context.webkitBackingStorePixelRatio ||
33608 context.mozBackingStorePixelRatio ||
33609 context.msBackingStorePixelRatio ||
33610 context.oBackingStorePixelRatio ||
33611 context.backingStorePixelRatio || 1;
33612
33613 this.pixelRatio = devicePixelRatio / backingStoreRatio;
33614
33615 // Size the canvas to match the internal dimensions of its container
33616
33617 this.resize(container.width(), container.height());
33618
33619 // Collection of HTML div layers for text overlaid onto the canvas
33620
33621 this.textContainer = null;
33622 this.text = {};
33623
33624 // Cache of text fragments and metrics, so we can avoid expensively
33625 // re-calculating them when the plot is re-rendered in a loop.
33626
33627 this._textCache = {};
33628 }
33629
33630 // Resizes the canvas to the given dimensions.
33631 //
33632 // @param {number} width New width of the canvas, in pixels.
33633 // @param {number} width New height of the canvas, in pixels.
33634
33635 Canvas.prototype.resize = function(width, height) {
33636
33637 if (width <= 0 || height <= 0) {
33638 throw new Error("Invalid dimensions for plot, width = " + width + ", height = " + height);
33639 }
33640
33641 var element = this.element,
33642 context = this.context,
33643 pixelRatio = this.pixelRatio;
33644
33645 // Resize the canvas, increasing its density based on the display's
33646 // pixel ratio; basically giving it more pixels without increasing the
33647 // size of its element, to take advantage of the fact that retina
33648 // displays have that many more pixels in the same advertised space.
33649
33650 // Resizing should reset the state (excanvas seems to be buggy though)
33651
33652 if (this.width != width) {
33653 element.width = width * pixelRatio;
33654 element.style.width = width + "px";
33655 this.width = width;
33656 }
33657
33658 if (this.height != height) {
33659 element.height = height * pixelRatio;
33660 element.style.height = height + "px";
33661 this.height = height;
33662 }
33663
33664 // Save the context, so we can reset in case we get replotted. The
33665 // restore ensure that we're really back at the initial state, and
33666 // should be safe even if we haven't saved the initial state yet.
33667
33668 context.restore();
33669 context.save();
33670
33671 // Scale the coordinate space to match the display density; so even though we
33672 // may have twice as many pixels, we still want lines and other drawing to
33673 // appear at the same size; the extra pixels will just make them crisper.
33674
33675 context.scale(pixelRatio, pixelRatio);
33676 };
33677
33678 // Clears the entire canvas area, not including any overlaid HTML text
33679
33680 Canvas.prototype.clear = function() {
33681 this.context.clearRect(0, 0, this.width, this.height);
33682 };
33683
33684 // Finishes rendering the canvas, including managing the text overlay.
33685
33686 Canvas.prototype.render = function() {
33687
33688 var cache = this._textCache;
33689
33690 // For each text layer, add elements marked as active that haven't
33691 // already been rendered, and remove those that are no longer active.
33692
33693 for (var layerKey in cache) {
33694 if (hasOwnProperty.call(cache, layerKey)) {
33695
33696 var layer = this.getTextLayer(layerKey),
33697 layerCache = cache[layerKey];
33698
33699 layer.hide();
33700
33701 for (var styleKey in layerCache) {
33702 if (hasOwnProperty.call(layerCache, styleKey)) {
33703 var styleCache = layerCache[styleKey];
33704 for (var key in styleCache) {
33705 if (hasOwnProperty.call(styleCache, key)) {
33706
33707 var positions = styleCache[key].positions;
33708
33709 for (var i = 0, position; position = positions[i]; i++) {
33710 if (position.active) {
33711 if (!position.rendered) {
33712 layer.append(position.element);
33713 position.rendered = true;
33714 }
33715 } else {
33716 positions.splice(i--, 1);
33717 if (position.rendered) {
33718 position.element.detach();
33719 }
33720 }
33721 }
33722
33723 if (positions.length == 0) {
33724 delete styleCache[key];
33725 }
33726 }
33727 }
33728 }
33729 }
33730
33731 layer.show();
33732 }
33733 }
33734 };
33735
33736 // Creates (if necessary) and returns the text overlay container.
33737 //
33738 // @param {string} classes String of space-separated CSS classes used to
33739 // uniquely identify the text layer.
33740 // @return {object} The jQuery-wrapped text-layer div.
33741
33742 Canvas.prototype.getTextLayer = function(classes) {
33743
33744 var layer = this.text[classes];
33745
33746 // Create the text layer if it doesn't exist
33747
33748 if (layer == null) {
33749
33750 // Create the text layer container, if it doesn't exist
33751
33752 if (this.textContainer == null) {
33753 this.textContainer = $("<div class='flot-text'></div>")
33754 .css({
33755 position: "absolute",
33756 top: 0,
33757 left: 0,
33758 bottom: 0,
33759 right: 0,
33760 'font-size': "smaller",
33761 color: "#545454"
33762 })
33763 .insertAfter(this.element);
33764 }
33765
33766 layer = this.text[classes] = $("<div></div>")
33767 .addClass(classes)
33768 .css({
33769 position: "absolute",
33770 top: 0,
33771 left: 0,
33772 bottom: 0,
33773 right: 0
33774 })
33775 .appendTo(this.textContainer);
33776 }
33777
33778 return layer;
33779 };
33780
33781 // Creates (if necessary) and returns a text info object.
33782 //
33783 // The object looks like this:
33784 //
33785 // {
33786 // width: Width of the text's wrapper div.
33787 // height: Height of the text's wrapper div.
33788 // element: The jQuery-wrapped HTML div containing the text.
33789 // positions: Array of positions at which this text is drawn.
33790 // }
33791 //
33792 // The positions array contains objects that look like this:
33793 //
33794 // {
33795 // active: Flag indicating whether the text should be visible.
33796 // rendered: Flag indicating whether the text is currently visible.
33797 // element: The jQuery-wrapped HTML div containing the text.
33798 // x: X coordinate at which to draw the text.
33799 // y: Y coordinate at which to draw the text.
33800 // }
33801 //
33802 // Each position after the first receives a clone of the original element.
33803 //
33804 // The idea is that that the width, height, and general 'identity' of the
33805 // text is constant no matter where it is placed; the placements are a
33806 // secondary property.
33807 //
33808 // Canvas maintains a cache of recently-used text info objects; getTextInfo
33809 // either returns the cached element or creates a new entry.
33810 //
33811 // @param {string} layer A string of space-separated CSS classes uniquely
33812 // identifying the layer containing this text.
33813 // @param {string} text Text string to retrieve info for.
33814 // @param {(string|object)=} font Either a string of space-separated CSS
33815 // classes or a font-spec object, defining the text's font and style.
33816 // @param {number=} angle Angle at which to rotate the text, in degrees.
33817 // Angle is currently unused, it will be implemented in the future.
33818 // @param {number=} width Maximum width of the text before it wraps.
33819 // @return {object} a text info object.
33820
33821 Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) {
33822
33823 var textStyle, layerCache, styleCache, info;
33824
33825 // Cast the value to a string, in case we were given a number or such
33826
33827 text = "" + text;
33828
33829 // If the font is a font-spec object, generate a CSS font definition
33830
33831 if (typeof font === "object") {
33832 textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px/" + font.lineHeight + "px " + font.family;
33833 } else {
33834 textStyle = font;
33835 }
33836
33837 // Retrieve (or create) the cache for the text's layer and styles
33838
33839 layerCache = this._textCache[layer];
33840
33841 if (layerCache == null) {
33842 layerCache = this._textCache[layer] = {};
33843 }
33844
33845 styleCache = layerCache[textStyle];
33846
33847 if (styleCache == null) {
33848 styleCache = layerCache[textStyle] = {};
33849 }
33850
33851 info = styleCache[text];
33852
33853 // If we can't find a matching element in our cache, create a new one
33854
33855 if (info == null) {
33856
33857 var element = $("<div></div>").html(text)
33858 .css({
33859 position: "absolute",
33860 'max-width': width,
33861 top: -9999
33862 })
33863 .appendTo(this.getTextLayer(layer));
33864
33865 if (typeof font === "object") {
33866 element.css({
33867 font: textStyle,
33868 color: font.color
33869 });
33870 } else if (typeof font === "string") {
33871 element.addClass(font);
33872 }
33873
33874 info = styleCache[text] = {
33875 width: element.outerWidth(true),
33876 height: element.outerHeight(true),
33877 element: element,
33878 positions: []
33879 };
33880
33881 element.detach();
33882 }
33883
33884 return info;
33885 };
33886
33887 // Adds a text string to the canvas text overlay.
33888 //
33889 // The text isn't drawn immediately; it is marked as rendering, which will
33890 // result in its addition to the canvas on the next render pass.
33891 //
33892 // @param {string} layer A string of space-separated CSS classes uniquely
33893 // identifying the layer containing this text.
33894 // @param {number} x X coordinate at which to draw the text.
33895 // @param {number} y Y coordinate at which to draw the text.
33896 // @param {string} text Text string to draw.
33897 // @param {(string|object)=} font Either a string of space-separated CSS
33898 // classes or a font-spec object, defining the text's font and style.
33899 // @param {number=} angle Angle at which to rotate the text, in degrees.
33900 // Angle is currently unused, it will be implemented in the future.
33901 // @param {number=} width Maximum width of the text before it wraps.
33902 // @param {string=} halign Horizontal alignment of the text; either "left",
33903 // "center" or "right".
33904 // @param {string=} valign Vertical alignment of the text; either "top",
33905 // "middle" or "bottom".
33906
33907 Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign) {
33908
33909 var info = this.getTextInfo(layer, text, font, angle, width),
33910 positions = info.positions;
33911
33912 // Tweak the div's position to match the text's alignment
33913
33914 if (halign == "center") {
33915 x -= info.width / 2;
33916 } else if (halign == "right") {
33917 x -= info.width;
33918 }
33919
33920 if (valign == "middle") {
33921 y -= info.height / 2;
33922 } else if (valign == "bottom") {
33923 y -= info.height;
33924 }
33925
33926 // Determine whether this text already exists at this position.
33927 // If so, mark it for inclusion in the next render pass.
33928
33929 for (var i = 0, position; position = positions[i]; i++) {
33930 if (position.x == x && position.y == y) {
33931 position.active = true;
33932 return;
33933 }
33934 }
33935
33936 // If the text doesn't exist at this position, create a new entry
33937
33938 // For the very first position we'll re-use the original element,
33939 // while for subsequent ones we'll clone it.
33940
33941 position = {
33942 active: true,
33943 rendered: false,
33944 element: positions.length ? info.element.clone() : info.element,
33945 x: x,
33946 y: y
33947 };
33948
33949 positions.push(position);
33950
33951 // Move the element to its final position within the container
33952
33953 position.element.css({
33954 top: Math.round(y),
33955 left: Math.round(x),
33956 'text-align': halign // In case the text wraps
33957 });
33958 };
33959
33960 // Removes one or more text strings from the canvas text overlay.
33961 //
33962 // If no parameters are given, all text within the layer is removed.
33963 //
33964 // Note that the text is not immediately removed; it is simply marked as
33965 // inactive, which will result in its removal on the next render pass.
33966 // This avoids the performance penalty for 'clear and redraw' behavior,
33967 // where we potentially get rid of all text on a layer, but will likely
33968 // add back most or all of it later, as when redrawing axes, for example.
33969 //
33970 // @param {string} layer A string of space-separated CSS classes uniquely
33971 // identifying the layer containing this text.
33972 // @param {number=} x X coordinate of the text.
33973 // @param {number=} y Y coordinate of the text.
33974 // @param {string=} text Text string to remove.
33975 // @param {(string|object)=} font Either a string of space-separated CSS
33976 // classes or a font-spec object, defining the text's font and style.
33977 // @param {number=} angle Angle at which the text is rotated, in degrees.
33978 // Angle is currently unused, it will be implemented in the future.
33979
33980 Canvas.prototype.removeText = function(layer, x, y, text, font, angle) {
33981 if (text == null) {
33982 var layerCache = this._textCache[layer];
33983 if (layerCache != null) {
33984 for (var styleKey in layerCache) {
33985 if (hasOwnProperty.call(layerCache, styleKey)) {
33986 var styleCache = layerCache[styleKey];
33987 for (var key in styleCache) {
33988 if (hasOwnProperty.call(styleCache, key)) {
33989 var positions = styleCache[key].positions;
33990 for (var i = 0, position; position = positions[i]; i++) {
33991 position.active = false;
33992 }
33993 }
33994 }
33995 }
33996 }
33997 }
33998 } else {
33999 var positions = this.getTextInfo(layer, text, font, angle).positions;
34000 for (var i = 0, position; position = positions[i]; i++) {
34001 if (position.x == x && position.y == y) {
34002 position.active = false;
34003 }
34004 }
34005 }
34006 };
34007
34008 ///////////////////////////////////////////////////////////////////////////
34009 // The top-level container for the entire plot.
34010
34011 function Plot(placeholder, data_, options_, plugins) {
34012 // data is on the form:
34013 // [ series1, series2 ... ]
34014 // where series is either just the data as [ [x1, y1], [x2, y2], ... ]
34015 // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... }
34016
34017 var series = [],
34018 options = {
34019 // the color theme used for graphs
34020 colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"],
34021 legend: {
34022 show: true,
34023 noColumns: 1, // number of colums in legend table
34024 labelFormatter: null, // fn: string -> string
34025 labelBoxBorderColor: "#ccc", // border color for the little label boxes
34026 container: null, // container (as jQuery object) to put legend in, null means default on top of graph
34027 position: "ne", // position of default legend container within plot
34028 margin: 5, // distance from grid edge to default legend container within plot
34029 backgroundColor: null, // null means auto-detect
34030 backgroundOpacity: 0.85, // set to 0 to avoid background
34031 sorted: null // default to no legend sorting
34032 },
34033 xaxis: {
34034 show: null, // null = auto-detect, true = always, false = never
34035 position: "bottom", // or "top"
34036 mode: null, // null or "time"
34037 font: null, // null (derived from CSS in placeholder) or object like { size: 11, lineHeight: 13, style: "italic", weight: "bold", family: "sans-serif", variant: "small-caps" }
34038 color: null, // base color, labels, ticks
34039 tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)"
34040 transform: null, // null or f: number -> number to transform axis
34041 inverseTransform: null, // if transform is set, this should be the inverse function
34042 min: null, // min. value to show, null means set automatically
34043 max: null, // max. value to show, null means set automatically
34044 autoscaleMargin: null, // margin in % to add if auto-setting min/max
34045 ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks
34046 tickFormatter: null, // fn: number -> string
34047 labelWidth: null, // size of tick labels in pixels
34048 labelHeight: null,
34049 reserveSpace: null, // whether to reserve space even if axis isn't shown
34050 tickLength: null, // size in pixels of ticks, or "full" for whole line
34051 alignTicksWithAxis: null, // axis number or null for no sync
34052 tickDecimals: null, // no. of decimals, null means auto
34053 tickSize: null, // number or [number, "unit"]
34054 minTickSize: null // number or [number, "unit"]
34055 },
34056 yaxis: {
34057 autoscaleMargin: 0.02,
34058 position: "left" // or "right"
34059 },
34060 xaxes: [],
34061 yaxes: [],
34062 series: {
34063 points: {
34064 show: false,
34065 radius: 3,
34066 lineWidth: 2, // in pixels
34067 fill: true,
34068 fillColor: "#ffffff",
34069 symbol: "circle" // or callback
34070 },
34071 lines: {
34072 // we don't put in show: false so we can see
34073 // whether lines were actively disabled
34074 lineWidth: 2, // in pixels
34075 fill: false,
34076 fillColor: null,
34077 steps: false
34078 // Omit 'zero', so we can later default its value to
34079 // match that of the 'fill' option.
34080 },
34081 bars: {
34082 show: false,
34083 lineWidth: 2, // in pixels
34084 barWidth: 1, // in units of the x axis
34085 fill: true,
34086 fillColor: null,
34087 align: "left", // "left", "right", or "center"
34088 horizontal: false,
34089 zero: true
34090 },
34091 shadowSize: 3,
34092 highlightColor: null
34093 },
34094 grid: {
34095 show: true,
34096 aboveData: false,
34097 color: "#545454", // primary color used for outline and labels
34098 backgroundColor: null, // null for transparent, else color
34099 borderColor: null, // set if different from the grid color
34100 tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)"
34101 margin: 0, // distance from the canvas edge to the grid
34102 labelMargin: 5, // in pixels
34103 axisMargin: 8, // in pixels
34104 borderWidth: 2, // in pixels
34105 minBorderMargin: null, // in pixels, null means taken from points radius
34106 markings: null, // array of ranges or fn: axes -> array of ranges
34107 markingsColor: "#f4f4f4",
34108 markingsLineWidth: 2,
34109 // interactive stuff
34110 clickable: false,
34111 hoverable: false,
34112 autoHighlight: true, // highlight in case mouse is near
34113 mouseActiveRadius: 10 // how far the mouse can be away to activate an item
34114 },
34115 interaction: {
34116 redrawOverlayInterval: 1000/60 // time between updates, -1 means in same flow
34117 },
34118 hooks: {}
34119 },
34120 surface = null, // the canvas for the plot itself
34121 overlay = null, // canvas for interactive stuff on top of plot
34122 eventHolder = null, // jQuery object that events should be bound to
34123 ctx = null, octx = null,
34124 xaxes = [], yaxes = [],
34125 plotOffset = { left: 0, right: 0, top: 0, bottom: 0},
34126 plotWidth = 0, plotHeight = 0,
34127 hooks = {
34128 processOptions: [],
34129 processRawData: [],
34130 processDatapoints: [],
34131 processOffset: [],
34132 drawBackground: [],
34133 drawSeries: [],
34134 draw: [],
34135 bindEvents: [],
34136 drawOverlay: [],
34137 shutdown: []
34138 },
34139 plot = this;
34140
34141 // public functions
34142 plot.setData = setData;
34143 plot.setupGrid = setupGrid;
34144 plot.draw = draw;
34145 plot.getPlaceholder = function() { return placeholder; };
34146 plot.getCanvas = function() { return surface.element; };
34147 plot.getPlotOffset = function() { return plotOffset; };
34148 plot.width = function () { return plotWidth; };
34149 plot.height = function () { return plotHeight; };
34150 plot.offset = function () {
34151 var o = eventHolder.offset();
34152 o.left += plotOffset.left;
34153 o.top += plotOffset.top;
34154 return o;
34155 };
34156 plot.getData = function () { return series; };
34157 plot.getAxes = function () {
34158 var res = {}, i;
34159 $.each(xaxes.concat(yaxes), function (_, axis) {
34160 if (axis)
34161 res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis;
34162 });
34163 return res;
34164 };
34165 plot.getXAxes = function () { return xaxes; };
34166 plot.getYAxes = function () { return yaxes; };
34167 plot.c2p = canvasToAxisCoords;
34168 plot.p2c = axisToCanvasCoords;
34169 plot.getOptions = function () { return options; };
34170 plot.highlight = highlight;
34171 plot.unhighlight = unhighlight;
34172 plot.triggerRedrawOverlay = triggerRedrawOverlay;
34173 plot.pointOffset = function(point) {
34174 return {
34175 left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left, 10),
34176 top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top, 10)
34177 };
34178 };
34179 plot.shutdown = shutdown;
34180 plot.destroy = function () {
34181 shutdown();
34182 placeholder.removeData("plot").empty();
34183
34184 series = [];
34185 options = null;
34186 surface = null;
34187 overlay = null;
34188 eventHolder = null;
34189 ctx = null;
34190 octx = null;
34191 xaxes = [];
34192 yaxes = [];
34193 hooks = null;
34194 highlights = [];
34195 plot = null;
34196 };
34197 plot.resize = function () {
34198 var width = placeholder.width(),
34199 height = placeholder.height();
34200 surface.resize(width, height);
34201 overlay.resize(width, height);
34202 };
34203
34204 // public attributes
34205 plot.hooks = hooks;
34206
34207 // initialize
34208 initPlugins(plot);
34209 parseOptions(options_);
34210 setupCanvases();
34211 setData(data_);
34212 setupGrid();
34213 draw();
34214 bindEvents();
34215
34216
34217 function executeHooks(hook, args) {
34218 args = [plot].concat(args);
34219 for (var i = 0; i < hook.length; ++i)
34220 hook[i].apply(this, args);
34221 }
34222
34223 function initPlugins() {
34224
34225 // References to key classes, allowing plugins to modify them
34226
34227 var classes = {
34228 Canvas: Canvas
34229 };
34230
34231 for (var i = 0; i < plugins.length; ++i) {
34232 var p = plugins[i];
34233 p.init(plot, classes);
34234 if (p.options)
34235 $.extend(true, options, p.options);
34236 }
34237 }
34238
34239 function parseOptions(opts) {
34240
34241 $.extend(true, options, opts);
34242
34243 // $.extend merges arrays, rather than replacing them. When less
34244 // colors are provided than the size of the default palette, we
34245 // end up with those colors plus the remaining defaults, which is
34246 // not expected behavior; avoid it by replacing them here.
34247
34248 if (opts && opts.colors) {
34249 options.colors = opts.colors;
34250 }
34251
34252 if (options.xaxis.color == null)
34253 options.xaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
34254 if (options.yaxis.color == null)
34255 options.yaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
34256
34257 if (options.xaxis.tickColor == null) // grid.tickColor for back-compatibility
34258 options.xaxis.tickColor = options.grid.tickColor || options.xaxis.color;
34259 if (options.yaxis.tickColor == null) // grid.tickColor for back-compatibility
34260 options.yaxis.tickColor = options.grid.tickColor || options.yaxis.color;
34261
34262 if (options.grid.borderColor == null)
34263 options.grid.borderColor = options.grid.color;
34264 if (options.grid.tickColor == null)
34265 options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString();
34266
34267 // Fill in defaults for axis options, including any unspecified
34268 // font-spec fields, if a font-spec was provided.
34269
34270 // If no x/y axis options were provided, create one of each anyway,
34271 // since the rest of the code assumes that they exist.
34272
34273 var i, axisOptions, axisCount,
34274 fontSize = placeholder.css("font-size"),
34275 fontSizeDefault = fontSize ? +fontSize.replace("px", "") : 13,
34276 fontDefaults = {
34277 style: placeholder.css("font-style"),
34278 size: Math.round(0.8 * fontSizeDefault),
34279 variant: placeholder.css("font-variant"),
34280 weight: placeholder.css("font-weight"),
34281 family: placeholder.css("font-family")
34282 };
34283
34284 axisCount = options.xaxes.length || 1;
34285 for (i = 0; i < axisCount; ++i) {
34286
34287 axisOptions = options.xaxes[i];
34288 if (axisOptions && !axisOptions.tickColor) {
34289 axisOptions.tickColor = axisOptions.color;
34290 }
34291
34292 axisOptions = $.extend(true, {}, options.xaxis, axisOptions);
34293 options.xaxes[i] = axisOptions;
34294
34295 if (axisOptions.font) {
34296 axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
34297 if (!axisOptions.font.color) {
34298 axisOptions.font.color = axisOptions.color;
34299 }
34300 if (!axisOptions.font.lineHeight) {
34301 axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15);
34302 }
34303 }
34304 }
34305
34306 axisCount = options.yaxes.length || 1;
34307 for (i = 0; i < axisCount; ++i) {
34308
34309 axisOptions = options.yaxes[i];
34310 if (axisOptions && !axisOptions.tickColor) {
34311 axisOptions.tickColor = axisOptions.color;
34312 }
34313
34314 axisOptions = $.extend(true, {}, options.yaxis, axisOptions);
34315 options.yaxes[i] = axisOptions;
34316
34317 if (axisOptions.font) {
34318 axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
34319 if (!axisOptions.font.color) {
34320 axisOptions.font.color = axisOptions.color;
34321 }
34322 if (!axisOptions.font.lineHeight) {
34323 axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15);
34324 }
34325 }
34326 }
34327
34328 // backwards compatibility, to be removed in future
34329 if (options.xaxis.noTicks && options.xaxis.ticks == null)
34330 options.xaxis.ticks = options.xaxis.noTicks;
34331 if (options.yaxis.noTicks && options.yaxis.ticks == null)
34332 options.yaxis.ticks = options.yaxis.noTicks;
34333 if (options.x2axis) {
34334 options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis);
34335 options.xaxes[1].position = "top";
34336 }
34337 if (options.y2axis) {
34338 options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis);
34339 options.yaxes[1].position = "right";
34340 }
34341 if (options.grid.coloredAreas)
34342 options.grid.markings = options.grid.coloredAreas;
34343 if (options.grid.coloredAreasColor)
34344 options.grid.markingsColor = options.grid.coloredAreasColor;
34345 if (options.lines)
34346 $.extend(true, options.series.lines, options.lines);
34347 if (options.points)
34348 $.extend(true, options.series.points, options.points);
34349 if (options.bars)
34350 $.extend(true, options.series.bars, options.bars);
34351 if (options.shadowSize != null)
34352 options.series.shadowSize = options.shadowSize;
34353 if (options.highlightColor != null)
34354 options.series.highlightColor = options.highlightColor;
34355
34356 // save options on axes for future reference
34357 for (i = 0; i < options.xaxes.length; ++i)
34358 getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i];
34359 for (i = 0; i < options.yaxes.length; ++i)
34360 getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i];
34361
34362 // add hooks from options
34363 for (var n in hooks)
34364 if (options.hooks[n] && options.hooks[n].length)
34365 hooks[n] = hooks[n].concat(options.hooks[n]);
34366
34367 executeHooks(hooks.processOptions, [options]);
34368 }
34369
34370 function setData(d) {
34371 series = parseData(d);
34372 fillInSeriesOptions();
34373 processData();
34374 }
34375
34376 function parseData(d) {
34377 var res = [];
34378 for (var i = 0; i < d.length; ++i) {
34379 var s = $.extend(true, {}, options.series);
34380
34381 if (d[i].data != null) {
34382 s.data = d[i].data; // move the data instead of deep-copy
34383 delete d[i].data;
34384
34385 $.extend(true, s, d[i]);
34386
34387 d[i].data = s.data;
34388 }
34389 else
34390 s.data = d[i];
34391 res.push(s);
34392 }
34393
34394 return res;
34395 }
34396
34397 function axisNumber(obj, coord) {
34398 var a = obj[coord + "axis"];
34399 if (typeof a == "object") // if we got a real axis, extract number
34400 a = a.n;
34401 if (typeof a != "number")
34402 a = 1; // default to first axis
34403 return a;
34404 }
34405
34406 function allAxes() {
34407 // return flat array without annoying null entries
34408 return $.grep(xaxes.concat(yaxes), function (a) { return a; });
34409 }
34410
34411 function canvasToAxisCoords(pos) {
34412 // return an object with x/y corresponding to all used axes
34413 var res = {}, i, axis;
34414 for (i = 0; i < xaxes.length; ++i) {
34415 axis = xaxes[i];
34416 if (axis && axis.used)
34417 res["x" + axis.n] = axis.c2p(pos.left);
34418 }
34419
34420 for (i = 0; i < yaxes.length; ++i) {
34421 axis = yaxes[i];
34422 if (axis && axis.used)
34423 res["y" + axis.n] = axis.c2p(pos.top);
34424 }
34425
34426 if (res.x1 !== undefined)
34427 res.x = res.x1;
34428 if (res.y1 !== undefined)
34429 res.y = res.y1;
34430
34431 return res;
34432 }
34433
34434 function axisToCanvasCoords(pos) {
34435 // get canvas coords from the first pair of x/y found in pos
34436 var res = {}, i, axis, key;
34437
34438 for (i = 0; i < xaxes.length; ++i) {
34439 axis = xaxes[i];
34440 if (axis && axis.used) {
34441 key = "x" + axis.n;
34442 if (pos[key] == null && axis.n == 1)
34443 key = "x";
34444
34445 if (pos[key] != null) {
34446 res.left = axis.p2c(pos[key]);
34447 break;
34448 }
34449 }
34450 }
34451
34452 for (i = 0; i < yaxes.length; ++i) {
34453 axis = yaxes[i];
34454 if (axis && axis.used) {
34455 key = "y" + axis.n;
34456 if (pos[key] == null && axis.n == 1)
34457 key = "y";
34458
34459 if (pos[key] != null) {
34460 res.top = axis.p2c(pos[key]);
34461 break;
34462 }
34463 }
34464 }
34465
34466 return res;
34467 }
34468
34469 function getOrCreateAxis(axes, number) {
34470 if (!axes[number - 1])
34471 axes[number - 1] = {
34472 n: number, // save the number for future reference
34473 direction: axes == xaxes ? "x" : "y",
34474 options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis)
34475 };
34476
34477 return axes[number - 1];
34478 }
34479
34480 function fillInSeriesOptions() {
34481
34482 var neededColors = series.length, maxIndex = -1, i;
34483
34484 // Subtract the number of series that already have fixed colors or
34485 // color indexes from the number that we still need to generate.
34486
34487 for (i = 0; i < series.length; ++i) {
34488 var sc = series[i].color;
34489 if (sc != null) {
34490 neededColors--;
34491 if (typeof sc == "number" && sc > maxIndex) {
34492 maxIndex = sc;
34493 }
34494 }
34495 }
34496
34497 // If any of the series have fixed color indexes, then we need to
34498 // generate at least as many colors as the highest index.
34499
34500 if (neededColors <= maxIndex) {
34501 neededColors = maxIndex + 1;
34502 }
34503
34504 // Generate all the colors, using first the option colors and then
34505 // variations on those colors once they're exhausted.
34506
34507 var c, colors = [], colorPool = options.colors,
34508 colorPoolSize = colorPool.length, variation = 0;
34509
34510 for (i = 0; i < neededColors; i++) {
34511
34512 c = $.color.parse(colorPool[i % colorPoolSize] || "#666");
34513
34514 // Each time we exhaust the colors in the pool we adjust
34515 // a scaling factor used to produce more variations on
34516 // those colors. The factor alternates negative/positive
34517 // to produce lighter/darker colors.
34518
34519 // Reset the variation after every few cycles, or else
34520 // it will end up producing only white or black colors.
34521
34522 if (i % colorPoolSize == 0 && i) {
34523 if (variation >= 0) {
34524 if (variation < 0.5) {
34525 variation = -variation - 0.2;
34526 } else variation = 0;
34527 } else variation = -variation;
34528 }
34529
34530 colors[i] = c.scale('rgb', 1 + variation);
34531 }
34532
34533 // Finalize the series options, filling in their colors
34534
34535 var colori = 0, s;
34536 for (i = 0; i < series.length; ++i) {
34537 s = series[i];
34538
34539 // assign colors
34540 if (s.color == null) {
34541 s.color = colors[colori].toString();
34542 ++colori;
34543 }
34544 else if (typeof s.color == "number")
34545 s.color = colors[s.color].toString();
34546
34547 // turn on lines automatically in case nothing is set
34548 if (s.lines.show == null) {
34549 var v, show = true;
34550 for (v in s)
34551 if (s[v] && s[v].show) {
34552 show = false;
34553 break;
34554 }
34555 if (show)
34556 s.lines.show = true;
34557 }
34558
34559 // If nothing was provided for lines.zero, default it to match
34560 // lines.fill, since areas by default should extend to zero.
34561
34562 if (s.lines.zero == null) {
34563 s.lines.zero = !!s.lines.fill;
34564 }
34565
34566 // setup axes
34567 s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x"));
34568 s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y"));
34569 }
34570 }
34571
34572 function processData() {
34573 var topSentry = Number.POSITIVE_INFINITY,
34574 bottomSentry = Number.NEGATIVE_INFINITY,
34575 fakeInfinity = Number.MAX_VALUE,
34576 i, j, k, m, length,
34577 s, points, ps, x, y, axis, val, f, p,
34578 data, format;
34579
34580 function updateAxis(axis, min, max) {
34581 if (min < axis.datamin && min != -fakeInfinity)
34582 axis.datamin = min;
34583 if (max > axis.datamax && max != fakeInfinity)
34584 axis.datamax = max;
34585 }
34586
34587 $.each(allAxes(), function (_, axis) {
34588 // init axis
34589 axis.datamin = topSentry;
34590 axis.datamax = bottomSentry;
34591 axis.used = false;
34592 });
34593
34594 for (i = 0; i < series.length; ++i) {
34595 s = series[i];
34596 s.datapoints = { points: [] };
34597
34598 executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]);
34599 }
34600
34601 // first pass: clean and copy data
34602 for (i = 0; i < series.length; ++i) {
34603 s = series[i];
34604
34605 data = s.data;
34606 format = s.datapoints.format;
34607
34608 if (!format) {
34609 format = [];
34610 // find out how to copy
34611 format.push({ x: true, number: true, required: true });
34612 format.push({ y: true, number: true, required: true });
34613
34614 if (s.bars.show || (s.lines.show && s.lines.fill)) {
34615 var autoscale = !!((s.bars.show && s.bars.zero) || (s.lines.show && s.lines.zero));
34616 format.push({ y: true, number: true, required: false, defaultValue: 0, autoscale: autoscale });
34617 if (s.bars.horizontal) {
34618 delete format[format.length - 1].y;
34619 format[format.length - 1].x = true;
34620 }
34621 }
34622
34623 s.datapoints.format = format;
34624 }
34625
34626 if (s.datapoints.pointsize != null)
34627 continue; // already filled in
34628
34629 s.datapoints.pointsize = format.length;
34630
34631 ps = s.datapoints.pointsize;
34632 points = s.datapoints.points;
34633
34634 var insertSteps = s.lines.show && s.lines.steps;
34635 s.xaxis.used = s.yaxis.used = true;
34636
34637 for (j = k = 0; j < data.length; ++j, k += ps) {
34638 p = data[j];
34639
34640 var nullify = p == null;
34641 if (!nullify) {
34642 for (m = 0; m < ps; ++m) {
34643 val = p[m];
34644 f = format[m];
34645
34646 if (f) {
34647 if (f.number && val != null) {
34648 val = +val; // convert to number
34649 if (isNaN(val))
34650 val = null;
34651 else if (val == Infinity)
34652 val = fakeInfinity;
34653 else if (val == -Infinity)
34654 val = -fakeInfinity;
34655 }
34656
34657 if (val == null) {
34658 if (f.required)
34659 nullify = true;
34660
34661 if (f.defaultValue != null)
34662 val = f.defaultValue;
34663 }
34664 }
34665
34666 points[k + m] = val;
34667 }
34668 }
34669
34670 if (nullify) {
34671 for (m = 0; m < ps; ++m) {
34672 val = points[k + m];
34673 if (val != null) {
34674 f = format[m];
34675 // extract min/max info
34676 if (f.autoscale !== false) {
34677 if (f.x) {
34678 updateAxis(s.xaxis, val, val);
34679 }
34680 if (f.y) {
34681 updateAxis(s.yaxis, val, val);
34682 }
34683 }
34684 }
34685 points[k + m] = null;
34686 }
34687 }
34688 else {
34689 // a little bit of line specific stuff that
34690 // perhaps shouldn't be here, but lacking
34691 // better means...
34692 if (insertSteps && k > 0
34693 && points[k - ps] != null
34694 && points[k - ps] != points[k]
34695 && points[k - ps + 1] != points[k + 1]) {
34696 // copy the point to make room for a middle point
34697 for (m = 0; m < ps; ++m)
34698 points[k + ps + m] = points[k + m];
34699
34700 // middle point has same y
34701 points[k + 1] = points[k - ps + 1];
34702
34703 // we've added a point, better reflect that
34704 k += ps;
34705 }
34706 }
34707 }
34708 }
34709
34710 // give the hooks a chance to run
34711 for (i = 0; i < series.length; ++i) {
34712 s = series[i];
34713
34714 executeHooks(hooks.processDatapoints, [ s, s.datapoints]);
34715 }
34716
34717 // second pass: find datamax/datamin for auto-scaling
34718 for (i = 0; i < series.length; ++i) {
34719 s = series[i];
34720 points = s.datapoints.points;
34721 ps = s.datapoints.pointsize;
34722 format = s.datapoints.format;
34723
34724 var xmin = topSentry, ymin = topSentry,
34725 xmax = bottomSentry, ymax = bottomSentry;
34726
34727 for (j = 0; j < points.length; j += ps) {
34728 if (points[j] == null)
34729 continue;
34730
34731 for (m = 0; m < ps; ++m) {
34732 val = points[j + m];
34733 f = format[m];
34734 if (!f || f.autoscale === false || val == fakeInfinity || val == -fakeInfinity)
34735 continue;
34736
34737 if (f.x) {
34738 if (val < xmin)
34739 xmin = val;
34740 if (val > xmax)
34741 xmax = val;
34742 }
34743 if (f.y) {
34744 if (val < ymin)
34745 ymin = val;
34746 if (val > ymax)
34747 ymax = val;
34748 }
34749 }
34750 }
34751
34752 if (s.bars.show) {
34753 // make sure we got room for the bar on the dancing floor
34754 var delta;
34755
34756 switch (s.bars.align) {
34757 case "left":
34758 delta = 0;
34759 break;
34760 case "right":
34761 delta = -s.bars.barWidth;
34762 break;
34763 default:
34764 delta = -s.bars.barWidth / 2;
34765 }
34766
34767 if (s.bars.horizontal) {
34768 ymin += delta;
34769 ymax += delta + s.bars.barWidth;
34770 }
34771 else {
34772 xmin += delta;
34773 xmax += delta + s.bars.barWidth;
34774 }
34775 }
34776
34777 updateAxis(s.xaxis, xmin, xmax);
34778 updateAxis(s.yaxis, ymin, ymax);
34779 }
34780
34781 $.each(allAxes(), function (_, axis) {
34782 if (axis.datamin == topSentry)
34783 axis.datamin = null;
34784 if (axis.datamax == bottomSentry)
34785 axis.datamax = null;
34786 });
34787 }
34788
34789 function setupCanvases() {
34790
34791 // Make sure the placeholder is clear of everything except canvases
34792 // from a previous plot in this container that we'll try to re-use.
34793
34794 placeholder.css("padding", 0) // padding messes up the positioning
34795 .children().filter(function(){
34796 return !$(this).hasClass("flot-overlay") && !$(this).hasClass('flot-base');
34797 }).remove();
34798
34799 if (placeholder.css("position") == 'static')
34800 placeholder.css("position", "relative"); // for positioning labels and overlay
34801
34802 surface = new Canvas("flot-base", placeholder);
34803 overlay = new Canvas("flot-overlay", placeholder); // overlay canvas for interactive features
34804
34805 ctx = surface.context;
34806 octx = overlay.context;
34807
34808 // define which element we're listening for events on
34809 eventHolder = $(overlay.element).unbind();
34810
34811 // If we're re-using a plot object, shut down the old one
34812
34813 var existing = placeholder.data("plot");
34814
34815 if (existing) {
34816 existing.shutdown();
34817 overlay.clear();
34818 }
34819
34820 // save in case we get replotted
34821 placeholder.data("plot", plot);
34822 }
34823
34824 function bindEvents() {
34825 // bind events
34826 if (options.grid.hoverable) {
34827 eventHolder.mousemove(onMouseMove);
34828
34829 // Use bind, rather than .mouseleave, because we officially
34830 // still support jQuery 1.2.6, which doesn't define a shortcut
34831 // for mouseenter or mouseleave. This was a bug/oversight that
34832 // was fixed somewhere around 1.3.x. We can return to using
34833 // .mouseleave when we drop support for 1.2.6.
34834
34835 eventHolder.bind("mouseleave", onMouseLeave);
34836 }
34837
34838 if (options.grid.clickable)
34839 eventHolder.click(onClick);
34840
34841 executeHooks(hooks.bindEvents, [eventHolder]);
34842 }
34843
34844 function shutdown() {
34845 if (redrawTimeout)
34846 clearTimeout(redrawTimeout);
34847
34848 eventHolder.unbind("mousemove", onMouseMove);
34849 eventHolder.unbind("mouseleave", onMouseLeave);
34850 eventHolder.unbind("click", onClick);
34851
34852 executeHooks(hooks.shutdown, [eventHolder]);
34853 }
34854
34855 function setTransformationHelpers(axis) {
34856 // set helper functions on the axis, assumes plot area
34857 // has been computed already
34858
34859 function identity(x) { return x; }
34860
34861 var s, m, t = axis.options.transform || identity,
34862 it = axis.options.inverseTransform;
34863
34864 // precompute how much the axis is scaling a point
34865 // in canvas space
34866 if (axis.direction == "x") {
34867 s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min));
34868 m = Math.min(t(axis.max), t(axis.min));
34869 }
34870 else {
34871 s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min));
34872 s = -s;
34873 m = Math.max(t(axis.max), t(axis.min));
34874 }
34875
34876 // data point to canvas coordinate
34877 if (t == identity) // slight optimization
34878 axis.p2c = function (p) { return (p - m) * s; };
34879 else
34880 axis.p2c = function (p) { return (t(p) - m) * s; };
34881 // canvas coordinate to data point
34882 if (!it)
34883 axis.c2p = function (c) { return m + c / s; };
34884 else
34885 axis.c2p = function (c) { return it(m + c / s); };
34886 }
34887
34888 function measureTickLabels(axis) {
34889
34890 var opts = axis.options,
34891 ticks = axis.ticks || [],
34892 labelWidth = opts.labelWidth || 0,
34893 labelHeight = opts.labelHeight || 0,
34894 maxWidth = labelWidth || (axis.direction == "x" ? Math.floor(surface.width / (ticks.length || 1)) : null),
34895 legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis",
34896 layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles,
34897 font = opts.font || "flot-tick-label tickLabel";
34898
34899 for (var i = 0; i < ticks.length; ++i) {
34900
34901 var t = ticks[i];
34902
34903 if (!t.label)
34904 continue;
34905
34906 var info = surface.getTextInfo(layer, t.label, font, null, maxWidth);
34907
34908 labelWidth = Math.max(labelWidth, info.width);
34909 labelHeight = Math.max(labelHeight, info.height);
34910 }
34911
34912 axis.labelWidth = opts.labelWidth || labelWidth;
34913 axis.labelHeight = opts.labelHeight || labelHeight;
34914 }
34915
34916 function allocateAxisBoxFirstPhase(axis) {
34917 // find the bounding box of the axis by looking at label
34918 // widths/heights and ticks, make room by diminishing the
34919 // plotOffset; this first phase only looks at one
34920 // dimension per axis, the other dimension depends on the
34921 // other axes so will have to wait
34922
34923 var lw = axis.labelWidth,
34924 lh = axis.labelHeight,
34925 pos = axis.options.position,
34926 isXAxis = axis.direction === "x",
34927 tickLength = axis.options.tickLength,
34928 axisMargin = options.grid.axisMargin,
34929 padding = options.grid.labelMargin,
34930 innermost = true,
34931 outermost = true,
34932 first = true,
34933 found = false;
34934
34935 // Determine the axis's position in its direction and on its side
34936
34937 $.each(isXAxis ? xaxes : yaxes, function(i, a) {
34938 if (a && a.reserveSpace) {
34939 if (a === axis) {
34940 found = true;
34941 } else if (a.options.position === pos) {
34942 if (found) {
34943 outermost = false;
34944 } else {
34945 innermost = false;
34946 }
34947 }
34948 if (!found) {
34949 first = false;
34950 }
34951 }
34952 });
34953
34954 // The outermost axis on each side has no margin
34955
34956 if (outermost) {
34957 axisMargin = 0;
34958 }
34959
34960 // The ticks for the first axis in each direction stretch across
34961
34962 if (tickLength == null) {
34963 tickLength = first ? "full" : 5;
34964 }
34965
34966 if (!isNaN(+tickLength))
34967 padding += +tickLength;
34968
34969 if (isXAxis) {
34970 lh += padding;
34971
34972 if (pos == "bottom") {
34973 plotOffset.bottom += lh + axisMargin;
34974 axis.box = { top: surface.height - plotOffset.bottom, height: lh };
34975 }
34976 else {
34977 axis.box = { top: plotOffset.top + axisMargin, height: lh };
34978 plotOffset.top += lh + axisMargin;
34979 }
34980 }
34981 else {
34982 lw += padding;
34983
34984 if (pos == "left") {
34985 axis.box = { left: plotOffset.left + axisMargin, width: lw };
34986 plotOffset.left += lw + axisMargin;
34987 }
34988 else {
34989 plotOffset.right += lw + axisMargin;
34990 axis.box = { left: surface.width - plotOffset.right, width: lw };
34991 }
34992 }
34993
34994 // save for future reference
34995 axis.position = pos;
34996 axis.tickLength = tickLength;
34997 axis.box.padding = padding;
34998 axis.innermost = innermost;
34999 }
35000
35001 function allocateAxisBoxSecondPhase(axis) {
35002 // now that all axis boxes have been placed in one
35003 // dimension, we can set the remaining dimension coordinates
35004 if (axis.direction == "x") {
35005 axis.box.left = plotOffset.left - axis.labelWidth / 2;
35006 axis.box.width = surface.width - plotOffset.left - plotOffset.right + axis.labelWidth;
35007 }
35008 else {
35009 axis.box.top = plotOffset.top - axis.labelHeight / 2;
35010 axis.box.height = surface.height - plotOffset.bottom - plotOffset.top + axis.labelHeight;
35011 }
35012 }
35013
35014 function adjustLayoutForThingsStickingOut() {
35015 // possibly adjust plot offset to ensure everything stays
35016 // inside the canvas and isn't clipped off
35017
35018 var minMargin = options.grid.minBorderMargin,
35019 axis, i;
35020
35021 // check stuff from the plot (FIXME: this should just read
35022 // a value from the series, otherwise it's impossible to
35023 // customize)
35024 if (minMargin == null) {
35025 minMargin = 0;
35026 for (i = 0; i < series.length; ++i)
35027 minMargin = Math.max(minMargin, 2 * (series[i].points.radius + series[i].points.lineWidth/2));
35028 }
35029
35030 var margins = {
35031 left: minMargin,
35032 right: minMargin,
35033 top: minMargin,
35034 bottom: minMargin
35035 };
35036
35037 // check axis labels, note we don't check the actual
35038 // labels but instead use the overall width/height to not
35039 // jump as much around with replots
35040 $.each(allAxes(), function (_, axis) {
35041 if (axis.reserveSpace && axis.ticks && axis.ticks.length) {
35042 var lastTick = axis.ticks[axis.ticks.length - 1];
35043 if (axis.direction === "x") {
35044 margins.left = Math.max(margins.left, axis.labelWidth / 2);
35045 if (lastTick.v <= axis.max) {
35046 margins.right = Math.max(margins.right, axis.labelWidth / 2);
35047 }
35048 } else {
35049 margins.bottom = Math.max(margins.bottom, axis.labelHeight / 2);
35050 if (lastTick.v <= axis.max) {
35051 margins.top = Math.max(margins.top, axis.labelHeight / 2);
35052 }
35053 }
35054 }
35055 });
35056
35057 plotOffset.left = Math.ceil(Math.max(margins.left, plotOffset.left));
35058 plotOffset.right = Math.ceil(Math.max(margins.right, plotOffset.right));
35059 plotOffset.top = Math.ceil(Math.max(margins.top, plotOffset.top));
35060 plotOffset.bottom = Math.ceil(Math.max(margins.bottom, plotOffset.bottom));
35061 }
35062
35063 function setupGrid() {
35064 var i, axes = allAxes(), showGrid = options.grid.show;
35065
35066 // Initialize the plot's offset from the edge of the canvas
35067
35068 for (var a in plotOffset) {
35069 var margin = options.grid.margin || 0;
35070 plotOffset[a] = typeof margin == "number" ? margin : margin[a] || 0;
35071 }
35072
35073 executeHooks(hooks.processOffset, [plotOffset]);
35074
35075 // If the grid is visible, add its border width to the offset
35076
35077 for (var a in plotOffset) {
35078 if(typeof(options.grid.borderWidth) == "object") {
35079 plotOffset[a] += showGrid ? options.grid.borderWidth[a] : 0;
35080 }
35081 else {
35082 plotOffset[a] += showGrid ? options.grid.borderWidth : 0;
35083 }
35084 }
35085
35086 // init axes
35087 $.each(axes, function (_, axis) {
35088 axis.show = axis.options.show;
35089 if (axis.show == null)
35090 axis.show = axis.used; // by default an axis is visible if it's got data
35091
35092 axis.reserveSpace = axis.show || axis.options.reserveSpace;
35093
35094 setRange(axis);
35095 });
35096
35097 if (showGrid) {
35098
35099 var allocatedAxes = $.grep(axes, function (axis) { return axis.reserveSpace; });
35100
35101 $.each(allocatedAxes, function (_, axis) {
35102 // make the ticks
35103 setupTickGeneration(axis);
35104 setTicks(axis);
35105 snapRangeToTicks(axis, axis.ticks);
35106 // find labelWidth/Height for axis
35107 measureTickLabels(axis);
35108 });
35109
35110 // with all dimensions calculated, we can compute the
35111 // axis bounding boxes, start from the outside
35112 // (reverse order)
35113 for (i = allocatedAxes.length - 1; i >= 0; --i)
35114 allocateAxisBoxFirstPhase(allocatedAxes[i]);
35115
35116 // make sure we've got enough space for things that
35117 // might stick out
35118 adjustLayoutForThingsStickingOut();
35119
35120 $.each(allocatedAxes, function (_, axis) {
35121 allocateAxisBoxSecondPhase(axis);
35122 });
35123 }
35124
35125 plotWidth = surface.width - plotOffset.left - plotOffset.right;
35126 plotHeight = surface.height - plotOffset.bottom - plotOffset.top;
35127
35128 // now we got the proper plot dimensions, we can compute the scaling
35129 $.each(axes, function (_, axis) {
35130 setTransformationHelpers(axis);
35131 });
35132
35133 if (showGrid) {
35134 drawAxisLabels();
35135 }
35136
35137 insertLegend();
35138 }
35139
35140 function setRange(axis) {
35141 var opts = axis.options,
35142 min = +(opts.min != null ? opts.min : axis.datamin),
35143 max = +(opts.max != null ? opts.max : axis.datamax),
35144 delta = max - min;
35145
35146 if (delta == 0.0) {
35147 // degenerate case
35148 var widen = max == 0 ? 1 : 0.01;
35149
35150 if (opts.min == null)
35151 min -= widen;
35152 // always widen max if we couldn't widen min to ensure we
35153 // don't fall into min == max which doesn't work
35154 if (opts.max == null || opts.min != null)
35155 max += widen;
35156 }
35157 else {
35158 // consider autoscaling
35159 var margin = opts.autoscaleMargin;
35160 if (margin != null) {
35161 if (opts.min == null) {
35162 min -= delta * margin;
35163 // make sure we don't go below zero if all values
35164 // are positive
35165 if (min < 0 && axis.datamin != null && axis.datamin >= 0)
35166 min = 0;
35167 }
35168 if (opts.max == null) {
35169 max += delta * margin;
35170 if (max > 0 && axis.datamax != null && axis.datamax <= 0)
35171 max = 0;
35172 }
35173 }
35174 }
35175 axis.min = min;
35176 axis.max = max;
35177 }
35178
35179 function setupTickGeneration(axis) {
35180 var opts = axis.options;
35181
35182 // estimate number of ticks
35183 var noTicks;
35184 if (typeof opts.ticks == "number" && opts.ticks > 0)
35185 noTicks = opts.ticks;
35186 else
35187 // heuristic based on the model a*sqrt(x) fitted to
35188 // some data points that seemed reasonable
35189 noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? surface.width : surface.height);
35190
35191 var delta = (axis.max - axis.min) / noTicks,
35192 dec = -Math.floor(Math.log(delta) / Math.LN10),
35193 maxDec = opts.tickDecimals;
35194
35195 if (maxDec != null && dec > maxDec) {
35196 dec = maxDec;
35197 }
35198
35199 var magn = Math.pow(10, -dec),
35200 norm = delta / magn, // norm is between 1.0 and 10.0
35201 size;
35202
35203 if (norm < 1.5) {
35204 size = 1;
35205 } else if (norm < 3) {
35206 size = 2;
35207 // special case for 2.5, requires an extra decimal
35208 if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) {
35209 size = 2.5;
35210 ++dec;
35211 }
35212 } else if (norm < 7.5) {
35213 size = 5;
35214 } else {
35215 size = 10;
35216 }
35217
35218 size *= magn;
35219
35220 if (opts.minTickSize != null && size < opts.minTickSize) {
35221 size = opts.minTickSize;
35222 }
35223
35224 axis.delta = delta;
35225 axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec);
35226 axis.tickSize = opts.tickSize || size;
35227
35228 // Time mode was moved to a plug-in in 0.8, and since so many people use it
35229 // we'll add an especially friendly reminder to make sure they included it.
35230
35231 if (opts.mode == "time" && !axis.tickGenerator) {
35232 throw new Error("Time mode requires the flot.time plugin.");
35233 }
35234
35235 // Flot supports base-10 axes; any other mode else is handled by a plug-in,
35236 // like flot.time.js.
35237
35238 if (!axis.tickGenerator) {
35239
35240 axis.tickGenerator = function (axis) {
35241
35242 var ticks = [],
35243 start = floorInBase(axis.min, axis.tickSize),
35244 i = 0,
35245 v = Number.NaN,
35246 prev;
35247
35248 do {
35249 prev = v;
35250 v = start + i * axis.tickSize;
35251 ticks.push(v);
35252 ++i;
35253 } while (v < axis.max && v != prev);
35254 return ticks;
35255 };
35256
35257 axis.tickFormatter = function (value, axis) {
35258
35259 var factor = axis.tickDecimals ? Math.pow(10, axis.tickDecimals) : 1;
35260 var formatted = "" + Math.round(value * factor) / factor;
35261
35262 // If tickDecimals was specified, ensure that we have exactly that
35263 // much precision; otherwise default to the value's own precision.
35264
35265 if (axis.tickDecimals != null) {
35266 var decimal = formatted.indexOf(".");
35267 var precision = decimal == -1 ? 0 : formatted.length - decimal - 1;
35268 if (precision < axis.tickDecimals) {
35269 return (precision ? formatted : formatted + ".") + ("" + factor).substr(1, axis.tickDecimals - precision);
35270 }
35271 }
35272
35273 return formatted;
35274 };
35275 }
35276
35277 if ($.isFunction(opts.tickFormatter))
35278 axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); };
35279
35280 if (opts.alignTicksWithAxis != null) {
35281 var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1];
35282 if (otherAxis && otherAxis.used && otherAxis != axis) {
35283 // consider snapping min/max to outermost nice ticks
35284 var niceTicks = axis.tickGenerator(axis);
35285 if (niceTicks.length > 0) {
35286 if (opts.min == null)
35287 axis.min = Math.min(axis.min, niceTicks[0]);
35288 if (opts.max == null && niceTicks.length > 1)
35289 axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]);
35290 }
35291
35292 axis.tickGenerator = function (axis) {
35293 // copy ticks, scaled to this axis
35294 var ticks = [], v, i;
35295 for (i = 0; i < otherAxis.ticks.length; ++i) {
35296 v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min);
35297 v = axis.min + v * (axis.max - axis.min);
35298 ticks.push(v);
35299 }
35300 return ticks;
35301 };
35302
35303 // we might need an extra decimal since forced
35304 // ticks don't necessarily fit naturally
35305 if (!axis.mode && opts.tickDecimals == null) {
35306 var extraDec = Math.max(0, -Math.floor(Math.log(axis.delta) / Math.LN10) + 1),
35307 ts = axis.tickGenerator(axis);
35308
35309 // only proceed if the tick interval rounded
35310 // with an extra decimal doesn't give us a
35311 // zero at end
35312 if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec))))
35313 axis.tickDecimals = extraDec;
35314 }
35315 }
35316 }
35317 }
35318
35319 function setTicks(axis) {
35320 var oticks = axis.options.ticks, ticks = [];
35321 if (oticks == null || (typeof oticks == "number" && oticks > 0))
35322 ticks = axis.tickGenerator(axis);
35323 else if (oticks) {
35324 if ($.isFunction(oticks))
35325 // generate the ticks
35326 ticks = oticks(axis);
35327 else
35328 ticks = oticks;
35329 }
35330
35331 // clean up/labelify the supplied ticks, copy them over
35332 var i, v;
35333 axis.ticks = [];
35334 for (i = 0; i < ticks.length; ++i) {
35335 var label = null;
35336 var t = ticks[i];
35337 if (typeof t == "object") {
35338 v = +t[0];
35339 if (t.length > 1)
35340 label = t[1];
35341 }
35342 else
35343 v = +t;
35344 if (label == null)
35345 label = axis.tickFormatter(v, axis);
35346 if (!isNaN(v))
35347 axis.ticks.push({ v: v, label: label });
35348 }
35349 }
35350
35351 function snapRangeToTicks(axis, ticks) {
35352 if (axis.options.autoscaleMargin && ticks.length > 0) {
35353 // snap to ticks
35354 if (axis.options.min == null)
35355 axis.min = Math.min(axis.min, ticks[0].v);
35356 if (axis.options.max == null && ticks.length > 1)
35357 axis.max = Math.max(axis.max, ticks[ticks.length - 1].v);
35358 }
35359 }
35360
35361 function draw() {
35362
35363 surface.clear();
35364
35365 executeHooks(hooks.drawBackground, [ctx]);
35366
35367 var grid = options.grid;
35368
35369 // draw background, if any
35370 if (grid.show && grid.backgroundColor)
35371 drawBackground();
35372
35373 if (grid.show && !grid.aboveData) {
35374 drawGrid();
35375 }
35376
35377 for (var i = 0; i < series.length; ++i) {
35378 executeHooks(hooks.drawSeries, [ctx, series[i]]);
35379 drawSeries(series[i]);
35380 }
35381
35382 executeHooks(hooks.draw, [ctx]);
35383
35384 if (grid.show && grid.aboveData) {
35385 drawGrid();
35386 }
35387
35388 surface.render();
35389
35390 // A draw implies that either the axes or data have changed, so we
35391 // should probably update the overlay highlights as well.
35392
35393 triggerRedrawOverlay();
35394 }
35395
35396 function extractRange(ranges, coord) {
35397 var axis, from, to, key, axes = allAxes();
35398
35399 for (var i = 0; i < axes.length; ++i) {
35400 axis = axes[i];
35401 if (axis.direction == coord) {
35402 key = coord + axis.n + "axis";
35403 if (!ranges[key] && axis.n == 1)
35404 key = coord + "axis"; // support x1axis as xaxis
35405 if (ranges[key]) {
35406 from = ranges[key].from;
35407 to = ranges[key].to;
35408 break;
35409 }
35410 }
35411 }
35412
35413 // backwards-compat stuff - to be removed in future
35414 if (!ranges[key]) {
35415 axis = coord == "x" ? xaxes[0] : yaxes[0];
35416 from = ranges[coord + "1"];
35417 to = ranges[coord + "2"];
35418 }
35419
35420 // auto-reverse as an added bonus
35421 if (from != null && to != null && from > to) {
35422 var tmp = from;
35423 from = to;
35424 to = tmp;
35425 }
35426
35427 return { from: from, to: to, axis: axis };
35428 }
35429
35430 function drawBackground() {
35431 ctx.save();
35432 ctx.translate(plotOffset.left, plotOffset.top);
35433
35434 ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)");
35435 ctx.fillRect(0, 0, plotWidth, plotHeight);
35436 ctx.restore();
35437 }
35438
35439 function drawGrid() {
35440 var i, axes, bw, bc;
35441
35442 ctx.save();
35443 ctx.translate(plotOffset.left, plotOffset.top);
35444
35445 // draw markings
35446 var markings = options.grid.markings;
35447 if (markings) {
35448 if ($.isFunction(markings)) {
35449 axes = plot.getAxes();
35450 // xmin etc. is backwards compatibility, to be
35451 // removed in the future
35452 axes.xmin = axes.xaxis.min;
35453 axes.xmax = axes.xaxis.max;
35454 axes.ymin = axes.yaxis.min;
35455 axes.ymax = axes.yaxis.max;
35456
35457 markings = markings(axes);
35458 }
35459
35460 for (i = 0; i < markings.length; ++i) {
35461 var m = markings[i],
35462 xrange = extractRange(m, "x"),
35463 yrange = extractRange(m, "y");
35464
35465 // fill in missing
35466 if (xrange.from == null)
35467 xrange.from = xrange.axis.min;
35468 if (xrange.to == null)
35469 xrange.to = xrange.axis.max;
35470 if (yrange.from == null)
35471 yrange.from = yrange.axis.min;
35472 if (yrange.to == null)
35473 yrange.to = yrange.axis.max;
35474
35475 // clip
35476 if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max ||
35477 yrange.to < yrange.axis.min || yrange.from > yrange.axis.max)
35478 continue;
35479
35480 xrange.from = Math.max(xrange.from, xrange.axis.min);
35481 xrange.to = Math.min(xrange.to, xrange.axis.max);
35482 yrange.from = Math.max(yrange.from, yrange.axis.min);
35483 yrange.to = Math.min(yrange.to, yrange.axis.max);
35484
35485 var xequal = xrange.from === xrange.to,
35486 yequal = yrange.from === yrange.to;
35487
35488 if (xequal && yequal) {
35489 continue;
35490 }
35491
35492 // then draw
35493 xrange.from = Math.floor(xrange.axis.p2c(xrange.from));
35494 xrange.to = Math.floor(xrange.axis.p2c(xrange.to));
35495 yrange.from = Math.floor(yrange.axis.p2c(yrange.from));
35496 yrange.to = Math.floor(yrange.axis.p2c(yrange.to));
35497
35498 if (xequal || yequal) {
35499 var lineWidth = m.lineWidth || options.grid.markingsLineWidth,
35500 subPixel = lineWidth % 2 ? 0.5 : 0;
35501 ctx.beginPath();
35502 ctx.strokeStyle = m.color || options.grid.markingsColor;
35503 ctx.lineWidth = lineWidth;
35504 if (xequal) {
35505 ctx.moveTo(xrange.to + subPixel, yrange.from);
35506 ctx.lineTo(xrange.to + subPixel, yrange.to);
35507 } else {
35508 ctx.moveTo(xrange.from, yrange.to + subPixel);
35509 ctx.lineTo(xrange.to, yrange.to + subPixel);
35510 }
35511 ctx.stroke();
35512 } else {
35513 ctx.fillStyle = m.color || options.grid.markingsColor;
35514 ctx.fillRect(xrange.from, yrange.to,
35515 xrange.to - xrange.from,
35516 yrange.from - yrange.to);
35517 }
35518 }
35519 }
35520
35521 // draw the ticks
35522 axes = allAxes();
35523 bw = options.grid.borderWidth;
35524
35525 for (var j = 0; j < axes.length; ++j) {
35526 var axis = axes[j], box = axis.box,
35527 t = axis.tickLength, x, y, xoff, yoff;
35528 if (!axis.show || axis.ticks.length == 0)
35529 continue;
35530
35531 ctx.lineWidth = 1;
35532
35533 // find the edges
35534 if (axis.direction == "x") {
35535 x = 0;
35536 if (t == "full")
35537 y = (axis.position == "top" ? 0 : plotHeight);
35538 else
35539 y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0);
35540 }
35541 else {
35542 y = 0;
35543 if (t == "full")
35544 x = (axis.position == "left" ? 0 : plotWidth);
35545 else
35546 x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0);
35547 }
35548
35549 // draw tick bar
35550 if (!axis.innermost) {
35551 ctx.strokeStyle = axis.options.color;
35552 ctx.beginPath();
35553 xoff = yoff = 0;
35554 if (axis.direction == "x")
35555 xoff = plotWidth + 1;
35556 else
35557 yoff = plotHeight + 1;
35558
35559 if (ctx.lineWidth == 1) {
35560 if (axis.direction == "x") {
35561 y = Math.floor(y) + 0.5;
35562 } else {
35563 x = Math.floor(x) + 0.5;
35564 }
35565 }
35566
35567 ctx.moveTo(x, y);
35568 ctx.lineTo(x + xoff, y + yoff);
35569 ctx.stroke();
35570 }
35571
35572 // draw ticks
35573
35574 ctx.strokeStyle = axis.options.tickColor;
35575
35576 ctx.beginPath();
35577 for (i = 0; i < axis.ticks.length; ++i) {
35578 var v = axis.ticks[i].v;
35579
35580 xoff = yoff = 0;
35581
35582 if (isNaN(v) || v < axis.min || v > axis.max
35583 // skip those lying on the axes if we got a border
35584 || (t == "full"
35585 && ((typeof bw == "object" && bw[axis.position] > 0) || bw > 0)
35586 && (v == axis.min || v == axis.max)))
35587 continue;
35588
35589 if (axis.direction == "x") {
35590 x = axis.p2c(v);
35591 yoff = t == "full" ? -plotHeight : t;
35592
35593 if (axis.position == "top")
35594 yoff = -yoff;
35595 }
35596 else {
35597 y = axis.p2c(v);
35598 xoff = t == "full" ? -plotWidth : t;
35599
35600 if (axis.position == "left")
35601 xoff = -xoff;
35602 }
35603
35604 if (ctx.lineWidth == 1) {
35605 if (axis.direction == "x")
35606 x = Math.floor(x) + 0.5;
35607 else
35608 y = Math.floor(y) + 0.5;
35609 }
35610
35611 ctx.moveTo(x, y);
35612 ctx.lineTo(x + xoff, y + yoff);
35613 }
35614
35615 ctx.stroke();
35616 }
35617
35618
35619 // draw border
35620 if (bw) {
35621 // If either borderWidth or borderColor is an object, then draw the border
35622 // line by line instead of as one rectangle
35623 bc = options.grid.borderColor;
35624 if(typeof bw == "object" || typeof bc == "object") {
35625 if (typeof bw !== "object") {
35626 bw = {top: bw, right: bw, bottom: bw, left: bw};
35627 }
35628 if (typeof bc !== "object") {
35629 bc = {top: bc, right: bc, bottom: bc, left: bc};
35630 }
35631
35632 if (bw.top > 0) {
35633 ctx.strokeStyle = bc.top;
35634 ctx.lineWidth = bw.top;
35635 ctx.beginPath();
35636 ctx.moveTo(0 - bw.left, 0 - bw.top/2);
35637 ctx.lineTo(plotWidth, 0 - bw.top/2);
35638 ctx.stroke();
35639 }
35640
35641 if (bw.right > 0) {
35642 ctx.strokeStyle = bc.right;
35643 ctx.lineWidth = bw.right;
35644 ctx.beginPath();
35645 ctx.moveTo(plotWidth + bw.right / 2, 0 - bw.top);
35646 ctx.lineTo(plotWidth + bw.right / 2, plotHeight);
35647 ctx.stroke();
35648 }
35649
35650 if (bw.bottom > 0) {
35651 ctx.strokeStyle = bc.bottom;
35652 ctx.lineWidth = bw.bottom;
35653 ctx.beginPath();
35654 ctx.moveTo(plotWidth + bw.right, plotHeight + bw.bottom / 2);
35655 ctx.lineTo(0, plotHeight + bw.bottom / 2);
35656 ctx.stroke();
35657 }
35658
35659 if (bw.left > 0) {
35660 ctx.strokeStyle = bc.left;
35661 ctx.lineWidth = bw.left;
35662 ctx.beginPath();
35663 ctx.moveTo(0 - bw.left/2, plotHeight + bw.bottom);
35664 ctx.lineTo(0- bw.left/2, 0);
35665 ctx.stroke();
35666 }
35667 }
35668 else {
35669 ctx.lineWidth = bw;
35670 ctx.strokeStyle = options.grid.borderColor;
35671 ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw);
35672 }
35673 }
35674
35675 ctx.restore();
35676 }
35677
35678 function drawAxisLabels() {
35679
35680 $.each(allAxes(), function (_, axis) {
35681 var box = axis.box,
35682 legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis",
35683 layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles,
35684 font = axis.options.font || "flot-tick-label tickLabel",
35685 tick, x, y, halign, valign;
35686
35687 // Remove text before checking for axis.show and ticks.length;
35688 // otherwise plugins, like flot-tickrotor, that draw their own
35689 // tick labels will end up with both theirs and the defaults.
35690
35691 surface.removeText(layer);
35692
35693 if (!axis.show || axis.ticks.length == 0)
35694 return;
35695
35696 for (var i = 0; i < axis.ticks.length; ++i) {
35697
35698 tick = axis.ticks[i];
35699 if (!tick.label || tick.v < axis.min || tick.v > axis.max)
35700 continue;
35701
35702 if (axis.direction == "x") {
35703 halign = "center";
35704 x = plotOffset.left + axis.p2c(tick.v);
35705 if (axis.position == "bottom") {
35706 y = box.top + box.padding;
35707 } else {
35708 y = box.top + box.height - box.padding;
35709 valign = "bottom";
35710 }
35711 } else {
35712 valign = "middle";
35713 y = plotOffset.top + axis.p2c(tick.v);
35714 if (axis.position == "left") {
35715 x = box.left + box.width - box.padding;
35716 halign = "right";
35717 } else {
35718 x = box.left + box.padding;
35719 }
35720 }
35721
35722 surface.addText(layer, x, y, tick.label, font, null, null, halign, valign);
35723 }
35724 });
35725 }
35726
35727 function drawSeries(series) {
35728 if (series.lines.show)
35729 drawSeriesLines(series);
35730 if (series.bars.show)
35731 drawSeriesBars(series);
35732 if (series.points.show)
35733 drawSeriesPoints(series);
35734 }
35735
35736 function drawSeriesLines(series) {
35737 function plotLine(datapoints, xoffset, yoffset, axisx, axisy) {
35738 var points = datapoints.points,
35739 ps = datapoints.pointsize,
35740 prevx = null, prevy = null;
35741
35742 ctx.beginPath();
35743 for (var i = ps; i < points.length; i += ps) {
35744 var x1 = points[i - ps], y1 = points[i - ps + 1],
35745 x2 = points[i], y2 = points[i + 1];
35746
35747 if (x1 == null || x2 == null)
35748 continue;
35749
35750 // clip with ymin
35751 if (y1 <= y2 && y1 < axisy.min) {
35752 if (y2 < axisy.min)
35753 continue; // line segment is outside
35754 // compute new intersection point
35755 x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
35756 y1 = axisy.min;
35757 }
35758 else if (y2 <= y1 && y2 < axisy.min) {
35759 if (y1 < axisy.min)
35760 continue;
35761 x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
35762 y2 = axisy.min;
35763 }
35764
35765 // clip with ymax
35766 if (y1 >= y2 && y1 > axisy.max) {
35767 if (y2 > axisy.max)
35768 continue;
35769 x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
35770 y1 = axisy.max;
35771 }
35772 else if (y2 >= y1 && y2 > axisy.max) {
35773 if (y1 > axisy.max)
35774 continue;
35775 x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
35776 y2 = axisy.max;
35777 }
35778
35779 // clip with xmin
35780 if (x1 <= x2 && x1 < axisx.min) {
35781 if (x2 < axisx.min)
35782 continue;
35783 y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
35784 x1 = axisx.min;
35785 }
35786 else if (x2 <= x1 && x2 < axisx.min) {
35787 if (x1 < axisx.min)
35788 continue;
35789 y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
35790 x2 = axisx.min;
35791 }
35792
35793 // clip with xmax
35794 if (x1 >= x2 && x1 > axisx.max) {
35795 if (x2 > axisx.max)
35796 continue;
35797 y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
35798 x1 = axisx.max;
35799 }
35800 else if (x2 >= x1 && x2 > axisx.max) {
35801 if (x1 > axisx.max)
35802 continue;
35803 y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
35804 x2 = axisx.max;
35805 }
35806
35807 if (x1 != prevx || y1 != prevy)
35808 ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset);
35809
35810 prevx = x2;
35811 prevy = y2;
35812 ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset);
35813 }
35814 ctx.stroke();
35815 }
35816
35817 function plotLineArea(datapoints, axisx, axisy) {
35818 var points = datapoints.points,
35819 ps = datapoints.pointsize,
35820 bottom = Math.min(Math.max(0, axisy.min), axisy.max),
35821 i = 0, top, areaOpen = false,
35822 ypos = 1, segmentStart = 0, segmentEnd = 0;
35823
35824 // we process each segment in two turns, first forward
35825 // direction to sketch out top, then once we hit the
35826 // end we go backwards to sketch the bottom
35827 while (true) {
35828 if (ps > 0 && i > points.length + ps)
35829 break;
35830
35831 i += ps; // ps is negative if going backwards
35832
35833 var x1 = points[i - ps],
35834 y1 = points[i - ps + ypos],
35835 x2 = points[i], y2 = points[i + ypos];
35836
35837 if (areaOpen) {
35838 if (ps > 0 && x1 != null && x2 == null) {
35839 // at turning point
35840 segmentEnd = i;
35841 ps = -ps;
35842 ypos = 2;
35843 continue;
35844 }
35845
35846 if (ps < 0 && i == segmentStart + ps) {
35847 // done with the reverse sweep
35848 ctx.fill();
35849 areaOpen = false;
35850 ps = -ps;
35851 ypos = 1;
35852 i = segmentStart = segmentEnd + ps;
35853 continue;
35854 }
35855 }
35856
35857 if (x1 == null || x2 == null)
35858 continue;
35859
35860 // clip x values
35861
35862 // clip with xmin
35863 if (x1 <= x2 && x1 < axisx.min) {
35864 if (x2 < axisx.min)
35865 continue;
35866 y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
35867 x1 = axisx.min;
35868 }
35869 else if (x2 <= x1 && x2 < axisx.min) {
35870 if (x1 < axisx.min)
35871 continue;
35872 y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
35873 x2 = axisx.min;
35874 }
35875
35876 // clip with xmax
35877 if (x1 >= x2 && x1 > axisx.max) {
35878 if (x2 > axisx.max)
35879 continue;
35880 y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
35881 x1 = axisx.max;
35882 }
35883 else if (x2 >= x1 && x2 > axisx.max) {
35884 if (x1 > axisx.max)
35885 continue;
35886 y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
35887 x2 = axisx.max;
35888 }
35889
35890 if (!areaOpen) {
35891 // open area
35892 ctx.beginPath();
35893 ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom));
35894 areaOpen = true;
35895 }
35896
35897 // now first check the case where both is outside
35898 if (y1 >= axisy.max && y2 >= axisy.max) {
35899 ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max));
35900 ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max));
35901 continue;
35902 }
35903 else if (y1 <= axisy.min && y2 <= axisy.min) {
35904 ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min));
35905 ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min));
35906 continue;
35907 }
35908
35909 // else it's a bit more complicated, there might
35910 // be a flat maxed out rectangle first, then a
35911 // triangular cutout or reverse; to find these
35912 // keep track of the current x values
35913 var x1old = x1, x2old = x2;
35914
35915 // clip the y values, without shortcutting, we
35916 // go through all cases in turn
35917
35918 // clip with ymin
35919 if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) {
35920 x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
35921 y1 = axisy.min;
35922 }
35923 else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) {
35924 x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
35925 y2 = axisy.min;
35926 }
35927
35928 // clip with ymax
35929 if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) {
35930 x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
35931 y1 = axisy.max;
35932 }
35933 else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) {
35934 x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
35935 y2 = axisy.max;
35936 }
35937
35938 // if the x value was changed we got a rectangle
35939 // to fill
35940 if (x1 != x1old) {
35941 ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1));
35942 // it goes to (x1, y1), but we fill that below
35943 }
35944
35945 // fill triangular section, this sometimes result
35946 // in redundant points if (x1, y1) hasn't changed
35947 // from previous line to, but we just ignore that
35948 ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1));
35949 ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
35950
35951 // fill the other rectangle if it's there
35952 if (x2 != x2old) {
35953 ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
35954 ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2));
35955 }
35956 }
35957 }
35958
35959 ctx.save();
35960 ctx.translate(plotOffset.left, plotOffset.top);
35961 ctx.lineJoin = "round";
35962
35963 var lw = series.lines.lineWidth,
35964 sw = series.shadowSize;
35965 // FIXME: consider another form of shadow when filling is turned on
35966 if (lw > 0 && sw > 0) {
35967 // draw shadow as a thick and thin line with transparency
35968 ctx.lineWidth = sw;
35969 ctx.strokeStyle = "rgba(0,0,0,0.1)";
35970 // position shadow at angle from the mid of line
35971 var angle = Math.PI/18;
35972 plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis);
35973 ctx.lineWidth = sw/2;
35974 plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis);
35975 }
35976
35977 ctx.lineWidth = lw;
35978 ctx.strokeStyle = series.color;
35979 var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight);
35980 if (fillStyle) {
35981 ctx.fillStyle = fillStyle;
35982 plotLineArea(series.datapoints, series.xaxis, series.yaxis);
35983 }
35984
35985 if (lw > 0)
35986 plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis);
35987 ctx.restore();
35988 }
35989
35990 function drawSeriesPoints(series) {
35991 function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) {
35992 var points = datapoints.points, ps = datapoints.pointsize;
35993
35994 for (var i = 0; i < points.length; i += ps) {
35995 var x = points[i], y = points[i + 1];
35996 if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
35997 continue;
35998
35999 ctx.beginPath();
36000 x = axisx.p2c(x);
36001 y = axisy.p2c(y) + offset;
36002 if (symbol == "circle")
36003 ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false);
36004 else
36005 symbol(ctx, x, y, radius, shadow);
36006 ctx.closePath();
36007
36008 if (fillStyle) {
36009 ctx.fillStyle = fillStyle;
36010 ctx.fill();
36011 }
36012 ctx.stroke();
36013 }
36014 }
36015
36016 ctx.save();
36017 ctx.translate(plotOffset.left, plotOffset.top);
36018
36019 var lw = series.points.lineWidth,
36020 sw = series.shadowSize,
36021 radius = series.points.radius,
36022 symbol = series.points.symbol;
36023
36024 // If the user sets the line width to 0, we change it to a very
36025 // small value. A line width of 0 seems to force the default of 1.
36026 // Doing the conditional here allows the shadow setting to still be
36027 // optional even with a lineWidth of 0.
36028
36029 if( lw == 0 )
36030 lw = 0.0001;
36031
36032 if (lw > 0 && sw > 0) {
36033 // draw shadow in two steps
36034 var w = sw / 2;
36035 ctx.lineWidth = w;
36036 ctx.strokeStyle = "rgba(0,0,0,0.1)";
36037 plotPoints(series.datapoints, radius, null, w + w/2, true,
36038 series.xaxis, series.yaxis, symbol);
36039
36040 ctx.strokeStyle = "rgba(0,0,0,0.2)";
36041 plotPoints(series.datapoints, radius, null, w/2, true,
36042 series.xaxis, series.yaxis, symbol);
36043 }
36044
36045 ctx.lineWidth = lw;
36046 ctx.strokeStyle = series.color;
36047 plotPoints(series.datapoints, radius,
36048 getFillStyle(series.points, series.color), 0, false,
36049 series.xaxis, series.yaxis, symbol);
36050 ctx.restore();
36051 }
36052
36053 function drawBar(x, y, b, barLeft, barRight, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) {
36054 var left, right, bottom, top,
36055 drawLeft, drawRight, drawTop, drawBottom,
36056 tmp;
36057
36058 // in horizontal mode, we start the bar from the left
36059 // instead of from the bottom so it appears to be
36060 // horizontal rather than vertical
36061 if (horizontal) {
36062 drawBottom = drawRight = drawTop = true;
36063 drawLeft = false;
36064 left = b;
36065 right = x;
36066 top = y + barLeft;
36067 bottom = y + barRight;
36068
36069 // account for negative bars
36070 if (right < left) {
36071 tmp = right;
36072 right = left;
36073 left = tmp;
36074 drawLeft = true;
36075 drawRight = false;
36076 }
36077 }
36078 else {
36079 drawLeft = drawRight = drawTop = true;
36080 drawBottom = false;
36081 left = x + barLeft;
36082 right = x + barRight;
36083 bottom = b;
36084 top = y;
36085
36086 // account for negative bars
36087 if (top < bottom) {
36088 tmp = top;
36089 top = bottom;
36090 bottom = tmp;
36091 drawBottom = true;
36092 drawTop = false;
36093 }
36094 }
36095
36096 // clip
36097 if (right < axisx.min || left > axisx.max ||
36098 top < axisy.min || bottom > axisy.max)
36099 return;
36100
36101 if (left < axisx.min) {
36102 left = axisx.min;
36103 drawLeft = false;
36104 }
36105
36106 if (right > axisx.max) {
36107 right = axisx.max;
36108 drawRight = false;
36109 }
36110
36111 if (bottom < axisy.min) {
36112 bottom = axisy.min;
36113 drawBottom = false;
36114 }
36115
36116 if (top > axisy.max) {
36117 top = axisy.max;
36118 drawTop = false;
36119 }
36120
36121 left = axisx.p2c(left);
36122 bottom = axisy.p2c(bottom);
36123 right = axisx.p2c(right);
36124 top = axisy.p2c(top);
36125
36126 // fill the bar
36127 if (fillStyleCallback) {
36128 c.fillStyle = fillStyleCallback(bottom, top);
36129 c.fillRect(left, top, right - left, bottom - top)
36130 }
36131
36132 // draw outline
36133 if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) {
36134 c.beginPath();
36135
36136 // FIXME: inline moveTo is buggy with excanvas
36137 c.moveTo(left, bottom);
36138 if (drawLeft)
36139 c.lineTo(left, top);
36140 else
36141 c.moveTo(left, top);
36142 if (drawTop)
36143 c.lineTo(right, top);
36144 else
36145 c.moveTo(right, top);
36146 if (drawRight)
36147 c.lineTo(right, bottom);
36148 else
36149 c.moveTo(right, bottom);
36150 if (drawBottom)
36151 c.lineTo(left, bottom);
36152 else
36153 c.moveTo(left, bottom);
36154 c.stroke();
36155 }
36156 }
36157
36158 function drawSeriesBars(series) {
36159 function plotBars(datapoints, barLeft, barRight, fillStyleCallback, axisx, axisy) {
36160 var points = datapoints.points, ps = datapoints.pointsize;
36161
36162 for (var i = 0; i < points.length; i += ps) {
36163 if (points[i] == null)
36164 continue;
36165 drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth);
36166 }
36167 }
36168
36169 ctx.save();
36170 ctx.translate(plotOffset.left, plotOffset.top);
36171
36172 // FIXME: figure out a way to add shadows (for instance along the right edge)
36173 ctx.lineWidth = series.bars.lineWidth;
36174 ctx.strokeStyle = series.color;
36175
36176 var barLeft;
36177
36178 switch (series.bars.align) {
36179 case "left":
36180 barLeft = 0;
36181 break;
36182 case "right":
36183 barLeft = -series.bars.barWidth;
36184 break;
36185 default:
36186 barLeft = -series.bars.barWidth / 2;
36187 }
36188
36189 var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null;
36190 plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, fillStyleCallback, series.xaxis, series.yaxis);
36191 ctx.restore();
36192 }
36193
36194 function getFillStyle(filloptions, seriesColor, bottom, top) {
36195 var fill = filloptions.fill;
36196 if (!fill)
36197 return null;
36198
36199 if (filloptions.fillColor)
36200 return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor);
36201
36202 var c = $.color.parse(seriesColor);
36203 c.a = typeof fill == "number" ? fill : 0.4;
36204 c.normalize();
36205 return c.toString();
36206 }
36207
36208 function insertLegend() {
36209
36210 if (options.legend.container != null) {
36211 $(options.legend.container).html("");
36212 } else {
36213 placeholder.find(".legend").remove();
36214 }
36215
36216 if (!options.legend.show) {
36217 return;
36218 }
36219
36220 var fragments = [], entries = [], rowStarted = false,
36221 lf = options.legend.labelFormatter, s, label;
36222
36223 // Build a list of legend entries, with each having a label and a color
36224
36225 for (var i = 0; i < series.length; ++i) {
36226 s = series[i];
36227 if (s.label) {
36228 label = lf ? lf(s.label, s) : s.label;
36229 if (label) {
36230 entries.push({
36231 label: label,
36232 color: s.color
36233 });
36234 }
36235 }
36236 }
36237
36238 // Sort the legend using either the default or a custom comparator
36239
36240 if (options.legend.sorted) {
36241 if ($.isFunction(options.legend.sorted)) {
36242 entries.sort(options.legend.sorted);
36243 } else if (options.legend.sorted == "reverse") {
36244 entries.reverse();
36245 } else {
36246 var ascending = options.legend.sorted != "descending";
36247 entries.sort(function(a, b) {
36248 return a.label == b.label ? 0 : (
36249 (a.label < b.label) != ascending ? 1 : -1 // Logical XOR
36250 );
36251 });
36252 }
36253 }
36254
36255 // Generate markup for the list of entries, in their final order
36256
36257 for (var i = 0; i < entries.length; ++i) {
36258
36259 var entry = entries[i];
36260
36261 if (i % options.legend.noColumns == 0) {
36262 if (rowStarted)
36263 fragments.push('</tr>');
36264 fragments.push('<tr>');
36265 rowStarted = true;
36266 }
36267
36268 fragments.push(
36269 '<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + entry.color + ';overflow:hidden"></div></div></td>' +
36270 '<td class="legendLabel">' + entry.label + '</td>'
36271 );
36272 }
36273
36274 if (rowStarted)
36275 fragments.push('</tr>');
36276
36277 if (fragments.length == 0)
36278 return;
36279
36280 var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>';
36281 if (options.legend.container != null)
36282 $(options.legend.container).html(table);
36283 else {
36284 var pos = "",
36285 p = options.legend.position,
36286 m = options.legend.margin;
36287 if (m[0] == null)
36288 m = [m, m];
36289 if (p.charAt(0) == "n")
36290 pos += 'top:' + (m[1] + plotOffset.top) + 'px;';
36291 else if (p.charAt(0) == "s")
36292 pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;';
36293 if (p.charAt(1) == "e")
36294 pos += 'right:' + (m[0] + plotOffset.right) + 'px;';
36295 else if (p.charAt(1) == "w")
36296 pos += 'left:' + (m[0] + plotOffset.left) + 'px;';
36297 var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(placeholder);
36298 if (options.legend.backgroundOpacity != 0.0) {
36299 // put in the transparent background
36300 // separately to avoid blended labels and
36301 // label boxes
36302 var c = options.legend.backgroundColor;
36303 if (c == null) {
36304 c = options.grid.backgroundColor;
36305 if (c && typeof c == "string")
36306 c = $.color.parse(c);
36307 else
36308 c = $.color.extract(legend, 'background-color');
36309 c.a = 1;
36310 c = c.toString();
36311 }
36312 var div = legend.children();
36313 $('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity);
36314 }
36315 }
36316 }
36317
36318
36319 // interactive features
36320
36321 var highlights = [],
36322 redrawTimeout = null;
36323
36324 // returns the data item the mouse is over, or null if none is found
36325 function findNearbyItem(mouseX, mouseY, seriesFilter) {
36326 var maxDistance = options.grid.mouseActiveRadius,
36327 smallestDistance = maxDistance * maxDistance + 1,
36328 item = null, foundPoint = false, i, j, ps;
36329
36330 for (i = series.length - 1; i >= 0; --i) {
36331 if (!seriesFilter(series[i]))
36332 continue;
36333
36334 var s = series[i],
36335 axisx = s.xaxis,
36336 axisy = s.yaxis,
36337 points = s.datapoints.points,
36338 mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster
36339 my = axisy.c2p(mouseY),
36340 maxx = maxDistance / axisx.scale,
36341 maxy = maxDistance / axisy.scale;
36342
36343 ps = s.datapoints.pointsize;
36344 // with inverse transforms, we can't use the maxx/maxy
36345 // optimization, sadly
36346 if (axisx.options.inverseTransform)
36347 maxx = Number.MAX_VALUE;
36348 if (axisy.options.inverseTransform)
36349 maxy = Number.MAX_VALUE;
36350
36351 if (s.lines.show || s.points.show) {
36352 for (j = 0; j < points.length; j += ps) {
36353 var x = points[j], y = points[j + 1];
36354 if (x == null)
36355 continue;
36356
36357 // For points and lines, the cursor must be within a
36358 // certain distance to the data point
36359 if (x - mx > maxx || x - mx < -maxx ||
36360 y - my > maxy || y - my < -maxy)
36361 continue;
36362
36363 // We have to calculate distances in pixels, not in
36364 // data units, because the scales of the axes may be different
36365 var dx = Math.abs(axisx.p2c(x) - mouseX),
36366 dy = Math.abs(axisy.p2c(y) - mouseY),
36367 dist = dx * dx + dy * dy; // we save the sqrt
36368
36369 // use <= to ensure last point takes precedence
36370 // (last generally means on top of)
36371 if (dist < smallestDistance) {
36372 smallestDistance = dist;
36373 item = [i, j / ps];
36374 }
36375 }
36376 }
36377
36378 if (s.bars.show && !item) { // no other point can be nearby
36379
36380 var barLeft, barRight;
36381
36382 switch (s.bars.align) {
36383 case "left":
36384 barLeft = 0;
36385 break;
36386 case "right":
36387 barLeft = -s.bars.barWidth;
36388 break;
36389 default:
36390 barLeft = -s.bars.barWidth / 2;
36391 }
36392
36393 barRight = barLeft + s.bars.barWidth;
36394
36395 for (j = 0; j < points.length; j += ps) {
36396 var x = points[j], y = points[j + 1], b = points[j + 2];
36397 if (x == null)
36398 continue;
36399
36400 // for a bar graph, the cursor must be inside the bar
36401 if (series[i].bars.horizontal ?
36402 (mx <= Math.max(b, x) && mx >= Math.min(b, x) &&
36403 my >= y + barLeft && my <= y + barRight) :
36404 (mx >= x + barLeft && mx <= x + barRight &&
36405 my >= Math.min(b, y) && my <= Math.max(b, y)))
36406 item = [i, j / ps];
36407 }
36408 }
36409 }
36410
36411 if (item) {
36412 i = item[0];
36413 j = item[1];
36414 ps = series[i].datapoints.pointsize;
36415
36416 return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps),
36417 dataIndex: j,
36418 series: series[i],
36419 seriesIndex: i };
36420 }
36421
36422 return null;
36423 }
36424
36425 function onMouseMove(e) {
36426 if (options.grid.hoverable)
36427 triggerClickHoverEvent("plothover", e,
36428 function (s) { return s["hoverable"] != false; });
36429 }
36430
36431 function onMouseLeave(e) {
36432 if (options.grid.hoverable)
36433 triggerClickHoverEvent("plothover", e,
36434 function (s) { return false; });
36435 }
36436
36437 function onClick(e) {
36438 triggerClickHoverEvent("plotclick", e,
36439 function (s) { return s["clickable"] != false; });
36440 }
36441
36442 // trigger click or hover event (they send the same parameters
36443 // so we share their code)
36444 function triggerClickHoverEvent(eventname, event, seriesFilter) {
36445 var offset = eventHolder.offset(),
36446 canvasX = event.pageX - offset.left - plotOffset.left,
36447 canvasY = event.pageY - offset.top - plotOffset.top,
36448 pos = canvasToAxisCoords({ left: canvasX, top: canvasY });
36449
36450 pos.pageX = event.pageX;
36451 pos.pageY = event.pageY;
36452
36453 var item = findNearbyItem(canvasX, canvasY, seriesFilter);
36454
36455 if (item) {
36456 // fill in mouse pos for any listeners out there
36457 item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left, 10);
36458 item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top, 10);
36459 }
36460
36461 if (options.grid.autoHighlight) {
36462 // clear auto-highlights
36463 for (var i = 0; i < highlights.length; ++i) {
36464 var h = highlights[i];
36465 if (h.auto == eventname &&
36466 !(item && h.series == item.series &&
36467 h.point[0] == item.datapoint[0] &&
36468 h.point[1] == item.datapoint[1]))
36469 unhighlight(h.series, h.point);
36470 }
36471
36472 if (item)
36473 highlight(item.series, item.datapoint, eventname);
36474 }
36475
36476 placeholder.trigger(eventname, [ pos, item ]);
36477 }
36478
36479 function triggerRedrawOverlay() {
36480 var t = options.interaction.redrawOverlayInterval;
36481 if (t == -1) { // skip event queue
36482 drawOverlay();
36483 return;
36484 }
36485
36486 if (!redrawTimeout)
36487 redrawTimeout = setTimeout(drawOverlay, t);
36488 }
36489
36490 function drawOverlay() {
36491 redrawTimeout = null;
36492
36493 // draw highlights
36494 octx.save();
36495 overlay.clear();
36496 octx.translate(plotOffset.left, plotOffset.top);
36497
36498 var i, hi;
36499 for (i = 0; i < highlights.length; ++i) {
36500 hi = highlights[i];
36501
36502 if (hi.series.bars.show)
36503 drawBarHighlight(hi.series, hi.point);
36504 else
36505 drawPointHighlight(hi.series, hi.point);
36506 }
36507 octx.restore();
36508
36509 executeHooks(hooks.drawOverlay, [octx]);
36510 }
36511
36512 function highlight(s, point, auto) {
36513 if (typeof s == "number")
36514 s = series[s];
36515
36516 if (typeof point == "number") {
36517 var ps = s.datapoints.pointsize;
36518 point = s.datapoints.points.slice(ps * point, ps * (point + 1));
36519 }
36520
36521 var i = indexOfHighlight(s, point);
36522 if (i == -1) {
36523 highlights.push({ series: s, point: point, auto: auto });
36524
36525 triggerRedrawOverlay();
36526 }
36527 else if (!auto)
36528 highlights[i].auto = false;
36529 }
36530
36531 function unhighlight(s, point) {
36532 if (s == null && point == null) {
36533 highlights = [];
36534 triggerRedrawOverlay();
36535 return;
36536 }
36537
36538 if (typeof s == "number")
36539 s = series[s];
36540
36541 if (typeof point == "number") {
36542 var ps = s.datapoints.pointsize;
36543 point = s.datapoints.points.slice(ps * point, ps * (point + 1));
36544 }
36545
36546 var i = indexOfHighlight(s, point);
36547 if (i != -1) {
36548 highlights.splice(i, 1);
36549
36550 triggerRedrawOverlay();
36551 }
36552 }
36553
36554 function indexOfHighlight(s, p) {
36555 for (var i = 0; i < highlights.length; ++i) {
36556 var h = highlights[i];
36557 if (h.series == s && h.point[0] == p[0]
36558 && h.point[1] == p[1])
36559 return i;
36560 }
36561 return -1;
36562 }
36563
36564 function drawPointHighlight(series, point) {
36565 var x = point[0], y = point[1],
36566 axisx = series.xaxis, axisy = series.yaxis,
36567 highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString();
36568
36569 if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
36570 return;
36571
36572 var pointRadius = series.points.radius + series.points.lineWidth / 2;
36573 octx.lineWidth = pointRadius;
36574 octx.strokeStyle = highlightColor;
36575 var radius = 1.5 * pointRadius;
36576 x = axisx.p2c(x);
36577 y = axisy.p2c(y);
36578
36579 octx.beginPath();
36580 if (series.points.symbol == "circle")
36581 octx.arc(x, y, radius, 0, 2 * Math.PI, false);
36582 else
36583 series.points.symbol(octx, x, y, radius, false);
36584 octx.closePath();
36585 octx.stroke();
36586 }
36587
36588 function drawBarHighlight(series, point) {
36589 var highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString(),
36590 fillStyle = highlightColor,
36591 barLeft;
36592
36593 switch (series.bars.align) {
36594 case "left":
36595 barLeft = 0;
36596 break;
36597 case "right":
36598 barLeft = -series.bars.barWidth;
36599 break;
36600 default:
36601 barLeft = -series.bars.barWidth / 2;
36602 }
36603
36604 octx.lineWidth = series.bars.lineWidth;
36605 octx.strokeStyle = highlightColor;
36606
36607 drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth,
36608 function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth);
36609 }
36610
36611 function getColorOrGradient(spec, bottom, top, defaultColor) {
36612 if (typeof spec == "string")
36613 return spec;
36614 else {
36615 // assume this is a gradient spec; IE currently only
36616 // supports a simple vertical gradient properly, so that's
36617 // what we support too
36618 var gradient = ctx.createLinearGradient(0, top, 0, bottom);
36619
36620 for (var i = 0, l = spec.colors.length; i < l; ++i) {
36621 var c = spec.colors[i];
36622 if (typeof c != "string") {
36623 var co = $.color.parse(defaultColor);
36624 if (c.brightness != null)
36625 co = co.scale('rgb', c.brightness);
36626 if (c.opacity != null)
36627 co.a *= c.opacity;
36628 c = co.toString();
36629 }
36630 gradient.addColorStop(i / (l - 1), c);
36631 }
36632
36633 return gradient;
36634 }
36635 }
36636 }
36637
36638 // Add the plot function to the top level of the jQuery object
36639
36640 $.plot = function(placeholder, data, options) {
36641 //var t0 = new Date();
36642 var plot = new Plot($(placeholder), data, options, $.plot.plugins);
36643 //(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime()));
36644 return plot;
36645 };
36646
36647 $.plot.version = "0.8.3-alpha";
36648
36649 $.plot.plugins = [];
36650
36651 // Also add the plot function as a chainable property
36652
36653 $.fn.plot = function(data, options) {
36654 return this.each(function() {
36655 $.plot(this, data, options);
36656 });
36657 };
36658
36659 // round to nearby lower multiple of base
36660 function floorInBase(n, base) {
36661 return base * Math.floor(n / base);
36662 }
36663
36664 })(jQuery);
36665 /* Flot plugin for rendering pie charts.
36666
36667 Copyright (c) 2007-2013 IOLA and Ole Laursen.
36668 Licensed under the MIT license.
36669
36670 The plugin assumes that each series has a single data value, and that each
36671 value is a positive integer or zero. Negative numbers don't make sense for a
36672 pie chart, and have unpredictable results. The values do NOT need to be
36673 passed in as percentages; the plugin will calculate the total and per-slice
36674 percentages internally.
36675
36676 * Created by Brian Medendorp
36677
36678 * Updated with contributions from btburnett3, Anthony Aragues and Xavi Ivars
36679
36680 The plugin supports these options:
36681
36682 series: {
36683 pie: {
36684 show: true/false
36685 radius: 0-1 for percentage of fullsize, or a specified pixel length, or 'auto'
36686 innerRadius: 0-1 for percentage of fullsize or a specified pixel length, for creating a donut effect
36687 startAngle: 0-2 factor of PI used for starting angle (in radians) i.e 3/2 starts at the top, 0 and 2 have the same result
36688 tilt: 0-1 for percentage to tilt the pie, where 1 is no tilt, and 0 is completely flat (nothing will show)
36689 offset: {
36690 top: integer value to move the pie up or down
36691 left: integer value to move the pie left or right, or 'auto'
36692 },
36693 stroke: {
36694 color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#FFF')
36695 width: integer pixel width of the stroke
36696 },
36697 label: {
36698 show: true/false, or 'auto'
36699 formatter: a user-defined function that modifies the text/style of the label text
36700 radius: 0-1 for percentage of fullsize, or a specified pixel length
36701 background: {
36702 color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#000')
36703 opacity: 0-1
36704 },
36705 threshold: 0-1 for the percentage value at which to hide labels (if they're too small)
36706 },
36707 combine: {
36708 threshold: 0-1 for the percentage value at which to combine slices (if they're too small)
36709 color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#CCC'), if null, the plugin will automatically use the color of the first slice to be combined
36710 label: any text value of what the combined slice should be labeled
36711 }
36712 highlight: {
36713 opacity: 0-1
36714 }
36715 }
36716 }
36717
36718 More detail and specific examples can be found in the included HTML file.
36719
36720 */
36721
36722 (function($) {
36723
36724 // Maximum redraw attempts when fitting labels within the plot
36725
36726 var REDRAW_ATTEMPTS = 10;
36727
36728 // Factor by which to shrink the pie when fitting labels within the plot
36729
36730 var REDRAW_SHRINK = 0.95;
36731
36732 function init(plot) {
36733
36734 var canvas = null,
36735 target = null,
36736 options = null,
36737 maxRadius = null,
36738 centerLeft = null,
36739 centerTop = null,
36740 processed = false,
36741 ctx = null;
36742
36743 // interactive variables
36744
36745 var highlights = [];
36746
36747 // add hook to determine if pie plugin in enabled, and then perform necessary operations
36748
36749 plot.hooks.processOptions.push(function(plot, options) {
36750 if (options.series.pie.show) {
36751
36752 options.grid.show = false;
36753
36754 // set labels.show
36755
36756 if (options.series.pie.label.show == "auto") {
36757 if (options.legend.show) {
36758 options.series.pie.label.show = false;
36759 } else {
36760 options.series.pie.label.show = true;
36761 }
36762 }
36763
36764 // set radius
36765
36766 if (options.series.pie.radius == "auto") {
36767 if (options.series.pie.label.show) {
36768 options.series.pie.radius = 3/4;
36769 } else {
36770 options.series.pie.radius = 1;
36771 }
36772 }
36773
36774 // ensure sane tilt
36775
36776 if (options.series.pie.tilt > 1) {
36777 options.series.pie.tilt = 1;
36778 } else if (options.series.pie.tilt < 0) {
36779 options.series.pie.tilt = 0;
36780 }
36781 }
36782 });
36783
36784 plot.hooks.bindEvents.push(function(plot, eventHolder) {
36785 var options = plot.getOptions();
36786 if (options.series.pie.show) {
36787 if (options.grid.hoverable) {
36788 eventHolder.unbind("mousemove").mousemove(onMouseMove);
36789 }
36790 if (options.grid.clickable) {
36791 eventHolder.unbind("click").click(onClick);
36792 }
36793 }
36794 });
36795
36796 plot.hooks.processDatapoints.push(function(plot, series, data, datapoints) {
36797 var options = plot.getOptions();
36798 if (options.series.pie.show) {
36799 processDatapoints(plot, series, data, datapoints);
36800 }
36801 });
36802
36803 plot.hooks.drawOverlay.push(function(plot, octx) {
36804 var options = plot.getOptions();
36805 if (options.series.pie.show) {
36806 drawOverlay(plot, octx);
36807 }
36808 });
36809
36810 plot.hooks.draw.push(function(plot, newCtx) {
36811 var options = plot.getOptions();
36812 if (options.series.pie.show) {
36813 draw(plot, newCtx);
36814 }
36815 });
36816
36817 function processDatapoints(plot, series, datapoints) {
36818 if (!processed) {
36819 processed = true;
36820 canvas = plot.getCanvas();
36821 target = $(canvas).parent();
36822 options = plot.getOptions();
36823 plot.setData(combine(plot.getData()));
36824 }
36825 }
36826
36827 function combine(data) {
36828
36829 var total = 0,
36830 combined = 0,
36831 numCombined = 0,
36832 color = options.series.pie.combine.color,
36833 newdata = [];
36834
36835 // Fix up the raw data from Flot, ensuring the data is numeric
36836
36837 for (var i = 0; i < data.length; ++i) {
36838
36839 var value = data[i].data;
36840
36841 // If the data is an array, we'll assume that it's a standard
36842 // Flot x-y pair, and are concerned only with the second value.
36843
36844 // Note how we use the original array, rather than creating a
36845 // new one; this is more efficient and preserves any extra data
36846 // that the user may have stored in higher indexes.
36847
36848 if ($.isArray(value) && value.length == 1) {
36849 value = value[0];
36850 }
36851
36852 if ($.isArray(value)) {
36853 // Equivalent to $.isNumeric() but compatible with jQuery < 1.7
36854 if (!isNaN(parseFloat(value[1])) && isFinite(value[1])) {
36855 value[1] = +value[1];
36856 } else {
36857 value[1] = 0;
36858 }
36859 } else if (!isNaN(parseFloat(value)) && isFinite(value)) {
36860 value = [1, +value];
36861 } else {
36862 value = [1, 0];
36863 }
36864
36865 data[i].data = [value];
36866 }
36867
36868 // Sum up all the slices, so we can calculate percentages for each
36869
36870 for (var i = 0; i < data.length; ++i) {
36871 total += data[i].data[0][1];
36872 }
36873
36874 // Count the number of slices with percentages below the combine
36875 // threshold; if it turns out to be just one, we won't combine.
36876
36877 for (var i = 0; i < data.length; ++i) {
36878 var value = data[i].data[0][1];
36879 if (value / total <= options.series.pie.combine.threshold) {
36880 combined += value;
36881 numCombined++;
36882 if (!color) {
36883 color = data[i].color;
36884 }
36885 }
36886 }
36887
36888 for (var i = 0; i < data.length; ++i) {
36889 var value = data[i].data[0][1];
36890 if (numCombined < 2 || value / total > options.series.pie.combine.threshold) {
36891 newdata.push(
36892 $.extend(data[i], { /* extend to allow keeping all other original data values
36893 and using them e.g. in labelFormatter. */
36894 data: [[1, value]],
36895 color: data[i].color,
36896 label: data[i].label,
36897 angle: value * Math.PI * 2 / total,
36898 percent: value / (total / 100)
36899 })
36900 );
36901 }
36902 }
36903
36904 if (numCombined > 1) {
36905 newdata.push({
36906 data: [[1, combined]],
36907 color: color,
36908 label: options.series.pie.combine.label,
36909 angle: combined * Math.PI * 2 / total,
36910 percent: combined / (total / 100)
36911 });
36912 }
36913
36914 return newdata;
36915 }
36916
36917 function draw(plot, newCtx) {
36918
36919 if (!target) {
36920 return; // if no series were passed
36921 }
36922
36923 var canvasWidth = plot.getPlaceholder().width(),
36924 canvasHeight = plot.getPlaceholder().height(),
36925 legendWidth = target.children().filter(".legend").children().width() || 0;
36926
36927 ctx = newCtx;
36928
36929 // WARNING: HACK! REWRITE THIS CODE AS SOON AS POSSIBLE!
36930
36931 // When combining smaller slices into an 'other' slice, we need to
36932 // add a new series. Since Flot gives plugins no way to modify the
36933 // list of series, the pie plugin uses a hack where the first call
36934 // to processDatapoints results in a call to setData with the new
36935 // list of series, then subsequent processDatapoints do nothing.
36936
36937 // The plugin-global 'processed' flag is used to control this hack;
36938 // it starts out false, and is set to true after the first call to
36939 // processDatapoints.
36940
36941 // Unfortunately this turns future setData calls into no-ops; they
36942 // call processDatapoints, the flag is true, and nothing happens.
36943
36944 // To fix this we'll set the flag back to false here in draw, when
36945 // all series have been processed, so the next sequence of calls to
36946 // processDatapoints once again starts out with a slice-combine.
36947 // This is really a hack; in 0.9 we need to give plugins a proper
36948 // way to modify series before any processing begins.
36949
36950 processed = false;
36951
36952 // calculate maximum radius and center point
36953
36954 maxRadius = Math.min(canvasWidth, canvasHeight / options.series.pie.tilt) / 2;
36955 centerTop = canvasHeight / 2 + options.series.pie.offset.top;
36956 centerLeft = canvasWidth / 2;
36957
36958 if (options.series.pie.offset.left == "auto") {
36959 if (options.legend.position.match("w")) {
36960 centerLeft += legendWidth / 2;
36961 } else {
36962 centerLeft -= legendWidth / 2;
36963 }
36964 if (centerLeft < maxRadius) {
36965 centerLeft = maxRadius;
36966 } else if (centerLeft > canvasWidth - maxRadius) {
36967 centerLeft = canvasWidth - maxRadius;
36968 }
36969 } else {
36970 centerLeft += options.series.pie.offset.left;
36971 }
36972
36973 var slices = plot.getData(),
36974 attempts = 0;
36975
36976 // Keep shrinking the pie's radius until drawPie returns true,
36977 // indicating that all the labels fit, or we try too many times.
36978
36979 do {
36980 if (attempts > 0) {
36981 maxRadius *= REDRAW_SHRINK;
36982 }
36983 attempts += 1;
36984 clear();
36985 if (options.series.pie.tilt <= 0.8) {
36986 drawShadow();
36987 }
36988 } while (!drawPie() && attempts < REDRAW_ATTEMPTS)
36989
36990 if (attempts >= REDRAW_ATTEMPTS) {
36991 clear();
36992 target.prepend("<div class='error'>Could not draw pie with labels contained inside canvas</div>");
36993 }
36994
36995 if (plot.setSeries && plot.insertLegend) {
36996 plot.setSeries(slices);
36997 plot.insertLegend();
36998 }
36999
37000 // we're actually done at this point, just defining internal functions at this point
37001
37002 function clear() {
37003 ctx.clearRect(0, 0, canvasWidth, canvasHeight);
37004 target.children().filter(".pieLabel, .pieLabelBackground").remove();
37005 }
37006
37007 function drawShadow() {
37008
37009 var shadowLeft = options.series.pie.shadow.left;
37010 var shadowTop = options.series.pie.shadow.top;
37011 var edge = 10;
37012 var alpha = options.series.pie.shadow.alpha;
37013 var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
37014
37015 if (radius >= canvasWidth / 2 - shadowLeft || radius * options.series.pie.tilt >= canvasHeight / 2 - shadowTop || radius <= edge) {
37016 return; // shadow would be outside canvas, so don't draw it
37017 }
37018
37019 ctx.save();
37020 ctx.translate(shadowLeft,shadowTop);
37021 ctx.globalAlpha = alpha;
37022 ctx.fillStyle = "#000";
37023
37024 // center and rotate to starting position
37025
37026 ctx.translate(centerLeft,centerTop);
37027 ctx.scale(1, options.series.pie.tilt);
37028
37029 //radius -= edge;
37030
37031 for (var i = 1; i <= edge; i++) {
37032 ctx.beginPath();
37033 ctx.arc(0, 0, radius, 0, Math.PI * 2, false);
37034 ctx.fill();
37035 radius -= i;
37036 }
37037
37038 ctx.restore();
37039 }
37040
37041 function drawPie() {
37042
37043 var startAngle = Math.PI * options.series.pie.startAngle;
37044 var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
37045
37046 // center and rotate to starting position
37047
37048 ctx.save();
37049 ctx.translate(centerLeft,centerTop);
37050 ctx.scale(1, options.series.pie.tilt);
37051 //ctx.rotate(startAngle); // start at top; -- This doesn't work properly in Opera
37052
37053 // draw slices
37054
37055 ctx.save();
37056 var currentAngle = startAngle;
37057 for (var i = 0; i < slices.length; ++i) {
37058 slices[i].startAngle = currentAngle;
37059 drawSlice(slices[i].angle, slices[i].color, true);
37060 }
37061 ctx.restore();
37062
37063 // draw slice outlines
37064
37065 if (options.series.pie.stroke.width > 0) {
37066 ctx.save();
37067 ctx.lineWidth = options.series.pie.stroke.width;
37068 currentAngle = startAngle;
37069 for (var i = 0; i < slices.length; ++i) {
37070 drawSlice(slices[i].angle, options.series.pie.stroke.color, false);
37071 }
37072 ctx.restore();
37073 }
37074
37075 // draw donut hole
37076
37077 drawDonutHole(ctx);
37078
37079 ctx.restore();
37080
37081 // Draw the labels, returning true if they fit within the plot
37082
37083 if (options.series.pie.label.show) {
37084 return drawLabels();
37085 } else return true;
37086
37087 function drawSlice(angle, color, fill) {
37088
37089 if (angle <= 0 || isNaN(angle)) {
37090 return;
37091 }
37092
37093 if (fill) {
37094 ctx.fillStyle = color;
37095 } else {
37096 ctx.strokeStyle = color;
37097 ctx.lineJoin = "round";
37098 }
37099
37100 ctx.beginPath();
37101 if (Math.abs(angle - Math.PI * 2) > 0.000000001) {
37102 ctx.moveTo(0, 0); // Center of the pie
37103 }
37104
37105 //ctx.arc(0, 0, radius, 0, angle, false); // This doesn't work properly in Opera
37106 ctx.arc(0, 0, radius,currentAngle, currentAngle + angle / 2, false);
37107 ctx.arc(0, 0, radius,currentAngle + angle / 2, currentAngle + angle, false);
37108 ctx.closePath();
37109 //ctx.rotate(angle); // This doesn't work properly in Opera
37110 currentAngle += angle;
37111
37112 if (fill) {
37113 ctx.fill();
37114 } else {
37115 ctx.stroke();
37116 }
37117 }
37118
37119 function drawLabels() {
37120
37121 var currentAngle = startAngle;
37122 var radius = options.series.pie.label.radius > 1 ? options.series.pie.label.radius : maxRadius * options.series.pie.label.radius;
37123
37124 for (var i = 0; i < slices.length; ++i) {
37125 if (slices[i].percent >= options.series.pie.label.threshold * 100) {
37126 if (!drawLabel(slices[i], currentAngle, i)) {
37127 return false;
37128 }
37129 }
37130 currentAngle += slices[i].angle;
37131 }
37132
37133 return true;
37134
37135 function drawLabel(slice, startAngle, index) {
37136
37137 if (slice.data[0][1] == 0) {
37138 return true;
37139 }
37140
37141 // format label text
37142
37143 var lf = options.legend.labelFormatter, text, plf = options.series.pie.label.formatter;
37144
37145 if (lf) {
37146 text = lf(slice.label, slice);
37147 } else {
37148 text = slice.label;
37149 }
37150
37151 if (plf) {
37152 text = plf(text, slice);
37153 }
37154
37155 var halfAngle = ((startAngle + slice.angle) + startAngle) / 2;
37156 var x = centerLeft + Math.round(Math.cos(halfAngle) * radius);
37157 var y = centerTop + Math.round(Math.sin(halfAngle) * radius) * options.series.pie.tilt;
37158
37159 var html = "<span class='pieLabel' id='pieLabel" + index + "' style='position:absolute;top:" + y + "px;left:" + x + "px;'>" + text + "</span>";
37160 target.append(html);
37161
37162 var label = target.children("#pieLabel" + index);
37163 var labelTop = (y - label.height() / 2);
37164 var labelLeft = (x - label.width() / 2);
37165
37166 label.css("top", labelTop);
37167 label.css("left", labelLeft);
37168
37169 // check to make sure that the label is not outside the canvas
37170
37171 if (0 - labelTop > 0 || 0 - labelLeft > 0 || canvasHeight - (labelTop + label.height()) < 0 || canvasWidth - (labelLeft + label.width()) < 0) {
37172 return false;
37173 }
37174
37175 if (options.series.pie.label.background.opacity != 0) {
37176
37177 // put in the transparent background separately to avoid blended labels and label boxes
37178
37179 var c = options.series.pie.label.background.color;
37180
37181 if (c == null) {
37182 c = slice.color;
37183 }
37184
37185 var pos = "top:" + labelTop + "px;left:" + labelLeft + "px;";
37186 $("<div class='pieLabelBackground' style='position:absolute;width:" + label.width() + "px;height:" + label.height() + "px;" + pos + "background-color:" + c + ";'></div>")
37187 .css("opacity", options.series.pie.label.background.opacity)
37188 .insertBefore(label);
37189 }
37190
37191 return true;
37192 } // end individual label function
37193 } // end drawLabels function
37194 } // end drawPie function
37195 } // end draw function
37196
37197 // Placed here because it needs to be accessed from multiple locations
37198
37199 function drawDonutHole(layer) {
37200 if (options.series.pie.innerRadius > 0) {
37201
37202 // subtract the center
37203
37204 layer.save();
37205 var innerRadius = options.series.pie.innerRadius > 1 ? options.series.pie.innerRadius : maxRadius * options.series.pie.innerRadius;
37206 layer.globalCompositeOperation = "destination-out"; // this does not work with excanvas, but it will fall back to using the stroke color
37207 layer.beginPath();
37208 layer.fillStyle = options.series.pie.stroke.color;
37209 layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false);
37210 layer.fill();
37211 layer.closePath();
37212 layer.restore();
37213
37214 // add inner stroke
37215
37216 layer.save();
37217 layer.beginPath();
37218 layer.strokeStyle = options.series.pie.stroke.color;
37219 layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false);
37220 layer.stroke();
37221 layer.closePath();
37222 layer.restore();
37223
37224 // TODO: add extra shadow inside hole (with a mask) if the pie is tilted.
37225 }
37226 }
37227
37228 //-- Additional Interactive related functions --
37229
37230 function isPointInPoly(poly, pt) {
37231 for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
37232 ((poly[i][1] <= pt[1] && pt[1] < poly[j][1]) || (poly[j][1] <= pt[1] && pt[1]< poly[i][1]))
37233 && (pt[0] < (poly[j][0] - poly[i][0]) * (pt[1] - poly[i][1]) / (poly[j][1] - poly[i][1]) + poly[i][0])
37234 && (c = !c);
37235 return c;
37236 }
37237
37238 function findNearbySlice(mouseX, mouseY) {
37239
37240 var slices = plot.getData(),
37241 options = plot.getOptions(),
37242 radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius,
37243 x, y;
37244
37245 for (var i = 0; i < slices.length; ++i) {
37246
37247 var s = slices[i];
37248
37249 if (s.pie.show) {
37250
37251 ctx.save();
37252 ctx.beginPath();
37253 ctx.moveTo(0, 0); // Center of the pie
37254 //ctx.scale(1, options.series.pie.tilt); // this actually seems to break everything when here.
37255 ctx.arc(0, 0, radius, s.startAngle, s.startAngle + s.angle / 2, false);
37256 ctx.arc(0, 0, radius, s.startAngle + s.angle / 2, s.startAngle + s.angle, false);
37257 ctx.closePath();
37258 x = mouseX - centerLeft;
37259 y = mouseY - centerTop;
37260
37261 if (ctx.isPointInPath) {
37262 if (ctx.isPointInPath(mouseX - centerLeft, mouseY - centerTop)) {
37263 ctx.restore();
37264 return {
37265 datapoint: [s.percent, s.data],
37266 dataIndex: 0,
37267 series: s,
37268 seriesIndex: i
37269 };
37270 }
37271 } else {
37272
37273 // excanvas for IE doesn;t support isPointInPath, this is a workaround.
37274
37275 var p1X = radius * Math.cos(s.startAngle),
37276 p1Y = radius * Math.sin(s.startAngle),
37277 p2X = radius * Math.cos(s.startAngle + s.angle / 4),
37278 p2Y = radius * Math.sin(s.startAngle + s.angle / 4),
37279 p3X = radius * Math.cos(s.startAngle + s.angle / 2),
37280 p3Y = radius * Math.sin(s.startAngle + s.angle / 2),
37281 p4X = radius * Math.cos(s.startAngle + s.angle / 1.5),
37282 p4Y = radius * Math.sin(s.startAngle + s.angle / 1.5),
37283 p5X = radius * Math.cos(s.startAngle + s.angle),
37284 p5Y = radius * Math.sin(s.startAngle + s.angle),
37285 arrPoly = [[0, 0], [p1X, p1Y], [p2X, p2Y], [p3X, p3Y], [p4X, p4Y], [p5X, p5Y]],
37286 arrPoint = [x, y];
37287
37288 // TODO: perhaps do some mathmatical trickery here with the Y-coordinate to compensate for pie tilt?
37289
37290 if (isPointInPoly(arrPoly, arrPoint)) {
37291 ctx.restore();
37292 return {
37293 datapoint: [s.percent, s.data],
37294 dataIndex: 0,
37295 series: s,
37296 seriesIndex: i
37297 };
37298 }
37299 }
37300
37301 ctx.restore();
37302 }
37303 }
37304
37305 return null;
37306 }
37307
37308 function onMouseMove(e) {
37309 triggerClickHoverEvent("plothover", e);
37310 }
37311
37312 function onClick(e) {
37313 triggerClickHoverEvent("plotclick", e);
37314 }
37315
37316 // trigger click or hover event (they send the same parameters so we share their code)
37317
37318 function triggerClickHoverEvent(eventname, e) {
37319
37320 var offset = plot.offset();
37321 var canvasX = parseInt(e.pageX - offset.left);
37322 var canvasY = parseInt(e.pageY - offset.top);
37323 var item = findNearbySlice(canvasX, canvasY);
37324
37325 if (options.grid.autoHighlight) {
37326
37327 // clear auto-highlights
37328
37329 for (var i = 0; i < highlights.length; ++i) {
37330 var h = highlights[i];
37331 if (h.auto == eventname && !(item && h.series == item.series)) {
37332 unhighlight(h.series);
37333 }
37334 }
37335 }
37336
37337 // highlight the slice
37338
37339 if (item) {
37340 highlight(item.series, eventname);
37341 }
37342
37343 // trigger any hover bind events
37344
37345 var pos = { pageX: e.pageX, pageY: e.pageY };
37346 target.trigger(eventname, [pos, item]);
37347 }
37348
37349 function highlight(s, auto) {
37350 //if (typeof s == "number") {
37351 // s = series[s];
37352 //}
37353
37354 var i = indexOfHighlight(s);
37355
37356 if (i == -1) {
37357 highlights.push({ series: s, auto: auto });
37358 plot.triggerRedrawOverlay();
37359 } else if (!auto) {
37360 highlights[i].auto = false;
37361 }
37362 }
37363
37364 function unhighlight(s) {
37365 if (s == null) {
37366 highlights = [];
37367 plot.triggerRedrawOverlay();
37368 }
37369
37370 //if (typeof s == "number") {
37371 // s = series[s];
37372 //}
37373
37374 var i = indexOfHighlight(s);
37375
37376 if (i != -1) {
37377 highlights.splice(i, 1);
37378 plot.triggerRedrawOverlay();
37379 }
37380 }
37381
37382 function indexOfHighlight(s) {
37383 for (var i = 0; i < highlights.length; ++i) {
37384 var h = highlights[i];
37385 if (h.series == s)
37386 return i;
37387 }
37388 return -1;
37389 }
37390
37391 function drawOverlay(plot, octx) {
37392
37393 var options = plot.getOptions();
37394
37395 var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
37396
37397 octx.save();
37398 octx.translate(centerLeft, centerTop);
37399 octx.scale(1, options.series.pie.tilt);
37400
37401 for (var i = 0; i < highlights.length; ++i) {
37402 drawHighlight(highlights[i].series);
37403 }
37404
37405 drawDonutHole(octx);
37406
37407 octx.restore();
37408
37409 function drawHighlight(series) {
37410
37411 if (series.angle <= 0 || isNaN(series.angle)) {
37412 return;
37413 }
37414
37415 //octx.fillStyle = parseColor(options.series.pie.highlight.color).scale(null, null, null, options.series.pie.highlight.opacity).toString();
37416 octx.fillStyle = "rgba(255, 255, 255, " + options.series.pie.highlight.opacity + ")"; // this is temporary until we have access to parseColor
37417 octx.beginPath();
37418 if (Math.abs(series.angle - Math.PI * 2) > 0.000000001) {
37419 octx.moveTo(0, 0); // Center of the pie
37420 }
37421 octx.arc(0, 0, radius, series.startAngle, series.startAngle + series.angle / 2, false);
37422 octx.arc(0, 0, radius, series.startAngle + series.angle / 2, series.startAngle + series.angle, false);
37423 octx.closePath();
37424 octx.fill();
37425 }
37426 }
37427 } // end init (plugin body)
37428
37429 // define pie specific options and their default values
37430
37431 var options = {
37432 series: {
37433 pie: {
37434 show: false,
37435 radius: "auto", // actual radius of the visible pie (based on full calculated radius if <=1, or hard pixel value)
37436 innerRadius: 0, /* for donut */
37437 startAngle: 3/2,
37438 tilt: 1,
37439 shadow: {
37440 left: 5, // shadow left offset
37441 top: 15, // shadow top offset
37442 alpha: 0.02 // shadow alpha
37443 },
37444 offset: {
37445 top: 0,
37446 left: "auto"
37447 },
37448 stroke: {
37449 color: "#fff",
37450 width: 1
37451 },
37452 label: {
37453 show: "auto",
37454 formatter: function(label, slice) {
37455 return "<div style='font-size:x-small;text-align:center;padding:2px;color:" + slice.color + ";'>" + label + "<br/>" + Math.round(slice.percent) + "%</div>";
37456 }, // formatter function
37457 radius: 1, // radius at which to place the labels (based on full calculated radius if <=1, or hard pixel value)
37458 background: {
37459 color: null,
37460 opacity: 0
37461 },
37462 threshold: 0 // percentage at which to hide the label (i.e. the slice is too narrow)
37463 },
37464 combine: {
37465 threshold: -1, // percentage at which to combine little slices into one larger slice
37466 color: null, // color to give the new slice (auto-generated if null)
37467 label: "Other" // label to give the new slice
37468 },
37469 highlight: {
37470 //color: "#fff", // will add this functionality once parseColor is available
37471 opacity: 0.5
37472 }
37473 }
37474 }
37475 };
37476
37477 $.plot.plugins.push({
37478 init: init,
37479 options: options,
37480 name: "pie",
37481 version: "1.1"
37482 });
37483
37484 })(jQuery);
37485 /* Flot plugin for automatically redrawing plots as the placeholder resizes.
37486
37487 Copyright (c) 2007-2013 IOLA and Ole Laursen.
37488 Licensed under the MIT license.
37489
37490 It works by listening for changes on the placeholder div (through the jQuery
37491 resize event plugin) - if the size changes, it will redraw the plot.
37492
37493 There are no options. If you need to disable the plugin for some plots, you
37494 can just fix the size of their placeholders.
37495
37496 */
37497
37498 /* Inline dependency:
37499 * jQuery resize event - v1.1 - 3/14/2010
37500 * http://benalman.com/projects/jquery-resize-plugin/
37501 *
37502 * Copyright (c) 2010 "Cowboy" Ben Alman
37503 * Dual licensed under the MIT and GPL licenses.
37504 * http://benalman.com/about/license/
37505 */
37506
37507 (function($,t,n){function p(){for(var n=r.length-1;n>=0;n--){var o=$(r[n]);if(o[0]==t||o.is(":visible")){var h=o.width(),d=o.height(),v=o.data(a);!v||h===v.w&&d===v.h?i[f]=i[l]:(i[f]=i[c],o.trigger(u,[v.w=h,v.h=d]))}else v=o.data(a),v.w=0,v.h=0}s!==null&&(s=t.requestAnimationFrame(p))}var r=[],i=$.resize=$.extend($.resize,{}),s,o="setTimeout",u="resize",a=u+"-special-event",f="delay",l="pendingDelay",c="activeDelay",h="throttleWindow";i[l]=250,i[c]=20,i[f]=i[l],i[h]=!0,$.event.special[u]={setup:function(){if(!i[h]&&this[o])return!1;var t=$(this);r.push(this),t.data(a,{w:t.width(),h:t.height()}),r.length===1&&(s=n,p())},teardown:function(){if(!i[h]&&this[o])return!1;var t=$(this);for(var n=r.length-1;n>=0;n--)if(r[n]==this){r.splice(n,1);break}t.removeData(a),r.length||(cancelAnimationFrame(s),s=null)},add:function(t){function s(t,i,s){var o=$(this),u=o.data(a);u.w=i!==n?i:o.width(),u.h=s!==n?s:o.height(),r.apply(this,arguments)}if(!i[h]&&this[o])return!1;var r;if($.isFunction(t))return r=t,s;r=t.handler,t.handler=s}},t.requestAnimationFrame||(t.requestAnimationFrame=function(){return t.webkitRequestAnimationFrame||t.mozRequestAnimationFrame||t.oRequestAnimationFrame||t.msRequestAnimationFrame||function(e,n){return t.setTimeout(e,i[f])}}()),t.cancelAnimationFrame||(t.cancelAnimationFrame=function(){return t.webkitCancelRequestAnimationFrame||t.mozCancelRequestAnimationFrame||t.oCancelRequestAnimationFrame||t.msCancelRequestAnimationFrame||clearTimeout}())})(jQuery,this);
37508
37509 (function ($) {
37510 var options = { }; // no options
37511
37512 function init(plot) {
37513 function onResize() {
37514 var placeholder = plot.getPlaceholder();
37515
37516 // somebody might have hidden us and we can't plot
37517 // when we don't have the dimensions
37518 if (placeholder.width() == 0 || placeholder.height() == 0)
37519 return;
37520
37521 plot.resize();
37522 plot.setupGrid();
37523 plot.draw();
37524 }
37525
37526 function bindEvents(plot, eventHolder) {
37527 plot.getPlaceholder().resize(onResize);
37528 }
37529
37530 function shutdown(plot, eventHolder) {
37531 plot.getPlaceholder().unbind("resize", onResize);
37532 }
37533
37534 plot.hooks.bindEvents.push(bindEvents);
37535 plot.hooks.shutdown.push(shutdown);
37536 }
37537
37538 $.plot.plugins.push({
37539 init: init,
37540 options: options,
37541 name: 'resize',
37542 version: '1.0'
37543 });
37544 })(jQuery);
37545 /* Flot plugin for selecting regions of a plot.
37546
37547 Copyright (c) 2007-2013 IOLA and Ole Laursen.
37548 Licensed under the MIT license.
37549
37550 The plugin supports these options:
37551
37552 selection: {
37553 mode: null or "x" or "y" or "xy",
37554 color: color,
37555 shape: "round" or "miter" or "bevel",
37556 minSize: number of pixels
37557 }
37558
37559 Selection support is enabled by setting the mode to one of "x", "y" or "xy".
37560 In "x" mode, the user will only be able to specify the x range, similarly for
37561 "y" mode. For "xy", the selection becomes a rectangle where both ranges can be
37562 specified. "color" is color of the selection (if you need to change the color
37563 later on, you can get to it with plot.getOptions().selection.color). "shape"
37564 is the shape of the corners of the selection.
37565
37566 "minSize" is the minimum size a selection can be in pixels. This value can
37567 be customized to determine the smallest size a selection can be and still
37568 have the selection rectangle be displayed. When customizing this value, the
37569 fact that it refers to pixels, not axis units must be taken into account.
37570 Thus, for example, if there is a bar graph in time mode with BarWidth set to 1
37571 minute, setting "minSize" to 1 will not make the minimum selection size 1
37572 minute, but rather 1 pixel. Note also that setting "minSize" to 0 will prevent
37573 "plotunselected" events from being fired when the user clicks the mouse without
37574 dragging.
37575
37576 When selection support is enabled, a "plotselected" event will be emitted on
37577 the DOM element you passed into the plot function. The event handler gets a
37578 parameter with the ranges selected on the axes, like this:
37579
37580 placeholder.bind( "plotselected", function( event, ranges ) {
37581 alert("You selected " + ranges.xaxis.from + " to " + ranges.xaxis.to)
37582 // similar for yaxis - with multiple axes, the extra ones are in
37583 // x2axis, x3axis, ...
37584 });
37585
37586 The "plotselected" event is only fired when the user has finished making the
37587 selection. A "plotselecting" event is fired during the process with the same
37588 parameters as the "plotselected" event, in case you want to know what's
37589 happening while it's happening,
37590
37591 A "plotunselected" event with no arguments is emitted when the user clicks the
37592 mouse to remove the selection. As stated above, setting "minSize" to 0 will
37593 destroy this behavior.
37594
37595 The plugin allso adds the following methods to the plot object:
37596
37597 - setSelection( ranges, preventEvent )
37598
37599 Set the selection rectangle. The passed in ranges is on the same form as
37600 returned in the "plotselected" event. If the selection mode is "x", you
37601 should put in either an xaxis range, if the mode is "y" you need to put in
37602 an yaxis range and both xaxis and yaxis if the selection mode is "xy", like
37603 this:
37604
37605 setSelection({ xaxis: { from: 0, to: 10 }, yaxis: { from: 40, to: 60 } });
37606
37607 setSelection will trigger the "plotselected" event when called. If you don't
37608 want that to happen, e.g. if you're inside a "plotselected" handler, pass
37609 true as the second parameter. If you are using multiple axes, you can
37610 specify the ranges on any of those, e.g. as x2axis/x3axis/... instead of
37611 xaxis, the plugin picks the first one it sees.
37612
37613 - clearSelection( preventEvent )
37614
37615 Clear the selection rectangle. Pass in true to avoid getting a
37616 "plotunselected" event.
37617
37618 - getSelection()
37619
37620 Returns the current selection in the same format as the "plotselected"
37621 event. If there's currently no selection, the function returns null.
37622
37623 */
37624
37625 (function ($) {
37626 function init(plot) {
37627 var selection = {
37628 first: { x: -1, y: -1}, second: { x: -1, y: -1},
37629 show: false,
37630 active: false
37631 };
37632
37633 // FIXME: The drag handling implemented here should be
37634 // abstracted out, there's some similar code from a library in
37635 // the navigation plugin, this should be massaged a bit to fit
37636 // the Flot cases here better and reused. Doing this would
37637 // make this plugin much slimmer.
37638 var savedhandlers = {};
37639
37640 var mouseUpHandler = null;
37641
37642 function onMouseMove(e) {
37643 if (selection.active) {
37644 updateSelection(e);
37645
37646 plot.getPlaceholder().trigger("plotselecting", [ getSelection() ]);
37647 }
37648 }
37649
37650 function onMouseDown(e) {
37651 if (e.which != 1) // only accept left-click
37652 return;
37653
37654 // cancel out any text selections
37655 document.body.focus();
37656
37657 // prevent text selection and drag in old-school browsers
37658 if (document.onselectstart !== undefined && savedhandlers.onselectstart == null) {
37659 savedhandlers.onselectstart = document.onselectstart;
37660 document.onselectstart = function () { return false; };
37661 }
37662 if (document.ondrag !== undefined && savedhandlers.ondrag == null) {
37663 savedhandlers.ondrag = document.ondrag;
37664 document.ondrag = function () { return false; };
37665 }
37666
37667 setSelectionPos(selection.first, e);
37668
37669 selection.active = true;
37670
37671 // this is a bit silly, but we have to use a closure to be
37672 // able to whack the same handler again
37673 mouseUpHandler = function (e) { onMouseUp(e); };
37674
37675 $(document).one("mouseup", mouseUpHandler);
37676 }
37677
37678 function onMouseUp(e) {
37679 mouseUpHandler = null;
37680
37681 // revert drag stuff for old-school browsers
37682 if (document.onselectstart !== undefined)
37683 document.onselectstart = savedhandlers.onselectstart;
37684 if (document.ondrag !== undefined)
37685 document.ondrag = savedhandlers.ondrag;
37686
37687 // no more dragging
37688 selection.active = false;
37689 updateSelection(e);
37690
37691 if (selectionIsSane())
37692 triggerSelectedEvent();
37693 else {
37694 // this counts as a clear
37695 plot.getPlaceholder().trigger("plotunselected", [ ]);
37696 plot.getPlaceholder().trigger("plotselecting", [ null ]);
37697 }
37698
37699 return false;
37700 }
37701
37702 function getSelection() {
37703 if (!selectionIsSane())
37704 return null;
37705
37706 if (!selection.show) return null;
37707
37708 var r = {}, c1 = selection.first, c2 = selection.second;
37709 $.each(plot.getAxes(), function (name, axis) {
37710 if (axis.used) {
37711 var p1 = axis.c2p(c1[axis.direction]), p2 = axis.c2p(c2[axis.direction]);
37712 r[name] = { from: Math.min(p1, p2), to: Math.max(p1, p2) };
37713 }
37714 });
37715 return r;
37716 }
37717
37718 function triggerSelectedEvent() {
37719 var r = getSelection();
37720
37721 plot.getPlaceholder().trigger("plotselected", [ r ]);
37722
37723 // backwards-compat stuff, to be removed in future
37724 if (r.xaxis && r.yaxis)
37725 plot.getPlaceholder().trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]);
37726 }
37727
37728 function clamp(min, value, max) {
37729 return value < min ? min: (value > max ? max: value);
37730 }
37731
37732 function setSelectionPos(pos, e) {
37733 var o = plot.getOptions();
37734 var offset = plot.getPlaceholder().offset();
37735 var plotOffset = plot.getPlotOffset();
37736 pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plot.width());
37737 pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plot.height());
37738
37739 if (o.selection.mode == "y")
37740 pos.x = pos == selection.first ? 0 : plot.width();
37741
37742 if (o.selection.mode == "x")
37743 pos.y = pos == selection.first ? 0 : plot.height();
37744 }
37745
37746 function updateSelection(pos) {
37747 if (pos.pageX == null)
37748 return;
37749
37750 setSelectionPos(selection.second, pos);
37751 if (selectionIsSane()) {
37752 selection.show = true;
37753 plot.triggerRedrawOverlay();
37754 }
37755 else
37756 clearSelection(true);
37757 }
37758
37759 function clearSelection(preventEvent) {
37760 if (selection.show) {
37761 selection.show = false;
37762 plot.triggerRedrawOverlay();
37763 if (!preventEvent)
37764 plot.getPlaceholder().trigger("plotunselected", [ ]);
37765 }
37766 }
37767
37768 // function taken from markings support in Flot
37769 function extractRange(ranges, coord) {
37770 var axis, from, to, key, axes = plot.getAxes();
37771
37772 for (var k in axes) {
37773 axis = axes[k];
37774 if (axis.direction == coord) {
37775 key = coord + axis.n + "axis";
37776 if (!ranges[key] && axis.n == 1)
37777 key = coord + "axis"; // support x1axis as xaxis
37778 if (ranges[key]) {
37779 from = ranges[key].from;
37780 to = ranges[key].to;
37781 break;
37782 }
37783 }
37784 }
37785
37786 // backwards-compat stuff - to be removed in future
37787 if (!ranges[key]) {
37788 axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0];
37789 from = ranges[coord + "1"];
37790 to = ranges[coord + "2"];
37791 }
37792
37793 // auto-reverse as an added bonus
37794 if (from != null && to != null && from > to) {
37795 var tmp = from;
37796 from = to;
37797 to = tmp;
37798 }
37799
37800 return { from: from, to: to, axis: axis };
37801 }
37802
37803 function setSelection(ranges, preventEvent) {
37804 var axis, range, o = plot.getOptions();
37805
37806 if (o.selection.mode == "y") {
37807 selection.first.x = 0;
37808 selection.second.x = plot.width();
37809 }
37810 else {
37811 range = extractRange(ranges, "x");
37812
37813 selection.first.x = range.axis.p2c(range.from);
37814 selection.second.x = range.axis.p2c(range.to);
37815 }
37816
37817 if (o.selection.mode == "x") {
37818 selection.first.y = 0;
37819 selection.second.y = plot.height();
37820 }
37821 else {
37822 range = extractRange(ranges, "y");
37823
37824 selection.first.y = range.axis.p2c(range.from);
37825 selection.second.y = range.axis.p2c(range.to);
37826 }
37827
37828 selection.show = true;
37829 plot.triggerRedrawOverlay();
37830 if (!preventEvent && selectionIsSane())
37831 triggerSelectedEvent();
37832 }
37833
37834 function selectionIsSane() {
37835 var minSize = plot.getOptions().selection.minSize;
37836 return Math.abs(selection.second.x - selection.first.x) >= minSize &&
37837 Math.abs(selection.second.y - selection.first.y) >= minSize;
37838 }
37839
37840 plot.clearSelection = clearSelection;
37841 plot.setSelection = setSelection;
37842 plot.getSelection = getSelection;
37843
37844 plot.hooks.bindEvents.push(function(plot, eventHolder) {
37845 var o = plot.getOptions();
37846 if (o.selection.mode != null) {
37847 eventHolder.mousemove(onMouseMove);
37848 eventHolder.mousedown(onMouseDown);
37849 }
37850 });
37851
37852
37853 plot.hooks.drawOverlay.push(function (plot, ctx) {
37854 // draw selection
37855 if (selection.show && selectionIsSane()) {
37856 var plotOffset = plot.getPlotOffset();
37857 var o = plot.getOptions();
37858
37859 ctx.save();
37860 ctx.translate(plotOffset.left, plotOffset.top);
37861
37862 var c = $.color.parse(o.selection.color);
37863
37864 ctx.strokeStyle = c.scale('a', 0.8).toString();
37865 ctx.lineWidth = 1;
37866 ctx.lineJoin = o.selection.shape;
37867 ctx.fillStyle = c.scale('a', 0.4).toString();
37868
37869 var x = Math.min(selection.first.x, selection.second.x) + 0.5,
37870 y = Math.min(selection.first.y, selection.second.y) + 0.5,
37871 w = Math.abs(selection.second.x - selection.first.x) - 1,
37872 h = Math.abs(selection.second.y - selection.first.y) - 1;
37873
37874 ctx.fillRect(x, y, w, h);
37875 ctx.strokeRect(x, y, w, h);
37876
37877 ctx.restore();
37878 }
37879 });
37880
37881 plot.hooks.shutdown.push(function (plot, eventHolder) {
37882 eventHolder.unbind("mousemove", onMouseMove);
37883 eventHolder.unbind("mousedown", onMouseDown);
37884
37885 if (mouseUpHandler)
37886 $(document).unbind("mouseup", mouseUpHandler);
37887 });
37888
37889 }
37890
37891 $.plot.plugins.push({
37892 init: init,
37893 options: {
37894 selection: {
37895 mode: null, // one of null, "x", "y" or "xy"
37896 color: "#e8cfac",
37897 shape: "round", // one of "round", "miter", or "bevel"
37898 minSize: 5 // minimum number of pixels
37899 }
37900 },
37901 name: 'selection',
37902 version: '1.1'
37903 });
37904 })(jQuery);
37905 /* Pretty handling of time axes.
37906
37907 Copyright (c) 2007-2013 IOLA and Ole Laursen.
37908 Licensed under the MIT license.
37909
37910 Set axis.mode to "time" to enable. See the section "Time series data" in
37911 API.txt for details.
37912
37913 */
37914
37915 (function($) {
37916
37917 var options = {
37918 xaxis: {
37919 timezone: null, // "browser" for local to the client or timezone for timezone-js
37920 timeformat: null, // format string to use
37921 twelveHourClock: false, // 12 or 24 time in time mode
37922 monthNames: null // list of names of months
37923 }
37924 };
37925
37926 // round to nearby lower multiple of base
37927
37928 function floorInBase(n, base) {
37929 return base * Math.floor(n / base);
37930 }
37931
37932 // Returns a string with the date d formatted according to fmt.
37933 // A subset of the Open Group's strftime format is supported.
37934
37935 function formatDate(d, fmt, monthNames, dayNames) {
37936
37937 if (typeof d.strftime == "function") {
37938 return d.strftime(fmt);
37939 }
37940
37941 var leftPad = function(n, pad) {
37942 n = "" + n;
37943 pad = "" + (pad == null ? "0" : pad);
37944 return n.length == 1 ? pad + n : n;
37945 };
37946
37947 var r = [];
37948 var escape = false;
37949 var hours = d.getHours();
37950 var isAM = hours < 12;
37951
37952 if (monthNames == null) {
37953 monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
37954 }
37955
37956 if (dayNames == null) {
37957 dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
37958 }
37959
37960 var hours12;
37961
37962 if (hours > 12) {
37963 hours12 = hours - 12;
37964 } else if (hours == 0) {
37965 hours12 = 12;
37966 } else {
37967 hours12 = hours;
37968 }
37969
37970 for (var i = 0; i < fmt.length; ++i) {
37971
37972 var c = fmt.charAt(i);
37973
37974 if (escape) {
37975 switch (c) {
37976 case 'a': c = "" + dayNames[d.getDay()]; break;
37977 case 'b': c = "" + monthNames[d.getMonth()]; break;
37978 case 'd': c = leftPad(d.getDate()); break;
37979 case 'e': c = leftPad(d.getDate(), " "); break;
37980 case 'h': // For back-compat with 0.7; remove in 1.0
37981 case 'H': c = leftPad(hours); break;
37982 case 'I': c = leftPad(hours12); break;
37983 case 'l': c = leftPad(hours12, " "); break;
37984 case 'm': c = leftPad(d.getMonth() + 1); break;
37985 case 'M': c = leftPad(d.getMinutes()); break;
37986 // quarters not in Open Group's strftime specification
37987 case 'q':
37988 c = "" + (Math.floor(d.getMonth() / 3) + 1); break;
37989 case 'S': c = leftPad(d.getSeconds()); break;
37990 case 'y': c = leftPad(d.getFullYear() % 100); break;
37991 case 'Y': c = "" + d.getFullYear(); break;
37992 case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break;
37993 case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break;
37994 case 'w': c = "" + d.getDay(); break;
37995 }
37996 r.push(c);
37997 escape = false;
37998 } else {
37999 if (c == "%") {
38000 escape = true;
38001 } else {
38002 r.push(c);
38003 }
38004 }
38005 }
38006
38007 return r.join("");
38008 }
38009
38010 // To have a consistent view of time-based data independent of which time
38011 // zone the client happens to be in we need a date-like object independent
38012 // of time zones. This is done through a wrapper that only calls the UTC
38013 // versions of the accessor methods.
38014
38015 function makeUtcWrapper(d) {
38016
38017 function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) {
38018 sourceObj[sourceMethod] = function() {
38019 return targetObj[targetMethod].apply(targetObj, arguments);
38020 };
38021 };
38022
38023 var utc = {
38024 date: d
38025 };
38026
38027 // support strftime, if found
38028
38029 if (d.strftime != undefined) {
38030 addProxyMethod(utc, "strftime", d, "strftime");
38031 }
38032
38033 addProxyMethod(utc, "getTime", d, "getTime");
38034 addProxyMethod(utc, "setTime", d, "setTime");
38035
38036 var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"];
38037
38038 for (var p = 0; p < props.length; p++) {
38039 addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]);
38040 addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]);
38041 }
38042
38043 return utc;
38044 };
38045
38046 // select time zone strategy. This returns a date-like object tied to the
38047 // desired timezone
38048
38049 function dateGenerator(ts, opts) {
38050 if (opts.timezone == "browser") {
38051 return new Date(ts);
38052 } else if (!opts.timezone || opts.timezone == "utc") {
38053 return makeUtcWrapper(new Date(ts));
38054 } else if (typeof timezoneJS != "undefined" && typeof timezoneJS.Date != "undefined") {
38055 var d = new timezoneJS.Date();
38056 // timezone-js is fickle, so be sure to set the time zone before
38057 // setting the time.
38058 d.setTimezone(opts.timezone);
38059 d.setTime(ts);
38060 return d;
38061 } else {
38062 return makeUtcWrapper(new Date(ts));
38063 }
38064 }
38065
38066 // map of app. size of time units in milliseconds
38067
38068 var timeUnitSize = {
38069 "second": 1000,
38070 "minute": 60 * 1000,
38071 "hour": 60 * 60 * 1000,
38072 "day": 24 * 60 * 60 * 1000,
38073 "month": 30 * 24 * 60 * 60 * 1000,
38074 "quarter": 3 * 30 * 24 * 60 * 60 * 1000,
38075 "year": 365.2425 * 24 * 60 * 60 * 1000
38076 };
38077
38078 // the allowed tick sizes, after 1 year we use
38079 // an integer algorithm
38080
38081 var baseSpec = [
38082 [1, "second"], [2, "second"], [5, "second"], [10, "second"],
38083 [30, "second"],
38084 [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"],
38085 [30, "minute"],
38086 [1, "hour"], [2, "hour"], [4, "hour"],
38087 [8, "hour"], [12, "hour"],
38088 [1, "day"], [2, "day"], [3, "day"],
38089 [0.25, "month"], [0.5, "month"], [1, "month"],
38090 [2, "month"]
38091 ];
38092
38093 // we don't know which variant(s) we'll need yet, but generating both is
38094 // cheap
38095
38096 var specMonths = baseSpec.concat([[3, "month"], [6, "month"],
38097 [1, "year"]]);
38098 var specQuarters = baseSpec.concat([[1, "quarter"], [2, "quarter"],
38099 [1, "year"]]);
38100
38101 function init(plot) {
38102 plot.hooks.processOptions.push(function (plot, options) {
38103 $.each(plot.getAxes(), function(axisName, axis) {
38104
38105 var opts = axis.options;
38106
38107 if (opts.mode == "time") {
38108 axis.tickGenerator = function(axis) {
38109
38110 var ticks = [];
38111 var d = dateGenerator(axis.min, opts);
38112 var minSize = 0;
38113
38114 // make quarter use a possibility if quarters are
38115 // mentioned in either of these options
38116
38117 var spec = (opts.tickSize && opts.tickSize[1] ===
38118 "quarter") ||
38119 (opts.minTickSize && opts.minTickSize[1] ===
38120 "quarter") ? specQuarters : specMonths;
38121
38122 if (opts.minTickSize != null) {
38123 if (typeof opts.tickSize == "number") {
38124 minSize = opts.tickSize;
38125 } else {
38126 minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]];
38127 }
38128 }
38129
38130 for (var i = 0; i < spec.length - 1; ++i) {
38131 if (axis.delta < (spec[i][0] * timeUnitSize[spec[i][1]]
38132 + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2
38133 && spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) {
38134 break;
38135 }
38136 }
38137
38138 var size = spec[i][0];
38139 var unit = spec[i][1];
38140
38141 // special-case the possibility of several years
38142
38143 if (unit == "year") {
38144
38145 // if given a minTickSize in years, just use it,
38146 // ensuring that it's an integer
38147
38148 if (opts.minTickSize != null && opts.minTickSize[1] == "year") {
38149 size = Math.floor(opts.minTickSize[0]);
38150 } else {
38151
38152 var magn = Math.pow(10, Math.floor(Math.log(axis.delta / timeUnitSize.year) / Math.LN10));
38153 var norm = (axis.delta / timeUnitSize.year) / magn;
38154
38155 if (norm < 1.5) {
38156 size = 1;
38157 } else if (norm < 3) {
38158 size = 2;
38159 } else if (norm < 7.5) {
38160 size = 5;
38161 } else {
38162 size = 10;
38163 }
38164
38165 size *= magn;
38166 }
38167
38168 // minimum size for years is 1
38169
38170 if (size < 1) {
38171 size = 1;
38172 }
38173 }
38174
38175 axis.tickSize = opts.tickSize || [size, unit];
38176 var tickSize = axis.tickSize[0];
38177 unit = axis.tickSize[1];
38178
38179 var step = tickSize * timeUnitSize[unit];
38180
38181 if (unit == "second") {
38182 d.setSeconds(floorInBase(d.getSeconds(), tickSize));
38183 } else if (unit == "minute") {
38184 d.setMinutes(floorInBase(d.getMinutes(), tickSize));
38185 } else if (unit == "hour") {
38186 d.setHours(floorInBase(d.getHours(), tickSize));
38187 } else if (unit == "month") {
38188 d.setMonth(floorInBase(d.getMonth(), tickSize));
38189 } else if (unit == "quarter") {
38190 d.setMonth(3 * floorInBase(d.getMonth() / 3,
38191 tickSize));
38192 } else if (unit == "year") {
38193 d.setFullYear(floorInBase(d.getFullYear(), tickSize));
38194 }
38195
38196 // reset smaller components
38197
38198 d.setMilliseconds(0);
38199
38200 if (step >= timeUnitSize.minute) {
38201 d.setSeconds(0);
38202 }
38203 if (step >= timeUnitSize.hour) {
38204 d.setMinutes(0);
38205 }
38206 if (step >= timeUnitSize.day) {
38207 d.setHours(0);
38208 }
38209 if (step >= timeUnitSize.day * 4) {
38210 d.setDate(1);
38211 }
38212 if (step >= timeUnitSize.month * 2) {
38213 d.setMonth(floorInBase(d.getMonth(), 3));
38214 }
38215 if (step >= timeUnitSize.quarter * 2) {
38216 d.setMonth(floorInBase(d.getMonth(), 6));
38217 }
38218 if (step >= timeUnitSize.year) {
38219 d.setMonth(0);
38220 }
38221
38222 var carry = 0;
38223 var v = Number.NaN;
38224 var prev;
38225
38226 do {
38227
38228 prev = v;
38229 v = d.getTime();
38230 ticks.push(v);
38231
38232 if (unit == "month" || unit == "quarter") {
38233 if (tickSize < 1) {
38234
38235 // a bit complicated - we'll divide the
38236 // month/quarter up but we need to take
38237 // care of fractions so we don't end up in
38238 // the middle of a day
38239
38240 d.setDate(1);
38241 var start = d.getTime();
38242 d.setMonth(d.getMonth() +
38243 (unit == "quarter" ? 3 : 1));
38244 var end = d.getTime();
38245 d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize);
38246 carry = d.getHours();
38247 d.setHours(0);
38248 } else {
38249 d.setMonth(d.getMonth() +
38250 tickSize * (unit == "quarter" ? 3 : 1));
38251 }
38252 } else if (unit == "year") {
38253 d.setFullYear(d.getFullYear() + tickSize);
38254 } else {
38255 d.setTime(v + step);
38256 }
38257 } while (v < axis.max && v != prev);
38258
38259 return ticks;
38260 };
38261
38262 axis.tickFormatter = function (v, axis) {
38263
38264 var d = dateGenerator(v, axis.options);
38265
38266 // first check global format
38267
38268 if (opts.timeformat != null) {
38269 return formatDate(d, opts.timeformat, opts.monthNames, opts.dayNames);
38270 }
38271
38272 // possibly use quarters if quarters are mentioned in
38273 // any of these places
38274
38275 var useQuarters = (axis.options.tickSize &&
38276 axis.options.tickSize[1] == "quarter") ||
38277 (axis.options.minTickSize &&
38278 axis.options.minTickSize[1] == "quarter");
38279
38280 var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
38281 var span = axis.max - axis.min;
38282 var suffix = (opts.twelveHourClock) ? " %p" : "";
38283 var hourCode = (opts.twelveHourClock) ? "%I" : "%H";
38284 var fmt;
38285
38286 if (t < timeUnitSize.minute) {
38287 fmt = hourCode + ":%M:%S" + suffix;
38288 } else if (t < timeUnitSize.day) {
38289 if (span < 2 * timeUnitSize.day) {
38290 fmt = hourCode + ":%M" + suffix;
38291 } else {
38292 fmt = "%b %d " + hourCode + ":%M" + suffix;
38293 }
38294 } else if (t < timeUnitSize.month) {
38295 fmt = "%b %d";
38296 } else if ((useQuarters && t < timeUnitSize.quarter) ||
38297 (!useQuarters && t < timeUnitSize.year)) {
38298 if (span < timeUnitSize.year) {
38299 fmt = "%b";
38300 } else {
38301 fmt = "%b %Y";
38302 }
38303 } else if (useQuarters && t < timeUnitSize.year) {
38304 if (span < timeUnitSize.year) {
38305 fmt = "Q%q";
38306 } else {
38307 fmt = "Q%q %Y";
38308 }
38309 } else {
38310 fmt = "%Y";
38311 }
38312
38313 var rt = formatDate(d, fmt, opts.monthNames, opts.dayNames);
38314
38315 return rt;
38316 };
38317 }
38318 });
38319 });
38320 }
38321
38322 $.plot.plugins.push({
38323 init: init,
38324 options: options,
38325 name: 'time',
38326 version: '1.0'
38327 });
38328
38329 // Time-axis support used to be in Flot core, which exposed the
38330 // formatDate function on the plot object. Various plugins depend
38331 // on the function, so we need to re-expose it here.
38332
38333 $.plot.formatDate = formatDate;
38334 $.plot.dateGenerator = dateGenerator;
38335
38336 })(jQuery);
38337 /*
38338 * jquery.flot.tooltip
38339 *
38340 * description: easy-to-use tooltips for Flot charts
38341 * version: 0.6.7
38342 * author: Krzysztof Urbas @krzysu [myviews.pl]
38343 * website: https://github.com/krzysu/flot.tooltip
38344 *
38345 * build on 2014-03-26
38346 * released under MIT License, 2012
38347 */
38348 // IE8 polyfill for Array.indexOf
38349 if (!Array.prototype.indexOf) {
38350 Array.prototype.indexOf = function (searchElement, fromIndex) {
38351 if ( this === undefined || this === null ) {
38352 throw new TypeError( '"this" is null or not defined' );
38353 }
38354 var length = this.length >>> 0; // Hack to convert object.length to a UInt32
38355 fromIndex = +fromIndex || 0;
38356 if (Math.abs(fromIndex) === Infinity) {
38357 fromIndex = 0;
38358 }
38359 if (fromIndex < 0) {
38360 fromIndex += length;
38361 if (fromIndex < 0) {
38362 fromIndex = 0;
38363 }
38364 }
38365
38366 for (;fromIndex < length; fromIndex++) {
38367 if (this[fromIndex] === searchElement) {
38368 return fromIndex;
38369 }
38370 }
38371
38372 return -1;
38373 };
38374 }
38375
38376 (function ($) {
38377
38378 // plugin options, default values
38379 var defaultOptions = {
38380 tooltip: false,
38381 tooltipOpts: {
38382 content: "%s | X: %x | Y: %y",
38383 // allowed templates are:
38384 // %s -> series label,
38385 // %lx -> x axis label (requires flot-axislabels plugin https://github.com/markrcote/flot-axislabels),
38386 // %ly -> y axis label (requires flot-axislabels plugin https://github.com/markrcote/flot-axislabels),
38387 // %x -> X value,
38388 // %y -> Y value,
38389 // %x.2 -> precision of X value,
38390 // %p -> percent
38391 xDateFormat: null,
38392 yDateFormat: null,
38393 monthNames: null,
38394 dayNames: null,
38395 shifts: {
38396 x: 10,
38397 y: 20
38398 },
38399 defaultTheme: true,
38400
38401 // callbacks
38402 onHover: function(flotItem, $tooltipEl) {}
38403 }
38404 };
38405
38406 // object
38407 var FlotTooltip = function(plot) {
38408
38409 // variables
38410 this.tipPosition = {x: 0, y: 0};
38411
38412 this.init(plot);
38413 };
38414
38415 // main plugin function
38416 FlotTooltip.prototype.init = function(plot) {
38417
38418 var that = this;
38419
38420 // detect other flot plugins
38421 var plotPluginsLength = $.plot.plugins.length;
38422 this.plotPlugins = [];
38423
38424 if (plotPluginsLength) {
38425 for (var p = 0; p < plotPluginsLength; p++) {
38426 this.plotPlugins.push($.plot.plugins[p].name);
38427 }
38428 }
38429
38430 plot.hooks.bindEvents.push(function (plot, eventHolder) {
38431
38432 // get plot options
38433 that.plotOptions = plot.getOptions();
38434
38435 // if not enabled return
38436 if (that.plotOptions.tooltip === false || typeof that.plotOptions.tooltip === 'undefined') return;
38437
38438 // shortcut to access tooltip options
38439 that.tooltipOptions = that.plotOptions.tooltipOpts;
38440
38441 // create tooltip DOM element
38442 var $tip = that.getDomElement();
38443
38444 // bind event
38445 $( plot.getPlaceholder() ).bind("plothover", plothover);
38446
38447 $(eventHolder).bind('mousemove', mouseMove);
38448 });
38449
38450 plot.hooks.shutdown.push(function (plot, eventHolder){
38451 $(plot.getPlaceholder()).unbind("plothover", plothover);
38452 $(eventHolder).unbind("mousemove", mouseMove);
38453 });
38454
38455 function mouseMove(e){
38456 var pos = {};
38457 pos.x = e.pageX;
38458 pos.y = e.pageY;
38459 that.updateTooltipPosition(pos);
38460 }
38461
38462 function plothover(event, pos, item) {
38463 var $tip = that.getDomElement();
38464 if (item) {
38465 var tipText;
38466
38467 // convert tooltip content template to real tipText
38468 tipText = that.stringFormat(that.tooltipOptions.content, item);
38469
38470 $tip.html( tipText );
38471 that.updateTooltipPosition({ x: pos.pageX, y: pos.pageY });
38472 $tip.css({
38473 left: that.tipPosition.x + that.tooltipOptions.shifts.x,
38474 top: that.tipPosition.y + that.tooltipOptions.shifts.y
38475 })
38476 .show();
38477
38478 // run callback
38479 if(typeof that.tooltipOptions.onHover === 'function') {
38480 that.tooltipOptions.onHover(item, $tip);
38481 }
38482 }
38483 else {
38484 $tip.hide().html('');
38485 }
38486 }
38487 };
38488
38489 /**
38490 * get or create tooltip DOM element
38491 * @return jQuery object
38492 */
38493 FlotTooltip.prototype.getDomElement = function() {
38494 var $tip;
38495
38496 if( $('#flotTip').length > 0 ){
38497 $tip = $('#flotTip');
38498 }
38499 else {
38500 $tip = $('<div />').attr('id', 'flotTip');
38501 $tip.appendTo('body').hide().css({position: 'absolute'});
38502
38503 if(this.tooltipOptions.defaultTheme) {
38504 $tip.css({
38505 'background': '#fff',
38506 'z-index': '1040',
38507 'padding': '0.4em 0.6em',
38508 'border-radius': '0.5em',
38509 'font-size': '0.8em',
38510 'border': '1px solid #111',
38511 'display': 'none',
38512 'white-space': 'nowrap'
38513 });
38514 }
38515 }
38516
38517 return $tip;
38518 };
38519
38520 // as the name says
38521 FlotTooltip.prototype.updateTooltipPosition = function(pos) {
38522 var totalTipWidth = $("#flotTip").outerWidth() + this.tooltipOptions.shifts.x;
38523 var totalTipHeight = $("#flotTip").outerHeight() + this.tooltipOptions.shifts.y;
38524 if ((pos.x - $(window).scrollLeft()) > ($(window).innerWidth() - totalTipWidth)) {
38525 pos.x -= totalTipWidth;
38526 }
38527 if ((pos.y - $(window).scrollTop()) > ($(window).innerHeight() - totalTipHeight)) {
38528 pos.y -= totalTipHeight;
38529 }
38530 this.tipPosition.x = pos.x;
38531 this.tipPosition.y = pos.y;
38532 };
38533
38534 /**
38535 * core function, create tooltip content
38536 * @param {string} content - template with tooltip content
38537 * @param {object} item - Flot item
38538 * @return {string} real tooltip content for current item
38539 */
38540 FlotTooltip.prototype.stringFormat = function(content, item) {
38541
38542 var percentPattern = /%p\.{0,1}(\d{0,})/;
38543 var seriesPattern = /%s/;
38544 var xLabelPattern = /%lx/; // requires flot-axislabels plugin https://github.com/markrcote/flot-axislabels, will be ignored if plugin isn't loaded
38545 var yLabelPattern = /%ly/; // requires flot-axislabels plugin https://github.com/markrcote/flot-axislabels, will be ignored if plugin isn't loaded
38546 var xPattern = /%x\.{0,1}(\d{0,})/;
38547 var yPattern = /%y\.{0,1}(\d{0,})/;
38548 var xPatternWithoutPrecision = "%x";
38549 var yPatternWithoutPrecision = "%y";
38550
38551 var x, y;
38552
38553 // for threshold plugin we need to read data from different place
38554 if (typeof item.series.threshold !== "undefined") {
38555 x = item.datapoint[0];
38556 y = item.datapoint[1];
38557 } else {
38558 x = item.series.data[item.dataIndex][0];
38559 y = item.series.data[item.dataIndex][1];
38560 }
38561
38562 // I think this is only in case of threshold plugin
38563 if (item.series.label === null && item.series.originSeries) {
38564 item.series.label = item.series.originSeries.label;
38565 }
38566
38567 // if it is a function callback get the content string
38568 if( typeof(content) === 'function' ) {
38569 content = content(item.series.label, x, y, item);
38570 }
38571
38572 // percent match for pie charts
38573 if( typeof (item.series.percent) !== 'undefined' ) {
38574 content = this.adjustValPrecision(percentPattern, content, item.series.percent);
38575 }
38576
38577 // series match
38578 if( typeof(item.series.label) !== 'undefined' ) {
38579 content = content.replace(seriesPattern, item.series.label);
38580 }
38581 else {
38582 //remove %s if label is undefined
38583 content = content.replace(seriesPattern, "");
38584 }
38585
38586 // x axis label match
38587 if( this.hasAxisLabel('xaxis', item) ) {
38588 content = content.replace(xLabelPattern, item.series.xaxis.options.axisLabel);
38589 }
38590 else {
38591 //remove %lx if axis label is undefined or axislabels plugin not present
38592 content = content.replace(xLabelPattern, "");
38593 }
38594
38595 // y axis label match
38596 if( this.hasAxisLabel('yaxis', item) ) {
38597 content = content.replace(yLabelPattern, item.series.yaxis.options.axisLabel);
38598 }
38599 else {
38600 //remove %ly if axis label is undefined or axislabels plugin not present
38601 content = content.replace(yLabelPattern, "");
38602 }
38603
38604 // time mode axes with custom dateFormat
38605 if(this.isTimeMode('xaxis', item) && this.isXDateFormat(item)) {
38606 content = content.replace(xPattern, this.timestampToDate(x, this.tooltipOptions.xDateFormat));
38607 }
38608
38609 if(this.isTimeMode('yaxis', item) && this.isYDateFormat(item)) {
38610 content = content.replace(yPattern, this.timestampToDate(y, this.tooltipOptions.yDateFormat));
38611 }
38612
38613 // set precision if defined
38614 if(typeof x === 'number') {
38615 content = this.adjustValPrecision(xPattern, content, x);
38616 }
38617 if(typeof y === 'number') {
38618 content = this.adjustValPrecision(yPattern, content, y);
38619 }
38620
38621 // change x from number to given label, if given
38622 if(typeof item.series.xaxis.ticks !== 'undefined') {
38623
38624 var ticks;
38625 if(this.hasRotatedXAxisTicks(item)) {
38626 // xaxis.ticks will be an empty array if tickRotor is being used, but the values are available in rotatedTicks
38627 ticks = 'rotatedTicks';
38628 }
38629 else {
38630 ticks = 'ticks';
38631 }
38632
38633 // see https://github.com/krzysu/flot.tooltip/issues/65
38634 var tickIndex = item.dataIndex + item.seriesIndex;
38635
38636 if(item.series.xaxis[ticks].length > tickIndex && !this.isTimeMode('xaxis', item))
38637 content = content.replace(xPattern, item.series.xaxis[ticks][tickIndex].label);
38638 }
38639
38640 // change y from number to given label, if given
38641 if(typeof item.series.yaxis.ticks !== 'undefined') {
38642 for (var index in item.series.yaxis.ticks) {
38643 if (item.series.yaxis.ticks.hasOwnProperty(index)) {
38644 var value = (this.isCategoriesMode('yaxis', item)) ? item.series.yaxis.ticks[index].label : item.series.yaxis.ticks[index].v;
38645 if (value === y) {
38646 content = content.replace(yPattern, item.series.yaxis.ticks[index].label);
38647 }
38648 }
38649 }
38650 }
38651
38652 // if no value customization, use tickFormatter by default
38653 if(typeof item.series.xaxis.tickFormatter !== 'undefined') {
38654 //escape dollar
38655 content = content.replace(xPatternWithoutPrecision, item.series.xaxis.tickFormatter(x, item.series.xaxis).replace(/\$/g, '$$'));
38656 }
38657 if(typeof item.series.yaxis.tickFormatter !== 'undefined') {
38658 //escape dollar
38659 content = content.replace(yPatternWithoutPrecision, item.series.yaxis.tickFormatter(y, item.series.yaxis).replace(/\$/g, '$$'));
38660 }
38661
38662 return content;
38663 };
38664
38665 // helpers just for readability
38666 FlotTooltip.prototype.isTimeMode = function(axisName, item) {
38667 return (typeof item.series[axisName].options.mode !== 'undefined' && item.series[axisName].options.mode === 'time');
38668 };
38669
38670 FlotTooltip.prototype.isXDateFormat = function(item) {
38671 return (typeof this.tooltipOptions.xDateFormat !== 'undefined' && this.tooltipOptions.xDateFormat !== null);
38672 };
38673
38674 FlotTooltip.prototype.isYDateFormat = function(item) {
38675 return (typeof this.tooltipOptions.yDateFormat !== 'undefined' && this.tooltipOptions.yDateFormat !== null);
38676 };
38677
38678 FlotTooltip.prototype.isCategoriesMode = function(axisName, item) {
38679 return (typeof item.series[axisName].options.mode !== 'undefined' && item.series[axisName].options.mode === 'categories');
38680 };
38681
38682 //
38683 FlotTooltip.prototype.timestampToDate = function(tmst, dateFormat) {
38684 var theDate = new Date(tmst*1);
38685 return $.plot.formatDate(theDate, dateFormat, this.tooltipOptions.monthNames, this.tooltipOptions.dayNames);
38686 };
38687
38688 //
38689 FlotTooltip.prototype.adjustValPrecision = function(pattern, content, value) {
38690
38691 var precision;
38692 var matchResult = content.match(pattern);
38693 if( matchResult !== null ) {
38694 if(RegExp.$1 !== '') {
38695 precision = RegExp.$1;
38696 value = value.toFixed(precision);
38697
38698 // only replace content if precision exists, in other case use thickformater
38699 content = content.replace(pattern, value);
38700 }
38701 }
38702 return content;
38703 };
38704
38705 // other plugins detection below
38706
38707 // check if flot-axislabels plugin (https://github.com/markrcote/flot-axislabels) is used and that an axis label is given
38708 FlotTooltip.prototype.hasAxisLabel = function(axisName, item) {
38709 return (this.plotPlugins.indexOf('axisLabels') !== -1 && typeof item.series[axisName].options.axisLabel !== 'undefined' && item.series[axisName].options.axisLabel.length > 0);
38710 };
38711
38712 // check whether flot-tickRotor, a plugin which allows rotation of X-axis ticks, is being used
38713 FlotTooltip.prototype.hasRotatedXAxisTicks = function(item) {
38714 return ($.grep($.plot.plugins, function(p){ return p.name === "tickRotor"; }).length === 1 && typeof item.series.xaxis.rotatedTicks !== 'undefined');
38715 };
38716
38717 //
38718 var init = function(plot) {
38719 new FlotTooltip(plot);
38720 };
38721
38722 // define Flot plugin
38723 $.plot.plugins.push({
38724 init: init,
38725 options: defaultOptions,
38726 name: 'tooltip',
38727 version: '0.6.7'
38728 });
38729
38730 })(jQuery);
38731 // SIMILE is not used anymore (and messes with jQuery!) so it was removed
38732 // TimeplotLoader.load(GeoTemCoLoader.urlPrefix + 'lib/', GeoTemCoLoader.loadScripts);
38733
38734 // ..but we still need (and use) the following defines, that where copied from there
38735 /* string.js */
38736 String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"");
38737 };
38738 String.prototype.startsWith=function(A){return this.length>=A.length&&this.substr(0,A.length)==A;
38739 };
38740 String.prototype.endsWith=function(A){return this.length>=A.length&&this.substr(this.length-A.length)==A;
38741 };
38742 String.substitute=function(B,D){var A="";
38743 var F=0;
38744 while(F<B.length-1){var C=B.indexOf("%",F);
38745 if(C<0||C==B.length-1){break;
38746 }else{if(C>F&&B.charAt(C-1)=="\\"){A+=B.substring(F,C-1)+"%";
38747 F=C+1;
38748 }else{var E=parseInt(B.charAt(C+1));
38749 if(isNaN(E)||E>=D.length){A+=B.substring(F,C+2);
38750 }else{A+=B.substring(F,C)+D[E].toString();
38751 }F=C+2;
38752 }}}if(F<B.length){A+=B.substring(F);
38753 }return A;
38754 };
38755
38756 /* date-time.js */
38757 SimileAjax=new Object();
38758 SimileAjax.DateTime=new Object();
38759 SimileAjax.DateTime.MILLISECOND=0;
38760 SimileAjax.DateTime.SECOND=1;
38761 SimileAjax.DateTime.MINUTE=2;
38762 SimileAjax.DateTime.HOUR=3;
38763 SimileAjax.DateTime.DAY=4;
38764 SimileAjax.DateTime.WEEK=5;
38765 SimileAjax.DateTime.MONTH=6;
38766 SimileAjax.DateTime.YEAR=7;
38767 SimileAjax.DateTime.DECADE=8;
38768 SimileAjax.DateTime.CENTURY=9;
38769 SimileAjax.DateTime.MILLENNIUM=10;
38770 SimileAjax.DateTime.EPOCH=-1;
38771 SimileAjax.DateTime.ERA=-2;
38772
38773 SimileAjax.includeCssFile = function(doc, url) {
38774 var link = doc.createElement("link");
38775 link.setAttribute("rel", "stylesheet");
38776 link.setAttribute("type", "text/css");
38777 link.setAttribute("href", url);
38778 doc.getElementsByTagName("head")[0].appendChild(link);
38779 };
38780 /*
38781 * Tooltips.js
38782 *
38783 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
38784 *
38785 * This library is free software; you can redistribute it and/or
38786 * modify it under the terms of the GNU Lesser General Public
38787 * License as published by the Free Software Foundation; either
38788 * version 3 of the License, or (at your option) any later version.
38789 *
38790 * This library is distributed in the hope that it will be useful,
38791 * but WITHOUT ANY WARRANTY; without even the implied warranty of
38792 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
38793 * Lesser General Public License for more details.
38794 *
38795 * You should have received a copy of the GNU Lesser General Public
38796 * License along with this library; if not, write to the Free Software
38797 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
38798 * MA 02110-1301 USA
38799 */
38800
38801 /**
38802 * Tooltips JSON
38803 * GeoTemCo tooltips definition file
38804 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
38805 * @release 1.0
38806 * @release date: 2012-07-27
38807 * @version date: 2012-07-27
38808 */
38809 var Tooltips = {
38810 "en" : {
38811 "locationType" : "Location type",
38812 "selectLocationType" : "Select location type",
38813 "mapType" : "Background map",
38814 "selectMapType" : "Select background map",
38815 "selectOverlay" : "Select layer for spatial filtering",
38816 "overlays" : "Select layer",
38817 "mapSelectorTools" : "Map selector tools",
38818 "overlaySelector" : "Selection layer",
38819 "square" : "Square selection: Mouse down for the center and mouse move to set square bounds",
38820 "circle" : "Circle selection: Mouse down for the center and mouse move to set circle radius",
38821 "polygon" : "Polygon selection: Click to add vertex and double click to complete the polygon",
38822 "country" : "Country selection: Click inside the political borders of a country",
38823 "singleEntry" : "Only 1 entry available",
38824 "resultsLocation" : "with location information",
38825 "home" : "Reset map to initial view",
38826 "zoomIn" : "Zoom in",
38827 "zoomOut" : "Zoom out",
38828 "zoomSlider" : "Zoom slider",
38829 "dragSelection" : "Drag&Drop shape",
38830 "zoomSelection" : "Zoom into selection",
38831 "clearSelection" : "Clear selection",
38832 "contemporaryMap" : "Contemporary Map",
38833 "activateGeoLocation" : "Show my location",
38834 "deactivateGeoLocation" : "Hide my location",
38835 "mapOf" : "Map of",
38836 "close" : "Close",
38837 "genericBinning" : "delaunay",
38838 "squareBinning" : "square",
38839 "hexagonalBinning" : "hexagonal",
38840 "triangularBinning" : "triangular",
38841 "noBinning" : "none",
38842 "selectBinningType" : "Select aggregation type",
38843 "binningType" : "Aggregation type",
38844 "binningTooltip" : "Select the aggregation type for the data sources",
38845 "results" : "results",
38846 "result" : "result",
38847 "timeType" : "Time type",
38848 "timeUnit" : "Time unit:",
38849 "selectTimeType" : "Select time type",
38850 "timeAnimation" : "Animation",
38851 "resultsTime" : "with time information",
38852 "animationDisabled" : "Animation control (disabled)",
38853 "animationPlay" : "Animate selected time range",
38854 "animationPause" : "Pause animation",
38855 "leftHandle" : "Drag&Drop left border",
38856 "rightHandle" : "Drag&Drop right border",
38857 "dragTimeRange" : "Drag&Drop time range",
38858 "connectionsOn" : "Switch on time-dependent connections between map circles",
38859 "connectionsOff" : "Switch off time-dependent connections",
38860 "timeFeather" : "Adjust time range feather to smoothen map animations",
38861 "allResults" : "all",
38862 "pageInfo" : "Page PAGE_ID of PAGES_ID",
38863 "resultsInfo" : "RESULTS_FROM_ID-RESULTS_TO_ID of RESULTS_ID Results",
38864 "otherResults" : "others",
38865 "mapAggregation" : "Aggregation",
38866 "aggregation" : "Circle aggregation",
38867 "noAggregation" : "No circle aggregation",
38868 "showBoxTitle" : "Boundingbox",
38869 "showBbox" : "Shows given Boundingbox extension",
38870 "hideBbox" : "Hides given Boundingbox extension",
38871 "spaceHelp" : "A point on the map corresponds to one or more objects from the result list. ",
38872 "timeHelp" : "On the timeline are the search results sorted by year. You can choose different time-based categories as basis for the representation.",
38873 "selectTablePageItemsHelp" : "Click to select all rows of this page",
38874 "deselectTablePageItemsHelp" : "Click to deselect all rows of this page",
38875 "selectAllTableItemsHelp" : "Click to select all rows of the table",
38876 "deselectAllTableItemsHelp" : "Click to deselect all rows of the table",
38877 "filter" : "Filter",
38878 "filterSelectedItemsHelp" : "Filter the selected items",
38879 "inverseFilterSelectedItemsHelp" : "Apply an inverse filter on the selected items removing them from the views",
38880 "undoFilterSelection" : "Undo the last filter / inverse filter",
38881 "cancelSelection" : "Discard the current selection (all items appear as deselected)",
38882 "showSelectedHelp" : "Show only elements within the selection",
38883 "selectByTextHelp" : "Select elements that contain the given text",
38884 "showAllElementsHelp" : "Show all elements",
38885 "paginationFirsPageHelp" : "Show first page",
38886 "paginationPreviousPageHelp" : "Show previous page",
38887 "paginationNextPageHelp" : "Show next page",
38888 "paginationLastPageHelp" : "Show last page",
38889 "sortAZHelp" : "Sort table elements ascending according this column",
38890 "sortZAHelp" : "Sort table elements descending according this column",
38891 "paginationDropdownHelp" : "Select number of elements per page",
38892 "selectTimeUnit" : "Select Time Unit",
38893 "valueScale" : "Value Scale",
38894 "linearPlot" : "Linear Value Scale",
38895 "logarithmicPlot" : "Logarithmic Value Scale",
38896 "playButton" : "Animate Selected Range",
38897 "pauseButton" : "Pause Animation",
38898 "createNewFromSelectedHelp" : "Create new dataset from selected values",
38899 "removeDatasetHelp" : "Remove this dataset",
38900 "exportDatasetHelp" : "Export this dataset to a KML file",
38901 "invertSelectionHelp" : "Invert the current selection",
38902 "colorShapeDatasetHelp" : "change color or shape of dataset",
38903 "lockMap" : "lock the map in this state"
38904 },
38905 "de" : {
38906 "locationType" : "Ortsfacette",
38907 "selectLocationType" : "W&auml;hle Ortsfacette",
38908 "mapType" : "Kartentyp",
38909 "selectMapType" : "W&auml;hle Kartentyp",
38910 "selectOverlay" : "Kartenauswahl f&uuml;r r&auml;mliches filtern",
38911 "overlays" : "W&auml;hle layer",
38912 "mapSelectorTools" : "Bereichsauswahl",
38913 "overlaySelector" : "Selection layer",
38914 "square" : "Quadratauswahl: Maus ziehen und loslassen um Mittelpunkt und Seitenl&auml;nge des Quadrats zu bestimmen",
38915 "circle" : "Kreisauswahl: Maus ziehen und loslassen um Mittelpunkt und Radius des Kreises zu bestimmen",
38916 "polygon" : "Polygonauswahl: Mausklick zum Hinzuf&uuml;gen eines Eckpunktes, Doppelklick zum Fertigstellen",
38917 "country" : "Landauswahl: Mausklick innerhalb politischer Grenze eines Landes",
38918 "singleEntry" : "Nur 1 Eintrag vorhanden",
38919 "resultsLocation" : "mit Geoinformation",
38920 "home" : "Zur&uuml;cksetzen zur initialen Sicht",
38921 "zoomIn" : "Vergr&ouml;&szlig;ern",
38922 "zoomOut" : "Verkleinern",
38923 "zoomSlider" : "Zoomregler",
38924 "dragSelection" : "Verschiebe Auswahl",
38925 "zoomSelection" : "Vergr&ouml;&szlig;ere Auswahl",
38926 "clearSelection" : "Entferne Auswahlbereich",
38927 "contemporaryMap" : "Aktuelle Weltkarte",
38928 "activateGeoLocation" : "Meinen Standort anzeigen",
38929 "deactivateGeoLocation" : "Meinen Standort ausblenden",
38930 "mapOf" : "Karte von",
38931 "close" : "Schliessen",
38932 "genericBinning" : "Generisch",
38933 "squareBinning" : "Quadrate",
38934 "hexagonalBinning" : "Hexagone",
38935 "triangularBinning" : "Dreiecke",
38936 "noBinning" : "Keine Bins",
38937 "selectBinningType" : "W&auml;hle Binningart",
38938 "binningTooltip" : "W&aunl;hle die Binninart f&uuml;r die Datenquellen",
38939 "binningType" : "Binningart",
38940 "results" : "Resultate",
38941 "result" : "Resultat",
38942 "timeType" : "Zeitfacette",
38943 "timeUnit" : "Zeiteinheit",
38944 "selectTimeType" : "W&auml;hle Zeitfacette",
38945 "timeAnimation" : "Animation",
38946 "resultsTime" : "mit Zeitinformation",
38947 "animationDisabled" : "Animationswerkzeug (deaktiviert)",
38948 "animationPlay" : "Animiere ausgew&auml;hlten Zeitbereich",
38949 "animationPause" : "Animation anhalten",
38950 "leftHandle" : "Verschiebe linke Grenze",
38951 "rightHandle" : "Verschiebe rechte Grenze",
38952 "dragTimeRange" : "Verschiebe Zeitbereich",
38953 "connectionsOn" : "Aktiviere zeitabhängige Verbindungen zwischen Kreisen auf der Karte",
38954 "connectionsOff" : "Deaktiviere zeitabhängige Verbindungen",
38955 "timeFeather" : "Ver&auml;ndere Zeitbereichs&uuml;berg&auml;nge zum Gl&auml;tten der Animation",
38956 "pageInfo" : "Seite PAGE_ID von PAGES_ID",
38957 "resultsInfo" : "RESULTS_FROM_ID-RESULTS_TO_ID von RESULTS_ID Ergebnissen",
38958 "allResults" : "alle",
38959 "otherResults" : "sonstige",
38960 "mapAggregation" : "Aggregation",
38961 "aggregation" : "Kreise aggregiert",
38962 "noAggregation" : "Kreise nicht aggregiert",
38963 "showBbox" : "Geografische Ausdehnung anzeigen",
38964 "hideBbox" : "Geografische Ausdehnung ausblenden",
38965 "spaceHelp" : "Jeder Punkt auf der Karte entspricht einem oder mehreren Objekten der Ergebnisliste. Sie k&ouml;nnen verschiedene ortsbezogene Kategorien als Grundlage f&uuml;r die Darstellung w&auml;hlen (Auswahlfeld <strong>Ortsfacette</strong>) und verschiedene Kartentypen. <br> Da es Objekte geben kann, die keine Ortsangabe in ihrer Beschreibung enthalten, ist die Menge der in der Karte dargestellten Objekte in der Regel kleiner als in der Ergebnisliste (Anzahl darstellbarer Objekte siehe rechts oben über der Karte). <br> Mit der Karte können Sie die Suchergebnisse weiter eingrenzen, indem Sie auf einen der Punkte klicken. Wählen Sie einen Ort aus und klicken Sie auf die kleine Lupe, um die Ergebnisliste so einzuschränken, dass nur noch die diesem Ort zugeordneten Objekte als Suchergebnis erscheinen. Mehr zur Karte im Benutzerhandbuch ...",
38966 "timeHelp" : "In der Zeitleiste sind die Suchergebnisse nach Jahren geordnet. Sie k&ouml;nnen verschiedene zeitbezogene Kategorien als Grundlage f&uuml;r die Darstellung w&auml;hlen (Auswahlfeld <strong>Zeitfacette</strong>). <br> Da es Objekte geben kann, die keine Zeitangabe in ihrer Beschreibung enthalten, ist die Zahl der in der Zeitleiste dargestellten Objekte in der Regel kleiner als in der Ergebnisliste. Die Angabe über darstellbare Objekte finden Sie rechts über der Zeitleiste. <br>Mit der Zeitleiste können Sie die Suchergebnisse weiter eingrenzen. Wählen Sie ein Jahr oder einen Zeitraum durch Klicken und Ziehen und klicken Sie auf die kleine Lupe. Die Ergebnisliste zeigt nur noch die Objekte in diesem Zeitraum. Mehr zur Zeitleiste im Benutzerhandbuch ...",
38967 "selectTablePageItemsHelp" : "Click to select all rows of this page",
38968 "deselectTablePageItemsHelp" : "Click to deselect all rows of this page",
38969 "selectAllTableItemsHelp" : "Click to select all rows of the table",
38970 "deselectAllTableItemsHelp" : "Click to deselect all rows of the table",
38971 "filter" : "Filter",
38972 "filterSelectedItemsHelp" : "Filter the selected items",
38973 "inverseFilterSelectedItemsHelp" : "Apply an inverse filter on the selected items removing them from the views",
38974 "undoFilterSelection" : "Undo the last filter / inverse filter",
38975 "cancelSelection" : "Discard the current selection (all items appear as deselected)",
38976 "showSelectedHelp" : "Show only elements within the selection",
38977 "selectByTextHelp" : "Select elements that contain the given text",
38978 "showAllElementsHelp" : "Show all elements",
38979 "paginationFirsPageHelp" : "Show first page",
38980 "paginationPreviousPageHelp" : "Show previous page",
38981 "paginationNextPageHelp" : "Show next page",
38982 "paginationLastPageHelp" : "Show last page",
38983 "sortAZHelp" : "Sort table elements ascending according this column",
38984 "sortZAHelp" : "Sort table elements descending according this column",
38985 "paginationDropdownHelp" : "Select number of elements per page",
38986 "selectTimeUnit" : "W&auml;hle Zeitinervalle",
38987 "valueScale" : "Value Scale",
38988 "linearPlot" : "Linear Value Scale",
38989 "logarithmicPlot" : "Logarithmic Value Scale",
38990 "playButton" : "Animate Selected Range",
38991 "pauseButton" : "Pause Animation",
38992 "createNewFromSelectedHelp" : "Erstelle neuen Datensatz aus den selektierten Eintr&auml;gen",
38993 "removeDatasetHelp" : "Diesen Datensatz entfernen",
38994 "exportDatasetHelp" : "Diesen Datensatz in KML Datei exportieren",
38995 "invertSelectionHelp" : "Jetzige Selektion umkehren",
38996 "colorShapeDatasetHelp" : "Farbe oder Form des Datensatzes ändern",
38997 "lockMap" : "Karte in diesem Zustand halten."
38998 }
38999 }
39000 /*
39001 * GeoTemConfig.js
39002 *
39003 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
39004 *
39005 * This library is free software; you can redistribute it and/or
39006 * modify it under the terms of the GNU Lesser General Public
39007 * License as published by the Free Software Foundation; either
39008 * version 3 of the License, or (at your option) any later version.
39009 *
39010 * This library is distributed in the hope that it will be useful,
39011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
39012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
39013 * Lesser General Public License for more details.
39014 *
39015 * You should have received a copy of the GNU Lesser General Public
39016 * License along with this library; if not, write to the Free Software
39017 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
39018 * MA 02110-1301 USA
39019 */
39020
39021 /**
39022 * @class GeoTemConfig
39023 * Global GeoTemCo Configuration File
39024 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
39025 * @release 1.0
39026 * @release date: 2012-07-27
39027 * @version date: 2012-07-27
39028 */
39029
39030
39031 // credits: user76888, The Digital Gabeg (http://stackoverflow.com/questions/1539367)
39032 $.fn.cleanWhitespace = function() {
39033 textNodes = this.contents().filter( function() {
39034 return (this.nodeType == 3 && !/\S/.test(this.nodeValue));
39035 }).remove();
39036 return this;
39037 };
39038
39039 GeoTemConfig = {
39040 debug : false, //show debug output (esp. regarding corrupt datasets)
39041 incompleteData : true, // show/hide data with either temporal or spatial metadata
39042 inverseFilter : true, // if inverse filtering is offered
39043 mouseWheelZoom : true, // enable/disable zoom with mouse wheel on map & timeplot
39044 language : 'en', // default language of GeoTemCo
39045 allowFilter : true, // if filtering should be allowed
39046 highlightEvents : true, // if updates after highlight events
39047 selectionEvents : true, // if updates after selection events
39048 tableExportDataset : true, // export dataset to KML
39049 allowCustomColoring : false, // if DataObjects can have an own color (useful for weighted coloring)
39050 allowUserShapeAndColorChange: false, // if the user can change the shapes and color of datasets
39051 // this turns MapConfig.useGraphics auto-on, but uses circles as default
39052 loadColorFromDataset : false, // if DataObject color should be loaded automatically (from column "color")
39053 allowColumnRenaming : true,
39054 //proxy : 'php/proxy.php?address=', //set this if a HTTP proxy shall be used (e.g. to bypass X-Domain problems)
39055 //colors for several datasets; rgb1 will be used for selected objects, rgb0 for unselected
39056 colors : [{
39057 r1 : 255,
39058 g1 : 101,
39059 b1 : 0,
39060 r0 : 253,
39061 g0 : 229,
39062 b0 : 205
39063 }, {
39064 r1 : 144,
39065 g1 : 26,
39066 b1 : 255,
39067 r0 : 230,
39068 g0 : 225,
39069 b0 : 255
39070 }, {
39071 r1 : 0,
39072 g1 : 217,
39073 b1 : 0,
39074 r0 : 213,
39075 g0 : 255,
39076 b0 : 213
39077 }, {
39078 r1 : 240,
39079 g1 : 220,
39080 b1 : 0,
39081 r0 : 247,
39082 g0 : 244,
39083 b0 : 197
39084 }]
39085
39086 }
39087
39088 GeoTemConfig.ie = false;
39089 GeoTemConfig.ie8 = false;
39090
39091 GeoTemConfig.independentMapId = 0;
39092 GeoTemConfig.independentTimeId = 0;
39093
39094 if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
39095 GeoTemConfig.ie = true;
39096 var ieversion = new Number(RegExp.$1);
39097 if (ieversion == 8) {
39098 GeoTemConfig.ie8 = true;
39099 }
39100 }
39101
39102 GeoTemConfig.quoteVal = function(val){
39103 return val.replace(new RegExp('"', 'g'), '%22');
39104
39105 }
39106
39107 GeoTemConfig.getIndependentId = function(target){
39108 if( target == 'map' ){
39109 return ++GeoTemConfig.independentMapId;
39110 }
39111 if( target == 'time' ){
39112 return ++GeoTemConfig.independentTimeId;
39113 }
39114 return 0;
39115 };
39116
39117 GeoTemConfig.setHexColor = function(hex,index,fill){
39118 var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
39119 if( fill ){
39120 GeoTemConfig.colors[index].r0 = parseInt(result[1], 16);
39121 GeoTemConfig.colors[index].g0 = parseInt(result[2], 16);
39122 GeoTemConfig.colors[index].b0 = parseInt(result[3], 16);
39123 }
39124 else {
39125 GeoTemConfig.colors[index].r1 = parseInt(result[1], 16);
39126 GeoTemConfig.colors[index].g1 = parseInt(result[2], 16);
39127 GeoTemConfig.colors[index].b1 = parseInt(result[3], 16);
39128 }
39129 }
39130
39131 GeoTemConfig.setRgbColor = function(r,g,b,index,fill){
39132 if( fill ){
39133 GeoTemConfig.colors[index].r0 = r;
39134 GeoTemConfig.colors[index].g0 = g;
39135 GeoTemConfig.colors[index].b0 = b;
39136 }
39137 else {
39138 GeoTemConfig.colors[index].r1 = r;
39139 GeoTemConfig.colors[index].g1 = g;
39140 GeoTemConfig.colors[index].b1 = b;
39141 }
39142 }
39143
39144 GeoTemConfig.configure = function(urlPrefix) {
39145 GeoTemConfig.urlPrefix = urlPrefix;
39146 GeoTemConfig.path = GeoTemConfig.urlPrefix + "images/";
39147 }
39148
39149 GeoTemConfig.applySettings = function(settings) {
39150 $.extend(this, settings);
39151 };
39152
39153 //Keeps track of how many colors where assigned yet.
39154 GeoTemConfig.assignedColorCount = 0;
39155 GeoTemConfig.getColor = function(id){
39156 if (typeof GeoTemConfig.datasets[id].color === "undefined"){
39157 var color;
39158
39159 while (true){
39160 if( GeoTemConfig.colors.length <= GeoTemConfig.assignedColorCount ){
39161 color = {
39162 r1 : Math.floor((Math.random()*255)+1),
39163 g1 : Math.floor((Math.random()*255)+1),
39164 b1 : Math.floor((Math.random()*255)+1),
39165 r0 : 230,
39166 g0 : 230,
39167 b0 : 230
39168 };
39169 } else
39170 color = GeoTemConfig.colors[GeoTemConfig.assignedColorCount];
39171
39172 //make sure that no other dataset has this color
39173 //TODO: one could also check that they are not too much alike
39174 var found = false;
39175 for (var i = 0; i < GeoTemConfig.datasets.length; i++){
39176 var dataset = GeoTemConfig.datasets[i];
39177
39178 if (typeof dataset.color === "undefined")
39179 continue;
39180
39181 if ( (dataset.color.r1 == color.r1) &&
39182 (dataset.color.g1 == color.g1) &&
39183 (dataset.color.b1 == color.b1) ){
39184 found = true;
39185 break;
39186 }
39187 }
39188 if (found === true){
39189 if( GeoTemConfig.colors.length <= GeoTemConfig.assignedColorCount ){
39190 //next time skip over this color
39191 GeoTemConfig.assignedColorCount++;
39192 }
39193 continue;
39194 } else {
39195 GeoTemConfig.colors.push(color);
39196 break;
39197 }
39198 }
39199 GeoTemConfig.datasets[id].color = color;
39200
39201 GeoTemConfig.assignedColorCount++;
39202 }
39203 return GeoTemConfig.datasets[id].color;
39204 };
39205
39206 GeoTemConfig.getAverageDatasetColor = function(id, objects){
39207 var c = new Object();
39208 var datasetColor = GeoTemConfig.getColor(id);
39209 c.r0 = datasetColor.r0;
39210 c.g0 = datasetColor.g0;
39211 c.b0 = datasetColor.b0;
39212 c.r1 = datasetColor.r1;
39213 c.g1 = datasetColor.g1;
39214 c.b1 = datasetColor.b1;
39215 if (!GeoTemConfig.allowCustomColoring)
39216 return c;
39217 if (objects.length == 0)
39218 return c;
39219 var avgColor = new Object();
39220 avgColor.r0 = 0;
39221 avgColor.g0 = 0;
39222 avgColor.b0 = 0;
39223 avgColor.r1 = 0;
39224 avgColor.g1 = 0;
39225 avgColor.b1 = 0;
39226
39227 $(objects).each(function(){
39228 if (this.hasColorInformation){
39229 avgColor.r0 += this.color.r0;
39230 avgColor.g0 += this.color.g0;
39231 avgColor.b0 += this.color.b0;
39232 avgColor.r1 += this.color.r1;
39233 avgColor.g1 += this.color.g1;
39234 avgColor.b1 += this.color.b1;
39235 } else {
39236 avgColor.r0 += datasetColor.r0;
39237 avgColor.g0 += datasetColor.g0;
39238 avgColor.b0 += datasetColor.b0;
39239 avgColor.r1 += datasetColor.r1;
39240 avgColor.g1 += datasetColor.g1;
39241 avgColor.b1 += datasetColor.b1;
39242 }
39243 });
39244
39245 c.r0 = Math.floor(avgColor.r0/objects.length);
39246 c.g0 = Math.floor(avgColor.g0/objects.length);
39247 c.b0 = Math.floor(avgColor.b0/objects.length);
39248 c.r1 = Math.floor(avgColor.r1/objects.length);
39249 c.g1 = Math.floor(avgColor.g1/objects.length);
39250 c.b1 = Math.floor(avgColor.b1/objects.length);
39251
39252 return c;
39253 };
39254
39255 GeoTemConfig.getString = function(field) {
39256 if ( typeof Tooltips[GeoTemConfig.language] == 'undefined') {
39257 GeoTemConfig.language = 'en';
39258 }
39259 return Tooltips[GeoTemConfig.language][field];
39260 }
39261 /**
39262 * returns the actual mouse position
39263 * @param {Event} e the mouseevent
39264 * @return the top and left position on the screen
39265 */
39266 GeoTemConfig.getMousePosition = function(e) {
39267 if (!e) {
39268 e = window.event;
39269 }
39270 var body = (window.document.compatMode && window.document.compatMode == "CSS1Compat") ? window.document.documentElement : window.document.body;
39271 return {
39272 top : e.pageY ? e.pageY : e.clientY,
39273 left : e.pageX ? e.pageX : e.clientX
39274 };
39275 }
39276 /**
39277 * returns the json object of the file from the given url
39278 * @param {String} url the url of the file to load
39279 * @return json object of given file
39280 */
39281 GeoTemConfig.getJson = function(url,asyncFunc) {
39282 var async = false;
39283 if( asyncFunc ){
39284 async = true;
39285 }
39286
39287 var data;
39288 $.ajax({
39289 url : url,
39290 async : async,
39291 dataType : 'json',
39292 success : function(json) {
39293 data = json;
39294 if (async){
39295 asyncFunc(data);
39296 }
39297 }
39298 });
39299
39300 if (async){
39301 return data;
39302 }
39303 }
39304
39305 GeoTemConfig.mergeObjects = function(set1, set2) {
39306 var inside = [];
39307 var newSet = [];
39308 for (var i = 0; i < GeoTemConfig.datasets.length; i++){
39309 inside.push([]);
39310 newSet.push([]);
39311 }
39312 for (var i = 0; i < set1.length; i++) {
39313 for (var j = 0; j < set1[i].length; j++) {
39314 inside[i][set1[i][j].index] = true;
39315 newSet[i].push(set1[i][j]);
39316 }
39317 }
39318 for (var i = 0; i < set2.length; i++) {
39319 for (var j = 0; j < set2[i].length; j++) {
39320 if (!inside[i][set2[i][j].index]) {
39321 newSet[i].push(set2[i][j]);
39322 }
39323 }
39324 }
39325 return newSet;
39326 };
39327
39328 GeoTemConfig.datasets = [];
39329
39330 GeoTemConfig.addDataset = function(newDataset){
39331 GeoTemConfig.datasets.push(newDataset);
39332 Publisher.Publish('filterData', GeoTemConfig.datasets, null);
39333 };
39334
39335 GeoTemConfig.addDatasets = function(newDatasets){
39336 $(newDatasets).each(function(){
39337 GeoTemConfig.datasets.push(this);
39338 });
39339 Publisher.Publish('filterData', GeoTemConfig.datasets, null);
39340 };
39341
39342 GeoTemConfig.removeDataset = function(index){
39343 GeoTemConfig.datasets.splice(index,1);
39344 Publisher.Publish('filterData', GeoTemConfig.datasets, null);
39345 };
39346
39347 GeoTemConfig.removeAllDatasets = function() {
39348
39349 if (GeoTemConfig.datasets.length > 0) {
39350 GeoTemConfig.datasets.splice(0, GeoTemConfig.datasets.length);
39351 Publisher.Publish('filterData', GeoTemConfig.datasets, null);
39352 }
39353 };
39354
39355 /**
39356 * converts the csv-file into json-format
39357 *
39358 * @param {String}
39359 * text
39360 */
39361 GeoTemConfig.convertCsv = function(text){
39362 /* convert here from CSV to JSON */
39363 var json = [];
39364 /* define expected csv table headers (first line) */
39365 var expectedHeaders = new Array("Name","Address","Description","Longitude","Latitude","TimeStamp","TimeSpan:begin","TimeSpan:end","weight");
39366 /* convert csv string to array of arrays using ucsv library */
39367 var csvArray = CSV.csvToArray(text);
39368 /* get real used table headers from csv file (first line) */
39369 var usedHeaders = csvArray[0];
39370 /* loop outer array, begin with second line */
39371 for (var i = 1; i < csvArray.length; i++) {
39372 var innerArray = csvArray[i];
39373 var dataObject = new Object();
39374 var tableContent = new Object();
39375 /* exclude lines with no content */
39376 var hasContent = false;
39377 for (var j = 0; j < innerArray.length; j++) {
39378 if (typeof innerArray[j] !== "undefined"){
39379 if (typeof innerArray[j] === "string"){
39380 if (innerArray[j].length > 0)
39381 hasContent = true;
39382 } else {
39383 hasContent = true;
39384 }
39385 }
39386
39387 if (hasContent === true)
39388 break;
39389 }
39390 if (hasContent === false)
39391 continue;
39392 /* loop inner array */
39393 for (var j = 0; j < innerArray.length; j++) {
39394 /* Name */
39395 if (usedHeaders[j] == expectedHeaders[0]) {
39396 dataObject["name"] = ""+innerArray[j];
39397 tableContent["name"] = ""+innerArray[j];
39398 }
39399 /* Address */
39400 else if (usedHeaders[j] == expectedHeaders[1]) {
39401 dataObject["place"] = ""+innerArray[j];
39402 tableContent["place"] = ""+innerArray[j];
39403 }
39404 /* Description */
39405 else if (usedHeaders[j] == expectedHeaders[2]) {
39406 dataObject["description"] = ""+innerArray[j];
39407 tableContent["description"] = ""+innerArray[j];
39408 }
39409 /* TimeStamp */
39410 else if (usedHeaders[j] == expectedHeaders[5]) {
39411 dataObject["time"] = ""+innerArray[j];
39412 }
39413 /* TimeSpan:begin */
39414 else if (usedHeaders[j] == expectedHeaders[6]) {
39415 tableContent["TimeSpan:begin"] = ""+innerArray[j];
39416 }
39417 /* TimeSpan:end */
39418 else if (usedHeaders[j] == expectedHeaders[7]) {
39419 tableContent["TimeSpan:end"] = ""+innerArray[j];
39420 }
39421 /* weight */
39422 else if (usedHeaders[j] == expectedHeaders[8]) {
39423 dataObject["weight"] = ""+innerArray[j];
39424 }
39425 /* Longitude */
39426 else if (usedHeaders[j] == expectedHeaders[3]) {
39427 dataObject["lon"] = parseFloat(innerArray[j]);
39428 }
39429 /* Latitude */
39430 else if (usedHeaders[j] == expectedHeaders[4]) {
39431 dataObject["lat"] = parseFloat(innerArray[j]);
39432 }
39433 else {
39434 var header = new String(usedHeaders[j]);
39435 //remove leading and trailing Whitespace
39436 header = $.trim(header);
39437 tableContent[header] = ""+innerArray[j];
39438 }
39439 }
39440
39441 dataObject["tableContent"] = tableContent;
39442
39443 json.push(dataObject);
39444 }
39445
39446 return json;
39447 };
39448
39449 /**
39450 * returns the xml dom object of the file from the given url
39451 * @param {String} url the url of the file to load
39452 * @return xml dom object of given file
39453 */
39454 GeoTemConfig.getKml = function(url,asyncFunc) {
39455 var data;
39456 var async = false;
39457 if( asyncFunc ){
39458 async = true;
39459 }
39460 $.ajax({
39461 url : url,
39462 async : async,
39463 dataType : 'xml',
39464 success : function(xml) {
39465 if( asyncFunc ){
39466 asyncFunc(xml);
39467 }
39468 else {
39469 data = xml;
39470 }
39471 }
39472 });
39473 if( !async ){
39474 return data;
39475 }
39476 }
39477
39478 /**
39479 * returns an array of all xml dom object of the kmls
39480 * found in the zip file from the given url
39481 *
39482 * can only be used with asyncFunc (because of browser
39483 * constraints regarding arraybuffer)
39484 *
39485 * @param {String} url the url of the file to load
39486 * @return xml dom object of given file
39487 */
39488 GeoTemConfig.getKmz = function(url,asyncFunc) {
39489 var kmlDom = new Array();
39490
39491 var async = true;
39492 if( !asyncFunc ){
39493 //if no asyncFunc is given return an empty array
39494 return kmlDom;
39495 }
39496
39497 //use XMLHttpRequest as "arraybuffer" is not
39498 //supported in jQuery native $.get
39499 var req = new XMLHttpRequest();
39500 req.open("GET",url,async);
39501 req.responseType = "arraybuffer";
39502 req.onload = function() {
39503 var zip = new JSZip();
39504 zip.load(req.response, {base64:false});
39505 var kmlFiles = zip.file(new RegExp("kml$"));
39506
39507 $(kmlFiles).each(function(){
39508 var kml = this;
39509 if (kml.data != null) {
39510 kmlDom.push($.parseXML(kml.data));
39511 }
39512 });
39513
39514 asyncFunc(kmlDom);
39515 };
39516 req.send();
39517 };
39518
39519 /**
39520 * returns the JSON "object"
39521 * from the csv file from the given url
39522 * @param {String} url the url of the file to load
39523 * @return xml dom object of given file
39524 */
39525 GeoTemConfig.getCsv = function(url,asyncFunc) {
39526 var async = false;
39527 if( asyncFunc ){
39528 async = true;
39529 }
39530
39531 //use XMLHttpRequest as synchronous behaviour
39532 //is not supported in jQuery native $.get
39533 var req = new XMLHttpRequest();
39534 req.open("GET",url,async);
39535 //can only be set on asynchronous now
39536 //req.responseType = "text";
39537 var json;
39538 req.onload = function() {
39539 json = GeoTemConfig.convertCsv(req.response);
39540 if( asyncFunc )
39541 asyncFunc(json);
39542 };
39543 req.send();
39544
39545 if( !async ){
39546 return json;
39547 }
39548 };
39549
39550 /**
39551 * loads a binary file
39552 * @param {String} url of the file to load
39553 * @return binary data
39554 */
39555 GeoTemConfig.getBinary = function(url,asyncFunc) {
39556 var async = true;
39557
39558 var req = new XMLHttpRequest();
39559 req.open("GET",url,async);
39560 req.responseType = "arraybuffer";
39561
39562 var binaryData;
39563 req.onload = function() {
39564 var arrayBuffer = req.response;
39565 asyncFunc(arrayBuffer);
39566 };
39567 req.send();
39568 };
39569
39570 /**
39571 * returns a Date and a SimileAjax.DateTime granularity value for a given XML time
39572 * @param {String} xmlTime the XML time as String
39573 * @return JSON object with a Date and a SimileAjax.DateTime granularity
39574 */
39575 GeoTemConfig.getTimeData = function(xmlTime) {
39576 if (!xmlTime)
39577 return;
39578 var dateData;
39579 try {
39580 var bc = false;
39581 if (xmlTime.startsWith("-")) {
39582 bc = true;
39583 xmlTime = xmlTime.substring(1);
39584 }
39585 var timeSplit = xmlTime.split("T");
39586 var timeData = timeSplit[0].split("-");
39587 for (var i = 0; i < timeData.length; i++) {
39588 parseInt(timeData[i]);
39589 }
39590 if (bc) {
39591 timeData[0] = "-" + timeData[0];
39592 }
39593 if (timeSplit.length == 1) {
39594 dateData = timeData;
39595 } else {
39596 var dayData;
39597 if (timeSplit[1].indexOf("Z") != -1) {
39598 dayData = timeSplit[1].substring(0, timeSplit[1].indexOf("Z") - 1).split(":");
39599 } else {
39600 dayData = timeSplit[1].substring(0, timeSplit[1].indexOf("+") - 1).split(":");
39601 }
39602 for (var i = 0; i < timeData.length; i++) {
39603 parseInt(dayData[i]);
39604 }
39605 dateData = timeData.concat(dayData);
39606 }
39607 } catch (exception) {
39608 return null;
39609 }
39610 var date, granularity;
39611 if (dateData.length == 6) {
39612 granularity = SimileAjax.DateTime.SECOND;
39613 date = new Date(Date.UTC(dateData[0], dateData[1] - 1, dateData[2], dateData[3], dateData[4], dateData[5]));
39614 } else if (dateData.length == 3) {
39615 granularity = SimileAjax.DateTime.DAY;
39616 date = new Date(Date.UTC(dateData[0], dateData[1] - 1, dateData[2]));
39617 } else if (dateData.length == 2) {
39618 granularity = SimileAjax.DateTime.MONTH;
39619 date = new Date(Date.UTC(dateData[0], dateData[1] - 1, 1));
39620 } else if (dateData.length == 1) {
39621 granularity = SimileAjax.DateTime.YEAR;
39622 date = new Date(Date.UTC(dateData[0], 0, 1));
39623 }
39624 if (timeData[0] && timeData[0] < 100) {
39625 date.setFullYear(timeData[0]);
39626 }
39627
39628 //check data validity;
39629 var isValidDate = true;
39630 if ( date instanceof Date ) {
39631 if ( isNaN( date.getTime() ) )
39632 isValidDate = false;
39633 } else
39634 isValidDate = false;
39635
39636 if (!isValidDate){
39637 if ((GeoTemConfig.debug)&&(typeof console !== "undefined"))
39638 console.error(xmlTime + " is no valid time format");
39639 return null;
39640 }
39641
39642 return {
39643 date : date,
39644 granularity : granularity
39645 };
39646 }
39647 /**
39648 * converts a JSON array into an array of data objects
39649 * @param {JSON} JSON a JSON array of data items
39650 * @return an array of data objects
39651 */
39652 GeoTemConfig.loadJson = function(JSON) {
39653 var mapTimeObjects = [];
39654 var runningIndex = 0;
39655 for (var i in JSON ) {
39656 try {
39657 var item = JSON[i];
39658 var index = item.index || item.id || runningIndex++;
39659 var name = item.name || "";
39660 var description = item.description || "";
39661 var tableContent = item.tableContent || [];
39662 var locations = [];
39663 if (item.location instanceof Array) {
39664 for (var j = 0; j < item.location.length; j++) {
39665 var place = item.location[j].place || "unknown";
39666 var lon = item.location[j].lon;
39667 var lat = item.location[j].lat;
39668 if ((typeof lon === "undefined" || typeof lat === "undefined" || isNaN(lon) || isNaN(lat) ) && !GeoTemConfig.incompleteData) {
39669 throw "e";
39670 }
39671 locations.push({
39672 longitude : lon,
39673 latitude : lat,
39674 place : place
39675 });
39676 }
39677 } else {
39678 var place = item.place || "unknown";
39679 var lon = item.lon;
39680 var lat = item.lat;
39681 if ((typeof lon === "undefined" || typeof lat === "undefined" || isNaN(lon) || isNaN(lat) ) && !GeoTemConfig.incompleteData) {
39682 throw "e";
39683 }
39684 locations.push({
39685 longitude : lon,
39686 latitude : lat,
39687 place : place
39688 });
39689 }
39690 var dates = [];
39691 if (item.time instanceof Array) {
39692 for (var j = 0; j < item.time.length; j++) {
39693 var time = GeoTemConfig.getTimeData(item.time[j]);
39694 if (time == null && !GeoTemConfig.incompleteData) {
39695 throw "e";
39696 }
39697 dates.push(time);
39698 }
39699 } else {
39700 var time = GeoTemConfig.getTimeData(item.time);
39701 if (time == null && !GeoTemConfig.incompleteData) {
39702 throw "e";
39703 }
39704 if (time != null) {
39705 dates.push(time);
39706 }
39707 }
39708 var weight = parseInt(item.weight) || 1;
39709 //add all "other" attributes to table data
39710 //this is a hack to allow "invalid" JSONs
39711 var specialAttributes = ["id", "name", "description", "lon", "lat", "place", "time",
39712 "tableContent", "location", "time"];
39713 for (var attribute in item){
39714 if ($.inArray(attribute, specialAttributes) == -1){
39715 tableContent[attribute] = item[attribute];
39716 }
39717 }
39718
39719 var mapTimeObject = new DataObject(name, description, locations, dates, weight, tableContent);
39720 mapTimeObject.setIndex(index);
39721 mapTimeObjects.push(mapTimeObject);
39722 } catch(e) {
39723 continue;
39724 }
39725 }
39726
39727 if (GeoTemConfig.loadColorFromDataset)
39728 GeoTemConfig.loadDataObjectColoring(mapTimeObjects);
39729
39730 return mapTimeObjects;
39731 }
39732 /**
39733 * converts a KML dom into an array of data objects
39734 * @param {XML dom} kml the XML dom for the KML file
39735 * @return an array of data objects
39736 */
39737 GeoTemConfig.loadKml = function(kml) {
39738 var mapObjects = [];
39739 var elements = kml.getElementsByTagName("Placemark");
39740 if (elements.length == 0) {
39741 return [];
39742 }
39743 var index = 0;
39744 var descriptionTableHeaders = [];
39745 var xmlSerializer = new XMLSerializer();
39746
39747 for (var i = 0; i < elements.length; i++) {
39748 var placemark = elements[i];
39749 var name, description, place, granularity, lon, lat, tableContent = [], time = [], location = [];
39750 var weight = 1;
39751 var timeData = false, mapData = false;
39752
39753 try {
39754 description = placemark.getElementsByTagName("description")[0].childNodes[0].nodeValue;
39755
39756 //cleanWhitespace removes non-sense text-nodes (space, tab)
39757 //and is an addition to jquery defined above
39758 try {
39759 var descriptionDocument = $($.parseXML(description)).cleanWhitespace();
39760
39761 //check whether the description element contains a table
39762 //if yes, this data will be loaded as separate columns
39763 $(descriptionDocument).find("table").each(function(){
39764 $(this).find("tr").each(
39765 function() {
39766 var isHeader = true;
39767 var lastHeader = "";
39768
39769 $(this).find("td").each(
39770 function() {
39771 if (isHeader) {
39772 lastHeader = $.trim($(this).text());
39773 isHeader = false;
39774 } else {
39775 var value = "";
39776
39777 //if this td contains HTML, serialize all
39778 //it's children (the "content"!)
39779 $(this).children().each(
39780 function() {
39781 value += xmlSerializer.serializeToString(this);
39782 }
39783 );
39784
39785 //no HTML content (or no content at all)
39786 if (value.length == 0)
39787 value = $(this).text();
39788 if (typeof value === "undefined")
39789 value = "";
39790
39791 if ($.inArray(lastHeader, descriptionTableHeaders) === -1)
39792 descriptionTableHeaders.push(lastHeader);
39793
39794 if (tableContent[lastHeader] != null)
39795 //append if a field occures more than once
39796 tableContent[lastHeader] += "\n" + value;
39797 else
39798 tableContent[lastHeader] = value;
39799
39800 isHeader = true;
39801 }
39802 }
39803 );
39804 }
39805 );
39806 });
39807 } catch(e) {
39808 //couldn't be parsed, so it contains no html table
39809 //or is not in valid XHTML syntax
39810 }
39811
39812 //check whether the description element contains content in the form of equations
39813 //e.g. someDescriptor = someValue, where these eqations are separated by <br/>
39814 //if yes, this data will be loaded as separate columns
39815 var descriptionRows = description.replace(/<\s*br\s*[\/]*\s*>/g,"<br/>");
39816 $(descriptionRows.split("<br/>")).each(function(){
39817 var row = this;
39818
39819 if (typeof row === "undefined")
39820 return;
39821
39822 var headerAndValue = row.split("=");
39823 if (headerAndValue.length != 2)
39824 return;
39825
39826 var header = $.trim(headerAndValue[0]);
39827 var value = $.trim(headerAndValue[1]);
39828
39829 if ($.inArray(header, descriptionTableHeaders) === -1)
39830 descriptionTableHeaders.push(header);
39831
39832 if (tableContent[header] != null)
39833 //append if a field occures more than once
39834 tableContent[header] += "\n" + value;
39835 else
39836 tableContent[header] = value;
39837 });
39838
39839 tableContent["description"] = description;
39840 } catch(e) {
39841 description = "";
39842 }
39843
39844 try {
39845 name = placemark.getElementsByTagName("name")[0].childNodes[0].nodeValue;
39846 tableContent["name"] = name;
39847 } catch(e) {
39848 if (typeof tableContent["name"] !== "undefined")
39849 name = tableContent["name"];
39850 else
39851 name = "";
39852 }
39853
39854 try {
39855 place = placemark.getElementsByTagName("address")[0].childNodes[0].nodeValue;
39856 tableContent["place"] = place;
39857 } catch(e) {
39858 if (typeof tableContent["place"] !== "undefined")
39859 place = tableContent["place"];
39860 else
39861 place = "";
39862 }
39863
39864 try {
39865 var coordinates = placemark.getElementsByTagName("Point")[0].getElementsByTagName("coordinates")[0].childNodes[0].nodeValue;
39866 var lonlat = coordinates.split(",");
39867 lon = lonlat[0];
39868 lat = lonlat[1];
39869 if (lon == "" || lat == "" || isNaN(lon) || isNaN(lat)) {
39870 throw "e";
39871 }
39872 location.push({
39873 longitude : lon,
39874 latitude : lat,
39875 place : place
39876 });
39877 } catch(e) {
39878 if (!GeoTemConfig.incompleteData) {
39879 continue;
39880 }
39881 }
39882
39883 try {
39884 var tuple = GeoTemConfig.getTimeData(placemark.getElementsByTagName("TimeStamp")[0].getElementsByTagName("when")[0].childNodes[0].nodeValue);
39885 if (tuple != null) {
39886 time.push(tuple);
39887 timeData = true;
39888 } else if (!GeoTemConfig.incompleteData) {
39889 continue;
39890 }
39891 } catch(e) {
39892 try {
39893 if ( (typeof tableContent["TimeSpan:begin"] === "undefined") &&
39894 (typeof tableContent["TimeSpan:end"] === "undefined") ){
39895 var timeStart = $(placemark).find("TimeSpan begin").text();
39896 var timeEnd = $(placemark).find("TimeSpan end").text();
39897
39898 if ( (timeStart != "") && (timeStart != "") ){
39899 tableContent["TimeSpan:begin"] = timeStart;
39900 tableContent["TimeSpan:end"] = timeEnd;
39901
39902 timeData = true;
39903 }
39904 }
39905 } catch(e) {
39906 if (!GeoTemConfig.incompleteData) {
39907 continue;
39908 }
39909 }
39910 }
39911 var object = new DataObject(name, description, location, time, 1, tableContent);
39912 object.setIndex(index);
39913 index++;
39914 mapObjects.push(object);
39915 }
39916
39917 //make sure that all "description table" columns exists in all rows
39918 if (descriptionTableHeaders.length > 0){
39919 $(mapObjects).each(function(){
39920 var object = this;
39921 $(descriptionTableHeaders).each(function(){
39922 if (typeof object.tableContent[this] === "undefined")
39923 object.tableContent[this] = "";
39924 });
39925 });
39926 }
39927
39928 if (GeoTemConfig.loadColorFromDataset)
39929 GeoTemConfig.loadDataObjectColoring(mapObjects);
39930
39931 return mapObjects;
39932 };
39933
39934 GeoTemConfig.createKMLfromDataset = function(index){
39935 var kmlContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><kml xmlns=\"http://www.opengis.net/kml/2.2\"><Document>";
39936
39937 //credits: Anatoly Mironov, http://stackoverflow.com/questions/2573521/how-do-i-output-an-iso-8601-formatted-string-in-javascript
39938 function pad(number) {
39939 var r = String(number);
39940 if ( r.length === 1 ) {
39941 r = '0' + r;
39942 }
39943 return r;
39944 }
39945
39946 var dateToISOString = function(date, granularity) {
39947 var ISOString = date.getFullYear();
39948
39949 if (granularity <= SimileAjax.DateTime.MONTH)
39950 ISOString += '-' + pad( date.getMonth() + 1 );
39951 if (granularity <= SimileAjax.DateTime.DAY)
39952 ISOString += '-' + pad( date.getDate() );
39953 if (granularity <= SimileAjax.DateTime.HOUR){
39954 ISOString += 'T' + pad( date.getHours() );
39955 if (granularity <= SimileAjax.DateTime.MINUTE)
39956 ISOString += ':' + pad( date.getMinutes() );
39957 if (granularity <= SimileAjax.DateTime.SECOND)
39958 ISOString += ':' + pad( date.getSeconds() );
39959 if (granularity <= SimileAjax.DateTime.MILLISECOND)
39960 ISOString += '.' + String( (date.getMilliseconds()/1000).toFixed(3) ).slice( 2, 5 );
39961 ISOString += 'Z';
39962 }
39963
39964 return ISOString;
39965 };
39966
39967 $(GeoTemConfig.datasets[index].objects).each(function(){
39968 var name = this.name;
39969 var description = this.description;
39970 //TODO: allow multiple time/date
39971 var place = this.getPlace(0,0);
39972 var lat = this.getLatitude(0);
39973 var lon = this.getLongitude(0);
39974
39975 var kmlEntry = "<Placemark>";
39976
39977 kmlEntry += "<name><![CDATA[" + name + "]]></name>";
39978 kmlEntry += "<address><![CDATA[" + place + "]]></address>";
39979 kmlEntry += "<description><![CDATA[" + description + "]]></description>";
39980 kmlEntry += "<Point><coordinates>" + lon + "," + lat + "</coordinates></Point>";
39981
39982 if (this.isTemporal){
39983 kmlEntry += "<TimeStamp><when>" + dateToISOString(this.getDate(0), this.getTimeGranularity(0)) + "</when></TimeStamp>";
39984 } else if (this.isFuzzyTemporal){
39985 kmlEntry += "<TimeSpan>"+
39986 "<begin>" + dateToISOString(this.TimeSpanBegin.utc().toDate(), this.TimeSpanBeginGranularity) + "</begin>" +
39987 "<end>" + dateToISOString(this.TimeSpanEnd.utc().toDate(), this.TimeSpanEndGranularity) + "</end>" +
39988 "</TimeSpan>";
39989 }
39990
39991 kmlEntry += "</Placemark>";
39992
39993 kmlContent += kmlEntry;
39994 });
39995
39996 kmlContent += "</Document></kml>";
39997
39998 return(kmlContent);
39999 };
40000
40001 GeoTemConfig.createCSVfromDataset = function(index){
40002 var csvContent = "";
40003 var header = ["name", "description", "weight"];
40004 var tableContent = [];
40005
40006 var firstDataObject = GeoTemConfig.datasets[index].objects[0];
40007
40008 for(var key in firstDataObject.tableContent){
40009 var found = false;
40010 $(header).each(function(index,val){
40011 if (val === key){
40012 found = true;
40013 return false;
40014 }
40015 });
40016 if (found === true)
40017 continue;
40018 else
40019 tableContent.push(key);
40020 }
40021
40022 var isFirst = true;
40023 $(header).each(function(key,val){
40024 if (isFirst){
40025 isFirst = false;
40026 } else {
40027 csvContent += ",";
40028 }
40029
40030 //Rename according to CSV import definition
40031 if (val === "name")
40032 val = "Name";
40033 else if (val === "description")
40034 val = "Description";
40035 csvContent += "\""+val+"\"";
40036 });
40037 $(tableContent).each(function(key,val){
40038 if (isFirst){
40039 isFirst = false;
40040 } else {
40041 csvContent += ",";
40042 }
40043 csvContent += "\""+val+"\"";
40044 });
40045 //Names according to CSV import definition
40046 csvContent += ",\"Address\",\"Latitude\",\"Longitude\",\"TimeStamp\",\"TimeSpan:begin\",\"TimeSpan:end\"";
40047 csvContent += "\n";
40048
40049 var isFirstRow = true;
40050 $(GeoTemConfig.datasets[index].objects).each(function(){
40051 var elem = this;
40052
40053 if (isFirstRow){
40054 isFirstRow = false;
40055 } else {
40056 csvContent += "\n";
40057 }
40058
40059 var isFirst = true;
40060 $(header).each(function(key,val){
40061 if (isFirst){
40062 isFirst = false;
40063 } else {
40064 csvContent += ",";
40065 }
40066 csvContent += "\""+elem[val]+"\"";
40067 });
40068 $(tableContent).each(function(key,val){
40069 if (isFirst){
40070 isFirst = false;
40071 } else {
40072 csvContent += ",";
40073 }
40074 csvContent += "\""+GeoTemConfig.quoteVal(elem.tableContent[val])+"\"";
40075 });
40076
40077 csvContent += ",";
40078 csvContent += "\"";
40079 if (elem.isGeospatial){
40080 csvContent += elem.locations[0].place;
40081 }
40082 csvContent += "\"";
40083
40084 csvContent += ",";
40085 csvContent += "\"";
40086 if ( (elem.isGeospatial) && (typeof elem.getLatitude(0) !== "undefined") ){
40087 csvContent += elem.getLatitude(0);
40088 }
40089 csvContent += "\"";
40090
40091 csvContent += ",";
40092 csvContent += "\"";
40093 if ( (elem.isGeospatial) && (typeof elem.getLongitude(0) !== "undefined") ){
40094 csvContent += elem.getLongitude(0);
40095 }
40096 csvContent += "\"";
40097
40098 csvContent += ",";
40099 csvContent += "\"";
40100 if ( (elem.isTemporal) && (typeof elem.getDate(0) !== "undefined") ){
40101 //TODO: not supported in IE8 switch to moment.js
40102 csvContent += elem.getDate(0).toISOString();
40103 }
40104 csvContent += "\"";
40105
40106 csvContent += ",";
40107 if (elem.isFuzzyTemporal){
40108 //TODO: not supported in IE8 switch to moment.js
40109 csvContent += "\""+elem.TimeSpanBegin.format()+"\",\""+elem.TimeSpanEnd.format()+"\"";
40110 } else {
40111 csvContent += "\"\",\"\"";
40112 }
40113 });
40114
40115 return(csvContent);
40116 };
40117 /**
40118 * iterates over Datasets/DataObjects and loads color values
40119 * from the "color0" and "color1" elements, which contains RGB
40120 * values in hex (CSS style #RRGGBB)
40121 * @param {dataObjects} array of DataObjects
40122 */
40123 GeoTemConfig.loadDataObjectColoring = function(dataObjects) {
40124 $(dataObjects).each(function(){
40125 var r0,g0,b0,r1,g1,b1;
40126 if ( (typeof this.tableContent !== "undefined") &&
40127 (typeof this.tableContent["color0"] !== "undefined") ){
40128 var color = this.tableContent["color0"];
40129 if ( (color.indexOf("#") == 0) && (color.length == 7) ){
40130 r0 = parseInt("0x"+color.substr(1,2));
40131 g0 = parseInt("0x"+color.substr(3,2));
40132 b0 = parseInt("0x"+color.substr(5,2));
40133 }
40134 }
40135 if ( (typeof this.tableContent !== "undefined") &&
40136 (typeof this.tableContent["color1"] !== "undefined") ){
40137 var color = this.tableContent["color1"];
40138 if ( (color.indexOf("#") == 0) && (color.length == 7) ){
40139 r1 = parseInt("0x"+color.substr(1,2));
40140 g1 = parseInt("0x"+color.substr(3,2));
40141 b1 = parseInt("0x"+color.substr(5,2));
40142 }
40143 }
40144
40145 if ( (typeof r0 !== "undefined") && (typeof g0 !== "undefined") && (typeof b0 !== "undefined") &&
40146 (typeof r1 !== "undefined") && (typeof g1 !== "undefined") && (typeof b1 !== "undefined") ){
40147 this.setColor(r0,g0,b0,r1,g1,b1);
40148 delete this.tableContent["color0"];
40149 delete this.tableContent["color1"];
40150 } else {
40151 if ((GeoTemConfig.debug)&&(typeof console !== undefined))
40152 console.error("Object '" + this.name + "' has invalid color information");
40153 }
40154 });
40155 };
40156
40157 /**
40158 * renames (or copies, see below) a column of each DataObject in a Dataset
40159 * @param {Dataset} dataset the dataset where the rename should take place
40160 * @param {String} oldColumn name of column that will be renamed
40161 * @param {String} newColumn new name of column
40162 * @param {Boolean} keepOld keep old column (copy mode)
40163 * @return an array of data objects
40164 */
40165 GeoTemConfig.renameColumns = function(dataset, renames){
40166 if (renames.length===0){
40167 return;
40168 }
40169 for (var renCnt = 0; renCnt < renames.length; renCnt++){
40170 var oldColumn = renames[renCnt].oldColumn;
40171 var newColumn = renames[renCnt].newColumn;
40172
40173 var keepOld = renames[renCnt].keepOld;
40174 if (typeof keepOld === "undefined"){
40175 keepOld = true;
40176 }
40177 var oldColumObject = {};
40178 if (oldColumn.indexOf("[") != -1){
40179 oldColumObject.columnName = oldColumn.split("[")[0];
40180 var IndexAndAttribute = oldColumn.split("[")[1];
40181 if (IndexAndAttribute.indexOf("]") != -1){
40182 oldColumObject.type = 2;
40183 oldColumObject.arrayIndex = IndexAndAttribute.split("]")[0];
40184 var attribute = IndexAndAttribute.split("]")[1];
40185 if (attribute.length > 0){
40186 oldColumObject.type = 3;
40187 oldColumObject.attribute = attribute.split(".")[1];
40188 }
40189 }
40190 } else {
40191 oldColumObject.type = 1;
40192 oldColumObject.name = oldColumn;
40193 }
40194
40195 var newColumObject = {};
40196 if (newColumn.indexOf("[") != -1){
40197 newColumObject.name = newColumn.split("[")[0];
40198 var IndexAndAttribute = newColumn.split("[")[1];
40199 if (IndexAndAttribute.indexOf("]") != -1){
40200 newColumObject.type = 2;
40201 newColumObject.arrayIndex = IndexAndAttribute.split("]")[0];
40202 var attribute = IndexAndAttribute.split("]")[1];
40203 if (attribute.length > 0){
40204 newColumObject.type = 3;
40205 newColumObject.attribute = attribute.split(".")[1];
40206 }
40207 }
40208 } else {
40209 newColumObject.type = 1;
40210 newColumObject.name = newColumn;
40211 }
40212
40213 for (var i = 0; i < dataset.objects.length; i++){
40214 var dataObject = dataset.objects[i];
40215
40216 //get value from old column name
40217 var value;
40218 if (oldColumObject.type == 1){
40219 value = dataObject[oldColumObject.name];
40220 if (typeof value === "undefined"){
40221 value = dataObject.tableContent[oldColumObject.name];
40222 }
40223 if (!keepOld){
40224 delete dataObject.tableContent[oldColumObject.name];
40225 delete dataObject[oldColumObject.name];
40226 }
40227 } else if (oldColumObject.type == 2){
40228 value = dataObject[oldColumObject.name][oldColumObject.arrayIndex];
40229 if (!keepOld){
40230 delete dataObject[oldColumObject.name][oldColumObject.arrayIndex];
40231 }
40232 } else if (oldColumObject.type == 3){
40233 value = dataObject[oldColumObject.name][oldColumObject.arrayIndex][oldColumObject.attribute];
40234 if (!keepOld){
40235 delete dataObject[oldColumObject.name][oldColumObject.arrayIndex][oldColumObject.attribute];
40236 }
40237 }
40238
40239 //create new column
40240 if (newColumObject.type == 1){
40241 dataObject[newColumObject.name] = value;
40242 dataObject.tableContent[newColumObject.name] = value;
40243 } else if (newColumObject.type == 2){
40244 if (typeof dataObject[newColumObject.name] == "undefined"){
40245 dataObject[newColumObject.name] = [];
40246 }
40247 dataObject[newColumObject.name][newColumObject.arrayIndex] = value;
40248 } else if (newColumObject.type == 3){
40249 if (typeof dataObject[newColumObject.name] == "undefined"){
40250 dataObject[newColumObject.name] = [];
40251 }
40252 if (typeof dataObject[newColumObject.name][newColumObject.arrayIndex] == "undefined"){
40253 dataObject[newColumObject.name][newColumObject.arrayIndex] = {};
40254 }
40255 dataObject[newColumObject.name][newColumObject.arrayIndex][newColumObject.attribute] = value;
40256 }
40257 }
40258 }
40259
40260 //actually create new dataObjects
40261 for (var i = 0; i < dataset.objects.length; i++){
40262 var dataObject = dataset.objects[i];
40263 //save index
40264 var index = dataObject.index;
40265
40266 dataset.objects[i] = new DataObject(dataObject.name, dataObject.description, dataObject.locations,
40267 dataObject.dates, dataObject.weight, dataObject.tableContent, dataObject.projection);
40268 //set index
40269 dataset.objects[i].setIndex(index);
40270 }
40271 };
40272 /*
40273 * MapControl.js
40274 *
40275 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
40276 *
40277 * This library is free software; you can redistribute it and/or
40278 * modify it under the terms of the GNU Lesser General Public
40279 * License as published by the Free Software Foundation; either
40280 * version 3 of the License, or (at your option) any later version.
40281 *
40282 * This library is distributed in the hope that it will be useful,
40283 * but WITHOUT ANY WARRANTY; without even the implied warranty of
40284 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
40285 * Lesser General Public License for more details.
40286 *
40287 * You should have received a copy of the GNU Lesser General Public
40288 * License along with this library; if not, write to the Free Software
40289 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
40290 * MA 02110-1301 USA
40291 */
40292
40293 /**
40294 * @class MapControl
40295 * Generic map control interface
40296 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
40297 * @release 1.0
40298 * @release date: 2012-07-27
40299 * @version date: 2012-07-27
40300 */
40301 function MapControl(map, button, label, onActivate, onDeactivate) {
40302
40303 var control = this;
40304 this.button = button;
40305 this.enabled = true;
40306 this.activated = false;
40307 this.label = label;
40308
40309 if (this.button != null) {
40310 $(this.button).addClass(label + 'Deactivated');
40311 $(this.button).attr("title", GeoTemConfig.getString(GeoTemConfig.language, label));
40312 //vhz
40313 $(this.button).click(function() {
40314 control.checkStatus();
40315 });
40316 }
40317
40318 this.checkStatus = function() {
40319 if (control.enabled) {
40320 if ( typeof map.activeControl != 'undefined') {
40321 if (control.activated) {
40322 control.deactivate();
40323 } else {
40324 map.activeControl.deactivate();
40325 control.activate();
40326 }
40327 } else {
40328 control.activate();
40329 }
40330 }
40331 };
40332
40333 this.setButtonClass = function(removeClass, addClass) {
40334 if (this.button != null) {
40335 $(this.button).removeClass(label + removeClass);
40336 $(this.button).addClass(label + addClass);
40337 $(this.button).attr("title", GeoTemConfig.getString(GeoTemConfig.language, label));
40338 }
40339 };
40340
40341 this.disable = function() {
40342 this.enabled = false;
40343 this.setButtonClass('Deactivated', 'Disabled');
40344 };
40345
40346 this.enable = function() {
40347 this.enabled = true;
40348 this.setButtonClass('Disabled', 'Deactivated');
40349 };
40350
40351 this.activate = function() {
40352 onActivate();
40353 this.activated = true;
40354 this.setButtonClass('Deactivated', 'Activated');
40355 map.activeControl = this;
40356 };
40357
40358 this.deactivate = function() {
40359 onDeactivate();
40360 this.activated = false;
40361 this.setButtonClass('Activated', 'Deactivated');
40362 map.activeControl = undefined;
40363 };
40364
40365 };
40366 /*
40367 * CircleObject.js
40368 *
40369 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
40370 *
40371 * This library is free software; you can redistribute it and/or
40372 * modify it under the terms of the GNU Lesser General Public
40373 * License as published by the Free Software Foundation; either
40374 * version 3 of the License, or (at your option) any later version.
40375 *
40376 * This library is distributed in the hope that it will be useful,
40377 * but WITHOUT ANY WARRANTY; without even the implied warranty of
40378 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
40379 * Lesser General Public License for more details.
40380 *
40381 * You should have received a copy of the GNU Lesser General Public
40382 * License along with this library; if not, write to the Free Software
40383 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
40384 * MA 02110-1301 USA
40385 */
40386
40387 /**
40388 * @class CircleObject
40389 * circle object aggregate for the map
40390 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
40391 * @release 1.0
40392 * @release date: 2012-07-27
40393 * @version date: 2012-07-27
40394 *
40395 * @param {float} x the x (longitude) value for the circle
40396 * @param {float} y the y (latitude) value for the circle
40397 * @param {DataObject[]} elements array of data objects belonging to the circle
40398 * @param {float} radius the resulting radius (in pixel) for the circle
40399 * @param {int} search dataset index
40400 * @param {int} weight summed weight of all elements
40401 * @param {JSON} fatherBin bin of the circle object if its part of a circle pack
40402 */
40403 CircleObject = function(originX, originY, shiftX, shiftY, elements, radius, search, weight, fatherBin) {
40404
40405 this.originX = originX;
40406 this.originY = originY;
40407 this.shiftX = shiftX;
40408 this.shiftY = shiftY;
40409 this.elements = elements;
40410 this.radius = radius;
40411 this.search = search;
40412 this.weight = weight;
40413 this.overlay = 0;
40414 this.overlayElements = [];
40415 this.smoothness = 0;
40416 this.fatherBin = fatherBin;
40417
40418 this.feature
40419 this.olFeature
40420 this.percentage = 0;
40421 this.selected = false;
40422
40423 };
40424
40425 CircleObject.prototype = {
40426
40427 /**
40428 * sets the OpenLayers point feature for this point object
40429 * @param {OpenLayers.Feature} pointFeature the point feature for this object
40430 */
40431 setFeature : function(feature) {
40432 this.feature = feature;
40433 },
40434
40435 /**
40436 * sets the OpenLayers point feature for this point object to manage its selection status
40437 * @param {OpenLayers.Feature} olPointFeature the overlay point feature for this object
40438 */
40439 setOlFeature : function(olFeature) {
40440 this.olFeature = olFeature;
40441 },
40442
40443 reset : function() {
40444 this.overlay = 0;
40445 this.overlayElements = [];
40446 this.smoothness = 0;
40447 },
40448
40449 setSelection : function(s) {
40450 this.selected = s;
40451 },
40452
40453 toggleSelection : function() {
40454 this.selected = !this.selected;
40455 }
40456 };
40457 /*
40458 * FilterBar.js
40459 *
40460 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
40461 *
40462 * This library is free software; you can redistribute it and/or
40463 * modify it under the terms of the GNU Lesser General Public
40464 * License as published by the Free Software Foundation; either
40465 * version 3 of the License, or (at your option) any later version.
40466 *
40467 * This library is distributed in the hope that it will be useful,
40468 * but WITHOUT ANY WARRANTY; without even the implied warranty of
40469 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
40470 * Lesser General Public License for more details.
40471 *
40472 * You should have received a copy of the GNU Lesser General Public
40473 * License along with this library; if not, write to the Free Software
40474 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
40475 * MA 02110-1301 USA
40476 */
40477
40478 /**
40479 * @class FilterBar
40480 * Implementation for FilterBar Object
40481 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
40482 * @release 1.0
40483 * @release date: 2012-07-27
40484 * @version date: 2012-07-27
40485 *
40486 * @param {Object} parent parent to call filter functions
40487 * @param {HTML object} parentDiv div to append filter buttons
40488 */
40489 FilterBarFactory = {
40490 filterBarArray :[],
40491 push : function(newFilterBar){
40492 FilterBarFactory.filterBarArray.push(newFilterBar);
40493 },
40494 resetAll : function(show) {
40495 $(FilterBarFactory.filterBarArray).each(function(){
40496 if (show) {
40497 this.filter.setAttribute('class', 'smallButton filter');
40498 this.filterInverse.setAttribute('class', 'smallButton filterInverse');
40499 this.cancelSelection.setAttribute('class', 'smallButton filterCancel');
40500 } else {
40501 this.filter.setAttribute('class', 'smallButton filterDisabled');
40502 this.filterInverse.setAttribute('class', 'smallButton filterInverseDisabled');
40503 this.cancelSelection.setAttribute('class', 'smallButton filterCancelDisabled');
40504 }
40505 });
40506 }
40507 };
40508
40509 function FilterBar(parent, parentDiv) {
40510 FilterBarFactory.push(this);
40511
40512 var bar = this;
40513
40514 this.filter = document.createElement('div');
40515 this.filter.setAttribute('class', 'smallButton filterDisabled');
40516 this.filter.onclick = function() {
40517 parent.filtering();
40518 };
40519
40520 this.filterInverse = document.createElement('div');
40521 this.filterInverse.setAttribute('class', 'smallButton filterInverseDisabled');
40522 this.filterInverse.onclick = function() {
40523 parent.inverseFiltering();
40524 };
40525 if (!GeoTemConfig.inverseFilter) {
40526 this.filterInverse.style.display = 'none';
40527 }
40528
40529 this.cancelSelection = document.createElement('div');
40530 this.cancelSelection.setAttribute('class', 'smallButton filterCancelDisabled');
40531 this.cancelSelection.onclick = function() {
40532 parent.deselection();
40533 };
40534
40535 this.appendTo = function(parentDiv) {
40536 parentDiv.appendChild(this.filter);
40537 parentDiv.appendChild(this.filterInverse);
40538 parentDiv.appendChild(this.cancelSelection);
40539 }
40540 if ( typeof parentDiv != 'undefined') {
40541 this.appendTo(parentDiv);
40542 }
40543
40544 this.reset = function(show) {
40545 FilterBarFactory.resetAll(show);
40546 };
40547
40548 };
40549 /*
40550 * Selection.js
40551 *
40552 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
40553 *
40554 * This library is free software; you can redistribute it and/or
40555 * modify it under the terms of the GNU Lesser General Public
40556 * License as published by the Free Software Foundation; either
40557 * version 3 of the License, or (at your option) any later version.
40558 *
40559 * This library is distributed in the hope that it will be useful,
40560 * but WITHOUT ANY WARRANTY; without even the implied warranty of
40561 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
40562 * Lesser General Public License for more details.
40563 *
40564 * You should have received a copy of the GNU Lesser General Public
40565 * License along with this library; if not, write to the Free Software
40566 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
40567 * MA 02110-1301 USA
40568 */
40569
40570 /**
40571 * @class Selection
40572 * Selection Class
40573 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
40574 * @release 1.0
40575 * @release date: 2012-07-27
40576 * @version date: 2012-07-27
40577 *
40578 * @param {Array} objects array of selected objects
40579 * @param {Object} widget which belongs to selection
40580 */
40581 function Selection(objects, widget) {
40582
40583 this.objects = objects;
40584 if ( typeof objects == 'undefined') {
40585 this.objects = [];
40586 for (var i = 0; i < GeoTemConfig.datasets.length; i++) {
40587 this.objects.push([]);
40588 }
40589 }
40590 this.widget = widget;
40591
40592 this.getObjects = function(widget) {
40593 if (!this.equal(widget)) {
40594 return this.objects;
40595 }
40596 this.objects = [];
40597 for (var i = 0; i < GeoTemConfig.datasets.length; i++) {
40598 this.objects.push([]);
40599 }
40600 return this.objects;
40601 };
40602
40603 this.equal = function(widget) {
40604 if (this.valid() && this.widget != widget) {
40605 return false;
40606 }
40607 return true;
40608 };
40609
40610 this.valid = function() {
40611 if ( typeof this.widget != 'undefined') {
40612 return true;
40613 }
40614 return false;
40615 };
40616
40617 this.loadAllObjects = function() {
40618 allObjects = [];
40619 $(GeoTemConfig.datasets).each(function(){
40620 var singleDatasetObjects = [];
40621 $(this.objects).each(function(){
40622 singleDatasetObjects.push(this);
40623 });
40624 allObjects.push(singleDatasetObjects);
40625 });
40626 this.objects = allObjects;
40627 };
40628 };
40629
40630 /*
40631 * PlacenameTags.js
40632 *
40633 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
40634 *
40635 * This library is free software; you can redistribute it and/or
40636 * modify it under the terms of the GNU Lesser General Public
40637 * License as published by the Free Software Foundation; either
40638 * version 3 of the License, or (at your option) any later version.
40639 *
40640 * This library is distributed in the hope that it will be useful,
40641 * but WITHOUT ANY WARRANTY; without even the implied warranty of
40642 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
40643 * Lesser General Public License for more details.
40644 *
40645 * You should have received a copy of the GNU Lesser General Public
40646 * License along with this library; if not, write to the Free Software
40647 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
40648 * MA 02110-1301 USA
40649 */
40650
40651 /**
40652 * @class PlacenameTags
40653 * place labels computation for circles
40654 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
40655 * @release 1.0
40656 * @release date: 2012-07-27
40657 * @version date: 2012-07-27
40658 */
40659 function PlacenameTags(circle, map) {
40660
40661 this.circle = circle;
40662 this.map = map;
40663
40664 this.placeLabels
40665 this.selectedLabel
40666
40667 this.allLabel
40668 this.othersLabel
40669 this.unknownLabel
40670
40671 this.calculate = function() {
40672 this.calculateLabels();
40673 this.calculatePlacenameTags();
40674 }
40675
40676 this.calculateLabels = function() {
40677 var elements = this.circle.elements;
40678 var k = this.circle.search;
40679 var weight = 0;
40680 var labels = [];
40681
40682 var levelOfDetail = 0;
40683 if (this.map.options.placenameTagsStyle === 'zoom')
40684 levelOfDetail = this.map.getLevelOfDetail();
40685
40686 if (this.map.options.placenameTagsStyle === 'value'){
40687 //find max level that _all_ elements have a value for
40688 var maxLevel;
40689 for (var i = 0; i < elements.length; i++) {
40690 var level = elements[i].placeDetails[this.map.options.mapIndex].length-1;
40691
40692 if (typeof maxLevel === "undefined")
40693 maxLevel = level;
40694 if (maxLevel > level)
40695 maxLevel = level;
40696 //smallest level anyway, no need to look any further
40697 if (level == 0)
40698 break;
40699 }
40700 //search for highest level where the values differ
40701 for (levelOfDetail = 0; levelOfDetail < maxLevel; levelOfDetail++){
40702 var differenceFound = false;
40703 for (var i = 0; i < (elements.length-1); i++) {
40704 if ( elements[i].getPlace(this.map.options.mapIndex, levelOfDetail) !==
40705 elements[i+1].getPlace(this.map.options.mapIndex, levelOfDetail))
40706 differenceFound = true;
40707 }
40708 if (differenceFound === true)
40709 break;
40710 }
40711 }
40712
40713 for (var i = 0; i < elements.length; i++) {
40714 weight += elements[i].weight;
40715 var found = false;
40716 var label = elements[i].getPlace(this.map.options.mapIndex, levelOfDetail);
40717 if (label == "") {
40718 label = "unknown";
40719 }
40720 for (var j = 0; j < labels.length; j++) {
40721 if (labels[j].place == label) {
40722 labels[j].elements.push(elements[i]);
40723 labels[j].weight += elements[i].weight;
40724 found = true;
40725 break;
40726 }
40727 }
40728 if (!found) {
40729 labels.push({
40730 id : elements[i].name,
40731 place : label,
40732 elements : new Array(elements[i]),
40733 weight : elements[i].weight,
40734 index : k
40735 });
40736 }
40737 }
40738 var sortBySize = function(label1, label2) {
40739 if (label1.weight > label2.weight) {
40740 return -1;
40741 }
40742 return 1;
40743 }
40744 labels.sort(sortBySize);
40745 if (map.options.maxPlaceLabels) {
40746 var ml = map.options.maxPlaceLabels;
40747 if (ml == 1) {
40748 labels = [];
40749 labels.push({
40750 place : "all",
40751 elements : elements,
40752 weight : weight,
40753 index : k
40754 });
40755 }
40756 if (ml == 2) {
40757 ml++;
40758 }
40759 if (ml > 2 && labels.length + 1 > ml) {
40760 var c = [];
40761 var w = 0;
40762 for (var i = ml - 2; i < labels.length; i++) {
40763 c = c.concat(labels[i].elements);
40764 w += labels[i].weight;
40765 }
40766 labels = labels.slice(0, ml - 2);
40767 labels.push({
40768 place : "others",
40769 elements : c,
40770 weight : w,
40771 index : k
40772 });
40773 }
40774 }
40775 if (labels.length > 1) {
40776 labels.push({
40777 place : "all",
40778 elements : elements,
40779 weight : weight,
40780 index : k
40781 });
40782 }
40783 this.placeLabels = labels;
40784 };
40785
40786 this.calculatePlacenameTags = function() {
40787 var cloud = this;
40788 var c = GeoTemConfig.getColor(this.circle.search);
40789 if( map.options.useGraphics ){
40790 c = map.config.getGraphic(this.circle.search).color;
40791 }
40792 var color0 = 'rgb(' + c.r0 + ',' + c.g0 + ',' + c.b0 + ')';
40793 var color1 = 'rgb(' + c.r1 + ',' + c.g1 + ',' + c.b1 + ')';
40794 var allStyles = "", hoverStyle = "", highlightStyle = "", selectedStyle = "", unselectedStyle = "";
40795
40796 if (GeoTemConfig.ie) {
40797 highlightStyle += map.options.ieHighlightLabel.replace(/COLOR1/g, color1).replace(/COLOR0/g, color0) + ";";
40798 hoverStyle += map.options.ieHoveredLabel.replace(/COLOR1/g, color1).replace(/COLOR0/g, color0) + ";";
40799 selectedStyle += map.options.ieSelectedLabel.replace(/COLOR1/g, color1).replace(/COLOR0/g, color0) + ";";
40800 unselectedStyle += map.options.ieUnselectedLabel.replace(/COLOR1/g, color1).replace(/COLOR0/g, color0) + ";";
40801 } else {
40802 highlightStyle += map.options.highlightLabel.replace(/COLOR1/g, color1).replace(/COLOR0/g, color0) + ";";
40803 hoverStyle += map.options.hoveredLabel.replace(/COLOR1/g, color1).replace(/COLOR0/g, color0) + ";";
40804 selectedStyle += map.options.selectedLabel.replace(/COLOR1/g, color1).replace(/COLOR0/g, color0) + ";";
40805 unselectedStyle += map.options.unselectedLabel.replace(/COLOR1/g, color1).replace(/COLOR0/g, color0) + ";";
40806 }
40807
40808 var clickFunction = function(label) {
40809 label.div.onclick = function() {
40810 cloud.changeLabelSelection(label);
40811 }
40812 }
40813 var maxLabelSize = this.count
40814 for (var i = 0; i < this.placeLabels.length; i++) {
40815 var l = this.placeLabels[i];
40816 l.selected = false;
40817 var div = document.createElement("div");
40818 div.setAttribute('class', 'tagCloudItem');
40819 var fontSize = 1 + (l.weight - 1) / this.map.count * map.options.maxLabelIncrease;
40820 if (l.place == "all") {
40821 fontSize = 1;
40822 }
40823 div.style.fontSize = fontSize + "em";
40824 l.allStyle = allStyles + "font-size: " + fontSize + "em;";
40825 l.selectedStyle = selectedStyle;
40826 l.unselectedStyle = unselectedStyle;
40827 l.highlightStyle = highlightStyle;
40828 l.hoverStyle = hoverStyle;
40829 div.innerHTML = l.place + "<span style='font-size:" + (1 / fontSize) + "em'>&nbsp;(" + l.weight + ")</span>";
40830 l.div = div;
40831 clickFunction(l);
40832 }
40833 if (map.options.labelGrid) {
40834 this.showPlacelabels();
40835 } else {
40836 for (var i = 0; i < this.placeLabels.length; i++) {
40837 this.placeLabels[i].div.setAttribute('style', this.placeLabels[i].allStyle + "" + this.placeLabels[i].highlightStyle);
40838 }
40839 }
40840 };
40841
40842 this.selectLabel = function(label) {
40843 if ( typeof label == 'undefined') {
40844 label = this.placeLabels[this.placeLabels.length - 1];
40845 }
40846 if (this.map.popup) {
40847 this.map.popup.showLabelContent(label);
40848 }
40849 this.selectedLabel = label;
40850 this.selectedLabel.div.setAttribute('style', this.selectedLabel.allStyle + "" + this.selectedLabel.selectedStyle);
40851 this.map.mapLabelSelection(label);
40852 };
40853
40854 // changes selection between labels (click, hover)
40855 this.changeLabelSelection = function(label) {
40856 if (this.selectedLabel == label) {
40857 return;
40858 }
40859 if ( typeof this.selectedLabel != 'undefined') {
40860 this.selectedLabel.div.setAttribute('style', this.selectedLabel.allStyle + "" + this.selectedLabel.unselectedStyle);
40861 }
40862 this.selectLabel(label);
40863 };
40864
40865 this.showPlacelabels = function() {
40866 this.leftDiv = document.createElement("div");
40867 this.leftDiv.setAttribute('class', 'tagCloudDiv');
40868 this.map.gui.mapWindow.appendChild(this.leftDiv);
40869 this.rightDiv = document.createElement("div");
40870 this.rightDiv.setAttribute('class', 'tagCloudDiv');
40871 this.map.gui.mapWindow.appendChild(this.rightDiv);
40872 for (var i = 0; i < this.placeLabels.length; i++) {
40873 if (i % 2 == 0) {
40874 this.leftDiv.appendChild(this.placeLabels[i].div);
40875 } else {
40876 this.rightDiv.appendChild(this.placeLabels[i].div);
40877 }
40878 this.placeLabels[i].div.setAttribute('style', this.placeLabels[i].allStyle + "" + this.placeLabels[i].highlightStyle);
40879 }
40880 this.placeTagCloud();
40881 };
40882
40883 this.placeTagCloud = function() {
40884 var lonlat = new OpenLayers.LonLat(this.circle.feature.geometry.x, this.circle.feature.geometry.y);
40885 var pixel = map.openlayersMap.getPixelFromLonLat(lonlat);
40886 var radius = this.circle.feature.style.pointRadius;
40887 var lw = this.leftDiv.offsetWidth;
40888 var rw = this.rightDiv.offsetWidth;
40889 this.leftDiv.style.left = (pixel.x - radius - lw - 5) + "px";
40890 this.rightDiv.style.left = (pixel.x + radius + 5) + "px";
40891 var lh = this.leftDiv.offsetHeight;
40892 var rh = this.rightDiv.offsetHeight;
40893 var lt = pixel.y - lh / 2;
40894 var rt = pixel.y - rh / 2;
40895 this.leftDiv.style.top = lt + "px";
40896 this.rightDiv.style.top = rt + "px";
40897 };
40898
40899 this.remove = function() {
40900 $(this.leftDiv).remove();
40901 $(this.rightDiv).remove();
40902 };
40903
40904 };
40905
40906 function PackPlacenameTags(circle, map) {
40907
40908 this.circle = circle;
40909 this.map = map;
40910
40911 this.placeLabels
40912 this.selectedLabel
40913
40914 this.allLabel
40915 this.othersLabel
40916 this.unknownLabel
40917
40918 this.calculate = function() {
40919 this.calculateLabels();
40920 this.calculatePlacenameTags();
40921 }
40922
40923 this.getLabelList = function(circle) {
40924
40925 var elements = circle.elements;
40926 var k = circle.search;
40927 var weight = 0;
40928 var labels = [];
40929 var levelOfDetail = this.map.getLevelOfDetail();
40930 for (var i = 0; i < elements.length; i++) {
40931 weight += elements[i].weight;
40932 var found = false;
40933 var label = elements[i].getPlace(this.map.options.mapIndex, levelOfDetail);
40934 if (label == "") {
40935 label = "unknown";
40936 }
40937 for (var j = 0; j < labels.length; j++) {
40938 if (labels[j].place == label) {
40939 labels[j].elements.push(elements[i]);
40940 labels[j].weight += elements[i].weight;
40941 found = true;
40942 break;
40943 }
40944 }
40945 if (!found) {
40946 labels.push({
40947 id : elements[i].name,
40948 place : label,
40949 elements : new Array(elements[i]),
40950 weight : elements[i].weight,
40951 index : k
40952 });
40953 }
40954 }
40955 var sortBySize = function(label1, label2) {
40956 if (label1.weight > label2.weight) {
40957 return -1;
40958 }
40959 return 1;
40960 }
40961 labels.sort(sortBySize);
40962 var droppedLabels = [];
40963 if (map.options.maxPlaceLabels) {
40964 var ml = map.options.maxPlaceLabels;
40965 if (ml == 1) {
40966 labels = [];
40967 labels.push({
40968 place : "all",
40969 elements : elements,
40970 weight : weight,
40971 index : k
40972 });
40973 }
40974 if (ml == 2) {
40975 ml++;
40976 }
40977 if (ml > 2 && labels.length + 1 > ml) {
40978 var c = [];
40979 var w = 0;
40980 for (var i = ml - 2; i < labels.length; i++) {
40981 c = c.concat(labels[i].elements);
40982 w += labels[i].weight;
40983 droppedLabels.push(labels[i]);
40984 }
40985 labels = labels.slice(0, ml - 2);
40986 var ol = {
40987 place : "others",
40988 elements : c,
40989 weight : w,
40990 index : k
40991 };
40992 labels.push(ol);
40993 this.othersLabels.push(ol);
40994 }
40995 }
40996 if (labels.length > 1) {
40997 labels.push({
40998 place : "all",
40999 elements : elements,
41000 weight : weight,
41001 index : k
41002 });
41003 }
41004 this.placeLabels.push(labels);
41005 this.droppedLabels.push(droppedLabels);
41006 };
41007
41008 this.calculateLabels = function() {
41009 var circles = this.circle.circles;
41010 this.placeLabels = [];
41011 this.droppedLabels = [];
41012 this.othersLabels = [];
41013 for (var i = 0; i < circles.length; i++) {
41014 this.getLabelList(circles[i]);
41015 }
41016 };
41017
41018 this.calculatePlacenameTags = function() {
41019 var cloud = this;
41020
41021 var unselectedStyles = [];
41022 var selectedStyles = [];
41023 var hoverStyles = [];
41024
41025 for (var k = 0; k < this.placeLabels.length; k++) {
41026 var c = GeoTemConfig.getColor(this.circle.circles[k].search);
41027 if( map.options.useGraphics ){
41028 c = map.config.getGraphic(this.circle.circles[k].search).color;
41029 }
41030 var color0 = 'rgb(' + c.r0 + ',' + c.g0 + ',' + c.b0 + ')';
41031 var color1 = 'rgb(' + c.r1 + ',' + c.g1 + ',' + c.b1 + ')';
41032 var allStyles = "", hoverStyle = "", highlightStyle = "", selectedStyle = "", unselectedStyle = "";
41033
41034 if (GeoTemConfig.ie) {
41035 highlightStyle += map.options.ieHighlightLabel.replace(/COLOR1/g, color1).replace(/COLOR0/g, color0) + ";";
41036 hoverStyle += map.options.ieHoveredLabel.replace(/COLOR1/g, color1).replace(/COLOR0/g, color0) + ";";
41037 selectedStyle += map.options.ieSelectedLabel.replace(/COLOR1/g, color1).replace(/COLOR0/g, color0) + ";";
41038 unselectedStyle += map.options.ieUnselectedLabel.replace(/COLOR1/g, color1).replace(/COLOR0/g, color0) + ";";
41039 } else {
41040 highlightStyle += map.options.highlightLabel.replace(/COLOR1/g, color1).replace(/COLOR0/g, color0) + ";";
41041 hoverStyle += map.options.hoveredLabel.replace(/COLOR1/g, color1).replace(/COLOR0/g, color0) + ";";
41042 selectedStyle += map.options.selectedLabel.replace(/COLOR1/g, color1).replace(/COLOR0/g, color0) + ";";
41043 unselectedStyle += map.options.unselectedLabel.replace(/COLOR1/g, color1).replace(/COLOR0/g, color0) + ";";
41044 }
41045
41046 allStyles += 'margin-right:5px;';
41047 allStyles += 'margin-left:5px;';
41048 unselectedStyles.push(unselectedStyle);
41049 selectedStyles.push(selectedStyle);
41050 hoverStyles.push(hoverStyle);
41051
41052 var clickFunction = function(label, id) {
41053 label.div.onmouseover = function() {
41054 if (!label.opposite) {
41055 var oppositeLabel, oppositeLabelDiv;
41056 label.div.setAttribute('style', allStyles + "" + selectedStyles[id]);
41057 var c = GeoTemConfig.getColor(id);
41058 if( map.options.useGraphics ){
41059 c = map.config.getGraphic(id).color;
41060 }
41061 var color0 = 'rgb(' + c.r0 + ',' + c.g0 + ',' + c.b0 + ')';
41062 if (id == 0) {
41063 for (var i = 0; i < cloud.droppedLabels[1].length; i++) {
41064 if (cloud.droppedLabels[1][i].place == label.place) {
41065 oppositeLabel = cloud.droppedLabels[1][i];
41066 cloud.rightDiv.appendChild(oppositeLabel.div);
41067 cloud.drawLine(cloud.ctxOl, label.div, oppositeLabel.div);
41068 var olDiv = cloud.othersLabels[1].div;
41069 olDiv.innerHTML = olDiv.innerHTML.replace(/\(\d*\)/g, '(' + (cloud.othersLabels[1].weight - oppositeLabel.weight) + ')');
41070 break;
41071 }
41072 }
41073 } else {
41074 for (var i = 0; i < cloud.droppedLabels[0].length; i++) {
41075 if (cloud.droppedLabels[0][i].place == label.place) {
41076 oppositeLabel = cloud.droppedLabels[0][i];
41077 cloud.leftDiv.appendChild(oppositeLabel.div);
41078 cloud.drawLine(cloud.ctxOl, oppositeLabel.div, label.div);
41079 var olDiv = cloud.othersLabels[0].div;
41080 olDiv.innerHTML = olDiv.innerHTML.replace(/\(\d*\)/g, '(' + (cloud.othersLabels[0].weight - oppositeLabel.weight) + ')');
41081 break;
41082 }
41083 }
41084 }
41085 if ( typeof oppositeLabel == 'undefined') {
41086 oppositeLabel = {
41087 div : cloud.naDiv
41088 };
41089 if (id == 0) {
41090 cloud.rightDiv.appendChild(cloud.naDiv);
41091 cloud.drawLine(cloud.ctxOl, label.div, cloud.naDiv);
41092 oppositeLabel.div.setAttribute('style', allStyles + "" + selectedStyles[1]);
41093 } else {
41094 cloud.leftDiv.appendChild(cloud.naDiv);
41095 cloud.drawLine(cloud.ctxOl, cloud.naDiv, label.div);
41096 oppositeLabel.div.setAttribute('style', allStyles + "" + selectedStyles[0]);
41097 }
41098 cloud.map.mapLabelHighlight(label);
41099 } else {
41100 cloud.map.mapLabelHighlight([label, oppositeLabel]);
41101 }
41102 label.div.onmouseout = function() {
41103 label.div.setAttribute('style', allStyles + "" + unselectedStyles[id]);
41104 var olDiv = cloud.othersLabels[0].div;
41105 olDiv.innerHTML = olDiv.innerHTML.replace(/\(\d*\)/g, '(' + cloud.othersLabels[0].weight + ')');
41106 var olDiv2 = cloud.othersLabels[1].div;
41107 olDiv2.innerHTML = olDiv2.innerHTML.replace(/\(\d*\)/g, '(' + cloud.othersLabels[1].weight + ')');
41108 $(oppositeLabel.div).remove();
41109 cloud.ctxOl.clearRect(0, 0, cloud.cvOl.width, cloud.cvOl.height);
41110 cloud.map.mapLabelHighlight();
41111 }
41112 }
41113 }
41114 }
41115 var maxLabelSize = this.count
41116 for (var i = 0; i < this.placeLabels[k].length; i++) {
41117 var l = this.placeLabels[k][i];
41118 l.selected = false;
41119 var div = document.createElement("div");
41120 div.setAttribute('class', 'tagCloudItem');
41121 var fontSize = 1 + (l.weight - 1) / this.map.count * map.options.maxLabelIncrease;
41122 if (l.place == "all") {
41123 fontSize = 1;
41124 }
41125 div.style.fontSize = fontSize + "em";
41126 l.allStyle = allStyles + "font-size: " + fontSize + "em;";
41127 l.selectedStyle = selectedStyle;
41128 l.unselectedStyle = unselectedStyle;
41129 l.hoverStyle = hoverStyle;
41130 div.innerHTML = l.place + "<span style='font-size:" + (1 / fontSize) + "em'>&nbsp;(" + l.weight + ")</span>";
41131 l.div = div;
41132 clickFunction(l, k);
41133 }
41134 for (var i = 0; i < this.droppedLabels[k].length; i++) {
41135 var l = this.droppedLabels[k][i];
41136 l.selected = false;
41137 var div = document.createElement("div");
41138 div.setAttribute('class', 'tagCloudItem');
41139 var fontSize = 1 + (l.weight - 1) / this.map.count * map.options.maxLabelIncrease;
41140 div.style.fontSize = fontSize + "em";
41141 l.allStyle = allStyles + "font-size: " + fontSize + "em;";
41142 l.selectedStyle = selectedStyle;
41143 l.unselectedStyle = unselectedStyle;
41144 l.hoverStyle = hoverStyle;
41145 div.innerHTML = l.place + "<span style='font-size:" + (1 / fontSize) + "em'>&nbsp;(" + l.weight + ")</span>";
41146 l.div = div;
41147 div.setAttribute('style', allStyles + "" + selectedStyle);
41148 }
41149 }
41150
41151 this.naDiv = document.createElement("div");
41152 this.naDiv.setAttribute('class', 'tagCloudItem');
41153 var fontSize = 1;
41154 div.style.fontSize = fontSize + "em";
41155 l.allStyle = allStyles + "font-size: " + fontSize + "em;";
41156 l.selectedStyle = selectedStyle;
41157 l.unselectedStyle = unselectedStyle;
41158 l.hoverStyle = hoverStyle;
41159 this.naDiv.innerHTML = "Not available";
41160 l.div = this.naDiv;
41161
41162 if (map.options.labelGrid) {
41163 this.showPlacelabels();
41164 }
41165 };
41166
41167 this.showPlacelabels = function() {
41168 this.leftDiv = document.createElement("div");
41169 this.leftDiv.setAttribute('class', 'tagCloudDiv');
41170 this.leftDiv.style.textAlign = 'right';
41171 this.map.gui.mapWindow.appendChild(this.leftDiv);
41172 this.centerDiv = document.createElement("div");
41173 this.centerDiv.setAttribute('class', 'tagCloudDiv');
41174 this.centerDiv.style.opacity = 0.7;
41175 this.map.gui.mapWindow.appendChild(this.centerDiv);
41176 this.centerDivOl = document.createElement("div");
41177 this.centerDivOl.setAttribute('class', 'tagCloudDiv');
41178 this.centerDivOl.style.opacity = 0.7;
41179 this.map.gui.mapWindow.appendChild(this.centerDivOl);
41180 this.rightDiv = document.createElement("div");
41181 this.rightDiv.setAttribute('class', 'tagCloudDiv');
41182 this.rightDiv.style.textAlign = 'left';
41183 this.map.gui.mapWindow.appendChild(this.rightDiv);
41184 for (var i = 0; i < this.placeLabels.length; i++) {
41185 for (var j = 0; j < this.placeLabels[i].length; j++) {
41186 if (i == 0) {
41187 this.leftDiv.appendChild(this.placeLabels[i][j].div);
41188 } else {
41189 this.rightDiv.appendChild(this.placeLabels[i][j].div);
41190 }
41191 this.placeLabels[i][j].div.setAttribute('style', this.placeLabels[i][j].allStyle + "" + this.placeLabels[i][j].unselectedStyle);
41192 }
41193 }
41194 this.placeTagCloud();
41195 this.setCanvas();
41196 };
41197
41198 this.placeTagCloud = function() {
41199 var lonlat = new OpenLayers.LonLat(this.circle.feature.geometry.x, this.circle.feature.geometry.y);
41200 var pixel = map.openlayersMap.getPixelFromLonLat(lonlat);
41201 var radius = this.circle.feature.style.pointRadius;
41202 var lw = this.leftDiv.offsetWidth;
41203 var rw = this.rightDiv.offsetWidth;
41204 this.leftDiv.style.left = (pixel.x - radius - lw - 5) + "px";
41205 this.rightDiv.style.left = (pixel.x + radius + 5) + "px";
41206 var lh = this.leftDiv.offsetHeight;
41207 var rh = this.rightDiv.offsetHeight;
41208 var lt = pixel.y - lh / 2;
41209 var rt = pixel.y - rh / 2;
41210 this.leftDiv.style.top = lt + "px";
41211 this.rightDiv.style.top = rt + "px";
41212 };
41213
41214 this.setCanvas = function() {
41215 var height = Math.max(this.leftDiv.offsetHeight, this.rightDiv.offsetHeight);
41216 var top = Math.min(this.leftDiv.offsetTop, this.rightDiv.offsetTop);
41217 var left = this.leftDiv.offsetLeft + this.leftDiv.offsetWidth;
41218 this.width = this.rightDiv.offsetLeft - left;
41219 this.centerDiv.style.left = left + "px";
41220 this.centerDiv.style.top = top + "px";
41221 this.centerDiv.style.height = height + "px";
41222 this.centerDiv.style.width = this.width + "px";
41223
41224 this.centerDivOl.style.left = left + "px";
41225 this.centerDivOl.style.top = top + "px";
41226 this.centerDivOl.style.height = height + "px";
41227 this.centerDivOl.style.width = this.width + "px";
41228
41229 var cv = document.createElement("canvas");
41230 this.centerDiv.appendChild(cv);
41231 if (!cv.getContext && G_vmlCanvasManager) {
41232 cv = G_vmlCanvasManager.initElement(cv);
41233 }
41234 cv.width = this.width;
41235 cv.height = height;
41236 ctx = cv.getContext('2d');
41237
41238 this.cvOl = document.createElement("canvas");
41239 this.centerDivOl.appendChild(this.cvOl);
41240 if (!this.cvOl.getContext && G_vmlCanvasManager) {
41241 this.cvOl = G_vmlCanvasManager.initElement(this.cvOl);
41242 }
41243 this.cvOl.width = this.width;
41244 this.cvOl.height = height + 50;
41245 this.ctxOl = this.cvOl.getContext('2d');
41246
41247 for (var i = 0; i < this.placeLabels[0].length; i++) {
41248 this.placeLabels[0][i].opposite = false;
41249 }
41250 for (var i = 0; i < this.placeLabels[1].length; i++) {
41251 this.placeLabels[1][i].opposite = false;
41252 }
41253 for (var i = 0; i < this.placeLabels[0].length; i++) {
41254 for (var j = 0; j < this.placeLabels[1].length; j++) {
41255 if (this.placeLabels[0][i].place == this.placeLabels[1][j].place) {
41256 this.drawLine(ctx, this.placeLabels[0][i].div, this.placeLabels[1][j].div);
41257 this.placeLabels[0][i].opposite = true;
41258 this.placeLabels[1][j].opposite = true;
41259 }
41260 }
41261 }
41262 }
41263
41264 this.drawLine = function(ctx, label1, label2) {
41265 var x1 = 5;
41266 var x2 = this.width - 5;
41267 var y1 = label1.offsetTop + label1.offsetHeight / 2;
41268 var y2 = label2.offsetTop + label2.offsetHeight / 2;
41269 if (this.leftDiv.offsetTop > this.rightDiv.offsetTop) {
41270 y1 += this.leftDiv.offsetTop - this.rightDiv.offsetTop;
41271 } else {
41272 y2 += this.rightDiv.offsetTop - this.leftDiv.offsetTop;
41273 }
41274 ctx.lineCap = 'round';
41275 ctx.lineWidth = 5;
41276 ctx.beginPath();
41277 ctx.moveTo(x1, y1);
41278 ctx.lineTo(x2, y2);
41279 ctx.strokeStyle = '#555';
41280 ctx.stroke();
41281 }
41282
41283 this.remove = function() {
41284 $(this.leftDiv).remove();
41285 $(this.rightDiv).remove();
41286 $(this.centerDiv).remove();
41287 $(this.centerDivOl).remove();
41288 };
41289
41290 };
41291 /*
41292 * MapConfig.js
41293 *
41294 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
41295 *
41296 * This library is free software; you can redistribute it and/or
41297 * modify it under the terms of the GNU Lesser General Public
41298 * License as published by the Free Software Foundation; either
41299 * version 3 of the License, or (at your option) any later version.
41300 *
41301 * This library is distributed in the hope that it will be useful,
41302 * but WITHOUT ANY WARRANTY; without even the implied warranty of
41303 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
41304 * Lesser General Public License for more details.
41305 *
41306 * You should have received a copy of the GNU Lesser General Public
41307 * License along with this library; if not, write to the Free Software
41308 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
41309 * MA 02110-1301 USA
41310 */
41311
41312 /**
41313 * @class MapConfig
41314 * Map Configuration File
41315 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
41316 * @release 1.0
41317 * @release date: 2012-07-27
41318 * @version date: 2012-07-27
41319 */
41320 function MapConfig(options) {
41321
41322 this.options = {
41323 mapWidth : false, // false or desired width css definition for the map
41324 mapHeight : '580px', // false or desired height css definition for the map
41325 mapTitle : 'GeoTemCo Map View', // title will be shown in map header
41326 mapIndex : 0, // index = position in location array; for multiple locations the 2nd map refers to index 1
41327 alternativeMap : [
41328 {
41329 name: 'Barrington Roman Empire',
41330 url: 'http://pelagios.dme.ait.ac.at/tilesets/imperium/${z}/${x}/${y}.png',
41331 type:'XYZ',
41332 attribution: "(c) Barrington Roman Empiry, <a href='http://pelagios.dme.ait.ac.at/maps/greco-roman/'>Pelagios</a>"
41333 },
41334 {
41335 name: 'Maps-for-Free Relief Map',
41336 url: 'http://maps-for-free.com/layer/relief/z${z}/row${y}/${z}_${x}-${y}.jpg',
41337 type:'XYZ',
41338 attribution: "(c) <a href='http://www.maps-for-free.com/html/about.html'>Maps for Free</a>"
41339 },
41340 {
41341 name: 'Contemporary Map (2010)',
41342 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41343 layer: 'historic:cntry2010',
41344 attribution: "(c) <a href='http://epp.eurostat.ec.europa.eu/portal/page/portal/gisco_Geographical_information_maps/popups/references/administrative_units_statistical_units_1'>EuroStat</a>"
41345 },
41346 {
41347 name: 'Historical Map of 2006',
41348 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41349 layer: 'historic:cntry2006',
41350 attribution: "(c) <a href='http://epp.eurostat.ec.europa.eu/portal/page/portal/gisco_Geographical_information_maps/popups/references/administrative_units_statistical_units_1'>EuroStat</a>"
41351 },
41352 {
41353 name: 'Historical Map of 1994',
41354 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41355 layer: 'historic:cntry1994',
41356 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41357 },
41358 {
41359 name: 'Historical Map of 1945',
41360 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41361 layer: 'historic:cntry1945',
41362 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41363 },
41364 {
41365 name: 'Historical Map of 1938',
41366 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41367 layer: 'historic:cntry1938',
41368 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41369 },
41370 {
41371 name: 'Historical Map of 1920',
41372 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41373 layer: 'historic:cntry1920',
41374 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41375 },
41376 {
41377 name: 'Historical Map of 1914',
41378 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41379 layer: 'historic:cntry1914',
41380 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41381 },
41382 {
41383 name: 'Historical Map of 1880',
41384 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41385 layer: 'historic:cntry1880',
41386 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41387 },
41388 {
41389 name: 'Historical Map of 1815',
41390 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41391 layer: 'historic:cntry1815',
41392 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41393 },
41394 {
41395 name: 'Historical Map of 1783',
41396 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41397 layer: 'historic:cntry1783',
41398 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41399 },
41400 {
41401 name: 'Historical Map of 1715',
41402 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41403 layer: 'historic:cntry1715',
41404 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41405 },
41406 {
41407 name: 'Historical Map of 1650',
41408 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41409 layer: 'historic:cntry1650',
41410 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41411 },
41412 {
41413 name: 'Historical Map of 1530',
41414 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41415 layer: 'historic:cntry1530',
41416 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41417 },
41418 {
41419 name: 'Historical Map of 1492',
41420 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41421 layer: 'historic:cntry1492',
41422 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41423 },
41424 {
41425 name: 'Historical Map of 1279',
41426 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41427 layer: 'historic:cntry1279',
41428 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41429 },
41430 {
41431 name: 'Historical Map of 1000',
41432 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41433 layer: 'historic:cntry1000',
41434 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41435 },
41436 {
41437 name: 'Historical Map of 800',
41438 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41439 layer: 'historic:cntry800',
41440 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41441 },
41442 {
41443 name: 'Historical Map of 600',
41444 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41445 layer: 'historic:cntry600',
41446 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41447 },
41448 {
41449 name: 'Historical Map of 400',
41450 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41451 layer: 'historic:cntry400',
41452 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41453 },
41454 {
41455 name: 'Historical Map of 1 BC',
41456 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41457 layer: 'historic:cntry1bc',
41458 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41459 },
41460 {
41461 name: 'Historical Map of 200 BC',
41462 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41463 layer: 'historic:cntry200bc',
41464 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41465 },
41466 {
41467 name: 'Historical Map of 323 BC',
41468 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41469 layer: 'historic:cntry323bc',
41470 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41471 },
41472 {
41473 name: 'Historical Map of 500 BC',
41474 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41475 layer: 'historic:cntry500bc',
41476 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41477 },
41478 {
41479 name: 'Historical Map of 1000 BC',
41480 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41481 layer: 'historic:cntry1000bc',
41482 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41483 },
41484 {
41485 name: 'Historical Map of 2000 BC',
41486 url: 'http://geoserver.mpiwg-berlin.mpg.de/geoserver/mpiwg/wms',
41487 layer: 'historic:cntry2000bc',
41488 attribution: "(c) <a href='http://webcache.googleusercontent.com/search?q=cache:NbaEeiehhzQJ:library.thinkquest.org/C006628/citations.html&client=ubuntu&hl=de&gl=de&strip=1'> ThinkQuest Team C006628</a>"
41489 },
41490 ],
41491 legend : true, // if a legend at the bottom of the map should be shown or not
41492 mapMerge : false, // if the elements of distinct datasets should be merged into one set or not
41493 useGraphics : false, // if different graphics should represent different datasets or not
41494 graphics : [
41495 {
41496 shape: "circle",
41497 rotation: 0
41498 },
41499 {
41500 shape: "square",
41501 rotation: 0
41502 },
41503 {
41504 shape: "triangle",
41505 rotation: 0
41506 },
41507 {
41508 shape: "square",
41509 rotation: 45
41510 }
41511 ],
41512 googleMaps : false, // enable/disable Google maps (actually, no Google Maps API key is required)
41513 bingMaps : false, // enable/disable Bing maps (you need to set the Bing Maps API key below)
41514 bingApiKey : 'none', // bing maps api key, see informations at http://bingmapsportal.com/
41515 osmMaps : true, // enable/disable OSM maps
41516 osmMapsMapQuest : true, // enable/disable OSM maps with MapQuest tiles
41517 baseLayer : 'Open Street Map', // initial layer to show (e.g. 'Google Streets')
41518 resetMap : true, // show/hide map reset button
41519 countrySelect : true, // show/hide map country selection control button
41520 polygonSelect : true, // show/hide map polygon selection control button
41521 circleSelect : true, // show/hide map circle selection control button
41522 squareSelect : true, // show/hide map square selection control button
41523 multiSelection : true, // true, if multiple polygons or multiple circles should be selectable
41524 popups : true, // enabled popups will show popup windows for circles on the map
41525 olNavigation : false, // show/hide OpenLayers navigation panel
41526 olLayerSwitcher : false, // show/hide OpenLayers layer switcher
41527 olMapOverview : false, // show/hide OpenLayers map overview
41528 olKeyboardDefaults : true, // (de)activate Openlayers keyboard defaults
41529 olScaleLine : false, // (de)activate Openlayers keyboard defaults
41530 geoLocation : true, // show/hide GeoLocation feature
41531 boundaries : {
41532 minLon : -29,
41533 minLat : 35,
41534 maxLon : 44,
41535 maxLat : 67
41536 }, // initial map boundaries or 'false' for no boundaries
41537 mapBackground : '#bbd0ed',
41538 labelGrid : true, // show label grid on hover
41539 maxPlaceLabels : 6, // Integer value for fixed number of place labels: 0 --> unlimited, 1 --> 1 label (won't be shown in popup, 2 --> is not possible because of others & all labels --> 3 labels, [3,...,N] --> [3,...,N] place labels)
41540 selectDefault : true, // true, if strongest label should be selected as default
41541 maxLabelIncrease : 2, // maximum increase (in em) for the font size of a label
41542 labelHover : false, // true, to update on label hover
41543 ieHighlightLabel : "color: COLOR1; background-color: COLOR0; filter:'progid:DXImageTransform.Microsoft.Alpha(Opacity=80)';-ms-filter:'progid:DXImageTransform.Microsoft.Alpha(Opacity=80)';", // css code for a highlighted place label in IE
41544 highlightLabel : "color: COLOR0; text-shadow: 0 0 0.4em black, 0 0 0.4em black, 0 0 0.4em black, 0 0 0.4em COLOR0;", // css code for a highlighted place label
41545 ieSelectedLabel : "color: COLOR1; font-weight: bold;", // css code for a selected place label in IE
41546 selectedLabel : "color: COLOR1; font-weight: bold;", // css code for a selected place label
41547 ieUnselectedLabel : "color: COLOR1; font-weight: normal;", // css code for an unselected place label in IE
41548 unselectedLabel : "color: COLOR1; font-weight: normal;", // css code for an unselected place label
41549 ieHoveredLabel : "color: COLOR1; font-weight: bold;", // css code for a hovered place label in IE
41550 hoveredLabel : "color: COLOR1; font-weight: bold;", // css code for a hovered place label
41551 circleGap : 0, // gap between the circles on the map (>=0)
41552 circleOverlap : {
41553 type: 'area', // 'area' or 'diameter' is possible
41554 overlap: 0 // the percentage of allowed overlap (0<=overlap<=1)
41555 }, // maximum allowed overlap in percent (if circleGap = 0, circleOverlap will be used)
41556 minimumRadius : 4, // minimum radius of a circle with mimimal weight (>0)
41557 circleOutline : 2, // false for no outline or a pixel value v with 0 < v
41558 circleOpacity : 'balloon', // 'balloon' for dynamic opacity of the circles or a value t with 0 <= t <= 1
41559 minTransparency : 0.55, // maximum transparency of a circle
41560 maxTransparency : 0.8, // minimum transparency of a circle
41561 binning : 'generic', // binning algorithm for the map, possible values are: 'generic', 'square', 'hexagonal', 'triangular' or false for 'no binning'
41562 noBinningRadii : 'dynamic', // for 'no binning': 'static' for only minimum radii, 'dynamic' for increasing radii for increasing weights
41563 circlePackings : true, // if circles of multiple result sets should be displayed in circle packs, if a binning is performed
41564 binCount : 10, // number of bins for x and y dimension for lowest zoom level
41565 showDescriptions : true, // true to show descriptions of data items (must be provided by kml/json), false if not
41566 mapSelection : true, // show/hide select map dropdown
41567 binningSelection : false, // show/hide binning algorithms dropdown
41568 mapSelectionTools : true, // show/hide map selector tools
41569 dataInformation : true, // show/hide data information
41570 overlayVisibility : false, // initial visibility of additional overlays
41571 //proxyHost : 'php/proxy.php?address=', //required for selectCountry feature, if the requested GeoServer and GeoTemCo are NOT on the same server
41572 placenameTagsStyle : 'value', // the style of the placenames "surrounding" a circle on hover. 'zoom' for tags based on zoom level (old behaviour), 'value' for new value-based
41573 hideUnselected : false //hide unselected circles (features) on highlight/selection
41574
41575 };
41576 if ( typeof options != 'undefined') {
41577 $.extend(this.options, options);
41578 }
41579
41580 //if the user can change shape/color graphics have to be used
41581 //but this will use circles as default shape
41582 if (GeoTemConfig.allowUserShapeAndColorChange){
41583 this.options.useGraphics = true;
41584 }
41585
41586 };
41587
41588 MapConfig.prototype.getGraphic = function(id){
41589 var dataset = GeoTemConfig.datasets[id];
41590
41591 var graphic;
41592 if (typeof dataset.graphic !== "undefined"){
41593 graphic = dataset.graphic;
41594 } else{
41595 graphic = this.options.graphics[id % this.options.graphics.length];
41596 }
41597
41598 var color;
41599 if (typeof dataset.color !== "undefined"){
41600 color = dataset.color;
41601 } else{
41602 color = GeoTemConfig.getColor(id);
41603 }
41604 return {
41605 shape: graphic.shape,
41606 rotation: graphic.rotation,
41607 color: color
41608 };
41609 };
41610 /*
41611 * MapGui.js
41612 *
41613 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
41614 *
41615 * This library is free software; you can redistribute it and/or
41616 * modify it under the terms of the GNU Lesser General Public
41617 * License as published by the Free Software Foundation; either
41618 * version 3 of the License, or (at your option) any later version.
41619 *
41620 * This library is distributed in the hope that it will be useful,
41621 * but WITHOUT ANY WARRANTY; without even the implied warranty of
41622 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
41623 * Lesser General Public License for more details.
41624 *
41625 * You should have received a copy of the GNU Lesser General Public
41626 * License along with this library; if not, write to the Free Software
41627 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
41628 * MA 02110-1301 USA
41629 */
41630
41631 /**
41632 * @class MapGui
41633 * Map GUI Implementation
41634 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
41635 * @release 1.0
41636 * @release date: 2012-07-27
41637 * @version date: 2012-07-27
41638 *
41639 * @param {MapWidget} parent map widget object
41640 * @param {HTML object} div parent div to append the map gui
41641 * @param {JSON} options map configuration
41642 */
41643 function MapGui(map, div, options, iid) {
41644
41645 this.map = map;
41646
41647 this.container = div;
41648 if (options.mapWidth) {
41649 this.container.style.width = options.mapWidth;
41650 }
41651 if (options.mapHeight) {
41652 this.container.style.height = options.mapHeight;
41653 }
41654 this.container.style.position = 'relative';
41655
41656 this.mapWindow = document.createElement("div");
41657 this.mapWindow.setAttribute('class', 'mapWindow');
41658 this.mapWindow.id = "mapWindow"+iid;
41659 this.mapWindow.style.background = options.mapBackground;
41660 this.container.appendChild(this.mapWindow);
41661
41662 this.mapContainer = document.createElement("div");
41663 this.mapContainer.setAttribute('class', 'mapContainer');
41664 this.mapContainer.id = "mapContainer"+iid;
41665 this.mapContainer.style.position = "absolute";
41666 this.mapContainer.style.zIndex = 0;
41667 this.mapWindow.appendChild(this.mapContainer);
41668
41669 var toolbarTable = document.createElement("table");
41670 toolbarTable.setAttribute('class', 'absoluteToolbar ddbToolbar');
41671 this.container.appendChild(toolbarTable);
41672 this.mapToolbar = toolbarTable;
41673
41674 var titles = document.createElement("tr");
41675 toolbarTable.appendChild(titles);
41676 var tools = document.createElement("tr");
41677 toolbarTable.appendChild(tools);
41678
41679 if (options.mapSelection) {
41680 this.mapTypeTitle = document.createElement("td");
41681 titles.appendChild(this.mapTypeTitle);
41682 this.mapTypeTitle.innerHTML = GeoTemConfig.getString('mapType');
41683 this.mapTypeSelector = document.createElement("td");
41684 tools.appendChild(this.mapTypeSelector);
41685 }
41686
41687 if (options.mapSelectionTools) {
41688 this.mapSelectorTitle = document.createElement("td");
41689 titles.appendChild(this.mapSelectorTitle);
41690 this.mapSelectorTitle.innerHTML = GeoTemConfig.getString('mapSelectorTools');
41691 var mapSelectorTools = document.createElement("td");
41692 var selectorTools = this.map.initSelectorTools();
41693 for (var i in selectorTools ) {
41694 mapSelectorTools.appendChild(selectorTools[i].button);
41695 }
41696 tools.appendChild(mapSelectorTools);
41697 }
41698
41699 if (options.binningSelection) {
41700 this.binningTitle = document.createElement("td");
41701 titles.appendChild(this.binningTitle);
41702 this.binningTitle.innerHTML = GeoTemConfig.getString('binningType');
41703 this.binningSelector = document.createElement("td");
41704 tools.appendChild(this.binningSelector);
41705 }
41706
41707 if (GeoTemConfig.allowFilter) {
41708 this.filterTitle = document.createElement("td");
41709 titles.appendChild(this.filterTitle);
41710 this.filterTitle.innerHTML = GeoTemConfig.getString('filter');
41711 this.filterOptions = document.createElement("td");
41712 tools.appendChild(this.filterOptions);
41713 }
41714
41715 if (options.dataInformation) {
41716 this.infoTitle = document.createElement("td");
41717 this.infoTitle.innerHTML = options.mapTitle;
41718 titles.appendChild(this.infoTitle);
41719 var mapSum = document.createElement("td");
41720 this.mapElements = document.createElement("div");
41721 this.mapElements.setAttribute('class', 'ddbElementsCount');
41722 mapSum.appendChild(this.mapElements);
41723 tools.appendChild(mapSum);
41724 }
41725
41726 this.lockTitle = document.createElement("td");
41727 titles.appendChild(this.lockTitle);
41728 this.lockIcon = document.createElement("td");
41729 var lockButton = document.createElement("div");
41730 $(lockButton).addClass('mapControl');
41731 var activateLock = function() {
41732 map.navigation.deactivate();
41733 }
41734 var deactivateLock = function() {
41735 map.navigation.activate();
41736 }
41737 var lockMapControl = new MapControl(this.map, lockButton, 'lock', activateLock, deactivateLock);
41738 tools.appendChild(lockMapControl.button);
41739
41740
41741 var gui = this;
41742 if (navigator.geolocation && options.geoLocation) {
41743 this.geoActive = false;
41744 this.geoLocation = document.createElement("div");
41745 this.geoLocation.setAttribute('class', 'geoLocationOff');
41746 this.geoLocation.title = GeoTemConfig.getString('activateGeoLocation');
41747 this.container.appendChild(this.geoLocation);
41748 this.geoLocation.style.left = "20px";
41749 this.geoLocation.onclick = function() {
41750 var changeStyle = function() {
41751 if (gui.geoActive) {
41752 gui.geoLocation.setAttribute('class', 'geoLocationOn');
41753 gui.geoLocation.title = GeoTemConfig.getString(GeoTemConfig.language, 'deactivateGeoLocation');
41754 } else {
41755 gui.geoLocation.setAttribute('class', 'geoLocationOff');
41756 gui.geoLocation.title = GeoTemConfig.getString(GeoTemConfig.language, 'activateGeoLocation');
41757 }
41758 }
41759 if (!gui.geoActive) {
41760 if ( typeof gui.longitude == 'undefined') {
41761 navigator.geolocation.getCurrentPosition(function(position) {
41762 gui.longitude = position.coords.longitude;
41763 gui.latitude = position.coords.latitude;
41764 gui.map.setMarker(gui.longitude, gui.latitude);
41765 gui.geoActive = true;
41766 changeStyle();
41767 }, function(msg) {
41768 console.log( typeof msg == 'string' ? msg : "error");
41769 });
41770 } else {
41771 gui.map.setMarker(gui.longitude, gui.latitude);
41772 gui.geoActive = true;
41773 changeStyle();
41774 }
41775 } else {
41776 gui.map.removeMarker();
41777 gui.geoActive = false;
41778 changeStyle();
41779 }
41780 }
41781 }
41782
41783 if (!options.olNavigation) {
41784 this.map.zoomSlider = new MapZoomSlider(this.map, "vertical");
41785 this.container.appendChild(this.map.zoomSlider.div);
41786 this.map.zoomSlider.div.style.left = "20px";
41787 }
41788
41789 if (options.resetMap) {
41790 this.homeButton = document.createElement("div");
41791 this.homeButton.setAttribute('class', 'mapHome');
41792 this.homeButton.title = GeoTemConfig.getString('home');
41793 this.container.appendChild(this.homeButton);
41794 this.homeButton.style.left = "20px";
41795 this.homeButton.onclick = function() {
41796 if (map.mds.getAllObjects() == null){
41797 map.openlayersMap.setCenter(new OpenLayers.LonLat(0, 0));
41798 map.openlayersMap.zoomTo(0);
41799 }
41800 gui.map.drawObjectLayer(true);
41801 }
41802 }
41803
41804 if (options.legend) {
41805 this.legendDiv = document.createElement("div");
41806 this.legendDiv.setAttribute('class', 'mapLegend');
41807 this.mapWindow.appendChild(this.legendDiv);
41808 }
41809
41810 var linkForOsm = 'http://www.openstreetmap.org/';
41811 var linkForLicense = 'http://creativecommons.org/licenses/by-sa/2.0/';
41812 this.osmLink = document.createElement("div");
41813 this.osmLink.setAttribute('class', 'osmLink');
41814 this.osmLink.innerHTML = '(c) <a href=' + linkForOsm + '>OpenStreetMap contributors</a>, <a href=' + linkForLicense + '>CC-BY-SA</a>';
41815 this.mapWindow.appendChild(this.osmLink);
41816 this.osmMapQuestLink = document.createElement("div");
41817 this.osmMapQuestLink.setAttribute('class', 'osmLink');
41818 this.osmMapQuestLink.innerHTML = '(c) Data, imagery and map information provided by MapQuest <a href="http://www.mapquest.com/" target="_blank">MapQuest</a> <img src="http://developer.mapquest.com/content/osm/mq_logo.png"> <a href=' + linkForOsm + '>OpenStreetMap contributors</a>, <a href=' + linkForLicense + '>CC-BY-SA</a>';
41819 this.mapWindow.appendChild(this.osmMapQuestLink);
41820
41821 // var tooltip = document.createElement("div");
41822 // tooltip.setAttribute('class','ddbTooltip');
41823 // toolbarTable.appendChild(tooltip);
41824
41825 // var tooltip = document.createElement("div");
41826 // tooltip.setAttribute('class','ddbTooltip');
41827 // toolbarTable.appendChild(tooltip);
41828 //
41829 // tooltip.onmouseover = function(){
41830 // /*
41831 // Publisher.Publish('TooltipContent', {
41832 // content: GeoTemConfig.getString(GeoTemConfig.language,'timeHelp'),
41833 // target: $(tooltip)
41834 // });
41835 // */
41836 // }
41837 // tooltip.onmouseout = function(){
41838 // // Publisher.Publish('TooltipContent');
41839 // }
41840 // //vhz tooltip on click should open a help file if defined in GeoTemConfig
41841 // if(GeoTemConfig.helpURL) {
41842 // tooltip.onclick = function () {
41843 //
41844 // }
41845 // }
41846
41847 // }
41848 // tooltip.onmouseout = function(){
41849 // Publisher.Publish('TooltipContent');
41850 // }
41851
41852 this.resize = function() {
41853 var w = this.container.offsetWidth;
41854 var h = this.container.offsetHeight;
41855 // this.mapWindow.style.width = w + "px";
41856 this.mapWindow.style.height = h + "px";
41857 // this.mapContainer.style.width = w + "px";
41858 this.mapContainer.style.height = h + "px";
41859 var top = toolbarTable.offsetHeight + 20;
41860 if (options.olLayerSwitcher) {
41861 var switcherDiv = $('.olControlLayerSwitcher')[0];
41862 $(switcherDiv).css('top', top + "px");
41863 }
41864 if ( typeof this.geoLocation != "undefined") {
41865 this.geoLocation.style.top = top + "px";
41866 top += this.geoLocation.offsetHeight + 4;
41867 }
41868 if (options.olNavigation) {
41869 var panZoomBar = $('.olControlPanZoom')[0];
41870 $(panZoomBar).css('top', top + 'px');
41871 $(panZoomBar).css('left', '12px');
41872 var zoomOut = document.getElementById('OpenLayers.Control.PanZoom_23_zoomout');
41873 top += $(zoomOut).height() + $(zoomOut).position().top + 4;
41874 } else {
41875 this.map.zoomSlider.div.style.top = top + "px";
41876 top += this.map.zoomSlider.div.offsetHeight + 2;
41877 }
41878 if (options.resetMap) {
41879 this.homeButton.style.top = top + "px";
41880 }
41881 this.headerHeight = toolbarTable.offsetHeight;
41882 this.headerWidth = toolbarTable.offsetWidth;
41883 this.map.openlayersMap.updateSize();
41884 this.map.drawObjectLayer(true);
41885 };
41886
41887 this.updateLegend = function(datasets){
41888 $(this.legendDiv).empty();
41889 var table = $('<table style="margin:10px"/>').appendTo(this.legendDiv);
41890 for( var i=0; i<datasets.length; i++ ){
41891 var row = $('<tr/>').appendTo(table);
41892 if( options.useGraphics ){
41893 var graphic = map.config.getGraphic(i);
41894 var fill = 'rgb(' + graphic.color.r0 + ',' + graphic.color.g0 + ',' + graphic.color.b0 + ')';
41895 var stroke = 'rgb(' + graphic.color.r1 + ',' + graphic.color.g1 + ',' + graphic.color.b1 + ')';
41896 var rot = graphic.rotation;
41897 var svg;
41898 if( graphic.shape == 'circle' ){
41899 svg = '<svg style="width:20px;height:20px;"><circle cx="10" cy="10" r="7" stroke="'+stroke+'" stroke-width="2" fill="'+fill+'"/></svg>';
41900 }
41901 else if( graphic.shape == 'square' ){
41902 svg = '<svg style="width:20px;height:20px;"><polygon points="4,4 16,4 16,16 4,16" style="fill:'+fill+';stroke:'+stroke+';stroke-width:2" transform="rotate('+rot+' 10,10)"/></svg>';
41903 }
41904 else if( graphic.shape == 'triangle' ){
41905 svg = '<svg style="width:20px;height:20px;"><polygon points="3,17 17,17 10,5" style="fill:'+fill+';stroke:'+stroke+';stroke-width:2" transform="rotate('+rot+' 10,10)"/></svg>';
41906 }
41907 $('<td>'+svg+'</td>').appendTo(row);
41908 }
41909 else {
41910 var c = GeoTemConfig.getColor(i);
41911 var fill = 'rgb(' + c.r0 + ',' + c.g0 + ',' + c.b0 + ')';
41912 var stroke = 'rgb(' + c.r1 + ',' + c.g1 + ',' + c.b1 + ')';
41913 var svg = '<svg style="width:20px;height:20px;"><circle cx="10" cy="10" r="7" stroke="'+stroke+'" stroke-width="2" fill="'+fill+'"/></svg>';
41914 $('<td>'+svg+'</td>').appendTo(row);
41915 }
41916 $('<td>'+datasets[i].label+'</td>').appendTo(row);
41917 }
41918 };
41919
41920 this.updateSpaceQuantity = function(count) {
41921 if (!options.dataInformation) {
41922 return;
41923 }
41924 this.mapCount = count;
41925 if (count != 1) {
41926 this.mapElements.innerHTML = this.beautifyCount(count) + " " + GeoTemConfig.getString('results');
41927 } else {
41928 this.mapElements.innerHTML = this.beautifyCount(count) + " " + GeoTemConfig.getString('result');
41929 }
41930 }
41931
41932 this.setMapsDropdown = function() {
41933 if (!options.mapSelection) {
41934 return;
41935 }
41936 $(this.mapTypeSelector).empty();
41937 var maps = [];
41938 var gui = this;
41939 var addMap = function(name, index) {
41940 var setMap = function() {
41941 gui.map.setMap(index);
41942 }
41943 maps.push({
41944 name : name,
41945 onclick : setMap
41946 });
41947 }
41948 for (var i = 0; i < this.map.baseLayers.length; i++) {
41949 addMap(this.map.baseLayers[i].name, i);
41950 }
41951 this.mapTypeDropdown = new Dropdown(this.mapTypeSelector, maps, GeoTemConfig.getString('selectMapType'));
41952 }
41953
41954 this.setMap = function() {
41955 if (options.mapSelection) {
41956 this.mapTypeDropdown.setEntry(this.map.baselayerIndex);
41957 }
41958 }
41959
41960 this.setBinningDropdown = function() {
41961 if (!options.binningSelection) {
41962 return;
41963 }
41964 $(this.binningSelector).empty();
41965 var binnings = [];
41966 var gui = this;
41967 var index = 0;
41968 var entry;
41969 var addBinning = function(name, id) {
41970 if (options.binning == id) {
41971 entry = index;
41972 } else {
41973 index++;
41974 }
41975 var setBinning = function() {
41976 options.binning = id;
41977 gui.map.initWidget(gui.map.datasets, false);
41978 gui.map.riseLayer();
41979 }
41980 binnings.push({
41981 name : name,
41982 onclick : setBinning
41983 });
41984 }
41985 addBinning(GeoTemConfig.getString('genericBinning'), 'generic');
41986 addBinning(GeoTemConfig.getString('squareBinning'), 'square');
41987 addBinning(GeoTemConfig.getString('hexagonalBinning'), 'hexagonal');
41988 addBinning(GeoTemConfig.getString('triangularBinning'), 'triangular');
41989 addBinning(GeoTemConfig.getString('noBinning'), false);
41990 var binningDropdown = new Dropdown(this.binningSelector, binnings, GeoTemConfig.getString('binningTooltip'));
41991 binningDropdown.setEntry(entry);
41992 }
41993 this.setBinningDropdown();
41994
41995 this.beautifyCount = function(count) {
41996 var c = count + '';
41997 var p = 0;
41998 var l = c.length;
41999 while (l - p > 3) {
42000 p += 3;
42001 c = c.substring(0, l - p) + "." + c.substring(l - p);
42002 p++;
42003 l++;
42004 }
42005 return c;
42006 }
42007
42008 };
42009 /*
42010 * MapWidget.js
42011 *
42012 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
42013 *
42014 * This library is free software; you can redistribute it and/or
42015 * modify it under the terms of the GNU Lesser General Public
42016 * License as published by the Free Software Foundation; either
42017 * version 3 of the License, or (at your option) any later version.
42018 *
42019 * This library is distributed in the hope that it will be useful,
42020 * but WITHOUT ANY WARRANTY; without even the implied warranty of
42021 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
42022 * Lesser General Public License for more details.
42023 *
42024 * You should have received a copy of the GNU Lesser General Public
42025 * License along with this library; if not, write to the Free Software
42026 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
42027 * MA 02110-1301 USA
42028 */
42029
42030 /**
42031 * @class MapWidget
42032 * MapWidget Implementation
42033 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
42034 * @release 1.0
42035 * @release date: 2012-07-27
42036 * @version date: 2012-07-27
42037 *
42038 * @param {MapWrapper} core wrapper for interaction to other widgets
42039 * @param {HTML object} div parent div to append the map widget div
42040 * @param {JSON} options user specified configuration that overwrites options in MapConfig.js
42041 */
42042 MapWidget = function(core, div, options) {
42043
42044 this.core = core;
42045 this.core.setWidget(this);
42046 this.openlayersMap
42047 this.baseLayers
42048 this.objectLayer
42049
42050 this.drawPolygon
42051 this.drawCircle
42052 this.selectCountry
42053 this.dragArea
42054 this.selectFeature
42055 this.navigation
42056
42057 this.div = div;
42058
42059 this.iid = GeoTemConfig.getIndependentId('map');
42060 this.config = new MapConfig(options);
42061 this.options = this.config.options;
42062 this.formerCP = this.options.circlePackings;
42063 this.gui = new MapGui(this, this.div, this.options, this.iid);
42064
42065 this.initialize();
42066
42067 }
42068
42069 MapWidget.prototype = {
42070
42071 /**
42072 * initializes the map for the Spatio Temporal Interface.
42073 * it includes setting up all layers of the map and defines all map specific interaction possibilities
42074 */
42075 initialize : function() {
42076
42077 var map = this;
42078
42079 //OpenLayers.ProxyHost = "/cgi-bin/proxy.cgi?url=";
42080 if (map.options.proxyHost) {
42081 OpenLayers.ProxyHost = map.options.proxyHost;
42082 }
42083
42084 this.polygons = [];
42085 this.connections = [];
42086 this.selection = new Selection();
42087 this.wmsOverlays = [];
42088
42089 this.layerZIndex = 1;
42090 this.zIndices = [];
42091
42092 var activateDrag = function() {
42093 map.dragArea.activate();
42094 }
42095 var deactivateDrag = function() {
42096 map.dragArea.deactivate();
42097 }
42098 this.dragControl = new MapControl(this, null, 'drag', activateDrag, deactivateDrag);
42099
42100 /*
42101 this.editPolygon = document.createElement("div");
42102 this.editPolygon.title = GeoTemConfig.getString('editPolygon');
42103 this.editPolygon.setAttribute('class','editMapPolygon');
42104 this.toolbar.appendChild(this.editPolygon);
42105 this.drag.onclick = function(evt){
42106 if( map.activeControl == "drag" ){
42107 map.deactivate("drag");
42108 if( GeoTemConfig.navigate ){
42109 map.activate("navigate");
42110 }
42111 }
42112 else {
42113 map.deactivate(map.activControl);
42114 map.activate("drag");
42115 }
42116 }
42117 map.addEditingMode(new OpenLayers.Control.EditingMode.PointArraySnapping());
42118 */
42119
42120 this.filterBar = new FilterBar(this, this.gui.filterOptions);
42121
42122 this.objectLayer = new OpenLayers.Layer.Vector("Data Objects", {
42123 projection : "EPSG:4326",
42124 'displayInLayerSwitcher' : false,
42125 rendererOptions : {
42126 zIndexing : true
42127 }
42128 });
42129
42130 this.markerLayer = new OpenLayers.Layer.Markers("Markers");
42131
42132 this.navigation = new OpenLayers.Control.Navigation({
42133 zoomWheelEnabled : GeoTemConfig.mouseWheelZoom
42134 });
42135 this.navigation.defaultDblClick = function(evt) {
42136 var newCenter = this.map.getLonLatFromViewPortPx(evt.xy);
42137 this.map.setCenter(newCenter, this.map.zoom + 1);
42138 map.drawObjectLayer(false);
42139 if (map.zoomSlider) {
42140 map.zoomSlider.setValue(map.getZoom());
42141 }
42142 }
42143 this.navigation.wheelUp = function(evt) {
42144 this.wheelChange(evt, 1);
42145 }
42146 this.navigation.wheelDown = function(evt) {
42147 this.wheelChange(evt, -1);
42148 }
42149
42150 this.resolutions = [78271.516953125, 39135.7584765625, 19567.87923828125, 9783.939619140625, 4891.9698095703125, 2445.9849047851562, 1222.9924523925781, 611.4962261962891, 305.74811309814453, 152.87405654907226, 76.43702827453613, 38.218514137268066, 19.109257068634033, 9.554628534317017, 4.777314267158508, 2.388657133579254, 1.194328566789627, 0.5971642833948135, 0.29858214169740677];
42151
42152 var options = {
42153 controls : [this.navigation],
42154 projection : new OpenLayers.Projection("EPSG:900913"),
42155 displayProjection : new OpenLayers.Projection("EPSG:4326"),
42156 resolutions : this.resolutions,
42157 units : 'meters',
42158 maxExtent : new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34)
42159 };
42160 this.openlayersMap = new OpenLayers.Map("mapContainer"+this.iid, options);
42161 if (map.options.navigate) {
42162 this.activeControl = "navigate";
42163 }
42164 //add attribution control
42165 this.openlayersMap.addControl(new OpenLayers.Control.Attribution());
42166 this.mds = new MapDataSource(this, this.options);
42167
42168 //on zoomend, redraw objects and set slider (if it exists) accordingly (zoom by mouse wheel)
42169 this.openlayersMap.events.register("zoomend", map, function(){
42170 map.drawObjectLayer(false);
42171 if (map.zoomSlider) {
42172 map.zoomSlider.setValue(map.getZoom());
42173 }
42174 map.core.triggerHighlight([]);
42175 });
42176
42177 if (map.options.olNavigation) {
42178 var zoomPanel = new OpenLayers.Control.PanZoom();
42179 zoomPanel.onButtonClick = function(evt) {
42180 var btn = evt.buttonElement;
42181 switch (btn.action) {
42182 case "panup":
42183 this.map.pan(0, -this.getSlideFactor("h"));
42184 break;
42185 case "pandown":
42186 this.map.pan(0, this.getSlideFactor("h"));
42187 break;
42188 case "panleft":
42189 this.map.pan(-this.getSlideFactor("w"), 0);
42190 break;
42191 case "panright":
42192 this.map.pan(this.getSlideFactor("w"), 0);
42193 break;
42194 case "zoomin":
42195 map.zoom(1);
42196 break;
42197 case "zoomout":
42198 map.zoom(-1);
42199 break;
42200 case "zoomworld":
42201 if (this.map) {
42202 map.zoom(this.map.zoom * -1);
42203 }
42204 break;
42205 }
42206 };
42207 this.openlayersMap.addControl(zoomPanel);
42208 }
42209
42210 if (map.options.popups) {
42211 var panMap = function() {
42212 if (map.selectedGlyph) {
42213 var lonlat = new OpenLayers.LonLat(map.selectedGlyph.lon, map.selectedGlyph.lat);
42214 var pixel = map.openlayersMap.getPixelFromLonLat(lonlat);
42215 if (map.popup) {
42216 map.popup.shift(pixel.x, pixel.y);
42217 }
42218 }
42219 }
42220 this.openlayersMap.events.register("move", this.openlayersMap, panMap);
42221 }
42222
42223 if (map.options.olMapOverview) {
42224 this.openlayersMap.addControl(new OpenLayers.Control.OverviewMap());
42225 }
42226 if (map.options.olKeyboardDefaults) {
42227 var keyboardControl = new OpenLayers.Control.KeyboardDefaults();
42228 keyboardControl.defaultKeyPress = function(evt) {
42229 switch(evt.keyCode) {
42230 case OpenLayers.Event.KEY_LEFT:
42231 this.map.pan(-this.slideFactor, 0);
42232 break;
42233 case OpenLayers.Event.KEY_RIGHT:
42234 this.map.pan(this.slideFactor, 0);
42235 break;
42236 case OpenLayers.Event.KEY_UP:
42237 this.map.pan(0, -this.slideFactor);
42238 break;
42239 case OpenLayers.Event.KEY_DOWN:
42240 this.map.pan(0, this.slideFactor);
42241 break;
42242
42243 case 33:
42244 // Page Up. Same in all browsers.
42245 var size = this.map.getSize();
42246 this.map.pan(0, -0.75 * size.h);
42247 break;
42248 case 34:
42249 // Page Down. Same in all browsers.
42250 var size = this.map.getSize();
42251 this.map.pan(0, 0.75 * size.h);
42252 break;
42253 case 35:
42254 // End. Same in all browsers.
42255 var size = this.map.getSize();
42256 this.map.pan(0.75 * size.w, 0);
42257 break;
42258 case 36:
42259 // Home. Same in all browsers.
42260 var size = this.map.getSize();
42261 this.map.pan(-0.75 * size.w, 0);
42262 break;
42263
42264 case 43:
42265 // +/= (ASCII), keypad + (ASCII, Opera)
42266 case 61:
42267 // +/= (Mozilla, Opera, some ASCII)
42268 case 187:
42269 // +/= (IE)
42270 case 107:
42271 // keypad + (IE, Mozilla)
42272 map.zoom(1);
42273 break;
42274 case 45:
42275 // -/_ (ASCII, Opera), keypad - (ASCII, Opera)
42276 case 109:
42277 // -/_ (Mozilla), keypad - (Mozilla, IE)
42278 case 189:
42279 // -/_ (IE)
42280 case 95:
42281 // -/_ (some ASCII)
42282 map.zoom(-1);
42283 break;
42284 }
42285 };
42286 this.openlayersMap.addControl(keyboardControl);
42287 }
42288 if (map.options.olLayerSwitcher) {
42289 this.openlayersMap.addControl(new OpenLayers.Control.LayerSwitcher());
42290 }
42291 if (map.options.olScaleLine) {
42292 this.openlayersMap.addControl(new OpenLayers.Control.ScaleLine());
42293 }
42294 this.gui.resize();
42295 this.setBaseLayers();
42296 this.gui.setMapsDropdown();
42297 this.gui.setMap();
42298 this.openlayersMap.addLayers([this.objectLayer, this.markerLayer]);
42299
42300 if (map.options.boundaries) {
42301 var boundaries = map.options.boundaries;
42302 var bounds = new OpenLayers.Bounds(boundaries.minLon, boundaries.minLat, boundaries.maxLon, boundaries.maxLat);
42303 var projectionBounds = bounds.transform(this.openlayersMap.displayProjection, this.openlayersMap.projection);
42304 this.openlayersMap.zoomToExtent(projectionBounds);
42305 } else {
42306 this.openlayersMap.zoomToMaxExtent();
42307 }
42308
42309 // manages selection of elements if a polygon was drawn
42310 this.drawnPolygonHandler = function(polygon) {
42311 if (map.mds.getAllObjects() == null) {
42312 return;
42313 }
42314 var polygonFeature;
42315 if ( polygon instanceof OpenLayers.Geometry.Polygon) {
42316 polygonFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.MultiPolygon([polygon]));
42317 } else if ( polygon instanceof OpenLayers.Geometry.MultiPolygon) {
42318 polygonFeature = new OpenLayers.Feature.Vector(polygon);
42319 }
42320 map.polygons.push(polygonFeature);
42321 var style = $.extend(true, {}, OpenLayers.Feature.Vector.style['default']);
42322 style.graphicZIndex = 0;
42323 polygonFeature.style = style;
42324 map.objectLayer.addFeatures([polygonFeature]);
42325 try {
42326 map.activeControl.deactivate();
42327 } catch(e) {
42328 }
42329 var circles = map.mds.getObjectsByZoom();
42330 for (var i = 0; i < circles.length; i++) {
42331 for (var j = 0; j < circles[i].length; j++) {
42332 var c = circles[i][j];
42333 if (map.inPolygon(c)) {
42334 if ( typeof c.fatherBin != 'undefined') {
42335 for (var k = 0; k < c.fatherBin.circles.length; k++) {
42336 if (c.fatherBin.circles[k]) {
42337 c.fatherBin.circles[k].setSelection(true);
42338 }
42339 }
42340 } else {
42341 c.setSelection(true);
42342 }
42343 }
42344 }
42345 }
42346 map.mapSelection();
42347 }
42348
42349 this.polygonDeselection = function() {
42350 var circles = map.mds.getObjectsByZoom();
42351 for (var i = 0; i < circles.length; i++) {
42352 for (var j = 0; j < circles[i].length; j++) {
42353 var c = circles[i][j];
42354 if (map.inPolygon(c)) {
42355 c.setSelection(false);
42356 }
42357 }
42358 }
42359 }
42360 this.snapper = function() {
42361 if (map.polygons.length == 0 || !map.options.multiSelection) {
42362 map.deselection();
42363 }
42364 }
42365 if (map.options.polygonSelect) {
42366 this.drawPolygon = new OpenLayers.Control.DrawFeature(map.objectLayer, OpenLayers.Handler.Polygon, {
42367 displayClass : "olControlDrawFeaturePolygon",
42368 callbacks : {
42369 "done" : map.drawnPolygonHandler,
42370 "create" : map.snapper
42371 }
42372 });
42373 this.openlayersMap.addControl(this.drawPolygon);
42374 }
42375
42376 if (map.options.circleSelect) {
42377 this.drawCircle = new OpenLayers.Control.DrawFeature(map.objectLayer, OpenLayers.Handler.RegularPolygon, {
42378 displayClass : "olControlDrawFeaturePolygon",
42379 handlerOptions : {
42380 sides : 40
42381 },
42382 callbacks : {
42383 "done" : map.drawnPolygonHandler,
42384 "create" : map.snapper
42385 }
42386 });
42387 this.openlayersMap.addControl(this.drawCircle);
42388 }
42389
42390 if (map.options.squareSelect) {
42391 this.drawSquare = new OpenLayers.Control.DrawFeature(map.objectLayer, OpenLayers.Handler.RegularPolygon, {
42392 displayClass : "olControlDrawFeaturePolygon",
42393 handlerOptions : {
42394 sides : 4,
42395 irregular: true
42396 },
42397 callbacks : {
42398 "done" : map.drawnPolygonHandler,
42399 "create" : map.snapper
42400 }
42401 });
42402 this.openlayersMap.addControl(this.drawSquare);
42403 }
42404
42405 if (map.options.polygonSelect || map.options.circleSelect || map.options.squareSelect) {
42406 this.dragArea = new OpenLayers.Control.DragFeature(map.objectLayer, {
42407 onStart : function(feature) {
42408 feature.style.graphicZIndex = 10000;
42409 map.polygonDeselection();
42410 },
42411 onComplete : function(feature) {
42412 feature.style.graphicZIndex = 0;
42413 map.drawnPolygonHandler(feature.geometry);
42414 }
42415 });
42416 this.openlayersMap.addControl(this.dragArea);
42417
42418 this.modifyArea = new OpenLayers.Control.ModifyFeature(map.objectLayer, {
42419 onStart : function(feature) {
42420 feature.style.graphicZIndex = 10000;
42421 map.polygonDeselection();
42422 },
42423 onComplete : function(feature) {
42424 feature.style.graphicZIndex = 0;
42425 map.drawnPolygonHandler(feature.geometry);
42426 }
42427 });
42428 this.openlayersMap.addControl(this.modifyArea);
42429 this.modifyArea.mode = OpenLayers.Control.ModifyFeature.RESHAPE;
42430
42431 }
42432
42433 // calculates the tag cloud
42434 // manages hover selection of point objects
42435 var hoverSelect = function(event) {
42436 var object = event.feature;
42437 if (object.geometry instanceof OpenLayers.Geometry.Point) {
42438 if ( typeof map.placenameTags != 'undefined') {
42439 map.placenameTags.remove();
42440 }
42441 var circle = event.feature.parent;
42442 if ( circle instanceof CircleObject) {
42443 circle.placenameTags = new PlacenameTags(circle, map);
42444 map.placenameTags = circle.placenameTags;
42445 } else {
42446 return;
42447 /*
42448 event.feature.style.fillOpacity = 0.2;
42449 event.feature.style.strokeOpacity = 1;
42450 map.objectLayer.drawFeature(event.feature);
42451 circle.placenameTags = new PackPlacenameTags(circle,map);
42452 */
42453 }
42454 circle.placenameTags.calculate();
42455 map.mapCircleHighlight(object.parent, false);
42456 if ( typeof map.featureInfo != 'undefined') {
42457 map.featureInfo.deactivate();
42458 }
42459 } else {
42460 map.dragControl.checkStatus();
42461 }
42462 };
42463 var hoverUnselect = function(event) {
42464 var object = event.feature;
42465 if (object.geometry instanceof OpenLayers.Geometry.Point) {
42466 var circle = event.feature.parent;
42467 if (!( circle instanceof CircleObject )) {
42468 return;
42469 /*
42470 event.feature.style.fillOpacity = 0;
42471 event.feature.style.strokeOpacity = 0;
42472 map.objectLayer.drawFeature(event.feature);
42473 */
42474 }
42475 circle.placenameTags.remove();
42476 map.mapCircleHighlight(object.parent, true);
42477 if ( typeof map.featureInfo != 'undefined') {
42478 map.featureInfo.activate();
42479 }
42480 } else {
42481 map.dragControl.deactivate();
42482 }
42483 };
42484 var highlightCtrl = new OpenLayers.Control.SelectFeature(this.objectLayer, {
42485 hover : true,
42486 highlightOnly : true,
42487 renderIntent : "temporary",
42488 eventListeners : {
42489 featurehighlighted : hoverSelect,
42490 featureunhighlighted : hoverUnselect
42491 }
42492 });
42493 this.openlayersMap.addControl(highlightCtrl);
42494 highlightCtrl.activate();
42495
42496 this.selectFeature = new OpenLayers.Control.SelectFeature(this.objectLayer);
42497
42498 document.onkeydown = function(e) {
42499 if (e.ctrlKey) {
42500 map.ctrlKey = true;
42501 }
42502 }
42503 document.onkeyup = function(e) {
42504 map.ctrlKey = false;
42505 }
42506 // manages click selection of point objects
42507 var onFeatureSelect = function(event, evt) {
42508 if (!(event.feature.geometry instanceof OpenLayers.Geometry.Point)) {
42509 return;
42510 }
42511 var circle = event.feature.parent;
42512 if (map.options.multiSelection && map.ctrlKey) {
42513 if (map.popup) {
42514 map.popup.reset();
42515 map.selectedGlyph = false;
42516 }
42517 circle.toggleSelection();
42518 map.mapSelection();
42519 return;
42520 }
42521 map.reset();
42522 circle.setSelection(true);
42523 map.objectLayer.drawFeature(circle.feature);
42524 if (map.options.popups) {
42525 if (map.popup) {
42526 map.popup.reset();
42527 }
42528 var lonlat = event.feature.geometry.getBounds().getCenterLonLat();
42529 var pixel = map.openlayersMap.getPixelFromLonLat(lonlat);
42530 map.selectedGlyph = {
42531 lon : lonlat.lon,
42532 lat : lonlat.lat
42533 };
42534 map.popup = new PlacenamePopup(map);
42535 map.popup.createPopup(pixel.x, pixel.y, circle.placenameTags.placeLabels);
42536 if (map.options.selectDefault) {
42537 circle.placenameTags.selectLabel();
42538 }
42539 }
42540 }
42541 this.objectLayer.events.on({
42542 "featureselected" : onFeatureSelect
42543 });
42544
42545 this.openlayersMap.addControl(this.selectFeature);
42546 this.selectFeature.activate();
42547
42548 if (this.zoomSlider) {
42549 this.zoomSlider.setMaxAndLevels(1000, this.openlayersMap.getNumZoomLevels());
42550 this.zoomSlider.setValue(this.getZoom());
42551 }
42552
42553 Publisher.Subscribe('mapChanged', this, function(mapName) {
42554 this.client.setBaseLayerByName(mapName);
42555 this.client.gui.setMap();
42556 });
42557
42558 },
42559
42560 shift : function(shiftX, shiftY) {
42561 this.openlayersMap.pan(shiftX, shiftY);
42562 },
42563
42564 addBaseLayers : function(layers) {
42565 if ( layers instanceof Array) {
42566 for (var i in layers ) {
42567 var layer;
42568 if (layers[i].type === "XYZ"){
42569 layer = new OpenLayers.Layer.XYZ(
42570 layers[i].name,
42571 [
42572 layers[i].url
42573 ],
42574 {
42575 sphericalMercator: true,
42576 transitionEffect: "resize",
42577 buffer: 1,
42578 numZoomLevels: 12,
42579 transparent : true,
42580 attribution: layers[i].attribution
42581 },
42582 {
42583 isBaseLayer : true
42584 }
42585 );
42586 } else {
42587 layer = new OpenLayers.Layer.WMS(
42588 layers[i].name, layers[i].url,
42589 {
42590 projection : "EPSG:4326",
42591 layers : layers[i].layer,
42592 transparent : "true",
42593 format : "image/png"
42594 },
42595 {
42596 attribution: layers[i].attribution,
42597 isBaseLayer : true
42598 }
42599 );
42600 }
42601 this.baseLayers.push(layer);
42602 this.openlayersMap.addLayers([layer]);
42603 }
42604 }
42605 this.gui.setMapsDropdown();
42606 },
42607
42608 /**
42609 * set online available maps for Google, Bing and OSM
42610 */
42611 setBaseLayers : function() {
42612 this.baseLayers = [];
42613 if (this.options.googleMaps) {
42614 // see http://openlayers.org/blog/2010/07/10/google-maps-v3-for-openlayers/ for information
42615 var gphy = new OpenLayers.Layer.Google("Google Physical", {
42616 type : google.maps.MapTypeId.TERRAIN,
42617 minZoomLevel : 1,
42618 maxZoomLevel : 19
42619 });
42620 var gmap = new OpenLayers.Layer.Google("Google Streets", {
42621 minZoomLevel : 1,
42622 maxZoomLevel : 19
42623 });
42624 var ghyb = new OpenLayers.Layer.Google("Google Hybrid", {
42625 type : google.maps.MapTypeId.HYBRID,
42626 minZoomLevel : 1,
42627 maxZoomLevel : 19
42628 });
42629 var gsat = new OpenLayers.Layer.Google("Google Satellite", {
42630 type : google.maps.MapTypeId.SATELLITE,
42631 minZoomLevel : 1,
42632 maxZoomLevel : 19
42633 });
42634 this.baseLayers.push(gphy);
42635 this.baseLayers.push(gmap);
42636 this.baseLayers.push(ghyb);
42637 this.baseLayers.push(gsat);
42638 }
42639 if (this.options.bingMaps) {
42640 // see http://openlayers.org/blog/2010/12/18/bing-tiles-for-openlayers/ for information
42641 var apiKey = this.options.bingApiKey;
42642 var road = new OpenLayers.Layer.Bing({
42643 name : "Road",
42644 key : apiKey,
42645 type : "Road"
42646 });
42647 var hybrid = new OpenLayers.Layer.Bing({
42648 name : "Hybrid",
42649 key : apiKey,
42650 type : "AerialWithLabels"
42651 });
42652 var aerial = new OpenLayers.Layer.Bing({
42653 name : "Aerial",
42654 key : apiKey,
42655 type : "Aerial"
42656 });
42657 this.baseLayers.push(road);
42658 this.baseLayers.push(hybrid);
42659 this.baseLayers.push(aerial);
42660 }
42661 if (this.options.osmMaps) {
42662 this.baseLayers.push(new OpenLayers.Layer.OSM('Open Street Map', '', {
42663 sphericalMercator : true,
42664 zoomOffset : 1,
42665 resolutions : this.resolutions
42666 }));
42667 }
42668 if (this.options.osmMapsMapQuest) {
42669 this.baseLayers.push(new OpenLayers.Layer.OSM('Open Street Map (MapQuest)',
42670 ["http://otile1.mqcdn.com/tiles/1.0.0/map/${z}/${x}/${y}.png",
42671 "http://otile2.mqcdn.com/tiles/1.0.0/map/${z}/${x}/${y}.png",
42672 "http://otile3.mqcdn.com/tiles/1.0.0/map/${z}/${x}/${y}.png",
42673 "http://otile4.mqcdn.com/tiles/1.0.0/map/${z}/${x}/${y}.png"],
42674 {
42675 sphericalMercator : true,
42676 zoomOffset : 1,
42677 resolutions : this.resolutions
42678 }
42679 ));
42680 }
42681 for (var i = 0; i < this.baseLayers.length; i++) {
42682 this.openlayersMap.addLayers([this.baseLayers[i]]);
42683 }
42684 if (this.options.alternativeMap) {
42685 if (!(this.options.alternativeMap instanceof Array))
42686 this.options.alternativeMap = [this.options.alternativeMap];
42687 this.addBaseLayers(this.options.alternativeMap);
42688 }
42689 this.setBaseLayerByName(this.options.baseLayer);
42690 },
42691
42692 setBaseLayerByName : function(name){
42693 for (var i = 0; i < this.baseLayers.length; i++) {
42694 if (this.baseLayers[i].name == name) {
42695 this.setMap(i);
42696 }
42697 }
42698 },
42699
42700 getBaseLayerName : function() {
42701 return this.openlayersMap.baseLayer.name;
42702 },
42703
42704 setOverlays : function(layers) {
42705 var map = this;
42706 for (var i in this.wmsOverlays ) {
42707 this.openlayersMap.removeLayer(this.wmsOverlays[i]);
42708 }
42709 this.wmsOverlays = [];
42710 var featureInfoLayers = [];
42711 if ( layers instanceof Array) {
42712 for (var i in layers ) {
42713 var layer = new OpenLayers.Layer.WMS(layers[i].name, layers[i].url, {
42714 projection : "EPSG:4326",
42715 layers : layers[i].layer,
42716 transparent : "true",
42717 format : "image/png"
42718 }, {
42719 isBaseLayer : false,
42720 visibility : map.options.overlayVisibility
42721 });
42722 this.wmsOverlays.push(layer);
42723 if (layers[i].featureInfo) {
42724 featureInfoLayers.push(layer);
42725 }
42726 }
42727 this.openlayersMap.addLayers(this.wmsOverlays);
42728 }
42729 if (this.wmsOverlays.length > 0 && map.options.overlayVisibility) {
42730 var map = this;
42731 if ( typeof this.featureInfo != 'undefined') {
42732 this.featureInfo.deactivate();
42733 this.openlayersMap.removeControl(this.featureInfo);
42734 }
42735 this.featureInfo = new OpenLayers.Control.WMSGetFeatureInfo({
42736 url : '/geoserver/wms',
42737 layers : featureInfoLayers,
42738 eventListeners : {
42739 getfeatureinfo : function(event) {
42740 if (event.text == '') {
42741 return;
42742 }
42743 var lonlat = map.openlayersMap.getLonLatFromPixel(new OpenLayers.Pixel(event.xy.x, event.xy.y));
42744 map.selectedGlyph = {
42745 lon : lonlat.lon,
42746 lat : lonlat.lat
42747 };
42748 if ( typeof map.popup != 'undefined') {
42749 map.popup.reset();
42750 }
42751 map.popup = new MapPopup(map);
42752 map.popup.initialize(event.xy.x, event.xy.y);
42753 map.popup.setContent(event.text);
42754 }
42755 }
42756 });
42757 this.openlayersMap.addControl(this.featureInfo);
42758 this.featureInfo.activate();
42759 this.activateCountrySelector(this.wmsOverlays[this.wmsOverlays.length - 1]);
42760 } else {
42761 this.deactivateCountrySelector();
42762 if (this.openlayersMap.baseLayer instanceof OpenLayers.Layer.WMS) {
42763 this.activateCountrySelector(this.openlayersMap.baseLayer);
42764 }
42765 }
42766 },
42767
42768 addBaseLayer : function(layer) {
42769 this.baseLayers.push(layer);
42770 this.openlayersMap.addLayers([layer]);
42771 for (var i in this.baseLayers ) {
42772 if (this.baseLayers[i].name == this.options.baseLayer) {
42773 this.setMap(i);
42774 }
42775 }
42776 },
42777
42778 /**
42779 * draws the object layer.
42780 * @param {boolean} zoom if there was a zoom; if not, the new boundary of the map is calculated
42781 */
42782 drawObjectLayer : function(zoom) {
42783 if ( typeof this.placenameTags != 'undefined') {
42784 this.placenameTags.remove();
42785 }
42786 var points = this.mds.getAllObjects();
42787 if (points == null) {
42788 return;
42789 }
42790 this.objectLayer.removeAllFeatures();
42791
42792 if (zoom) {
42793 var minLat, maxLat, minLon, maxLon;
42794 var pointsHighestZoom = points[points.length - 1];
42795 for (var i = 0; i < pointsHighestZoom.length; i++) {
42796 for (var j = 0; j < pointsHighestZoom[i].length; j++) {
42797 var point = pointsHighestZoom[i][j];
42798 if (minLon == null || point.originX < minLon) {
42799 minLon = point.originX;
42800 }
42801 if (maxLon == null || point.originX > maxLon) {
42802 maxLon = point.originX;
42803 }
42804 if (minLat == null || point.originY < minLat) {
42805 minLat = point.originY;
42806 }
42807 if (maxLat == null || point.originY > maxLat) {
42808 maxLat = point.originY;
42809 }
42810 }
42811 }
42812 if (minLon == maxLon && minLat == maxLat) {
42813 this.openlayersMap.setCenter(new OpenLayers.LonLat(minLon, minLat));
42814 } else {
42815 var gapX = 0.1 * (maxLon - minLon );
42816 var gapY1 = 0.1 * (maxLat - minLat );
42817 var gapY2 = (this.gui.headerHeight / this.gui.mapWindow.offsetHeight + 0.1 ) * (maxLat - minLat );
42818 this.openlayersMap.zoomToExtent(new OpenLayers.Bounds(minLon - gapX, minLat - gapY1, maxLon + gapX, maxLat + gapY2));
42819 this.openlayersMap.zoomTo(Math.floor(this.getZoom()));
42820 }
42821 if (this.zoomSlider) {
42822 this.zoomSlider.setValue(this.getZoom());
42823 }
42824 }
42825 var displayPoints = this.mds.getObjectsByZoom();
42826 var resolution = this.openlayersMap.getResolution();
42827 for (var i = 0; i < displayPoints.length; i++) {
42828 for (var j = 0; j < displayPoints[i].length; j++) {
42829 var p = displayPoints[i][j];
42830 var x = p.originX + resolution * p.shiftX;
42831 var y = p.originY + resolution * p.shiftY;
42832 p.feature.geometry.x = x;
42833 p.feature.geometry.y = y;
42834 p.olFeature.geometry.x = x;
42835 p.olFeature.geometry.y = y;
42836 p.feature.style.graphicZIndex = this.zIndices[i];
42837 p.olFeature.style.graphicZIndex = this.zIndices[i] + 1;
42838 this.objectLayer.addFeatures([p.feature]);
42839 this.objectLayer.addFeatures([p.olFeature]);
42840 }
42841 }
42842 var zoomLevel = this.getZoom();
42843 /*
42844 for (var i = 0; i < this.bins[zoomLevel].length; i++) {
42845 var p = this.bins[zoomLevel][i];
42846 p.feature.style.graphicZIndex = 0;
42847 this.objectLayer.addFeatures([p.feature]);
42848 }
42849 */
42850
42851 var dist = function(p1, p2) {
42852 return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
42853 }
42854
42855 this.highlightChanged(this.selection.getObjects(this.core));
42856
42857 },
42858
42859 riseLayer : function(id) {
42860 this.lastId = id;
42861 if ( typeof id == 'undefined') {
42862 id = this.lastId || 0;
42863 }
42864 this.zIndices[id] = this.layerZIndex;
42865 this.layerZIndex += 2;
42866 this.drawObjectLayer(false);
42867 for( var i=0; i<this.polygons.length; i++ ){
42868 this.objectLayer.addFeatures([this.polygons[i]]);
42869 }
42870 },
42871
42872 /**
42873 * initializes the object layer.
42874 * all point representations for all zoom levels are calculated and initialized
42875 * @param {MapObject[][]} mapObjects an array of map objects from different (1-4) sets
42876 */
42877 initWidget : function(datasets, zoom) {
42878
42879 this.clearMap();
42880
42881 this.datasets = datasets;
42882 var mapObjects = [];
42883 for (var i = 0; i < datasets.length; i++) {
42884 mapObjects.push(datasets[i].objects);
42885 }
42886 if (mapObjects.length > 4) {
42887 this.options.circlePackings = false;
42888 } else {
42889 this.options.circlePackings = this.formerCP;
42890 }
42891
42892 if ( typeof mapObjects == 'undefined') {
42893 return;
42894 }
42895
42896 this.count = 0;
42897 this.objectCount = 0;
42898 for (var i = 0; i < mapObjects.length; i++) {
42899 var c = 0;
42900 for (var j = 0; j < mapObjects[i].length; j++) {
42901 if (mapObjects[i][j].isGeospatial) {
42902 c += mapObjects[i][j].weight;
42903 this.objectCount++;
42904 }
42905 }
42906 this.count += c;
42907 this.zIndices.push(this.layerZIndex);
42908 this.layerZIndex += 2;
42909 }
42910
42911 this.mds.initialize(mapObjects);
42912 var points = this.mds.getAllObjects();
42913 if (points == null) {
42914 return;
42915 }
42916
42917 var getArea = function(radius) {
42918 return Math.PI * radius * radius;
42919 }
42920 for (var i = 0; i < points.length; i++) {
42921 var area = 0;
42922 var maxRadius = 0;
42923 for (var j = 0; j < points[i].length; j++) {
42924 for (var k = 0; k < points[i][j].length; k++) {
42925 if (points[i][j][k].radius > maxRadius) {
42926 maxRadius = points[i][j][k].radius;
42927 area = getArea(maxRadius);
42928 }
42929 }
42930 }
42931 var minArea = getArea(this.options.minimumRadius);
42932 var areaDiff = area - minArea;
42933 for (var j = 0; j < points[i].length; j++) {
42934 for (var k = 0; k < points[i][j].length; k++) {
42935 var point = points[i][j][k];
42936 var c, shape, rotation, multiplier = 1;
42937 if( this.options.useGraphics ){
42938 var graphic = this.config.getGraphic(point.search);
42939 c = graphic.color;
42940 shape = graphic.shape;
42941 rotation = graphic.rotation;
42942 if( shape == 'square' ){
42943 multiplier = 0.75;
42944 }
42945 }
42946 else {
42947 c = GeoTemConfig.getAverageDatasetColor(point.search,point.elements);
42948 shape = 'circle';
42949 rotation = 0;
42950 }
42951 var opacity;
42952 if (this.options.circleOpacity == 'balloon') {
42953 var min = this.options.minTransparency;
42954 var max = this.options.maxTransparency;
42955 opacity = min + Math.abs(min - max) * (1 - (getArea(point.radius) - minArea) / areaDiff);
42956 }
42957 else {
42958 opacity = this.options.circleOpacity;
42959 }
42960 var col = false, ols = 0;
42961 if( this.options.circleOutline ){
42962 col = true;
42963 ols = this.options.circleOutline;
42964 }
42965 var style = {
42966 graphicName: shape,
42967 rotation: rotation,
42968 fillColor : 'rgb(' + c.r0 + ',' + c.g0 + ',' + c.b0 + ')',
42969 fillOpacity : opacity,
42970 strokeWidth : ols,
42971 strokeColor : 'rgb(' + c.r1 + ',' + c.g1 + ',' + c.b1 + ')',
42972 stroke : col,
42973 pointRadius : point.radius * multiplier,
42974 cursor : "pointer"
42975 };
42976 var pointGeometry = new OpenLayers.Geometry.Point(point.originX, point.originY, null);
42977 var feature = new OpenLayers.Feature.Vector(pointGeometry);
42978 feature.style = style;
42979 feature.parent = point;
42980 point.setFeature(feature);
42981 var olStyle = {
42982 graphicName: shape,
42983 rotation: rotation,
42984 fillColor : 'rgb(' + c.r1 + ',' + c.g1 + ',' + c.b1 + ')',
42985 fillOpacity : opacity,
42986 stroke : false,
42987 pointRadius : 0,
42988 cursor : "pointer"
42989 };
42990 var olPointGeometry = new OpenLayers.Geometry.Point(point.originX, point.originY, null);
42991 var olFeature = new OpenLayers.Feature.Vector(olPointGeometry);
42992 olFeature.style = olStyle;
42993 olFeature.parent = point;
42994 point.setOlFeature(olFeature);
42995 }
42996 }
42997 }
42998
42999 /*
43000 this.bins = this.mds.getAllBins();
43001 for (var i = 0; i < this.bins.length; i++) {
43002 for (var j = 0; j < this.bins[i].length; j++) {
43003 var bin = this.bins[i][j];
43004 var style = {
43005 fillColor : 'rgb(140,140,140)',
43006 fillOpacity : 0,
43007 strokeWidth : 2,
43008 strokeOpacity : 0,
43009 strokeColor : 'rgb(140,140,140)',
43010 // stroke: false,
43011 pointRadius : bin.radius,
43012 cursor : "pointer"
43013 };
43014 var pointGeometry = new OpenLayers.Geometry.Point(bin.x, bin.y, null);
43015 var feature = new OpenLayers.Feature.Vector(pointGeometry);
43016 feature.style = style;
43017 feature.parent = bin;
43018 bin.feature = feature;
43019 }
43020 }
43021 */
43022
43023 this.gui.updateLegend(datasets);
43024
43025 if ( typeof zoom == "undefined") {
43026 this.drawObjectLayer(true);
43027 } else {
43028 this.drawObjectLayer(zoom);
43029 }
43030 this.gui.updateSpaceQuantity(this.count);
43031
43032 },
43033
43034 /**
43035 * resets the map by destroying all additional elements except the point objects, which are replaced
43036 */
43037 reset : function() {
43038 if ( typeof this.placenameTags != 'undefined') {
43039 this.placenameTags.remove();
43040 }
43041 this.objectLayer.removeFeatures(this.polygons);
43042 this.polygons = [];
43043 this.objectLayer.removeFeatures(this.connections);
43044 this.connections = [];
43045 this.selectFeature.unselectAll();
43046 this.selectedGlyph = false;
43047 if (this.dragControl.activated) {
43048 this.dragControl.deactivate();
43049 }
43050 if (this.popup) {
43051 this.popup.reset();
43052 }
43053 this.filterBar.reset(false);
43054 var points = this.mds.getObjectsByZoom();
43055 if (points == null) {
43056 return;
43057 }
43058 for (var i = 0; i < points.length; i++) {
43059 for (var j = 0; j < points[i].length; j++) {
43060 points[i][j].setSelection(false);
43061 }
43062 }
43063 },
43064
43065 /**
43066 * resets the map by destroying all elements
43067 */
43068 clearMap : function() {
43069 this.reset();
43070 this.selection = new Selection();
43071 this.zIndices = [];
43072 this.layerZIndex = 1;
43073 this.objectLayer.destroyFeatures();
43074 },
43075
43076 /**
43077 * updates the proportional selection status of a point object
43078 * @param {PointObject} point the point to update
43079 * @param {OpenLayers.Geometry.Polygon} polygon the actual displayed map polygon
43080 */
43081 updatePoint : function(point, polygon) {
43082 var olRadius = this.mds.binning.getRadius(point.overlay);
43083 if( this.options.useGraphics ){
43084 var graphic = this.config.getGraphic(point.search);
43085 if( graphic.shape == 'square' ){
43086 olRadius *= 0.75;
43087 }
43088 }
43089 point.olFeature.style.pointRadius = olRadius;
43090 var c = GeoTemConfig.getAverageDatasetColor(point.search, point.overlayElements);
43091 point.olFeature.style.fillColor = 'rgb(' + c.r1 + ',' + c.g1 + ',' + c.b1 + ')';
43092 if (polygon.containsPoint(point.feature.geometry)) {
43093 this.objectLayer.drawFeature(point.olFeature);
43094 }
43095 },
43096
43097 /**
43098 * updates the the object layer of the map after selections had been executed in timeplot or table or zoom level has changed
43099 */
43100 highlightChanged : function(mapObjects) {
43101 var hideEmptyCircles = false;
43102
43103 if (this.config.options.hideUnselected){
43104 var overallCnt = 0;
43105 for (var i in mapObjects){
43106 overallCnt += mapObjects[i].length;
43107 }
43108 if (overallCnt > 0){
43109 hideEmptyCircles = true;
43110 }
43111 }
43112
43113 if( !GeoTemConfig.highlightEvents ){
43114 return;
43115 }
43116 this.mds.clearOverlay();
43117 if (this.selection.valid()) {
43118 this.mds.setOverlay(GeoTemConfig.mergeObjects(mapObjects, this.selection.getObjects()));
43119 } else {
43120 this.mds.setOverlay(mapObjects);
43121 }
43122 var points = this.mds.getObjectsByZoom();
43123 var polygon = this.openlayersMap.getExtent().toGeometry();
43124 for (var i in points ) {
43125 for (var j in points[i] ) {
43126 var point = points[i][j];
43127
43128 if (hideEmptyCircles){
43129 point.feature.style.display = 'none';
43130 } else {
43131 point.feature.style.display = '';
43132 }
43133
43134 this.updatePoint(points[i][j], polygon);
43135 }
43136 }
43137 this.displayConnections();
43138 this.objectLayer.redraw();
43139 },
43140
43141 selectionChanged : function(selection) {
43142 if( !GeoTemConfig.selectionEvents ){
43143 return;
43144 }
43145 this.reset();
43146 this.selection = selection;
43147 this.highlightChanged(selection.objects);
43148 },
43149
43150 inPolygon : function(point) {
43151 for (var i = 0; i < this.polygons.length; i++) {
43152 var polygon = this.polygons[i].geometry;
43153 for (var j = 0; j < polygon.components.length; j++) {
43154 if (polygon.components[j].containsPoint(point.feature.geometry)) {
43155 return true;
43156 }
43157 }
43158 }
43159 return false;
43160 },
43161
43162 mapSelection : function() {
43163 var selectedObjects = [];
43164 for (var i = 0; i < this.mds.size(); i++) {
43165 selectedObjects.push([]);
43166 }
43167 var circles = this.mds.getObjectsByZoom();
43168 for (var i = 0; i < circles.length; i++) {
43169
43170 for (var j = 0; j < circles[i].length; j++) {
43171 var c = circles[i][j];
43172 if (c.selected) {
43173 selectedObjects[i] = selectedObjects[i].concat(c.elements);
43174 }
43175 }
43176 }
43177 this.selection = new Selection(selectedObjects, this);
43178 this.highlightChanged(selectedObjects);
43179 this.core.triggerSelection(this.selection);
43180 this.filterBar.reset(true);
43181 },
43182
43183 deselection : function() {
43184 this.reset();
43185 this.selection = new Selection();
43186 this.highlightChanged([]);
43187 this.core.triggerSelection(this.selection);
43188 },
43189
43190 filtering : function() {
43191 for (var i = 0; i < this.datasets.length; i++) {
43192 this.datasets[i].objects = this.selection.objects[i];
43193 }
43194 this.core.triggerRefining(this.datasets);
43195 },
43196
43197 inverseFiltering : function() {
43198 var selectedObjects = [];
43199 for (var i = 0; i < this.mds.size(); i++) {
43200 selectedObjects.push([]);
43201 }
43202 var circles = this.mds.getObjectsByZoom();
43203 for (var i = 0; i < circles.length; i++) {
43204 for (var j = 0; j < circles[i].length; j++) {
43205 var c = circles[i][j];
43206 if (!c.selected) {
43207 selectedObjects[i] = selectedObjects[i].concat(c.elements);
43208 }
43209 }
43210 }
43211 this.selection = new Selection(selectedObjects, this);
43212 this.filtering();
43213 },
43214
43215 mapCircleHighlight : function(circle, undo) {
43216 if (this.polygons.length > 0 && this.inPolygon(circle)) {
43217 return;
43218 }
43219 var mapObjects = [];
43220 for (var i = 0; i < this.mds.size(); i++) {
43221 mapObjects.push([]);
43222 }
43223 if (!undo && !circle.selected) {
43224 mapObjects[circle.search] = circle.elements;
43225 }
43226 this.objectLayer.drawFeature(circle.feature);
43227 this.core.triggerHighlight(mapObjects);
43228 },
43229
43230 mapLabelSelection : function(label) {
43231 var selectedObjects = [];
43232 for (var i = 0; i < this.mds.size(); i++) {
43233 selectedObjects.push([]);
43234 }
43235 selectedObjects[label.index] = label.elements;
43236 this.selection = new Selection(selectedObjects, this);
43237 this.highlightChanged(selectedObjects);
43238 this.core.triggerSelection(this.selection);
43239 this.filterBar.reset(true);
43240 },
43241
43242 triggerMapChanged : function(mapName) {
43243 Publisher.Publish('mapChanged', mapName, this);
43244 },
43245
43246 /**
43247 * displays connections between data objects
43248 */
43249 displayConnections : function() {
43250 return;
43251 if ( typeof this.connection != 'undefined') {
43252 this.objectLayer.removeFeatures(this.connections);
43253 this.connections = [];
43254 }
43255 if (this.options.connections) {
43256 var points = this.mds.getObjectsByZoom();
43257 for (var i in points ) {
43258 for (var j in points[i] ) {
43259
43260 }
43261 }
43262
43263 var slices = this.core.timeplot.getSlices();
43264 for (var i = 0; i < slices.length; i++) {
43265 for (var j = 0; j < slices[i].stacks.length; j++) {
43266 var e = slices[i].stacks[j].elements;
43267 if (e.length == 0) {
43268 continue;
43269 }
43270 var points = [];
43271 for (var k = 0; k < e.length; k++) {
43272 var point = this.mds.getCircle(j, e[k].index).feature.geometry;
43273 if (arrayIndex(points, point) == -1) {
43274 points.push(point);
43275 }
43276 }
43277 var matrix = new AdjMatrix(points.length);
43278 for (var k = 0; k < points.length - 1; k++) {
43279 for (var l = k + 1; l < points.length; l++) {
43280 matrix.setEdge(k, l, dist(points[k], points[l]));
43281 }
43282 }
43283 var tree = Prim(matrix);
43284 var lines = [];
43285 for (var z = 0; z < tree.length; z++) {
43286 lines.push(new OpenLayers.Geometry.LineString(new Array(points[tree[z].v1], points[tree[z].v2])));
43287 }
43288 this.connections[j].push({
43289 first : this.mds.getCircle(j, e[0].index).feature.geometry,
43290 last : this.mds.getCircle(j, e[e.length - 1].index).feature.geometry,
43291 lines : lines,
43292 time : slices[i].date
43293 });
43294 }
43295 }
43296 var ltm = this.core.timeplot.leftFlagTime;
43297 var rtm = this.core.timeplot.rightFlagTime;
43298 if (ltm == undefined || ltm == null) {
43299 return;
43300 } else {
43301 ltm = ltm.getTime();
43302 rtm = rtm.getTime();
43303 }
43304 // this.connectionLayer.destroyFeatures();
43305 if (thisConnections) {
43306 for (var i = 0; i < this.connections.length; i++) {
43307 var c = GeoTemConfig.colors[i];
43308 var style = {
43309 strokeColor : 'rgb(' + c.r1 + ',' + c.g1 + ',' + c.b1 + ')',
43310 strokeOpacity : 0.5,
43311 strokeWidth : 3
43312 };
43313 var pointsToConnect = [];
43314 var last = undefined;
43315 for (var j = 0; j < this.connections[i].length; j++) {
43316 var c = this.connections[i][j];
43317 var ct = c.time.getTime();
43318 if (ct >= ltm && ct <= rtm) {
43319 if (last != undefined) {
43320 var line = new OpenLayers.Geometry.LineString(new Array(last, c.first));
43321 this.connectionLayer.addFeatures([new OpenLayers.Feature.Vector(line, null, style)]);
43322 }
43323 for (var k = 0; k < c.lines.length; k++) {
43324 this.connectionLayer.addFeatures([new OpenLayers.Feature.Vector(c.lines[k], null, style)]);
43325 }
43326 last = c.last;
43327 }
43328 }
43329 }
43330 // this.connectionLayer.redraw();
43331 }
43332 }
43333 },
43334
43335 /**
43336 * performs a zoom on the map
43337 * @param {int} delta the change of zoom levels
43338 */
43339 zoom : function(delta) {
43340 var zoom = this.getZoom() + delta;
43341 if (this.openlayersMap.baseLayer instanceof OpenLayers.Layer.WMS) {
43342 this.openlayersMap.zoomTo(zoom);
43343 } else {
43344 this.openlayersMap.zoomTo(Math.round(zoom));
43345 if (this.zoomSlider) {
43346 this.zoomSlider.setValue(this.getZoom());
43347 }
43348 }
43349 return true;
43350 },
43351
43352 deactivateCountrySelector : function() {
43353 this.openlayersMap.removeControl(this.selectCountry);
43354 this.selectCountry = undefined;
43355 },
43356
43357 activateCountrySelector : function(layer) {
43358 var map = this;
43359 if (this.options.countrySelect && this.options.mapSelectionTools) {
43360 this.selectCountry = new OpenLayers.Control.GetFeature({
43361 protocol : OpenLayers.Protocol.WFS.fromWMSLayer(layer),
43362 click : true
43363 });
43364 this.selectCountry.events.register("featureselected", this, function(e) {
43365 map.snapper();
43366 map.drawnPolygonHandler(e.feature.geometry);
43367 });
43368 this.openlayersMap.addControl(this.selectCountry);
43369 this.countrySelectionControl.enable();
43370 }
43371 },
43372
43373 setMap : function(index) {
43374 this.baselayerIndex = index;
43375 if (this.selectCountry) {
43376 // if( this.wmsOverlays.length == 0 ){
43377 this.deactivateCountrySelector();
43378 // }
43379 }
43380 if (this.baseLayers[index] instanceof OpenLayers.Layer.WMS) {
43381 // if( this.wmsOverlays.length == 0 ){
43382 this.activateCountrySelector(this.baseLayers[index]);
43383 // }
43384 } else {
43385 if (this.countrySelectionControl) {
43386 this.countrySelectionControl.disable();
43387 }
43388 }
43389 this.openlayersMap.zoomTo(Math.floor(this.getZoom()));
43390 this.openlayersMap.setBaseLayer(this.baseLayers[index]);
43391 if (this.baseLayers[index].name == 'Open Street Map') {
43392 this.gui.osmLink.style.visibility = 'visible';
43393 } else {
43394 this.gui.osmLink.style.visibility = 'hidden';
43395 }
43396 if (this.baseLayers[index].name == 'Open Street Map (MapQuest)') {
43397 this.gui.osmMapQuestLink.style.visibility = 'visible';
43398 } else {
43399 this.gui.osmMapQuestLink.style.visibility = 'hidden';
43400 }
43401 this.triggerMapChanged(this.baseLayers[index].name);
43402 },
43403
43404 //vhz added title to buttons
43405 initSelectorTools : function() {
43406 var map = this;
43407 this.mapControls = [];
43408
43409 if (this.options.squareSelect) {
43410 var button = document.createElement("div");
43411 $(button).addClass('mapControl');
43412 var activate = function() {
43413 map.drawSquare.activate();
43414 }
43415 var deactivate = function() {
43416 map.drawSquare.deactivate();
43417 }
43418 this.mapControls.push(new MapControl(this, button, 'square', activate, deactivate));
43419 }
43420 if (this.options.circleSelect) {
43421 var button = document.createElement("div");
43422 $(button).addClass('mapControl');
43423 var activate = function() {
43424 map.drawCircle.activate();
43425 }
43426 var deactivate = function() {
43427 map.drawCircle.deactivate();
43428 }
43429 this.mapControls.push(new MapControl(this, button, 'circle', activate, deactivate));
43430 }
43431 if (this.options.polygonSelect) {
43432 var button = document.createElement("div");
43433 $(button).addClass('mapControl');
43434 var activate = function() {
43435 map.drawPolygon.activate();
43436 }
43437 var deactivate = function() {
43438 map.drawPolygon.deactivate();
43439 }
43440 this.mapControls.push(new MapControl(this, button, 'polygon', activate, deactivate));
43441 }
43442 if (this.options.countrySelect) {
43443 var button = document.createElement("div");
43444 $(button).addClass('mapControl');
43445 var activate = function() {
43446 map.selectCountry.activate();
43447 map.dragControl.disable();
43448 }
43449 var deactivate = function() {
43450 map.selectCountry.deactivate();
43451 map.dragControl.enable();
43452 }
43453 this.countrySelectionControl = new MapControl(this, button, 'country', activate, deactivate);
43454 this.mapControls.push(this.countrySelectionControl);
43455 /*
43456 if( !(this.openlayersMap.baseLayer instanceof OpenLayers.Layer.WMS) ){
43457 this.countrySelectionControl.disable();
43458 }
43459 */
43460 }
43461 return this.mapControls;
43462 },
43463
43464 getZoom : function() {
43465 //calculate zoom from active resolution
43466 var resolution = this.openlayersMap.getResolution();
43467 var zoom = this.resolutions.indexOf(resolution);
43468 if (zoom == -1){
43469 //fractional zoom
43470 for (zoom = 0; zoom < this.resolutions.length; zoom++){
43471 if (resolution>=this.resolutions[zoom]){
43472 break;
43473 }
43474 }
43475 if (zoom == this.resolutions.length){
43476 zoom--;
43477 }
43478 }
43479 return(zoom);
43480 },
43481
43482 setMarker : function(lon, lat) {
43483 var p = new OpenLayers.Geometry.Point(lon, lat, null);
43484 p.transform(this.openlayersMap.displayProjection, this.openlayersMap.projection);
43485 this.openlayersMap.setCenter(new OpenLayers.LonLat(p.x, p.y));
43486 var size = new OpenLayers.Size(22, 33);
43487 var offset = new OpenLayers.Pixel(-(size.w / 2), -size.h);
43488 var icon = new OpenLayers.Icon(GeoTemConfig.path + 'marker.png', size, offset);
43489 var marker = new OpenLayers.Marker(new OpenLayers.LonLat(p.x, p.y), icon);
43490 marker.setOpacity(0.9);
43491 this.markerLayer.setZIndex(parseInt(this.objectLayer.getZIndex()) + 1);
43492 this.markerLayer.addMarker(marker);
43493 // find nearest neighbor
43494 var nearestNeighbor;
43495 var points = this.mds.getAllObjects();
43496 if (points == null) {
43497 return;
43498 }
43499 var dist = function(p1, p2) {
43500 return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
43501 }
43502 var zoomLevels = this.openlayersMap.getNumZoomLevels();
43503 var pointSet = points[zoomLevels - 1];
43504 var closestDistance = undefined;
43505 var closestPoint;
43506 for (var i = 0; i < pointSet.length; i++) {
43507 for (var j = 0; j < pointSet[i].length; j++) {
43508 var point = pointSet[i][j].feature.geometry;
43509 var d = dist(point, p);
43510 if (!closestDistance || d < closestDistance) {
43511 closestDistance = d;
43512 closestPoint = point;
43513 }
43514 }
43515 }
43516 // find minimal zoom level
43517 var gap = 0;
43518 var x_s = this.gui.mapWindow.offsetWidth / 2 - gap;
43519 var y_s = this.gui.mapWindow.offsetHeight / 2 - gap;
43520 if (typeof closestPoint !== "undefined"){
43521 var xDist = Math.abs(p.x - closestPoint.x);
43522 var yDist = Math.abs(p.y - closestPoint.y);
43523 for (var i = 0; i < zoomLevels; i++) {
43524 var resolution = this.openlayersMap.getResolutionForZoom(zoomLevels - i - 1);
43525 if (xDist / resolution < x_s && yDist / resolution < y_s) {
43526 this.openlayersMap.zoomTo(zoomLevels - i - 1);
43527 if (this.zoomSlider) {
43528 this.zoomSlider.setValue(this.getZoom());
43529 }
43530 this.drawObjectLayer(false);
43531 break;
43532 }
43533 }
43534 } else {
43535 //if there are no points on the map, zoom to max
43536 this.openlayersMap.zoomTo(0);
43537 if (this.zoomSlider) {
43538 this.zoomSlider.setValue(this.getZoom());
43539 }
43540 this.drawObjectLayer(false);
43541 }
43542 },
43543
43544 removeMarker : function() {
43545 this.markerLayer.removeMarker(this.markerLayer.markers[0]);
43546 },
43547
43548 getLevelOfDetail : function() {
43549 var zoom = Math.floor(this.getZoom());
43550 if (zoom <= 1) {
43551 return 0;
43552 } else if (zoom <= 3) {
43553 return 1;
43554 } else if (zoom <= 8) {
43555 return 2;
43556 } else {
43557 return 3;
43558 }
43559 },
43560
43561
43562 getConfig : function(inquiringWidget){
43563 var mapWidget = this;
43564 var config = {};
43565
43566 //save widget specific configurations here into the config object
43567 config.mapIndex = this.baselayerIndex;
43568 config.mapCenter = this.openlayersMap.center;
43569 config.mapZoom = this.openlayersMap.zoom;
43570 //send config to iquiring widget
43571 if (typeof inquiringWidget.sendConfig !== "undefined"){
43572 inquiringWidget.sendConfig({widgetName: "map", 'config': config});
43573 }
43574 },
43575
43576 setConfig : function(configObj){
43577 var mapWidget = this;
43578
43579 if (configObj.widgetName === "map"){
43580 var config = configObj.config;
43581
43582 //set widgets configuration provided by config
43583 this.setMap(config.mapIndex);
43584 this.gui.mapTypeDropdown.setEntry(config.mapIndex);
43585
43586 this.openlayersMap.setCenter(config.mapCenter);
43587 this.openlayersMap.zoomTo(config.mapZoom);
43588 }
43589 },
43590
43591 }
43592 /*
43593 * TimeConfig.js
43594 *
43595 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
43596 *
43597 * This library is free software; you can redistribute it and/or
43598 * modify it under the terms of the GNU Lesser General Public
43599 * License as published by the Free Software Foundation; either
43600 * version 3 of the License, or (at your option) any later version.
43601 *
43602 * This library is distributed in the hope that it will be useful,
43603 * but WITHOUT ANY WARRANTY; without even the implied warranty of
43604 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
43605 * Lesser General Public License for more details.
43606 *
43607 * You should have received a copy of the GNU Lesser General Public
43608 * License along with this library; if not, write to the Free Software
43609 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
43610 * MA 02110-1301 USA
43611 */
43612
43613 /**
43614 * @class TimeConfig
43615 * Time Configuration File
43616 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
43617 * @release 1.0
43618 * @release date: 2012-07-27
43619 * @version date: 2012-07-27
43620 */
43621 function TimeConfig(options) {
43622
43623 this.options = {
43624 timeTitle : 'GeoTemCo Time View', // title will be shown in timeplot header
43625 timeIndex : 0, // index = position in date array; for multiple dates the 2nd timeplot refers to index 1
43626 timeWidth : false, // false or desired width css definition for the timeplot
43627 timeHeight : '100px', // false or desired height css definition for the timeplot
43628 defaultMinDate : new Date(2012, 0, 1), // required, when empty timelines are possible
43629 defaultMaxDate : new Date(), // required, when empty timelines are possible
43630 timeCanvasFrom : '#EEE', // time widget background gradient color top
43631 timeCanvasTo : '#EEE', // time widget background gradient color bottom
43632 rangeBoxColor : "white", // fill color for time range box
43633 rangeBorder : "1px solid #de7708", // border of frames
43634 dataInformation : true, // show/hide data information
43635 rangeAnimation : true, // show/hide animation buttons
43636 scaleSelection : true, // show/hide scale selection buttons
43637 linearScale : true, // true for linear value scaling, false for logarithmic
43638 unitSelection : true, // show/hide time unit selection dropdown
43639 timeUnit : -1, // minimum temporal unit (SimileAjax.DateTime or -1 if none) of the data
43640 timeMerge : false // if the elements of distinct datasets should be merged into one set or not
43641 };
43642 if ( typeof options != 'undefined') {
43643 $.extend(this.options, options);
43644 }
43645
43646 };
43647 /*
43648 * TimeGui.js
43649 *
43650 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
43651 *
43652 * This library is free software; you can redistribute it and/or
43653 * modify it under the terms of the GNU Lesser General Public
43654 * License as published by the Free Software Foundation; either
43655 * version 3 of the License, or (at your option) any later version.
43656 *
43657 * This library is distributed in the hope that it will be useful,
43658 * but WITHOUT ANY WARRANTY; without even the implied warranty of
43659 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
43660 * Lesser General Public License for more details.
43661 *
43662 * You should have received a copy of the GNU Lesser General Public
43663 * License along with this library; if not, write to the Free Software
43664 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
43665 * MA 02110-1301 USA
43666 */
43667
43668 /**
43669 * @class TimeGui
43670 * Time GUI Implementation
43671 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
43672 * @release 1.0
43673 * @release date: 2012-07-27
43674 * @version date: 2012-07-27
43675 *
43676 * @param {TimeWidget} parent time widget object
43677 * @param {HTML object} div parent div to append the time gui
43678 * @param {JSON} options time configuration
43679 */
43680 function TimeGui(plot, div, options, iid) {
43681
43682 var gui = this;
43683
43684 this.plot = plot;
43685
43686 this.container = div;
43687 if (options.timeWidth) {
43688 this.container.style.width = options.timeWidth;
43689 }
43690 if (options.timeHeight) {
43691 this.container.style.height = options.timeHeight;
43692 }
43693 this.container.style.position = 'relative';
43694
43695 var w = this.container.offsetWidth;
43696 var h = this.container.offsetHeight;
43697
43698 var toolbarTable = document.createElement("table");
43699 toolbarTable.setAttribute('class', 'ddbToolbar');
43700 this.container.appendChild(toolbarTable);
43701
43702 this.plotWindow = document.createElement("div");
43703 this.plotWindow.id = "plotWindow"+iid;
43704 this.plotWindow.setAttribute('class', 'plotWindow');
43705 // this.plotWindow.style.width = w + "px";
43706
43707 this.plotWindow.style.height = (h + 12) + "px";
43708 this.container.style.height = (h + 12) + "px";
43709
43710 this.plotWindow.onmousedown = function() {
43711 return false;
43712 }
43713
43714 this.plotContainer = document.createElement("div");
43715 this.plotContainer.id = "plotContainer"+iid;
43716 this.plotContainer.setAttribute('class', 'plotContainer');
43717 // this.plotContainer.style.width = w + "px";
43718 this.plotContainer.style.height = h + "px";
43719 this.plotContainer.style.position = "absolute";
43720 this.plotContainer.style.zIndex = 0;
43721 this.plotContainer.style.top = "12px";
43722 this.plotWindow.appendChild(this.plotContainer);
43723 this.container.appendChild(this.plotWindow);
43724
43725 this.timeplotDiv = document.createElement("div");
43726 this.timeplotDiv.style.left = "16px";
43727 this.timeplotDiv.style.width = (w - 32) + "px";
43728 this.timeplotDiv.style.height = h + "px";
43729 this.plotContainer.appendChild(this.timeplotDiv);
43730
43731 var cv = document.createElement("canvas");
43732 cv.setAttribute('class', 'plotCanvas');
43733 this.plotWindow.appendChild(cv);
43734 if (!cv.getContext && G_vmlCanvasManager)
43735 cv = G_vmlCanvasManager.initElement(cv);
43736 var ctx = cv.getContext('2d');
43737
43738 var setCanvas = function(){
43739 cv.width = gui.plotWindow.clientWidth;
43740 cv.height = gui.plotWindow.clientHeight;
43741 var gradient = ctx.createLinearGradient(0, 0, 0, gui.plotWindow.clientHeight);
43742 gradient.addColorStop(0, options.timeCanvasFrom);
43743 gradient.addColorStop(1, options.timeCanvasTo);
43744 ctx.fillStyle = gradient;
43745 ctx.fillRect(0, 0, gui.plotWindow.clientWidth, gui.plotWindow.clientHeight);
43746 }
43747 setCanvas();
43748
43749 this.resize = function(){
43750 gui.timeplotDiv.style.width = (gui.container.offsetWidth - 32) + "px";
43751 ctx.clearRect(0,0,gui.plotWindow.clientWidth, gui.plotWindow.clientHeight);
43752 if( typeof plot.datasets != "undefined" ){
43753 plot.redrawPlot();
43754 plot.resetOpacityPlots();
43755 }
43756 setCanvas();
43757 };
43758
43759 var titles = document.createElement("tr");
43760 toolbarTable.appendChild(titles);
43761 var tools = document.createElement("tr");
43762 toolbarTable.appendChild(tools);
43763
43764 this.timeUnitTitle = document.createElement("td");
43765 this.timeUnitTitle.innerHTML = GeoTemConfig.getString('timeUnit');
43766 this.timeUnitSelector = document.createElement("td");
43767 if (options.unitSelection) {
43768 tools.appendChild(this.timeUnitSelector);
43769 titles.appendChild(this.timeUnitTitle);
43770 }
43771
43772 this.timeAnimation = document.createElement("td");
43773 this.timeAnimation.innerHTML = GeoTemConfig.getString('timeAnimation');
43774 var timeAnimationTools = document.createElement("td");
43775
43776 var status;
43777 this.updateAnimationButtons = function(s) {
43778 status = s;
43779 if (status == 0) {
43780 gui.playButton.setAttribute('class', 'smallButton playDisabled');
43781 gui.pauseButton.setAttribute('class', 'smallButton pauseDisabled');
43782 } else if (status == 1) {
43783 gui.playButton.setAttribute('class', 'smallButton playEnabled');
43784 gui.pauseButton.setAttribute('class', 'smallButton pauseDisabled');
43785 } else {
43786 gui.playButton.setAttribute('class', 'smallButton playDisabled');
43787 gui.pauseButton.setAttribute('class', 'smallButton pauseEnabled');
43788 }
43789 };
43790 this.playButton = document.createElement("div");
43791 this.playButton.title = GeoTemConfig.getString('playButton');
43792 timeAnimationTools.appendChild(this.playButton);
43793 this.playButton.onclick = function() {
43794 if (status == 1) {
43795 plot.play();
43796 }
43797 }
43798
43799 this.pauseButton = document.createElement("div");
43800 this.pauseButton.title = GeoTemConfig.getString('pauseButton');
43801 timeAnimationTools.appendChild(this.pauseButton);
43802 this.pauseButton.onclick = function() {
43803 if (status == 2) {
43804 plot.stop();
43805 }
43806 }
43807
43808 this.valueScale = document.createElement("td");
43809 this.valueScale.innerHTML = GeoTemConfig.getString('valueScale');
43810 var valueScaleTools = document.createElement("td");
43811
43812 var linearPlot;
43813 var setValueScale = function(linScale) {
43814 if (linearPlot != linScale) {
43815 linearPlot = linScale;
43816 if (linearPlot) {
43817 gui.linButton.setAttribute('class', 'smallButton linearPlotActivated');
43818 gui.logButton.setAttribute('class', 'smallButton logarithmicPlotDeactivated');
43819 plot.drawLinearPlot();
43820 } else {
43821 gui.linButton.setAttribute('class', 'smallButton linearPlotDeactivated');
43822 gui.logButton.setAttribute('class', 'smallButton logarithmicPlotActivated');
43823 plot.drawLogarithmicPlot();
43824 }
43825 }
43826 };
43827 this.linButton = document.createElement("div");
43828 this.linButton.title = GeoTemConfig.getString('linearPlot');
43829 valueScaleTools.appendChild(this.linButton);
43830 this.linButton.onclick = function() {
43831 setValueScale(true);
43832 }
43833
43834 this.logButton = document.createElement("div");
43835 this.logButton.title = GeoTemConfig.getString('logarithmicPlot');
43836 valueScaleTools.appendChild(this.logButton);
43837 this.logButton.onclick = function() {
43838 setValueScale(false);
43839 }
43840 if (options.rangeAnimation) {
43841 titles.appendChild(this.timeAnimation);
43842 tools.appendChild(timeAnimationTools);
43843 this.updateAnimationButtons(0);
43844 }
43845
43846 if (options.scaleSelection) {
43847 titles.appendChild(this.valueScale);
43848 tools.appendChild(valueScaleTools);
43849 setValueScale(options.linearScale);
43850 }
43851
43852 if (GeoTemConfig.allowFilter) {
43853 this.filterTitle = document.createElement("td");
43854 titles.appendChild(this.filterTitle);
43855 this.filterTitle.innerHTML = GeoTemConfig.getString('filter');
43856 this.filterOptions = document.createElement("td");
43857 tools.appendChild(this.filterOptions);
43858 }
43859
43860 if (options.dataInformation) {
43861 this.infoTitle = document.createElement("td");
43862 this.infoTitle.innerHTML = options.timeTitle;
43863 titles.appendChild(this.infoTitle);
43864 var timeSum = document.createElement("td");
43865 this.timeElements = document.createElement("div");
43866 this.timeElements.setAttribute('class', 'ddbElementsCount');
43867 timeSum.appendChild(this.timeElements);
43868 tools.appendChild(timeSum);
43869 }
43870
43871 /*
43872 var tooltip = document.createElement("div");
43873 tooltip.setAttribute('class','ddbTooltip');
43874 toolbarTable.appendChild(tooltip);
43875
43876 tooltip.onmouseover = function(){
43877 /*
43878 getPublisher().Publish('TooltipContent', {
43879 content: GeoTemConfig.getString(GeoTemConfig.language,'timeHelp'),
43880 target: $(tooltip)
43881 });
43882
43883 }
43884 tooltip.onmouseout = function(){
43885 //getPublisher().Publish('TooltipContent');
43886 }
43887 */
43888
43889 this.setHeight = function() {
43890 this.container.style.height = (this.plotWindow.offsetHeight + toolbarTable.offsetHeight) + "px";
43891 };
43892
43893 this.updateTimeQuantity = function(count) {
43894 if (options.dataInformation) {
43895 this.plotCount = count;
43896 if (count != 1) {
43897 this.timeElements.innerHTML = this.beautifyCount(count) + " " + GeoTemConfig.getString('results');
43898 } else {
43899 this.timeElements.innerHTML = this.beautifyCount(count) + " " + GeoTemConfig.getString('result');
43900 }
43901 }
43902 }
43903
43904 this.setTimeUnitDropdown = function(units) {
43905 $(this.timeUnitSelector).empty();
43906 var gui = this;
43907 var timeUnits = [];
43908 var addUnit = function(unit, index) {
43909 var setUnit = function() {
43910 gui.plot.setTimeUnit(unit.unit);
43911 }
43912 timeUnits.push({
43913 name : unit.label,
43914 onclick : setUnit
43915 });
43916 }
43917 for (var i = 0; i < units.length; i++) {
43918 addUnit(units[i], i);
43919 }
43920 this.timeUnitDropdown = new Dropdown(this.timeUnitSelector, timeUnits, GeoTemConfig.getString('selectTimeUnit'), '100px');
43921 this.timeUnitDropdown.setEntry(0);
43922 }
43923 this.setTimeUnitDropdown([{
43924 name : 'none',
43925 id : -1
43926 }]);
43927
43928 this.beautifyCount = function(count) {
43929 var c = count + '';
43930 var p = 0;
43931 var l = c.length;
43932 while (l - p > 3) {
43933 p += 3;
43934 c = c.substring(0, l - p) + "." + c.substring(l - p);
43935 p++;
43936 l++;
43937 }
43938 return c;
43939 }
43940
43941 this.hideTimeUnitSelection = function() {
43942 this.timeUnitTitle.style.display = 'none';
43943 this.timeUnitSelector.style.display = 'none';
43944 }
43945 };
43946 /*
43947 * TimeWidget.js
43948 *
43949 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
43950 *
43951 * This library is free software; you can redistribute it and/or
43952 * modify it under the terms of the GNU Lesser General Public
43953 * License as published by the Free Software Foundation; either
43954 * version 3 of the License, or (at your option) any later version.
43955 *
43956 * This library is distributed in the hope that it will be useful,
43957 * but WITHOUT ANY WARRANTY; without even the implied warranty of
43958 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
43959 * Lesser General Public License for more details.
43960 *
43961 * You should have received a copy of the GNU Lesser General Public
43962 * License along with this library; if not, write to the Free Software
43963 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
43964 * MA 02110-1301 USA
43965 */
43966
43967 /**
43968 * @class TimeWidget
43969 * TableWidget Implementation
43970 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
43971 * @release 1.0
43972 * @release date: 2012-07-27
43973 * @version date: 2012-07-27
43974 *
43975 * @param {TimeWrapper} core wrapper for interaction to other widgets
43976 * @param {HTML object} div parent div to append the time widget div
43977 * @param {JSON} options user specified configuration that overwrites options in TimeConfig.js
43978 */
43979 TimeWidget = function(core, div, options) {
43980
43981 /* HACK DW: stelle sicher, dass das nicht zweimal aufgerufen wird! */
43982 if (typeof TimeWidget_cont == "undefined"){
43983 TimeWidget_cont="Done";
43984
43985 this.core = core;
43986 this.core.setWidget(this);
43987 this.timeplot
43988 this.dataSources
43989 this.eventSources
43990 this.tds
43991 this.timeGeometry
43992 this.valueGeometry
43993 this.canvas
43994
43995 this.leftFlagPole
43996 this.rightFlagPole
43997 this.rangeBox
43998 this.leftHandle
43999 this.rightHandle
44000
44001 this.leftFlagPos = null;
44002 this.leftFlagTime = null;
44003 this.rightFlagPos = null;
44004 this.rightFlagTime = null;
44005
44006 this.mouseDownTime
44007 this.mouseUpTime
44008 this.mouseTempTime
44009 this.mouseDownPos
44010 this.mouseUpPos
44011 this.mouseTempPos
44012
44013 this.status
44014 this.slider
44015
44016 this.iid = GeoTemConfig.getIndependentId('time');
44017 this.options = (new TimeConfig(options)).options;
44018 this.gui = new TimeGui(this, div, this.options, this.iid);
44019 this.initialize();
44020
44021 }
44022 }
44023 TimeWidget.prototype = {
44024
44025 /**
44026 * clears the timeplot canvas and the timeGeometry properties
44027 */
44028 clearTimeplot : function() {
44029 this.timeplot._clearCanvas();
44030 this.timeGeometry._earliestDate = null;
44031 this.timeGeometry._latestDate = null;
44032 this.valueGeometry._minValue = 0;
44033 this.valueGeometry._maxValue = 0;
44034 this.highlightedSlice = undefined;
44035 this.timeGeometry._clearLabels();
44036 this.selection = new Selection();
44037 },
44038
44039 /**
44040 * initializes the timeplot elements with arrays of time objects
44041 * @param {TimeObject[][]} timeObjects an array of time objects from different (1-4) sets
44042 */
44043 initWidget : function(datasets) {
44044 this.datasets = datasets;
44045 var timeObjects = [];
44046 for (var i = 0; i < datasets.length; i++) {
44047 timeObjects.push(datasets[i].objects);
44048 }
44049 this.clearTimeplot();
44050 this.reset();
44051 for (var i = 0; i < this.timeplot._plots.length; i++) {
44052 this.timeplot._plots[i].dispose();
44053 }
44054 this.dataSources = new Array();
44055 this.plotInfos = new Array();
44056 this.eventSources = new Array();
44057 var granularity = 0;
44058 this.count = 0;
44059 for (var i = 0; i < timeObjects.length; i++) {
44060 if( i==0 || !this.options.timeMerge ){
44061 var eventSource = new Timeplot.DefaultEventSource();
44062 var dataSource = new Timeplot.ColumnSource(eventSource, 1);
44063 this.dataSources.push(dataSource);
44064 this.eventSources.push(eventSource);
44065 var c = GeoTemConfig.getColor(i);
44066 var plotInfo = Timeplot.createPlotInfo({
44067 id : "plot" + i,
44068 dataSource : dataSource,
44069 timeGeometry : this.timeGeometry,
44070 valueGeometry : this.valueGeometry,
44071 fillGradient : false,
44072 lineColor : 'rgba(' + c.r1 + ',' + c.g1 + ',' + c.b1 + ', 1)',
44073 fillColor : 'rgba(' + c.r0 + ',' + c.g0 + ',' + c.b0 + ', 0.3)',
44074 showValues : true
44075 });
44076 this.plotInfos.push(plotInfo);
44077 }
44078 for (var j = 0; j < timeObjects[i].length; j++) {
44079 var o = timeObjects[i][j];
44080 if (o.isTemporal) {
44081 var g = o.dates[this.options.timeIndex].granularity;
44082 if (g == null) {
44083 continue;
44084 } else if (g > granularity) {
44085 granularity = g;
44086 }
44087 this.count += o.weight;
44088 }
44089 }
44090 }
44091 this.timeGeometry._granularity = granularity;
44092 this.timeGeometry._clearLabels();
44093 this.timeplot.resetPlots(this.plotInfos);
44094 if (this.plotInfos.length == 0) {
44095 this.initLabels(this.timeplot.regularGrid());
44096 return;
44097 }
44098 this.timeGeometry.extendedDataSource = this.tds;
44099 this.tds.initialize(this.dataSources, this.eventSources, timeObjects, granularity, this.options.timeUnit, this.gui.timeplotDiv.offsetWidth);
44100 this.gui.setTimeUnitDropdown(this.tds.availableUnits);
44101 this.gui.timeUnitDropdown.setEntry(this.tds.getUnitIndex());
44102 var plots = this.timeplot._plots;
44103 for (var i = 0; i < plots.length; i++) {
44104 plots[i].pins = [];
44105 plots[i].style = this.style;
44106 for (var j = 0; j < this.tds.getSliceNumber(); j++) {
44107 plots[i].pins.push({
44108 height : 0,
44109 count : 0
44110 });
44111 }
44112 }
44113 /*
44114 var levels = Math.round( (this.tds.timeSlices.length-3)/2 );
44115 if( GeoTemConfig.timeZoom ){
44116 this.zoomSlider.setMaxAndLevels(levels,levels);
44117 }
44118 */
44119 this.timeplot.repaint();
44120 this.timeplot._resizeCanvas();
44121 // set maximum number of slider steps
44122 var slices = this.tds.timeSlices.length;
44123 var numSlices = Math.floor(slices / this.canvas.width * this.canvas.height + 0.5);
44124
44125 this.initLabels([]);
44126 this.initOverview();
44127 this.gui.updateTimeQuantity(this.count);
44128
44129 },
44130
44131 setTimeUnit : function(unit) {
44132 this.clearTimeplot();
44133 this.reset();
44134 this.tds.setTimeUnit(unit);
44135 var plots = this.timeplot._plots;
44136 for (var i = 0; i < plots.length; i++) {
44137 plots[i].pins = [];
44138 plots[i].style = this.style;
44139 for (var j = 0; j < this.tds.getSliceNumber(); j++) {
44140 plots[i].pins.push({
44141 height : 0,
44142 count : 0
44143 });
44144 }
44145 }
44146 this.initLabels([]);
44147 },
44148
44149 /**
44150 * initializes the timeplot for the Spatio Temporal Interface.
44151 * all elements (including their events) that are needed for user interaction are instantiated here, the slider element as well
44152 */
44153 initialize : function() {
44154
44155 this.status = 0;
44156 this.selection = new Selection();
44157 this.paused = true;
44158 this.dataSources = new Array();
44159 this.plotInfos = new Array();
44160 this.eventSources = new Array();
44161 this.timeGeometry = new Timeplot.DefaultTimeGeometry({
44162 gridColor : "#000000",
44163 axisLabelsPlacement : "top"
44164 });
44165 this.style = 'graph';
44166 this.timeGeometry._hideLabels = true;
44167 this.timeGeometry._granularity = 0;
44168 this.valueGeometry = new Timeplot.LogarithmicValueGeometry({
44169 min : 0
44170 });
44171 this.valueGeometry.actLinear();
44172
44173 var plot = this;
44174
44175 this.timeplot = Timeplot.create(this.gui.timeplotDiv, this.plotInfos);
44176 this.tds = new TimeDataSource(this.options);
44177
44178 this.canvas = this.timeplot.getCanvas();
44179
44180 this.leftFlagPole = this.timeplot.putDiv("leftflagpole", "timeplot-dayflag-pole");
44181 this.rightFlagPole = this.timeplot.putDiv("rightflagpole", "timeplot-dayflag-pole");
44182 SimileAjax.Graphics.setOpacity(this.leftFlagPole, 50);
44183 SimileAjax.Graphics.setOpacity(this.rightFlagPole, 50);
44184
44185 this.rangeBox = this.timeplot.putDiv("rangebox", "range-box");
44186 this.rangeBox.style.backgroundColor = plot.options.rangeBoxColor;
44187 this.rangeBox.style.border = plot.options.rangeBorder;
44188
44189 this.leftHandle = document.createElement("div");
44190 this.rightHandle = document.createElement("div");
44191 this.gui.plotWindow.appendChild(this.leftHandle);
44192 this.gui.plotWindow.appendChild(this.rightHandle);
44193 this.leftHandle.title = GeoTemConfig.getString('leftHandle');
44194 this.rightHandle.title = GeoTemConfig.getString('rightHandle');
44195
44196 this.leftHandle.style.backgroundImage = "url(" + GeoTemConfig.path + "leftHandle.png" + ")";
44197 this.leftHandle.setAttribute('class', 'plotHandle plotHandleIcon');
44198 this.rightHandle.style.backgroundImage = "url(" + GeoTemConfig.path + "rightHandle.png" + ")";
44199 this.rightHandle.setAttribute('class', 'plotHandle plotHandleIcon');
44200
44201 this.poles = this.timeplot.putDiv("poles", "pole");
44202 this.timeplot.placeDiv(this.poles, {
44203 left : 0,
44204 bottom : 0,
44205 width : this.canvas.width,
44206 height : this.canvas.height,
44207 display : "block"
44208 });
44209 this.poles.appendChild(document.createElement("canvas"));
44210
44211 this.filterBar = new FilterBar(this, this.gui.filterOptions);
44212
44213 var plot = this;
44214
44215 this.dragButton = document.createElement("div");
44216 this.dragButton.title = GeoTemConfig.getString('dragTimeRange');
44217 this.cancelButton = document.createElement("div");
44218 this.cancelButton.title = GeoTemConfig.getString('clearSelection');
44219 this.cancelButton.onclick = function() {
44220 plot.deselection();
44221 }
44222
44223 this.toolbar = document.createElement("div");
44224 this.toolbar.setAttribute('class', 'plotToolbar');
44225 this.toolbar.style.borderTop = plot.options.rangeBorder;
44226 this.toolbar.style.textAlign = "center";
44227 this.gui.plotWindow.appendChild(this.toolbar);
44228
44229 this.toolbarAbsoluteDiv = document.createElement("div");
44230 this.toolbarAbsoluteDiv.setAttribute('class', 'absoluteToolbar');
44231 this.toolbar.appendChild(this.toolbarAbsoluteDiv);
44232
44233 this.dragButton.setAttribute('class', 'dragTimeRangeAlt');
44234 this.dragButton.style.backgroundImage = "url(" + GeoTemConfig.path + "drag.png" + ")";
44235 // this.zoomButton.setAttribute('class','zoomRangeAlt');
44236 this.cancelButton.setAttribute('class', 'cancelRangeAlt');
44237 this.toolbarAbsoluteDiv.appendChild(this.dragButton);
44238 this.toolbarAbsoluteDiv.style.width = this.dragButton.offsetWidth + "px";
44239 // this.gui.plotWindow.appendChild(this.zoomButton);
44240 this.gui.plotWindow.appendChild(this.cancelButton);
44241
44242 this.overview = document.createElement("div");
44243 this.overview.setAttribute('class', 'timeOverview');
44244 this.gui.plotWindow.appendChild(this.overview);
44245
44246 var mousedown = false;
44247 this.shift = function(shift) {
44248 if (!mousedown) {
44249 return;
44250 }
44251 if (plot.tds.setShift(shift)) {
44252 plot.redrawPlot();
44253 }
44254 setTimeout(function() {
44255 plot.shift(shift);
44256 }, 200);
44257 }
44258 var shiftPressed = function(shift) {
44259 mousedown = true;
44260 document.onmouseup = function() {
44261 mousedown = false;
44262 document.onmouseup = null;
44263 }
44264 plot.shift(shift);
44265 }
44266
44267 this.shiftLeft = document.createElement("div");
44268 this.shiftLeft.setAttribute('class', 'shiftLeft');
44269 this.gui.plotWindow.appendChild(this.shiftLeft);
44270 this.shiftLeft.onmousedown = function() {
44271 shiftPressed(1);
44272 }
44273
44274 this.shiftRight = document.createElement("div");
44275 this.shiftRight.setAttribute('class', 'shiftRight');
44276 this.gui.plotWindow.appendChild(this.shiftRight);
44277 this.shiftRight.onmousedown = function() {
44278 shiftPressed(-1);
44279 }
44280
44281 this.plotLabels = document.createElement("div");
44282 this.plotLabels.setAttribute('class', 'plotLabels');
44283 this.gui.plotWindow.appendChild(this.plotLabels);
44284
44285 this.initLabels(this.timeplot.regularGrid());
44286
44287 //Finds the time corresponding to the position x on the timeplot
44288 var getCorrelatedTime = function(x) {
44289 if (x >= plot.canvas.width)
44290 x = plot.canvas.width;
44291 if (isNaN(x) || x < 0)
44292 x = 0;
44293 var t = plot.timeGeometry.fromScreen(x);
44294 if (t == 0)
44295 return;
44296 return plot.dataSources[0].getClosestValidTime(t);
44297 }
44298 //Finds the position corresponding to the time t on the timeplot
44299 var getCorrelatedPosition = function(t) {
44300 var x = plot.timeGeometry.toScreen(t);
44301 if (x >= plot.canvas.width)
44302 x = plot.canvas.width;
44303 if (isNaN(x) || x < 0)
44304 x = 0;
44305 return x;
44306 }
44307 //Maps the 2 positions in the right order to left and right bound of the chosen timeRange
44308 var mapPositions = function(pos1, pos2) {
44309 if (pos1 > pos2) {
44310 plot.leftFlagPos = pos2;
44311 plot.rightFlagPos = pos1;
44312 } else {
44313 plot.leftFlagPos = pos1;
44314 plot.rightFlagPos = pos2;
44315 }
44316 plot.leftFlagTime = plot.dataSources[0].getClosestValidTime(plot.timeGeometry.fromScreen(plot.leftFlagPos));
44317 plot.rightFlagTime = plot.dataSources[0].getClosestValidTime(plot.timeGeometry.fromScreen(plot.rightFlagPos));
44318 }
44319 //Sets the divs corresponding to the actual chosen timeRange
44320 var setRangeDivs = function() {
44321 plot.leftFlagPole.style.visibility = "visible";
44322 plot.rightFlagPole.style.visibility = "visible";
44323 plot.rangeBox.style.visibility = "visible";
44324 plot.timeplot.placeDiv(plot.leftFlagPole, {
44325 left : plot.leftFlagPos,
44326 bottom : 0,
44327 height : plot.canvas.height,
44328 display : "block"
44329 });
44330 plot.timeplot.placeDiv(plot.rightFlagPole, {
44331 left : plot.rightFlagPos,
44332 bottom : 0,
44333 height : plot.canvas.height,
44334 display : "block"
44335 });
44336 var boxWidth = plot.rightFlagPos - plot.leftFlagPos;
44337 if (plot.popup) {
44338 plot.popupClickDiv.style.visibility = "visible";
44339 plot.timeplot.placeDiv(plot.popupClickDiv, {
44340 left : plot.leftFlagPos,
44341 width : boxWidth + 1,
44342 height : plot.canvas.height,
44343 display : "block"
44344 });
44345 }
44346 plot.timeplot.placeDiv(plot.rangeBox, {
44347 left : plot.leftFlagPos,
44348 width : boxWidth + 1,
44349 height : plot.canvas.height,
44350 display : "block"
44351 });
44352 var plots = plot.timeplot._plots;
44353 for ( i = 0; i < plots.length; i++) {
44354 plots[i].fullOpacityPlot(plot.leftFlagTime, plot.rightFlagTime, plot.leftFlagPos, plot.rightFlagPos, GeoTemConfig.getColor(i));
44355 plots[i].opacityPlot.style.visibility = "visible";
44356 }
44357 var unit = plot.tds.unit;
44358
44359 var top = plot.gui.plotContainer.offsetTop;
44360 var left = plot.gui.plotContainer.offsetLeft;
44361 var leftPos = plot.leftFlagPole.offsetLeft + plot.timeplot.getElement().offsetLeft;
44362 var rightPos = plot.rightFlagPole.offsetLeft + plot.timeplot.getElement().offsetLeft;
44363 var rW = rightPos - leftPos;
44364 var pW = plot.canvas.width;
44365 var pL = plot.timeplot.getElement().offsetLeft;
44366
44367 var handleTop = top + Math.floor(plot.gui.timeplotDiv.offsetHeight / 2 - plot.leftHandle.offsetHeight / 2);
44368 plot.leftHandle.style.visibility = "visible";
44369 plot.rightHandle.style.visibility = "visible";
44370 plot.leftHandle.style.left = (leftPos - plot.leftHandle.offsetWidth / 2) + "px";
44371 plot.rightHandle.style.left = (rightPos - plot.rightHandle.offsetWidth + 1 + plot.rightHandle.offsetWidth / 2) + "px";
44372 plot.leftHandle.style.top = handleTop + "px";
44373 plot.rightHandle.style.top = handleTop + "px";
44374 if (rightPos == leftPos) {
44375 plot.rightHandle.style.visibility = "hidden";
44376 plot.leftHandle.style.backgroundImage = "url(" + GeoTemConfig.path + "mergedHandle.png" + ")";
44377 } else {
44378 plot.leftHandle.style.backgroundImage = "url(" + GeoTemConfig.path + "leftHandle.png" + ")";
44379 }
44380 plot.cancelButton.style.visibility = "visible";
44381 plot.cancelButton.style.top = top + "px";
44382
44383 if (rW > plot.cancelButton.offsetWidth) {
44384 plot.cancelButton.style.left = (left + rightPos - plot.cancelButton.offsetWidth) + "px";
44385 } else {
44386 plot.cancelButton.style.left = (left + rightPos) + "px";
44387 }
44388 var tW = plot.toolbarAbsoluteDiv.offsetWidth;
44389 if (rW >= tW) {
44390 plot.toolbar.style.left = leftPos + "px";
44391 plot.toolbar.style.width = (rW + 1) + "px";
44392 plot.toolbarAbsoluteDiv.style.left = ((rW - tW) / 2) + "px";
44393 } else {
44394 plot.toolbar.style.left = (pL + plot.leftFlagPos * (pW - tW) / (pW - rW)) + "px";
44395 plot.toolbar.style.width = (tW + 2) + "px";
44396 plot.toolbarAbsoluteDiv.style.left = "0px";
44397 }
44398 plot.toolbar.style.top = (top + plot.timeplot.getElement().offsetHeight) + "px";
44399 plot.toolbar.style.visibility = "visible";
44400 plot.toolbarAbsoluteDiv.style.visibility = "visible";
44401
44402 }
44403 var getAbsoluteLeft = function(div) {
44404 var left = 0;
44405 while (div) {
44406 left += div.offsetLeft;
44407 div = div.offsetParent;
44408 }
44409 return left;
44410 }
44411 var timeplotLeft = getAbsoluteLeft(plot.timeplot.getElement());
44412
44413 var checkPolesForStyle = function(x) {
44414 if (plot.style == 'bars' && plot.leftFlagTime == plot.rightFlagTime) {
44415 var index = plot.tds.getSliceIndex(plot.leftFlagTime);
44416 var time1 = plot.leftFlagTime;
44417 var pos1 = plot.leftFlagPos;
44418 var time2, pos2;
44419 if (index == 0) {
44420 time2 = plot.tds.getSliceTime(index + 1);
44421 } else if (index == plot.tds.getSliceNumber() - 1) {
44422 time2 = plot.tds.getSliceTime(index - 1);
44423 } else {
44424 if (x < plot.leftFlagPos) {
44425 time2 = plot.tds.getSliceTime(index - 1);
44426 } else {
44427 time2 = plot.tds.getSliceTime(index + 1);
44428 }
44429 }
44430 pos2 = plot.timeGeometry.toScreen(time2);
44431 mapPositions(pos1, pos2, time1, time2);
44432 }
44433 }
44434 var startX, startY, multiplier;
44435
44436 // mousemove function that causes moving selection of objects and toolbar divs
44437 var moveToolbar = function(start, actual) {
44438 var pixelShift = actual - start;
44439 if (plot.status == 2) {
44440 var newTime = getCorrelatedTime(startX + pixelShift);
44441 if (newTime == plot.mouseTempTime) {
44442 return;
44443 }
44444 plot.mouseTempTime = newTime;
44445 plot.mouseTempPos = plot.timeGeometry.toScreen(plot.mouseTempTime);
44446 mapPositions(plot.mouseDownPos, plot.mouseTempPos);
44447 } else if (plot.status == 3) {
44448 pixelShift *= multiplier;
44449 var plotPos = actual - timeplotLeft;
44450 if (plotPos <= plot.canvas.width / 2) {
44451 var newTime = getCorrelatedTime(startX + pixelShift);
44452 if (newTime == plot.leftFlagTime) {
44453 return;
44454 }
44455 plot.leftFlagTime = newTime;
44456 var diff = plot.leftFlagPos;
44457 plot.leftFlagPos = plot.timeGeometry.toScreen(plot.leftFlagTime);
44458 diff -= plot.leftFlagPos;
44459 plot.rightFlagTime = getCorrelatedTime(plot.rightFlagPos - diff);
44460 plot.rightFlagPos = plot.timeGeometry.toScreen(plot.rightFlagTime);
44461 } else {
44462 var newTime = getCorrelatedTime(startY + pixelShift);
44463 if (newTime == plot.rightFlagTime) {
44464 return;
44465 }
44466 plot.rightFlagTime = newTime;
44467 var diff = plot.rightFlagPos;
44468 plot.rightFlagPos = plot.timeGeometry.toScreen(plot.rightFlagTime);
44469 diff -= plot.rightFlagPos;
44470 plot.leftFlagTime = getCorrelatedTime(plot.leftFlagPos - diff);
44471 plot.leftFlagPos = plot.timeGeometry.toScreen(plot.leftFlagTime);
44472 }
44473 }
44474 checkPolesForStyle(actual - timeplotLeft);
44475 setRangeDivs();
44476 plot.timeSelection();
44477 }
44478 // fakes user interaction mouse move
44479 var playIt = function(start, actual, reset) {
44480 if (!plot.paused) {
44481 var pixel = plot.canvas.width / (plot.tds.timeSlices.length - 1 ) / 5;
44482 var wait = 20 * pixel;
44483 if (reset) {
44484 actual = 0;
44485 }
44486 moveToolbar(start, actual);
44487 if (plot.rightFlagPos >= plot.canvas.width) {
44488 reset = true;
44489 wait = 1000;
44490 } else {
44491 reset = false;
44492 }
44493 setTimeout(function() {
44494 playIt(start, actual + pixel, reset)
44495 }, wait);
44496 }
44497 }
44498 var setMultiplier = function() {
44499 var rangeWidth = plot.rightFlagPos - plot.leftFlagPos;
44500 var toolbarWidth = plot.toolbarAbsoluteDiv.offsetWidth;
44501 var plotWidth = plot.canvas.width;
44502 if (rangeWidth < toolbarWidth) {
44503 multiplier = (plotWidth - rangeWidth) / (plotWidth - toolbarWidth);
44504 } else {
44505 multiplier = 1;
44506 }
44507 }
44508 /**
44509 * starts the animation
44510 */
44511 this.play = function() {
44512 if (this.leftFlagPos == null) {
44513 return;
44514 }
44515 plot.paused = false;
44516 plot.gui.updateAnimationButtons(2);
44517 plot.status = 3;
44518 setMultiplier();
44519 startX = plot.leftFlagPos;
44520 startY = plot.rightFlagPos;
44521 var position = Math.round(plot.leftFlagPos);
44522 playIt(position, position + 1, false);
44523 }
44524 /**
44525 * stops the animation
44526 */
44527 this.stop = function() {
44528 plot.paused = true;
44529 plot.status = 0;
44530 plot.gui.updateAnimationButtons(1);
44531 }
44532 // triggers the mousemove function to move the range and toolbar
44533 var toolbarEvent = function(evt) {
44534 var left = GeoTemConfig.getMousePosition(evt).left;
44535 document.onmousemove = function(evt) {
44536 moveToolbar(left, GeoTemConfig.getMousePosition(evt).left);
44537 if (plot.popup) {
44538 plot.popup.reset();
44539 }
44540 }
44541 }
44542 var initializeLeft = function() {
44543 plot.mouseDownTime = plot.rightFlagTime;
44544 plot.mouseTempTime = plot.leftFlagTime;
44545 plot.mouseDownPos = plot.timeGeometry.toScreen(plot.mouseDownTime);
44546 startX = plot.leftFlagPos;
44547 }
44548 var initializeRight = function() {
44549 plot.mouseDownTime = plot.leftFlagTime;
44550 plot.mouseTempTime = plot.rightFlagTime;
44551 plot.mouseDownPos = plot.timeGeometry.toScreen(plot.mouseDownTime);
44552 startX = plot.rightFlagPos;
44553 }
44554 var initializeDrag = function() {
44555 startX = plot.leftFlagPos;
44556 startY = plot.rightFlagPos;
44557 setMultiplier();
44558 }
44559 var checkBorders = function() {
44560 if (plot.style == 'bars' && plot.mouseUpTime == plot.mouseDownTime) {
44561 var index = plot.tds.getSliceIndex(plot.mouseUpTime);
44562 if (index == 0) {
44563 plot.mouseUpTime = plot.tds.getSliceTime(index + 1);
44564 } else if (index == plot.tds.getSliceNumber() - 1) {
44565 plot.mouseUpTime = plot.tds.getSliceTime(index - 1);
44566 } else {
44567 if (plot.x < plot.leftFlagPos) {
44568 plot.mouseUpTime = plot.tds.getSliceTime(index - 1);
44569 } else {
44570 plot.mouseUpTime = plot.tds.getSliceTime(index + 1);
44571 }
44572 }
44573 }
44574 }
44575 // handles mousedown on left handle
44576 this.leftHandle.onmousedown = function(evt) {
44577 if (plot.status != 2) {
44578
44579 initializeLeft();
44580 plot.status = 2;
44581 toolbarEvent(evt);
44582 document.onmouseup = function() {
44583 document.onmousemove = null;
44584 document.onmouseup = null;
44585 plot.stop();
44586 }
44587 }
44588 }
44589 // handles mousedown on right handle
44590 this.rightHandle.onmousedown = function(evt) {
44591 if (plot.status != 2) {
44592 initializeRight();
44593 plot.status = 2;
44594 toolbarEvent(evt);
44595 document.onmouseup = function() {
44596 document.onmousemove = null;
44597 document.onmouseup = null;
44598 plot.stop();
44599 }
44600 }
44601 }
44602 // handles mousedown on drag button
44603 this.dragButton.onmousedown = function(evt) {
44604 if (plot.status != 3) {
44605 plot.status = 3;
44606 initializeDrag();
44607 toolbarEvent(evt);
44608 document.onmouseup = function() {
44609 document.onmousemove = null;
44610 document.onmouseup = null;
44611 plot.stop();
44612 }
44613 }
44614 }
44615 // handles mousedown-Event on timeplot
44616 var mouseDownHandler = function(elmt, evt, target) {
44617 if (plot.dataSources.length > 0) {
44618
44619 plot.x = Math.round(SimileAjax.DOM.getEventRelativeCoordinates(evt, plot.canvas).x);
44620 if (plot.status == 0) {
44621 var time = getCorrelatedTime(plot.x);
44622 if (plot.leftFlagPos != null && plot.popup && time >= plot.leftFlagTime && time <= plot.rightFlagTime) {
44623 var x = plot.leftFlagPos + (plot.rightFlagPos - plot.leftFlagPos) / 2;
44624 var elements = [];
44625 for (var i = 0; i < plot.dataSources.length; i++) {
44626 elements.push([]);
44627 }
44628 for (var i = 0; i < plot.selectedObjects.length; i++) {
44629 if (plot.selectedObjects[i].value == 1) {
44630 for (var j = 0; j < plot.selectedObjects[i].objects.length; j++) {
44631 elements[j] = elements[j].concat(plot.selectedObjects[i].objects[j]);
44632 }
44633 }
44634 }
44635 var labels = [];
44636 for (var i = 0; i < elements.length; i++) {
44637 if (elements[i].length == 0) {
44638 continue;
44639 }
44640 var c = GeoTemConfig.getColor(i);
44641 var color = 'rgb(' + c.r0 + ',' + c.g0 + ',' + c.b0 + ')';
44642 var div = document.createElement("div");
44643 div.setAttribute('class', 'tagCloudItem');
44644 div.style.color = color;
44645 var label = {
44646 div : div,
44647 elements : elements[i]
44648 };
44649 var weight = 0;
44650 for (j in elements[i] ) {
44651 weight += elements[i][j].weight;
44652 }
44653 var fs = 2 * weight / 1000;
44654 if (fs > 2) {
44655 fs = 2;
44656 }
44657 div.style.fontSize = (1 + fs) + "em";
44658 div.style.textShadow = "0 0 0.4em black, 0 0 0.4em black, 0 0 0.4em black, 0 0 0.4em " + c.hex;
44659 if (weight == 1) {
44660 div.innerHTML = weight + " object";
44661 } else {
44662 div.innerHTML = weight + " objects";
44663 }
44664 var appendMouseFunctions = function(label, div, color) {
44665 div.onclick = function() {
44666 plot.popup.showLabelContent(label);
44667 div.style.textShadow = "0 0 0.4em black, 0 0 0.4em black, 0 0 0.4em black, 0 0 0.4em " + color;
44668 }
44669 div.onmouseover = function() {
44670 div.style.textShadow = "0 -1px " + color + ", 1px 0 " + color + ", 0 1px " + color + ", -1px 0 " + color;
44671 }
44672 div.onmouseout = function() {
44673 div.style.textShadow = "0 0 0.4em black, 0 0 0.4em black, 0 0 0.4em black, 0 0 0.4em " + color;
44674 }
44675 }
44676 appendMouseFunctions(label, div, c.hex);
44677 labels.push(label);
44678 }
44679 if (labels.length > 0) {
44680 plot.popup.createPopup(x + 20, 0, labels);
44681 }
44682 } else {
44683 plot.deselection();
44684 plot.status = 1;
44685 plot.mouseDownTime = time;
44686 plot.mouseTempTime = plot.mouseDownTime;
44687 plot.mouseDownPos = plot.timeGeometry.toScreen(plot.mouseDownTime);
44688 mapPositions(plot.mouseDownPos, plot.mouseDownPos, plot.mouseDownTime, plot.mouseDownTime);
44689 // handles mouseup-Event on timeplot
44690 document.onmouseup = function() {
44691 if (plot.status == 1) {
44692 plot.mouseUpTime = plot.mouseTempTime;
44693 plot.mouseUpPos = plot.timeGeometry.toScreen(plot.mouseUpTime);
44694 mapPositions(plot.mouseDownPos, plot.mouseUpPos, plot.mouseDownTime, plot.mouseUpTime);
44695 checkPolesForStyle(plot.x);
44696 setRangeDivs();
44697 plot.timeSelection();
44698 plot.gui.updateAnimationButtons(1);
44699 document.onmouseup = null;
44700 plot.status = 0;
44701 }
44702 }
44703 }
44704 }
44705 }
44706 }
44707 // handles mousemove-Event on timeplot
44708 var mouseMoveHandler = function(elmt, evt, target) {
44709 if (plot.dataSources.length > 0) {
44710 plot.x = Math.round(SimileAjax.DOM.getEventRelativeCoordinates(evt, plot.canvas).x);
44711 if (plot.status == 1) {
44712 plot.mouseTempTime = getCorrelatedTime(plot.x);
44713 plot.mouseTempPos = plot.timeGeometry.toScreen(plot.mouseTempTime);
44714 mapPositions(plot.mouseDownPos, plot.mouseTempPos, plot.mouseDownTime, plot.mouseTempTime);
44715 checkPolesForStyle(plot.x);
44716 setRangeDivs();
44717 }
44718 }
44719 }
44720 // handles mouseout-Event on timeplot
44721 var mouseOutHandler = function(elmt, evt, target) {
44722 if (plot.dataSources.length > 0) {
44723 var x = Math.round(SimileAjax.DOM.getEventRelativeCoordinates(evt, plot.canvas).x);
44724 var y = Math.round(SimileAjax.DOM.getEventRelativeCoordinates(evt, plot.canvas).y);
44725 if (x > plot.canvas.width - 2 || isNaN(x) || x < 2) {
44726 plot.timeHighlight(true);
44727 plot.highlightedSlice = undefined;
44728 } else if (y > plot.canvas.height - 2 || isNaN(y) || y < 2) {
44729 plot.timeHighlight(true);
44730 plot.highlightedSlice = undefined;
44731 }
44732 }
44733 }
44734 // handles mouse(h)over-Event on timeplot
44735 var mouseHoverHandler = function(elmt, evt, target) {
44736 if (plot.dataSources.length > 0) {
44737 var x = Math.round(SimileAjax.DOM.getEventRelativeCoordinates(evt, plot.canvas).x);
44738 var time = getCorrelatedTime(x);
44739 if (time == undefined) {
44740 return;
44741 }
44742 var highlightSlice;
44743 var slices = plot.tds.timeSlices;
44744 var index = plot.tds.getSliceIndex(time);
44745 if (plot.style == 'graph') {
44746 highlightSlice = slices[index];
44747 }
44748 if (plot.style == 'bars') {
44749 var pos = plot.timeGeometry.toScreen(time);
44750 if (x < pos && index > 0) {
44751 highlightSlice = slices[index - 1];
44752 } else {
44753 highlightSlice = slices[index];
44754 }
44755 }
44756 if (plot.highlightedSlice == undefined || plot.highlightedSlice != highlightSlice) {
44757 plot.highlightedSlice = highlightSlice;
44758 plot.timeHighlight(false);
44759 }
44760 }
44761 }
44762
44763 this.redrawPlot = function() {
44764 plot.clearTimeplot();
44765 plot.tds.reset(this.timeGeometry);
44766 plot.timeplot._prepareCanvas();
44767 plot.timeplot.repaint();
44768 if (plot.leftFlagPos != null) {
44769 plot.leftFlagPos = getCorrelatedPosition(plot.leftFlagTime);
44770 plot.rightFlagPos = getCorrelatedPosition(plot.rightFlagTime);
44771 setRangeDivs();
44772 } else {
44773 plot.displayOverlay();
44774 }
44775 plot.initLabels([]);
44776 plot.updateOverview();
44777 }
44778
44779 this.resetOpacityPlots = function() {
44780 var plots = plot.timeplot._plots;
44781 for ( var i = 0; i < plots.length; i++) {
44782 plots[i]._opacityCanvas.width = this.canvas.width;
44783 plots[i]._opacityCanvas.height = this.canvas.height;
44784 if( plot.leftFlagTime != null ){
44785 plots[i].fullOpacityPlot(plot.leftFlagTime, plot.rightFlagTime, plot.leftFlagPos, plot.rightFlagPos, GeoTemConfig.getColor(i));
44786 }
44787 }
44788 }
44789
44790 /**
44791 * handles zoom of the timeplot
44792 * @param {int} delta the change of zoom
44793 * @param {Date} time a time that corresponds to a slice, that was clicked
44794 */
44795 /*
44796 this.zoom = function(delta,time){
44797 if( this.eventSources.length == 0 ){
44798 if( GeoTemConfig.timeZoom ){
44799 this.zoomSlider.setValue(0);
44800 }
44801 return false;
44802 }
44803 if( time == null ){
44804 time = getCorrelatedTime(this.canvas.width/2);
44805 }
44806 if( this.tds.setZoom(delta,time,this.leftFlagTime,this.rightFlagTime) ){
44807 this.redrawPlot();
44808 }
44809 if( GeoTemConfig.timeZoom ){
44810 this.zoomSlider.setValue(this.tds.getZoom());
44811 }
44812 return true;
44813 }
44814 */
44815
44816 // handles mousewheel event on the timeplot
44817 var mouseWheelHandler = function(elmt, evt, target) {
44818 if (evt.preventDefault) {
44819 evt.preventDefault();
44820 }
44821 if (plot.dataSources.length == 0) {
44822 return;
44823 }
44824 var delta = 0;
44825 if (!evt)
44826 evt = window.event;
44827 if (evt.wheelDelta) {
44828 delta = evt.wheelDelta / 120;
44829 if (window.opera)
44830 delta = -delta;
44831 } else if (evt.detail) {
44832 delta = -evt.detail / 3;
44833 }
44834 if (delta) {
44835 var x = Math.round(SimileAjax.DOM.getEventRelativeCoordinates(evt, plot.canvas).x);
44836 var time = getCorrelatedTime(x);
44837 plot.zoom(delta, time);
44838 }
44839 }
44840 var timeplotElement = this.timeplot.getElement();
44841 SimileAjax.DOM.registerEvent(timeplotElement, "mousedown", mouseDownHandler);
44842 SimileAjax.DOM.registerEvent(timeplotElement, "mousemove", mouseMoveHandler);
44843 SimileAjax.DOM.registerEvent(timeplotElement, "mousemove", mouseHoverHandler);
44844 SimileAjax.DOM.registerEvent(timeplotElement, "mouseout", mouseOutHandler);
44845 if (GeoTemConfig.mouseWheelZoom) {
44846 //SimileAjax.DOM.registerEvent(timeplotElement, "mousewheel", mouseWheelHandler);
44847 }
44848
44849 this.gui.setHeight();
44850
44851 },
44852
44853 resetOverlay : function() {
44854 this.poles.style.visibility = "hidden";
44855 var plots = this.timeplot._plots;
44856 for (var i = 0; i < plots.length; i++) {
44857 for (var j = 0; j < plots[i].pins.length; j++) {
44858 plots[i].pins[j] = {
44859 height : 0,
44860 count : 0
44861 };
44862 }
44863 }
44864 },
44865
44866 /**
44867 * resets the timeplot to non selection status
44868 */
44869 reset : function() {
44870
44871 this.leftFlagPole.style.visibility = "hidden";
44872 this.rightFlagPole.style.visibility = "hidden";
44873 this.rangeBox.style.visibility = "hidden";
44874 this.leftHandle.style.visibility = "hidden";
44875 this.rightHandle.style.visibility = "hidden";
44876 this.toolbar.style.visibility = "hidden";
44877 this.toolbarAbsoluteDiv.style.visibility = "hidden";
44878 this.cancelButton.style.visibility = "hidden";
44879
44880 var plots = this.timeplot._plots;
44881 for (var i = 0; i < plots.length; i++) {
44882 plots[i].opacityPlot.style.visibility = "hidden";
44883 }
44884 this.resetOverlay();
44885 this.filterBar.reset(false);
44886
44887 var slices = this.tds.timeSlices;
44888 if (slices != undefined) {
44889 for (var i = 0; i < slices.length; i++) {
44890 slices[i].reset();
44891 }
44892 }
44893
44894 this.status = 0;
44895 this.stop();
44896 this.gui.updateAnimationButtons(0);
44897
44898 this.leftFlagPos = null;
44899 this.leftFlagTime = null;
44900 this.rightFlagPos = null;
44901 this.rightFlagTime = null;
44902
44903 this.mouseDownTime = null;
44904 this.mouseUpTime = null;
44905 this.mouseTempTime = null;
44906
44907 this.mouseDownPos = null;
44908 this.mouseUpPos = null;
44909 this.mouseTempPos = null;
44910
44911 if (this.popup) {
44912 this.popup.reset();
44913 this.popupClickDiv.style.visibility = "hidden";
44914 }
44915
44916 },
44917
44918 /**
44919 * sets a pole on the timeplot
44920 * @param {Date} time the time of the specific timeslice
44921 * @param {int[]} the number of selected elements per dataset
44922 */
44923 displayOverlay : function() {
44924 this.poles.style.visibility = "visible";
44925 var cv = this.poles.getElementsByTagName("canvas")[0];
44926 cv.width = this.canvas.width;
44927 cv.height = this.canvas.height;
44928 if (!cv.getContext && G_vmlCanvasManager) {
44929 cv = G_vmlCanvasManager.initElement(cv);
44930 }
44931 var ctx = cv.getContext('2d');
44932 ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
44933 var plots = this.timeplot._plots;
44934 var slices = this.tds.timeSlices;
44935 for (var i = 0; i < slices.length; i++) {
44936 if (this.style == 'bars' && i + 1 == slices.length) {
44937 return;
44938 }
44939 if (slices[i].overlay() == 0) {
44940 continue;
44941 }
44942 var projStacks = slices[i].projStacks;
44943 var time = slices[i].date;
44944 var pos;
44945 if (this.style == 'graph') {
44946 pos = this.timeGeometry.toScreen(time);
44947 } else if (this.style == 'bars') {
44948 var x1 = this.timeGeometry.toScreen(time);
44949 var x2 = this.timeGeometry.toScreen(slices[i + 1].date);
44950 pos = (x1 + x2 ) / 2;
44951 }
44952 var heights = [];
44953 var h = 0;
44954 for (var j = 0; j < projStacks.length; j++) {
44955 var data = plots[j]._dataSource.getData();
44956 for (var k = 0; k < data.times.length; k++) {
44957 if (data.times[k].getTime() == time.getTime()) {
44958 var height = plots[j]._valueGeometry.toScreen(plots[j]._dataSource.getData().values[k]) * projStacks[j].overlay / projStacks[j].value;
44959 heights.push(height);
44960 plots[j].pins[i] = {
44961 height : height,
44962 count : projStacks[j].overlay
44963 };
44964 if (height > h) {
44965 h = height;
44966 }
44967 break;
44968 }
44969 }
44970 }
44971 ctx.fillStyle = "rgb(102,102,102)";
44972 ctx.beginPath();
44973 ctx.rect(pos - 1, this.canvas.height - h, 2, h);
44974 ctx.fill();
44975 for (var j = 0; j < heights.length; j++) {
44976 if (heights[j] > 0) {
44977 var color = GeoTemConfig.getColor(j);
44978 ctx.fillStyle = "rgba(" + color.r1 + "," + color.g1 + "," + color.b1 + ",0.6)";
44979 ctx.beginPath();
44980 ctx.arc(pos, this.canvas.height - heights[j], 2.5, 0, Math.PI * 2, true);
44981 ctx.closePath();
44982 ctx.fill();
44983 }
44984 }
44985 }
44986 },
44987
44988 /**
44989 * updates the timeplot by displaying place poles, after a selection had been executed in another widget
44990 */
44991 highlightChanged : function(timeObjects) {
44992 if( !GeoTemConfig.highlightEvents ){
44993 return;
44994 }
44995 this.resetOverlay();
44996 if (this.selection.valid()) {
44997 if (!this.selection.equal(this)) {
44998 this.tds.setOverlay(GeoTemConfig.mergeObjects(timeObjects, this.selection.getObjects(this)));
44999 } else {
45000 this.tds.setOverlay(timeObjects);
45001 }
45002 } else {
45003 this.tds.setOverlay(timeObjects);
45004 }
45005 this.displayOverlay();
45006 },
45007
45008 /**
45009 * updates the timeplot by displaying place poles, after a selection had been executed in another widget
45010 */
45011 selectionChanged : function(selection) {
45012 if( !GeoTemConfig.selectionEvents ){
45013 return;
45014 }
45015 this.reset();
45016 this.selection = selection;
45017 this.tds.setOverlay(selection.objects);
45018 this.displayOverlay();
45019 },
45020
45021 /**
45022 * returns the approximate left position of a slice inside the overview representation
45023 * @param {Date} time time of the slice
45024 */
45025 getOverviewLeft : function(time) {
45026 var w = this.overview.offsetWidth;
45027 var s = this.tds.earliest().getTime();
45028 var e = this.tds.latest().getTime();
45029 var t = time.getTime();
45030 return Math.round(w * (t - s) / (e - s));
45031 },
45032
45033 /**
45034 * visualizes the overview div (shows viewable part of zoomed timeplot)
45035 */
45036 initOverview : function() {
45037 var labels = this.timeGeometry._grid;
45038 if (labels.length == 0) {
45039 var plot = this;
45040 setTimeout(function() {
45041 plot.initOverview();
45042 }, 10);
45043 return;
45044 }
45045
45046 this.overview.style.width = this.canvas.width + "px";
45047 var left = this.gui.timeplotDiv.offsetLeft;
45048 this.overview.innerHTML = "";
45049 this.overview.style.left = left + "px";
45050
45051 this.overviewRange = document.createElement("div");
45052 this.overviewRange.setAttribute('class', 'overviewRange');
45053 this.overview.appendChild(this.overviewRange);
45054
45055 for (var i = 0; i < labels.length; i++) {
45056 var label = document.createElement("div");
45057 label.setAttribute('class', 'overviewLabel');
45058 label.innerHTML = labels[i].label;
45059 label.style.left = Math.floor(labels[i].x) + "px";
45060 this.overview.appendChild(label);
45061 }
45062
45063 this.updateOverview();
45064 },
45065
45066 /**
45067 * visualizes the labels of the timeplot
45068 */
45069 initLabels : function(labels) {
45070 if (labels.length == 0) {
45071 labels = this.timeGeometry._grid;
45072 if (labels.length == 0) {
45073 var plot = this;
45074 setTimeout(function() {
45075 plot.initLabels([]);
45076 }, 10);
45077 return;
45078 }
45079 }
45080 this.plotLabels.style.width = this.canvas.width + "px";
45081 var left = this.gui.timeplotDiv.offsetLeft;
45082 this.plotLabels.style.left = left + "px";
45083 this.plotLabels.innerHTML = "";
45084 for (var i = 0; i < labels.length; i++) {
45085 var label = document.createElement("div");
45086 label.setAttribute('class', 'plotLabel');
45087 label.innerHTML = labels[i].label;
45088 label.style.left = Math.floor(labels[i].x) + "px";
45089 this.plotLabels.appendChild(label);
45090 }
45091 },
45092
45093 /**
45094 * updates the overview div
45095 */
45096 updateOverview : function() {
45097 if (this.tds.getZoom() > 0) {
45098 this.plotLabels.style.visibility = "hidden";
45099 this.timeGeometry._hideLabels = false;
45100 this.overview.style.visibility = "visible";
45101 this.shiftLeft.style.visibility = "visible";
45102 this.shiftRight.style.visibility = "visible";
45103 var left = this.getOverviewLeft(this.tds.timeSlices[this.tds.leftSlice].date);
45104 var right = this.getOverviewLeft(this.tds.timeSlices[this.tds.rightSlice].date);
45105 this.overviewRange.style.left = left + "px";
45106 this.overviewRange.style.width = (right - left) + "px";
45107 } else {
45108 this.timeGeometry._hideLabels = true;
45109 this.plotLabels.style.visibility = "visible";
45110 this.overview.style.visibility = "hidden";
45111 this.shiftLeft.style.visibility = "hidden";
45112 this.shiftRight.style.visibility = "hidden";
45113 }
45114 },
45115
45116 /**
45117 * returns the time slices which are created by the extended data source
45118 */
45119 getSlices : function() {
45120 return this.tds.timeSlices;
45121 },
45122
45123 timeSelection : function() {
45124 var slices = this.tds.timeSlices;
45125 var ls, rs;
45126 for (var i = 0; i < slices.length; i++) {
45127 if (slices[i].date.getTime() == this.leftFlagTime.getTime())
45128 ls = i;
45129 if (slices[i].date.getTime() == this.rightFlagTime.getTime()) {
45130 if (this.style == 'graph') {
45131 rs = i;
45132 }
45133 if (this.style == 'bars') {
45134 rs = i - 1;
45135 }
45136 }
45137 }
45138 var selectedObjects = [];
45139 for (var i = 0; i < GeoTemConfig.datasets.length; i++) {
45140 selectedObjects.push([]);
45141 }
45142 for (var i = 0; i < slices.length; i++) {
45143 if (i >= ls && i <= rs) {
45144 for (var j in slices[i].stacks ) {
45145 selectedObjects[j] = selectedObjects[j].concat(slices[i].stacks[j].elements);
45146 }
45147 }
45148 }
45149 this.selection = new Selection(selectedObjects, this);
45150 this.core.triggerSelection(this.selection);
45151 this.filterBar.reset(true);
45152 },
45153
45154 deselection : function() {
45155 this.reset();
45156 this.selection = new Selection();
45157 this.core.triggerSelection(this.selection);
45158 },
45159
45160 filtering : function() {
45161 for (var i = 0; i < this.datasets.length; i++) {
45162 this.datasets[i].objects = this.selection.objects[i];
45163 }
45164 this.core.triggerRefining(this.datasets);
45165 },
45166
45167 inverseFiltering : function() {
45168 var slices = this.tds.timeSlices;
45169 var ls, rs;
45170 for (var i = 0; i < slices.length; i++) {
45171 if (slices[i].date.getTime() == this.leftFlagTime.getTime())
45172 ls = i;
45173 if (slices[i].date.getTime() == this.rightFlagTime.getTime()) {
45174 if (this.style == 'graph') {
45175 rs = i;
45176 }
45177 if (this.style == 'bars') {
45178 rs = i - 1;
45179 }
45180 }
45181 }
45182 var selectedObjects = [];
45183 for (var i = 0; i < GeoTemConfig.datasets.length; i++) {
45184 selectedObjects.push([]);
45185 }
45186 for (var i = 0; i < slices.length; i++) {
45187 if (i >= ls && i <= rs) {
45188 continue;
45189 }
45190 for (var j in slices[i].stacks ) {
45191 selectedObjects[j] = selectedObjects[j].concat(slices[i].stacks[j].elements);
45192 }
45193 }
45194 this.selection = new Selection(selectedObjects, this);
45195 this.filtering();
45196 },
45197
45198 timeHighlight : function(undo) {
45199 if (this.status == 0) {
45200 var s = this.highlightedSlice;
45201 var timeObjects = [];
45202 for (var i = 0; i < this.tds.size(); i++) {
45203 timeObjects.push([]);
45204 }
45205 var add = true;
45206 if (this.leftFlagTime != null) {
45207 if (this.style == 'graph' && s.date >= this.leftFlagTime && s.date <= this.rightFlagTime) {
45208 add = false;
45209 }
45210 if (this.style == 'bars' && s.date >= this.leftFlagTime && s.date < this.rightFlagTime) {
45211 add = false;
45212 }
45213 }
45214 if (!undo && add) {
45215 for (var i in s.stacks ) {
45216 timeObjects[i] = timeObjects[i].concat(s.stacks[i].elements);
45217 }
45218 }
45219 this.core.triggerHighlight(timeObjects);
45220 }
45221 },
45222
45223 timeRefining : function() {
45224 this.core.triggerRefining(this.selection.objects);
45225 },
45226
45227 setStyle : function(style) {
45228 this.style = style;
45229 },
45230
45231 drawLinearPlot : function() {
45232 if ( typeof this.valueGeometry != 'undefined') {
45233 this.valueGeometry.actLinear();
45234 this.timeplot.repaint();
45235 this.resetOpacityPlots();
45236 this.displayOverlay();
45237 }
45238 },
45239
45240 drawLogarithmicPlot : function() {
45241 if ( typeof this.valueGeometry != 'undefined') {
45242 this.valueGeometry.actLogarithmic();
45243 this.timeplot.repaint();
45244 this.resetOpacityPlots();
45245 this.displayOverlay();
45246 }
45247 }
45248 }
45249 /*
45250 * TableConfig.js
45251 *
45252 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
45253 *
45254 * This library is free software; you can redistribute it and/or
45255 * modify it under the terms of the GNU Lesser General Public
45256 * License as published by the Free Software Foundation; either
45257 * version 3 of the License, or (at your option) any later version.
45258 *
45259 * This library is distributed in the hope that it will be useful,
45260 * but WITHOUT ANY WARRANTY; without even the implied warranty of
45261 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
45262 * Lesser General Public License for more details.
45263 *
45264 * You should have received a copy of the GNU Lesser General Public
45265 * License along with this library; if not, write to the Free Software
45266 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
45267 * MA 02110-1301 USA
45268 */
45269
45270 /**
45271 * @class TableConfig
45272 * Table Configuration File
45273 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
45274 * @release 1.0
45275 * @release date: 2012-07-27
45276 * @version date: 2012-07-27
45277 */
45278 function TableConfig(options) {
45279
45280 this.options = {
45281 tableWidth : false, // false or desired width css definition for the table
45282 tableHeight : false, // false or desired height css definition for the table
45283 validResultsPerPage : [10, 20, 50, 100], // valid number of elements per page
45284 initialResultsPerPage : 10, // initial number of elements per page
45285 tableSorting : true, // true, if sorting of columns should be possible
45286 tableContentOffset : 250, // maximum display number of characters in a table cell
45287 tableSelectPage : true, // selection of complete table pages
45288 tableSelectAll : false, // selection of complete tables
45289 tableShowSelected : true, // show selected objects only option
45290 tableKeepShowSelected : true, // don't revert to show all on "reset" (e.g. selection)
45291 tableInvertSelection : true, // show invert selection option
45292 tableSelectByText : true, // select objects by full-text search
45293 tableCreateNewFromSelected : true, // create new dataset from selected objects
45294 unselectedCellColor : '#EEE', // color for an unselected row/tab
45295 verticalAlign : 'top', // vertical alignment of the table cells ('top','center','bottom')
45296 };
45297 if ( typeof options != 'undefined') {
45298 $.extend(this.options, options);
45299 }
45300
45301 };
45302 /*
45303 * TableGui.js
45304 *
45305 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
45306 *
45307 * This library is free software; you can redistribute it and/or
45308 * modify it under the terms of the GNU Lesser General Public
45309 * License as published by the Free Software Foundation; either
45310 * version 3 of the License, or (at your option) any later version.
45311 *
45312 * This library is distributed in the hope that it will be useful,
45313 * but WITHOUT ANY WARRANTY; without even the implied warranty of
45314 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
45315 * Lesser General Public License for more details.
45316 *
45317 * You should have received a copy of the GNU Lesser General Public
45318 * License along with this library; if not, write to the Free Software
45319 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
45320 * MA 02110-1301 USA
45321 */
45322
45323 /**
45324 * @class TableGui
45325 * Table GUI Implementation
45326 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
45327 * @release 1.0
45328 * @release date: 2012-07-27
45329 * @version date: 2012-07-27
45330 *
45331 * @param {TableWidget} parent table widget object
45332 * @param {HTML object} div parent div to append the table gui
45333 * @param {JSON} options table configuration
45334 */
45335 function TableGui(table, div, options) {
45336
45337 this.tableContainer = div;
45338 if (options.tableWidth) {
45339 this.tableContainer.style.width = options.tableWidth;
45340 }
45341 if (options.tableHeight) {
45342 this.tableContainer.style.height = options.tableHeight;
45343 }
45344 this.tableContainer.style.position = 'relative';
45345
45346 this.tabs = document.createElement('div');
45347 this.tabs.setAttribute('class', 'tableTabs');
45348 div.appendChild(this.tabs);
45349
45350 this.input = document.createElement('div');
45351 this.input.setAttribute('class', 'tableInput');
45352 div.appendChild(this.input);
45353
45354 };
45355 /*
45356 * TableWidget.js
45357 *
45358 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
45359 *
45360 * This library is free software; you can redistribute it and/or
45361 * modify it under the terms of the GNU Lesser General Public
45362 * License as published by the Free Software Foundation; either
45363 * version 3 of the License, or (at your option) any later version.
45364 *
45365 * This library is distributed in the hope that it will be useful,
45366 * but WITHOUT ANY WARRANTY; without even the implied warranty of
45367 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
45368 * Lesser General Public License for more details.
45369 *
45370 * You should have received a copy of the GNU Lesser General Public
45371 * License along with this library; if not, write to the Free Software
45372 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
45373 * MA 02110-1301 USA
45374 */
45375
45376 /**
45377 * @class TableWidget
45378 * TableWidget Implementation
45379 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
45380 * @release 1.0
45381 * @release date: 2012-07-27
45382 * @version date: 2012-07-27
45383 *
45384 * @param {TableWrapper} core wrapper for interaction to other widgets
45385 * @param {HTML object} div parent div to append the table widget div
45386 * @param {JSON} options user specified configuration that overwrites options in TableConfig.js
45387 */
45388 TableWidget = function(core, div, options) {
45389
45390 this.core = core;
45391 this.core.setWidget(this);
45392 this.tables = [];
45393 this.tableTabs = [];
45394 this.tableElements = [];
45395 this.tableHash = [];
45396
45397 this.options = (new TableConfig(options)).options;
45398 this.gui = new TableGui(this, div, this.options);
45399 this.filterBar = new FilterBar(this);
45400
45401 }
45402
45403 TableWidget.prototype = {
45404
45405 initWidget : function(data) {
45406 this.datasets = data;
45407
45408 $(this.gui.tabs).empty();
45409 $(this.gui.input).empty();
45410 this.activeTable = undefined;
45411 this.tables = [];
45412 this.tableTabs = [];
45413 this.tableElements = [];
45414 this.tableHash = [];
45415 this.selection = new Selection();
45416 this.filterBar.reset(false);
45417
45418 var tableWidget = this;
45419 var addTab = function(name, index) {
45420 var dataSet = GeoTemConfig.datasets[index];
45421 var tableTab = document.createElement('div');
45422 var tableTabTable = document.createElement('table');
45423 $(tableTab).append(tableTabTable);
45424 var tableTabTableRow = document.createElement('tr');
45425 $(tableTabTable).append(tableTabTableRow);
45426 tableTab.setAttribute('class', 'tableTab');
45427 var c = GeoTemConfig.getColor(index);
45428 tableTab.style.backgroundColor = 'rgb(' + c.r0 + ',' + c.g0 + ',' + c.b0 + ')';
45429 tableTab.onclick = function() {
45430 tableWidget.selectTable(index);
45431 }
45432 var tableNameDiv = document.createElement('div');
45433 $(tableNameDiv).append(name);
45434 $(tableNameDiv).dblclick(function() {
45435 var n = $(tableNameDiv).text();
45436 $(tableNameDiv).empty();
45437 var nameInput = $('<input type="text" name="nameinput" value="'+n+'" />');
45438 $(tableNameDiv).append(nameInput);
45439 $(nameInput).focus();
45440 $(nameInput).focusout(function() {
45441 var newname = $(nameInput).val();
45442 $(tableNameDiv).empty();
45443 $(tableNameDiv).append(newname);
45444 dataSet.label = newname;
45445 });
45446 $(nameInput).keypress(function(event) {
45447 if (event.which == 13) {
45448 var newname = $(nameInput).val();
45449 $(tableNameDiv).empty();
45450 $(tableNameDiv).append(newname);
45451 dataSet.label = newname;
45452 }
45453 });
45454 });
45455
45456 if (typeof dataSet.url !== "undefined"){
45457 var tableLinkDiv = document.createElement('a');
45458 tableLinkDiv.title = dataSet.url;
45459 tableLinkDiv.href = dataSet.url;
45460 tableLinkDiv.target = '_';
45461 tableLinkDiv.setAttribute('class', 'externalLink');
45462 $(tableNameDiv).append(tableLinkDiv);
45463 }
45464 $(tableTabTableRow).append($(document.createElement('td')).append(tableNameDiv));
45465
45466 var removeTabDiv = document.createElement('div');
45467 removeTabDiv.setAttribute('class', 'smallButton removeDataset');
45468 removeTabDiv.title = GeoTemConfig.getString('removeDatasetHelp');
45469 removeTabDiv.onclick = $.proxy(function(e) {
45470 GeoTemConfig.removeDataset(index);
45471 //don't let the event propagate to the DIV above
45472 e.stopPropagation();
45473 //discard link click
45474 return(false);
45475 },{index:index});
45476 $(tableTabTableRow).append($(document.createElement('td')).append(removeTabDiv));
45477
45478 if (GeoTemConfig.tableExportDataset){
45479 var exportTabDiv = document.createElement('div');
45480 exportTabDiv.setAttribute('class', 'smallButton exportDataset');
45481 exportTabDiv.title = GeoTemConfig.getString('exportDatasetHelp');
45482 var exportTabForm = document.createElement('form');
45483 //TODO: make this configurable
45484 exportTabForm.action = 'php/download.php';
45485 exportTabForm.method = 'post';
45486 var exportTabHiddenValue = document.createElement('input');
45487 exportTabHiddenValue.name = 'file';
45488 exportTabHiddenValue.type = 'hidden';
45489 exportTabForm.appendChild(exportTabHiddenValue);
45490 exportTabDiv.onclick = $.proxy(function(e) {
45491 $(exportTabHiddenValue).val(GeoTemConfig.createKMLfromDataset(index));
45492 $(exportTabForm).submit();
45493 //don't let the event propagate to the DIV
45494 e.stopPropagation();
45495 //discard link click
45496 return(false);
45497 },{index:index});
45498 exportTabDiv.appendChild(exportTabForm);
45499 $(tableTabTableRow).append($(document.createElement('td')).append(exportTabDiv));
45500 }
45501
45502 if (GeoTemConfig.allowUserShapeAndColorChange){
45503 var dataset = GeoTemConfig.datasets[index];
45504
45505 var changeColorShapeSelect = $("<select></select>");
45506 changeColorShapeSelect.attr("title", GeoTemConfig.getString("colorShapeDatasetHelp"));
45507 changeColorShapeSelect.css("font-size","1.5em");
45508
45509 var currentOptgroup = $("<optgroup label='Current'></optgroup>");
45510 var currentOption = $("<option value='current'></option>");
45511 var color = GeoTemConfig.getColor(index);
45512 currentOption.css("color","rgb("+color.r1+","+color.g1+","+color.b1+")");
45513 currentOption.data("color",{r1:color.r1,g1:color.g1,b1:color.b1,r0:color.r0,g0:color.g0,b0:color.b0});
45514 if (dataset.graphic.shape=="circle"){
45515 currentOption.append("●");
45516 } else if (dataset.graphic.shape=="triangel"){
45517 currentOption.append("▲");
45518 } else if (dataset.graphic.shape=="square"){
45519 if (dataset.graphic.rotation===0){
45520 currentOption.append("■");
45521 } else {
45522 currentOption.append("◆");
45523 }
45524 }
45525 currentOptgroup.append(currentOption);
45526 changeColorShapeSelect.append(currentOptgroup);
45527
45528 var defaultOptgroup = $("<optgroup label='Default'></optgroup>");
45529 var defaultOption = $("<option value='default'></option>");
45530 var color = GeoTemConfig.colors[index];
45531 defaultOption.css("color","rgb("+color.r1+","+color.g1+","+color.b1+")");
45532 defaultOption.data("color",{r1:color.r1,g1:color.g1,b1:color.b1,r0:color.r0,g0:color.g0,b0:color.b0});
45533 defaultOption.append("●");
45534 defaultOptgroup.append(defaultOption);
45535 changeColorShapeSelect.append(defaultOptgroup);
45536
45537 var shapeOptgroup = $("<optgroup label='Shapes'></optgroup>");
45538 shapeOptgroup.append("<option>○</option>");
45539 shapeOptgroup.append("<option>□</option>");
45540 shapeOptgroup.append("<option>◇</option>");
45541 shapeOptgroup.append("<option>△</option>");
45542 changeColorShapeSelect.append(shapeOptgroup);
45543
45544 var colorOptgroup = $("<optgroup label='Colors'></optgroup>");
45545 var red = $("<option style='color:red'>■</option>");
45546 red.data("color",{r1:255,g1:0,b1:0});
45547 colorOptgroup.append(red);
45548 var green = $("<option style='color:green'>■</option>");
45549 green.data("color",{r1:0,g1:255,b1:0});
45550 colorOptgroup.append(green);
45551 var blue = $("<option style='color:blue'>■</option>");
45552 blue.data("color",{r1:0,g1:0,b1:255});
45553 colorOptgroup.append(blue);
45554 var yellow = $("<option style='color:yellow'>■</option>");
45555 yellow.data("color",{r1:255,g1:255,b1:0});
45556 colorOptgroup.append(yellow);
45557 changeColorShapeSelect.append(colorOptgroup);
45558
45559 changeColorShapeSelect.change($.proxy(function(e) {
45560 var selected = changeColorShapeSelect.find("option:selected");
45561
45562 //credits: Pimp Trizkit @ http://stackoverflow.com/a/13542669
45563 function shadeRGBColor(color, percent) {
45564 var f=color.split(","),t=percent<0?0:255,p=percent<0?percent*-1:percent,R=parseInt(f[0].slice(4)),G=parseInt(f[1]),B=parseInt(f[2]);
45565 return "rgb("+(Math.round((t-R)*p)+R)+","+(Math.round((t-G)*p)+G)+","+(Math.round((t-B)*p)+B)+")";
45566 }
45567
45568 var color = selected.data("color");
45569
45570 if (typeof color !== "undefined"){
45571 if ( (typeof color.r0 === "undefined") ||
45572 (typeof color.g0 === "undefined") ||
45573 (typeof color.b0 === "undefined") ){
45574 var shadedrgb = shadeRGBColor("rgb("+color.r1+","+color.g1+","+color.b1+")",0.7);
45575 shadedrgb = shadedrgb.replace("rgb(","").replace(")","");
45576 shadedrgb = shadedrgb.split(",");
45577
45578 color.r0 = parseInt(shadedrgb[0]);
45579 color.g0 = parseInt(shadedrgb[1]);
45580 color.b0 = parseInt(shadedrgb[2]);
45581 }
45582 }
45583
45584 var shapeText = selected.text();
45585 var graphic;
45586 if ((shapeText=="■") || (shapeText=="□")){
45587 graphic = {
45588 shape: "square",
45589 rotation: 0
45590 };
45591 } else if ((shapeText=="●") || (shapeText=="○")){
45592 graphic = {
45593 shape: "circle",
45594 rotation: 0
45595 };
45596 } else if ((shapeText=="◆") || (shapeText=="◇")){
45597 graphic = {
45598 shape: "square",
45599 rotation: 45
45600 };
45601 } else if ((shapeText=="▲") || (shapeText=="△")){
45602 graphic = {
45603 shape: "triangle",
45604 rotation: 0
45605 };
45606 }
45607
45608 if (shapeOptgroup.has(selected).length>0){
45609 //shape change
45610 dataset.graphic = graphic;
45611 } else if (colorOptgroup.has(selected).length>0){
45612 //color changed
45613 dataset.color = color;
45614 } else {
45615 //back to default
45616 dataset.graphic = graphic;
45617 dataset.color = color;
45618 }
45619
45620 //reload data
45621 Publisher.Publish('filterData', GeoTemConfig.datasets, null);
45622
45623 //don't let the event propagate to the DIV
45624 e.stopPropagation();
45625 //discard link click
45626 return(false);
45627 },{index:index}));
45628 $(tableTabTableRow).append($(document.createElement('td')).append(changeColorShapeSelect));
45629 }
45630
45631 return tableTab;
45632 }
45633 tableWidget.addTab = addTab;
45634
45635 for (var i in data ) {
45636 this.tableHash.push([]);
45637 var tableTab = addTab(data[i].label, i);
45638 this.gui.tabs.appendChild(tableTab);
45639 this.tableTabs.push(tableTab);
45640 var elements = [];
45641 for (var j in data[i].objects ) {
45642 elements.push(new TableElement(data[i].objects[j]));
45643 this.tableHash[i][data[i].objects[j].index] = elements[elements.length - 1];
45644 }
45645 var table = new Table(elements, this, i);
45646 this.tables.push(table);
45647 this.tableElements.push(elements);
45648 }
45649
45650 if (data.length > 0) {
45651 this.selectTable(0);
45652 }
45653
45654 },
45655
45656 getHeight : function() {
45657 if (this.options.tableHeight) {
45658 return this.gui.tableContainer.offsetHeight - this.gui.tabs.offsetHeight;
45659 }
45660 return false;
45661 },
45662
45663 selectTable : function(index) {
45664 if (this.activeTable != index) {
45665 if ( typeof this.activeTable != 'undefined') {
45666 this.tables[this.activeTable].hide();
45667 var c = GeoTemConfig.getColor(this.activeTable);
45668 this.tableTabs[this.activeTable].style.backgroundColor = 'rgb(' + c.r0 + ',' + c.g0 + ',' + c.b0 + ')';
45669 }
45670 this.activeTable = index;
45671 this.tables[this.activeTable].show();
45672 var c = GeoTemConfig.getColor(this.activeTable);
45673 this.tableTabs[this.activeTable].style.backgroundColor = 'rgb(' + c.r1 + ',' + c.g1 + ',' + c.b1 + ')';
45674 this.core.triggerRise(index);
45675 }
45676
45677 },
45678
45679 highlightChanged : function(objects) {
45680 if( !GeoTemConfig.highlightEvents || (typeof this.tables[this.activeTable] === "undefined")){
45681 return;
45682 }
45683 if( this.tables.length > 0 ){
45684 return;
45685 }
45686 for (var i = 0; i < this.tableElements.length; i++) {
45687 for (var j = 0; j < this.tableElements[i].length; j++) {
45688 this.tableElements[i][j].highlighted = false;
45689 }
45690 }
45691 for (var i = 0; i < objects.length; i++) {
45692 for (var j = 0; j < objects[i].length; j++) {
45693 this.tableHash[i][objects[i][j].index].highlighted = true;
45694 }
45695 }
45696 this.tables[this.activeTable].update();
45697 },
45698
45699 selectionChanged : function(selection) {
45700 if( !GeoTemConfig.selectionEvents || (typeof this.tables[this.activeTable] === "undefined")){
45701 return;
45702 }
45703 this.reset();
45704 if( this.tables.length == 0 ){
45705 return;
45706 }
45707 this.selection = selection;
45708 for (var i = 0; i < this.tableElements.length; i++) {
45709 for (var j = 0; j < this.tableElements[i].length; j++) {
45710 this.tableElements[i][j].selected = false;
45711 this.tableElements[i][j].highlighted = false;
45712 }
45713 }
45714 var objects = selection.getObjects(this);
45715 for (var i = 0; i < objects.length; i++) {
45716 for (var j = 0; j < objects[i].length; j++) {
45717 this.tableHash[i][objects[i][j].index].selected = true;
45718 }
45719 }
45720 this.tables[this.activeTable].reset();
45721 this.tables[this.activeTable].update();
45722 },
45723
45724 triggerHighlight : function(item) {
45725 var selectedObjects = [];
45726 for (var i = 0; i < GeoTemConfig.datasets.length; i++) {
45727 selectedObjects.push([]);
45728 }
45729 if ( typeof item != 'undefined') {
45730 selectedObjects[this.activeTable].push(item);
45731 }
45732 this.core.triggerHighlight(selectedObjects);
45733 },
45734
45735 tableSelection : function() {
45736 var selectedObjects = [];
45737 for (var i = 0; i < GeoTemConfig.datasets.length; i++) {
45738 selectedObjects.push([]);
45739 }
45740 var valid = false;
45741 for (var i = 0; i < this.tableElements.length; i++) {
45742 for (var j = 0; j < this.tableElements[i].length; j++) {
45743 var e = this.tableElements[i][j];
45744 if (e.selected) {
45745 selectedObjects[i].push(e.object);
45746 valid = true;
45747 }
45748 }
45749 }
45750 this.selection = new Selection();
45751 if (valid) {
45752 this.selection = new Selection(selectedObjects, this);
45753 }
45754 this.core.triggerSelection(this.selection);
45755 this.filterBar.reset(true);
45756 },
45757
45758 deselection : function() {
45759 this.reset();
45760 this.selection = new Selection();
45761 this.core.triggerSelection(this.selection);
45762 },
45763
45764 filtering : function() {
45765 for (var i = 0; i < this.datasets.length; i++) {
45766 this.datasets[i].objects = this.selection.objects[i];
45767 }
45768 this.core.triggerRefining(this.datasets);
45769 },
45770
45771 inverseFiltering : function() {
45772 var selectedObjects = [];
45773 for (var i = 0; i < GeoTemConfig.datasets.length; i++) {
45774 selectedObjects.push([]);
45775 }
45776 var valid = false;
45777 for (var i = 0; i < this.tableElements.length; i++) {
45778 for (var j = 0; j < this.tableElements[i].length; j++) {
45779 var e = this.tableElements[i][j];
45780 if (!e.selected) {
45781 selectedObjects[i].push(e.object);
45782 valid = true;
45783 }
45784 }
45785 }
45786 this.selection = new Selection();
45787 if (valid) {
45788 this.selection = new Selection(selectedObjects, this);
45789 }
45790 this.filtering();
45791 },
45792
45793 triggerRefining : function() {
45794 this.core.triggerRefining(this.selection.objects);
45795 },
45796
45797 reset : function() {
45798 this.filterBar.reset(false);
45799 if( this.tables.length > 0 ){
45800 this.tables[this.activeTable].resetElements();
45801 this.tables[this.activeTable].reset();
45802 this.tables[this.activeTable].update();
45803 }
45804 },
45805
45806
45807 getConfig : function(inquiringWidget){
45808 var tableWidget = this;
45809 var config = {};
45810
45811 //save widget specific configurations here into the config object
45812
45813 //send config to iquiring widget
45814 if (typeof inquiringWidget.sendConfig !== "undefined"){
45815 inquiringWidget.sendConfig({widgetName: "table", 'config': config});
45816 }
45817 },
45818
45819 setConfig : function(configObj){
45820 var tableWidget = this;
45821
45822 if (configObj.widgetName === "table"){
45823 var config = configObj.config;
45824
45825 //set widgets configuration provided by config
45826
45827 }
45828 },
45829
45830 }
45831 /*
45832 * Table.js
45833 *
45834 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
45835 *
45836 * This library is free software; you can redistribute it and/or
45837 * modify it under the terms of the GNU Lesser General Public
45838 * License as published by the Free Software Foundation; either
45839 * version 3 of the License, or (at your option) any later version.
45840 *
45841 * This library is distributed in the hope that it will be useful,
45842 * but WITHOUT ANY WARRANTY; without even the implied warranty of
45843 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
45844 * Lesser General Public License for more details.
45845 *
45846 * You should have received a copy of the GNU Lesser General Public
45847 * License along with this library; if not, write to the Free Software
45848 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
45849 * MA 02110-1301 USA
45850 */
45851
45852 /**
45853 * @class Table
45854 * Implementation for a single table
45855 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
45856 * @release 1.0
45857 * @release date: 2012-07-27
45858 * @version date: 2012-07-27
45859 *
45860 * @param {Array} elements list of data items
45861 * @param {HTML object} parent div to append the table
45862 * @param {int} id dataset index
45863 */
45864 function Table(elements, parent, id) {
45865
45866 this.elements = elements;
45867 this.showElementsLength = elements.length;
45868 this.parent = parent;
45869 this.id = id;
45870 this.options = parent.options;
45871
45872 this.validResultsPerPage = [10, 20, 50, 100];
45873 this.keyHeaderList = [];
45874 this.initialize();
45875
45876 }
45877
45878 Table.prototype = {
45879
45880 initToolbar : function() {
45881
45882 var table = this;
45883
45884 this.toolbar = document.createElement("table");
45885 this.toolbar.setAttribute('class', 'ddbToolbar');
45886 this.toolbar.style.overflow = 'auto';
45887 this.tableDiv.appendChild(this.toolbar);
45888
45889 var navigation = document.createElement("tr");
45890 this.toolbar.appendChild(navigation);
45891
45892 var selectors = document.createElement("td");
45893 navigation.appendChild(selectors);
45894
45895 if (table.options.tableSelectPage) {
45896 var selectPageItems = true;
45897 this.selectPage = document.createElement('div');
45898 $(this.selectPage).css("float","left");
45899 this.selectPage.setAttribute('class', 'smallButton selectPage');
45900 this.selectPage.title = GeoTemConfig.getString('selectTablePageItemsHelp');
45901 selectors.appendChild(this.selectPage);
45902 this.selectPage.onclick = function() {
45903 selectPageItems = !selectPageItems;
45904 if (selectPageItems) {
45905 var items = 0;
45906 for (var i = table.first; i < table.elements.length; i++) {
45907 table.elements[i].selected = false;
45908 items++;
45909 if (items == table.resultsPerPage) {
45910 break;
45911 }
45912 }
45913 table.selectPage.setAttribute('class', 'smallButton selectPage');
45914 table.selectPage.title = GeoTemConfig.getString('selectTablePageItemsHelp');
45915 } else {
45916 var items = 0;
45917 for (var i = table.first; i < table.elements.length; i++) {
45918 table.elements[i].selected = true;
45919 items++;
45920 if (items == table.resultsPerPage) {
45921 break;
45922 }
45923 }
45924 table.selectPage.setAttribute('class', 'smallButton deselectPage');
45925 table.selectPage.title = GeoTemConfig.getString('deselectTablePageItemsHelp');
45926 }
45927 table.update();
45928 table.parent.tableSelection();
45929 }
45930 }
45931
45932 if (table.options.tableSelectAll) {
45933 var selectAllItems = true;
45934 this.selectAll = document.createElement('div');
45935 this.selectAll.setAttribute('class', 'smallButton selectAll');
45936 $(this.selectAll).css("float","left");
45937 table.selectAll.title = GeoTemConfig.getString('selectAllTableItemsHelp');
45938 selectors.appendChild(this.selectAll);
45939 this.selectAll.onclick = function() {
45940 selectAllItems = !selectAllItems;
45941 if (selectAllItems) {
45942 for (var i = 0; i < table.elements.length; i++) {
45943 table.elements[i].selected = false;
45944 }
45945 table.selectAll.setAttribute('class', 'smallButton selectAll');
45946 table.selectAll.title = GeoTemConfig.getString('selectAllTableItemsHelp');
45947 } else {
45948 for (var i = 0; i < table.elements.length; i++) {
45949 table.elements[i].selected = true;
45950 }
45951 table.selectAll.setAttribute('class', 'smallButton deselectAll');
45952 table.selectAll.title = GeoTemConfig.getString('deselectAllTableItemsHelp');
45953 }
45954 table.update();
45955 table.parent.tableSelection();
45956 }
45957 }
45958
45959 if (table.options.tableInvertSelection) {
45960 this.invertSelection = document.createElement('div');
45961 this.invertSelection.setAttribute('class', 'smallButton invertSelection');
45962 $(this.invertSelection).css("float","left");
45963 table.invertSelection.title = GeoTemConfig.getString('invertSelectionHelp');
45964 selectors.appendChild(this.invertSelection);
45965 this.invertSelection.onclick = function() {
45966 for (var i = 0; i < table.elements.length; i++) {
45967 if (table.elements[i].selected === true)
45968 table.elements[i].selected = false;
45969 else
45970 table.elements[i].selected = true;
45971 }
45972 table.update();
45973 table.parent.tableSelection();
45974 }
45975 }
45976
45977 this.showSelectedItems = false;
45978 if (table.options.tableShowSelected) {
45979 this.showSelected = document.createElement('div');
45980 this.showSelected.setAttribute('class', 'smallButton showSelected');
45981 $(this.showSelected).css("float","left");
45982 table.showSelected.title = GeoTemConfig.getString('showSelectedHelp');
45983 selectors.appendChild(this.showSelected);
45984 this.showSelected.onclick = function() {
45985 table.showSelectedItems = !table.showSelectedItems;
45986 if (table.showSelectedItems) {
45987 table.showElementsLength = 0;
45988 for (var i = 0; i < table.elements.length; i++) {
45989 if (table.elements[i].selected) {
45990 table.showElementsLength++;
45991 }
45992 }
45993 table.showSelected.setAttribute('class', 'smallButton showAll');
45994 // table.selectAll.title = GeoTemConfig.getString('showAllElementsHelp');
45995 } else {
45996 table.showElementsLength = table.elements.length;
45997 table.showSelected.setAttribute('class', 'smallButton showSelected');
45998 // table.selectAll.title = GeoTemConfig.getString('showSelectedHelp');
45999 }
46000 table.updateIndices(table.resultsPerPage);
46001 table.update();
46002 }
46003 }
46004
46005 if (table.options.tableSelectByText) {
46006 this.selectByTextDiv = document.createElement('div');
46007 $(this.selectByTextDiv).css("float","left");
46008 $(this.selectByTextDiv).css("vertical-align", "top");
46009 //TODO: improve appearance (wrong margin)
46010 $(this.selectByTextDiv).css("display", "inline-block");
46011 //create and append the input field
46012 this.selectByTextInput = document.createElement('input');
46013 $(this.selectByTextInput).attr("type","text");
46014 $(this.selectByTextDiv).append(this.selectByTextInput);
46015 //create and append the button
46016 this.selectByTextButton = document.createElement('input');
46017 $(this.selectByTextButton).attr("type","button");
46018 //TODO: add button-image
46019 $(this.selectByTextButton).val("search");
46020 $(this.selectByTextDiv).append(this.selectByTextButton);
46021
46022 table.selectByTextDiv.title = GeoTemConfig.getString('selectByTextHelp');
46023 selectors.appendChild(this.selectByTextDiv);
46024 $(this.selectByTextButton).click($.proxy(function() {
46025 this.selectByText($(this.selectByTextInput).val());
46026 },this));
46027 }
46028
46029 if (table.options.tableCreateNewFromSelected) {
46030 this.createNewFromSelected = document.createElement('div');
46031 this.createNewFromSelected.setAttribute('class', 'smallButton createNewRefined');
46032 $(this.createNewFromSelected).css("float","left");
46033 this.createNewFromSelected.title = GeoTemConfig.getString('createNewFromSelectedHelp');
46034 selectors.appendChild(this.createNewFromSelected);
46035 this.createNewFromSelected.onclick = function() {
46036 var copyID = table.id;
46037 var tableWidget = table.parent;
46038
46039 var newObjects = [];
46040 $(table.elements).each(function(){
46041 if (this.selected)
46042 newObjects.push(this.object);
46043 });
46044
46045 var newDataset = new Dataset();
46046 newDataset.label = tableWidget.datasets[copyID].label + " refined";
46047 newDataset.objects = newObjects;
46048
46049 GeoTemConfig.addDataset(newDataset);
46050 };
46051 }
46052
46053 this.selectors = selectors;
46054
46055 // selectors.style.width = (this.filter.offsetWidth + this.selectAll.offsetWidth + this.selectPage.offsetWidth)+"px";
46056
46057 var results = document.createElement("td");
46058 navigation.appendChild(results);
46059
46060 var pagination = document.createElement("td");
46061 $(pagination).css('float', 'right');
46062 navigation.appendChild(pagination);
46063
46064 this.resultsInfo = document.createElement('div');
46065 this.resultsInfo.setAttribute('class', 'resultsInfo');
46066 results.appendChild(this.resultsInfo);
46067
46068 this.resultsDropdown = document.createElement('div');
46069 this.resultsDropdown.setAttribute('class', 'resultsDropdown');
46070 pagination.appendChild(this.resultsDropdown);
46071 var itemNumbers = [];
46072 var addItemNumber = function(count, index) {
46073 var setItemNumber = function() {
46074 table.updateIndices(count);
46075 table.update();
46076 }
46077 itemNumbers.push({
46078 name : count,
46079 onclick : setItemNumber
46080 });
46081 }
46082 for (var i = 0; i < table.options.validResultsPerPage.length; i++) {
46083 addItemNumber(table.options.validResultsPerPage[i], i);
46084 }
46085 var dropdown = new Dropdown(this.resultsDropdown, itemNumbers, GeoTemConfig.getString('paginationDropdownHelp'));
46086 for (var i = 0; i < table.options.validResultsPerPage.length; i++) {
46087 if (table.options.initialResultsPerPage == table.options.validResultsPerPage[i]) {
46088 dropdown.setEntry(i);
46089 break;
46090 }
46091 }
46092 dropdown.div.title = GeoTemConfig.getString('paginationDropdownHelp');
46093
46094 this.firstPage = document.createElement('div');
46095 this.firstPage.setAttribute('class', 'paginationButton');
46096 this.firstPage.title = GeoTemConfig.getString('paginationFirsPageHelp');
46097
46098 pagination.appendChild(this.firstPage);
46099 this.firstPage.onclick = function() {
46100 if (table.page != 0) {
46101 table.page = 0;
46102 table.update();
46103 }
46104 }
46105
46106 this.previousPage = document.createElement('div');
46107 this.previousPage.setAttribute('class', 'paginationButton');
46108 this.previousPage.title = GeoTemConfig.getString('paginationPreviousPageHelp');
46109 pagination.appendChild(this.previousPage);
46110 this.previousPage.onclick = function() {
46111 if (table.page > 0) {
46112 table.page--;
46113 table.update();
46114 }
46115 }
46116
46117 this.pageInfo = document.createElement('div');
46118 this.pageInfo.setAttribute('class', 'pageInfo');
46119 pagination.appendChild(this.pageInfo);
46120
46121 this.nextPage = document.createElement('div');
46122 this.nextPage.setAttribute('class', 'paginationButton');
46123 this.nextPage.title = GeoTemConfig.getString('paginationNextPageHelp');
46124 pagination.appendChild(this.nextPage);
46125 this.nextPage.onclick = function() {
46126 if (table.page < table.pages - 1) {
46127 table.page++;
46128 table.update();
46129 }
46130 }
46131
46132 this.lastPage = document.createElement('div');
46133 this.lastPage.setAttribute('class', 'paginationButton');
46134 this.lastPage.title = GeoTemConfig.getString('paginationLastPageHelp');
46135 pagination.appendChild(this.lastPage);
46136 this.lastPage.onclick = function() {
46137 if (table.page != table.pages - 1) {
46138 table.page = table.pages - 1;
46139 table.update();
46140 }
46141 }
46142
46143 this.input = document.createElement("div");
46144 this.input.style.overflow = 'auto';
46145 this.tableDiv.appendChild(this.input);
46146
46147 this.elementList = document.createElement("table");
46148 this.elementList.setAttribute('class', 'resultList');
46149 this.input.appendChild(this.elementList);
46150 var height = this.parent.getHeight();
46151 if (height) {
46152 this.input.style.height = (height - pagination.offsetHeight) + 'px';
46153 this.input.style.overflowY = 'auto';
46154 }
46155
46156 this.elementListHeader = document.createElement("tr");
46157 this.elementList.appendChild(this.elementListHeader);
46158
46159 if (GeoTemConfig.allowFilter) {
46160 var cell = document.createElement('th');
46161 this.elementListHeader.appendChild(cell);
46162 }
46163
46164 //Bottom pagination elements
46165 this.bottomToolbar = document.createElement("table");
46166 this.bottomToolbar.setAttribute('class', 'ddbToolbar');
46167 this.bottomToolbar.style.overflow = 'auto';
46168 this.tableDiv.appendChild(this.bottomToolbar);
46169
46170 var bottomNavigation = document.createElement("tr");
46171 this.bottomToolbar.appendChild(bottomNavigation);
46172
46173 var bottomPagination = document.createElement("td");
46174 bottomNavigation.appendChild(bottomPagination);
46175
46176 this.bottomLastPage = document.createElement('div');
46177 this.bottomLastPage.setAttribute('class', 'paginationButton');
46178 this.bottomLastPage.title = GeoTemConfig.getString('paginationLastPageHelp');
46179 $(this.bottomLastPage).css('float', 'right');
46180 bottomPagination.appendChild(this.bottomLastPage);
46181 this.bottomLastPage.onclick = function() {
46182 if (table.page != table.pages - 1) {
46183 table.page = table.pages - 1;
46184 table.update();
46185 }
46186 }
46187
46188 this.bottomNextPage = document.createElement('div');
46189 this.bottomNextPage.setAttribute('class', 'paginationButton');
46190 this.bottomNextPage.title = GeoTemConfig.getString('paginationNextPageHelp');
46191 $(this.bottomNextPage).css('float', 'right');
46192 bottomPagination.appendChild(this.bottomNextPage);
46193 this.bottomNextPage.onclick = function() {
46194 if (table.page < table.pages - 1) {
46195 table.page++;
46196 table.update();
46197 }
46198 }
46199
46200 this.bottomPageInfo = document.createElement('div');
46201 this.bottomPageInfo.setAttribute('class', 'pageInfo');
46202 $(this.bottomPageInfo).css('float', 'right');
46203 bottomPagination.appendChild(this.bottomPageInfo);
46204
46205 this.bottomPreviousPage = document.createElement('div');
46206 this.bottomPreviousPage.setAttribute('class', 'paginationButton');
46207 this.bottomPreviousPage.title = GeoTemConfig.getString('paginationPreviousPageHelp');
46208 $(this.bottomPreviousPage).css('float', 'right');
46209 bottomPagination.appendChild(this.bottomPreviousPage);
46210 this.bottomPreviousPage.onclick = function() {
46211 if (table.page > 0) {
46212 table.page--;
46213 table.update();
46214 }
46215 }
46216
46217 this.bottomFirstPage = document.createElement('div');
46218 this.bottomFirstPage.setAttribute('class', 'paginationButton');
46219 this.bottomFirstPage.title = GeoTemConfig.getString('paginationFirsPageHelp');
46220 $(this.bottomFirstPage).css('float', 'right');
46221 bottomPagination.appendChild(this.bottomFirstPage);
46222 this.bottomFirstPage.onclick = function() {
46223 if (table.page != 0) {
46224 table.page = 0;
46225 table.update();
46226 }
46227 }
46228
46229 if ( typeof (this.elements[0]) == 'undefined') {
46230 return;
46231 }
46232
46233 var ascButtons = [];
46234 var descButtons = [];
46235 var clearButtons = function() {
46236 for (var i in ascButtons ) {
46237 ascButtons[i].setAttribute('class', 'sort sortAscDeactive');
46238 }
46239 for (var i in descButtons ) {
46240 descButtons[i].setAttribute('class', 'sort sortDescDeactive');
46241 }
46242 }
46243 var addSortButton = function(key) {
46244 table.keyHeaderList.push(key);
46245 var cell = document.createElement('th');
46246 table.elementListHeader.appendChild(cell);
46247 var sortAsc = document.createElement('div');
46248 var sortDesc = document.createElement('div');
46249 var span = document.createElement('div');
46250 span.setAttribute('class', 'headerLabel');
46251 span.innerHTML = key;
46252 cell.appendChild(sortDesc);
46253 cell.appendChild(span);
46254 cell.appendChild(sortAsc);
46255 sortAsc.setAttribute('class', 'sort sortAscDeactive');
46256 sortAsc.title = GeoTemConfig.getString('sortAZHelp');
46257 sortDesc.setAttribute('class', 'sort sortDescDeactive');
46258 sortDesc.title = GeoTemConfig.getString('sortZAHelp');
46259 ascButtons.push(sortAsc);
46260 descButtons.push(sortDesc);
46261 sortAsc.onclick = function() {
46262 clearButtons();
46263 sortAsc.setAttribute('class', 'sort sortAscActive');
46264 table.sortAscending(key);
46265 table.update();
46266 }
46267 sortDesc.onclick = function() {
46268 clearButtons();
46269 sortDesc.setAttribute('class', 'sort sortDescActive');
46270 table.sortDescending(key);
46271 table.update();
46272 }
46273 }
46274 for (var key in this.elements[0].object.tableContent) {
46275 addSortButton(key);
46276 }
46277 },
46278
46279 sortAscending : function(key) {
46280 var sortFunction = function(e1, e2) {
46281 if (e1.object.tableContent[key] < e2.object.tableContent[key]) {
46282 return -1;
46283 }
46284 return 1;
46285 }
46286 this.elements.sort(sortFunction);
46287 },
46288
46289 sortDescending : function(key) {
46290 var sortFunction = function(e1, e2) {
46291 if (e1.object.tableContent[key] > e2.object.tableContent[key]) {
46292 return -1;
46293 }
46294 return 1;
46295 }
46296 this.elements.sort(sortFunction);
46297 },
46298
46299 selectByText : function(text) {
46300 //deselect all elements
46301 $(this.elements).each(function(){
46302 this.selected = false;
46303 });
46304
46305 var selectedCount = 0;
46306 $(this.elements).filter(function(index){
46307 return this.object.contains(text);
46308 }).each(function(){
46309 this.selected = true;
46310 selectedCount++;
46311 });
46312
46313 //only show selected elements
46314 this.showSelectedItems = true;
46315 this.showElementsLength = selectedCount;
46316 this.showSelected.setAttribute('class', 'smallButton showAll');
46317
46318 this.update();
46319 this.parent.tableSelection();
46320 },
46321
46322 setPagesText : function() {
46323 var infoText = GeoTemConfig.getString('pageInfo');
46324 infoText = infoText.replace('PAGES_ID', this.pages);
46325 infoText = infoText.replace('PAGE_ID', this.page + 1);
46326 this.pageInfo.innerHTML = infoText;
46327 this.bottomPageInfo.innerHTML = infoText;
46328 },
46329
46330 setResultsText : function() {
46331 if (this.elements.length == 0) {
46332 this.resultsInfo.innerHTML = '0 Results';
46333 } else {
46334 var infoText = GeoTemConfig.getString('resultsInfo');
46335 var first = this.page * this.resultsPerPage + 1;
46336 var last = (this.page + 1 == this.pages ) ? this.showElementsLength : first + this.resultsPerPage - 1;
46337 infoText = infoText.replace('RESULTS_FROM_ID', first);
46338 infoText = infoText.replace('RESULTS_TO_ID', last);
46339 infoText = infoText.replace('RESULTS_ID', this.showElementsLength);
46340 this.resultsInfo.innerHTML = infoText;
46341 }
46342 },
46343
46344 updateIndices : function(rpp) {
46345 if ( typeof this.resultsPerPage == 'undefined') {
46346 this.page = 0;
46347 this.resultsPerPage = 0;
46348 }
46349 var index = this.page * this.resultsPerPage;
46350 this.resultsPerPage = rpp;
46351 if (this.showSelectedItems) {
46352 index = 0;
46353 }
46354 this.pages = Math.floor(this.showElementsLength / this.resultsPerPage);
46355 if (this.showElementsLength % this.resultsPerPage != 0) {
46356 this.pages++;
46357 }
46358 this.page = Math.floor(index / this.resultsPerPage);
46359 },
46360
46361 update : function() {
46362 var table = this;
46363 $(this.elementList).find("tr:gt(0)").remove();
46364 if (this.page == 0) {
46365 this.previousPage.setAttribute('class', 'paginationButton previousPageDisabled');
46366 this.firstPage.setAttribute('class', 'paginationButton firstPageDisabled');
46367 this.bottomPreviousPage.setAttribute('class', 'paginationButton previousPageDisabled');
46368 this.bottomFirstPage.setAttribute('class', 'paginationButton firstPageDisabled');
46369 } else {
46370 this.previousPage.setAttribute('class', 'paginationButton previousPageEnabled');
46371 this.firstPage.setAttribute('class', 'paginationButton firstPageEnabled');
46372 this.bottomPreviousPage.setAttribute('class', 'paginationButton previousPageEnabled');
46373 this.bottomFirstPage.setAttribute('class', 'paginationButton firstPageEnabled');
46374 }
46375 if (this.page == this.pages - 1) {
46376 this.nextPage.setAttribute('class', 'paginationButton nextPageDisabled');
46377 this.lastPage.setAttribute('class', 'paginationButton lastPageDisabled');
46378 this.bottomNextPage.setAttribute('class', 'paginationButton nextPageDisabled');
46379 this.bottomLastPage.setAttribute('class', 'paginationButton lastPageDisabled');
46380 } else {
46381 this.nextPage.setAttribute('class', 'paginationButton nextPageEnabled');
46382 this.lastPage.setAttribute('class', 'paginationButton lastPageEnabled');
46383 this.bottomNextPage.setAttribute('class', 'paginationButton nextPageEnabled');
46384 this.bottomLastPage.setAttribute('class', 'paginationButton lastPageEnabled');
46385 }
46386 this.setPagesText();
46387 this.setResultsText();
46388 if (this.showSelectedItems) {
46389 var start = this.page * this.resultsPerPage;
46390 var items = 0;
46391 for (var i = 0; i < this.elements.length; i++) {
46392 if (items == start) {
46393 this.first = i;
46394 break;
46395 }
46396 if (this.elements[i].selected) {
46397 items++;
46398 }
46399 }
46400 } else {
46401 this.first = this.page * this.resultsPerPage;
46402 }
46403 //this.last = ( this.page + 1 == this.pages ) ? this.elements.length : this.first + this.resultsPerPage;
46404 var c = GeoTemConfig.getColor(this.id);
46405 var itemSet = [];
46406 var clearDivs = function() {
46407 for (var i = 0; i < itemSet.length; i++) {
46408 if (!itemSet[i].e.selected) {
46409 itemSet[i].e.highlighted = false;
46410 $(itemSet[i].div).css('background-color', table.options.unselectedCellColor);
46411 }
46412 }
46413 }
46414 var setHighlight = function(item, div) {
46415 var enter = function() {
46416 clearDivs();
46417 if (!item.selected) {
46418 item.highlighted = true;
46419 $(div).css('background-color', 'rgb(' + c.r0 + ',' + c.g0 + ',' + c.b0 + ')');
46420 table.parent.triggerHighlight(item.object);
46421 }
46422 }
46423 var leave = function() {
46424 clearDivs();
46425 if (!item.selected) {
46426 table.parent.triggerHighlight();
46427 }
46428 }
46429 $(div).hover(enter, leave);
46430 $(div).mousemove(function() {
46431 if (!item.selected && !item.highlighted) {
46432 item.highlighted = true;
46433 $(div).css('background-color', 'rgb(' + c.r0 + ',' + c.g0 + ',' + c.b0 + ')');
46434 table.parent.triggerHighlight(item.object);
46435 }
46436 });
46437 }
46438 var setSelection = function(item, div, checkbox) {
46439 var click = function(e) {
46440 var checked = $(checkbox).is(':checked');
46441 if (checked) {
46442 item.selected = true;
46443 item.highlighted = false;
46444 } else {
46445 item.selected = false;
46446 item.highlighted = true;
46447 }
46448 //if( e.target == div ){
46449 // $(checkbox).attr('checked', !checked);
46450 //}
46451 table.parent.tableSelection();
46452 }
46453 //$(div).click(click);
46454 $(checkbox).click(click);
46455 }
46456 this.checkboxes = [];
46457 var items = 0;
46458 for (var i = this.first; i < this.elements.length; i++) {
46459 var e = this.elements[i];
46460 //vhz because of an error
46461 if ( typeof (e) == "undefined") {
46462 continue;
46463 }
46464 if (this.showSelectedItems && !e.selected) {
46465 continue;
46466 }
46467 var itemRow = $("<tr/>").appendTo(this.elementList);
46468 if (GeoTemConfig.allowFilter) {
46469 var checkColumn = $("<td/>").appendTo(itemRow);
46470 var checkbox = $("<input type='checkbox'/>").appendTo(checkColumn);
46471 $(checkbox).attr('checked', e.selected);
46472 }
46473 var makeSubtext = function(cell, text) {
46474 var subtext = text.substring(0, table.options.tableContentOffset);
46475 subtext = subtext.substring(0, subtext.lastIndexOf(' '));
46476 subtext += ' ... ';
46477 var textDiv = $("<div style='display:inline-block;'/>").appendTo(cell);
46478 $(textDiv).html(subtext);
46479 var show = false;
46480 var fullDiv = $("<div style='display:inline-block;'><a href='javascript:void(0)'>\>\></a></div>").appendTo(cell);
46481 $(fullDiv).click(function() {
46482 show = !show;
46483 if (show) {
46484 $(textDiv).html(text);
46485 $(fullDiv).html('<a href="javascript:void(0)">\<\<</a>');
46486 } else {
46487 $(textDiv).html(subtext);
46488 $(fullDiv).html('<a href="javascript:void(0)">\>\></a>');
46489 }
46490 });
46491 }
46492 for (var k = 0; k < table.keyHeaderList.length; k++) {
46493 var key = table.keyHeaderList[k];
46494 //vhz
46495 var text = e.object.tableContent[key];
46496 if (typeof text === "undefined")
46497 text = "";
46498 var cell = $("<td></td>").appendTo(itemRow);
46499
46500 //align the elements (if unset: "center")
46501 if (typeof table.options.verticalAlign !== "undefined"){
46502 if (table.options.verticalAlign === "top")
46503 $(cell).attr("valign","top");
46504 else if (table.options.verticalAlign === "center")
46505 $(cell).attr("valign","center");
46506 else if (table.options.verticalAlign === "bottom")
46507 $(cell).attr("valign","bottom");
46508 }
46509
46510 if (table.options.tableContentOffset && text.length < table.options.tableContentOffset) {
46511 $(cell).html(text);
46512 } else {
46513 makeSubtext(cell, text);
46514 }
46515 }
46516 if (e.selected || e.highlighted) {
46517 $(itemRow).css('background-color', 'rgb(' + c.r0 + ',' + c.g0 + ',' + c.b0 + ')');
46518 } else {
46519 $(itemRow).css('background-color', table.options.unselectedCellColor);
46520 }
46521 itemSet.push({
46522 e : e,
46523 div : itemRow
46524 });
46525 setHighlight(e, itemRow);
46526 if (GeoTemConfig.allowFilter) {
46527 setSelection(e, itemRow, checkbox);
46528 this.checkboxes.push(checkbox);
46529 $(checkColumn).css('text-align', 'center');
46530 }
46531 items++;
46532 if (items == this.resultsPerPage) {
46533 break;
46534 }
46535 }
46536 },
46537
46538 show : function() {
46539 if (GeoTemConfig.allowFilter) {
46540 this.parent.filterBar.appendTo(this.selectors);
46541 }
46542 this.tableDiv.style.display = "block";
46543 },
46544
46545 hide : function() {
46546 this.tableDiv.style.display = "none";
46547 },
46548
46549 resetElements : function() {
46550 for (var i = 0; i < this.elements.length; i++) {
46551 this.elements[i].selected = false;
46552 this.elements[i].highlighted = false;
46553 }
46554 },
46555
46556 reset : function() {
46557 if (!this.options.tableKeepShowSelected){
46558 this.showSelectedItems = false;
46559 this.showElementsLength = this.elements.length;
46560 this.showSelected.setAttribute('class', 'smallButton showSelected');
46561 }
46562 this.updateIndices(this.resultsPerPage);
46563 },
46564
46565 initialize : function() {
46566
46567 this.tableDiv = document.createElement("div");
46568 this.tableDiv.setAttribute('class', 'singleTable');
46569 this.parent.gui.input.appendChild(this.tableDiv);
46570
46571 this.initToolbar();
46572
46573 this.tableDiv.style.display = 'none';
46574 this.updateIndices(this.options.initialResultsPerPage);
46575
46576 this.update();
46577
46578 }
46579 }
46580
46581 function TableElement(object) {
46582
46583 this.object = object;
46584 this.selected = false;
46585 this.highlighted = false;
46586
46587 }
46588 /*
46589 * Dataloader.js
46590 *
46591 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
46592 *
46593 * This library is free software; you can redistribute it and/or
46594 * modify it under the terms of the GNU Lesser General Public
46595 * License as published by the Free Software Foundation; either
46596 * version 3 of the License, or (at your option) any later version.
46597 *
46598 * This library is distributed in the hope that it will be useful,
46599 * but WITHOUT ANY WARRANTY; without even the implied warranty of
46600 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
46601 * Lesser General Public License for more details.
46602 *
46603 * You should have received a copy of the GNU Lesser General Public
46604 * License along with this library; if not, write to the Free Software
46605 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
46606 * MA 02110-1301 USA
46607 */
46608
46609 /**
46610 * @class Dataloader
46611 * Implementation for a Dataloader UI
46612 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
46613 *
46614 * @param {HTML object} parent div to append the Dataloader
46615 */
46616 function Dataloader(parent) {
46617
46618 this.dataLoader = this;
46619
46620 this.parent = parent;
46621 this.options = parent.options;
46622
46623 this.initialize();
46624 }
46625
46626 Dataloader.prototype = {
46627
46628 show : function() {
46629 this.dataloaderDiv.style.display = "block";
46630 },
46631
46632 hide : function() {
46633 this.dataloaderDiv.style.display = "none";
46634 },
46635
46636 initialize : function() {
46637
46638 this.addStaticLoader();
46639 this.addLocalStorageLoader();
46640 this.addKMLLoader();
46641 this.addKMZLoader();
46642 this.addCSVLoader();
46643 this.addLocalKMLLoader();
46644 this.addLocalCSVLoader();
46645 this.addLocalXLSXLoader();
46646
46647 // trigger change event on the select so
46648 // that only the first loader div will be shown
46649 $(this.parent.gui.loaderTypeSelect).change();
46650 },
46651
46652 getFileName : function(url) {
46653 var fileName = $.url(url).attr('file');
46654 if ( (typeof fileName === "undefined") || (fileName.length === 0) ){
46655 fileName = $.url(url).attr('path');
46656 //startsWith and endsWith defined in SIMILE Ajax (string.js)
46657 while (fileName.endsWith("/")){
46658 fileName = fileName.substr(0,fileName.length-1);
46659 }
46660 if (fileName.length > 1)
46661 fileName = fileName.substr(fileName.lastIndexOf("/")+1);
46662 else
46663 fileName = "unnamed dataset";
46664 }
46665 return fileName;
46666 },
46667
46668 distributeDataset : function(dataSet) {
46669 GeoTemConfig.addDataset(dataSet);
46670 },
46671
46672 distributeDatasets : function(datasets) {
46673 GeoTemConfig.addDatasets(datasets);
46674 },
46675
46676 addStaticLoader : function() {
46677 if (this.options.staticKML.length > 0){
46678 $(this.parent.gui.loaderTypeSelect).append("<option value='StaticLoader'>Static Data</option>");
46679
46680 this.StaticLoaderTab = document.createElement("div");
46681 $(this.StaticLoaderTab).attr("id","StaticLoader");
46682
46683 this.staticKMLList = document.createElement("select");
46684 $(this.StaticLoaderTab).append(this.staticKMLList);
46685
46686 var staticKMLList = this.staticKMLList;
46687 var isFirstHeader = true;
46688 $(this.options.staticKML).each(function(){
46689 var label = this.label;
46690 var url = this.url;
46691 var header = this.header;
46692 if (typeof header !== "undefined"){
46693 if (!isFirstHeader)
46694 $(staticKMLList).append("</optgroup>");
46695 $(staticKMLList).append("<optgroup label='"+header+"'>");
46696 isFirstHeader = false;
46697 } else
46698 $(staticKMLList).append("<option value='"+url+"'> "+label+"</option>");
46699 });
46700 //close last optgroup (if there were any)
46701 if (!isFirstHeader)
46702 $(staticKMLList).append("</optgroup>");
46703
46704 this.loadStaticKMLButton = document.createElement("button");
46705 $(this.loadStaticKMLButton).text("load");
46706 $(this.StaticLoaderTab).append(this.loadStaticKMLButton);
46707
46708 $(this.loadStaticKMLButton).click($.proxy(function(){
46709 var kmlURL = $(this.staticKMLList).find(":selected").attr("value");
46710 if (kmlURL.length === 0)
46711 return;
46712 var origURL = kmlURL;
46713 var fileName = this.getFileName(kmlURL);
46714 if (typeof GeoTemConfig.proxy != 'undefined')
46715 kmlURL = GeoTemConfig.proxy + kmlURL;
46716 var kml = GeoTemConfig.getKml(kmlURL);
46717 if ((typeof kml !== "undefined") && (kml != null)) {
46718 var dataSet = new Dataset(GeoTemConfig.loadKml(kml), fileName, origURL);
46719
46720 if (dataSet != null)
46721 this.distributeDataset(dataSet);
46722 } else
46723 alert("Could not load file.");
46724 },this));
46725
46726 $(this.parent.gui.loaders).append(this.StaticLoaderTab);
46727 }
46728 },
46729
46730 addKMLLoader : function() {
46731 $(this.parent.gui.loaderTypeSelect).append("<option value='KMLLoader'>KML File URL</option>");
46732
46733 this.KMLLoaderTab = document.createElement("div");
46734 $(this.KMLLoaderTab).attr("id","KMLLoader");
46735
46736 this.kmlURL = document.createElement("input");
46737 $(this.kmlURL).attr("type","text");
46738 $(this.KMLLoaderTab).append(this.kmlURL);
46739
46740 this.loadKMLButton = document.createElement("button");
46741 $(this.loadKMLButton).text("load KML");
46742 $(this.KMLLoaderTab).append(this.loadKMLButton);
46743
46744 $(this.loadKMLButton).click($.proxy(function(){
46745 var kmlURL = $(this.kmlURL).val();
46746 if (kmlURL.length === 0)
46747 return;
46748 var origURL = kmlURL;
46749 var fileName = this.getFileName(kmlURL);
46750 if (typeof GeoTemConfig.proxy != 'undefined')
46751 kmlURL = GeoTemConfig.proxy + kmlURL;
46752 var kml = GeoTemConfig.getKml(kmlURL);
46753 if ((typeof kml !== "undefined") && (kml != null)) {
46754 var dataSet = new Dataset(GeoTemConfig.loadKml(kml), fileName, origURL);
46755
46756 if (dataSet != null)
46757 this.distributeDataset(dataSet);
46758 } else
46759 alert("Could not load file.");
46760 },this));
46761
46762 $(this.parent.gui.loaders).append(this.KMLLoaderTab);
46763 },
46764
46765 addKMZLoader : function() {
46766 $(this.parent.gui.loaderTypeSelect).append("<option value='KMZLoader'>KMZ File URL</option>");
46767
46768 this.KMZLoaderTab = document.createElement("div");
46769 $(this.KMZLoaderTab).attr("id","KMZLoader");
46770
46771 this.kmzURL = document.createElement("input");
46772 $(this.kmzURL).attr("type","text");
46773 $(this.KMZLoaderTab).append(this.kmzURL);
46774
46775 this.loadKMZButton = document.createElement("button");
46776 $(this.loadKMZButton).text("load KMZ");
46777 $(this.KMZLoaderTab).append(this.loadKMZButton);
46778
46779 $(this.loadKMZButton).click($.proxy(function(){
46780
46781 var dataLoader = this;
46782
46783 var kmzURL = $(this.kmzURL).val();
46784 if (kmzURL.length === 0)
46785 return;
46786 var origURL = kmzURL;
46787 var fileName = dataLoader.getFileName(kmzURL);
46788 if (typeof GeoTemConfig.proxy != 'undefined')
46789 kmzURL = GeoTemConfig.proxy + kmzURL;
46790
46791 GeoTemConfig.getKmz(kmzURL, function(kmlArray){
46792 $(kmlArray).each(function(){
46793 var dataSet = new Dataset(GeoTemConfig.loadKml(this), fileName, origURL);
46794
46795 if (dataSet != null)
46796 dataLoader.distributeDataset(dataSet);
46797 });
46798 });
46799 },this));
46800
46801 $(this.parent.gui.loaders).append(this.KMZLoaderTab);
46802 },
46803
46804 addCSVLoader : function() {
46805 $(this.parent.gui.loaderTypeSelect).append("<option value='CSVLoader'>CSV File URL</option>");
46806
46807 this.CSVLoaderTab = document.createElement("div");
46808 $(this.CSVLoaderTab).attr("id","CSVLoader");
46809
46810 this.csvURL = document.createElement("input");
46811 $(this.csvURL).attr("type","text");
46812 $(this.CSVLoaderTab).append(this.csvURL);
46813
46814 this.loadCSVButton = document.createElement("button");
46815 $(this.loadCSVButton).text("load CSV");
46816 $(this.CSVLoaderTab).append(this.loadCSVButton);
46817
46818 $(this.loadCSVButton).click($.proxy(function(){
46819 var dataLoader = this;
46820
46821 var csvURL = $(this.csvURL).val();
46822 if (csvURL.length === 0)
46823 return;
46824 var origURL = csvURL;
46825 var fileName = dataLoader.getFileName(csvURL);
46826 if (typeof GeoTemConfig.proxy != 'undefined')
46827 csvURL = GeoTemConfig.proxy + csvURL;
46828 GeoTemConfig.getCsv(csvURL, function(json){
46829 if ((typeof json !== "undefined") && (json.length > 0)) {
46830 var dataSet = new Dataset(GeoTemConfig.loadJson(json), fileName, origURL);
46831
46832 if (dataSet != null)
46833 dataLoader.distributeDataset(dataSet);
46834 } else
46835 alert("Could not load file.");
46836 });
46837 },this));
46838
46839 $(this.parent.gui.loaders).append(this.CSVLoaderTab);
46840 },
46841
46842 addLocalKMLLoader : function() {
46843 $(this.parent.gui.loaderTypeSelect).append("<option value='LocalKMLLoader'>local KML File</option>");
46844
46845 this.localKMLLoaderTab = document.createElement("div");
46846 $(this.localKMLLoaderTab).attr("id","LocalKMLLoader");
46847
46848 this.kmlFile = document.createElement("input");
46849 $(this.kmlFile).attr("type","file");
46850 $(this.localKMLLoaderTab).append(this.kmlFile);
46851
46852 this.loadLocalKMLButton = document.createElement("button");
46853 $(this.loadLocalKMLButton).text("load KML");
46854 $(this.localKMLLoaderTab).append(this.loadLocalKMLButton);
46855
46856 $(this.loadLocalKMLButton).click($.proxy(function(){
46857 var filelist = $(this.kmlFile).get(0).files;
46858 if (filelist.length > 0){
46859 var file = filelist[0];
46860 var fileName = file.name;
46861 var reader = new FileReader();
46862
46863 reader.onloadend = ($.proxy(function(theFile) {
46864 return function(e) {
46865 var dataSet = new Dataset(GeoTemConfig.loadKml($.parseXML(reader.result)), fileName);
46866 if (dataSet != null)
46867 this.distributeDataset(dataSet);
46868 };
46869 }(file),this));
46870
46871 reader.readAsText(file);
46872 }
46873 },this));
46874
46875 $(this.parent.gui.loaders).append(this.localKMLLoaderTab);
46876 },
46877
46878 addLocalCSVLoader : function() {
46879 $(this.parent.gui.loaderTypeSelect).append("<option value='LocalCSVLoader'>local CSV File</option>");
46880
46881 this.localCSVLoaderTab = document.createElement("div");
46882 $(this.localCSVLoaderTab).attr("id","LocalCSVLoader");
46883
46884 this.csvFile = document.createElement("input");
46885 $(this.csvFile).attr("type","file");
46886 $(this.localCSVLoaderTab).append(this.csvFile);
46887
46888 this.loadLocalCSVButton = document.createElement("button");
46889 $(this.loadLocalCSVButton).text("load CSV");
46890 $(this.localCSVLoaderTab).append(this.loadLocalCSVButton);
46891
46892 $(this.loadLocalCSVButton).click($.proxy(function(){
46893 var filelist = $(this.csvFile).get(0).files;
46894 if (filelist.length > 0){
46895 var file = filelist[0];
46896 var fileName = file.name;
46897 var reader = new FileReader();
46898
46899 reader.onloadend = ($.proxy(function(theFile) {
46900 return function(e) {
46901 var json = GeoTemConfig.convertCsv(reader.result);
46902 var dataSet = new Dataset(GeoTemConfig.loadJson(json), fileName);
46903 if (dataSet != null)
46904 this.distributeDataset(dataSet);
46905 };
46906 }(file),this));
46907
46908 reader.readAsText(file);
46909 }
46910 },this));
46911
46912 $(this.parent.gui.loaders).append(this.localCSVLoaderTab);
46913 },
46914
46915 addLocalStorageLoader : function() {
46916 var dataLoader = this;
46917 this.localStorageLoaderTab = document.createElement("div");
46918 $(this.localStorageLoaderTab).attr("id","LocalStorageLoader");
46919
46920 var localDatasets = document.createElement("select");
46921 $(this.localStorageLoaderTab).append(localDatasets);
46922
46923 var localStorageDatasetCount = 0;
46924 for(var key in localStorage){
46925 //TODO: this is a somewhat bad idea, as it is used in multiple widgets.
46926 //A global GeoTemCo option "prefix" could be better. But still..
46927 if (key.startsWith("GeoBrowser_dataset_")){
46928 localStorageDatasetCount++;
46929 var label = key.substring("GeoBrowser_dataset_".length);
46930 var url = key;
46931 $(localDatasets).append("<option value='"+url+"'>"+decodeURIComponent(label)+"</option>");
46932 }
46933 }
46934
46935 //only show if there are datasets
46936 if (localStorageDatasetCount > 0)
46937 $(this.parent.gui.loaderTypeSelect).append("<option value='LocalStorageLoader'>browser storage</option>");
46938
46939 this.loadLocalStorageButton = document.createElement("button");
46940 $(this.loadLocalStorageButton).text("load");
46941 $(this.localStorageLoaderTab).append(this.loadLocalStorageButton);
46942
46943 $(this.loadLocalStorageButton).click($.proxy(function(){
46944 var fileKey = $(localDatasets).find(":selected").attr("value");
46945 if (fileKey.length === 0)
46946 return;
46947 var csv = $.remember({name:fileKey});
46948 //TODO: this is a somewhat bad idea, as it is used in multiple widgets.
46949 //A global GeoTemCo option "prefix" could be better. But still..
46950 var fileName = decodeURIComponent(fileKey.substring("GeoBrowser_dataset_".length));
46951 var json = GeoTemConfig.convertCsv(csv);
46952 var dataSet = new Dataset(GeoTemConfig.loadJson(json), fileName, fileKey, "local");
46953 if (dataSet != null)
46954 dataLoader.distributeDataset(dataSet);
46955 },this));
46956
46957 $(this.parent.gui.loaders).append(this.localStorageLoaderTab);
46958 },
46959
46960 addLocalXLSXLoader : function() {
46961 //taken from http://oss.sheetjs.com/js-xlsx/
46962 var fixdata = function(data) {
46963 var o = "", l = 0, w = 10240;
46964 for(; l<data.byteLength/w; ++l) o+=String.fromCharCode.apply(null,new Uint8Array(data.slice(l*w,l*w+w)));
46965 o+=String.fromCharCode.apply(null, new Uint8Array(data.slice(o.length)));
46966 return o;
46967 }
46968
46969 $(this.parent.gui.loaderTypeSelect).append("<option value='LocalXLSXLoader'>local XLS/XLSX File</option>");
46970
46971 this.LocalXLSXLoader = document.createElement("div");
46972 $(this.LocalXLSXLoader).attr("id","LocalXLSXLoader");
46973
46974 this.xlsxFile = document.createElement("input");
46975 $(this.xlsxFile).attr("type","file");
46976 $(this.LocalXLSXLoader).append(this.xlsxFile);
46977
46978 this.loadLocalXLSXButton = document.createElement("button");
46979 $(this.loadLocalXLSXButton).text("load XLS/XLSX");
46980 $(this.LocalXLSXLoader).append(this.loadLocalXLSXButton);
46981
46982 $(this.loadLocalXLSXButton).click($.proxy(function(){
46983 var filelist = $(this.xlsxFile).get(0).files;
46984 if (filelist.length > 0){
46985 var file = filelist[0];
46986 var fileName = file.name;
46987 var reader = new FileReader();
46988
46989 reader.onloadend = ($.proxy(function(theFile) {
46990 return function(e) {
46991 var workbook;
46992 var json;
46993 if (fileName.toLowerCase().indexOf("xlsx")!=-1){
46994 workbook = XLSX.read(btoa(fixdata(reader.result)), {type: 'base64'});
46995 var csv = XLSX.utils.sheet_to_csv(workbook.Sheets[workbook.SheetNames[0]]);
46996 var json = GeoTemConfig.convertCsv(csv);
46997 } else {
46998 workbook = XLS.read(btoa(fixdata(reader.result)), {type: 'base64'});
46999 var csv = XLS.utils.sheet_to_csv(workbook.Sheets[workbook.SheetNames[0]]);
47000 var json = GeoTemConfig.convertCsv(csv);
47001 }
47002
47003 var dataSet = new Dataset(GeoTemConfig.loadJson(json), fileName);
47004 if (dataSet != null)
47005 this.distributeDataset(dataSet);
47006 };
47007 }(file),this));
47008
47009 reader.readAsArrayBuffer(file);
47010 }
47011 },this));
47012
47013 $(this.parent.gui.loaders).append(this.LocalXLSXLoader);
47014 },
47015 };
47016 /*
47017 * DataloaderConfig.js
47018 *
47019 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
47020 *
47021 * This library is free software; you can redistribute it and/or
47022 * modify it under the terms of the GNU Lesser General Public
47023 * License as published by the Free Software Foundation; either
47024 * version 3 of the License, or (at your option) any later version.
47025 *
47026 * This library is distributed in the hope that it will be useful,
47027 * but WITHOUT ANY WARRANTY; without even the implied warranty of
47028 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
47029 * Lesser General Public License for more details.
47030 *
47031 * You should have received a copy of the GNU Lesser General Public
47032 * License along with this library; if not, write to the Free Software
47033 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
47034 * MA 02110-1301 USA
47035 */
47036
47037 /**
47038 * @class DataloaderConfig
47039 * Dataloader Configuration File
47040 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
47041 */
47042 function DataloaderConfig(options) {
47043
47044 this.options = {
47045 staticKML : [
47046 // {header: "header label"},
47047 // {label: "Johann Wolfgang von Goethe", url:"http://.../goethe.kml" },
47048 ]
47049 };
47050 if ( typeof options != 'undefined') {
47051 $.extend(this.options, options);
47052 }
47053
47054 };
47055 /*
47056 * DataloaderGui.js
47057 *
47058 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
47059 *
47060 * This library is free software; you can redistribute it and/or
47061 * modify it under the terms of the GNU Lesser General Public
47062 * License as published by the Free Software Foundation; either
47063 * version 3 of the License, or (at your option) any later version.
47064 *
47065 * This library is distributed in the hope that it will be useful,
47066 * but WITHOUT ANY WARRANTY; without even the implied warranty of
47067 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
47068 * Lesser General Public License for more details.
47069 *
47070 * You should have received a copy of the GNU Lesser General Public
47071 * License along with this library; if not, write to the Free Software
47072 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
47073 * MA 02110-1301 USA
47074 */
47075
47076 /**
47077 * @class DataloaderGui
47078 * Dataloader GUI Implementation
47079 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
47080 *
47081 * @param {DataloaderWidget} parent Dataloader widget object
47082 * @param {HTML object} div parent div to append the Dataloader gui
47083 * @param {JSON} options Dataloader configuration
47084 */
47085 function DataloaderGui(dataloader, div, options) {
47086
47087 var dataloaderGui = this;
47088
47089 this.dataloaderContainer = div;
47090 this.dataloaderContainer.style.position = 'relative';
47091
47092 this.loaderTypeSelect = document.createElement("select");
47093 div.appendChild(this.loaderTypeSelect);
47094
47095 this.loaders = document.createElement("div");
47096 div.appendChild(this.loaders);
47097
47098 $(this.loaderTypeSelect).change(function(){
47099 var activeLoader = $(this).val();
47100 $(dataloaderGui.loaders).find("div").each(function(){
47101 if ($(this).attr("id") == activeLoader)
47102 $(this).show();
47103 else
47104 $(this).hide();
47105 });
47106 });
47107 };
47108 /*
47109 * DataloaderWidget.js
47110 *
47111 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
47112 *
47113 * This library is free software; you can redistribute it and/or
47114 * modify it under the terms of the GNU Lesser General Public
47115 * License as published by the Free Software Foundation; either
47116 * version 3 of the License, or (at your option) any later version.
47117 *
47118 * This library is distributed in the hope that it will be useful,
47119 * but WITHOUT ANY WARRANTY; without even the implied warranty of
47120 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
47121 * Lesser General Public License for more details.
47122 *
47123 * You should have received a copy of the GNU Lesser General Public
47124 * License along with this library; if not, write to the Free Software
47125 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
47126 * MA 02110-1301 USA
47127 */
47128
47129 /**
47130 * @class DataloaderWidget
47131 * DataloaderWidget Implementation
47132 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
47133 *
47134 * @param {WidgetWrapper} core wrapper for interaction to other widgets
47135 * @param {HTML object} div parent div to append the Dataloader widget div
47136 * @param {JSON} options user specified configuration that overwrites options in DataloaderConfig.js
47137 */
47138 DataloaderWidget = function(core, div, options) {
47139
47140 this.core = core;
47141 this.core.setWidget(this);
47142
47143 this.options = (new DataloaderConfig(options)).options;
47144 this.gui = new DataloaderGui(this, div, this.options);
47145
47146 this.dataLoader = new Dataloader(this);
47147
47148 this.datasets = [];
47149 }
47150
47151 DataloaderWidget.prototype = {
47152
47153 initWidget : function() {
47154
47155 var dataloaderWidget = this;
47156 },
47157
47158 highlightChanged : function(objects) {
47159 if( !GeoTemConfig.highlightEvents ){
47160 return;
47161 }
47162 },
47163
47164 selectionChanged : function(selection) {
47165 if( !GeoTemConfig.selectionEvents ){
47166 return;
47167 }
47168 },
47169
47170 triggerHighlight : function(item) {
47171 },
47172
47173 tableSelection : function() {
47174 },
47175
47176 deselection : function() {
47177 },
47178
47179 filtering : function() {
47180 },
47181
47182 inverseFiltering : function() {
47183 },
47184
47185 triggerRefining : function() {
47186 },
47187
47188 reset : function() {
47189 },
47190
47191 loadRenames : function(){
47192 //load (optional!) attribute renames
47193 //each rename param is {latitude:..,longitude:..,place:..,date:..,timeSpanBegin:..,timeSpanEnd:..}
47194 //examples:
47195 // &rename1={"latitude":"lat1","longitude":"lon1"}
47196 // &rename2=[{"latitude":"lat1","longitude":"lon1"},{"latitude":"lat2","longitude":"lon2"}]
47197 var dataLoaderWidget = this;
47198 var datasets = dataLoaderWidget.datasets;
47199 $.each($.url().param(),function(paramName, paramValue){
47200 if (paramName.toLowerCase().startsWith("rename")){
47201 var datasetID = parseInt(paramName.replace(/\D/g,''));
47202 var dataset;
47203 if (isNaN(datasetID)){
47204 var dataset;
47205 for (datasetID in datasets){
47206 break;
47207 }
47208 }
47209 dataset = datasets[datasetID];
47210
47211 if (typeof dataset === "undefined")
47212 return;
47213
47214 var renameFunc = function(index,latAttr,lonAttr,placeAttr,dateAttr,timespanBeginAttr,
47215 timespanEndAttr,indexAttr){
47216 var renameArray = [];
47217
47218 if (typeof index === "undefined"){
47219 index = 0;
47220 }
47221
47222 if ((typeof latAttr !== "undefined") && (typeof lonAttr !== "undefined")){
47223 renameArray.push({
47224 oldColumn:latAttr,
47225 newColumn:"locations["+index+"].latitude"
47226 });
47227 renameArray.push({
47228 oldColumn:lonAttr,
47229 newColumn:"locations["+index+"].longitude"
47230 });
47231 }
47232
47233 if (typeof placeAttr !== "undefined"){
47234 renameArray.push({
47235 oldColumn:placeAttr,
47236 newColumn:"locations["+index+"].place"
47237 });
47238 }
47239
47240 if (typeof dateAttr !== "undefined"){
47241 renameArray.push({
47242 oldColumn:dateAttr,
47243 newColumn:"dates["+index+"]"
47244 });
47245 }
47246
47247 if ((typeof timespanBeginAttr !== "undefined") &&
47248 (typeof timespanEndAttr !== "undefined")){
47249 renameArray.push({
47250 oldColumn:timespanBeginAttr,
47251 newColumn:"tableContent[TimeSpan:begin]"
47252 });
47253 renameArray.push({
47254 oldColumn:timespanEndAttr,
47255 newColumn:"tableContent[TimeSpan:end]"
47256 });
47257 }
47258
47259 if (typeof indexAttr !== "undefined"){
47260 renameArray.push({
47261 oldColumn:indexAttr,
47262 newColumn:"index"
47263 });
47264 }
47265
47266 GeoTemConfig.renameColumns(dataset,renameArray);
47267 };
47268
47269 var renames = JSON.parse(paramValue);
47270
47271 if (renames instanceof Array){
47272 for (var i=0; i < renames.length; i++){
47273 renameFunc(i,renames[i].latitude,renames[i].longitude,renames[i].place,renames[i].date,
47274 renames[i].timeSpanBegin,renames[i].timeSpanEnd,renames[i].index);
47275 }
47276 } else {
47277 renameFunc(0,renames.latitude,renames.longitude,renames.place,renames.date,
47278 renames.timeSpanBegin,renames.timeSpanEnd,renames.index);
47279 }
47280 }
47281 });
47282 },
47283
47284 loadFilters : function(){
47285 //load (optional!) filters
47286 //those will create a new(!) dataset, that only contains the filtered IDs
47287 var dataLoaderWidget = this;
47288 var datasets = dataLoaderWidget.datasets;
47289 $.each($.url().param(),function(paramName, paramValue){
47290 //startsWith and endsWith defined in SIMILE Ajax (string.js)
47291 if (paramName.toLowerCase().startsWith("filter")){
47292 var datasetID = parseInt(paramName.replace(/\D/g,''));
47293 var dataset;
47294 if (isNaN(datasetID)){
47295 var dataset;
47296 for (datasetID in datasets){
47297 break;
47298 }
47299 }
47300 dataset = datasets[datasetID];
47301
47302 if (typeof dataset === "undefined")
47303 return;
47304
47305 var filterValues = function(paramValue){
47306 var filter = JSON.parse(paramValue);
47307 var filteredObjects = [];
47308 for(var i = 0; i < dataset.objects.length; i++){
47309 var dataObject = dataset.objects[i];
47310 if ($.inArray(dataObject.index,filter) != -1){
47311 filteredObjects.push(dataObject);
47312 }
47313 }
47314 var filteredDataset = new Dataset(filteredObjects, dataset.label + " (filtered)", dataset.url, dataset.type);
47315 datasets.push(filteredDataset);
47316 }
47317
47318 if (paramValue instanceof Array){
47319 for (var i=0; i < paramValue.length; i++){
47320 filterValues(paramValue[i]);
47321 }
47322 } else {
47323 filterValues(paramValue);
47324 }
47325
47326 }
47327 });
47328 },
47329
47330 loadColors : function(){
47331 //Load the (optional!) dataset colors
47332 var dataLoaderWidget = this;
47333 var datasets = dataLoaderWidget.datasets;
47334 $.each($.url().param(),function(paramName, paramValue){
47335 if (paramName.toLowerCase().startsWith("color")){
47336 //color is 1-based, index is 0-based!
47337 var datasetID = parseInt(paramName.replace(/\D/g,''));
47338 if (datasets.length > datasetID){
47339 if (typeof datasets[datasetID].color === "undefined"){
47340 var color = new Object();
47341 var colorsSelectedUnselected = paramValue.split(",");
47342 if (colorsSelectedUnselected.length > 2)
47343 return;
47344
47345 var color1 = colorsSelectedUnselected[0];
47346 if (color1.length != 6)
47347 return;
47348
47349 color.r1 = parseInt(color1.substr(0,2),16);
47350 color.g1 = parseInt(color1.substr(2,2),16);
47351 color.b1 = parseInt(color1.substr(4,2),16);
47352
47353 //check if a unselected color is given
47354 if (colorsSelectedUnselected.length == 2){
47355 var color0 = colorsSelectedUnselected[1];
47356 if (color0.length != 6)
47357 return;
47358
47359 color.r0 = parseInt(color0.substr(0,2),16);
47360 color.g0 = parseInt(color0.substr(2,2),16);
47361 color.b0 = parseInt(color0.substr(4,2),16);
47362 } else {
47363 //if not: use the selected color "halved"
47364 color.r0 = Math.round(color.r1/2);
47365 color.g0 = Math.round(color.g1/2);
47366 color.b0 = Math.round(color.b1/2);
47367 }
47368
47369 datasets[datasetID].color = color;
47370 }
47371 }
47372 }
47373 });
47374 },
47375
47376 loadFromURL : function() {
47377 var dataLoaderWidget = this;
47378 dataLoaderWidget.datasets = [];
47379 //using jQuery-URL-Parser (https://github.com/skruse/jQuery-URL-Parser)
47380 var datasets = dataLoaderWidget.datasets;
47381 var parametersHash = $.url().param();
47382 var parametersArray = [];
47383 $.each(parametersHash,function(paramName, paramValue){
47384 parametersArray.push({paramName:paramName, paramValue:paramValue});
47385 });
47386
47387 var parseParam = function(paramNr){
47388
47389 if (paramNr==parametersArray.length){
47390 dataLoaderWidget.loadRenames();
47391 dataLoaderWidget.loadFilters();
47392 dataLoaderWidget.loadColors();
47393
47394 //delete undefined entries in the array
47395 //(can happen if the sequence given in the URL is not complete
47396 // e.g. kml0=..,kml2=..)
47397 //this also reorders the array, starting with 0
47398 var tempDatasets = [];
47399 for(var index in datasets){
47400 if (datasets[index] instanceof Dataset){
47401 tempDatasets.push(datasets[index]);
47402 }
47403 }
47404 datasets = tempDatasets;
47405
47406 if (datasets.length > 0){
47407 dataLoaderWidget.dataLoader.distributeDatasets(datasets);
47408 }
47409 return;
47410 }
47411
47412 var paramName = parametersArray[paramNr].paramName;
47413 var paramValue = parametersArray[paramNr].paramValue;
47414
47415 var datasetID = parseInt(paramName.replace(/\D/g,''));
47416
47417 //startsWith and endsWith defined in SIMILE Ajax (string.js)
47418 var fileName = dataLoaderWidget.dataLoader.getFileName(paramValue);
47419 var origURL = paramValue;
47420 if (typeof GeoTemConfig.proxy != 'undefined')
47421 paramValue = GeoTemConfig.proxy + paramValue;
47422 if (paramName.toLowerCase().startsWith("kml")){
47423 GeoTemConfig.getKml(paramValue, function(kmlDoc){
47424 var dataSet = new Dataset(GeoTemConfig.loadKml(kmlDoc), fileName, origURL);
47425 if (dataSet != null){
47426 if (!isNaN(datasetID)){
47427 datasets[datasetID] = dataSet;
47428 } else {
47429 datasets.push(dataSet);
47430 }
47431 }
47432 setTimeout(function(){parseParam(paramNr+1)},1);
47433 });
47434 }
47435 else if (paramName.toLowerCase().startsWith("csv")){
47436 GeoTemConfig.getCsv(paramValue,function(json){
47437 var dataSet = new Dataset(GeoTemConfig.loadJson(json), fileName, origURL);
47438 if (dataSet != null){
47439 if (!isNaN(datasetID)){
47440 datasets[datasetID] = dataSet;
47441 } else {
47442 datasets.push(dataSet);
47443 }
47444 }
47445 setTimeout(function(){parseParam(paramNr+1)},1);
47446 });
47447 }
47448 else if (paramName.toLowerCase().startsWith("json")){
47449 GeoTemConfig.getJson(paramValue,function(json ){
47450 var dataSet = new Dataset(GeoTemConfig.loadJson(json), fileName, origURL);
47451 if (dataSet != null){
47452 if (!isNaN(datasetID)){
47453 datasets[datasetID] = dataSet;
47454 } else {
47455 datasets.push(dataSet);
47456 }
47457 }
47458 setTimeout(function(){parseParam(paramNr+1)},1);
47459 });
47460 }
47461 else if (paramName.toLowerCase().startsWith("local")){
47462 var csv = $.remember({name:encodeURIComponent(origURL)});
47463 //TODO: this is a bad idea and will be changed upon having a better
47464 //usage model for local stored data
47465 var fileName = origURL.substring("GeoBrowser_dataset_".length);
47466 var json = GeoTemConfig.convertCsv(csv);
47467 var dataSet = new Dataset(GeoTemConfig.loadJson(json), fileName, origURL, "local");
47468 if (dataSet != null){
47469 if (!isNaN(datasetID)){
47470 datasets[datasetID] = dataSet;
47471 } else {
47472 datasets.push(dataSet);
47473 }
47474 }
47475 setTimeout(function(){parseParam(paramNr+1)},1);
47476 } else if (paramName.toLowerCase().startsWith("xls")){
47477 GeoTemConfig.getBinary(paramValue,function(binaryData){
47478 var data = new Uint8Array(binaryData);
47479 var arr = new Array();
47480 for(var i = 0; i != data.length; ++i){
47481 arr[i] = String.fromCharCode(data[i]);
47482 }
47483
47484 var workbook;
47485 var json;
47486 if (paramName.toLowerCase().startsWith("xlsx")){
47487 workbook = XLSX.read(arr.join(""), {type:"binary"});
47488 var csv = XLSX.utils.sheet_to_csv(workbook.Sheets[workbook.SheetNames[0]]);
47489 var json = GeoTemConfig.convertCsv(csv);
47490 } else {
47491 workbook = XLS.read(arr.join(""), {type:"binary"});
47492 var csv = XLS.utils.sheet_to_csv(workbook.Sheets[workbook.SheetNames[0]]);
47493 var json = GeoTemConfig.convertCsv(csv);
47494 }
47495
47496 var dataSet = new Dataset(GeoTemConfig.loadJson(json), fileName, origURL);
47497 if (dataSet != null){
47498 if (!isNaN(datasetID)){
47499 datasets[datasetID] = dataSet;
47500 } else {
47501 datasets.push(dataSet);
47502 }
47503 }
47504 setTimeout(function(){parseParam(paramNr+1)},1);
47505 });
47506 } else {
47507 setTimeout(function(){parseParam(paramNr+1)},1);
47508 }
47509 };
47510
47511 if (parametersArray.length>0){
47512 parseParam(0)
47513 }
47514 }
47515 };
47516 /*
47517 * FuzzyTimelineConfig.js
47518 *
47519 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
47520 *
47521 * This library is free software; you can redistribute it and/or
47522 * modify it under the terms of the GNU Lesser General Public
47523 * License as published by the Free Software Foundation; either
47524 * version 3 of the License, or (at your option) any later version.
47525 *
47526 * This library is distributed in the hope that it will be useful,
47527 * but WITHOUT ANY WARRANTY; without even the implied warranty of
47528 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
47529 * Lesser General Public License for more details.
47530 *
47531 * You should have received a copy of the GNU Lesser General Public
47532 * License along with this library; if not, write to the Free Software
47533 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
47534 * MA 02110-1301 USA
47535 */
47536
47537 /**
47538 * @class FuzzyTimelineConfig
47539 * FuzzyTimeline Configuration File
47540 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
47541 */
47542 function FuzzyTimelineConfig(options) {
47543
47544 this.options = {
47545 //TODO: experiment with number of ticks, 150 seems to be ok for now
47546 maxBars : 50,
47547 maxDensityTicks : 150,
47548 /*drawing modes:
47549 * fuzzy - weight is distributed over all spans an object overlaps, so that the sum remains the weight,
47550 * stacking - every span that on object overlaps gets the complete weight (limited by the amount the span is overlapped, e.g. first span and last might get less)
47551 */
47552 timelineMode : 'stacking',
47553 showRangePiechart : false,
47554 backgroundColor : "#EEEEEE",
47555 showYAxis : true,
47556 //whether time-spans that "enlargen" the plot are allowed
47557 //if set to true, a span that creates more "bars" than fit on the screen
47558 //will lead to a width-increase of the chart (and a scroll bar appears)
47559 showAllPossibleSpans : true,
47560 };
47561 if ( typeof options != 'undefined') {
47562 $.extend(this.options, options);
47563 }
47564
47565 };
47566 /*
47567 * FuzzyTimelineDensity.js
47568 *
47569 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
47570 *
47571 * This library is free software; you can redistribute it and/or
47572 * modify it under the terms of the GNU Lesser General Public
47573 * License as published by the Free Software Foundation; either
47574 * version 3 of the License, or (at your option) any later version.
47575 *
47576 * This library is distributed in the hope that it will be useful,
47577 * but WITHOUT ANY WARRANTY; without even the implied warranty of
47578 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
47579 * Lesser General Public License for more details.
47580 *
47581 * You should have received a copy of the GNU Lesser General Public
47582 * License along with this library; if not, write to the Free Software
47583 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
47584 * MA 02110-1301 USA
47585 */
47586
47587 /**
47588 * @class FuzzyTimelineDensity
47589 * Implementation for a fuzzy time-ranges density plot
47590 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
47591 *
47592 * @param {HTML object} parent div to append the FuzzyTimeline
47593 */
47594 function FuzzyTimelineDensity(parent,div) {
47595
47596 this.index;
47597 this.fuzzyTimeline = this;
47598 this.singleTickWidth;
47599 this.singleTickCenter = function(){return this.singleTickWidth/2;};
47600 //contains all data
47601 this.datasetsPlot;
47602 this.datasetsHash;
47603 this.highlightedDatasetsPlot;
47604 this.yValMin;
47605 this.yValMax;
47606 this.displayType;
47607 //contains selected data
47608 this.selected = undefined;
47609 //contains the last selected "date"
47610 this.highlighted;
47611
47612 this.parent = parent;
47613 this.div = div;
47614 this.options = parent.options;
47615 this.plot;
47616 this.maxTickCount = this.options.maxDensityTicks;
47617
47618 this.datasets;
47619 }
47620
47621 FuzzyTimelineDensity.prototype = {
47622
47623 initialize : function(datasets) {
47624 var density = this;
47625
47626 density.datasets = datasets;
47627 density.selected = [];
47628 },
47629
47630 createPlot : function(data){
47631 density = this;
47632 var chartData = [];
47633
47634 chartData.push([density.parent.overallMin,0]);
47635 $.each(data, function(name,val){
47636 var tickCenterTime = density.parent.overallMin+name*density.singleTickWidth+density.singleTickCenter();
47637 var dateObj = moment(tickCenterTime);
47638 chartData.push([dateObj,val]);
47639 });
47640 var maxPlotedDate = chartData[chartData.length-1][0];
47641 if (density.parent.overallMax > maxPlotedDate){
47642 chartData.push([density.parent.overallMax,0]);
47643 } else {
47644 chartData.push([maxPlotedDate+1,0]);
47645 }
47646
47647
47648
47649 return chartData;
47650 },
47651
47652 //uniform distribution (UD)
47653 createUDData : function(datasets) {
47654 var density = this;
47655 var plots = [];
47656 var objectHashes = [];
47657 $(datasets).each(function(){
47658 var chartDataCounter = new Object();
47659 var objectHash = new Object();
47660
47661 for (var i = 0; i < density.tickCount; i++){
47662 chartDataCounter[i]=0;
47663 }
47664 //check if we got "real" datasets, or just array of objects
47665 var datasetObjects = this;
47666 if (typeof this.objects !== "undefined")
47667 datasetObjects = this.objects;
47668 $(datasetObjects).each(function(){
47669 var ticks = density.parent.getTicks(this, density.singleTickWidth);
47670 if (typeof ticks !== "undefined"){
47671 var exactTickCount =
47672 ticks.firstTickPercentage+
47673 ticks.lastTickPercentage+
47674 (ticks.lastTick-ticks.firstTick-1);
47675 for (var i = ticks.firstTick; i <= ticks.lastTick; i++){
47676 var weight = 0;
47677 //calculate the weight for each span, that the object overlaps
47678 if (density.parent.options.timelineMode == 'fuzzy'){
47679 //in fuzzy mode, each span gets just a fraction of the complete weight
47680 if (i == ticks.firstTick)
47681 weight = this.weight * ticks.firstTickPercentage/exactTickCount;
47682 else if (i == ticks.lastTick)
47683 weight = this.weight * ticks.lastTickPercentage/exactTickCount;
47684 else
47685 weight = this.weight * 1/exactTickCount;
47686 } else if (density.parent.options.timelineMode == 'stacking'){
47687 //in stacking mode each span gets the same amount.
47688 //(besides first and last..)
47689 if (i == ticks.firstTick)
47690 weight = this.weight * ticks.firstTickPercentage;
47691 else if (i == ticks.lastTick)
47692 weight = this.weight * ticks.lastTickPercentage;
47693 else
47694 weight = this.weight;
47695 }
47696
47697 chartDataCounter[i] += weight;
47698 //add this object to the hash
47699 if (typeof objectHash[i] === "undefined")
47700 objectHash[i] = [];
47701 objectHash[i].push(this);
47702 }
47703 }
47704 });
47705
47706 //scale according to selected type
47707 chartDataCounter = density.parent.scaleData(chartDataCounter);
47708
47709 var udChartData = density.createPlot(chartDataCounter);
47710 if (udChartData.length > 0)
47711 plots.push(udChartData);
47712
47713 objectHashes.push(objectHash);
47714 });
47715
47716 return {plots:plots, hashs:objectHashes};
47717 },
47718
47719 showPlot : function() {
47720 var density = this;
47721 var plot = density.datasetsPlot;
47722 var highlight_select_plot = $.merge([],plot);
47723
47724 //see if there are selected/highlighted values
47725 if (density.highlightedDatasetsPlot instanceof Array){
47726 //check if plot is some other - external - graph
47727 if (plot === density.datasetsPlot)
47728 highlight_select_plot = $.merge(highlight_select_plot,density.highlightedDatasetsPlot);
47729 }
47730
47731 var axisFormatString = "%Y";
47732 var tooltipFormatString = "YYYY";
47733 if (density.singleTickWidth<60*1000){
47734 axisFormatString = "%Y/%m/%d %H:%M:%S";
47735 tooltipFormatString = "YYYY/MM/DD HH:mm:ss";
47736 } else if (density.singleTickWidth<60*60*1000) {
47737 axisFormatString = "%Y/%m/%d %H:%M";
47738 tooltipFormatString = "YYYY/MM/DD HH:mm";
47739 } else if (density.singleTickWidth<24*60*60*1000){
47740 axisFormatString = "%Y/%m/%d %H";
47741 tooltipFormatString = "YYYY/MM/DD HH";
47742 } else if (density.singleTickWidth<31*24*60*60*1000){
47743 axisFormatString = "%Y/%m/%d";
47744 tooltipFormatString = "YYYY/MM/DD";
47745 } else if (density.singleTickWidth<12*31*24*60*60*1000){
47746 axisFormatString = "%Y/%m";
47747 tooltipFormatString = "YYYY/MM";
47748 }
47749
47750 //credits: Pimp Trizkit @ http://stackoverflow.com/a/13542669
47751 function shadeRGBColor(color, percent) {
47752 var f=color.split(","),t=percent<0?0:255,p=percent<0?percent*-1:percent,R=parseInt(f[0].slice(4)),G=parseInt(f[1]),B=parseInt(f[2]);
47753 return "rgb("+(Math.round((t-R)*p)+R)+","+(Math.round((t-G)*p)+G)+","+(Math.round((t-B)*p)+B)+")";
47754 }
47755
47756 //credits: Tupak Goliam @ http://stackoverflow.com/a/3821786
47757 var drawLines = function(plot, ctx) {
47758 var data = plot.getData();
47759 var axes = plot.getAxes();
47760 var offset = plot.getPlotOffset();
47761 for (var i = 0; i < data.length; i++) {
47762 var series = data[i];
47763 var lineWidth = 1;
47764
47765 for (var j = 0; j < series.data.length-1; j++) {
47766 var d = (series.data[j]);
47767 var d2 = (series.data[j+1]);
47768
47769 var x = offset.left + axes.xaxis.p2c(d[0]);
47770 var y = offset.top + axes.yaxis.p2c(d[1]);
47771
47772 var x2 = offset.left + axes.xaxis.p2c(d2[0]);
47773 var y2 = offset.top + axes.yaxis.p2c(d2[1]);
47774
47775 //hide lines that "connect" 0 and 0
47776 //essentially blanking out the 0 values
47777 if ((d[1]==0)&&(d2[1]==0)){
47778 continue;
47779 }
47780
47781 ctx.strokeStyle=series.color;
47782 ctx.lineWidth = lineWidth;
47783 ctx.beginPath();
47784 ctx.moveTo(x,y);
47785 ctx.lineTo(x2,y2);
47786
47787 //add shadow (esp. to make background lines more visible)
47788 ctx.shadowColor = shadeRGBColor(series.color,-0.3);
47789 ctx.shadowBlur=1;
47790 ctx.shadowOffsetX = 1;
47791 ctx.shadowOffsetY = 1;
47792
47793 ctx.stroke();
47794 }
47795 }
47796 };
47797
47798 var options = {
47799 series:{
47800 //width:0 because line is drawn in own routine above
47801 //but everything else (data points, shadow) should be drawn
47802 lines:{show: true, lineWidth: 0, shadowSize: 0},
47803 },
47804 grid: {
47805 hoverable: true,
47806 clickable: true,
47807 backgroundColor: density.parent.options.backgroundColor,
47808 borderWidth: 0,
47809 minBorderMargin: 0,
47810 },
47811 legend: {
47812 },
47813 tooltip: true,
47814 tooltipOpts: {
47815 content: function(label, xval, yval, flotItem){
47816 highlightString = moment(xval-density.singleTickCenter()).format(tooltipFormatString) + " - " +
47817 moment(xval+density.singleTickCenter()).format(tooltipFormatString) + " : ";
47818 //(max.)2 Nachkomma-Stellen von y-Wert anzeigen
47819 highlightString += Math.round(yval*100)/100;
47820
47821 return highlightString;
47822 }
47823 },
47824 selection: {
47825 mode: "x"
47826 },
47827 xaxis: {
47828 mode: "time",
47829 timeformat:axisFormatString,
47830 min : density.parent.overallMin,
47831 max : density.parent.overallMax,
47832 },
47833 yaxis: {
47834 min : density.yValMin,
47835 max : density.yValMax*1.05
47836 },
47837 hooks: {
47838 draw : drawLines
47839 },
47840 };
47841 if (!density.parent.options.showYAxis)
47842 options.yaxis.show=false;
47843
47844 var highlight_select_plot_colors = [];
47845 var i = 0;
47846 $(highlight_select_plot).each(function(){
47847 var color;
47848 if (i < GeoTemConfig.datasets.length){
47849 var datasetColors = GeoTemConfig.getColor(i);
47850 if (highlight_select_plot.length>GeoTemConfig.datasets.length)
47851 color = "rgb("+datasetColors.r0+","+datasetColors.g0+","+datasetColors.b0+")";
47852 else
47853 color = "rgb("+datasetColors.r1+","+datasetColors.g1+","+datasetColors.b1+")";
47854 } else {
47855 var datasetColors = GeoTemConfig.getColor(i-GeoTemConfig.datasets.length);
47856 color = "rgb("+datasetColors.r1+","+datasetColors.g1+","+datasetColors.b1+")";
47857 }
47858
47859 highlight_select_plot_colors.push({
47860 color : color,
47861 data : this
47862 });
47863 i++;
47864 });
47865
47866 density.plot = $.plot($(density.div), highlight_select_plot_colors, options);
47867 density.parent.drawHandles();
47868
47869 var rangeBars = density.parent.rangeBars;
47870 if (typeof rangeBars !== "undefined")
47871 $(density.div).unbind("plothover", rangeBars.hoverFunction);
47872 $(density.div).unbind("plothover", density.hoverFunction);
47873 $(density.div).bind("plothover", density.hoverFunction);
47874
47875 //this var prevents the execution of the plotclick event after a select event
47876 density.wasSelection = false;
47877 $(density.div).unbind("plotclick");
47878 $(density.div).bind("plotclick", density.clickFunction);
47879
47880 $(density.div).unbind("plotselected");
47881 $(density.div).bind("plotselected", density.selectFuntion);
47882 },
47883
47884 hoverFunction : function (event, pos, item) {
47885 var hoverPoint;
47886 //TODO: this could be wanted (if negative weight is used)
47887 if ((item)&&(item.datapoint[1] != 0)) {
47888 //at begin and end of plot there are added 0 points
47889 hoverPoint = item.dataIndex-1;
47890 }
47891 //remember last point, so that we don't redraw the current state
47892 //that "hoverPoint" may be undefined is on purpose
47893 if (density.highlighted !== hoverPoint){
47894 density.highlighted = hoverPoint;
47895 density.triggerHighlight(hoverPoint);
47896 }
47897 },
47898
47899 clickFunction : function (event, pos, item) {
47900 if (density.wasSelection)
47901 density.wasSelection = false;
47902 else {
47903 //remove selection handles (if there were any)
47904 density.parent.clearHandles();
47905
47906 var selectPoint;
47907 //that date may be undefined is on purpose
47908 //TODO: ==0 could be wanted (if negative weight is used)
47909 if ((item)&&(item.datapoint[1] != 0)) {
47910 //at begin and end of plot there are added 0 points
47911 selectPoint = item.dataIndex-1;
47912 }
47913 density.triggerSelection(selectPoint);
47914 }
47915 },
47916
47917 selectFuntion : function(event, ranges) {
47918 var spanArray = density.parent.getSpanArray(density.singleTickWidth);
47919 var startSpan, endSpan;
47920 for (var i = 0; i < spanArray.length-1; i++){
47921 if ((typeof startSpan === "undefined") && (ranges.xaxis.from <= spanArray[i+1]))
47922 startSpan = i;
47923 if ((typeof endSpan === "undefined") && (ranges.xaxis.to <= spanArray[i+1]))
47924 endSpan = i;
47925 }
47926
47927 if ((typeof startSpan !== "undefined") && (typeof endSpan !== "undefined")){
47928 density.triggerSelection(startSpan, endSpan);
47929 density.wasSelection = true;
47930
47931 density.parent.clearHandles();
47932 var xaxis = density.plot.getAxes().xaxis;
47933 var x1 = density.plot.pointOffset({x:ranges.xaxis.from,y:0}).left;
47934 var x2 = density.plot.pointOffset({x:ranges.xaxis.to,y:0}).left;
47935
47936 density.parent.addHandle(x1,x2);
47937 }
47938 },
47939
47940 selectByX : function(x1, x2){
47941 density = this;
47942 var xaxis = density.plot.getAxes().xaxis;
47943 var offset = density.plot.getPlotOffset().left;
47944 var from = xaxis.c2p(x1-offset);
47945 var to = xaxis.c2p(x2-offset);
47946
47947 var spanArray = density.parent.getSpanArray(density.singleTickWidth);
47948 var startSpan, endSpan;
47949 for (var i = 0; i < spanArray.length-1; i++){
47950 if ((typeof startSpan === "undefined") && (from <= spanArray[i+1]))
47951 startSpan = i;
47952 if ((typeof endSpan === "undefined") && (to <= spanArray[i+1]))
47953 endSpan = i;
47954 }
47955
47956 if ((typeof startSpan !== "undefined") && (typeof endSpan !== "undefined")){
47957 density.triggerSelection(startSpan, endSpan);
47958 }
47959 },
47960
47961 drawDensityPlot : function(datasets, tickWidth) {
47962 var density = this;
47963 //calculate tick width (will be in ms)
47964 delete density.tickCount;
47965 delete density.singleTickWidth;
47966 delete density.highlightedDatasetsPlot;
47967 density.parent.zoomPlot(1);
47968 if (typeof tickWidth !== "undefined"){
47969 density.singleTickWidth = tickWidth;
47970 density.tickCount = Math.ceil((density.parent.overallMax-density.parent.overallMin)/tickWidth);
47971 }
47972 if ((typeof density.tickCount === "undefined") || (density.tickCount > density.maxTickCount)){
47973 density.tickCount = density.maxTickCount;
47974 density.singleTickWidth = (density.parent.overallMax-density.parent.overallMin)/density.tickCount;
47975 if (density.singleTickWidth === 0)
47976 density.singleTickWidth = 1;
47977 }
47978
47979 var hashAndPlot = density.createUDData(datasets);
47980
47981 density.datasetsPlot = hashAndPlot.plots;
47982 density.datasetsHash = hashAndPlot.hashs;
47983
47984 density.yValMin = 0;
47985 density.yValMax = 0;
47986
47987 density.combinedDatasetsPlot = [];
47988 for (var i = 0; i < density.datasetsPlot.length; i++){
47989 for (var j = 0; j < density.datasetsPlot[i].length; j++){
47990 var val = density.datasetsPlot[i][j][1];
47991
47992 if (val < density.yValMin)
47993 density.yValMin = val;
47994 if (val > density.yValMax)
47995 density.yValMax = val;
47996 }
47997 }
47998
47999 density.showPlot();
48000 },
48001
48002 triggerHighlight : function(hoverPoint) {
48003 var density = this;
48004 var highlightedObjects = [];
48005
48006
48007 if (typeof hoverPoint !== "undefined") {
48008 $(density.datasetsHash).each(function(){
48009 if (typeof this[hoverPoint] !== "undefined")
48010 highlightedObjects.push(this[hoverPoint]);
48011 else
48012 highlightedObjects.push([]);
48013 });
48014 } else {
48015 for (var i = 0; i < GeoTemConfig.datasets.length; i++)
48016 highlightedObjects.push([]);
48017 }
48018 this.parent.core.triggerHighlight(highlightedObjects);
48019 },
48020
48021 triggerSelection : function(startPoint, endPoint) {
48022 var density = this;
48023 var selection;
48024 if (typeof startPoint !== "undefined") {
48025 if (typeof endPoint === "undefined")
48026 endPoint = startPoint;
48027 density.selected = [];
48028 $(density.datasetsHash).each(function(){
48029 var objects = [];
48030 for (var i = startPoint; i <= endPoint; i++){
48031 $(this[i]).each(function(){
48032 if ($.inArray(this, objects) == -1){
48033 objects.push(this);
48034 }
48035 });
48036 }
48037 density.selected.push(objects);
48038 });
48039
48040 selection = new Selection(density.selected, density.parent);
48041 } else {
48042 //empty selection
48043 density.selected = [];
48044 for (var i = 0; i < GeoTemConfig.datasets.length; i++)
48045 density.selected.push([]);
48046 selection = new Selection(density.selected);
48047 }
48048
48049 this.parent.selectionChanged(selection);
48050 this.parent.core.triggerSelection(selection);
48051 },
48052
48053 highlightChanged : function(objects) {
48054 if( !GeoTemConfig.highlightEvents ){
48055 return;
48056 }
48057 var density = this;
48058 var emptyHighlight = true;
48059 var selected_highlighted = objects;
48060 if (typeof density.selected !== "undefined")
48061 selected_highlighted = GeoTemConfig.mergeObjects(objects,density.selected);
48062 $(selected_highlighted).each(function(){
48063 if ((this instanceof Array) && (this.length > 0)){
48064 emptyHighlight = false;
48065 return false;
48066 }
48067 });
48068 if (emptyHighlight && (typeof density.selected === "undefined")){
48069 density.highlightedDatasetsPlot = [];
48070 } else {
48071 density.highlightedDatasetsPlot = density.createUDData(selected_highlighted).plots;
48072 }
48073 density.showPlot();
48074 },
48075
48076 selectionChanged : function(objects) {
48077 if( !GeoTemConfig.selectionEvents ){
48078 return;
48079 }
48080 var density = this;
48081 density.selected = objects;
48082 density.highlightChanged([]);
48083 },
48084
48085 deselection : function() {
48086 },
48087
48088 filtering : function() {
48089 },
48090
48091 inverseFiltering : function() {
48092 },
48093
48094 triggerRefining : function() {
48095 },
48096
48097 reset : function() {
48098 },
48099
48100 show : function() {
48101 },
48102
48103 hide : function() {
48104 }
48105 };
48106 /*
48107 * FuzzyTimelineGui.js
48108 *
48109 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
48110 *
48111 * This library is free software; you can redistribute it and/or
48112 * modify it under the terms of the GNU Lesser General Public
48113 * License as published by the Free Software Foundation; either
48114 * version 3 of the License, or (at your option) any later version.
48115 *
48116 * This library is distributed in the hope that it will be useful,
48117 * but WITHOUT ANY WARRANTY; without even the implied warranty of
48118 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
48119 * Lesser General Public License for more details.
48120 *
48121 * You should have received a copy of the GNU Lesser General Public
48122 * License along with this library; if not, write to the Free Software
48123 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
48124 * MA 02110-1301 USA
48125 */
48126
48127 /**
48128 * @class FuzzyTimelineGui
48129 * FuzzyTimeline GUI Implementation
48130 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
48131 *
48132 * @param {FuzzyTimelineWidget} parent FuzzyTimeline widget object
48133 * @param {HTML object} div parent div to append the FuzzyTimeline gui
48134 * @param {JSON} options FuzzyTimeline configuration
48135 */
48136 function FuzzyTimelineGui(fuzzyTimelineWidget, div, options) {
48137
48138 this.parent = fuzzyTimelineWidget;
48139 var fuzzyTimelineGui = this;
48140
48141 this.fuzzyTimelineContainer = div;
48142 //if no height is given, draw it in a 32/9 ratio
48143 if ($(this.fuzzyTimelineContainer).height() === 0)
48144 $(this.fuzzyTimelineContainer).height($(this.fuzzyTimelineContainer).width()*9/32);
48145 //this.fuzzyTimelineContainer.style.position = 'relative';
48146
48147 this.sliderTable = document.createElement("table");
48148 $(this.sliderTable).addClass("ddbToolbar");
48149 $(this.sliderTable).width("100%");
48150 $(this.sliderTable).height("49px");
48151 div.appendChild(this.sliderTable);
48152
48153 this.plotDIVHeight = $(this.fuzzyTimelineContainer).height()-$(this.sliderTable).height();
48154 var plotScrollContainer = $("<div></div>");
48155 plotScrollContainer.css("overflow-x","auto");
48156 plotScrollContainer.css("overflow-y","hidden");
48157 plotScrollContainer.width("100%");
48158 plotScrollContainer.height(this.plotDIVHeight);
48159 $(div).append(plotScrollContainer);
48160 this.plotDiv = document.createElement("div");
48161 $(this.plotDiv).width("100%");
48162 $(this.plotDiv).height(this.plotDIVHeight);
48163 plotScrollContainer.append(this.plotDiv);
48164 if (this.parent.options.showRangePiechart){
48165 this.rangePiechartDiv = document.createElement("div");
48166 $(this.rangePiechartDiv).css("float","right");
48167 //alter plot div width (leave space for piechart)
48168 $(this.plotDiv).width("75%");
48169 $(this.rangePiechartDiv).width("25%");
48170 $(this.rangePiechartDiv).height(plotDIVHeight);
48171 div.appendChild(this.rangePiechartDiv);
48172 }
48173 };
48174
48175 FuzzyTimelineGui.prototype = {
48176 };
48177 /*
48178 * FuzzyTimelineRangeBars.js
48179 *
48180 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
48181 *
48182 * This library is free software; you can redistribute it and/or
48183 * modify it under the terms of the GNU Lesser General Public
48184 * License as published by the Free Software Foundation; either
48185 * version 3 of the License, or (at your option) any later version.
48186 *
48187 * This library is distributed in the hope that it will be useful,
48188 * but WITHOUT ANY WARRANTY; without even the implied warranty of
48189 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
48190 * Lesser General Public License for more details.
48191 *
48192 * You should have received a copy of the GNU Lesser General Public
48193 * License along with this library; if not, write to the Free Software
48194 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
48195 * MA 02110-1301 USA
48196 */
48197
48198 /**
48199 * @class FuzzyTimelineRangeBars
48200 * Implementation for a fuzzy time-ranges barchart
48201 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
48202 *
48203 * @param {HTML object} parent div to append the FuzzyTimeline
48204 */
48205 function FuzzyTimelineRangeBars(parent) {
48206
48207 this.rangeBars = this;
48208
48209 this.parent = parent;
48210 this.options = parent.options;
48211
48212 this.datasets;
48213 //contains selected data
48214 this.selected = undefined;
48215
48216 this.datasetsPlot;
48217 this.highlightedDatasetsPlot;
48218 this.yValMin;
48219 this.yValMax;
48220 this.displayType;
48221
48222 this.plotDiv = this.parent.gui.plotDiv;
48223
48224 this.spanWidth;
48225 this.tickSpans;
48226 this.plot;
48227 }
48228
48229 FuzzyTimelineRangeBars.prototype = {
48230
48231 initialize : function(datasets) {
48232 var rangeBar = this;
48233
48234 rangeBar.datasets = datasets;
48235 rangeBar.selected = [];
48236 },
48237
48238 createPlot : function(datasets) {
48239 var rangeBar = this;
48240 var plots = [];
48241 var objectHashes = [];
48242
48243 //-1 because last span is always empty (only there to have the ending date)
48244 var tickCount = rangeBar.tickSpans.length-1;
48245
48246 $(datasets).each(function(){
48247 var chartDataCounter = [];
48248 var objectHash = new Object();
48249
48250 for (var i = 0; i < tickCount; i++){
48251 chartDataCounter[i]=0;
48252 }
48253 //check if we got "real" datasets, or just array of objects
48254 var datasetObjects = this;
48255 if (typeof this.objects !== "undefined")
48256 datasetObjects = this.objects;
48257 $(datasetObjects).each(function(){
48258 var ticks = rangeBar.parent.getTicks(this, rangeBar.spanWidth);
48259 if (typeof ticks !== "undefined"){
48260 var exactTickCount =
48261 ticks.firstTickPercentage+
48262 ticks.lastTickPercentage+
48263 (ticks.lastTick-ticks.firstTick-1);
48264 for (var i = ticks.firstTick; i <= ticks.lastTick; i++){
48265 var weight = 0;
48266 //calculate the weight for each span, that the object overlaps
48267 if (rangeBar.parent.options.timelineMode == 'fuzzy'){
48268 //in fuzzy mode, each span gets just a fraction of the complete weight
48269 if (i == ticks.firstTick)
48270 weight = this.weight * ticks.firstTickPercentage/exactTickCount;
48271 else if (i == ticks.lastTick)
48272 weight = this.weight * ticks.lastTickPercentage/exactTickCount;
48273 else
48274 weight = this.weight * 1/exactTickCount;
48275 } else if (rangeBar.parent.options.timelineMode == 'stacking'){
48276 //in stacking mode each span gets the same amount.
48277 //(besides first and last..)
48278 if (i == ticks.firstTick)
48279 weight = this.weight * ticks.firstTickPercentage;
48280 else if (i == ticks.lastTick)
48281 weight = this.weight * ticks.lastTickPercentage;
48282 else
48283 weight = this.weight;
48284 }
48285
48286 chartDataCounter[i] += weight;
48287 //add this object to the hash
48288 if (typeof objectHash[i] === "undefined")
48289 objectHash[i] = [];
48290 objectHash[i].push(this);
48291 }
48292 }
48293 });
48294
48295 //scale according to selected type
48296 chartDataCounter = rangeBar.parent.scaleData(chartDataCounter);
48297
48298 //transform data so it can be passed to the flot barchart
48299 var plotData = [];
48300 for (var i = 0; i < tickCount; i++){
48301 plotData[i] = [];
48302 plotData[i][0] = i;
48303 plotData[i][1] = chartDataCounter[i];
48304 }
48305
48306 //delete bars with 0 values
48307 for (var i = 0; i < tickCount; i++){
48308 if (plotData[i][1]==0)
48309 delete plotData[i];
48310 }
48311
48312 plots.push(plotData);
48313 objectHashes.push(objectHash);
48314 });
48315
48316 return {plots:plots, hashs:objectHashes};
48317 },
48318
48319 showPlot : function(){
48320 var rangeBar = this;
48321 var plot = rangeBar.datasetsPlot;
48322 var highlight_select_plot = $.merge([],plot);
48323
48324 //see if there are selected/highlighted values
48325 if (rangeBar.highlightedDatasetsPlot instanceof Array){
48326 //check if plot is some other - external - graph
48327 if (plot === rangeBar.datasetsPlot)
48328 highlight_select_plot = $.merge(highlight_select_plot,rangeBar.highlightedDatasetsPlot);
48329 }
48330
48331 var tickCount = rangeBar.tickSpans.length-1;
48332 var ticks = [];
48333
48334 var axisFormatString = "YYYY";
48335 if (rangeBar.spanWidth<60*1000){
48336 axisFormatString = "YYYY/MM/DD HH:mm:ss";
48337 } else if (rangeBar.spanWidth<60*60*1000) {
48338 axisFormatString = "YYYY/MM/DD HH:mm";
48339 } else if (rangeBar.spanWidth<24*60*60*1000){
48340 axisFormatString = "YYYY/MM/DD HH";
48341 } else if (rangeBar.spanWidth<31*24*60*60*1000){
48342 axisFormatString = "YYYY/MM/DD";
48343 } else if (rangeBar.spanWidth<12*31*24*60*60*1000){
48344 axisFormatString = "YYYY/MM";
48345 }
48346 //only show ~10 labels on the x-Axis (increase if zoomed)
48347 var labelModulo = Math.ceil(tickCount/(10*rangeBar.parent.zoomFactor));
48348 for (var i = 0; i < tickCount; i++){
48349 var tickLabel = "";
48350 if (i%labelModulo==0){
48351 tickLabel = rangeBar.tickSpans[i].format(axisFormatString);
48352 }
48353 while ((tickLabel.length > 1) && (tickLabel.indexOf("0")==0))
48354 tickLabel = tickLabel.substring(1);
48355 ticks[i] = [i,tickLabel];
48356 }
48357
48358 var options = {
48359 series:{
48360 bars:{show: true}
48361 },
48362 grid: {
48363 hoverable: true,
48364 clickable: true,
48365 backgroundColor: rangeBar.parent.options.backgroundColor,
48366 borderWidth: 0,
48367 minBorderMargin: 0,
48368 },
48369 xaxis: {
48370 ticks: ticks,
48371 min : 0,
48372 max : tickCount,
48373 },
48374 yaxis: {
48375 min : rangeBar.yValMin,
48376 max : rangeBar.yValMax*1.05
48377 },
48378 tooltip: true,
48379 tooltipOpts: {
48380 content: function(label, xval, yval, flotItem){
48381 var fromLabel = rangeBar.tickSpans[xval].format(axisFormatString);
48382 while ((fromLabel.length > 1) && (fromLabel.indexOf("0")==0))
48383 fromLabel = fromLabel.substring(1);
48384 var toLabel = rangeBar.tickSpans[xval+1].clone().subtract("ms",1).format(axisFormatString);
48385 while ((toLabel.length > 1) && (toLabel.indexOf("0")==0))
48386 toLabel = toLabel.substring(1);
48387 highlightString = fromLabel + " - " + toLabel + " : ";
48388 //(max.)2 Nachkomma-Stellen von y-Wert anzeigen
48389 highlightString += Math.round(yval*100)/100;
48390
48391 return highlightString;
48392 }
48393 },
48394 selection: {
48395 mode: "x"
48396 }
48397 };
48398 if (!rangeBar.parent.options.showYAxis)
48399 options.yaxis.show=false;
48400
48401 var highlight_select_plot_colors = [];
48402 var i = 0;
48403 $(highlight_select_plot).each(function(){
48404 var color;
48405 if (i < GeoTemConfig.datasets.length){
48406 var datasetColors = GeoTemConfig.getColor(i);
48407 if (highlight_select_plot.length>GeoTemConfig.datasets.length)
48408 color = "rgb("+datasetColors.r0+","+datasetColors.g0+","+datasetColors.b0+")";
48409 else
48410 color = "rgb("+datasetColors.r1+","+datasetColors.g1+","+datasetColors.b1+")";
48411 } else {
48412 var datasetColors = GeoTemConfig.getColor(i-GeoTemConfig.datasets.length);
48413 color = "rgb("+datasetColors.r1+","+datasetColors.g1+","+datasetColors.b1+")";
48414 }
48415
48416 highlight_select_plot_colors.push({
48417 color : color,
48418 data : this
48419 });
48420 i++;
48421 });
48422
48423 $(rangeBar.plotDiv).unbind();
48424 rangeBar.plot = $.plot($(rangeBar.plotDiv), highlight_select_plot_colors, options);
48425 rangeBar.parent.drawHandles();
48426
48427 var density = rangeBar.parent.density;
48428 if (typeof density !== "undefined")
48429 $(rangeBar.plotDiv).unbind("plothover", density.hoverFunction);
48430 $(rangeBar.plotDiv).unbind("plothover", rangeBar.hoverFunction);
48431 $(rangeBar.plotDiv).bind("plothover", $.proxy(rangeBar.hoverFunction,rangeBar));
48432
48433 //this var prevents the execution of the plotclick event after a select event
48434 rangeBar.wasSelection = false;
48435 $(rangeBar.plotDiv).unbind("plotclick");
48436 $(rangeBar.plotDiv).bind("plotclick", $.proxy(rangeBar.clickFunction,rangeBar));
48437
48438 $(rangeBar.plotDiv).unbind("plotselected");
48439 $(rangeBar.plotDiv).bind("plotselected", $.proxy(rangeBar.selectFunction,rangeBar));
48440 },
48441
48442 hoverFunction : function (event, pos, item) {
48443 var rangeBar = this;
48444 var hoverBar;
48445 var spans;
48446 if (item) {
48447 hoverBar = item.datapoint[0];
48448 }
48449 //remember last date, so that we don't redraw the current state
48450 //that date may be undefined is on purpose
48451 if (rangeBar.highlighted !== hoverBar){
48452 rangeBar.highlighted = hoverBar;
48453 if (typeof hoverBar === "undefined")
48454 rangeBar.triggerHighlight();
48455 else
48456 rangeBar.triggerHighlight(hoverBar);
48457 }
48458 },
48459
48460 clickFunction : function (event, pos, item) {
48461 var rangeBar = this;
48462 if (rangeBar.wasSelection)
48463 rangeBar.wasSelection = false;
48464 else {
48465 //remove selection handles (if there were any)
48466 rangeBar.parent.clearHandles();
48467
48468 var clickBar;
48469 if (item) {
48470 //contains the x-value (date)
48471 clickBar = item.datapoint[0];
48472 }
48473 if (typeof clickBar === "undefined")
48474 rangeBar.triggerSelection();
48475 else
48476 rangeBar.triggerSelection(clickBar);
48477 wasDataClick = true;
48478 }
48479 },
48480
48481 selectFunction : function(event, ranges) {
48482 var rangeBar = this;
48483 startBar = Math.floor(ranges.xaxis.from);
48484 endBar = Math.floor(ranges.xaxis.to);
48485 rangeBar.triggerSelection(startBar, endBar);
48486 rangeBar.wasSelection = true;
48487
48488 rangeBar.parent.clearHandles();
48489 var xaxis = rangeBar.plot.getAxes().xaxis;
48490 var x1 = rangeBar.plot.pointOffset({x:ranges.xaxis.from,y:0}).left;
48491 var x2 = rangeBar.plot.pointOffset({x:ranges.xaxis.to,y:0}).left;
48492 rangeBar.parent.addHandle(x1,x2);
48493 },
48494
48495 selectByX : function(x1, x2){
48496 rangeBar = this;
48497 var xaxis = rangeBar.plot.getAxes().xaxis;
48498 var offset = rangeBar.plot.getPlotOffset().left;
48499 var from = Math.floor(xaxis.c2p(x1-offset));
48500 var to = Math.floor(xaxis.c2p(x2-offset));
48501
48502 rangeBar.triggerSelection(from, to);
48503 },
48504
48505 drawRangeBarChart : function(datasets, spanWidth){
48506 var rangeBar = this;
48507 rangeBar.spanWidth = spanWidth;
48508 rangeBar.tickSpans = rangeBar.parent.getSpanArray(rangeBar.spanWidth);
48509 //-1 because last span is always empty (only there to have the ending date)
48510 var tickCount = rangeBar.tickSpans.length-1;
48511
48512 if (tickCount > rangeBar.options.maxBars){
48513 var zoomFactor = tickCount / rangeBar.options.maxBars;
48514 rangeBar.parent.zoomPlot(zoomFactor);
48515 } else
48516 rangeBar.parent.zoomPlot(1);
48517
48518 rangeBar.yValMin = 0;
48519 rangeBar.yValMax = 0;
48520
48521 var plotAndHash = rangeBar.createPlot(datasets);
48522 rangeBar.datasetsPlot = plotAndHash.plots;
48523 rangeBar.datasetsHash = plotAndHash.hashs;
48524 delete rangeBar.highlightedDatasetsPlot;
48525 //redraw selected plot to fit (possible) new scale
48526 rangeBar.selectionChanged(rangeBar.selected);
48527
48528 //get min and max values
48529 for (var i = 0; i < rangeBar.datasetsPlot.length; i++){
48530 for (var j = 0; j < rangeBar.datasetsPlot[i].length; j++){
48531 if (typeof rangeBar.datasetsPlot[i][j] !== "undefined"){
48532 var val = rangeBar.datasetsPlot[i][j][1];
48533
48534 if (val < rangeBar.yValMin)
48535 rangeBar.yValMin = val;
48536 if (val > rangeBar.yValMax)
48537 rangeBar.yValMax = val;
48538 }
48539 }
48540 }
48541
48542 rangeBar.showPlot();
48543 },
48544
48545 highlightChanged : function(objects) {
48546 if( !GeoTemConfig.highlightEvents ){
48547 return;
48548 }
48549 var rangeBar = this;
48550 var emptyHighlight = true;
48551 var selected_highlighted = objects;
48552 if (typeof rangeBar.selected !== "undefined")
48553 var selected_highlighted = GeoTemConfig.mergeObjects(objects,rangeBar.selected);
48554 $(selected_highlighted).each(function(){
48555 if ((this instanceof Array) && (this.length > 0)){
48556 emptyHighlight = false;
48557 return false;
48558 }
48559 });
48560 if (emptyHighlight && (typeof rangeBar.selected === "undefined")){
48561 rangeBar.highlightedDatasetsPlot = [];
48562 } else {
48563 rangeBar.highlightedDatasetsPlot = rangeBar.createPlot(selected_highlighted).plots;
48564 }
48565 rangeBar.showPlot();
48566 },
48567
48568 selectionChanged : function(objects) {
48569 if( !GeoTemConfig.selectionEvents ){
48570 return;
48571 }
48572 var rangeBar = this;
48573 rangeBar.selected = objects;
48574 rangeBar.highlightChanged([]);
48575 },
48576
48577 triggerHighlight : function(hoverPoint) {
48578 var rangeBar = this;
48579 var highlightedObjects = [];
48580
48581 if (typeof hoverPoint !== "undefined"){
48582 $(rangeBar.datasetsHash).each(function(){
48583 if (typeof this[hoverPoint] !== "undefined")
48584 highlightedObjects.push(this[hoverPoint]);
48585 else
48586 highlightedObjects.push([]);
48587 });
48588 } else {
48589 for (var i = 0; i < GeoTemConfig.datasets.length; i++)
48590 highlightedObjects.push([]);
48591 }
48592
48593 this.parent.core.triggerHighlight(highlightedObjects);
48594 },
48595
48596 triggerSelection : function(startBar, endBar) {
48597 var rangeBar = this;
48598 var selection;
48599 if (typeof startBar !== "undefined") {
48600 if (typeof endBar === "undefined")
48601 endBar = startBar;
48602 rangeBar.selected = [];
48603 $(rangeBar.datasetsHash).each(function(){
48604 var objects = [];
48605 for (var i = startBar; i <= endBar; i++){
48606 $(this[i]).each(function(){
48607 if ($.inArray(this, objects) == -1){
48608 objects.push(this);
48609 }
48610 });
48611 }
48612 rangeBar.selected.push(objects);
48613 });
48614 selection = new Selection(rangeBar.selected, rangeBar.parent);
48615 } else {
48616 rangeBar.selected = [];
48617 for (var i = 0; i < GeoTemConfig.datasets.length; i++)
48618 rangeBar.selected.push([]);
48619 selection = new Selection(rangeBar.selected);
48620 }
48621
48622 rangeBar.parent.selectionChanged(selection);
48623 rangeBar.parent.core.triggerSelection(selection);
48624 },
48625
48626 deselection : function() {
48627 },
48628
48629 filtering : function() {
48630 },
48631
48632 inverseFiltering : function() {
48633 },
48634
48635 triggerRefining : function() {
48636 },
48637
48638 reset : function() {
48639 },
48640
48641 show : function() {
48642 },
48643
48644 hide : function() {
48645 }
48646 };
48647 /*
48648 * FuzzyTimelineRangePiechart.js
48649 *
48650 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
48651 *
48652 * This library is free software; you can redistribute it and/or
48653 * modify it under the terms of the GNU Lesser General Public
48654 * License as published by the Free Software Foundation; either
48655 * version 3 of the License, or (at your option) any later version.
48656 *
48657 * This library is distributed in the hope that it will be useful,
48658 * but WITHOUT ANY WARRANTY; without even the implied warranty of
48659 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
48660 * Lesser General Public License for more details.
48661 *
48662 * You should have received a copy of the GNU Lesser General Public
48663 * License along with this library; if not, write to the Free Software
48664 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
48665 * MA 02110-1301 USA
48666 */
48667
48668 /**
48669 * @class FuzzyTimelineRangePiechart
48670 * Implementation for a fuzzy time-ranges pie chart
48671 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
48672 *
48673 * @param {HTML object} parent div to append the FuzzyTimeline
48674 */
48675 function FuzzyTimelineRangePiechart(parent,div) {
48676
48677 this.fuzzyTimeline = this;
48678
48679 this.parent = parent;
48680 this.options = parent.options;
48681
48682 this.div = div;
48683
48684 this.selected = [];
48685
48686 this.maxSlices = 10;
48687 }
48688
48689 FuzzyTimelineRangePiechart.prototype = {
48690
48691 initialize : function(datasets) {
48692 var piechart = this;
48693 if (piechart.parent.showRangePiechart){
48694 piechart.datasets = datasets;
48695 piechart.drawPieChart(piechart.datasets);
48696 }
48697 },
48698
48699 drawPieChart : function(datasets){
48700 var piechart = this;
48701 //build hashmap of spans (span length -> objects[])
48702 var spans = [];
48703 var index = 0;
48704 $(datasets).each(function(){
48705 var objects = this;
48706 //check whether we got "real" dataset or just a set of DataObjects
48707 if (typeof objects.objects !== "undefined")
48708 objects = objects.objects;
48709 $(objects).each(function(){
48710 var dataObject = this;
48711 var span;
48712 if (dataObject.isTemporal){
48713 span = SimileAjax.DateTime.MILLISECOND;
48714 } else if (dataObject.isFuzzyTemporal){
48715 span = dataObject.TimeSpanGranularity;
48716 }
48717
48718 if (typeof span === "undefined")
48719 return;
48720
48721 var found = false;
48722 $(spans).each(function(){
48723 if (this.span === span){
48724 this.objects[index].push(dataObject);
48725 found = true;
48726 return false;
48727 }
48728 });
48729 if (found === false){
48730 var newObjectSet = [];
48731 for (var i = 0; i < piechart.datasets.length; i++)
48732 newObjectSet.push([]);
48733 newObjectSet[index].push(dataObject);
48734 spans.push({span:span,objects:newObjectSet});
48735 }
48736 });
48737 index++;
48738 });
48739
48740 //TODO: join elements of span array to keep below certain threshold
48741
48742 //sort array by span length
48743 spans.sort(function(a,b){
48744 return(a.span-b.span);
48745 });
48746
48747 //create chart data
48748 var chartData = [];
48749 $(spans).each(function(){
48750 var spanElem = this;
48751 $(spanElem.objects).each(function(){
48752 var label = "unknown";
48753
48754 if (spanElem.span === SimileAjax.DateTime.MILLENNIUM){
48755 label = "millenia";
48756 } else if (spanElem.span === SimileAjax.DateTime.DECADE){
48757 label = "decades";
48758 } else if (spanElem.span === SimileAjax.DateTime.CENTURY){
48759 label = "centuries";
48760 } else if (spanElem.span === SimileAjax.DateTime.YEAR){
48761 label = "years";
48762 } else if (spanElem.span === SimileAjax.DateTime.MONTH){
48763 label = "months";
48764 } else if (spanElem.span === SimileAjax.DateTime.DAY){
48765 label = "days";
48766 } else if (spanElem.span === SimileAjax.DateTime.HOUR){
48767 label = "hours";
48768 } else if (spanElem.span === SimileAjax.DateTime.MINUTE){
48769 label = "minutes";
48770 } else if (spanElem.span === SimileAjax.DateTime.SECOND){
48771 label = "seconds";
48772 } else if (spanElem.span === SimileAjax.DateTime.MILLISECOND){
48773 label = "milliseconds";
48774 }
48775
48776 chartData.push({label:label,data:this.length});
48777 });
48778 });
48779
48780 $(piechart.div).unbind("plotclick");
48781 $(piechart.div).unbind("plothover");
48782 $(piechart.div).empty();
48783 if (spans.length === 0){
48784 //TODO: language specific message
48785 $(piechart.div).append("empty selection");
48786 } else {
48787 $.plot($(piechart.div), chartData,
48788 {
48789 series: {
48790 // Make this a pie chart.
48791 pie: {
48792 show:true
48793 }
48794 },
48795 legend: { show:false},
48796 grid: {
48797 hoverable: true,
48798 clickable: true
48799 },
48800 tooltip: true,
48801 }
48802 );
48803
48804 var lastHighlighted;
48805 var hoverFunction = function (event, pos, item) {
48806 if (item) {
48807 var highlightedSpan = Math.ceil(item.seriesIndex/piechart.datasets.length);
48808 if (lastHighlighted !== highlightedSpan){
48809 var highlightedObjects = [];
48810 for(;highlightedSpan>=0;highlightedSpan--){
48811 highlightedObjects = GeoTemConfig.mergeObjects(highlightedObjects,spans[highlightedSpan].objects);
48812 }
48813 lastHighlighted = highlightedSpan;
48814 }
48815 piechart.triggerHighlight(highlightedObjects);
48816 } else {
48817 piechart.triggerHighlight([]);
48818 }
48819 };
48820 $(piechart.div).bind("plothover", hoverFunction);
48821
48822 $(piechart.div).bind("plotclick", function (event, pos, item) {
48823 $(piechart.div).unbind("plothover");
48824 if (item){
48825 var selectedSpan = Math.ceil(item.seriesIndex/piechart.datasets.length);
48826 var selectedObjects = [];
48827 for(;selectedSpan>=0;selectedSpan--){
48828 selectedObjects = GeoTemConfig.mergeObjects(selectedObjects,spans[selectedSpan].objects);
48829 }
48830 piechart.triggerSelection(selectedObjects);
48831 } else {
48832 //if it was a click outside of the pie-chart, enable highlight events
48833 $(piechart.div).bind("plothover", hoverFunction);
48834 //return to old state
48835 piechart.triggerSelection(piechart.selected);
48836 //and redraw piechart
48837 piechart.highlightChanged([]);
48838 }
48839 });
48840 }
48841 },
48842
48843 highlightChanged : function(objects) {
48844 var piechart = this;
48845 if (piechart.parent.showRangePiechart){
48846 //check if this is an empty highlight
48847 var emptyHighlight = true;
48848 $(objects).each(function(){
48849 if ((this instanceof Array) && (this.length > 0)){
48850 emptyHighlight = false;
48851 return false;
48852 }
48853 });
48854
48855 if (emptyHighlight === false)
48856 piechart.drawPieChart(GeoTemConfig.mergeObjects(piechart.selected, objects));
48857 else{
48858 //return to selection (or all objects, if no selection is active)
48859 if (piechart.selected.length > 0)
48860 piechart.drawPieChart(piechart.selected);
48861 else
48862 piechart.drawPieChart(piechart.datasets);
48863 }
48864 }
48865 },
48866
48867 selectionChanged : function(selection) {
48868 var piechart = this;
48869 if (piechart.parent.showRangePiechart){
48870 if( !GeoTemConfig.selectionEvents ){
48871 return;
48872 }
48873 piechart.selected = selection;
48874 piechart.highlightChanged([]);
48875 }
48876 },
48877
48878 triggerHighlight : function(highlightedObjects) {
48879 this.parent.triggerHighlight(highlightedObjects);
48880 },
48881
48882 triggerSelection : function(selectedObjects) {
48883 this.parent.triggerSelection(selectedObjects);
48884 },
48885
48886 deselection : function() {
48887 },
48888
48889 filtering : function() {
48890 },
48891
48892 inverseFiltering : function() {
48893 },
48894
48895 triggerRefining : function() {
48896 },
48897
48898 reset : function() {
48899 },
48900
48901 show : function() {
48902 },
48903
48904 hide : function() {
48905 }
48906 };
48907 /*
48908 * FuzzyTimelineRangeSlider.js
48909 *
48910 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
48911 *
48912 * This library is free software; you can redistribute it and/or
48913 * modify it under the terms of the GNU Lesser General Public
48914 * License as published by the Free Software Foundation; either
48915 * version 3 of the License, or (at your option) any later version.
48916 *
48917 * This library is distributed in the hope that it will be useful,
48918 * but WITHOUT ANY WARRANTY; without even the implied warranty of
48919 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
48920 * Lesser General Public License for more details.
48921 *
48922 * You should have received a copy of the GNU Lesser General Public
48923 * License along with this library; if not, write to the Free Software
48924 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
48925 * MA 02110-1301 USA
48926 */
48927
48928 /**
48929 * @class FuzzyTimelineRangeSlider
48930 * Implementation for a fuzzy time-ranges slider
48931 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
48932 *
48933 * @param {HTML object} parent div to append the FuzzyTimeline
48934 */
48935 function FuzzyTimelineRangeSlider(parent) {
48936
48937 var rangeSlider = this;
48938
48939 this.parent = parent;
48940 this.options = parent.options;
48941
48942 this.spans;
48943
48944 this.datasets;
48945
48946 this.sliderParentTable = this.parent.gui.sliderTable;
48947 var headerRow = $("<tr></tr>");
48948 var controlsRow = $("<tr></tr>");
48949 $(this.sliderParentTable).append(headerRow).append(controlsRow);
48950
48951 headerRow.append("<td>Time start</td>");
48952 this.rangeStart = document.createElement("select");
48953 controlsRow.append($("<td></td>").append(this.rangeStart));
48954
48955 headerRow.append("<td>Time unit</td>");
48956 this.rangeDropdown = document.createElement("select");
48957 controlsRow.append($("<td></td>").append(this.rangeDropdown));
48958
48959 headerRow.append("<td>Scaling</td>");
48960 this.scalingDropdown = document.createElement("select");
48961 controlsRow.append($("<td></td>").append(this.scalingDropdown));
48962 $(this.scalingDropdown).append("<option>normal</option>");
48963 $(this.scalingDropdown).append("<option>logarithm</option>");
48964 $(this.scalingDropdown).append("<option>percentage</option>");
48965 $(this.scalingDropdown).change(function(eventObject){
48966 var scaleMode = $(rangeSlider.scalingDropdown).find("option:selected").text();
48967 rangeSlider.parent.changeScaleMode(scaleMode);
48968 });
48969
48970 headerRow.append("<td>Animation</td>");
48971 this.startAnimation = document.createElement("div");
48972 $(this.startAnimation).addClass("smallButton playDisabled");
48973 this.pauseAnimation = document.createElement("div");
48974 $(this.pauseAnimation).addClass("smallButton pauseDisabled");
48975 controlsRow.append($("<td></td>").append(this.startAnimation).append(this.pauseAnimation));
48976
48977 headerRow.append("<td>Dated Objects</td>");
48978 this.numberDatedObjects = 0;
48979 this.numberDatedObjectsDIV = document.createElement("div");
48980 $(this.numberDatedObjectsDIV).addClass("ddbElementsCount");
48981 controlsRow.append($("<td></td>").append(this.numberDatedObjectsDIV));
48982 }
48983
48984 FuzzyTimelineRangeSlider.prototype = {
48985
48986 initialize : function(datasets) {
48987 var rangeSlider = this;
48988 rangeSlider.datasets = datasets;
48989
48990 //reset values
48991 rangeSlider.spans = [];
48992 rangeSlider.spanHash = [];
48993
48994 //find smallest (most accurate) time-span
48995 var smallestSpan;
48996 rangeSlider.numberDatedObjects = 0;
48997 $(this.datasets).each(function(){
48998 $(this.objects).each(function(){
48999 var dataObject = this;
49000 var span;
49001 if (dataObject.isTemporal){
49002 rangeSlider.numberDatedObjects++;
49003 smallestSpan = moment.duration(1,'milliseconds');
49004 } else if (dataObject.isFuzzyTemporal){
49005 rangeSlider.numberDatedObjects++;
49006 span = moment.duration(dataObject.TimeSpanEnd-dataObject.TimeSpanBegin);
49007 if ( (typeof smallestSpan === 'undefined') || (span < smallestSpan))
49008 smallestSpan = span;
49009 }
49010 });
49011 if ((typeof smallestSpan !== 'undefined') && (smallestSpan.asMilliseconds() === 1))
49012 return false;
49013 });
49014
49015 //show number of objects that have a time in header
49016 $(rangeSlider.numberDatedObjectsDIV).empty().append(rangeSlider.numberDatedObjects + " results");
49017
49018 if (typeof smallestSpan === 'undefined')
49019 return;
49020
49021 var fixedSpans = [
49022 moment.duration(1, 'seconds'),
49023 moment.duration(1, 'minutes'),
49024 moment.duration(10, 'minutes'),
49025 moment.duration(15, 'minutes'),
49026 moment.duration(30, 'minutes'),
49027 moment.duration(1, 'hours'),
49028 moment.duration(5, 'hours'),
49029 moment.duration(10, 'hours'),
49030 moment.duration(12, 'hours'),
49031 moment.duration(1, 'days'),
49032 moment.duration(7, 'days'),
49033 moment.duration(1, 'weeks'),
49034 moment.duration(2, 'weeks'),
49035 moment.duration(1, 'months'),
49036 moment.duration(2, 'months'),
49037 moment.duration(3, 'months'),
49038 moment.duration(6, 'months'),
49039 moment.duration(1, 'years'),
49040 moment.duration(5, 'years'),
49041 moment.duration(10, 'years'),
49042 moment.duration(20, 'years'),
49043 moment.duration(25, 'years'),
49044 moment.duration(50, 'years'),
49045 moment.duration(100, 'years'),
49046 moment.duration(200, 'years'),
49047 moment.duration(250, 'years'),
49048 moment.duration(500, 'years'),
49049 moment.duration(1000, 'years'),
49050 moment.duration(2000, 'years'),
49051 moment.duration(2500, 'years'),
49052 moment.duration(5000, 'years'),
49053 moment.duration(10000, 'years'),
49054 ];
49055 var overallSpan = rangeSlider.parent.overallMax-rangeSlider.parent.overallMin;
49056 //only add spans that are not too small for the data
49057 for (var i = 0; i < fixedSpans.length; i++){
49058 if ( (fixedSpans[i].asMilliseconds() > (smallestSpan.asMilliseconds() * 0.25)) &&
49059 (fixedSpans[i].asMilliseconds() < overallSpan)
49060 &&
49061 (
49062 rangeSlider.parent.options.showAllPossibleSpans ||
49063 ((rangeSlider.parent.overallMax-rangeSlider.parent.overallMin)/fixedSpans[i]<rangeSlider.options.maxBars)
49064 ))
49065 rangeSlider.spans.push(fixedSpans[i]);
49066 }
49067
49068 $(rangeSlider.rangeDropdown).empty();
49069
49070 $(rangeSlider.rangeDropdown).append("<option>continuous</option>");
49071 var index = 0;
49072 $(rangeSlider.spans).each(function(){
49073 var duration = this;
49074 if (duration < moment.duration(1,'second'))
49075 humanizedSpan = duration.milliseconds() + "ms";
49076 else if (duration < moment.duration(1,'minute'))
49077 humanizedSpan = duration.seconds() + "s";
49078 else if (duration < moment.duration(1,'hour'))
49079 humanizedSpan = duration.minutes() + "min";
49080 else if (duration < moment.duration(1,'day'))
49081 humanizedSpan = duration.hours() + "h";
49082 else if (duration < moment.duration(1,'month')){
49083 var days = duration.days();
49084 humanizedSpan = days + " day";
49085 if (days > 1)
49086 humanizedSpan += "s";
49087 } else if (duration < moment.duration(1,'year')){
49088 var months = duration.months();
49089 humanizedSpan = months + " month";
49090 if (months > 1)
49091 humanizedSpan += "s";
49092 } else {
49093 var years = duration.years();
49094 humanizedSpan = years + " year";
49095 if (years > 1)
49096 humanizedSpan += "s";
49097 }
49098 $(rangeSlider.rangeDropdown).append("<option index='"+index+"'>"+humanizedSpan+"</option>");
49099 index++;
49100 });
49101
49102 $(rangeSlider.rangeDropdown).change(function( eventObject ){
49103 var handlePosition = $(rangeSlider.rangeDropdown).find("option:selected").first().attr("index");
49104 //if there is no index, "continuous" is selected - so the density plot will be drawn
49105
49106 if (typeof handlePosition === "undefined"){
49107 rangeSlider.parent.switchViewMode("density");
49108 } else {
49109 rangeSlider.parent.switchViewMode("barchart");
49110 }
49111
49112 rangeSlider.parent.slidePositionChanged(rangeSlider.spans[handlePosition]);
49113 });
49114
49115 $(rangeSlider.rangeStart).empty();
49116 //add start of timeline selections
49117 //TODO: add Months/Days/etc., atm there are only years
49118 var starts = [];
49119 var overallMin = rangeSlider.parent.overallMin;
49120 var last = moment(overallMin).year();
49121 starts.push(last);
49122 for (i = 1;;i++){
49123 var date = moment(overallMin).year();
49124 date = date/Math.pow(10,i);
49125 if (Math.abs(date)<1)
49126 break;
49127 date = Math.floor(date);
49128 date = date*Math.pow(10,i);
49129 if (date != last)
49130 starts.push(date);
49131 last = date;
49132 }
49133 $(starts).each(function(){
49134 $(rangeSlider.rangeStart).append("<option>"+this+"</option>");
49135 });
49136
49137 $(rangeSlider.rangeStart).change(function( eventObject ){
49138 var handlePosition = rangeSlider.rangeStart.selectedIndex;
49139 var start = starts[handlePosition];
49140
49141 rangeSlider.parent.overallMin = moment().year(start);
49142 $(rangeSlider.rangeDropdown).change();
49143 });
49144
49145 $(rangeSlider.rangeDropdown).change();
49146
49147 $(rangeSlider.startAnimation).click(function(){
49148 if ($(rangeSlider.startAnimation).hasClass("playEnabled")){
49149 $(rangeSlider.startAnimation).removeClass("playEnabled").addClass("playDisabled");
49150 $(rangeSlider.pauseAnimation).removeClass("pauseDisabled").addClass("pauseEnabled");
49151
49152 rangeSlider.parent.startAnimation();
49153 }
49154 });
49155
49156 $(rangeSlider.pauseAnimation).prop('disabled', true);
49157 $(rangeSlider.pauseAnimation).click(function(){
49158 if ($(rangeSlider.pauseAnimation).hasClass("pauseEnabled")){
49159 $(rangeSlider.startAnimation).removeClass("playDisabled").addClass("playEnabled");
49160 $(rangeSlider.pauseAnimation).removeClass("pauseEnabled").addClass("pauseDisabled");
49161
49162 rangeSlider.parent.pauseAnimation();
49163 }
49164 });
49165 },
49166
49167 triggerHighlight : function(columnElement) {
49168
49169 },
49170
49171 triggerSelection : function(columnElement) {
49172
49173 },
49174
49175 deselection : function() {
49176 },
49177
49178 filtering : function() {
49179 },
49180
49181 inverseFiltering : function() {
49182 },
49183
49184 triggerRefining : function() {
49185 },
49186
49187 reset : function() {
49188 },
49189
49190 show : function() {
49191 },
49192
49193 hide : function() {
49194 }
49195 };
49196 /*
49197 * FuzzyTimelineWidget.js
49198 *
49199 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
49200 *
49201 * This library is free software; you can redistribute it and/or
49202 * modify it under the terms of the GNU Lesser General Public
49203 * License as published by the Free Software Foundation; either
49204 * version 3 of the License, or (at your option) any later version.
49205 *
49206 * This library is distributed in the hope that it will be useful,
49207 * but WITHOUT ANY WARRANTY; without even the implied warranty of
49208 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
49209 * Lesser General Public License for more details.
49210 *
49211 * You should have received a copy of the GNU Lesser General Public
49212 * License along with this library; if not, write to the Free Software
49213 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
49214 * MA 02110-1301 USA
49215 */
49216
49217 /**
49218 * @class FuzzyTimelineWidget
49219 * FuzzyTimelineWidget Implementation
49220 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
49221 *
49222 * @param {WidgetWrapper} core wrapper for interaction to other widgets
49223 * @param {HTML object} div parent div to append the FuzzyTimeline widget div
49224 * @param {JSON} options user specified configuration that overwrites options in FuzzyTimelineConfig.js
49225 */
49226 FuzzyTimelineWidget = function(core, div, options) {
49227 if (typeof FuzzyTimelineWidget_cont == "undefined"){
49228 FuzzyTimelineWidget_cont="Done";
49229
49230 this.datasets;
49231 this.selected = undefined;
49232 this.overallMin;
49233 this.overallMax;
49234
49235 this.core = core;
49236 this.core.setWidget(this);
49237
49238 this.options = (new FuzzyTimelineConfig(options)).options;
49239 this.gui = new FuzzyTimelineGui(this, div, this.options);
49240
49241 this.viewMode;
49242 this.density;
49243 this.rangeSlider;
49244 this.rangeBars;
49245 this.rangePiechart;
49246 this.spanHash = [];
49247
49248 this.handles = [];
49249 this.zoomFactor = 1;
49250
49251 this.scaleMode = "normal";
49252 }
49253 }
49254
49255 FuzzyTimelineWidget.prototype = {
49256
49257 initWidget : function(data) {
49258 var fuzzyTimeline = this;
49259
49260 delete fuzzyTimeline.overallMin;
49261 delete fuzzyTimeline.overallMax;
49262
49263 $(fuzzyTimeline.gui.plotDiv).empty();
49264 $(fuzzyTimeline.gui.sliderTable).empty();
49265 delete fuzzyTimeline.rangeSlider;
49266 $(fuzzyTimeline.gui.rangePiechartDiv).empty();
49267 delete fuzzyTimeline.rangePiechart;
49268
49269 fuzzyTimeline.switchViewMode("density");
49270
49271 if ( (data instanceof Array) && (data.length > 0) )
49272 {
49273 fuzzyTimeline.datasets = data;
49274
49275 $(fuzzyTimeline.datasets).each(function(){
49276 $(this.objects).each(function(){
49277 var datemin,datemax;
49278 if (this.isTemporal){
49279 //TODO: allow more than one date
49280 datemin = moment(this.dates[0].date);
49281 datemax = datemin;
49282 } else if (this.isFuzzyTemporal){
49283 //TODO: allow more than one date
49284 datemin = this.TimeSpanBegin;
49285 datemax = this.TimeSpanEnd;
49286 }
49287
49288 if (typeof fuzzyTimeline.overallMin === "undefined")
49289 fuzzyTimeline.overallMin = datemin;
49290 if (typeof fuzzyTimeline.overallMax === "undefined")
49291 fuzzyTimeline.overallMax = datemax;
49292
49293 if (fuzzyTimeline.overallMin > datemin)
49294 fuzzyTimeline.overallMin = datemin;
49295 if (fuzzyTimeline.overallMax < datemax)
49296 fuzzyTimeline.overallMax = datemax;
49297 });
49298 });
49299
49300 fuzzyTimeline.rangeSlider = new FuzzyTimelineRangeSlider(fuzzyTimeline);
49301 fuzzyTimeline.rangeSlider.initialize(fuzzyTimeline.datasets);
49302
49303 fuzzyTimeline.rangePiechart = new FuzzyTimelineRangePiechart(fuzzyTimeline, fuzzyTimeline.gui.rangePiechartDiv);
49304 fuzzyTimeline.rangePiechart.initialize(fuzzyTimeline.datasets);
49305 }
49306 },
49307
49308 switchViewMode : function(viewMode){
49309 var fuzzyTimeline = this;
49310 if (viewMode !== fuzzyTimeline.viewMode){
49311 $(fuzzyTimeline.gui.plotDiv).empty();
49312 if (viewMode === "density"){
49313 fuzzyTimeline.density = new FuzzyTimelineDensity(fuzzyTimeline,fuzzyTimeline.gui.plotDiv);
49314 } else if (viewMode === "barchart"){
49315 fuzzyTimeline.rangeBars = new FuzzyTimelineRangeBars(fuzzyTimeline);
49316 }
49317 fuzzyTimeline.viewMode = viewMode;
49318 }
49319 },
49320
49321 scaleData : function(data){
49322 var fuzzyTimeline = this;
49323 if (fuzzyTimeline.scaleMode == "normal"){
49324 return data;
49325 } else if (fuzzyTimeline.scaleMode == "logarithm"){
49326 for(var index in data){
49327 var val = data[index];
49328 if (val!=0){
49329 var sign = 1;
49330 if (val<0){
49331 sign = -1;
49332 }
49333 data[index] = sign*Math.log(Math.abs(data[index])+1);
49334 }
49335 }
49336 return data;
49337 } else if (fuzzyTimeline.scaleMode == "percentage"){
49338 var overallCnt = 0;
49339 for(var index in data){
49340 var val = data[index];
49341 if (val > 0){
49342 overallCnt += val;
49343 }
49344 }
49345 //make 1 = 100%
49346 overallCnt = overallCnt/100;
49347 if (overallCnt != 0){
49348 for(var index in data){
49349 data[index] = (data[index])/overallCnt;
49350 }
49351 }
49352 return data;
49353 }
49354 },
49355
49356 changeScaleMode : function(scaleMode) {
49357 var fuzzyTimeline = this;
49358 fuzzyTimeline.scaleMode = scaleMode;
49359 fuzzyTimeline.drawFuzzyTimeline();
49360 },
49361
49362 slidePositionChanged : function(spanWidth) {
49363 var fuzzyTimeline = this;
49364 fuzzyTimeline.spanWidth = spanWidth;
49365 fuzzyTimeline.drawFuzzyTimeline();
49366 },
49367
49368 drawFuzzyTimeline : function(){
49369 var fuzzyTimeline = this;
49370 var datasets = fuzzyTimeline.datasets;
49371 if (fuzzyTimeline.viewMode === "density"){
49372 //redraw density plot
49373 fuzzyTimeline.density.drawDensityPlot(datasets);
49374 //select currently selected data (if there is any)
49375 fuzzyTimeline.density.selectionChanged(fuzzyTimeline.selected);
49376 } else if (fuzzyTimeline.viewMode === "barchart"){
49377 //redraw range plot
49378 fuzzyTimeline.rangeBars.drawRangeBarChart(datasets,fuzzyTimeline.spanWidth);
49379 //select currently selected data (if there is any)
49380 fuzzyTimeline.rangeBars.selectionChanged(fuzzyTimeline.selected);
49381 }
49382 },
49383
49384 highlightChanged : function(objects) {
49385 var fuzzyTimeline = this;
49386 if( !GeoTemConfig.highlightEvents ){
49387 return;
49388 }
49389 if ( (typeof objects === "undefined") || (objects.length == 0) ){
49390 return;
49391 }
49392 if (fuzzyTimeline.viewMode === "density")
49393 this.density.highlightChanged(objects);
49394 else if (fuzzyTimeline.viewMode === "barchart")
49395 this.rangeBars.highlightChanged(objects);
49396
49397 fuzzyTimeline.rangePiechart.highlightChanged(objects);
49398 },
49399
49400 selectionChanged : function(selection) {
49401 var fuzzyTimeline = this;
49402 if( !GeoTemConfig.selectionEvents ){
49403 return;
49404 }
49405 if ((typeof selection.objects !== "undefined")&&
49406 (selection.objects.length == GeoTemConfig.datasets.length)){
49407 var objectCount = 0;
49408 for (var i=0, il=selection.objects.length; i < il; i++){
49409 objectCount += selection.objects[i].length;
49410 }
49411 if (objectCount > 0){
49412 fuzzyTimeline.selected = selection.objects;
49413 } else {
49414 delete fuzzyTimeline.selected;
49415 }
49416 } else
49417 delete fuzzyTimeline.selected;
49418 if (fuzzyTimeline.viewMode === "density")
49419 this.density.selectionChanged(fuzzyTimeline.selected);
49420 else if (fuzzyTimeline.viewMode === "barchart")
49421 this.rangeBars.selectionChanged(fuzzyTimeline.selected);
49422
49423 if (selection.valid())
49424 fuzzyTimeline.rangePiechart.selectionChanged(fuzzyTimeline.selected);
49425 else
49426 fuzzyTimeline.rangePiechart.selectionChanged([]);
49427
49428 //selections "overwrite" each other
49429 if (selection.widget != fuzzyTimeline)
49430 fuzzyTimeline.clearHandles();
49431 },
49432
49433 buildSpanArray : function(spanWidth) {
49434 var spanArray = [];
49435 var tickStart = moment(this.overallMin);
49436 do{
49437 spanArray.push(moment(tickStart));
49438 tickStart.add(spanWidth);
49439 } while (tickStart <= this.overallMax);
49440 spanArray.push(moment(tickStart));
49441
49442 this.spanHash.push({spanWidth:spanWidth,overallMin:moment(this.overallMin),spanArray:spanArray});
49443 return(spanArray);
49444 },
49445
49446 getSpanArray : function(spanWidth){
49447 for (var i = 0; i < this.spanHash.length; i++){
49448 var element = this.spanHash[i];
49449 if ( ((this.overallMin-element.overallMin)===0) &&
49450 ((spanWidth-element.spanWidth)===0))
49451 return element.spanArray;
49452 }
49453 return this.buildSpanArray(spanWidth);
49454 },
49455
49456 clearSpanArray : function(){
49457 this.spanHash = [];
49458 },
49459
49460 getTicks : function(dataObject, spanWidth) {
49461 var datemin,datemax;
49462 if (dataObject.isTemporal){
49463 datemin = moment(dataObject.dates[0].date);
49464 datemax = datemin;
49465 } else if (dataObject.isFuzzyTemporal){
49466 datemin = dataObject.TimeSpanBegin;
49467 datemax = dataObject.TimeSpanEnd;
49468 } else{
49469 return;
49470 }
49471
49472 if (typeof spanWidth._data === "undefined"){
49473 //This does only work with millisecond spans, as the length of years is (very) inaccurate.
49474 //(e.g. 100-0 = 99, 2000-1000 = 1001, 5000-0 = 5003, and so on and even more: duration(5000a) = 4932a)
49475 //So the time consuming loop below is needed for accurate dates, when years/months/days etc. are supplied
49476 var firstTick = Math.floor((datemin-this.overallMin)/spanWidth);
49477 var lastTick = Math.floor((datemax-this.overallMin)/spanWidth);
49478 //calculate how much the first (and last) tick and the time-span overlap
49479 var firstTickPercentage = 1;
49480 var lastTickPercentage = 1;
49481 if (firstTick != lastTick){
49482 var secondTickStart = this.overallMin+(firstTick+1)*spanWidth;
49483 var lastTickStart = this.overallMin+lastTick*spanWidth;
49484 firstTickPercentage = (secondTickStart-datemin)/spanWidth;
49485 lastTickPercentage = (datemax-lastTickStart)/spanWidth;
49486 }
49487 if (firstTickPercentage === 0){
49488 firstTick++;
49489 firstTickPercentage = 1;
49490 }
49491 if (lastTickPercentage === 0){
49492 lastTick--;
49493 lastTickPercentage = 1;
49494 }
49495 } else {
49496 var spanArray = this.getSpanArray(spanWidth);
49497 var firstTick, lastTick;
49498 var tickCount = 0;
49499 var tickStart = spanArray[0];
49500 var lastTickStart;
49501 do{
49502 lastTickStart = spanArray[tickCount];
49503 tickCount++;
49504 tickStart = spanArray[tickCount];
49505 if ( (typeof firstTick === "undefined") && (datemin < tickStart) ){
49506 firstTick = tickCount-1;
49507 firstTickPercentage = (tickStart - datemin)/spanWidth;
49508 }
49509 if ( (typeof lastTick === "undefined") && (datemax <= tickStart) ){
49510 lastTick = tickCount-1;
49511 lastTickPercentage = (datemax - lastTickStart)/spanWidth;
49512 }
49513 } while (tickStart < datemax);
49514 if (firstTick == lastTick){
49515 firstTickPercentage = 1;
49516 lastTickPercentage = 1;
49517 }
49518 }
49519
49520 return({ firstTick:firstTick,
49521 lastTick:lastTick,
49522 firstTickPercentage:firstTickPercentage,
49523 lastTickPercentage:lastTickPercentage});
49524 },
49525
49526 getObjects : function(dateStart, dateEnd) {
49527 var fuzzyTimeline = this;
49528 var searchDateStart, searchDateEnd;
49529 if (typeof dateStart !== "undefined")
49530 searchDateStart = moment(dateStart);
49531 if (typeof dateEnd !== "undefined")
49532 searchDateEnd = moment(dateEnd);
49533
49534 var datasets = [];
49535 $(fuzzyTimeline.datasets).each(function(){
49536 var objects = [];
49537 //check if we got "real" datasets, or just array of objects
49538 var datasetObjects = this;
49539 if (typeof this.objects !== "undefined")
49540 datasetObjects = this.objects;
49541 $(datasetObjects).each(function(){
49542 var datemin,datemax;
49543 var dataObject = this;
49544 if (dataObject.isTemporal){
49545 datemin = moment(dataObject.dates[0].date);
49546 datemax = datemin;
49547 } else if (dataObject.isFuzzyTemporal){
49548 datemin = dataObject.TimeSpanBegin;
49549 datemax = dataObject.TimeSpanEnd;
49550 } else{
49551 return;
49552 }
49553
49554 if (typeof searchDateEnd === 'undefined'){
49555 if ( (datemin <= searchDateStart) && (datemax >= searchDateStart) )
49556 objects.push(this);
49557 } else {
49558 if ((datemin < searchDateEnd) && (datemax >= searchDateStart))
49559 objects.push(this);
49560 }
49561 });
49562 datasets.push(objects);
49563 });
49564
49565 return(datasets);
49566 },
49567
49568 triggerHighlight : function(highlightedObjects){
49569 var fuzzyTimeline = this;
49570 if (fuzzyTimeline.viewMode === "density")
49571 fuzzyTimeline.density.highlightChanged(highlightedObjects);
49572 else if (fuzzyTimeline.viewMode === "barchart")
49573 fuzzyTimeline.rangeBars.highlightChanged(highlightedObjects);
49574
49575 fuzzyTimeline.core.triggerHighlight(highlightedObjects);
49576 },
49577
49578 triggerSelection : function(selectedObjects){
49579 var fuzzyTimeline = this;
49580 fuzzyTimeline.selected = selectedObjects;
49581 if (fuzzyTimeline.viewMode === "density")
49582 fuzzyTimeline.density.selectionChanged(selectedObjects);
49583 else if (fuzzyTimeline.viewMode === "barchart")
49584 fuzzyTimeline.rangeBars.selectionChanged(selectedObjects);
49585
49586 selection = new Selection(selectedObjects);
49587
49588 fuzzyTimeline.core.triggerSelection(selection);
49589 },
49590
49591 addHandle : function(x1,x2){
49592 var fuzzyTimeline = this;
49593 //make sure the interval is ordered correctly
49594 if (x2<x1){
49595 var temp = x1;
49596 x1 = x2;
49597 x2 = temp;
49598 }
49599 fuzzyTimeline.handles.push({x1:x1,x2:x2});
49600 fuzzyTimeline.drawHandles();
49601 //enabled "play" button
49602 $(fuzzyTimeline.rangeSlider.startAnimation).removeClass("playDisabled").addClass("playEnabled");
49603 },
49604
49605 selectByX : function(x1,x2){
49606 var fuzzyTimeline = this;
49607 if (fuzzyTimeline.viewMode === "density"){
49608 fuzzyTimeline.density.selectByX(x1,x2);
49609 } else if (fuzzyTimeline.viewMode === "barchart"){
49610 fuzzyTimeline.rangeBars.selectByX(x1,x2);
49611 }
49612 },
49613
49614 drawHandles : function(){
49615 var fuzzyTimeline = this;
49616
49617 $(fuzzyTimeline.gui.plotDiv).find(".plotHandle").remove();
49618 $(fuzzyTimeline.gui.plotDiv).find(".dragTimeRangeAlt").remove();
49619 $(fuzzyTimeline.gui.plotDiv).find(".plotHandleBox").remove();
49620
49621 var plotHeight = (fuzzyTimeline.density.plot?fuzzyTimeline.density.plot:fuzzyTimeline.rangeBars.plot).height();
49622 var plotWidth = (fuzzyTimeline.density.plot?fuzzyTimeline.density.plot:fuzzyTimeline.rangeBars.plot).width();
49623 //flot sends the wrong width if we extend the parent div, so scale it accordingly
49624 plotWidth = plotWidth*fuzzyTimeline.zoomFactor;
49625 var plotOffset = (fuzzyTimeline.density.plot?fuzzyTimeline.density.plot:fuzzyTimeline.rangeBars.plot).getPlotOffset().left;
49626
49627 $(fuzzyTimeline.handles).each(function(){
49628 var handle = this;
49629
49630 var moveLeftHandle = function(){
49631 leftHandle.style.left = handle.x1-$(leftHandle).width() + "px";
49632 };
49633
49634 var moveRightHandle = function(){
49635 rightHandle.style.left = handle.x2+ "px";
49636 };
49637
49638 var resizeHandleBox = function(){
49639 handleBox.style.left = handle.x1+"px";
49640 $(handleBox).width(handle.x2-handle.x1);
49641 };
49642
49643 var moveDragButton = function(){
49644 dragButton.style.left = (handle.x1+handle.x2)/2 - $(dragButton).width()/2 + "px";
49645 };
49646
49647 var leftHandle = document.createElement("div");
49648 leftHandle.title = GeoTemConfig.getString('leftHandle');
49649 leftHandle.style.backgroundImage = "url(" + GeoTemConfig.path + "leftHandle.png" + ")";
49650 leftHandle.setAttribute('class', 'plotHandle plotHandleIcon');
49651 leftHandle.style.visibility = "visible";
49652 $(fuzzyTimeline.gui.plotDiv).append(leftHandle);
49653 moveLeftHandle();
49654 leftHandle.style.top = plotHeight/2-$(leftHandle).height()/2 + "px";
49655
49656 var rightHandle = document.createElement("div");
49657 rightHandle.title = GeoTemConfig.getString('leftHandle');
49658 rightHandle.style.backgroundImage = "url(" + GeoTemConfig.path + "rightHandle.png" + ")";
49659 rightHandle.setAttribute('class', 'plotHandle plotHandleIcon');
49660 rightHandle.style.visibility = "visible";
49661 moveRightHandle();
49662 $(fuzzyTimeline.gui.plotDiv).append(rightHandle);
49663
49664 rightHandle.style.top = plotHeight/2-$(rightHandle).height()/2 + "px";
49665
49666 var handleBox = document.createElement("div");
49667 $(fuzzyTimeline.gui.plotDiv).append(handleBox);
49668 $(handleBox).addClass("plotHandleBox");
49669 resizeHandleBox();
49670 $(handleBox).height(plotHeight);
49671
49672 var dragButton = document.createElement("div");
49673 dragButton.title = GeoTemConfig.getString('dragTimeRange');
49674 dragButton.style.backgroundImage = "url(" + GeoTemConfig.path + "drag.png" + ")";
49675 dragButton.setAttribute('class', 'dragTimeRangeAlt plotHandleIcon');
49676 $(fuzzyTimeline.gui.plotDiv).append(dragButton);
49677 moveDragButton();
49678 dragButton.style.top = plotHeight + "px";
49679
49680 $(leftHandle).mousedown(function(){
49681 $(fuzzyTimeline.gui.plotDiv).mousemove(function(eventObj){
49682 var x = eventObj.clientX;
49683 x += $(fuzzyTimeline.gui.plotDiv).parent().scrollLeft();
49684 if ((x < handle.x2) &&
49685 (x >= plotOffset)){
49686 x = x - leftHandle.offsetWidth;
49687 handle.x1 = x + $(leftHandle).width();
49688
49689 moveLeftHandle();
49690 resizeHandleBox();
49691 moveDragButton();
49692 }
49693 });
49694 $(fuzzyTimeline.gui.plotDiv).mouseup(function(eventObj){
49695 fuzzyTimeline.selectByX(handle.x1,handle.x2);
49696 $(fuzzyTimeline.gui.plotDiv).unbind("mouseup");
49697 $(fuzzyTimeline.gui.plotDiv).unbind("mousemove");
49698 });
49699 });
49700
49701 $(rightHandle).mousedown(function(){
49702 $(fuzzyTimeline.gui.plotDiv).mousemove(function(eventObj){
49703 var x = eventObj.clientX;
49704 x += $(fuzzyTimeline.gui.plotDiv).parent().scrollLeft();
49705 x = x - rightHandle.offsetWidth;
49706 if ((x > handle.x1) &&
49707 (x <= plotOffset+plotWidth)){
49708 handle.x2 = x;
49709
49710 moveRightHandle();
49711 resizeHandleBox();
49712 moveDragButton();
49713 }
49714 });
49715 $(fuzzyTimeline.gui.plotDiv).mouseup(function(eventObj){
49716 fuzzyTimeline.selectByX(handle.x1,handle.x2);
49717 $(fuzzyTimeline.gui.plotDiv).unbind("mouseup");
49718 $(fuzzyTimeline.gui.plotDiv).unbind("mousemove");
49719 });
49720 });
49721
49722 $(dragButton).mousedown(function(){
49723 $(fuzzyTimeline.gui.plotDiv).mousemove(function(eventObj){
49724 var x = eventObj.clientX;
49725 //TODO: for some reason we don't need the scoll offset here
49726 //this should be investigated?
49727 //x += $(fuzzyTimeline.gui.plotDiv).parent().scrollLeft();
49728 var xdiff = x - $(dragButton).offset().left - $(dragButton).width()/2;
49729 handle.x1 = handle.x1+xdiff;
49730 handle.x2 = handle.x2+xdiff;
49731
49732 moveLeftHandle();
49733 moveRightHandle();
49734 resizeHandleBox();
49735 moveDragButton();
49736 });
49737 $(fuzzyTimeline.gui.plotDiv).mouseup(function(eventObj){
49738 if (handle.x1 < plotOffset)
49739 handle.x1 = plotOffset;
49740 if (handle.x2 > plotOffset+plotWidth)
49741 handle.x2 = plotOffset+plotWidth;
49742
49743 moveLeftHandle();
49744 moveRightHandle();
49745 resizeHandleBox();
49746 moveDragButton();
49747
49748 fuzzyTimeline.selectByX(handle.x1,handle.x2);
49749 $(fuzzyTimeline.gui.plotDiv).unbind("mouseup");
49750 $(fuzzyTimeline.gui.plotDiv).unbind("mousemove");
49751 });
49752 });
49753 });
49754 },
49755
49756 clearHandles : function(){
49757 var fuzzyTimeline = this;
49758 $(fuzzyTimeline.gui.plotDiv).find(".plotHandle").remove();
49759 $(fuzzyTimeline.gui.plotDiv).find(".dragTimeRangeAlt").remove();
49760 $(fuzzyTimeline.gui.plotDiv).find(".plotHandleBox").remove();
49761 fuzzyTimeline.handles = [];
49762 //disable buttons
49763 $(fuzzyTimeline.rangeSlider.startAnimation).removeClass("playEnabled").addClass("playDisabled");
49764 $(fuzzyTimeline.rangeSlider.pauseAnimation).removeClass("pauseEnabled").addClass("pauseDisabled");
49765 //stop the animation (if one was running)
49766 fuzzyTimeline.pauseAnimation();
49767 },
49768
49769 startAnimation : function(){
49770 var fuzzyTimeline = this;
49771 fuzzyTimeline.loopFunction = function(steps){
49772 $(fuzzyTimeline.handles).each(function(){
49773 if (typeof steps === "undefined")
49774 steps = 1;
49775
49776 var handle = this;
49777 var x1 = handle.x1;
49778 var x2 = handle.x2;
49779
49780 if (typeof handle.width === "undefined")
49781 handle.width = x2-x1;
49782
49783 var plotWidth = (fuzzyTimeline.density.plot?fuzzyTimeline.density.plot:fuzzyTimeline.rangeBars.plot).width();
49784 var plotOffset = (fuzzyTimeline.density.plot?fuzzyTimeline.density.plot:fuzzyTimeline.rangeBars.plot).getPlotOffset().left;
49785
49786 var plotMax = plotWidth+plotOffset;
49787
49788 //TODO: has to be plotMin
49789 if (!((x1 === plotOffset)&&(x2-x1 <= handle.width))){
49790 x1 += steps;
49791 }
49792 if (x2 <= plotMax){
49793 x2 += steps;
49794 if (x2 > plotMax)
49795 x2 = plotMax;
49796 if (x2-x1 > handle.width){
49797 x1 = x2-handle.width;
49798 }
49799 }
49800 if (x1 >= plotMax){
49801 //TODO: has to be plotMin
49802 x1 = plotOffset;
49803 x2 = plotOffset;
49804 }
49805
49806 handle.x1 = x1;
49807 handle.x2 = x2;
49808
49809 fuzzyTimeline.drawHandles();
49810 fuzzyTimeline.selectByX(handle.x1, handle.x2);
49811 });
49812 };
49813
49814 fuzzyTimeline.loopId = setInterval(function(){
49815 fuzzyTimeline.loopFunction(10);
49816 }, 100);
49817 },
49818
49819 pauseAnimation : function(){
49820 var fuzzyTimeline = this;
49821 clearInterval(fuzzyTimeline.loopId);
49822 $(fuzzyTimeline.handles).each(function(){
49823 var handle = this;
49824 delete handle.width;
49825 });
49826 },
49827
49828 //This function enlargens the plot area
49829 zoomPlot : function(zoomFactor){
49830 var fuzzyTimeline = this;
49831 var oldZoomFactor = fuzzyTimeline.zoomFactor;
49832 fuzzyTimeline.zoomFactor = zoomFactor;
49833 if (zoomFactor > 1){
49834 $(fuzzyTimeline.gui.plotDiv).width(zoomFactor*100+"%");
49835 } else{
49836 $(fuzzyTimeline.gui.plotDiv).width("100%");
49837 }
49838 //leave place for the scrollbar
49839 $(fuzzyTimeline.gui.plotDiv).height(fuzzyTimeline.gui.plotDIVHeight-20);
49840
49841 //fit handles
49842 //this does not make much sense, as the selections are _completely_ different
49843 //for each scale rate, as the objects may reside in different "ticks" of the graph
49844 $(fuzzyTimeline.handles).each(function(){
49845 var handle = this;
49846 handle.x1 = handle.x1 * (zoomFactor/oldZoomFactor);
49847 handle.x2 = handle.x2 * (zoomFactor/oldZoomFactor);
49848 });
49849 },
49850
49851 getConfig : function(inquiringWidget){
49852 var fuzzyTimeline = this;
49853 var config = {};
49854
49855 //create handle copy
49856 var handleCopy = JSON.parse( JSON.stringify( fuzzyTimeline.handles ) );
49857 config.handles = handleCopy;
49858
49859 config.viewMode = fuzzyTimeline.viewMode;
49860
49861 config.rangeDropdownVal = $(fuzzyTimeline.rangeSlider.rangeDropdown).val();
49862 config.rangeStartVal = $(fuzzyTimeline.rangeSlider.rangeStart).val();
49863
49864 //send config to iquiring widget
49865 if (typeof inquiringWidget.sendConfig !== "undefined"){
49866 inquiringWidget.sendConfig({widgetName: "fuzzyTimeline", 'config': config});
49867 }
49868 },
49869
49870 setConfig : function(configObj){
49871 var fuzzyTimeline = this;
49872
49873 if (configObj.widgetName === "fuzzyTimeline"){
49874 var config = configObj.config;
49875
49876 $(fuzzyTimeline.rangeSlider.rangeDropdown).val(config.rangeDropdownVal);
49877 $(fuzzyTimeline.rangeSlider.rangeDropdown).change();
49878 fuzzyTimeline.switchViewMode(config.viewMode);
49879
49880 $(fuzzyTimeline.rangeSlider.rangeStart).val(config.rangeStartVal);
49881 $(fuzzyTimeline.rangeSlider.rangeStart).change();
49882
49883 //clear handles
49884 fuzzyTimeline.clearHandles();
49885
49886 //create handle copy
49887 var handleCopy = JSON.parse( JSON.stringify( config.handles ) );
49888 fuzzyTimeline.handles = handleCopy;
49889
49890 // redraw handles
49891 fuzzyTimeline.drawHandles();
49892
49893 // select elements
49894 $(fuzzyTimeline.handles).each(function(){
49895 var handle = this;
49896 fuzzyTimeline.selectByX(handle.x1, handle.x2)
49897 });
49898 }
49899 },
49900 };
49901 /*
49902 * Overlayloader.js
49903 *
49904 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
49905 *
49906 * This library is free software; you can redistribute it and/or
49907 * modify it under the terms of the GNU Lesser General Public
49908 * License as published by the Free Software Foundation; either
49909 * version 3 of the License, or (at your option) any later version.
49910 *
49911 * This library is distributed in the hope that it will be useful,
49912 * but WITHOUT ANY WARRANTY; without even the implied warranty of
49913 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
49914 * Lesser General Public License for more details.
49915 *
49916 * You should have received a copy of the GNU Lesser General Public
49917 * License along with this library; if not, write to the Free Software
49918 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
49919 * MA 02110-1301 USA
49920 */
49921
49922 /**
49923 * @class Overlayloader
49924 * Implementation for a Overlayloader UI
49925 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
49926 *
49927 * @param {HTML object} parent div to append the Overlayloader
49928 */
49929 function Overlayloader(parent) {
49930
49931 this.overlayLoader = this;
49932
49933 this.parent = parent;
49934 this.options = parent.options;
49935 this.attachedMapWidgets = parent.attachedMapWidgets;
49936
49937 this.overlays = [];
49938
49939 this.initialize();
49940 }
49941
49942 Overlayloader.prototype = {
49943
49944 show : function() {
49945 this.overlayloaderDiv.style.display = "block";
49946 },
49947
49948 hide : function() {
49949 this.overlayloaderDiv.style.display = "none";
49950 },
49951
49952 initialize : function() {
49953
49954 this.addKMLLoader();
49955 this.addKMZLoader();
49956 this.addArcGISWMSLoader();
49957 this.addXYZLoader();
49958 this.addRomanEmpireLoader();
49959 this.addMapsForFreeWaterLayer();
49960 this.addConfigLoader();
49961
49962 // trigger change event on the select so
49963 // that only the first loader div will be shown
49964 $(this.parent.gui.loaderTypeSelect).change();
49965 },
49966
49967 distributeKML : function(kmlURL) {
49968 var newOverlay = new Object();
49969 newOverlay.name = kmlURL;
49970 newOverlay.layers = [];
49971
49972 $(this.attachedMapWidgets).each(function(){
49973 var newLayer = new OpenLayers.Layer.Vector("KML", {
49974 projection: this.openlayersMap.displayProjection,
49975 strategies: [new OpenLayers.Strategy.Fixed()],
49976 protocol: new OpenLayers.Protocol.HTTP({
49977 url: kmlURL,
49978 format: new OpenLayers.Format.KML({
49979 extractStyles: true,
49980 extractAttributes: true
49981 })
49982 })
49983 });
49984
49985 newOverlay.layers.push({map:this.openlayersMap,layer:newLayer});
49986
49987 this.openlayersMap.addLayer(newLayer);
49988 });
49989
49990 this.overlays.push(newOverlay);
49991 this.parent.gui.refreshOverlayList();
49992 },
49993
49994 distributeKMZ : function(kmzURL) {
49995 var newOverlay = new Object();
49996 newOverlay.name = kmzURL;
49997 newOverlay.layers = [];
49998
49999 $(this.attachedMapWidgets).each(function(){
50000 var newLayer = new OpenLayers.Layer.Vector("KML", {
50001 projection: this.openlayersMap.displayProjection,
50002 strategies: [new OpenLayers.Strategy.Fixed()],
50003 format: OpenLayers.Format.KML,
50004 extractAttributes: true
50005 });
50006
50007 newOverlay.layers.push({map:this.openlayersMap,layer:newLayer});
50008
50009 var map = this.openlayersMap;
50010
50011 GeoTemConfig.getKmz(kmzURL, function(kmlDoms){
50012 $(kmlDoms).each(function(){
50013 var kml = new OpenLayers.Format.KML().read(this);
50014 newLayer.addFeatures(kml);
50015 map.addLayer(newLayer);
50016 });
50017 });
50018 });
50019
50020 this.overlays.push(newOverlay);
50021 this.parent.gui.refreshOverlayList();
50022 },
50023
50024 distributeArcGISWMS : function(wmsURL, wmsLayer) {
50025 var newOverlay = new Object();
50026 newOverlay.name = wmsURL + " - " + wmsLayer;
50027 newOverlay.layers = [];
50028
50029 var newLayer = new OpenLayers.Layer.WMS("ArcGIS WMS label", wmsURL, {
50030 layers: wmsLayer,
50031 format: "image/png",
50032 transparent: "true"
50033 }
50034 ,{
50035 displayOutsideMaxExtent: true,
50036 isBaseLayer: false,
50037 projection : "EPSG:3857"
50038 }
50039 );
50040
50041 newLayer.setIsBaseLayer(false);
50042 $(this.attachedMapWidgets).each(function(){
50043 this.openlayersMap.addLayer(newLayer);
50044 newOverlay.layers.push({map:this.openlayersMap,layer:newLayer});
50045 });
50046
50047 this.overlays.push(newOverlay);
50048 this.parent.gui.refreshOverlayList();
50049 },
50050
50051 distributeXYZ : function(xyzURL,zoomOffset) {
50052 var newOverlay = new Object();
50053 newOverlay.name = xyzURL;
50054 newOverlay.layers = [];
50055
50056 var newLayer = new OpenLayers.Layer.XYZ(
50057 "XYZ Layer",
50058 [
50059 xyzURL
50060 ], {
50061 sphericalMercator: true,
50062 transitionEffect: "resize",
50063 buffer: 1,
50064 numZoomLevels: 12,
50065 transparent : true,
50066 isBaseLayer : false,
50067 zoomOffset:zoomOffset?zoomOffset:0
50068 }
50069 );
50070
50071 newLayer.setIsBaseLayer(false);
50072 $(this.attachedMapWidgets).each(function(){
50073 this.openlayersMap.addLayer(newLayer);
50074 newOverlay.layers.push({map:this.openlayersMap,layer:newLayer});
50075 });
50076
50077 this.overlays.push(newOverlay);
50078 this.parent.gui.refreshOverlayList();
50079 },
50080
50081 addKMLLoader : function() {
50082 $(this.parent.gui.loaderTypeSelect).append("<option value='KMLLoader'>KML File URL</option>");
50083
50084 this.KMLLoaderTab = document.createElement("div");
50085 $(this.KMLLoaderTab).attr("id","KMLLoader");
50086
50087 this.kmlURL = document.createElement("input");
50088 $(this.kmlURL).attr("type","text");
50089 $(this.KMLLoaderTab).append(this.kmlURL);
50090
50091 this.loadKMLButton = document.createElement("button");
50092 $(this.loadKMLButton).text("load KML");
50093 $(this.KMLLoaderTab).append(this.loadKMLButton);
50094
50095 $(this.loadKMLButton).click($.proxy(function(){
50096 var kmlURL = $(this.kmlURL).val();
50097 if (kmlURL.length == 0)
50098 return;
50099 if (typeof GeoTemConfig.proxy != 'undefined')
50100 kmlURL = GeoTemConfig.proxy + kmlURL;
50101
50102 this.distributeKML(kmlURL);
50103 },this));
50104
50105 $(this.parent.gui.loaders).append(this.KMLLoaderTab);
50106 },
50107
50108 addKMZLoader : function() {
50109 $(this.parent.gui.loaderTypeSelect).append("<option value='KMZLoader'>KMZ File URL</option>");
50110
50111 this.KMZLoaderTab = document.createElement("div");
50112 $(this.KMZLoaderTab).attr("id","KMZLoader");
50113
50114 this.kmzURL = document.createElement("input");
50115 $(this.kmzURL).attr("type","text");
50116 $(this.KMZLoaderTab).append(this.kmzURL);
50117
50118 this.loadKMZButton = document.createElement("button");
50119 $(this.loadKMZButton).text("load KMZ");
50120 $(this.KMZLoaderTab).append(this.loadKMZButton);
50121
50122 $(this.loadKMZButton).click($.proxy(function(){
50123 var kmzURL = $(this.kmzURL).val();
50124 if (kmzURL.length == 0)
50125 return;
50126 if (typeof GeoTemConfig.proxy != 'undefined')
50127 kmzURL = GeoTemConfig.proxy + kmzURL;
50128
50129 this.distributeKMZ(kmzURL);
50130 },this));
50131
50132 $(this.parent.gui.loaders).append(this.KMZLoaderTab);
50133 },
50134
50135 addArcGISWMSLoader : function() {
50136 $(this.parent.gui.loaderTypeSelect).append("<option value='ArcGISWMSLoader'>ArcGIS WMS</option>");
50137
50138 this.ArcGISWMSLoaderTab = document.createElement("div");
50139 $(this.ArcGISWMSLoaderTab).attr("id","ArcGISWMSLoader");
50140
50141 $(this.ArcGISWMSLoaderTab).append("URL: ");
50142
50143 this.wmsURL = document.createElement("input");
50144 $(this.wmsURL).attr("type","text");
50145 $(this.ArcGISWMSLoaderTab).append(this.wmsURL);
50146
50147 $(this.ArcGISWMSLoaderTab).append("Layer: ");
50148
50149 this.wmsLayer = document.createElement("input");
50150 $(this.wmsLayer).attr("type","text");
50151 $(this.ArcGISWMSLoaderTab).append(this.wmsLayer);
50152
50153 this.loadArcGISWMSButton = document.createElement("button");
50154 $(this.loadArcGISWMSButton).text("load Layer");
50155 $(this.ArcGISWMSLoaderTab).append(this.loadArcGISWMSButton);
50156
50157 $(this.loadArcGISWMSButton).click($.proxy(function(){
50158 var wmsURL = $(this.wmsURL).val();
50159 var wmsLayer = $(this.wmsLayer).val();
50160 if (wmsURL.length == 0)
50161 return;
50162
50163 this.distributeArcGISWMS(wmsURL, wmsLayer);
50164 },this));
50165
50166 $(this.parent.gui.loaders).append(this.ArcGISWMSLoaderTab);
50167 },
50168
50169 addXYZLoader : function() {
50170 $(this.parent.gui.loaderTypeSelect).append("<option value='XYZLoader'>XYZ Layer</option>");
50171
50172 this.XYZLoaderTab = document.createElement("div");
50173 $(this.XYZLoaderTab).attr("id","XYZLoader");
50174
50175 $(this.XYZLoaderTab).append("URL (with x,y,z variables): ");
50176
50177 this.xyzURL = document.createElement("input");
50178 $(this.xyzURL).attr("type","text");
50179 $(this.XYZLoaderTab).append(this.xyzURL);
50180
50181 this.loadXYZButton = document.createElement("button");
50182 $(this.loadXYZButton).text("load Layer");
50183 $(this.XYZLoaderTab).append(this.loadXYZButton);
50184
50185 $(this.loadXYZButton).click($.proxy(function(){
50186 var xyzURL = $(this.xyzURL).val();
50187 if (xyzURL.length == 0)
50188 return;
50189
50190 this.distributeXYZ(xyzURL);
50191 },this));
50192
50193 $(this.parent.gui.loaders).append(this.XYZLoaderTab);
50194 },
50195
50196 addRomanEmpireLoader : function() {
50197 $(this.parent.gui.loaderTypeSelect).append("<option value='RomanEmpireLoader'>Roman Empire</option>");
50198
50199 this.RomanEmpireLoaderTab = document.createElement("div");
50200 $(this.RomanEmpireLoaderTab).attr("id","RomanEmpireLoader");
50201
50202 this.loadRomanEmpireButton = document.createElement("button");
50203 $(this.loadRomanEmpireButton).text("load Layer");
50204 $(this.RomanEmpireLoaderTab).append(this.loadRomanEmpireButton);
50205
50206 $(this.loadRomanEmpireButton).click($.proxy(function(){
50207 this.distributeXYZ("http://pelagios.dme.ait.ac.at/tilesets/imperium/${z}/${x}/${y}.png",1);
50208 },this));
50209
50210 $(this.parent.gui.loaders).append(this.RomanEmpireLoaderTab);
50211 },
50212
50213 addMapsForFreeWaterLayer : function() {
50214 $(this.parent.gui.loaderTypeSelect).append("<option value='MapsForFreeWaterLayerLoader'>Water Layer (Maps-For-Free)</option>");
50215
50216 this.MapsForFreeWaterTab = document.createElement("div");
50217 $(this.MapsForFreeWaterTab).attr("id","MapsForFreeWaterLayerLoader");
50218
50219 this.loadMapsForFreeWaterLayerButton = document.createElement("button");
50220 $(this.loadMapsForFreeWaterLayerButton).text("load Layer");
50221 $(this.MapsForFreeWaterTab).append(this.loadMapsForFreeWaterLayerButton);
50222
50223 $(this.loadMapsForFreeWaterLayerButton).click($.proxy(function(){
50224 this.distributeXYZ("http://maps-for-free.com/layer/water/z${z}/row${y}/${z}_${x}-${y}.gif",1);
50225 },this));
50226
50227 $(this.parent.gui.loaders).append(this.MapsForFreeWaterTab);
50228 },
50229
50230 addConfigLoader : function() {
50231 if ( (this.parent.options.wms_overlays instanceof Array) &&
50232 (this.parent.options.wms_overlays.length > 0) ){
50233 var overlayloader = this;
50234
50235 $(this.parent.gui.loaderTypeSelect).append("<option value='ConfigLoader'>Other WMS maps</option>");
50236
50237 this.ConfigLoaderTab = document.createElement("div");
50238 $(this.ConfigLoaderTab).attr("id","ConfigLoader");
50239
50240 this.ConfigMapSelect = document.createElement("select");
50241 $(this.parent.options.wms_overlays).each(function(){
50242 var name = this.name, server = this.server, layer = this.layer;
50243 $(overlayloader.ConfigMapSelect).append("<option layer='"+layer+"' server='"+server+"' >"+name+"</option>");
50244 });
50245
50246 $(this.ConfigLoaderTab).append(this.ConfigMapSelect);
50247
50248 this.loadConfigMapButton = document.createElement("button");
50249 $(this.loadConfigMapButton).text("load Layer");
50250 $(this.ConfigLoaderTab).append(this.loadConfigMapButton);
50251
50252 $(this.loadConfigMapButton).click($.proxy(function(){
50253 var server = $(this.ConfigMapSelect).find(":selected").attr("server");
50254 var layer = $(this.ConfigMapSelect).find(":selected").attr("layer");
50255 this.distributeArcGISWMS(server,layer);
50256 },this));
50257
50258 $(this.parent.gui.loaders).append(this.ConfigLoaderTab);
50259 }
50260 }
50261
50262 };
50263 /*
50264 * OverlayloaderConfig.js
50265 *
50266 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
50267 *
50268 * This library is free software; you can redistribute it and/or
50269 * modify it under the terms of the GNU Lesser General Public
50270 * License as published by the Free Software Foundation; either
50271 * version 3 of the License, or (at your option) any later version.
50272 *
50273 * This library is distributed in the hope that it will be useful,
50274 * but WITHOUT ANY WARRANTY; without even the implied warranty of
50275 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
50276 * Lesser General Public License for more details.
50277 *
50278 * You should have received a copy of the GNU Lesser General Public
50279 * License along with this library; if not, write to the Free Software
50280 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
50281 * MA 02110-1301 USA
50282 */
50283
50284 /**
50285 * @class OverlayloaderConfig
50286 * Overlayloader Configuration File
50287 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
50288 */
50289 function OverlayloaderConfig(options) {
50290
50291 this.options = {
50292 wms_overlays : [
50293 //e.g. {name:'name', server:'url', layer:'layer'},
50294 ],
50295 };
50296 if ( typeof options != 'undefined') {
50297 $.extend(this.options, options);
50298 }
50299
50300 };
50301 /*
50302 * OverlayloaderGui.js
50303 *
50304 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
50305 *
50306 * This library is free software; you can redistribute it and/or
50307 * modify it under the terms of the GNU Lesser General Public
50308 * License as published by the Free Software Foundation; either
50309 * version 3 of the License, or (at your option) any later version.
50310 *
50311 * This library is distributed in the hope that it will be useful,
50312 * but WITHOUT ANY WARRANTY; without even the implied warranty of
50313 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
50314 * Lesser General Public License for more details.
50315 *
50316 * You should have received a copy of the GNU Lesser General Public
50317 * License along with this library; if not, write to the Free Software
50318 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
50319 * MA 02110-1301 USA
50320 */
50321
50322 /**
50323 * @class OverlayloaderGui
50324 * Overlayloader GUI Implementation
50325 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
50326 *
50327 * @param {OverlayloaderWidget} parent Overlayloader widget object
50328 * @param {HTML object} div parent div to append the Overlayloader gui
50329 * @param {JSON} options Overlayloader configuration
50330 */
50331 function OverlayloaderGui(overlayloader, div, options) {
50332
50333 this.parent = overlayloader;
50334 var overlayloaderGui = this;
50335
50336 this.overlayloaderContainer = div;
50337 this.overlayloaderContainer.style.position = 'relative';
50338
50339 this.loaderTypeSelect = document.createElement("select");
50340 div.appendChild(this.loaderTypeSelect);
50341
50342 this.loaders = document.createElement("div");
50343 div.appendChild(this.loaders);
50344
50345 this.overlayList = document.createElement("div");
50346 div.appendChild(this.overlayList);
50347
50348 $(this.loaderTypeSelect).change(function(){
50349 var activeLoader = $(this).val();
50350 $(overlayloaderGui.loaders).find("div").each(function(){
50351 if ($(this).attr("id") == activeLoader)
50352 $(this).show();
50353 else
50354 $(this).hide();
50355 });
50356 });
50357
50358 this.refreshOverlayList = function(){
50359 var overlayloaderGui = this;
50360
50361 $(overlayloaderGui.overlayList).empty();
50362 $(this.parent.overlayLoader.overlays).each(function(){
50363 var overlay = this;
50364 $(overlayloaderGui.overlayList).append(overlay.name);
50365 var link = document.createElement("a");
50366 $(link).text("(x)");
50367 link.href="";
50368
50369 $(link).click($.proxy(function(){
50370 $(overlay.layers).each(function(){
50371 this.map.removeLayer(this.layer);
50372 });
50373
50374 var overlays = overlayloaderGui.parent.overlayLoader.overlays;
50375
50376 overlays = $.grep(overlays, function(value) {
50377 return overlay != value;
50378 });
50379
50380 overlayloaderGui.parent.overlayLoader.overlays = overlays;
50381
50382 overlayloaderGui.refreshOverlayList();
50383
50384 return(false);
50385 },{overlay:overlay,overlayloaderGui:overlayloaderGui}));
50386 $(overlayloaderGui.overlayList).append(link);
50387 });
50388 };
50389 };
50390 /*
50391 * OverlayloaderWidget.js
50392 *
50393 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
50394 *
50395 * This library is free software; you can redistribute it and/or
50396 * modify it under the terms of the GNU Lesser General Public
50397 * License as published by the Free Software Foundation; either
50398 * version 3 of the License, or (at your option) any later version.
50399 *
50400 * This library is distributed in the hope that it will be useful,
50401 * but WITHOUT ANY WARRANTY; without even the implied warranty of
50402 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
50403 * Lesser General Public License for more details.
50404 *
50405 * You should have received a copy of the GNU Lesser General Public
50406 * License along with this library; if not, write to the Free Software
50407 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
50408 * MA 02110-1301 USA
50409 */
50410
50411 /**
50412 * @class OverlayloaderWidget
50413 * OverlayloaderWidget Implementation
50414 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
50415 *
50416 * @param {WidgetWrapper} core wrapper for interaction to other widgets
50417 * @param {HTML object} div parent div to append the Overlayloader widget div
50418 * @param {JSON} options user specified configuration that overwrites options in OverlayloaderConfig.js
50419 */
50420 OverlayloaderWidget = function(core, div, options) {
50421
50422 this.core = core;
50423 this.core.setWidget(this);
50424
50425 this.options = (new OverlayloaderConfig(options)).options;
50426 this.gui = new OverlayloaderGui(this, div, this.options);
50427
50428 this.attachedMapWidgets = new Array();
50429
50430 this.overlayLoader = new Overlayloader(this);
50431 }
50432
50433 OverlayloaderWidget.prototype = {
50434
50435 initWidget : function() {
50436
50437 var overlayloaderWidget = this;
50438 },
50439
50440 highlightChanged : function(objects) {
50441 if( !GeoTemConfig.highlightEvents ){
50442 return;
50443 }
50444 },
50445
50446 selectionChanged : function(selection) {
50447 if( !GeoTemConfig.selectionEvents ){
50448 return;
50449 }
50450 },
50451
50452 triggerHighlight : function(item) {
50453 },
50454
50455 tableSelection : function() {
50456 },
50457
50458 deselection : function() {
50459 },
50460
50461 filtering : function() {
50462 },
50463
50464 inverseFiltering : function() {
50465 },
50466
50467 triggerRefining : function() {
50468 },
50469
50470 reset : function() {
50471 },
50472
50473 attachMapWidget : function(widget) {
50474 this.attachedMapWidgets.push(widget);
50475 }
50476 };
50477 /*
50478 * PieChart.js
50479 *
50480 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
50481 *
50482 * This library is free software; you can redistribute it and/or
50483 * modify it under the terms of the GNU Lesser General Public
50484 * License as published by the Free Software Foundation; either
50485 * version 3 of the License, or (at your option) any later version.
50486 *
50487 * This library is distributed in the hope that it will be useful,
50488 * but WITHOUT ANY WARRANTY; without even the implied warranty of
50489 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
50490 * Lesser General Public License for more details.
50491 *
50492 * You should have received a copy of the GNU Lesser General Public
50493 * License along with this library; if not, write to the Free Software
50494 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
50495 * MA 02110-1301 USA
50496 */
50497
50498 /**
50499 * @class PieChart
50500 * Implementation for a PieChart
50501 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
50502 *
50503 * @param {HTML object} parent div to append the PieChart
50504 */
50505 function PieChart(parent, watchedDataset, watchedColumn, selectionFunction) {
50506
50507 if ((typeof selectionFunction !== "undefined") &&
50508 (typeof selectionFunction.type !== "undefined") &&
50509 (typeof selectionFunction.categories !== "undefined")){
50510 this.type = selectionFunction.type;
50511 this.categories = selectionFunction.categories;
50512 }
50513 this.pieChart = this;
50514 this.pieChartDiv;
50515 this.preHighlightObjects;
50516 this.highlightedLabel;
50517
50518 this.informationDIV;
50519 this.pieChartLabel;
50520
50521 this.parent = parent;
50522 this.options = parent.options;
50523
50524 this.watchedDatasetObject;
50525 this.watchedDataset = parseInt(watchedDataset);
50526 this.watchColumn = watchedColumn;
50527 if (typeof selectionFunction !== "undefined")
50528 this.selectionFunction = selectionFunction;
50529 else
50530 //default selectionFunction returns value (creates "distinct" piechart)
50531 this.selectionFunction = function(columnData){return columnData;};
50532 }
50533
50534 PieChart.prototype = {
50535
50536 remove : function() {
50537 for (var i = 0; i < this.parent.pieCharts.length; i++){
50538 if (this.parent.pieCharts[i] === this)
50539 this.parent.pieCharts[i] = null;
50540 }
50541 $(this.pieChartDiv).remove();
50542 $(this.informationDIV).remove();
50543 this.parent.redrawPieCharts();
50544 },
50545
50546 refreshLabel : function(){
50547 $(this.pieChartLabel).empty();
50548 $(this.pieChartLabel).append(this.watchedDatasetObject.label + " - " + this.watchColumn);
50549
50550 var c = GeoTemConfig.getColor(this.watchedDataset);
50551 $(this.pieChartLabel).css("color","rgb("+c.r1+","+c.g1+","+c.b1+")");
50552 },
50553
50554 initialize : function() {
50555 var pieChart = this;
50556
50557 if (typeof this.pieChartDiv === "undefined"){
50558 this.informationDIV = document.createElement("div");
50559 this.pieChartLabel = $("<span></span>");
50560 $(this.informationDIV).append(this.pieChartLabel);
50561 this.refreshLabel();
50562
50563 var removeButton = document.createElement("button");
50564 $(this.informationDIV).append(removeButton);
50565 $(removeButton).text("remove");
50566 $(removeButton).click(function(){
50567 pieChart.remove();
50568 });
50569
50570 //only allow editing if it is a "manually" created piechart
50571 //automatic (with a selection function) ones, can lead to numerous problems,
50572 //e.g. too many categories or numeral categories threated as text ones
50573 if ((typeof pieChart.type !== "undefined")&&
50574 (typeof pieChart.categories !== "undefined")){
50575 var editButton = document.createElement("button");
50576 $(this.informationDIV).append(editButton);
50577 $(editButton).text("edit");
50578 $(editButton).click(function(){
50579 var chooser = new PieChartCategoryChooser(
50580 pieChart.parent,
50581 pieChart.parent.options,
50582 pieChart.watchedDataset,
50583 pieChart.watchColumn,
50584 pieChart.type,
50585 pieChart.categories);
50586 });
50587
50588 //add save button
50589 if (pieChart.options.allowLocalStorage){
50590 var saveButton = document.createElement("button");
50591 $(this.informationDIV).append(saveButton);
50592 $(saveButton).text("save");
50593 $(saveButton).click(function(){
50594 $( "<div>" +
50595 "pie chart name : " +
50596 "<input type='text' size=30 id='saveName' class='ui-widget-content ui-corner-all'></input>" +
50597 "</div>").dialog({
50598 width:'auto',
50599 buttons: [
50600 {
50601 text: "save",
50602 click: function(){
50603 var saveName = $("#saveName").val();
50604 var saveObject = new Object();
50605 saveObject.type = pieChart.type;
50606 saveObject.categories = pieChart.categories;
50607 saveObject.columnName = pieChart.watchColumn;
50608 //save to LocalStorage
50609 $.remember({
50610 name:pieChart.options.localStoragePrefix+saveName,
50611 value:saveObject,
50612 json:true
50613 });
50614 $(this).dialog( "close" );
50615 }
50616 }
50617 ]
50618 });
50619
50620 //set value to default (column name)
50621 $("#saveName").val(pieChart.watchColumn);
50622 //TODO: z-index has to be set, as the "tool-bars" of map (.ddbToolbar in style.css)
50623 //also have a z-index of 10000. z-index should be removed from all elements.
50624 $(".ui-dialog").css("z-index",10005);
50625 });
50626 }
50627 }
50628
50629 $(this.parent.gui.pieChartsDiv).append(this.informationDIV);
50630 this.pieChartDiv = document.createElement("div");
50631 $(this.parent.gui.pieChartsDiv).append(this.pieChartDiv);
50632
50633 $(this.pieChartDiv).unbind();
50634 $(this.pieChartDiv).bind("plothover", function (event, pos, item) {
50635 var highlightedLabel;
50636
50637 if (item) {
50638 highlightedLabel = item.series.label;
50639 }
50640 if (highlightedLabel !== pieChart.highlightedLabel){
50641 pieChart.highlightedLabel = highlightedLabel;
50642 pieChart.triggerHighlight(highlightedLabel);
50643 }
50644 });
50645
50646 $(this.pieChartDiv).bind("plotclick", function (event, pos, item) {
50647 if (item) {
50648 //item.series.label contains the column element
50649 pieChart.triggerSelection(item.series.label);
50650 } else {
50651 pieChart.triggerSelection();
50652 }
50653 });
50654 }
50655 },
50656
50657 //check if dataset is still there
50658 checkForDataSet : function() {
50659 var datasets = this.parent.datasets;
50660 if ((typeof datasets !== "undefined") && (typeof this.watchedDatasetObject !== "undefined")){
50661 //check if our data went missing
50662 for (var i = 0; i < datasets.length; i++){
50663 if (datasets[i] === this.watchedDatasetObject){
50664 //if dataset "before" this one was removed, the index changes
50665 if (this.watchedDataset !== i){
50666 //change color to the new one (changes with index!)
50667 this.watchedDataset = i;
50668 this.refreshLabel();
50669 }
50670 return true;
50671 }
50672 }
50673 }
50674 return false;
50675 },
50676
50677 initPieChart : function(dataSets) {
50678 // get dataset object (could not be there on startup, e.g. piechart defined before load completes)
50679 if (typeof this.watchedDatasetObject === "undefined")
50680 this.watchedDatasetObject = this.parent.datasets[this.watchedDataset];
50681
50682 this.initialize();
50683
50684 // if our dataset went missing, remove this piechart
50685 if (!this.checkForDataSet()){
50686 this.remove();
50687 return;
50688 }
50689
50690 var objects = [];
50691 for (var i = 0; i < dataSets.length; i++)
50692 objects.push([]);
50693 objects[this.watchedDataset] = dataSets[this.watchedDataset].objects;
50694
50695 this.preHighlightObjects = objects;
50696 this.redrawPieChart(objects);
50697 },
50698
50699 redrawPieChart : function(objects) {
50700
50701 if (typeof objects === "undefined")
50702 objects = this.preHighlightObjects;
50703
50704 if (this.checkForDataSet(objects)){
50705 var pieChart = this;
50706 if (objects[this.watchedDataset].length === 0)
50707 objects = this.preHighlightObjects;
50708
50709 var calculateSlices = function(dataObjects){
50710 var chartDataCounter = new Object;
50711
50712 $(dataObjects).each(function(){
50713 var columnData = pieChart.parent.getElementData(this, pieChart.watchColumn, pieChart.selectionFunction);
50714
50715 //disregard empty cells
50716 if ( (typeof columnData === "undefined") || (columnData == "") )
50717 return;
50718
50719 var weight = this.weight;
50720
50721 if (typeof chartDataCounter[columnData] === "undefined")
50722 chartDataCounter[columnData] = weight;
50723 else
50724 chartDataCounter[columnData] += weight;
50725 });
50726
50727 var chartData = [];
50728 $.each(chartDataCounter, function(name,val){
50729 //get rgb-color (24bit = 6 hex digits) from hash
50730 var color = '#'+hex_md5(name).substr(0,6);
50731 chartData.push({label:name,data:val,color:color});
50732 });
50733
50734 //sort by count (occurances of category)
50735 var sortByVal = function(a,b){
50736 return (b.data-a.data);
50737 };
50738 chartData.sort(sortByVal);
50739
50740 return chartData;
50741 };
50742
50743 var chartData = calculateSlices(objects[this.watchedDataset]);
50744
50745 if (chartData.length>0){
50746 $(this.pieChartDiv).empty();
50747
50748 //calculate height (flot NEEDS a height)
50749 var parentHeight = $(this.parent.gui.pieChartsDiv).outerHeight(true) - $(this.parent.gui.columnSelectorDiv).outerHeight(true);
50750 var pieChartCount = 0;
50751 $(this.parent.pieCharts).each(function(){
50752 if (this instanceof PieChart)
50753 pieChartCount++;
50754 });
50755 var height = (parentHeight/pieChartCount) - $(this.informationDIV).outerHeight(true);
50756 if (pieChart.options.restrictPieChartSize !== false)
50757 height = Math.min(height, $(window).height() * pieChart.options.restrictPieChartSize);
50758 $(this.pieChartDiv).height(height);
50759
50760 $.plot($(this.pieChartDiv), chartData,
50761 {
50762 series: {
50763 // Make this a pie chart.
50764 pie: {
50765 show:true
50766 }
50767 },
50768 legend: { show:true, position: 'se' },
50769 grid: {
50770 hoverable: true,
50771 clickable: true
50772 },
50773 tooltip: true,
50774 tooltipOpts: {
50775 content: "%s %p.1%"
50776 }
50777 }
50778 );
50779 }
50780 }
50781 },
50782
50783 triggerHighlight : function(columnElement) {
50784 var highlightedObjects = [];
50785 for (var i = 0; i < GeoTemConfig.datasets.length; i++)
50786 highlightedObjects.push([]);
50787
50788 if (this.watchedDataset >= 0)
50789 highlightedObjects[this.watchedDataset] =
50790 this.parent.getElementsByValue(columnElement, this.watchedDataset, this.watchColumn, this.selectionFunction);
50791 else
50792 highlightedObjects[this.watchedDataset] = [];
50793
50794 this.parent.core.triggerHighlight(highlightedObjects);
50795
50796 var pieChart = this;
50797 $(this.parent.pieCharts).each(function(){
50798 if (this instanceof PieChart && (this !== pieChart)){
50799 if (this.watchedDataset === pieChart.watchedDataset)
50800 this.redrawPieChart(highlightedObjects);
50801 }
50802 });
50803 },
50804
50805 triggerSelection : function(columnElement) {
50806 var selectedObjects = [];
50807 for (var i = 0; i < GeoTemConfig.datasets.length; i++)
50808 selectedObjects.push([]);
50809
50810 var selection;
50811 if (typeof columnElement !== "undefined"){
50812 selectedObjects[this.watchedDataset] =
50813 this.parent.getElementsByValue(columnElement, this.watchedDataset, this.watchColumn, this.selectionFunction);
50814 selection = new Selection(selectedObjects, this);
50815 } else {
50816 selection = new Selection(selectedObjects);
50817 }
50818
50819 this.parent.core.triggerSelection(selection);
50820
50821 if (!selection.valid()){
50822 selection.loadAllObjects();
50823 //"undo" selection (click next to piechart)
50824 //so also redraw this dataset
50825 this.preHighlightObjects = selection.objects;
50826 this.redrawPieChart(selection.objects);
50827 }
50828
50829 var pieChart = this;
50830 $(this.parent.pieCharts).each(function(){
50831 if (this instanceof PieChart && (this !== pieChart)){
50832 if (this.watchedDataset === pieChart.watchedDataset){
50833 this.preHighlightObjects = selection.objects;
50834 this.redrawPieChart(selection.objects);
50835 }
50836 }
50837 });
50838 },
50839
50840 deselection : function() {
50841 },
50842
50843 filtering : function() {
50844 },
50845
50846 inverseFiltering : function() {
50847 },
50848
50849 triggerRefining : function() {
50850 },
50851
50852 reset : function() {
50853 },
50854
50855 show : function() {
50856 },
50857
50858 hide : function() {
50859 }
50860 };
50861 /*
50862 * PieChartCategoryChooser.js
50863 *
50864 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
50865 *
50866 * This library is free software; you can redistribute it and/or
50867 * modify it under the terms of the GNU Lesser General Public
50868 * License as published by the Free Software Foundation; either
50869 * version 3 of the License, or (at your option) any later version.
50870 *
50871 * This library is distributed in the hope that it will be useful,
50872 * but WITHOUT ANY WARRANTY; without even the implied warranty of
50873 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
50874 * Lesser General Public License for more details.
50875 *
50876 * You should have received a copy of the GNU Lesser General Public
50877 * License along with this library; if not, write to the Free Software
50878 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
50879 * MA 02110-1301 USA
50880 */
50881
50882 /**
50883 * @class PieChartCategoryChooser
50884 * PieChart dialog for category creation
50885 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
50886 *
50887 * @param {PieChartWidget} parent PieChart widget object
50888 * @param {JSON} options PieChart configuration
50889 * @param {number} datasetIndex index of the dataset
50890 * @param {String} columnName name of the column
50891 */
50892
50893 function PieChartCategoryChooser(pieChart, options, datasetIndex, columnName, type, categories) {
50894
50895 var pieChartCategoryChooser = this;
50896
50897 this.parent = pieChart;
50898 this.options = options;
50899 this.datasetIndex = parseInt(datasetIndex);
50900 this.columnName = columnName;
50901 this.chartData;
50902
50903 this.dialog = $("<div></div>");
50904 this.dialog.html("").dialog({modal: true}).dialog('open');
50905
50906 //to asure that the dialog is above (z-index of) the toolbars
50907 $(".ui-front").css("z-index","10001");
50908
50909 var allNumeric = this.loadValues(datasetIndex, columnName);
50910
50911 if (typeof allNumeric === "undefined")
50912 return;
50913 if (allNumeric === true){
50914 this.createNumeralBasedChooser(this.chartData, categories);
50915 } else {
50916 this.createTextBasedChooser(this.chartData, categories);
50917 }
50918 };
50919
50920 PieChartCategoryChooser.prototype = {
50921
50922 loadValues : function(datasetIndex, columnName){
50923 var pieChartCategoryChooser = this;
50924
50925 var allNumeric = true;
50926 pieChartCategoryChooser.chartData = [];
50927 var chartData = pieChartCategoryChooser.chartData;
50928 $(GeoTemConfig.datasets[datasetIndex].objects).each(function(){
50929 var columnData =
50930 pieChartCategoryChooser.parent.getElementData(this, columnName);
50931
50932 if (isNaN(parseFloat(columnData)))
50933 allNumeric = false;
50934
50935 if ($.inArray(columnData, chartData) == -1)
50936 chartData.push(columnData);
50937 });
50938
50939 if (chartData.length === 0)
50940 return;
50941 else
50942 return allNumeric;
50943 },
50944
50945 createTextBasedChooser : function(chartData, categories){
50946 var pieChartCategoryChooser = this;
50947
50948 var addCategory = function(name,elements){
50949 var newCategoryContainer = document.createElement("fieldset");
50950 var newCategoryLegend = document.createElement("legend");
50951 var newCategoryName = document.createElement("input");
50952 $(newCategoryName).width("80%");
50953 newCategoryName.type = "text";
50954 newCategoryName.value = name;
50955 var newCategoryRemove = document.createElement("button");
50956 $(newCategoryRemove).text("X");
50957 $(newCategoryRemove).click(function(){
50958 $(newCategoryContainer).find("li").each(function(){
50959 //move all elements to unselected list
50960 //("unselected" is defined below)
50961 //prepend so the items appear on top
50962 $(this).prependTo(unselected);
50963 });
50964 //and remove this category
50965 $(newCategoryContainer).remove();
50966 });
50967 $(newCategoryLegend).append(newCategoryName);
50968 $(newCategoryLegend).append(newCategoryRemove);
50969 $(newCategoryContainer).append(newCategoryLegend);
50970 $(newCategoryContainer).width("200px");
50971 $(newCategoryContainer).css("float","left");
50972 var newCategory = document.createElement("ul");
50973 $(newCategory).addClass("connectedSortable");
50974 $(newCategory).css("background", "#eee");
50975 newCategoryContainer.appendChild(newCategory);
50976 $(newCategory).append("<br/>");
50977 cell.appendChild(newCategoryContainer);
50978 //if there are pre-selected elements (e.g. "edit")
50979 //add them and remove them from unselected value list
50980 if (typeof elements !== "undefined"){
50981 $(elements).each(function(){
50982 var value = this;
50983 //add to category
50984 $(newCategory).append("<li>"+value+"</li>");
50985 //remove from unselected list
50986 $(unselected).find("li").filter(function(){
50987 return ($(this).text() === ""+value);
50988 }).remove();
50989 });
50990 }
50991
50992 $( ".connectedSortable" ).sortable({
50993 connectWith: ".connectedSortable"
50994 }).disableSelection();
50995 };
50996
50997 var table = document.createElement("table");
50998 var row = document.createElement("tr");
50999 table.appendChild(row);
51000 var cell = document.createElement("td");
51001 row.appendChild(cell);
51002 cell = document.createElement("td");
51003 row.appendChild(cell);
51004 var addCategoryButton = document.createElement("button");
51005 $(addCategoryButton).text("add new category");
51006 cell.appendChild(addCategoryButton);
51007 var applyCategoryButton = document.createElement("button");
51008 $(applyCategoryButton).text("apply");
51009 cell.appendChild(applyCategoryButton);
51010
51011 row = document.createElement("tr");
51012 table.appendChild(row);
51013 cell = document.createElement("td");
51014 row.appendChild(cell);
51015 var unselected = document.createElement("ul");
51016 $(unselected).addClass("connectedSortable");
51017 cell.appendChild(unselected);
51018 cell = document.createElement("td");
51019 $(cell).attr("valign","top");
51020 $(cell).width("100%");
51021 row.appendChild(cell);
51022
51023 this.dialog.append(table);
51024
51025 $( ".connectedSortable" ).sortable({
51026 connectWith: ".connectedSortable"
51027 }).disableSelection();
51028
51029 $(chartData).each(function(){
51030 $(unselected).append("<li class='ui-state-default'>"+this+"</li>");
51031 });
51032
51033 if (typeof categories !== "undefined"){
51034 $(categories).each(function(){
51035 var category = this;
51036 addCategory(category.label, category.values);
51037 });
51038 }
51039
51040 $(addCategoryButton).click(function(){addCategory();});
51041
51042 $(applyCategoryButton).click(function(){
51043 var categories = [];
51044 $(cell).children().each(function(){
51045 var label = $(this).find("legend > input").val();
51046 var values = [];
51047 $(this).find("li").each(function(){
51048 values.push($(this).text());
51049 });
51050
51051 categories.push({label:label,values:values});
51052 });
51053
51054 var values = [];
51055 $(unselected).find("li").each(function(){
51056 values.push($(this).text());
51057 });
51058
51059 categories.push({label:"other",values:values});
51060
51061 //create pie chart
51062 pieChartCategoryChooser.parent.addCategorizedPieChart(
51063 pieChartCategoryChooser.datasetIndex, pieChartCategoryChooser.columnName,
51064 "text", categories);
51065
51066 //close dialog
51067 $(pieChartCategoryChooser.dialog).dialog("close");
51068 });
51069
51070 //set dialog size
51071 var wWidth = $(window).width();
51072 var dWidth = wWidth * 0.9;
51073 var wHeight = $(window).height();
51074 var dHeight = wHeight * 0.9;
51075 $(this.dialog).dialog("option", "width", dWidth);
51076 $(this.dialog).dialog("option", "height", dHeight);
51077 },
51078
51079 createNumeralBasedChooser : function(chartData, existingCategories){
51080 var numericChartData = [];
51081 for (var i = 0; i < chartData.length; i++){
51082 numericChartData.push(parseFloat(chartData[i]));
51083 }
51084 chartData = numericChartData;
51085 chartData = chartData.sort(function sortNumber(a,b){
51086 return a - b;
51087 });
51088
51089 var min = chartData[0];
51090 var max = chartData[chartData.length-1];
51091 //find minimum step width that is needed
51092 //(otherwise there could be steps that contain more than one element)
51093 var minStep=max-min;
51094 for (var i = 1; i < chartData.length; i++){
51095 var thisStep = chartData[i]-chartData[i-1];
51096 if ((thisStep) < minStep)
51097 minStep = thisStep;
51098 }
51099
51100 var pieChartCategoryChooser = this;
51101
51102 var addCategoryButton = document.createElement("button");
51103 $(addCategoryButton).text("add new category");
51104 this.dialog.append(addCategoryButton);
51105 var applyCategoryButton = document.createElement("button");
51106 $(applyCategoryButton).text("apply");
51107 this.dialog.append(applyCategoryButton);
51108 this.dialog.append("tip: use left/right arrow key for finer adjustment");
51109
51110 var table = document.createElement("table");
51111 row = document.createElement("tr");
51112 table.appendChild(row);
51113 cell = document.createElement("td");
51114 row.appendChild(cell);
51115 cell.colSpan = 2;
51116 var slider = document.createElement("div");
51117 cell.appendChild(slider);
51118 var handles = [];
51119 var categories = [];
51120
51121 row = document.createElement("tr");
51122 table.appendChild(row);
51123 cell = document.createElement("td");
51124 $(cell).attr("valign","top");
51125 row.appendChild(cell);
51126 var unselected = document.createElement("ul");
51127 cell.appendChild(unselected);
51128
51129 cell = document.createElement("td");
51130 $(cell).attr("valign","top");
51131 $(cell).width("100%");
51132 row.appendChild(cell);
51133
51134 this.dialog.append(table);
51135
51136 $(chartData).each(function(){
51137 $(unselected).append("<li class='ui-state-default'>"+this+"</li>");
51138 });
51139
51140 var addCategory = function(boundary){
51141 //check if another handle can be added
51142 if ((handles.length>0) && (handles[handles.length-1] === max))
51143 return false;
51144 //destroy old slider (has to be recreated to show the new handle)
51145 if (handles.length>0)
51146 $(slider).slider("destroy");
51147
51148 if (typeof boundary === "undefined")
51149 boundary = max;
51150 handles.push(boundary);
51151
51152 $(slider).slider({
51153 min:min,
51154 max:max,
51155 step:minStep,
51156 values: handles
51157 });
51158
51159 var placeValues = function(){
51160 $(unselected).find("li").remove();
51161 $(cell).children().find("li").remove();
51162
51163 var j = 0, i = 0;
51164 for (; i < chartData.length; i++){
51165 if (chartData[i]>handles[j])
51166 j++;
51167 if (j == handles.length)
51168 break;
51169 $(categories[j]).append("<li class='ui-state-default'>"+chartData[i]+"</li>");
51170 }
51171 for (; i < chartData.length; i++){
51172 $(unselected).append("<li class='ui-state-default'>"+chartData[i]+"</li>");
51173 }
51174 };
51175
51176 $(slider).on( "slide", function( event, ui ){
51177 var last = min;
51178 //check whether handle values are increasing
51179 for(var i = 0; i < ui.values.length; i++){
51180 if (ui.values[i]<last)
51181 return false;
51182 last = ui.values[i];
51183 }
51184 handles = ui.values;
51185 for(var i = 0; i < handles.length; i++){
51186 $(categories[i]).parent().find("legend").text("<="+handles[i]);
51187 }
51188
51189 placeValues();
51190 });
51191
51192 var newCategoryContainer = document.createElement("fieldset");
51193 $(newCategoryContainer).append("<legend><="+boundary+"</legend>");
51194 $(newCategoryContainer).width("188px");
51195 $(newCategoryContainer).css("float","left");
51196 var newCategory = document.createElement("ul");
51197 $(newCategory).addClass("connectedSortable");
51198 $(newCategory).css("background", "#eee");
51199 newCategoryContainer.appendChild(newCategory);
51200 cell.appendChild(newCategoryContainer);
51201 categories.push(newCategory);
51202
51203 placeValues();
51204 };
51205
51206 $(addCategoryButton).click(function(){addCategory();});
51207
51208 if (typeof existingCategories !== "undefined"){
51209 $(existingCategories).each(function(){
51210 var boundary = this;
51211 addCategory(boundary);
51212 });
51213 }
51214
51215 $(applyCategoryButton).click(function(){
51216 var categorieBoundaries = handles;
51217
51218 //create pie chart
51219 pieChartCategoryChooser.parent.addCategorizedPieChart(
51220 pieChartCategoryChooser.datasetIndex, pieChartCategoryChooser.columnName,
51221 "numeral", categorieBoundaries);
51222
51223 //close dialog
51224 $(pieChartCategoryChooser.dialog).dialog("close");
51225 });
51226
51227 //set dialog size
51228 var wWidth = $(window).width();
51229 var dWidth = wWidth * 0.9;
51230 var wHeight = $(window).height();
51231 var dHeight = wHeight * 0.9;
51232 $(this.dialog).dialog("option", "width", dWidth);
51233 $(this.dialog).dialog("option", "height", dHeight);
51234 }
51235 };
51236 /*
51237 * PieChartConfig.js
51238 *
51239 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
51240 *
51241 * This library is free software; you can redistribute it and/or
51242 * modify it under the terms of the GNU Lesser General Public
51243 * License as published by the Free Software Foundation; either
51244 * version 3 of the License, or (at your option) any later version.
51245 *
51246 * This library is distributed in the hope that it will be useful,
51247 * but WITHOUT ANY WARRANTY; without even the implied warranty of
51248 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
51249 * Lesser General Public License for more details.
51250 *
51251 * You should have received a copy of the GNU Lesser General Public
51252 * License along with this library; if not, write to the Free Software
51253 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
51254 * MA 02110-1301 USA
51255 */
51256
51257 /**
51258 * @class PieChartConfig
51259 * PieChart Configuration File
51260 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
51261 */
51262 function PieChartConfig(options) {
51263
51264 this.options = {
51265 restrictPieChartSize : 0.25, // restrict size to percantage of window size (false for no restriction)
51266 localStoragePrefix : "GeoBrowser_PieChart_", // prefix for value name in LocalStorage
51267 allowLocalStorage : true, //whether LocalStorage save and load should be allowed (and buttons shown)
51268 };
51269 if ( typeof options != 'undefined') {
51270 $.extend(this.options, options);
51271 }
51272
51273 };
51274 /*
51275 * PieChartGui.js
51276 *
51277 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
51278 *
51279 * This library is free software; you can redistribute it and/or
51280 * modify it under the terms of the GNU Lesser General Public
51281 * License as published by the Free Software Foundation; either
51282 * version 3 of the License, or (at your option) any later version.
51283 *
51284 * This library is distributed in the hope that it will be useful,
51285 * but WITHOUT ANY WARRANTY; without even the implied warranty of
51286 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
51287 * Lesser General Public License for more details.
51288 *
51289 * You should have received a copy of the GNU Lesser General Public
51290 * License along with this library; if not, write to the Free Software
51291 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
51292 * MA 02110-1301 USA
51293 */
51294
51295 /**
51296 * @class PieChartGui
51297 * PieChart GUI Implementation
51298 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
51299 *
51300 * @param {PieChartWidget} parent PieChart widget object
51301 * @param {HTML object} div parent div to append the PieChart gui
51302 * @param {JSON} options PieChart configuration
51303 */
51304 function PieChartGui(pieChart, div, options) {
51305
51306 this.parent = pieChart;
51307 this.options = options;
51308 var pieChartGui = this;
51309
51310 this.pieChartContainer = div;
51311 this.pieChartContainer.style.position = 'relative';
51312
51313 this.columnSelectorDiv = document.createElement("div");
51314 div.appendChild(this.columnSelectorDiv);
51315 this.datasetSelect = document.createElement("select");
51316 $(this.datasetSelect).change(function(event){
51317 if (typeof pieChartGui.parent.datasets !== "undefined"){
51318 var dataset = pieChartGui.parent.datasets[$(pieChartGui.datasetSelect).val()];
51319 if (dataset.objects.length > 0){
51320 //This implies that the dataObjects are homogenous
51321 var firstObject = dataset.objects[0];
51322 var firstTableContent = firstObject.tableContent;
51323 $(pieChartGui.columnSelect).empty();
51324
51325 $(pieChartGui.columnSelect).append("<optgroup label='saved'>");
51326
51327 for(var key in localStorage){
51328 //TODO: this is a somewhat bad idea, as it is used in multiple widgets.
51329 //A global GeoTemCo option "prefix" could be better. But still..
51330 var prefix = pieChartGui.options.localStoragePrefix;
51331 if (key.startsWith(prefix)){
51332 var saveObject = $.remember({name:key,json:true});
51333 var label = key.substring(prefix.length);
51334 //small safety-check: if the column is not part of this dataset, don't show it
51335 if (typeof firstTableContent[saveObject.columnName] !== "undefined")
51336 $(pieChartGui.columnSelect).append("<option isSaved=1 value='"+label+"'>"+decodeURIComponent(label)+"</option>");
51337 }
51338 }
51339 $(pieChartGui.columnSelect).append("</optgroup>");
51340
51341 $(pieChartGui.columnSelect).append("<optgroup label='new'>");
51342 for (var attribute in firstTableContent) {
51343 $(pieChartGui.columnSelect).append("<option value='"+attribute+"'>"+attribute+"</option>");
51344 }
51345 if (firstObject.isTemporal)
51346 $(pieChartGui.columnSelect).append("<option value='dates[0].date'>date</option>");
51347 if (typeof firstObject.locations[0] !== "undefined"){
51348 $(pieChartGui.columnSelect).append("<option value='locations[0].latitude'>lat</option>");
51349 $(pieChartGui.columnSelect).append("<option value='locations[0].longitude'>lon</option>");
51350 }
51351 $(pieChartGui.columnSelect).append("</optgroup>");
51352 }
51353 }
51354 });
51355 this.columnSelectorDiv.appendChild(this.datasetSelect);
51356 this.columnSelect = document.createElement("select");
51357 this.columnSelectorDiv.appendChild(this.columnSelect);
51358 this.buttonNewPieChart = document.createElement("button");
51359 $(this.buttonNewPieChart).text("add");
51360 this.columnSelectorDiv.appendChild(this.buttonNewPieChart);
51361 $(this.buttonNewPieChart).click(function(){
51362 //check if this is a local saved pie chart
51363 var isSaved=$(pieChartGui.columnSelect).find("option:selected").first().attr("isSaved");
51364 if ((typeof isSaved === "undefined") || (isSaved!=1)){
51365 //create new pie chart (where each value is its own category)
51366 pieChartGui.parent.addPieChart($(pieChartGui.datasetSelect).val(), $(pieChartGui.columnSelect).val());
51367 } else {
51368 //is local saved, get value
51369 var name = pieChartGui.options.localStoragePrefix + $(pieChartGui.columnSelect).val();
51370 var saveObject = $.remember({name:name,json:true});
51371 if ((typeof saveObject !== "undefined") && (saveObject != null)){
51372 var categories = saveObject.categories;
51373 var type = saveObject.type;
51374 var columnName = saveObject.columnName;
51375
51376 //create pie chart
51377 pieChartGui.parent.addCategorizedPieChart(
51378 $(pieChartGui.datasetSelect).val(), columnName,
51379 type, categories);
51380 }
51381 }
51382 });
51383 this.buttonPieChartCategoryChooser = document.createElement("button");
51384 $(this.buttonPieChartCategoryChooser).text("categorize");
51385 this.columnSelectorDiv.appendChild(this.buttonPieChartCategoryChooser);
51386 $(this.buttonPieChartCategoryChooser).click(function(){
51387 //check if this is a local saved pie chart
51388 var isSaved=$(pieChartGui.columnSelect).find("option:selected").first().attr("isSaved");
51389 if ((typeof isSaved === "undefined") || (isSaved!=1)){
51390 var chooser = new PieChartCategoryChooser( pieChartGui.parent,
51391 pieChartGui.options,
51392 $(pieChartGui.datasetSelect).val(),
51393 $(pieChartGui.columnSelect).val() );
51394 } else {
51395 alert("Saved datasets can not be categorized again. Try loading and editing instead.");
51396 }
51397 });
51398
51399 this.refreshColumnSelector();
51400
51401 this.pieChartsDiv = document.createElement("div");
51402 this.pieChartsDiv.id = "pieChartsDivID";
51403 div.appendChild(this.pieChartsDiv);
51404 $(this.pieChartsDiv).height("100%");
51405 };
51406
51407 PieChartGui.prototype = {
51408
51409 refreshColumnSelector : function(){
51410 $(this.datasetSelect).empty();
51411 $(this.columnSelect).empty();
51412
51413 if ( (typeof this.parent.datasets !== "undefined") && (this.parent.datasets.length > 0)) {
51414 var index = 0;
51415 var pieChartGui = this;
51416 $(this.parent.datasets).each(function(){
51417 $(pieChartGui.datasetSelect).append("<option value="+index+">"+this.label+"</option>");
51418 index++;
51419 });
51420
51421 $(pieChartGui.datasetSelect).change();
51422 }
51423 }
51424 };
51425 /*
51426 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
51427 * Digest Algorithm, as defined in RFC 1321.
51428 * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
51429 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
51430 * Distributed under the BSD License
51431 * See http://pajhome.org.uk/crypt/md5 for more info.
51432 */
51433
51434 /*
51435 * Configurable variables. You may need to tweak these to be compatible with
51436 * the server-side, but the defaults work in most cases.
51437 */
51438 var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
51439 var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
51440
51441 /*
51442 * These are the functions you'll usually want to call
51443 * They take string arguments and return either hex or base-64 encoded strings
51444 */
51445 function hex_md5(s) { return rstr2hex(rstr_md5(str2rstr_utf8(s))); }
51446 function b64_md5(s) { return rstr2b64(rstr_md5(str2rstr_utf8(s))); }
51447 function any_md5(s, e) { return rstr2any(rstr_md5(str2rstr_utf8(s)), e); }
51448 function hex_hmac_md5(k, d)
51449 { return rstr2hex(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); }
51450 function b64_hmac_md5(k, d)
51451 { return rstr2b64(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); }
51452 function any_hmac_md5(k, d, e)
51453 { return rstr2any(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)), e); }
51454
51455 /*
51456 * Perform a simple self-test to see if the VM is working
51457 */
51458 function md5_vm_test()
51459 {
51460 return hex_md5("abc").toLowerCase() == "900150983cd24fb0d6963f7d28e17f72";
51461 }
51462
51463 /*
51464 * Calculate the MD5 of a raw string
51465 */
51466 function rstr_md5(s)
51467 {
51468 return binl2rstr(binl_md5(rstr2binl(s), s.length * 8));
51469 }
51470
51471 /*
51472 * Calculate the HMAC-MD5, of a key and some data (raw strings)
51473 */
51474 function rstr_hmac_md5(key, data)
51475 {
51476 var bkey = rstr2binl(key);
51477 if(bkey.length > 16) bkey = binl_md5(bkey, key.length * 8);
51478
51479 var ipad = Array(16), opad = Array(16);
51480 for(var i = 0; i < 16; i++)
51481 {
51482 ipad[i] = bkey[i] ^ 0x36363636;
51483 opad[i] = bkey[i] ^ 0x5C5C5C5C;
51484 }
51485
51486 var hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
51487 return binl2rstr(binl_md5(opad.concat(hash), 512 + 128));
51488 }
51489
51490 /*
51491 * Convert a raw string to a hex string
51492 */
51493 function rstr2hex(input)
51494 {
51495 try { hexcase } catch(e) { hexcase=0; }
51496 var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
51497 var output = "";
51498 var x;
51499 for(var i = 0; i < input.length; i++)
51500 {
51501 x = input.charCodeAt(i);
51502 output += hex_tab.charAt((x >>> 4) & 0x0F)
51503 + hex_tab.charAt( x & 0x0F);
51504 }
51505 return output;
51506 }
51507
51508 /*
51509 * Convert a raw string to a base-64 string
51510 */
51511 function rstr2b64(input)
51512 {
51513 try { b64pad } catch(e) { b64pad=''; }
51514 var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
51515 var output = "";
51516 var len = input.length;
51517 for(var i = 0; i < len; i += 3)
51518 {
51519 var triplet = (input.charCodeAt(i) << 16)
51520 | (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0)
51521 | (i + 2 < len ? input.charCodeAt(i+2) : 0);
51522 for(var j = 0; j < 4; j++)
51523 {
51524 if(i * 8 + j * 6 > input.length * 8) output += b64pad;
51525 else output += tab.charAt((triplet >>> 6*(3-j)) & 0x3F);
51526 }
51527 }
51528 return output;
51529 }
51530
51531 /*
51532 * Convert a raw string to an arbitrary string encoding
51533 */
51534 function rstr2any(input, encoding)
51535 {
51536 var divisor = encoding.length;
51537 var i, j, q, x, quotient;
51538
51539 /* Convert to an array of 16-bit big-endian values, forming the dividend */
51540 var dividend = Array(Math.ceil(input.length / 2));
51541 for(i = 0; i < dividend.length; i++)
51542 {
51543 dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
51544 }
51545
51546 /*
51547 * Repeatedly perform a long division. The binary array forms the dividend,
51548 * the length of the encoding is the divisor. Once computed, the quotient
51549 * forms the dividend for the next step. All remainders are stored for later
51550 * use.
51551 */
51552 var full_length = Math.ceil(input.length * 8 /
51553 (Math.log(encoding.length) / Math.log(2)));
51554 var remainders = Array(full_length);
51555 for(j = 0; j < full_length; j++)
51556 {
51557 quotient = Array();
51558 x = 0;
51559 for(i = 0; i < dividend.length; i++)
51560 {
51561 x = (x << 16) + dividend[i];
51562 q = Math.floor(x / divisor);
51563 x -= q * divisor;
51564 if(quotient.length > 0 || q > 0)
51565 quotient[quotient.length] = q;
51566 }
51567 remainders[j] = x;
51568 dividend = quotient;
51569 }
51570
51571 /* Convert the remainders to the output string */
51572 var output = "";
51573 for(i = remainders.length - 1; i >= 0; i--)
51574 output += encoding.charAt(remainders[i]);
51575
51576 return output;
51577 }
51578
51579 /*
51580 * Encode a string as utf-8.
51581 * For efficiency, this assumes the input is valid utf-16.
51582 */
51583 function str2rstr_utf8(input)
51584 {
51585 var output = "";
51586 var i = -1;
51587 var x, y;
51588
51589 while(++i < input.length)
51590 {
51591 /* Decode utf-16 surrogate pairs */
51592 x = input.charCodeAt(i);
51593 y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
51594 if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF)
51595 {
51596 x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
51597 i++;
51598 }
51599
51600 /* Encode output as utf-8 */
51601 if(x <= 0x7F)
51602 output += String.fromCharCode(x);
51603 else if(x <= 0x7FF)
51604 output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F),
51605 0x80 | ( x & 0x3F));
51606 else if(x <= 0xFFFF)
51607 output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
51608 0x80 | ((x >>> 6 ) & 0x3F),
51609 0x80 | ( x & 0x3F));
51610 else if(x <= 0x1FFFFF)
51611 output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
51612 0x80 | ((x >>> 12) & 0x3F),
51613 0x80 | ((x >>> 6 ) & 0x3F),
51614 0x80 | ( x & 0x3F));
51615 }
51616 return output;
51617 }
51618
51619 /*
51620 * Encode a string as utf-16
51621 */
51622 function str2rstr_utf16le(input)
51623 {
51624 var output = "";
51625 for(var i = 0; i < input.length; i++)
51626 output += String.fromCharCode( input.charCodeAt(i) & 0xFF,
51627 (input.charCodeAt(i) >>> 8) & 0xFF);
51628 return output;
51629 }
51630
51631 function str2rstr_utf16be(input)
51632 {
51633 var output = "";
51634 for(var i = 0; i < input.length; i++)
51635 output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,
51636 input.charCodeAt(i) & 0xFF);
51637 return output;
51638 }
51639
51640 /*
51641 * Convert a raw string to an array of little-endian words
51642 * Characters >255 have their high-byte silently ignored.
51643 */
51644 function rstr2binl(input)
51645 {
51646 var output = Array(input.length >> 2);
51647 for(var i = 0; i < output.length; i++)
51648 output[i] = 0;
51649 for(var i = 0; i < input.length * 8; i += 8)
51650 output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (i%32);
51651 return output;
51652 }
51653
51654 /*
51655 * Convert an array of little-endian words to a string
51656 */
51657 function binl2rstr(input)
51658 {
51659 var output = "";
51660 for(var i = 0; i < input.length * 32; i += 8)
51661 output += String.fromCharCode((input[i>>5] >>> (i % 32)) & 0xFF);
51662 return output;
51663 }
51664
51665 /*
51666 * Calculate the MD5 of an array of little-endian words, and a bit length.
51667 */
51668 function binl_md5(x, len)
51669 {
51670 /* append padding */
51671 x[len >> 5] |= 0x80 << ((len) % 32);
51672 x[(((len + 64) >>> 9) << 4) + 14] = len;
51673
51674 var a = 1732584193;
51675 var b = -271733879;
51676 var c = -1732584194;
51677 var d = 271733878;
51678
51679 for(var i = 0; i < x.length; i += 16)
51680 {
51681 var olda = a;
51682 var oldb = b;
51683 var oldc = c;
51684 var oldd = d;
51685
51686 a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
51687 d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
51688 c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
51689 b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
51690 a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
51691 d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
51692 c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
51693 b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
51694 a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
51695 d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
51696 c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
51697 b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
51698 a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
51699 d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
51700 c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
51701 b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
51702
51703 a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
51704 d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
51705 c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
51706 b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
51707 a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
51708 d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
51709 c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
51710 b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
51711 a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
51712 d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
51713 c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
51714 b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
51715 a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
51716 d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
51717 c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
51718 b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
51719
51720 a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
51721 d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
51722 c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
51723 b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
51724 a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
51725 d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
51726 c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
51727 b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
51728 a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
51729 d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
51730 c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
51731 b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
51732 a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
51733 d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
51734 c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
51735 b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
51736
51737 a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
51738 d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
51739 c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
51740 b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
51741 a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
51742 d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
51743 c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
51744 b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
51745 a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
51746 d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
51747 c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
51748 b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
51749 a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
51750 d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
51751 c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
51752 b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
51753
51754 a = safe_add(a, olda);
51755 b = safe_add(b, oldb);
51756 c = safe_add(c, oldc);
51757 d = safe_add(d, oldd);
51758 }
51759 return Array(a, b, c, d);
51760 }
51761
51762 /*
51763 * These functions implement the four basic operations the algorithm uses.
51764 */
51765 function md5_cmn(q, a, b, x, s, t)
51766 {
51767 return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
51768 }
51769 function md5_ff(a, b, c, d, x, s, t)
51770 {
51771 return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
51772 }
51773 function md5_gg(a, b, c, d, x, s, t)
51774 {
51775 return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
51776 }
51777 function md5_hh(a, b, c, d, x, s, t)
51778 {
51779 return md5_cmn(b ^ c ^ d, a, b, x, s, t);
51780 }
51781 function md5_ii(a, b, c, d, x, s, t)
51782 {
51783 return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
51784 }
51785
51786 /*
51787 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
51788 * to work around bugs in some JS interpreters.
51789 */
51790 function safe_add(x, y)
51791 {
51792 var lsw = (x & 0xFFFF) + (y & 0xFFFF);
51793 var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
51794 return (msw << 16) | (lsw & 0xFFFF);
51795 }
51796
51797 /*
51798 * Bitwise rotate a 32-bit number to the left.
51799 */
51800 function bit_rol(num, cnt)
51801 {
51802 return (num << cnt) | (num >>> (32 - cnt));
51803 }
51804 /*
51805 * PieChartWidget.js
51806 *
51807 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
51808 *
51809 * This library is free software; you can redistribute it and/or
51810 * modify it under the terms of the GNU Lesser General Public
51811 * License as published by the Free Software Foundation; either
51812 * version 3 of the License, or (at your option) any later version.
51813 *
51814 * This library is distributed in the hope that it will be useful,
51815 * but WITHOUT ANY WARRANTY; without even the implied warranty of
51816 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
51817 * Lesser General Public License for more details.
51818 *
51819 * You should have received a copy of the GNU Lesser General Public
51820 * License along with this library; if not, write to the Free Software
51821 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
51822 * MA 02110-1301 USA
51823 */
51824
51825 /**
51826 * @class PieChartWidget
51827 * PieChartWidget Implementation
51828 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
51829 *
51830 * @param {WidgetWrapper} core wrapper for interaction to other widgets
51831 * @param {HTML object} div parent div to append the PieChart widget div
51832 * @param {JSON} options user specified configuration that overwrites options in PieChartConfig.js
51833 */
51834 PieChartWidget = function(core, div, options) {
51835
51836 /* HACK DW: stelle sicher, dass das nicht zweimal aufgerufen wird! */
51837 if (typeof PieChartWidget_cont == "undefined"){
51838 PieChartWidget_cont="Done";
51839
51840 this.datasets;
51841 this.selected;
51842 this.core = core;
51843 this.core.setWidget(this);
51844
51845 this.options = (new PieChartConfig(options)).options;
51846 this.gui = new PieChartGui(this, div, this.options);
51847 }
51848 this.pieCharts = [];
51849
51850 }
51851
51852 PieChartWidget.prototype = {
51853
51854 addCategorizedPieChart : function(watchedDataset, watchedColumn, type, categories){
51855 var selectionFunction;
51856 if (type === "text"){
51857 //create selection function for the pie chart
51858 var selectionFunction = function(columnData){
51859 var categoryLabel;
51860 $(categories).each(function(){
51861 if ($.inArray(columnData,this.values) != -1){
51862 categoryLabel = this.label;
51863 //exit .each
51864 return false;
51865 }
51866 if (typeof categoryLabel !== "undefined")
51867 return false;
51868 });
51869
51870 if (typeof categoryLabel === "undefined")
51871 categoryLabel = "unknown";
51872
51873 return categoryLabel;
51874 };
51875 } else if (type === "numeral"){
51876 //create selection function for the pie chart
51877 var selectionFunction = function(columnData){
51878 var categoryLabel;
51879 var columnDataNumeric = parseFloat(columnData);
51880 for (var i = 0; i < categories.length; i++){
51881 if (columnDataNumeric<=categories[i]){
51882 categoryLabel = pieChartCategoryChooser.columnName + "<=" + categories[i];
51883 break;
51884 }
51885 }
51886
51887 if (typeof categoryLabel === "undefined")
51888 categoryLabel = "unknown";
51889
51890 return categoryLabel;
51891 };
51892 } else
51893 return;
51894
51895 //make categories easy accessible for later usage
51896 selectionFunction.type = type;
51897 selectionFunction.categories = categories;
51898
51899 this.addPieChart(watchedDataset, watchedColumn, selectionFunction);
51900 },
51901
51902 addPieChart : function(watchedDataset, watchedColumn, selectionFunction){
51903 var newPieChart = new PieChart(this, watchedDataset, watchedColumn, selectionFunction);
51904 this.pieCharts.push(newPieChart);
51905 if ( (typeof GeoTemConfig.datasets !== "undefined") &&
51906 (GeoTemConfig.datasets.length > watchedDataset) )
51907 newPieChart.initPieChart(GeoTemConfig.datasets);
51908 this.redrawPieCharts(this.selected);
51909 },
51910
51911 initWidget : function(data) {
51912 var piechart = this;
51913 this.datasets = data;
51914 piechart.selected = [];
51915 $(this.datasets).each(function(){
51916 piechart.selected.push(this.objects);
51917 })
51918
51919 this.gui.refreshColumnSelector();
51920
51921 $(this.pieCharts).each(function(){
51922 if (this instanceof PieChart)
51923 this.initPieChart(data);
51924 });
51925 },
51926
51927 redrawPieCharts : function(objects, overwrite) {
51928 $(this.pieCharts).each(function(){
51929 if (this instanceof PieChart){
51930 if ( (typeof overwrite !== "undefined") && overwrite)
51931 this.preHighlightObjects = objects;
51932 this.redrawPieChart(objects);
51933 }
51934 });
51935 },
51936
51937 highlightChanged : function(objects) {
51938 if( !GeoTemConfig.highlightEvents ){
51939 return;
51940 }
51941 if ( (typeof objects === "undefined") || (objects.length == 0) ){
51942 return;
51943 }
51944 this.redrawPieCharts(objects, false);
51945 },
51946
51947 selectionChanged : function(selection) {
51948 if( !GeoTemConfig.selectionEvents ){
51949 return;
51950 }
51951 if (!selection.valid()){
51952 selection.loadAllObjects();
51953 }
51954 var objects = selection.objects;
51955 this.selected = objects;
51956 this.redrawPieCharts(objects, true);
51957 },
51958
51959 getElementData : function(dataObject, watchedColumn, selectionFunction) {
51960 var columnData;
51961 if (watchedColumn.indexOf("[") === -1){
51962 columnData = dataObject[watchedColumn];
51963 if (typeof columnData === "undefined"){
51964 columnData = dataObject.tableContent[watchedColumn];
51965 };
51966 } else {
51967 try {
51968 var columnName = watchedColumn.split("[")[0];
51969 var IndexAndAttribute = watchedColumn.split("[")[1];
51970 if (IndexAndAttribute.indexOf("]") != -1){
51971 var arrayIndex = IndexAndAttribute.split("]")[0];
51972 var attribute = IndexAndAttribute.split("]")[1];
51973
51974 if (typeof attribute === "undefined")
51975 columnData = dataObject[columnName][arrayIndex];
51976 else{
51977 attribute = attribute.split(".")[1];
51978 columnData = dataObject[columnName][arrayIndex][attribute];
51979 }
51980 }
51981 } catch(e) {
51982 if (typeof console !== undefined)
51983 console.error(e);
51984
51985 delete columnData;
51986 }
51987 }
51988
51989 if ( (typeof columnData !== "undefined") && (typeof selectionFunction !== "undefined") )
51990 columnData = selectionFunction(columnData);
51991
51992 return(columnData);
51993 },
51994
51995 getElementsByValue : function(columnValue, watchedDataset, watchedColumn, selectionFunction) {
51996 var elements = [];
51997 var pieChart = this;
51998
51999 $(this.datasets[watchedDataset].objects).each(function(){
52000 var columnData = pieChart.getElementData(this, watchedColumn, selectionFunction);
52001 if (columnData === columnValue)
52002 elements.push(this);
52003 });
52004
52005 return elements;
52006 },
52007
52008 getConfig : function(inquiringWidget){
52009 var pieChartWidget = this;
52010 var config = {};
52011
52012 //save widget specific configurations here into the config object
52013 var pieCharts = [];
52014 for (var i=0; i < pieChartWidget.pieCharts.length; i++){
52015 pieChart = pieChartWidget.pieCharts[i];
52016
52017 if (!pieChart){
52018 continue;
52019 }
52020
52021 if (pieChart.selectionFunction.categories){
52022 pieCharts.push({
52023 watchColumn:pieChart.watchColumn,
52024 watchedDataset:pieChart.watchedDataset,
52025 type:pieChart.selectionFunction.type,
52026 categories:pieChart.selectionFunction.categories
52027 });
52028 } else {
52029 pieCharts.push({
52030 watchColumn:pieChart.watchColumn,
52031 watchedDataset:pieChart.watchedDataset
52032 });
52033 }
52034 }
52035
52036 config.pieCharts = pieCharts;
52037
52038 //send config to iquiring widget
52039 if (typeof inquiringWidget.sendConfig !== "undefined"){
52040 inquiringWidget.sendConfig({widgetName: "pieChart", 'config': config});
52041 }
52042 },
52043
52044 setConfig : function(configObj){
52045 var pieChartWidget = this;
52046
52047 if (configObj.widgetName === "pieChart"){
52048 var config = configObj.config;
52049
52050 //remove old piecharts
52051 pieChartWidget.pieCharts = [];
52052 //set widgets configuration provided by config
52053 for (var i=0; i < config.pieCharts.length; i++){
52054 pieChart = config.pieCharts[i];
52055
52056 if (pieChart.type){
52057 pieChartWidget.addCategorizedPieChart(
52058 pieChart.watchedDataset,
52059 pieChart.watchColumn,
52060 pieChart.type,
52061 pieChart.categories
52062 );
52063 } else {
52064 pieChartWidget.addPieChart(
52065 pieChart.watchedDataset,
52066 pieChart.watchColumn
52067 );
52068 }
52069 }
52070 }
52071 },
52072
52073 };
52074 /*
52075 * Storytelling.js
52076 *
52077 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
52078 *
52079 * This library is free software; you can redistribute it and/or
52080 * modify it under the terms of the GNU Lesser General Public
52081 * License as published by the Free Software Foundation; either
52082 * version 3 of the License, or (at your option) any later version.
52083 *
52084 * This library is distributed in the hope that it will be useful,
52085 * but WITHOUT ANY WARRANTY; without even the implied warranty of
52086 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
52087 * Lesser General Public License for more details.
52088 *
52089 * You should have received a copy of the GNU Lesser General Public
52090 * License along with this library; if not, write to the Free Software
52091 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
52092 * MA 02110-1301 USA
52093 */
52094
52095 /**
52096 * @class Storytelling
52097 * Implementation of story telling "storage"
52098 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
52099 *
52100 * @param {HTML object} parent div to append the Storytelling widget
52101 */
52102 function Storytelling(parent) {
52103
52104 this.index;
52105 this.storytelling = this;
52106
52107 this.parent = parent;
52108 this.options = parent.options;
52109
52110 this.initialize();
52111 }
52112
52113 Storytelling.prototype = {
52114
52115 remove : function() {
52116 },
52117
52118 initialize : function() {
52119 },
52120
52121 triggerHighlight : function(columnElement) {
52122 },
52123
52124 triggerSelection : function(columnElement) {
52125 },
52126
52127 deselection : function() {
52128 },
52129
52130 filtering : function() {
52131 },
52132
52133 inverseFiltering : function() {
52134 },
52135
52136 triggerRefining : function() {
52137 },
52138
52139 reset : function() {
52140 },
52141
52142 show : function() {
52143 },
52144
52145 hide : function() {
52146 }
52147 };
52148 /*
52149 * StorytellingConfig.js
52150 *
52151 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
52152 *
52153 * This library is free software; you can redistribute it and/or
52154 * modify it under the terms of the GNU Lesser General Public
52155 * License as published by the Free Software Foundation; either
52156 * version 3 of the License, or (at your option) any later version.
52157 *
52158 * This library is distributed in the hope that it will be useful,
52159 * but WITHOUT ANY WARRANTY; without even the implied warranty of
52160 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
52161 * Lesser General Public License for more details.
52162 *
52163 * You should have received a copy of the GNU Lesser General Public
52164 * License along with this library; if not, write to the Free Software
52165 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
52166 * MA 02110-1301 USA
52167 */
52168
52169 /**
52170 * @class StorytellingConfig
52171 * Storytelling Configuration File
52172 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
52173 */
52174 function StorytellingConfig(options) {
52175
52176 this.options = {
52177 dariahStorage : false,
52178 localStorage : true
52179 };
52180 if ( typeof options != 'undefined') {
52181 $.extend(this.options, options);
52182 }
52183
52184 };
52185 /*
52186 * StorytellingGui.js
52187 *
52188 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
52189 *
52190 * This library is free software; you can redistribute it and/or
52191 * modify it under the terms of the GNU Lesser General Public
52192 * License as published by the Free Software Foundation; either
52193 * version 3 of the License, or (at your option) any later version.
52194 *
52195 * This library is distributed in the hope that it will be useful,
52196 * but WITHOUT ANY WARRANTY; without even the implied warranty of
52197 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
52198 * Lesser General Public License for more details.
52199 *
52200 * You should have received a copy of the GNU Lesser General Public
52201 * License along with this library; if not, write to the Free Software
52202 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
52203 * MA 02110-1301 USA
52204 */
52205
52206 /**
52207 * @class StorytellingGui
52208 * Storytelling GUI Implementation
52209 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
52210 *
52211 * @param {StorytellingWidget} parent Storytelling widget object
52212 * @param {HTML object} div parent div to append the Storytelling gui
52213 * @param {JSON} options Storytelling configuration
52214 */
52215 function StorytellingGui(storytelling, div, options) {
52216
52217 this.parent = storytelling;
52218 var storytellingGui = this;
52219
52220 storytellingGui.storytellingContainer = document.createElement('div');
52221 $(div).append(storytellingGui.storytellingContainer);
52222 storytellingGui.storytellingContainer.style.position = 'relative';
52223 };
52224
52225 StorytellingGui.prototype = {
52226 };
52227 /*
52228 * StorytellingWidget.js
52229 *
52230 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
52231 *
52232 * This library is free software; you can redistribute it and/or
52233 * modify it under the terms of the GNU Lesser General Public
52234 * License as published by the Free Software Foundation; either
52235 * version 3 of the License, or (at your option) any later version.
52236 *
52237 * This library is distributed in the hope that it will be useful,
52238 * but WITHOUT ANY WARRANTY; without even the implied warranty of
52239 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
52240 * Lesser General Public License for more details.
52241 *
52242 * You should have received a copy of the GNU Lesser General Public
52243 * License along with this library; if not, write to the Free Software
52244 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
52245 * MA 02110-1301 USA
52246 */
52247
52248 /**
52249 * @class StorytellingWidget
52250 * StorytellingWidget Implementation
52251 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
52252 *
52253 * @param {WidgetWrapper} core wrapper for interaction to other widgets
52254 * @param {HTML object} div parent div to append the Storytelling widget div
52255 * @param {JSON} options user specified configuration that overwrites options in StorytellingConfig.js
52256 */
52257 StorytellingWidget = function(core, div, options) {
52258
52259 this.datasets;
52260 this.core = core;
52261 this.core.setWidget(this);
52262 this.currentStatus = new Object();
52263
52264 this.options = (new StorytellingConfig(options)).options;
52265 this.gui = new StorytellingGui(this, div, this.options);
52266
52267 this.datasetLink;
52268
52269 Publisher.Subscribe('mapChanged', this, function(mapName) {
52270 this.client.currentStatus["mapChanged"] = mapName;
52271 this.client.createLink();
52272 });
52273
52274 var currentStatus = $.url().param("currentStatus");
52275 if (typeof currentStatus !== "undefined"){
52276 this.currentStatus = $.deparam(currentStatus);
52277 $.each(this.currentStatus,function(action,data){
52278 Publisher.Publish(action, data, this);
52279 });
52280 }
52281 }
52282
52283 StorytellingWidget.prototype = {
52284
52285 initWidget : function(data) {
52286 var storytellingWidget = this;
52287 var gui = storytellingWidget.gui;
52288
52289 storytellingWidget.datasets = data;
52290
52291 $(gui.storytellingContainer).empty();
52292
52293 var magneticLinkParam = "";
52294 var datasetIndex = 0;
52295 var linkCount = 1;
52296 $(storytellingWidget.datasets).each(function(){
52297 var dataset = this;
52298
52299 if (magneticLinkParam.length > 0)
52300 magneticLinkParam += "&";
52301
52302 var paragraph = $("<p></p>");
52303 paragraph.append(dataset.label);
52304 if (typeof dataset.url !== "undefined"){
52305 //TODO: makes only sense for KML or CSV URLs, so "type" of
52306 //URL should be preserved (in dataset).
52307 //startsWith and endsWith defined in SIMILE Ajax (string.js)
52308 var type="csv";
52309 if (typeof dataset.type !== "undefined")
52310 type = dataset.type;
52311 else {
52312 if (dataset.url.toLowerCase().endsWith("kml"))
52313 type = "kml";
52314 }
52315
52316 magneticLinkParam += type+linkCount+"=";
52317 linkCount++;
52318 magneticLinkParam += dataset.url;
52319
52320 var tableLinkDiv = document.createElement('a');
52321 tableLinkDiv.title = dataset.url;
52322 tableLinkDiv.href = dataset.url;
52323 tableLinkDiv.target = '_';
52324 tableLinkDiv.setAttribute('class', 'externalLink');
52325 paragraph.append(tableLinkDiv);
52326 } else {
52327 if (storytellingWidget.options.dariahStorage){
52328 var uploadToDARIAH = document.createElement('a');
52329 $(uploadToDARIAH).append("Upload to DARIAH Storage");
52330 uploadToDARIAH.title = "";
52331 uploadToDARIAH.href = dataset.url;
52332
52333 var localDatasetIndex = new Number(datasetIndex);
52334 $(uploadToDARIAH).click(function(){
52335 var csv = GeoTemConfig.createCSVfromDataset(localDatasetIndex);
52336 // taken from dariah.storage.js
52337 var storageURL = "http://ref.dariah.eu/storage/"
52338 $.ajax({
52339 url: storageURL,
52340 type: 'POST',
52341 contentType: 'text/csv',
52342 data: csv,
52343 success: function(data, status, xhr) {
52344 var location = xhr.getResponseHeader('Location');
52345 // the dariah storage id
52346 dsid = location.substring(location.lastIndexOf('/')+1);
52347
52348 //add URL to dataset
52349 storytellingWidget.datasets[localDatasetIndex].url = location;
52350 storytellingWidget.datasets[localDatasetIndex].type = "csv";
52351 //refresh list
52352 storytellingWidget.initWidget(storytellingWidget.datasets);
52353 },
52354 error: function (data, text, error) {
52355 alert('error creating new file in dariah storage because ' + text);
52356 console.log(data);
52357 console.log(text);
52358 console.log(error);
52359 }
52360 });
52361 //discard link click-event
52362 return(false);
52363 });
52364 paragraph.append(uploadToDARIAH);
52365 }
52366 // TODO: if layout is more usable, both options could be used ("else" removed)
52367 else if (storytellingWidget.options.localStorage){
52368 var saveToLocalStorage = document.createElement('a');
52369 $(saveToLocalStorage).append("Save to Local Storage");
52370 saveToLocalStorage.title = "";
52371 saveToLocalStorage.href = dataset.url;
52372
52373 var localDatasetIndex = new Number(datasetIndex);
52374 $(saveToLocalStorage).click(function(){
52375 var csv = GeoTemConfig.createCSVfromDataset(localDatasetIndex);
52376
52377 var storageName = "GeoBrowser_dataset_"+GeoTemConfig.datasets[localDatasetIndex].label;
52378 $.remember({
52379 name:storageName,
52380 value:csv
52381 });
52382
52383 //add URL to dataset
52384 storytellingWidget.datasets[localDatasetIndex].url = storageName;
52385 storytellingWidget.datasets[localDatasetIndex].type = "local";
52386 //refresh list
52387 storytellingWidget.initWidget(storytellingWidget.datasets);
52388
52389 //discard link click-event
52390 return(false);
52391 });
52392 paragraph.append(saveToLocalStorage);
52393 }
52394 }
52395
52396 $(gui.storytellingContainer).append(paragraph);
52397 datasetIndex++;
52398 });
52399
52400 this.datasetLink = magneticLinkParam;
52401 this.createLink();
52402 },
52403
52404 createLink : function() {
52405 $(this.gui.storytellingContainer).find('.magneticLink').remove();
52406
52407 var magneticLink = document.createElement('a');
52408 magneticLink.setAttribute('class', 'magneticLink');
52409 $(magneticLink).append("Magnetic Link");
52410 magneticLink.title = "Use this link to reload currently loaded (online) data.";
52411 magneticLink.href = "?"+this.datasetLink;
52412 var currentStatusParam = $.param(this.currentStatus);
52413 if (currentStatusParam.length > 0)
52414 magneticLink.href += "&currentStatus="+currentStatusParam;
52415 magneticLink.target = '_';
52416 $(this.gui.storytellingContainer).prepend(magneticLink);
52417 },
52418
52419 highlightChanged : function(objects) {
52420 },
52421
52422 selectionChanged : function(selection) {
52423 },
52424 };
52425 /*
52426 * Storytellingv2.js
52427 *
52428 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
52429 *
52430 * This library is free software; you can redistribute it and/or
52431 * modify it under the terms of the GNU Lesser General Public
52432 * License as published by the Free Software Foundation; either
52433 * version 3 of the License, or (at your option) any later version.
52434 *
52435 * This library is distributed in the hope that it will be useful,
52436 * but WITHOUT ANY WARRANTY; without even the implied warranty of
52437 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
52438 * Lesser General Public License for more details.
52439 *
52440 * You should have received a copy of the GNU Lesser General Public
52441 * License along with this library; if not, write to the Free Software
52442 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
52443 * MA 02110-1301 USA
52444 */
52445
52446 /**
52447 * @class Storytellingv2
52448 * Storytelling Version 2
52449 * @author Mike Bretschneider (mike.bretschneider@gmx.de)
52450 *
52451 * @param {HTML object} parent div to append the Storytellingv2 widget
52452 */
52453 function Storytellingv2(parent) {
52454
52455 this.index;
52456 this.storytellingv2 = this;
52457
52458 this.parent = parent;
52459 this.options = parent.options;
52460
52461 this.initialize();
52462 }
52463
52464 Storytellingv2.prototype = {
52465
52466
52467 deleteAllNodes : function(tree) {
52468 var nodes = tree.jstree().get_children_dom('#');
52469 nodes.each(function() {
52470 tree.jstree().delete_node(this);
52471 });
52472 },
52473
52474 findNodesByType : function(tree,type, parent) {
52475 if (parent != undefined) {
52476 parent = tree.jstree().get_node(parent);
52477 } else {
52478 parent = tree.jstree().get_node('#');
52479 }
52480 var nodes = new Array();
52481
52482 if (parent.type == type) {
52483 nodes.push(parent);
52484 }
52485 for (var i = 0; i < parent.children_d.length; i++) {
52486 var n = tree.jstree().get_node(parent.children_d[i]);
52487 if (n.type == type) {
52488 nodes.push(n);
52489 }
52490 }
52491
52492 return nodes;
52493 },
52494
52495
52496 handleFileSelect : function(evt) {
52497
52498 // var storytellingv2 = this;
52499
52500 var file = evt.target.files[0];
52501 var tree = $('#storytellingv2jstree');
52502
52503 var reader = new FileReader();
52504
52505 var deleteAllNodes = function(tree) {
52506 var nodes = tree.jstree().get_children_dom('#');
52507 nodes.each(function() {
52508 tree.jstree().delete_node(this);
52509 });
52510 }
52511
52512 reader.onload = (function(f) {
52513 return function(e) {
52514
52515 var treedata = JSON.parse(e.target.result);
52516 deleteAllNodes(tree);
52517 for (var i = 0; i < treedata.length; i++) {
52518 if (treedata[i].type == 'dataset') {
52519 tree.jstree().create_node(treedata[i].parent,treedata[i]);
52520 var n = tree.jstree().get_node(treedata[i].id);
52521 tree.jstree().set_type(n, 'snapshot');
52522 $('#storytellingv2expert').show();
52523 $('#storytellingv2simple').hide();
52524 } else if (treedata[i].type == 'snapshot') {
52525 treedata[i].type = 'dataset';
52526 tree.jstree().create_node(treedata[i].parent,treedata[i]);
52527 var n = tree.jstree().get_node(treedata[i].id);
52528 tree.jstree().set_type(n, 'snapshot');
52529 $('#storytellingv2expert').show();
52530 $('#storytellingv2simple').hide();
52531 } else {
52532 tree.jstree().create_node(treedata[i].parent,treedata[i]);
52533 }
52534 };
52535
52536 }
52537 })(file);
52538 reader.readAsText(file);
52539 },
52540
52541
52542 makeSimple : function(tree) {
52543 var configs = this.findNodesByType(tree,'config');
52544 var datasets = this.findNodesByType(tree,'dataset');
52545 for (var i = 0; i < datasets.length; i++) {
52546 tree.jstree().set_type(datasets[i], 'snapshot');
52547 datasets[i].li_attr.dataset_text = datasets[i].text;
52548 datasets[i].text = datasets[i].li_attr.snapshot_text || datasets[i].text;
52549 }
52550 for (var i = 0; i < configs.length; i++) {
52551 var c = tree.jstree().get_node(configs[i], true);
52552 $(c).hide();
52553 }
52554 },
52555
52556
52557
52558
52559
52560
52561
52562
52563 defaultSession : function(tree) {
52564 if (tree.jstree().is_leaf('#')) {
52565 tree.jstree().create_node('#', {
52566 'text' : 'Default Session',
52567 'type' : 'session',
52568 'li_attr' : {
52569 'timestamp' : Date.now(),
52570 'description' : 'Default Session'
52571 }
52572 })
52573 };
52574
52575 },
52576
52577 remove : function() {
52578 },
52579
52580 initialize : function() {
52581 },
52582
52583 triggerHighlight : function(columnElement) {
52584 },
52585
52586 triggerSelection : function(columnElement) {
52587 },
52588
52589 deselection : function() {
52590 },
52591
52592 filtering : function() {
52593 },
52594
52595 inverseFiltering : function() {
52596 },
52597
52598 triggerRefining : function() {
52599 },
52600
52601 reset : function() {
52602 },
52603
52604 show : function() {
52605 },
52606
52607 hide : function() {
52608 }
52609 };
52610 /*
52611 * Storytellingv2Config.js
52612 *
52613 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
52614 *
52615 * This library is free software; you can redistribute it and/or
52616 * modify it under the terms of the GNU Lesser General Public
52617 * License as published by the Free Software Foundation; either
52618 * version 3 of the License, or (at your option) any later version.
52619 *
52620 * This library is distributed in the hope that it will be useful,
52621 * but WITHOUT ANY WARRANTY; without even the implied warranty of
52622 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
52623 * Lesser General Public License for more details.
52624 *
52625 * You should have received a copy of the GNU Lesser General Public
52626 * License along with this library; if not, write to the Free Software
52627 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
52628 * MA 02110-1301 USA
52629 */
52630
52631 /**
52632 * @class Storytellingv2Config
52633 * Storytellingv2 Configuration File
52634 * @author Mike Bretschneider (mike.bretschneider@gmx.de)
52635 */
52636 function Storytellingv2Config(options) {
52637
52638 this.options = {
52639 dariahStorage : false,
52640 localStorage : true
52641 };
52642 if ( typeof options != 'undefined') {
52643 $.extend(this.options, options);
52644 }
52645
52646 };
52647 /*
52648 * Storytellingv2Gui.js
52649 *
52650 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
52651 *
52652 * This library is free software; you can redistribute it and/or
52653 * modify it under the terms of the GNU Lesser General Public
52654 * License as published by the Free Software Foundation; either
52655 * version 3 of the License, or (at your option) any later version.
52656 *
52657 * This library is distributed in the hope that it will be useful,
52658 * but WITHOUT ANY WARRANTY; without even the implied warranty of
52659 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
52660 * Lesser General Public License for more details.
52661 *
52662 * You should have received a copy of the GNU Lesser General Public
52663 * License along with this library; if not, write to the Free Software
52664 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
52665 * MA 02110-1301 USA
52666 */
52667
52668 /**
52669 * @class StorytellingGui
52670 * Storytellingv2 GUI Implementation
52671 * @author Mike Bretschneider (mike.bretschneider@gmx.de)
52672 *
52673 * @param {Storytellingv2Widget} parent Storytellingv2 widget object
52674 * @param {HTML object} div parent div to append the Storytellingv2 gui
52675 * @param {JSON} options Storytellingv2 configuration
52676 */
52677 function Storytellingv2Gui(storytellingv2, div, options) {
52678
52679 this.parent = storytellingv2;
52680 var storytellingv2Gui = this;
52681
52682 storytellingv2Gui.storytellingv2Container = document.createElement('div');
52683 $(div).append(storytellingv2Gui.storytellingv2Container);
52684 storytellingv2Gui.storytellingv2Container.style.position = 'relative';
52685 };
52686
52687 Storytellingv2Gui.prototype = {
52688
52689 initGui : function() {
52690
52691 var storytellingv2Gui = this;
52692 var storytellingv2Widget = storytellingv2Gui.parent;
52693 var storytellingv2 = storytellingv2Widget.storytellingv2;
52694
52695 if (storytellingv2Gui.tree == undefined) {
52696 storytellingv2Gui.initTree();
52697 }
52698 },
52699
52700 initTree : function() {
52701
52702 var storytellingv2Gui = this;
52703 var storytellingv2Widget = storytellingv2Gui.parent;
52704 var storytellingv2 = storytellingv2Widget.storytellingv2;
52705
52706 $(storytellingv2Gui.storytellingv2Container).empty();
52707
52708 storytellingv2Gui.tree = $('<div style="border: 2px solid; padding: 5px; float: left;" id="storytellingv2jstree"><ul></ul></div>');
52709 storytellingv2Gui.tree.jstree({
52710 'core' : {
52711 'check_callback' : true,
52712 },
52713 'plugins' : [ 'dnd', 'types' ],
52714 'types' : {
52715 '#' : {
52716 valid_children : ['session']
52717 },
52718 'session' : {
52719 valid_children : ['dataset', 'config']
52720 },
52721 'dataset' : {
52722 'valid_children' : ['config'],
52723 'icon' : 'lib/jstree/themes/default/dataset.png'
52724 },
52725 'snapshot' : {
52726 'valid_children' : ['config'],
52727 'icon' : 'lib/jstree/themes/default/snapshot.png'
52728 },
52729 'config' : {
52730 'valid_children' : ['config'],
52731 'icon' : 'lib/jstree/themes/default/filter.png'
52732 }
52733 }
52734 });
52735
52736 storytellingv2Gui.tree.on('open_node.jstree', function(e, data) {
52737 var node = data.node;
52738 if (node.type == 'snapshot') {
52739 storytellingv2Gui.tree.jstree().close_node(node, false);
52740 }
52741
52742 });
52743
52744 storytellingv2Gui.menu = $('<div style="float: left;"></div>');
52745 storytellingv2Gui.importexportsubmenu = $('<div style="border: 2px solid; margin: 2px; padding: 5px;"></div>');
52746
52747 storytellingv2Gui.addImportButton();
52748 storytellingv2Gui.addExportButton();
52749 storytellingv2Gui.addResetButton();
52750 storytellingv2Gui.addExpertButton();
52751 storytellingv2Gui.addSimpleButton();
52752
52753 storytellingv2Gui.simplebutton.hide();
52754 $(storytellingv2Gui.importexportsubmenu).append(storytellingv2Gui.importbutton);
52755 $(storytellingv2Gui.importexportsubmenu).append(storytellingv2Gui.exportbutton);
52756 $(storytellingv2Gui.importexportsubmenu).append(storytellingv2Gui.resetbutton);
52757 $(storytellingv2Gui.importexportsubmenu).append(storytellingv2Gui.expertbutton);
52758 $(storytellingv2Gui.importexportsubmenu).append(storytellingv2Gui.simplebutton);
52759 $(storytellingv2Gui.importexportsubmenu).append(storytellingv2Gui.importfile);
52760
52761 storytellingv2Gui.treemanipulationsubmenu = $('<div style="border: 2px solid; margin: 2px; padding: 5px;"></div>');
52762
52763 storytellingv2Gui.addNewButton();
52764 storytellingv2Gui.addSnapshotButton();
52765 storytellingv2Gui.addRestoreButton();
52766 storytellingv2Gui.addDeleteButton();
52767 storytellingv2Gui.addEditButton();
52768 storytellingv2Gui.addBackwardButton();
52769 storytellingv2Gui.addForwardButton();
52770
52771 $(storytellingv2Gui.treemanipulationsubmenu).append(storytellingv2Gui.newbutton);
52772 $(storytellingv2Gui.treemanipulationsubmenu).append(storytellingv2Gui.snapshotbutton);
52773 $(storytellingv2Gui.treemanipulationsubmenu).append(storytellingv2Gui.restorebutton);
52774 $(storytellingv2Gui.treemanipulationsubmenu).append(storytellingv2Gui.deletebutton);
52775 $(storytellingv2Gui.treemanipulationsubmenu).append(storytellingv2Gui.editbutton);
52776 $(storytellingv2Gui.treemanipulationsubmenu).append(storytellingv2Gui.backwardbutton);
52777 $(storytellingv2Gui.treemanipulationsubmenu).append(storytellingv2Gui.forwardbutton);
52778
52779 storytellingv2Gui.addMetadata();
52780
52781 storytellingv2Gui.newbutton.hide();
52782 $(storytellingv2Gui.storytellingv2Container).append(storytellingv2Gui.tree);
52783 $(storytellingv2Gui.menu).append(storytellingv2Gui.importexportsubmenu);
52784 $(storytellingv2Gui.menu).append(storytellingv2Gui.treemanipulationsubmenu);
52785 $(storytellingv2Gui.menu).append(storytellingv2Gui.metadata);
52786 $(storytellingv2Gui.storytellingv2Container).append(storytellingv2Gui.menu);
52787
52788 storytellingv2Gui.tree.hide();
52789 storytellingv2Gui.metadata.hide();
52790
52791 storytellingv2Gui.tree.on('create_node.jstree delete_node.jstree', function(e, data) {
52792 var root = storytellingv2Gui.tree.jstree().get_node('#');
52793 if (root.children.length > 0) {
52794 storytellingv2Gui.tree.show();
52795 storytellingv2Gui.metadata.show();
52796 if (e.type == "create_node") {
52797 storytellingv2Gui.tree.jstree().deselect_all();
52798 storytellingv2Gui.tree.jstree().select_node(data.node);
52799 } if (e.type == "delete_node") {
52800 storytellingv2Gui.tree.jstree().deselect_all();
52801 var prev_node = storytellingv2Gui.tree.jstree().get_prev_dom(data.node);
52802 storytellingv2Gui.tree.jstree().select_node(prev_node);
52803 }
52804 } else {
52805 storytellingv2Gui.tree.hide();
52806 storytellingv2Gui.metadata.hide();
52807 }
52808
52809 });
52810
52811 if (localStorage.getItem('PLATIN.storytellingv2.last_snapshot')) {
52812 var lastSession = storytellingv2Gui.tree.jstree().create_node('#', {
52813 'text' : 'Last Session',
52814 'type' : 'session',
52815 'li_attr' : {
52816 'timestamp' : Date.now(),
52817 'description' : 'Default Session'
52818 }
52819 });
52820 var nodes = JSON.parse(localStorage.getItem('PLATIN.storytellingv2.last_snapshot'));
52821 var last = storytellingv2Gui.tree.jstree().create_node(lastSession, nodes);
52822 storytellingv2.makeSimple(storytellingv2Gui.tree);
52823
52824 }
52825
52826 },
52827
52828 addImportButton : function() {
52829
52830 var storytellingv2Gui = this;
52831 var storytellingv2Widget = storytellingv2Gui.parent;
52832 var storytellingv2 = storytellingv2Widget.storytellingv2;
52833
52834 storytellingv2Gui.importbutton = $('<input type="button" id="storytellingv2import" name="import" value="import" />');
52835 storytellingv2Gui.importfile = $('<input type="file" id="storytellingv2importfile" accept="application/json" style="display: block; visibility:hidden; width: 0; height: 0" />');
52836 storytellingv2Gui.importfile.change(storytellingv2.handleFileSelect);
52837
52838 storytellingv2Gui.importbutton.click($.proxy(function() {
52839 storytellingv2Gui.importfile.click();
52840 }));
52841
52842 },
52843
52844 addExportButton : function() {
52845
52846 var storytellingv2Gui = this;
52847 var storytellingv2Widget = storytellingv2Gui.parent;
52848 var storytellingv2 = storytellingv2Widget.storytellingv2;
52849
52850 storytellingv2Gui.exportbutton = $('<input type="button" id="storytellingv2export" name="export" value="export" />');
52851 var dialog = $('<div id="tree-export-filename" title="Save File As?"><p><input type="text" size="25" /></p></div>');
52852 storytellingv2Gui.exportbutton.append(dialog);
52853 dialog.dialog({
52854 resizable: false,
52855 autoOpen: false,
52856 height: 220,
52857 modal: true,
52858 buttons: {
52859 'Ok': function() {
52860 $(this).dialog("close");
52861 },
52862 Cancel: function() {
52863 $(this).dialog("close");
52864 }
52865 }
52866 });
52867 storytellingv2Gui.exportbutton.click($.proxy(function() {
52868 var tree_as_json = JSON.stringify($('#storytellingv2jstree').jstree(true).get_json('#', { 'flat': true }));
52869 var exportdate = new Date().toUTCString();
52870
52871 dialog.dialog('open');
52872 $(dialog).find(':input').val("Storytelling State(" + exportdate + ").json");
52873 dialog.dialog('option', 'buttons', {
52874 'Ok': function() {
52875 var blob = new Blob([tree_as_json], {type: "text/plain;charset=utf-8"});
52876 saveAs(blob, dialog.find(':input').val());
52877 $(this).dialog("close");
52878 },
52879 Cancel: function() {
52880 $(this).dialog("close");
52881 }
52882 })
52883 // var blob = new Blob([tree_as_json], {type: "text/plain;charset=utf-8"});
52884 // saveAs(blob, "Storytelling State(" + exportdate + ").json");
52885
52886 /*
52887 var pom = document.createElement('a');
52888 pom.setAttribute('href','data:application/json;charset=UTF-8, ' + encodeURIComponent(tree_as_json));
52889 pom.setAttribute('download','Storytelling State(' + exportdate + ').json');
52890 pom.click();
52891 */
52892 }));
52893
52894 },
52895
52896 addResetButton : function() {
52897
52898 var storytellingv2Gui = this;
52899 var storytellingv2Widget = storytellingv2Gui.parent;
52900 var storytellingv2 = storytellingv2Widget.storytellingv2;
52901
52902 storytellingv2Gui.resetbutton = $('<input type="button" id="storytellingv2reset" name="reset" value="reset" />');
52903 var dialog = $('<div id="tree-reset-dialog-confirm" title="Erase all tree content?"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Tree items will be permanently deleted and cannot be recovered. Are you sure?</p></div>');
52904 storytellingv2Gui.resetbutton.append(dialog)
52905 dialog.dialog({
52906 resizable: false,
52907 autoOpen: false,
52908 height: 260,
52909 modal: true,
52910 buttons: {
52911 'Yes': function() {
52912 storytellingv2.deleteAllNodes(storytellingv2Gui.tree);
52913 $(this).dialog("close");
52914 },
52915 Cancel: function() {
52916 $(this).dialog("close");
52917 }
52918 }
52919 });
52920
52921 storytellingv2Gui.resetbutton.click($.proxy(function() {
52922 dialog.dialog('open');
52923 }));
52924 },
52925
52926 addExpertButton : function() {
52927
52928 var storytellingv2Gui = this;
52929 var storytellingv2Widget = storytellingv2Gui.parent;
52930 var storytellingv2 = storytellingv2Widget.storytellingv2;
52931
52932 storytellingv2Gui.expertbutton = $('<input type="button" id="storytellingv2expert" name="expert" value="expert" />');
52933 storytellingv2Gui.expertbutton.click($.proxy(function() {
52934 storytellingv2Gui.expertbutton.hide();
52935 storytellingv2Gui.simplebutton.show();
52936 storytellingv2Gui.snapshotbutton.hide();
52937 storytellingv2Gui.newbutton.show();
52938 storytellingv2Gui.parent.simplemode = false;
52939 var configs = storytellingv2.findNodesByType(storytellingv2Gui.tree,'config');
52940 for (var i = 0; i < configs.length; i++) {
52941 storytellingv2Gui.tree.jstree().get_node(configs[i], true).show();
52942 }
52943 var snapshots = storytellingv2.findNodesByType(storytellingv2Gui.tree,'snapshot');
52944 for (var i = 0; i < snapshots.length; i++) {
52945 storytellingv2Gui.tree.jstree().set_type(snapshots[i], 'dataset');
52946 snapshots[i].li_attr.snapshot_text = snapshots[i].text;
52947 snapshots[i].text = snapshots[i].li_attr.dataset_text || snapshots[i].text;
52948 }
52949
52950 }));
52951
52952 },
52953
52954 addSimpleButton : function() {
52955
52956 var storytellingv2Gui = this;
52957 var storytellingv2Widget = storytellingv2Gui.parent;
52958 var storytellingv2 = storytellingv2Widget.storytellingv2;
52959
52960 storytellingv2Gui.simplebutton = $('<input type="button" id="storytellingv2simple" name="simple" value="simple" />');
52961 storytellingv2Gui.simplebutton.click($.proxy(function() {
52962 storytellingv2Gui.simplebutton.hide();
52963 storytellingv2Gui.expertbutton.show();
52964 storytellingv2Gui.newbutton.hide();
52965 storytellingv2Gui.snapshotbutton.show();
52966 storytellingv2Gui.parent.simplemode = true;
52967 storytellingv2.makeSimple(storytellingv2Gui.tree);
52968 }));
52969
52970 },
52971
52972 addNewButton : function() {
52973
52974 var storytellingv2Gui = this;
52975 var storytellingv2Widget = storytellingv2Gui.parent;
52976 var storytellingv2 = storytellingv2Widget.storytellingv2;
52977
52978 storytellingv2Gui.newbutton = $('<input type="button" id="storytellingv2new" name="new" value="new" />');
52979 storytellingv2Gui.newbutton.click($.proxy(function() {
52980 storytellingv2.defaultSession(storytellingv2Gui.tree);
52981 var newform = $('<div></div>');
52982 var nameinput = $('<p>Name: <input type="text" /></p>');
52983 var typeinput = $('<p>Type: <select name="type"><option value="session">Session</option><option value="dataset">Dataset</option><option value="config">Config</option></select></p>');
52984 var descriptioninput = $('<p>Description: <textarea name="description"></textarea></p>');
52985 var addbutton = $('<p><input type="button" name="add" value="add" /></p>');
52986 newform.focusout(function() {
52987 var elem = $(this);
52988 setTimeout(function() {
52989 var hasFocus = !!(elem.find(':focus').length > 0);
52990 if (! hasFocus) {
52991 newform.empty();
52992 }
52993 }, 10);
52994 });
52995 addbutton.click($.proxy(function() {
52996 var sel = storytellingv2Gui.tree.jstree().get_selected()[0] || '#' ;
52997 if ($(typeinput).find('option:selected').val() == 'session') {
52998 sel = '#';
52999 }
53000 sel = storytellingv2Gui.tree.jstree().create_node(sel, {
53001 "text" : $(nameinput).find(':text').first().val(),
53002 "type" : $(typeinput).find('option:selected').val(),
53003 "li_attr" : {
53004 "timestamp" : Date.now(),
53005 "description" : $(descriptioninput).find('textarea').first().val()
53006 }
53007 });
53008 var newNode = storytellingv2Gui.tree.jstree().get_node(sel);
53009
53010 if (newNode.type == 'config') {
53011 Publisher.Publish('getConfig',storytellingv2Widget);
53012 newNode.li_attr.configs = storytellingv2Widget.configArray.slice();
53013 } else if (newNode.type == 'dataset') {
53014 var datasets = [];
53015 if (storytellingv2Widget.datasets != undefined) {
53016 for (var i = 0; i < storytellingv2Widget.datasets.length; i++) {
53017 var ds = {};
53018 ds.label = storytellingv2Widget.datasets[i].label;
53019 ds.objects = GeoTemConfig.convertCsv(GeoTemConfig.createCSVfromDataset(i));
53020 datasets.push(ds);
53021 }
53022 }
53023 newNode.li_attr.selected = storytellingv2Widget.selected;
53024 newNode.li_attr.datasets = datasets;
53025 }
53026 // tree.jstree().set_type(sel, 'session');
53027 $(newform).empty();
53028 }));
53029 $(newform).append(nameinput);
53030 $(newform).append(typeinput);
53031 $(newform).append(descriptioninput);
53032 $(newform).append(addbutton);
53033 $(storytellingv2Gui.treemanipulationsubmenu).append(newform);
53034 $(nameinput).find(':input').focus();
53035 }));
53036
53037 },
53038
53039 addSnapshotButton : function() {
53040
53041 var storytellingv2Gui = this;
53042 var storytellingv2Widget = storytellingv2Gui.parent;
53043 var storytellingv2 = storytellingv2Widget.storytellingv2;
53044
53045 storytellingv2Gui.snapshotbutton = $('<input type="button" id="storytellingv2snapshot" name="snapshot" value="snapshot" />');
53046 storytellingv2Gui.snapshotbutton.click($.proxy(function() {
53047 storytellingv2.defaultSession(storytellingv2Gui.tree);
53048 var root = storytellingv2Gui.tree.jstree().get_node('#');
53049 var session = storytellingv2Gui.tree.jstree().get_node(root.children[0]);
53050 var countSnapshots = session.children.length + 1;
53051 var datasets = [];
53052
53053 if (storytellingv2Widget.datasets != undefined) {
53054 for (var i = 0; i < storytellingv2Widget.datasets.length; i++) {
53055 var ds = {};
53056 ds.label = storytellingv2Widget.datasets[i].label;
53057 ds.objects = GeoTemConfig.convertCsv(GeoTemConfig.createCSVfromDataset(i));
53058 datasets.push(ds);
53059 }
53060 }
53061 var newDataset = storytellingv2Gui.tree.jstree().create_node(session, {
53062 'text' : 'Snapshot #'+countSnapshots,
53063 'type' : 'dataset',
53064 'li_attr' : {
53065 'timestamp' : Date.now(),
53066 'description' : 'Snapshot #'+countSnapshots+' Dataset',
53067 'datasets' : datasets,
53068 'selected' : storytellingv2Widget.selected
53069 }
53070 });
53071 Publisher.Publish('getConfig',storytellingv2Widget);
53072 var newConfig = storytellingv2Gui.tree.jstree().create_node(newDataset, {
53073 'text' : 'Snapshot #'+countSnapshots,
53074 'type' : 'config',
53075 'li_attr' : {
53076 'timestamp' : Date.now(),
53077 'description' : 'Snapshot #'+countSnapshots+' Config',
53078 'configs' : storytellingv2Widget.configArray.slice()
53079 }
53080 });
53081 snapshot_as_json = JSON.stringify(storytellingv2Gui.tree.jstree(true).get_json(newDataset));
53082 localStorage.setItem("PLATIN.storytellingv2.last_snapshot",snapshot_as_json);
53083 storytellingv2.makeSimple(storytellingv2Gui.tree);
53084
53085 }));
53086
53087 },
53088
53089 addRestoreButton : function() {
53090
53091 var storytellingv2Gui = this;
53092 var storytellingv2Widget = storytellingv2Gui.parent;
53093 var storytellingv2 = storytellingv2Widget.storytellingv2;
53094
53095 storytellingv2Gui.restorebutton = $('<input type="button" id="storytellingv2restore" name="restore" value="restore" />');
53096 var loadDataset = function(node) {
53097 var datasets = node.li_attr.datasets;
53098 if (datasets != undefined) {
53099 GeoTemConfig.removeAllDatasets();
53100 for (var i = 0; i < datasets.length; i++) {
53101 var dataset = new Dataset(GeoTemConfig.loadJson(datasets[i].objects), datasets[i].label);
53102 GeoTemConfig.addDataset(dataset);
53103 }
53104 }
53105
53106 }
53107
53108 var loadFilter = function(node) {
53109 var configArray = node.li_attr.configs;
53110 for (var i = 0; i < configArray.length; i++) {
53111 Publisher.Publish('setConfig', configArray[i]);
53112 }
53113 }
53114
53115 var loadSnapshot = function(node) {
53116 loadDataset(node);
53117 var childNode = node;
53118 while (storytellingv2Gui.tree.jstree().is_parent(childNode)) {
53119 childNode = storytellingv2Gui.tree.jstree().get_node(childNode.children[0]);
53120 if (childNode.type == 'config') {
53121 loadFilter(childNode);
53122 }
53123 }
53124 }
53125
53126 storytellingv2Gui.restorebutton.click($.proxy(function() {
53127 var selectedNode = storytellingv2Gui.tree.jstree().get_node(storytellingv2Gui.tree.jstree().get_selected()[0]);
53128 if (selectedNode == 'undefined' || selectedNode.type == 'session') {
53129 return;
53130 }
53131 if (selectedNode.type == 'snapshot') {
53132 loadSnapshot(selectedNode);
53133 return;
53134 }
53135 for (var i = selectedNode.parents.length - 1; i >= 0; i--) {
53136 var curNode = storytellingv2Gui.tree.jstree().get_node(selectedNode.parents[i]);
53137 if (curNode.type == 'dataset') {
53138 loadDataset(curNode);
53139 } else if (curNode.type == 'config') {
53140 loadFilter(curNode);
53141 }
53142 }
53143 if (selectedNode.type == 'dataset') {
53144 loadDataset(selectedNode);
53145 } else if (selectedNode.type == 'config') {
53146 loadFilter(selectedNode);
53147 }
53148 }));
53149
53150 },
53151
53152 addDeleteButton : function() {
53153
53154 var storytellingv2Gui = this;
53155 var storytellingv2Widget = storytellingv2Gui.parent;
53156 var storytellingv2 = storytellingv2Widget.storytellingv2;
53157
53158 storytellingv2Gui.deletebutton = $('<input type="button" id="storytellingv2delete" name="delete" value="delete" />');
53159 storytellingv2Gui.deletebutton.click($.proxy(function() {
53160 var selectedNode = storytellingv2Gui.tree.jstree().get_node(storytellingv2Gui.tree.jstree().get_selected()[0]);
53161 storytellingv2Gui.tree.jstree().delete_node(selectedNode);
53162 }))
53163
53164 },
53165
53166 addEditButton : function() {
53167
53168 var storytellingv2Gui = this;
53169 var storytellingv2Widget = storytellingv2Gui.parent;
53170 var storytellingv2 = storytellingv2Widget.storytellingv2;
53171
53172 storytellingv2Gui.editbutton = $('<input type="button" id="storytellingv2edit" name="edit" value="edit" />');
53173 storytellingv2Gui.editbutton.click($.proxy(function() {
53174 var sel = storytellingv2Gui.tree.jstree().get_selected()[0];
53175 if (sel != undefined ) {
53176 sel = storytellingv2Gui.tree.jstree().get_node(sel);
53177 var editform = $('<div></div>');
53178 var nameinput = $('<p>Name: <input type="text" value="'+sel.text+'" /></p>');
53179 var descriptioninput = $('<p>Description: <textarea name="description">'+sel.li_attr.description+'</textarea></p>');
53180 var savebutton = $('<p><input type="button" name="save" value="save" /></p>');
53181 editform.focusout(function() {
53182 var elem = $(this);
53183 setTimeout(function() {
53184 var hasFocus = !!(elem.find(':focus').length > 0);
53185 if (! hasFocus) {
53186 editform.empty();
53187 }
53188 }, 10);
53189 });
53190 savebutton.click($.proxy(function() {
53191 storytellingv2Gui.tree.jstree().rename_node(sel, $(nameinput).find(':text').first().val());
53192 sel.li_attr.description = $(descriptioninput).find('textarea').first().val();
53193 storytellingv2Gui.tree.jstree().redraw();
53194 $(editform).empty();
53195 }));
53196 // $(editform).focusout(function() {
53197 // $(editform).empty();
53198 // });
53199 $(editform).append(nameinput);
53200 $(editform).append(descriptioninput);
53201 $(editform).append(savebutton);
53202 storytellingv2Gui.treemanipulationsubmenu.append(editform);
53203 nameinput.find(':input').focus();
53204 }
53205
53206
53207 }));
53208
53209 },
53210
53211 addForwardButton : function() {
53212
53213 var storytellingv2Gui = this;
53214 var storytellingv2Widget = storytellingv2Gui.parent;
53215 var storytellingv2 = storytellingv2Widget.storytellingv2;
53216
53217 storytellingv2Gui.forwardbutton = $('<input type="button" id="storytellingv2forward" name="forward" value=">>" />');
53218 storytellingv2Gui.forwardbutton.click($.proxy(function() {
53219 var sel = storytellingv2Gui.tree.jstree().get_selected()[0];
53220 if (storytellingv2Gui.tree.jstree().get_next_dom(sel, true)) {
53221 storytellingv2Gui.tree.jstree().deselect_node(sel);
53222 storytellingv2Gui.tree.jstree().select_node(storytellingv2Gui.tree.jstree().get_next_dom(sel, true));
53223 }
53224
53225 }));
53226
53227 },
53228
53229 addBackwardButton : function() {
53230
53231 var storytellingv2Gui = this;
53232 var storytellingv2Widget = storytellingv2Gui.parent;
53233 var storytellingv2 = storytellingv2Widget.storytellingv2;
53234
53235 storytellingv2Gui.backwardbutton = $('<input type="button" id="storytellingv2backward" name="backward" value="<<" />');
53236 storytellingv2Gui.backwardbutton.click($.proxy(function() {
53237 var sel = storytellingv2Gui.tree.jstree().get_selected()[0];
53238 if (storytellingv2Gui.tree.jstree().get_prev_dom(sel, true)) {
53239 storytellingv2Gui.tree.jstree().deselect_node(sel);
53240 storytellingv2Gui.tree.jstree().select_node(storytellingv2Gui.tree.jstree().get_prev_dom(sel, true));
53241 }
53242
53243 }));
53244
53245
53246 },
53247
53248 addMetadata : function() {
53249
53250 var storytellingv2Gui = this;
53251 var storytellingv2Widget = storytellingv2Gui.parent;
53252 var storytellingv2 = storytellingv2Widget.storytellingv2;
53253
53254 storytellingv2Gui.metadata = $('<div></div>');
53255 var metadatafieldset = $('<fieldset style="border: 2px solid; margin: 2px; padding: 5px;"><legend>Metadata</legend></fieldset>');
53256 var metadataname = $('<p>Name:</p>');
53257 var metadatatype = $('<p>Type:</p>');
53258 var metadatatimestamp = $('<p>Timestamp:</p>');
53259 var metadatadescription = $('<p>Description:</p>');
53260 var metadataselected = $('<p></p>');
53261 $(metadatafieldset).append(metadataname);
53262 $(metadatafieldset).append(metadatatype);
53263 $(metadatafieldset).append(metadatatimestamp);
53264 $(metadatafieldset).append(metadatadescription);
53265 $(metadatafieldset).append(metadataselected);
53266 $(storytellingv2Gui.metadata).append(metadatafieldset);
53267 storytellingv2Gui.tree.on('changed.jstree rename_node.jstree', function(e, data) {
53268 if (data.node == undefined) {
53269 return;
53270 }
53271 $(metadataname).empty().append($('<p>Name: '+data.node.text+'</p>'));
53272 $(metadatatype).empty().append($('<p>Type: '+data.node.type+'</p>'));
53273 var tstamp = new Date(data.node.li_attr.timestamp);
53274 $(metadatatimestamp).empty().append($('<p>Timestamp: '+tstamp.toUTCString()+'</p>'));
53275 $(metadatadescription).empty().append($('<p>Description: '+data.node.li_attr.description+'</p>'));
53276 var objectcount = 0;
53277 var datasetcount = 0;
53278 if ($.isArray(data.node.li_attr.selected)) {
53279 datasetcount = data.node.li_attr.selected.length;
53280 $(data.node.li_attr.selected).each(function() {
53281 objectcount += this.length;
53282 });
53283 }
53284 // $(metadataselected).empty().append($('<p>'+objectcount+' Selected Objects in '+datasetcount+' Datasets</p>'));
53285 });
53286
53287 }
53288
53289
53290 };
53291 /*
53292 * StorytellingWidget.js
53293 *
53294 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
53295 *
53296 * This library is free software; you can redistribute it and/or
53297 * modify it under the terms of the GNU Lesser General Public
53298 * License as published by the Free Software Foundation; either
53299 * version 3 of the License, or (at your option) any later version.
53300 *
53301 * This library is distributed in the hope that it will be useful,
53302 * but WITHOUT ANY WARRANTY; without even the implied warranty of
53303 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
53304 * Lesser General Public License for more details.
53305 *
53306 * You should have received a copy of the GNU Lesser General Public
53307 * License along with this library; if not, write to the Free Software
53308 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
53309 * MA 02110-1301 USA
53310 */
53311
53312 /**
53313 * @class Storytellingv2Widget
53314 * Storytellingv2Widget Implementation
53315 * @author Mike Bretschneider (mike.bretschneider@gmx.de)
53316 *
53317 * @param {WidgetWrapper} core wrapper for interaction to other widgets
53318 * @param {HTML object} div parent div to append the Storytellingv2 widget div
53319 * @param {JSON} options user specified configuration that overwrites options in Storytellingv2Config.js
53320 */
53321 Storytellingv2Widget = function(core, div, options) {
53322 /* HACK DW: stelle sicher, dass das nicht zweimal aufgerufen wird! */
53323 if (typeof Storytellingv2Widget_cont == "undefined"){
53324 Storytellingv2Widget_cont="Done";
53325
53326 this.datasets;
53327 this.core = core;
53328 this.core.setWidget(this);
53329 this.currentStatus = new Object();
53330
53331 this.options = (new Storytellingv2Config(options)).options;
53332 this.gui = new Storytellingv2Gui(this, div, this.options);
53333 this.storytellingv2 = new Storytellingv2(this);
53334
53335 this.datasetLink;
53336
53337 this.selected;
53338 this.configArray = [];
53339
53340 this.simplemode = true;
53341
53342 this.initWidget();
53343
53344 }
53345 }
53346
53347 Storytellingv2Widget.prototype = {
53348
53349 initWidget : function(data) {
53350
53351
53352 var storytellingv2Widget = this;
53353 var gui = storytellingv2Widget.gui;
53354
53355 storytellingv2Widget.datasets = data;
53356
53357 gui.initGui();
53358
53359 },
53360
53361 createLink : function() {
53362 },
53363
53364 highlightChanged : function(objects) {
53365 },
53366
53367 selectionChanged : function(selection) {
53368 if (!selection.valid()) {
53369 selection.loadAllObjects();
53370 }
53371 this.selected = selection.objects;
53372 },
53373
53374 sendConfig : function(widgetConfig){
53375 for (var i = 0; i < this.configArray.length; i++) {
53376 if (this.configArray[i].widgetName == widgetConfig.widgetName) {
53377 this.configArray.splice(i,1);
53378 }
53379 }
53380 this.configArray.push(widgetConfig);
53381 },
53382
53383 };
53384 /*
53385 * LineOverlay.js
53386 *
53387 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
53388 *
53389 * This library is free software; you can redistribute it and/or
53390 * modify it under the terms of the GNU Lesser General Public
53391 * License as published by the Free Software Foundation; either
53392 * version 3 of the License, or (at your option) any later version.
53393 *
53394 * This library is distributed in the hope that it will be useful,
53395 * but WITHOUT ANY WARRANTY; without even the implied warranty of
53396 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
53397 * Lesser General Public License for more details.
53398 *
53399 * You should have received a copy of the GNU Lesser General Public
53400 * License along with this library; if not, write to the Free Software
53401 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
53402 * MA 02110-1301 USA
53403 */
53404
53405 /**
53406 * @class LineOverlay
53407 * Implementation for an overlay showing lines between points
53408 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
53409 *
53410 * @param {HTML object} parent div to append the LineOverlay
53411 */
53412 function LineOverlay(parent) {
53413
53414 this.lineOverlay = this;
53415
53416 this.parent = parent;
53417 this.options = parent.options;
53418 this.attachedMapWidgets = parent.attachedMapWidgets;
53419
53420 this.overlays = [];
53421
53422 this.initialize();
53423 }
53424
53425 LineOverlay.prototype = {
53426
53427 initialize : function() {
53428 }
53429 };
53430 /*
53431 * LineOverlayConfig.js
53432 *
53433 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
53434 *
53435 * This library is free software; you can redistribute it and/or
53436 * modify it under the terms of the GNU Lesser General Public
53437 * License as published by the Free Software Foundation; either
53438 * version 3 of the License, or (at your option) any later version.
53439 *
53440 * This library is distributed in the hope that it will be useful,
53441 * but WITHOUT ANY WARRANTY; without even the implied warranty of
53442 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
53443 * Lesser General Public License for more details.
53444 *
53445 * You should have received a copy of the GNU Lesser General Public
53446 * License along with this library; if not, write to the Free Software
53447 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
53448 * MA 02110-1301 USA
53449 */
53450
53451 /**
53452 * @class LineOverlayConfig
53453 * LineOverlay Configuration File
53454 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
53455 */
53456 function LineOverlayConfig(options) {
53457 this.options = {
53458 showArrows : true,
53459 showLines : "both", //which directions will be shown: "both", "inbound", "outbound"
53460 onlyShowSelectedOrHighlighted : false, //only show lines in case of selection/highlight
53461 }
53462
53463 if ( typeof options != 'undefined') {
53464 $.extend(this.options, options);
53465 }
53466
53467 };
53468 /*
53469 * LineOverlayWidget.js
53470 *
53471 * Copyright (c) 2013, Sebastian Kruse. All rights reserved.
53472 *
53473 * This library is free software; you can redistribute it and/or
53474 * modify it under the terms of the GNU Lesser General Public
53475 * License as published by the Free Software Foundation; either
53476 * version 3 of the License, or (at your option) any later version.
53477 *
53478 * This library is distributed in the hope that it will be useful,
53479 * but WITHOUT ANY WARRANTY; without even the implied warranty of
53480 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
53481 * Lesser General Public License for more details.
53482 *
53483 * You should have received a copy of the GNU Lesser General Public
53484 * License along with this library; if not, write to the Free Software
53485 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
53486 * MA 02110-1301 USA
53487 */
53488
53489 //calculate angle between line and x-axis
53490 //credits: geometricnet (http://geometricnet.sourceforge.net/examples/directions.html)
53491 bearing = function(x1,y1,x2,y2) {
53492 b_x = 0;
53493 b_y = 1;
53494 a_x = x2 - x1;
53495 a_y = y2 - y1;
53496 angle_rad = Math.acos((a_x*b_x+a_y*b_y)/Math.sqrt(a_x*a_x+a_y*a_y)) ;
53497 angle = 360/(2*Math.PI)*angle_rad;
53498 if (a_x < 0) {
53499 return 360 - angle;
53500 } else {
53501 return angle;
53502 }
53503 };
53504
53505 /**
53506 * @class LineOverlayWidget
53507 * Implementation for the widget interactions of an overlay showing lines between points
53508 * @author Sebastian Kruse (skruse@mpiwg-berlin.mpg.de)
53509 *
53510 * @param {WidgetWrapper} core wrapper for interaction to other widgets
53511 * @param {JSON} options user specified configuration that overwrites options in OverlayloaderConfig.js
53512 */
53513 LineOverlayWidget = function (core, options) {
53514
53515 this.core = core;
53516 this.core.setWidget(this);
53517
53518 this.options = (new LineOverlayConfig(options)).options;
53519
53520 this.attachedMapWidgets = new Array();
53521
53522 this.lineOverlay = new LineOverlay(this);
53523 this.lines = [];
53524 this.multiLineFeature;
53525
53526 this.selected = [];
53527 }
53528
53529 /**
53530 * @param {Number} dataSet number of dataSet in dataSet array
53531 * @param {Number} objectID number of DataObject in objects array
53532 */
53533
53534 function Line(objectStart, objectEnd ) {
53535 this.objectStart = objectStart;
53536 this.objectEnd = objectEnd;
53537 }
53538
53539 LineOverlayWidget.prototype = {
53540
53541 initWidget : function() {
53542 var lineOverlayWidget = this;
53543 this.drawLines();
53544 },
53545
53546 highlightChanged : function(objects) {
53547 if( !GeoTemConfig.highlightEvents ){
53548 return;
53549 }
53550 this.drawLines(GeoTemConfig.mergeObjects(objects,this.selected));
53551 },
53552
53553 selectionChanged : function(selection) {
53554 if( !GeoTemConfig.selectionEvents ){
53555 return;
53556 }
53557 if (selection.valid())
53558 this.selected = selection.objects;
53559 else
53560 this.selected = [];
53561
53562 this.drawLines(this.selected);
53563 },
53564
53565 triggerHighlight : function(item) {
53566 },
53567
53568 tableSelection : function() {
53569 },
53570
53571 deselection : function() {
53572 },
53573
53574 filtering : function() {
53575 },
53576
53577 inverseFiltering : function() {
53578 },
53579
53580 triggerRefining : function() {
53581 },
53582
53583 reset : function() {
53584 },
53585
53586 //identical to the function in PieChartWidget
53587 //here cause widgets may be used independed of each other
53588 getElementData : function(dataObject, watchedColumn, selectionFunction) {
53589 var columnData;
53590 if (watchedColumn.indexOf("[") === -1){
53591 columnData = dataObject[watchedColumn];
53592 if (typeof columnData === "undefined"){
53593 columnData = dataObject.tableContent[watchedColumn];
53594 };
53595 } else {
53596 try {
53597 var columnName = watchedColumn.split("[")[0];
53598 var IndexAndAttribute = watchedColumn.split("[")[1];
53599 if (IndexAndAttribute.indexOf("]") != -1){
53600 var arrayIndex = IndexAndAttribute.split("]")[0];
53601 var attribute = IndexAndAttribute.split("]")[1];
53602
53603 if (typeof attribute === "undefined")
53604 columnData = dataObject[columnName][arrayIndex];
53605 else{
53606 attribute = attribute.split(".")[1];
53607 columnData = dataObject[columnName][arrayIndex][attribute];
53608 }
53609 }
53610 } catch(e) {
53611 if (typeof console !== undefined)
53612 console.error(e);
53613
53614 delete columnData;
53615 }
53616 }
53617
53618 if ( (typeof columnData !== "undefined") && (typeof selectionFunction !== "undefined") )
53619 columnData = selectionFunction(columnData);
53620
53621 return(columnData);
53622 },
53623
53624 matchColumns : function(dataSet1, columnName1, dataSet2, columnName2) {
53625 var lineOverlayWidget = this;
53626 lineOverlayWidget.lines;
53627 $(GeoTemConfig.datasets[dataSet1].objects).each(function(){
53628 var object1 = this;
53629 var data1 = lineOverlayWidget.getElementData(object1, columnName1);
53630 //split because there could be multiple comma separated values
53631 data1 = data1.split(",");
53632
53633 $(GeoTemConfig.datasets[dataSet2].objects).each(function(){
53634 var object2 = this;
53635 //avoid reflexive and double entries
53636 if ((columnName1 === columnName2)&&(dataSet1 === dataSet2)&&(object1.index<=object2.index))
53637 return;
53638 var data2 = lineOverlayWidget.getElementData(object2, columnName2);
53639 //split because there could be multiple comma separated values
53640 data2 = data2.split(",");
53641
53642 //check if at least one pair matches
53643 for(var i = 0; i < data1.length; i++ ){
53644 var firstVal = data1[i];
53645 if (data2.indexOf(firstVal) !== -1){
53646 lineOverlayWidget.lines.push(new Line(object1, object2));
53647 break;
53648 }
53649 }
53650 });
53651 });
53652 },
53653
53654 getXYofObject : function(cs,dataObject){
53655 //iterata over datasets
53656 var x,y;
53657 var found = false;
53658 $(cs).each(function(){
53659 //iterate over circles
53660 $(this).each(function(){
53661 var circle = this;
53662 //iterata over objects in this circle;
53663 var index = $.inArray(dataObject,circle.elements);
53664 if (index !== -1){
53665 x = circle.feature.geometry.x;
53666 y = circle.feature.geometry.y;
53667 found = true;
53668 return false;
53669 }
53670 });
53671 //break loop
53672 if (found === true)
53673 return false;
53674 });
53675
53676 return ({x:x,y:y});
53677 },
53678
53679 /**
53680 * @param {DataObjects[][]} objects set of objects to limit to
53681 */
53682 drawLines : function(objects) {
53683 var flatObjects = [];
53684 if ( (typeof objects !== "undefined") &&
53685 (objects instanceof Array) &&
53686 (objects.length > 0) ) {
53687 $(objects).each(function(){
53688 $.merge(flatObjects, this);
53689 });
53690 }
53691 var lineOverlayWidget = this;
53692
53693 $(lineOverlayWidget.attachedMapWidgets).each(function(){
53694 var mapWidget = this.mapWidget;
53695 var lineLayer = this.lineLayer;
53696
53697 var map = mapWidget.openlayersMap;
53698 var cs = mapWidget.mds.getObjectsByZoom();
53699
53700 mapWidget.openlayersMap.setLayerIndex(lineLayer, 99);
53701
53702 lineLayer.removeAllFeatures();
53703
53704 var lineElements = [];
53705
53706 var checkIfLineInPreset = function(){return false;};
53707 if (lineOverlayWidget.options.showLines === "inbound"){
53708 checkIfLineInPreset = function(objectStart,objectEnd,flatObjects){
53709 return ($.inArray(objectEnd, flatObjects) === -1);
53710 };
53711 } else if (lineOverlayWidget.options.showLines === "outbound"){
53712 checkIfLineInPreset = function(objectStart,objectEnd,flatObjects){
53713 return ($.inArray(objectStart, flatObjects) === -1);
53714 };
53715 } else /*if (lineOverlayWidget.options.showLines === "both")*/{
53716 checkIfLineInPreset = function(objectStart,objectEnd,flatObjects){
53717 return ( ($.inArray(objectStart, flatObjects) === -1) &&
53718 ($.inArray(objectEnd, flatObjects) === -1) );
53719 };
53720 }
53721
53722 $(lineOverlayWidget.lines).each(function(){
53723 var line = this;
53724
53725 if ((lineOverlayWidget.options.onlyShowSelectedOrHighlighted === true) || (flatObjects.length > 0)){
53726 //if objects are limited, check whether start or end are within
53727 if (checkIfLineInPreset(line.objectStart, line.objectEnd, flatObjects))
53728 return;
53729 }
53730 //get XY-val of start Object
53731 var xyStart = lineOverlayWidget.getXYofObject(cs, line.objectStart);
53732 //continue if no valid XY-coords where found
53733 if ( (typeof xyStart.x === "undefined") && (typeof xyStart.y === "undefined") )
53734 return;
53735 var xyEnd = lineOverlayWidget.getXYofObject(cs, line.objectEnd);
53736 //continue if no valid XY-coords where found
53737 if ( (typeof xyEnd.x === "undefined") && (typeof xyEnd.y === "undefined") )
53738 return;
53739
53740 //do not draw 0-length lines (from same circle)
53741 if ( (xyStart.x === xyEnd.x) && (xyStart.y === xyEnd.y) )
53742 return;
53743
53744 var points = new Array(
53745 new OpenLayers.Geometry.Point(xyStart.x, xyStart.y),
53746 new OpenLayers.Geometry.Point(xyEnd.x, xyEnd.y)
53747 );
53748
53749 var line = new OpenLayers.Geometry.LineString(points);
53750
53751 //Only draw each line once. Unfortunately this check is faster
53752 //than drawing multiple lines.
53753 var found = false;
53754 $(lineElements).each(function(){
53755 var checkLine = this.line;
53756 if (( (checkLine.components[0].x === line.components[0].x) &&
53757 (checkLine.components[0].y === line.components[0].y) &&
53758 (checkLine.components[1].x === line.components[1].x) &&
53759 (checkLine.components[1].y === line.components[1].y) ) ||
53760 // if lines are "directional" (arrows) the opposite one isn't the same anymore!
53761 ( (lineOverlayWidget.options.showArrows === false) &&
53762 (checkLine.components[0].x === line.components[1].x) &&
53763 (checkLine.components[0].y === line.components[1].y) &&
53764 (checkLine.components[1].x === line.components[0].x) &&
53765 (checkLine.components[1].y === line.components[0].y) ) ){
53766 found = true;
53767 //increase width of this line
53768 this.width++;
53769 //and don't draw it again
53770 return false;
53771 }
53772 });
53773
53774 if (found === true)
53775 return;
53776
53777 lineElements.push({line:line,width:1});
53778 });
53779
53780 $(lineElements).each(function(){
53781 var line = this.line;
53782 var width = this.width;
53783
53784 if (lineOverlayWidget.options.showArrows === true){
53785 var xyStart = line.components[0];
53786 var xyEnd = line.components[1];
53787 var arrowFeature = new OpenLayers.Feature.Vector(
53788 new OpenLayers.Geometry.Point(xyEnd.x-((xyEnd.x-xyStart.x)*0.03), xyEnd.y-((xyEnd.y-xyStart.y)*0.03)),
53789 {
53790 type: "triangle",
53791 angle: bearing(xyStart.x,xyStart.y,xyEnd.x,xyEnd.y),
53792 width: width+1
53793 }
53794 );
53795 lineLayer.addFeatures(arrowFeature);
53796 }
53797
53798 var lineFeature = new OpenLayers.Feature.Vector(line,{width:width});
53799 lineLayer.addFeatures(lineFeature);
53800 });
53801 });
53802 },
53803
53804 attachMapWidget : function(mapWidget) {
53805 var styles = new OpenLayers.StyleMap({
53806 "default": {
53807 graphicName: "${type}",
53808 rotation: "${angle}",
53809 pointRadius: "${width}",
53810 strokeColor: '#0000ff',
53811 strokeOpacity: 0.5,
53812 strokeWidth: "${width}",
53813 fillOpacity: 1
53814 }
53815 });
53816
53817 var lineOverlayWidget = this;
53818 var lineLayer = new OpenLayers.Layer.Vector("Line Layer", {
53819 styleMap: styles,
53820 isBaseLayer:false
53821 });
53822 mapWidget.openlayersMap.addLayer(lineLayer);
53823 mapWidget.openlayersMap.setLayerIndex(lineLayer, 99);
53824 this.attachedMapWidgets.push({mapWidget:mapWidget,lineLayer:lineLayer});
53825 //register zoom event
53826 mapWidget.openlayersMap.events.register("zoomend", lineOverlayWidget, function(){
53827 this.drawLines(this.selected);
53828 });
53829 }
53830 };
53831 /*
53832 * DataObject.js
53833 *
53834 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
53835 *
53836 * This library is free software; you can redistribute it and/or
53837 * modify it under the terms of the GNU Lesser General Public
53838 * License as published by the Free Software Foundation; either
53839 * version 3 of the License, or (at your option) any later version.
53840 *
53841 * This library is distributed in the hope that it will be useful,
53842 * but WITHOUT ANY WARRANTY; without even the implied warranty of
53843 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
53844 * Lesser General Public License for more details.
53845 *
53846 * You should have received a copy of the GNU Lesser General Public
53847 * License along with this library; if not, write to the Free Software
53848 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
53849 * MA 02110-1301 USA
53850 */
53851
53852 /**
53853 * @class DataObject
53854 * GeoTemCo's data object class
53855 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
53856 * @release 1.0
53857 * @release date: 2012-07-27
53858 * @version date: 2012-07-27
53859 *
53860 * @param {String} name name of the data object
53861 * @param {String} description description of the data object
53862 * @param {JSON} locations a list of locations with longitude, latitide and place name
53863 * @param {JSON} dates a list of dates
53864 * @param {float} lon longitude value of the given place
53865 * @param {float} lat latitude value of the given place
53866 * @param {Date} timeStart start time of the data object
53867 * @param {Date} timeEnd end time of the data object
53868 * @param {int} granularity granularity of the given time
53869 * @param {int} weight weight of the time object
53870 * @param {Openlayers.Projection} projection of the coordinates (optional)
53871 */
53872
53873 DataObject = function(name, description, locations, dates, weight, tableContent, projection) {
53874
53875 this.name = $.trim(name);
53876 this.description = $.trim(description);
53877 this.weight = weight;
53878 this.tableContent = new Object();
53879 var objectTableContent = this.tableContent;
53880 for(key in tableContent){
53881 value = tableContent[key];
53882 objectTableContent[$.trim(key)]=$.trim(value);
53883 }
53884
53885 this.percentage = 0;
53886 this.setPercentage = function(percentage) {
53887 this.percentage = percentage;
53888 }
53889
53890 this.locations = [];
53891 var objectLocations = this.locations;
53892 $(locations).each(function(){
53893 objectLocations.push({
53894 latitude:this.latitude,
53895 longitude:this.longitude,
53896 place:$.trim(this.place)
53897 });
53898 });
53899
53900 //Check if locations are valid
53901 if (!(projection instanceof OpenLayers.Projection)){
53902 //per default GeoTemCo uses WGS84 (-90<=lat<=90, -180<=lon<=180)
53903 projection = new OpenLayers.Projection("EPSG:4326");
53904 }
53905 this.projection = projection;
53906
53907 var tempLocations = [];
53908 if (typeof this.locations !== "undefined"){
53909 $(this.locations).each(function(){
53910 //EPSG:4326 === WGS84
53911 this.latitude = parseFloat(this.latitude);
53912 this.longitude = parseFloat(this.longitude);
53913 if (projection.getCode() === "EPSG:4326"){
53914 if ( (typeof this.latitude === "number") &&
53915 (this.latitude>=-90) &&
53916 (this.latitude<=90) &&
53917 (typeof this.longitude === "number") &&
53918 (this.longitude>=-180) &&
53919 (this.longitude<=180) )
53920 tempLocations.push(this);
53921 else{
53922 if ((GeoTemConfig.debug)&&(typeof console !== undefined)){
53923 console.error("Object " + name + " has no valid coordinate. ("+this.latitude+","+this.longitude+")");
53924 }
53925 }
53926
53927 //solve lat=-90 bug
53928 if( this.longitude == 180 ){
53929 this.longitude = 179.999;
53930 }
53931 if( this.longitude == -180 ){
53932 this.longitude = -179.999;
53933 }
53934 if( this.latitude == 90 ){
53935 this.latitude = 89.999;
53936 }
53937 if( this.latitude == -90 ){
53938 this.latitude = -89.999;
53939 }
53940 }
53941 });
53942 this.locations = tempLocations;
53943 }
53944
53945 this.isGeospatial = false;
53946 if ((typeof this.locations !== "undefined") && (this.locations.length > 0)) {
53947 this.isGeospatial = true;
53948 }
53949
53950 this.placeDetails = [];
53951 for (var i = 0; i < this.locations.length; i++) {
53952 this.placeDetails.push(this.locations[i].place.split("/"));
53953 }
53954
53955 this.getLatitude = function(locationId) {
53956 return this.locations[locationId].latitude;
53957 }
53958
53959 this.getLongitude = function(locationId) {
53960 return this.locations[locationId].longitude;
53961 }
53962
53963 this.getPlace = function(locationId, level) {
53964 if (level >= this.placeDetails[locationId].length) {
53965 return this.placeDetails[locationId][this.placeDetails[locationId].length - 1];
53966 }
53967 return this.placeDetails[locationId][level];
53968 }
53969
53970 this.dates = dates;
53971 this.isTemporal = false;
53972 if ((typeof this.dates !== "undefined") && (this.dates.length > 0)) {
53973 this.isTemporal = true;
53974 //test if we already have date "objects" or if we should parse the dates
53975 for (var i = 0; i < this.dates.length; i++){
53976 if (typeof this.dates[i] === "string"){
53977 var date = GeoTemConfig.getTimeData(this.dates[i]);
53978 //check whether we got valid dates
53979 if ((typeof date !== "undefined")&&(date != null)){
53980 this.dates[i] = date;
53981 } else {
53982 //at least one date is invalid, so this dataObject has
53983 //no valid date information and is therefor not "temporal"
53984 this.isTemporal = false;
53985 break;
53986 }
53987 }
53988 }
53989 }
53990
53991 //TODO: allow more than one timespan (as with dates/places)
53992 this.isFuzzyTemporal = false;
53993 if (this.isTemporal) {
53994 this.isTemporal = false;
53995 this.isFuzzyTemporal = true;
53996
53997 var date = this.dates[0].date;
53998 var granularity = this.dates[0].granularity;
53999
54000 this.TimeSpanGranularity = granularity;
54001
54002 if (granularity === SimileAjax.DateTime.YEAR){
54003 this.TimeSpanBegin = moment(date).startOf("year");
54004 this.TimeSpanEnd = moment(date).endOf("year");
54005 } else if (granularity === SimileAjax.DateTime.MONTH){
54006 this.TimeSpanBegin = moment(date).startOf("month");
54007 this.TimeSpanEnd = moment(date).endOf("month");
54008 } else if (granularity === SimileAjax.DateTime.DAY){
54009 this.TimeSpanBegin = moment(date).startOf("day");
54010 this.TimeSpanEnd = moment(date).endOf("day");
54011 } else if (granularity === SimileAjax.DateTime.HOUR){
54012 this.TimeSpanBegin = moment(date).startOf("hour");
54013 this.TimeSpanEnd = moment(date).endOf("hour");
54014 } else if (granularity === SimileAjax.DateTime.MINUTE){
54015 this.TimeSpanBegin = moment(date).startOf("minute");
54016 this.TimeSpanEnd = moment(date).endOf("minute");
54017 } else if (granularity === SimileAjax.DateTime.SECOND){
54018 this.TimeSpanBegin = moment(date).startOf("second");
54019 this.TimeSpanEnd = moment(date).endOf("second");
54020 } else if (granularity === SimileAjax.DateTime.MILLISECOND){
54021 //this is a "real" exact time
54022 this.isTemporal = true;
54023 this.isFuzzyTemporal = false;
54024 }
54025 } else if ( (typeof this.tableContent["TimeSpan:begin"] !== "undefined") &&
54026 (typeof this.tableContent["TimeSpan:end"] !== "undefined") ){
54027 //parse according to ISO 8601
54028 //don't use the default "cross browser support" from moment.js
54029 //cause it won't work correctly with negative years
54030 var formats = [ "YYYYYY",
54031 "YYYYYY-MM",
54032 "YYYYYY-MM-DD",
54033 "YYYYYY-MM-DDTHH",
54034 "YYYYYY-MM-DDTHH:mm",
54035 "YYYYYY-MM-DDTHH:mm:ss",
54036 "YYYYYY-MM-DDTHH:mm:ss.SSS"
54037 ];
54038 this.TimeSpanBegin = moment(this.tableContent["TimeSpan:begin"],formats.slice());
54039 this.TimeSpanEnd = moment(this.tableContent["TimeSpan:end"],formats.slice());
54040 if ((this.TimeSpanBegin instanceof Object) && this.TimeSpanBegin.isValid() &&
54041 (this.TimeSpanEnd instanceof Object) && this.TimeSpanEnd.isValid()){
54042 //check whether dates are correctly sorted
54043 if (this.TimeSpanBegin>this.TimeSpanEnd){
54044 //dates are in the wrong order
54045 if ((GeoTemConfig.debug)&&(typeof console !== undefined))
54046 console.error("Object " + this.name + " has wrong fuzzy dating (twisted start/end?).");
54047
54048 } else {
54049 var timeSpanBeginGranularity = formats.indexOf(this.TimeSpanBegin._f);
54050 var timeSpanEndGranularity = formats.indexOf(this.TimeSpanEnd._f);
54051 var timeSpanGranularity = Math.max( timeSpanBeginGranularity,
54052 timeSpanEndGranularity );
54053
54054 //set granularity according to formats above
54055 if (timeSpanGranularity === 0){
54056 this.TimeSpanGranularity = SimileAjax.DateTime.YEAR;
54057 } else if (timeSpanGranularity === 1){
54058 this.TimeSpanGranularity = SimileAjax.DateTime.MONTH;
54059 } else if (timeSpanGranularity === 2){
54060 this.TimeSpanGranularity = SimileAjax.DateTime.DAY;
54061 } else if (timeSpanGranularity === 3){
54062 this.TimeSpanGranularity = SimileAjax.DateTime.HOUR;
54063 } else if (timeSpanGranularity === 4){
54064 this.TimeSpanGranularity = SimileAjax.DateTime.MINUTE;
54065 } else if (timeSpanGranularity === 5){
54066 this.TimeSpanGranularity = SimileAjax.DateTime.SECOND;
54067 } else if (timeSpanGranularity === 6){
54068 this.TimeSpanGranularity = SimileAjax.DateTime.MILLISECOND;
54069 }
54070
54071 if (timeSpanBeginGranularity === 0){
54072 this.TimeSpanBeginGranularity = SimileAjax.DateTime.YEAR;
54073 } else if (timeSpanBeginGranularity === 1){
54074 this.TimeSpanBeginGranularity = SimileAjax.DateTime.MONTH;
54075 } else if (timeSpanBeginGranularity === 2){
54076 this.TimeSpanBeginGranularity = SimileAjax.DateTime.DAY;
54077 } else if (timeSpanBeginGranularity === 3){
54078 this.TimeSpanBeginGranularity = SimileAjax.DateTime.HOUR;
54079 } else if (timeSpanBeginGranularity === 4){
54080 this.TimeSpanBeginGranularity = SimileAjax.DateTime.MINUTE;
54081 } else if (timeSpanBeginGranularity === 5){
54082 this.TimeSpanBeginGranularity = SimileAjax.DateTime.SECOND;
54083 } else if (timeSpanBeginGranularity === 6){
54084 this.TimeSpanBeginGranularity = SimileAjax.DateTime.MILLISECOND;
54085 }
54086
54087 if (timeSpanEndGranularity === 0){
54088 this.TimeSpanEndGranularity = SimileAjax.DateTime.YEAR;
54089 } else if (timeSpanEndGranularity === 1){
54090 this.TimeSpanEndGranularity = SimileAjax.DateTime.MONTH;
54091 } else if (timeSpanEndGranularity === 2){
54092 this.TimeSpanEndGranularity = SimileAjax.DateTime.DAY;
54093 } else if (timeSpanEndGranularity === 3){
54094 this.TimeSpanEndGranularity = SimileAjax.DateTime.HOUR;
54095 } else if (timeSpanEndGranularity === 4){
54096 this.TimeSpanEndGranularity = SimileAjax.DateTime.MINUTE;
54097 } else if (timeSpanEndGranularity === 5){
54098 this.TimeSpanEndGranularity = SimileAjax.DateTime.SECOND;
54099 } else if (timeSpanEndGranularity === 6){
54100 this.TimeSpanEndGranularity = SimileAjax.DateTime.MILLISECOND;
54101 }
54102
54103 if (this.TimeSpanEnd.year()-this.TimeSpanBegin.year() >= 1000)
54104 this.TimeSpanGranularity = SimileAjax.DateTime.MILLENNIUM;
54105 else if (this.TimeSpanEnd.year()-this.TimeSpanBegin.year() >= 100)
54106 this.TimeSpanGranularity = SimileAjax.DateTime.CENTURY;
54107 else if (this.TimeSpanEnd.year()-this.TimeSpanBegin.year() >= 10)
54108 this.TimeSpanGranularity = SimileAjax.DateTime.DECADE;
54109
54110 //also set upper bounds according to granularity
54111 //(lower bound is already correct)
54112 if (timeSpanEndGranularity === 0){
54113 this.TimeSpanEnd.endOf("year");
54114 } else if (timeSpanEndGranularity === 1){
54115 this.TimeSpanEnd.endOf("month");
54116 } else if (timeSpanEndGranularity === 2){
54117 this.TimeSpanEnd.endOf("day");
54118 } else if (timeSpanEndGranularity === 3){
54119 this.TimeSpanEnd.endOf("hour");
54120 } else if (timeSpanEndGranularity === 4){
54121 this.TimeSpanEnd.endOf("minute");
54122 } else if (timeSpanEndGranularity === 5){
54123 this.TimeSpanEnd.endOf("second");
54124 } else if (timeSpanEndGranularity === 6){
54125 //has max accuracy, so no change needed
54126 }
54127
54128 this.isFuzzyTemporal = true;
54129 }
54130 }
54131 }
54132
54133
54134 this.getDate = function(dateId) {
54135 return this.dates[dateId].date;
54136 }
54137
54138 this.getTimeGranularity = function(dateId) {
54139 return this.dates[dateId].granularity;
54140 }
54141
54142 this.setIndex = function(index) {
54143 this.index = index;
54144 }
54145
54146 this.getTimeString = function() {
54147 if (this.timeStart != this.timeEnd) {
54148 return (SimileAjax.DateTime.getTimeString(this.granularity, this.timeStart) + " - " + SimileAjax.DateTime.getTimeString(this.granularity, this.timeEnd));
54149 } else {
54150 return SimileAjax.DateTime.getTimeString(this.granularity, this.timeStart) + "";
54151 }
54152 };
54153
54154 this.contains = function(text) {
54155 var allCombined = this.name + " " + this.description + " " + this.weight + " ";
54156
54157 $.each(this.dates, function(key, value){
54158 $.each(value, function(){
54159 allCombined += this + " ";
54160 });
54161 });
54162
54163 $.each(this.locations, function(key, value){
54164 $.each(value, function(){
54165 allCombined += this + " ";
54166 });
54167 });
54168
54169 $.each(this.tableContent, function(key, value){
54170 allCombined += value + " ";
54171 });
54172
54173 return (allCombined.indexOf(text) != -1);
54174 };
54175
54176 this.hasColorInformation = false;
54177
54178 this.setColor = function(r0,g0,b0,r1,g1,b1) {
54179 this.hasColorInformation = true;
54180
54181 this.color = new Object();
54182 this.color.r0 = r0;
54183 this.color.g0 = g0;
54184 this.color.b0 = b0;
54185 this.color.r1 = r1;
54186 this.color.g1 = g1;
54187 this.color.b1 = b1;
54188 };
54189
54190 this.getColor = function() {
54191 if (!this.hasColorInformation)
54192 return;
54193
54194 color = new Object();
54195 color.r0 = this.r0;
54196 color.g0 = this.g0;
54197 color.b0 = this.b0;
54198 color.r1 = this.r1;
54199 color.g1 = this.g1;
54200 color.b1 = this.b1;
54201
54202 return color;
54203 };
54204
54205 Publisher.Publish('dataobjectAfterCreation', this);
54206 };
54207
54208 /*
54209 * Dataset.js
54210 *
54211 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
54212 *
54213 * This library is free software; you can redistribute it and/or
54214 * modify it under the terms of the GNU Lesser General Public
54215 * License as published by the Free Software Foundation; either
54216 * version 3 of the License, or (at your option) any later version.
54217 *
54218 * This library is distributed in the hope that it will be useful,
54219 * but WITHOUT ANY WARRANTY; without even the implied warranty of
54220 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
54221 * Lesser General Public License for more details.
54222 *
54223 * You should have received a copy of the GNU Lesser General Public
54224 * License along with this library; if not, write to the Free Software
54225 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
54226 * MA 02110-1301 USA
54227 */
54228
54229 /**
54230 * @class Dataset
54231 * GeoTemCo's Dataset class
54232 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
54233 * @release 1.0
54234 * @release date: 2012-07-27
54235 * @version date: 2012-07-27
54236 *
54237 * @param {Array} objects data item arrays from different datasets
54238 * @param {String} label label for the datasets
54239 */
54240 Dataset = function(objects, label, url, type) {
54241
54242 this.objects = objects;
54243 this.label = label;
54244 this.url = url;
54245 this.type = type;
54246
54247 this.color;
54248
54249 //if the user can change shapes, every dataset needs a default shape
54250 if (GeoTemConfig.allowUserShapeAndColorChange){
54251 this.graphic={
54252 shape: "circle",
54253 rotation: 0
54254 }
54255 }
54256
54257 Publisher.Publish('datasetAfterCreation', this);
54258 }
54259 /*
54260 * TimeDataSource.js
54261 *
54262 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
54263 *
54264 * This library is free software; you can redistribute it and/or
54265 * modify it under the terms of the GNU Lesser General Public
54266 * License as published by the Free Software Foundation; either
54267 * version 3 of the License, or (at your option) any later version.
54268 *
54269 * This library is distributed in the hope that it will be useful,
54270 * but WITHOUT ANY WARRANTY; without even the implied warranty of
54271 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
54272 * Lesser General Public License for more details.
54273 *
54274 * You should have received a copy of the GNU Lesser General Public
54275 * License along with this library; if not, write to the Free Software
54276 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
54277 * MA 02110-1301 USA
54278 */
54279
54280 /**
54281 * @class TimeDataSource, TimeSlice, TimeStack
54282 * implementation for aggregation of time items
54283 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
54284 * @release 1.0
54285 * @release date: 2012-07-27
54286 * @version date: 2012-07-27
54287 *
54288 * @param {JSON} options time configuration
54289 */
54290 function TimeDataSource(options) {
54291
54292 this.options = options;
54293 this.timeSlices = [];
54294 this.unit
54295 this.minDate
54296 this.maxDate
54297 this.eventSources
54298 this.events
54299 this.leftSlice
54300 this.rightSlice
54301
54302 this.hashMapping
54303
54304 };
54305
54306 TimeDataSource.prototype = {
54307
54308 findTimeUnits : function(granularity, timeUnit, pixels) {
54309
54310 var time = SimileAjax.DateTime;
54311 this.availableUnits = [];
54312 var givenUnits = SimileAjax.DateTime.gregorianUnitLengths;
54313 for (var i = 0; i < givenUnits.length; i++) {
54314 if (granularity > i) {
54315 continue;
54316 }
54317 var slices = 0;
54318 var t = new Date(this.minDate.getTime());
54319 do {
54320 time.roundDownToInterval(t, i, undefined, 1, 0);
54321 slices++;
54322 time.incrementByInterval(t, i, undefined);
54323 } while( t.getTime() <= this.maxDate.getTime() && slices < pixels+2 );
54324 if (slices > 0 && slices <= pixels) {
54325 this.availableUnits.push({
54326 unit : i,
54327 slices : slices,
54328 label : SimileAjax.DateTime.Strings[GeoTemConfig.language][i]
54329 });
54330 }
54331 }
54332 var unitDiff200 = pixels + 1;
54333 for (var i = 0; i < this.availableUnits.length; i++) {
54334 var diff = Math.abs(this.availableUnits[i].slices - 200);
54335 if (diff < unitDiff200) {
54336 unitDiff200 = diff;
54337 this.unit = this.availableUnits[i].unit;
54338 }
54339 }
54340
54341 },
54342
54343 getUnitIndex : function() {
54344 for (var i = 0; i < this.availableUnits.length; i++) {
54345 if (this.unit == this.availableUnits[i].unit) {
54346 return i;
54347 }
54348 }
54349 return 0;
54350 },
54351
54352 setTimeUnit : function(unit) {
54353 this.unit = unit;
54354 this.initializeSlices();
54355 },
54356
54357 /**
54358 * initializes the TimeDataSource
54359 * @param {Timeplot.ColumnSource[]} dataSources the column sources corresponding to the data sets
54360 * @param {Timeplot.DefaultEventSource[]} eventSources the event sources corresponding to the column sources
54361 * @param {TimeObject[][]} timeObjects an array of time objects of different sets
54362 * @param {SimileAjax.DateTime} granularity the time granularity of the given data
54363 */
54364 initialize : function(dataSources, eventSources, timeObjects, granularity, timeUnit, pixels) {
54365
54366 this.dataSources = dataSources;
54367 this.eventSources = eventSources;
54368 this.timeObjects = timeObjects;
54369
54370 this.minDate = undefined;
54371 this.maxDate = undefined;
54372 this.hashMapping = [];
54373 this.projHashMapping = [];
54374
54375 for (var i = 0; i < timeObjects.length; i++) {
54376 this.hashMapping.push([]);
54377 this.projHashMapping.push([]);
54378 for (var j = 0; j < timeObjects[i].length; j++) {
54379 var o = timeObjects[i][j];
54380 if (o.isTemporal) {
54381 var g = o.dates[this.options.timeIndex].granularity;
54382 //o.getTimeGranularity(this.options.timeIndex);
54383 if (g == null) {
54384 continue;
54385 }
54386 var time = o.dates[this.options.timeIndex].date;
54387 //o.getDate(this.options.timeIndex);
54388 if (this.minDate == undefined || time.getTime() < this.minDate.getTime()) {
54389 this.minDate = time;
54390 }
54391 if (this.maxDate == undefined || time.getTime() > this.maxDate.getTime()) {
54392 this.maxDate = time;
54393 }
54394 }
54395 }
54396 }
54397
54398 if (this.minDate == undefined) {
54399 this.minDate = this.options.defaultMinDate;
54400 this.maxDate = this.options.defaultMaxDate;
54401 }
54402
54403 this.findTimeUnits(granularity, timeUnit, pixels);
54404 this.initializeSlices();
54405
54406 },
54407
54408 initializeSlices : function() {
54409 for (var i = 0; i < this.dataSources.length; i++) {
54410 this.dataSources[i]._range = {
54411 earliestDate : null,
54412 latestDate : null,
54413 min : 0,
54414 max : 0
54415 };
54416 }
54417 this.timeSlices = [];
54418 var time = SimileAjax.DateTime;
54419 var t = new Date(this.minDate.getTime() - 0.9 * time.gregorianUnitLengths[this.unit]);
54420 do {
54421 time.roundDownToInterval(t, this.unit, undefined, 1, 0);
54422 var slice = new TimeSlice(SimileAjax.NativeDateUnit.cloneValue(t), this.timeObjects.length, this.dataSources.length);
54423 this.timeSlices.push(slice);
54424 time.incrementByInterval(t, this.unit, undefined);
54425 } while (t.getTime() <= this.maxDate.getTime() + 1.1 * time.gregorianUnitLengths[this.unit]);
54426
54427 for (var i = 0; i < this.timeObjects.length; i++) {
54428 var projId = i;
54429 if( this.dataSources.length == 1 ){
54430 projId = 0;
54431 }
54432 for (var j = 0; j < this.timeObjects[i].length; j++) {
54433 var o = this.timeObjects[i][j];
54434 if (o.isTemporal) {
54435 var date = o.dates[this.options.timeIndex].date;
54436 //o.getDate(this.options.timeIndex);
54437 for (var k = 0; k < this.timeSlices.length - 1; k++) {
54438 var t1 = this.timeSlices[k].date.getTime();
54439 var t2 = this.timeSlices[k + 1].date.getTime();
54440 var stack = null, projStack = null;
54441 if (date >= t1 && date < t2) {
54442 stack = this.timeSlices[k].getStack(i);
54443 projStack = this.timeSlices[k].getProjStack(projId);
54444 }
54445 if (k == this.timeSlices.length - 2 && date >= t2) {
54446 stack = this.timeSlices[k + 1].getStack(i);
54447 projStack = this.timeSlices[k + 1].getProjStack(projId);
54448 }
54449 if (stack != null) {
54450 stack.addObject(o);
54451 projStack.addObject(o);
54452 this.hashMapping[i][o.index] = stack;
54453 this.projHashMapping[i][o.index] = projStack;
54454 break;
54455 }
54456 }
54457 }
54458 }
54459 }
54460
54461 this.events = [];
54462 for (var i = 0; i < this.eventSources.length; i++) {
54463 var eventSet = [];
54464 for (var j = 0; j < this.timeSlices.length; j++) {
54465 var value = new Array("" + this.timeSlices[j].projStacks[i].value);
54466 eventSet.push({
54467 date : this.timeSlices[j].date,
54468 value : value
54469 });
54470 }
54471 this.eventSources[i].loadData(eventSet);
54472 this.events.push(eventSet);
54473 }
54474
54475 this.leftSlice = 0;
54476 this.rightSlice = this.timeSlices.length - 1;
54477
54478 },
54479
54480 getSliceNumber : function() {
54481 return this.timeSlices.length;
54482 },
54483
54484 /**
54485 * computes the slice index corresponding to a given time
54486 * @param {Date} time the given time
54487 * @return the corresponding slice index
54488 */
54489 getSliceIndex : function(time) {
54490 for (var i = 0; i < this.timeSlices.length; i++) {
54491 if (time == this.timeSlices[i].date) {
54492 return i;
54493 }
54494 }
54495 },
54496
54497 /**
54498 * returns the time of a specific time slice
54499 * @param {int} time the given slice index
54500 * @return the corresponding slice date
54501 */
54502 getSliceTime : function(index) {
54503 return this.timeSlices[index].date;
54504 },
54505
54506 /**
54507 * shifts the actual zoomed range
54508 * @param {int} delta the value to shift (negative for left shift, positive for right shift)
54509 * @return boolean value, if the range could be shifted
54510 */
54511 setShift : function(delta) {
54512 if (delta == 1 && this.leftSlice != 0) {
54513 this.leftSlice--;
54514 this.rightSlice--;
54515 return true;
54516 } else if (delta == -1 && this.rightSlice != this.timeSlices.length - 1) {
54517 this.leftSlice++;
54518 this.rightSlice++;
54519 return true;
54520 } else {
54521 return false;
54522 }
54523 },
54524
54525 /**
54526 * zooms the actual range
54527 * @param {int} delta the value to zoom (negative for zoom out, positive for zoom in)
54528 * @param {Date} time the corresponding time of the actual mouse position on the plot
54529 * @param {Date} leftTime the time of the left border of a selected timerange or null
54530 * @param {Date} rightTime the time of the right border of a selected timerange or null
54531 * @return boolean value, if the range could be zoomed
54532 */
54533 setZoom : function(delta, time, leftTime, rightTime) {
54534 var n1 = 0;
54535 var n2 = 0;
54536 var m = -1;
54537 if (delta > 0) {
54538 m = 1;
54539 if (leftTime != null) {
54540 n1 = this.getSliceIndex(leftTime) - this.leftSlice;
54541 n2 = this.rightSlice - this.getSliceIndex(rightTime);
54542 } else {
54543 slice = this.getSliceIndex(time);
54544 if (slice == this.leftSlice || slice == this.rightSlice) {
54545 return;
54546 }
54547 n1 = slice - 1 - this.leftSlice;
54548 n2 = this.rightSlice - slice - 1;
54549 }
54550 } else if (delta < 0) {
54551
54552 n1 = this.leftSlice;
54553 n2 = this.timeSlices.length - 1 - this.rightSlice;
54554 }
54555
54556 var zoomSlices = 2 * delta;
54557 if (Math.abs(n1 + n2) < Math.abs(zoomSlices)) {
54558 zoomSlices = n1 + n2;
54559 }
54560
54561 if (n1 + n2 == 0) {
54562 return false;
54563 }
54564
54565 var m1 = Math.round(n1 / (n1 + n2) * zoomSlices);
54566 var m2 = zoomSlices - m1;
54567
54568 this.leftSlice += m1;
54569 this.rightSlice -= m2;
54570
54571 return true;
54572 },
54573
54574 /**
54575 * resets the plots by loading data of actual zoomed range
54576 */
54577 reset : function(timeGeometry) {
54578 for (var i = 0; i < this.eventSources.length; i++) {
54579 this.eventSources[i].loadData(this.events[i].slice(this.leftSlice, this.rightSlice + 1));
54580 if (i + 1 < this.eventSources.length) {
54581 timeGeometry._earliestDate = null;
54582 timeGeometry._latestDate = null;
54583 }
54584
54585 }
54586 },
54587
54588 /**
54589 * Getter for actual zoom
54590 * @return actual zoom value
54591 */
54592 getZoom : function() {
54593 if (this.timeSlices == undefined) {
54594 return 0;
54595 }
54596 return Math.round((this.timeSlices.length - 3) / 2) - Math.round((this.rightSlice - this.leftSlice - 2) / 2);
54597 },
54598
54599 /**
54600 * Getter for date of the first timeslice
54601 * @return date of the first timeslice
54602 */
54603 earliest : function() {
54604 return this.timeSlices[0].date;
54605 },
54606
54607 /**
54608 * Getter for date of the last timeslice
54609 * @return date of the last timeslice
54610 */
54611 latest : function() {
54612 return this.timeSlices[this.timeSlices.length - 1].date;
54613 },
54614
54615 setOverlay : function(timeObjects) {
54616 for (var i = 0; i < this.timeSlices.length; i++) {
54617 this.timeSlices[i].reset();
54618 }
54619 for (var j in timeObjects ) {
54620 for (var k in timeObjects[j] ) {
54621 var o = timeObjects[j][k];
54622 if (o.isTemporal) {
54623 if (o.getTimeGranularity(this.options.timeIndex) == null) {
54624 continue;
54625 }
54626 this.hashMapping[j][o.index].overlay += o.weight;
54627 this.projHashMapping[j][o.index].overlay += o.weight;
54628 }
54629 }
54630 }
54631 },
54632
54633 size : function() {
54634 if (this.timeSlices.length == 0) {
54635 return 0;
54636 }
54637 return this.timeSlices[0].stacks.length;
54638 }
54639 };
54640
54641 /**
54642 * small class that represents a time slice of the actual timeplot.
54643 * it has a specific date and contains its corrsponding data objects as well
54644 */
54645 function TimeSlice(date, rows, projRows) {
54646
54647 this.date = date;
54648 this.selected = false;
54649
54650 this.stacks = [];
54651 this.projStacks = [];
54652 for (var i = 0; i < rows; i++) {
54653 this.stacks.push(new TimeStack());
54654 }
54655 for (var i = 0; i < projRows; i++) {
54656 this.projStacks.push(new TimeStack());
54657 }
54658
54659 this.getStack = function(row) {
54660 return this.stacks[row];
54661 };
54662
54663 this.getProjStack = function(row) {
54664 return this.projStacks[row];
54665 };
54666
54667 this.reset = function() {
54668 for (var i in this.projStacks ) {
54669 this.stacks[i].overlay = 0;
54670 this.projStacks[i].overlay = 0;
54671 }
54672 };
54673
54674 this.overlay = function() {
54675 var value = 0;
54676 for (var i in this.projStacks ) {
54677 if (this.projStacks[i].overlay > value) {
54678 value = this.projStacks[i].overlay;
54679 }
54680 }
54681 return value;
54682 };
54683
54684 };
54685
54686 /**
54687 * small class that represents a stack for a time slice which
54688 * holds items for different datasets for the specific time range
54689 */
54690 function TimeStack() {
54691
54692 this.overlay = 0;
54693 this.value = 0;
54694 this.elements = [];
54695
54696 this.addObject = function(object) {
54697 this.elements.push(object);
54698 this.value += object.weight;
54699 };
54700
54701 };
54702 /*
54703 * Binning.js
54704 *
54705 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
54706 *
54707 * This library is free software; you can redistribute it and/or
54708 * modify it under the terms of the GNU Lesser General Public
54709 * License as published by the Free Software Foundation; either
54710 * version 3 of the License, or (at your option) any later version.
54711 *
54712 * This library is distributed in the hope that it will be useful,
54713 * but WITHOUT ANY WARRANTY; without even the implied warranty of
54714 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
54715 * Lesser General Public License for more details.
54716 *
54717 * You should have received a copy of the GNU Lesser General Public
54718 * License along with this library; if not, write to the Free Software
54719 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
54720 * MA 02110-1301 USA
54721 */
54722
54723 /**
54724 * @class Binning
54725 * Calculates map aggregation with several binning algorithms
54726 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
54727 * @release 1.0
54728 * @release date: 2012-07-27
54729 * @version date: 2012-07-27
54730 */
54731 Binning = function(map, options) {
54732
54733 this.map = map;
54734 this.options = options;
54735 this.reset();
54736
54737 };
54738
54739 Binning.prototype = {
54740
54741 getSet : function() {
54742 var type = this.options.binning;
54743 if (!type) {
54744 return this.getExactBinning();
54745 } else if (type == 'generic') {
54746 return this.getGenericBinning();
54747 } else if (type == 'square') {
54748 return this.getSquareBinning();
54749 } else if (type == 'hexagonal') {
54750 return this.getHexagonalBinning();
54751 } else if (type == 'triangular') {
54752 return this.getTriangularBinning();
54753 }
54754 },
54755
54756 getExactBinning : function() {
54757 if ( typeof this.binnings['exact'] == 'undefined') {
54758 this.exactBinning();
54759 }
54760 return this.binnings['exact'];
54761 },
54762
54763 getGenericBinning : function() {
54764 if ( typeof this.binnings['generic'] == 'undefined') {
54765 this.genericBinning();
54766 }
54767 return this.binnings['generic'];
54768 },
54769
54770 getSquareBinning : function() {
54771 if ( typeof this.binnings['square'] == 'undefined') {
54772 this.squareBinning();
54773 }
54774 return this.binnings['square'];
54775 },
54776
54777 getHexagonalBinning : function() {
54778 if ( typeof this.binnings['hexagonal'] == 'undefined') {
54779 this.hexagonalBinning();
54780 }
54781 return this.binnings['hexagonal'];
54782 },
54783
54784 getTriangularBinning : function() {
54785 if ( typeof this.binnings['triangular'] == 'undefined') {
54786 this.triangularBinning();
54787 }
54788 return this.binnings['triangular'];
54789 },
54790
54791 reset : function() {
54792 this.zoomLevels = this.map.getNumZoomLevels();
54793 this.binnings = [];
54794 this.minimumRadius = this.options.minimumRadius;
54795 this.maximumRadius = this.minimumRadius;
54796 this.maximumPoints = 0;
54797 this.minArea = 0;
54798 this.maxArea = 0;
54799 },
54800
54801 getMaxRadius : function(size) {
54802 return 4 * Math.log(size) / Math.log(2);
54803 },
54804
54805 setObjects : function(objects) {
54806 this.objects = objects;
54807 for (var i = 0; i < this.objects.length; i++) {
54808 var weight = 0;
54809 for (var j = 0; j < this.objects[i].length; j++) {
54810 if (this.objects[i][j].isGeospatial) {
54811 weight += this.objects[i][j].weight;
54812 }
54813 }
54814 var r = this.getMaxRadius(weight);
54815 if (r > this.maximumRadius) {
54816 this.maximumRadius = r;
54817 this.maximumPoints = weight;
54818 this.maxArea = Math.PI * this.maximumRadius * this.maximumRadius;
54819 this.minArea = Math.PI * this.minimumRadius * this.minimumRadius;
54820 }
54821 }
54822 },
54823
54824 dist : function(x1, y1, x2, y2) {
54825 return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
54826 },
54827
54828 exactBinning : function() {
54829 var circleSets = [];
54830 var hashMaps = [];
54831 var selectionHashs = [];
54832
54833 var circleAggregates = [];
54834 var bins = [];
54835 for (var i = 0; i < this.objects.length; i++) {
54836 bins.push([]);
54837 circleAggregates.push([]);
54838 for (var j = 0; j < this.objects[i].length; j++) {
54839 var o = this.objects[i][j];
54840 if (o.isGeospatial) {
54841 if ( typeof circleAggregates[i]['' + o.getLongitude(this.options.mapIndex)] == 'undefined') {
54842 circleAggregates[i]['' + o.getLongitude(this.options.mapIndex)] = [];
54843 }
54844 if ( typeof circleAggregates[i][''+o.getLongitude(this.options.mapIndex)]['' + o.getLatitude(this.options.mapIndex)] == 'undefined') {
54845 circleAggregates[i][''+o.getLongitude(this.options.mapIndex)]['' + o.getLatitude(this.options.mapIndex)] = [];
54846 bins[i].push(circleAggregates[i][''+o.getLongitude(this.options.mapIndex)]['' + o.getLatitude(this.options.mapIndex)]);
54847 }
54848 circleAggregates[i][''+o.getLongitude(this.options.mapIndex)]['' + o.getLatitude(this.options.mapIndex)].push(o);
54849 }
54850 }
54851 }
54852
54853 var circles = [];
54854 var hashMap = [];
54855 var selectionMap = [];
54856 for (var i = 0; i < bins.length; i++) {
54857 circles.push([]);
54858 hashMap.push([]);
54859 selectionMap.push([]);
54860 for (var j = 0; j < bins[i].length; j++) {
54861 var bin = bins[i][j];
54862 var p = new OpenLayers.Geometry.Point(bin[0].getLongitude(this.options.mapIndex), bin[0].getLatitude(this.options.mapIndex), null);
54863 p.transform(this.map.displayProjection, this.map.projection);
54864 var weight = 0;
54865 for (var z = 0; z < bin.length; z++) {
54866 weight += bin[z].weight;
54867 }
54868 var radius = this.options.minimumRadius;
54869 if (this.options.noBinningRadii == 'dynamic') {
54870 radius = this.getRadius(weight);
54871 }
54872 var circle = new CircleObject(p.x, p.y, 0, 0, bin, radius, i, weight);
54873 circles[i].push(circle);
54874 for (var z = 0; z < bin.length; z++) {
54875 hashMap[i][bin[z].index] = circle;
54876 selectionMap[i][bin[z].index] = false;
54877 }
54878 }
54879 }
54880 for (var k = 0; k < this.zoomLevels; k++) {
54881 circleSets.push(circles);
54882 hashMaps.push(hashMap);
54883 selectionHashs.push(selectionMap);
54884 }
54885 this.binnings['exact'] = {
54886 circleSets : circleSets,
54887 hashMaps : hashMaps,
54888 selectionHashs : selectionHashs
54889 };
54890 },
54891
54892 genericClustering : function(objects, id) {
54893 var binSets = [];
54894 var circleSets = [];
54895 var hashMaps = [];
54896 var selectionHashs = [];
54897 var clustering = new Clustering(-20037508.34, -20037508.34, 20037508.34, 20037508.34);
54898 for (var i = 0; i < objects.length; i++) {
54899 for (var j = 0; j < objects[i].length; j++) {
54900 var o = objects[i][j];
54901 if (o.isGeospatial) {
54902 var p = new OpenLayers.Geometry.Point(o.getLongitude(this.options.mapIndex), o.getLatitude(this.options.mapIndex), null);
54903 p.transform(this.map.displayProjection, this.map.projection);
54904 var point = new Vertex(Math.floor(p.x), Math.floor(p.y), objects.length, this);
54905 point.addElement(o, o.weight, i);
54906 clustering.add(point);
54907 }
54908 }
54909 }
54910
54911 for (var i = 0; i < this.zoomLevels; i++) {
54912 var bins = [];
54913 var circles = [];
54914 var hashMap = [];
54915 var selectionMap = [];
54916 for (var j = 0; j < objects.length; j++) {
54917 circles.push([]);
54918 hashMap.push([]);
54919 selectionMap.push([]);
54920 }
54921 var resolution = this.map.getResolutionForZoom(this.zoomLevels - i - 1);
54922 clustering.mergeForResolution(resolution, this.options.circleGap, this.options.circleOverlap);
54923 for (var j = 0; j < clustering.vertices.length; j++) {
54924 var point = clustering.vertices[j];
54925 if (!point.legal) {
54926 continue;
54927 }
54928 var balls = [];
54929 for (var k = 0; k < point.elements.length; k++) {
54930 if (point.elements[k].length > 0) {
54931 balls.push({
54932 search : k,
54933 elements : point.elements[k],
54934 radius : point.radii[k],
54935 weight : point.weights[k]
54936 });
54937 }
54938 }
54939 var orderBalls = function(b1, b2) {
54940 if (b1.radius > b2.radius) {
54941 return -1;
54942 }
54943 if (b2.radius > b1.radius) {
54944 return 1;
54945 }
54946 return 0;
54947 }
54948 var fatherBin = {
54949 circles : [],
54950 length : 0,
54951 radius : point.radius / resolution,
54952 x : point.x,
54953 y : point.y
54954 };
54955 for (var k = 0; k < objects.length; k++) {
54956 fatherBin.circles.push(false);
54957 }
54958 var createCircle = function(sx, sy, ball) {
54959 var index = id || ball.search;
54960 var circle = new CircleObject(point.x, point.y, sx, sy, ball.elements, ball.radius, index, ball.weight, fatherBin);
54961 circles[ball.search].push(circle);
54962 fatherBin.circles[index] = circle;
54963 fatherBin.length++;
54964 for (var k = 0; k < ball.elements.length; k++) {
54965 hashMap[ball.search][ball.elements[k].index] = circle;
54966 selectionMap[ball.search][ball.elements[k].index] = false;
54967 }
54968 }
54969 if (balls.length == 1) {
54970 createCircle(0, 0, balls[0]);
54971 } else if (balls.length == 2) {
54972 var r1 = balls[0].radius;
54973 var r2 = balls[1].radius;
54974 createCircle(-1 * r2, 0, balls[0]);
54975 createCircle(r1, 0, balls[1]);
54976 } else if (balls.length == 3) {
54977 balls.sort(orderBalls);
54978 var r1 = balls[0].radius;
54979 var r2 = balls[1].radius;
54980 var r3 = balls[2].radius;
54981 var d = ((2 / 3 * Math.sqrt(3) - 1) / 2) * r2;
54982 var delta1 = point.radius / resolution - r1 - d;
54983 var delta2 = r1 - delta1;
54984 createCircle(-delta1, 0, balls[0]);
54985 createCircle(delta2 + r2 - 3 * d, r2, balls[1]);
54986 createCircle(delta2 + r2 - 3 * d, -1 * r3, balls[2]);
54987 // createCircle(delta2 + r3 - (3 * d * r3 / r2), -1 * r3, balls[2]);
54988 } else if (balls.length == 4) {
54989 balls.sort(orderBalls);
54990 var r1 = balls[0].radius;
54991 var r2 = balls[1].radius;
54992 var r3 = balls[2].radius;
54993 var r4 = balls[3].radius;
54994 var d = (Math.sqrt(2) - 1) * r2;
54995 createCircle(-1 * d - r2, 0, balls[0]);
54996 createCircle(r1 - r2, -1 * d - r4, balls[3]);
54997 createCircle(r1 - r2, d + r3, balls[2]);
54998 createCircle(d + r1, 0, balls[1]);
54999 }
55000 if (fatherBin.length > 1) {
55001 bins.push(fatherBin);
55002 }
55003 }
55004 circleSets.push(circles);
55005 binSets.push(bins);
55006 hashMaps.push(hashMap);
55007 selectionHashs.push(selectionMap);
55008 }
55009 circleSets.reverse();
55010 binSets.reverse();
55011 hashMaps.reverse();
55012 selectionHashs.reverse();
55013 return {
55014 circleSets : circleSets,
55015 binSets : binSets,
55016 hashMaps : hashMaps,
55017 selectionHashs : selectionHashs
55018 };
55019 },
55020
55021 genericBinning : function() {
55022 if (this.options.circlePackings || this.objects.length == 1) {
55023 this.binnings['generic'] = this.genericClustering(this.objects);
55024 } else {
55025 var circleSets = [];
55026 var hashMaps = [];
55027 var selectionHashs = [];
55028 for (var i = 0; i < this.objects.length; i++) {
55029 var sets = this.genericClustering([this.objects[i]], i);
55030 if (i == 0) {
55031 circleSets = sets.circleSets;
55032 hashMaps = sets.hashMaps;
55033 selectionHashs = sets.selectionHashs;
55034 } else {
55035 for (var j = 0; j < circleSets.length; j++) {
55036 circleSets[j] = circleSets[j].concat(sets.circleSets[j]);
55037 hashMaps[j] = hashMaps[j].concat(sets.hashMaps[j]);
55038 selectionHashs[j] = selectionHashs[j].concat(sets.selectionHashs[j]);
55039 }
55040 }
55041 }
55042 this.binnings['generic'] = {
55043 circleSets : circleSets,
55044 hashMaps : hashMaps,
55045 selectionHashs : selectionHashs
55046 };
55047 }
55048 },
55049
55050 getRadius : function(n) {
55051 if (n == 0) {
55052 return 0;
55053 }
55054 if (n == 1) {
55055 return this.minimumRadius;
55056 }
55057 return Math.sqrt((this.minArea + (this.maxArea - this.minArea) / (this.maximumPoints - 1) * (n - 1) ) / Math.PI);
55058 },
55059
55060 getBinRadius : function(n, r_max, N) {
55061 if (n == 0) {
55062 return 0;
55063 }
55064 /*
55065 function log2(x) {
55066 return (Math.log(x)) / (Math.log(2));
55067 }
55068 var r0 = this.options.minimumRadius;
55069 var r;
55070 if ( typeof r_max == 'undefined') {
55071 return r0 + n / Math.sqrt(this.options.maximumPoints);
55072 }
55073 return r0 + (r_max - r0 ) * log2(n) / log2(N);
55074 */
55075 var minArea = Math.PI * this.options.minimumRadius * this.options.minimumRadius;
55076 var maxArea = Math.PI * r_max * r_max;
55077 return Math.sqrt((minArea + (maxArea - minArea) / (N - 1) * (n - 1) ) / Math.PI);
55078 },
55079
55080 shift : function(type, bin, radius, elements) {
55081
55082 var x1 = bin.x, x2 = 0;
55083 var y1 = bin.y, y2 = 0;
55084 for (var i = 0; i < elements.length; i++) {
55085 x2 += elements[i].x / elements.length;
55086 y2 += elements[i].y / elements.length;
55087 }
55088
55089 var sx = 0, sy = 0;
55090
55091 if (type == 'square') {
55092 var dx = Math.abs(x2 - x1);
55093 var dy = Math.abs(y2 - y1);
55094 var m = dy / dx;
55095 var n = y1 - m * x1;
55096 if (dx > dy) {
55097 sx = bin.x - (x1 + bin.r - radius );
55098 sy = bin.y - (m * bin.x + n );
55099 } else {
55100 sy = bin.y - (y1 + bin.r - radius );
55101 sx = bin.x - (bin.y - n) / m;
55102 }
55103 }
55104
55105 return {
55106 x : sx,
55107 y : sy
55108 };
55109
55110 },
55111
55112 binSize : function(elements) {
55113 var size = 0;
55114 for (var i in elements ) {
55115 size += elements[i].weight;
55116 }
55117 return size;
55118 },
55119
55120 setCircleSet : function(id, binData) {
55121 var circleSets = [];
55122 var hashMaps = [];
55123 var selectionHashs = [];
55124 for (var i = 0; i < binData.length; i++) {
55125 var circles = [];
55126 var hashMap = [];
55127 var selectionMap = [];
55128 for (var j = 0; j < this.objects.length; j++) {
55129 circles.push([]);
55130 hashMap.push([]);
55131 selectionMap.push([]);
55132 }
55133 var points = [];
55134 var max = 0;
55135 var radius = 0;
55136 var resolution = this.map.getResolutionForZoom(i);
55137 for (var j = 0; j < binData[i].length; j++) {
55138 for (var k = 0; k < binData[i][j].bin.length; k++) {
55139 var bs = this.binSize(binData[i][j].bin[k]);
55140 if (bs > max) {
55141 max = bs;
55142 radius = binData[i][j].r / resolution;
55143 }
55144 }
55145 }
55146 for (var j = 0; j < binData[i].length; j++) {
55147 var bin = binData[i][j];
55148 for (var k = 0; k < bin.bin.length; k++) {
55149 if (bin.bin[k].length == 0) {
55150 continue;
55151 }
55152 var weight = this.binSize(bin.bin[k]);
55153 var r = this.getBinRadius(weight, radius, max);
55154 var shift = this.shift(id, bin, r * resolution, bin.bin[k], i);
55155 var circle = new CircleObject(bin.x - shift.x, bin.y - shift.y, 0, 0, bin.bin[k], r, k, weight);
55156 circles[k].push(circle);
55157 for (var z = 0; z < bin.bin[k].length; z++) {
55158 hashMap[k][bin.bin[k][z].index] = circle;
55159 selectionMap[k][bin.bin[k][z].index] = false;
55160 }
55161 }
55162 }
55163 circleSets.push(circles);
55164 hashMaps.push(hashMap);
55165 selectionHashs.push(selectionMap);
55166 }
55167 this.binnings[id] = {
55168 circleSets : circleSets,
55169 hashMaps : hashMaps,
55170 selectionHashs : selectionHashs
55171 };
55172 },
55173
55174 squareBinning : function() {
55175
55176 var l = 20037508.34;
55177 var area0 = l * l * 4;
55178 var binCount = this.options.binCount;
55179
55180 var bins = [];
55181 var binData = [];
55182 for (var k = 0; k < this.zoomLevels; k++) {
55183 bins.push([]);
55184 binData.push([]);
55185 }
55186
55187 for (var i = 0; i < this.objects.length; i++) {
55188 for (var j = 0; j < this.objects[i].length; j++) {
55189 var o = this.objects[i][j];
55190 if (!o.isGeospatial) {
55191 continue;
55192 }
55193 var p = new OpenLayers.Geometry.Point(o.getLongitude(this.options.mapIndex), o.getLatitude(this.options.mapIndex), null);
55194 p.transform(this.map.displayProjection, this.map.projection);
55195 o.x = p.x;
55196 o.y = p.y;
55197 for (var k = 0; k < this.zoomLevels; k++) {
55198 var bc = binCount * Math.pow(2, k);
55199 var a = 2 * l / bc;
55200 var binX = Math.floor((p.x + l) / (2 * l) * bc);
55201 var binY = Math.floor((p.y + l) / (2 * l) * bc);
55202 if ( typeof bins[k]['' + binX] == 'undefined') {
55203 bins[k]['' + binX] = [];
55204 }
55205 if ( typeof bins[k][''+binX]['' + binY] == 'undefined') {
55206 bins[k][''+binX]['' + binY] = [];
55207 for (var z = 0; z < this.objects.length; z++) {
55208 bins[k][''+binX]['' + binY].push([]);
55209 }
55210 var x = binX * a + a / 2 - l;
55211 var y = binY * a + a / 2 - l;
55212 binData[k].push({
55213 bin : bins[k][''+binX]['' + binY],
55214 x : x,
55215 y : y,
55216 a : a,
55217 r : a / 2
55218 });
55219 }
55220 bins[k][''+binX][''+binY][i].push(o);
55221 }
55222 }
55223 }
55224
55225 this.setCircleSet('square', binData);
55226
55227 },
55228
55229 triangularBinning : function() {
55230
55231 var l = 20037508.34;
55232 var a0 = this.options.binCount;
55233 var a1 = Math.sqrt(4 * a0 * a0 / Math.sqrt(3));
55234 var binCount = a0 / a1 * a0;
55235
55236 var bins = [];
55237 var binData = [];
55238 for (var k = 0; k < this.zoomLevels; k++) {
55239 bins.push([]);
55240 binData.push([]);
55241 }
55242
55243 for (var i = 0; i < this.objects.length; i++) {
55244 for (var j = 0; j < this.objects[i].length; j++) {
55245 var o = this.objects[i][j];
55246 if (!o.isGeospatial) {
55247 continue;
55248 }
55249 var p = new OpenLayers.Geometry.Point(o.getLongitude(this.options.mapIndex), o.getLatitude(this.options.mapIndex), null);
55250 p.transform(this.map.displayProjection, this.map.projection);
55251 o.x = p.x;
55252 o.y = p.y;
55253 for (var k = 0; k < this.zoomLevels; k++) {
55254 var x_bc = binCount * Math.pow(2, k);
55255 var y_bc = x_bc * x_bc / Math.sqrt(x_bc * x_bc - x_bc * x_bc / 4);
55256 var a = 2 * l / x_bc;
55257 var h = 2 * l / y_bc;
55258 var binY = Math.floor((p.y + l) / (2 * l) * y_bc);
55259 if ( typeof bins[k]['' + binY] == 'undefined') {
55260 bins[k]['' + binY] = [];
55261 }
55262 var triangleIndex;
55263 var partitionsX = x_bc * 2;
55264 var partition = Math.floor((p.x + l) / (2 * l) * partitionsX);
55265 var xMax = a / 2;
55266 var yMax = h;
55267 var x = p.x + l - partition * a / 2;
55268 var y = p.y + l - binY * h;
55269 if (binY % 2 == 0 && partition % 2 == 1 || binY % 2 == 1 && partition % 2 == 0) {
55270 if (y + yMax / xMax * x < yMax) {
55271 triangleIndex = partition;
55272 } else {
55273 triangleIndex = partition + 1;
55274 }
55275 } else {
55276 if (y > yMax / xMax * x) {
55277 triangleIndex = partition;
55278 } else {
55279 triangleIndex = partition + 1;
55280 }
55281 }
55282 if ( typeof bins[k][''+binY]['' + triangleIndex] == 'undefined') {
55283 bins[k][''+binY]['' + triangleIndex] = [];
55284 for (var z = 0; z < this.objects.length; z++) {
55285 bins[k][''+binY]['' + triangleIndex].push([]);
55286 }
55287 var r = Math.sqrt(3) / 6 * a;
55288 var x = (triangleIndex - 1) * a / 2 + a / 2 - l;
55289 var y;
55290 if (binY % 2 == 0 && triangleIndex % 2 == 0 || binY % 2 == 1 && triangleIndex % 2 == 1) {
55291 y = binY * h + h - r - l;
55292 } else {
55293 y = binY * h + r - l;
55294 }
55295 binData[k].push({
55296 bin : bins[k][''+binY]['' + triangleIndex],
55297 x : x,
55298 y : y,
55299 a : a,
55300 r : r
55301 });
55302 }
55303 bins[k][''+binY][''+triangleIndex][i].push(o);
55304 }
55305 }
55306 }
55307
55308 this.setCircleSet('triangular', binData);
55309
55310 },
55311
55312 hexagonalBinning : function() {
55313
55314 var l = 20037508.34;
55315 var a0 = this.options.binCount;
55316 var a2 = Math.sqrt(4 * a0 * a0 / Math.sqrt(3)) / Math.sqrt(6);
55317 var binCount = a0 / a2 * a0;
55318
55319 var bins = [];
55320 var binData = [];
55321 for (var k = 0; k < this.zoomLevels; k++) {
55322 bins.push([]);
55323 binData.push([]);
55324 }
55325
55326 for (var i = 0; i < this.objects.length; i++) {
55327 for (var j = 0; j < this.objects[i].length; j++) {
55328 var o = this.objects[i][j];
55329 if (!o.isGeospatial) {
55330 continue;
55331 }
55332 var p = new OpenLayers.Geometry.Point(o.getLongitude(this.options.mapIndex), o.getLatitude(this.options.mapIndex), null);
55333 p.transform(this.map.displayProjection, this.map.projection);
55334 o.x = p.x;
55335 o.y = p.y;
55336 for (var k = 0; k < this.zoomLevels; k++) {
55337 var x_bc = binCount * Math.pow(2, k);
55338 var y_bc = x_bc * x_bc / Math.sqrt(x_bc * x_bc - x_bc * x_bc / 4);
55339 var a = 2 * l / x_bc;
55340 var h = 2 * l / y_bc;
55341 var binY = Math.floor((p.y + l) / (2 * l) * y_bc);
55342 if ( typeof bins[k]['' + binY] == 'undefined') {
55343 bins[k]['' + binY] = [];
55344 }
55345 var triangleIndex;
55346 var partitionsX = x_bc * 2;
55347 var partition = Math.floor((p.x + l) / (2 * l) * partitionsX);
55348 var xMax = a / 2;
55349 var yMax = h;
55350 var x = p.x + l - partition * a / 2;
55351 var y = p.y + l - binY * h;
55352 if (binY % 2 == 0 && partition % 2 == 1 || binY % 2 == 1 && partition % 2 == 0) {
55353 if (y + yMax / xMax * x < yMax) {
55354 triangleIndex = partition;
55355 } else {
55356 triangleIndex = partition + 1;
55357 }
55358 } else {
55359 if (y > yMax / xMax * x) {
55360 triangleIndex = partition;
55361 } else {
55362 triangleIndex = partition + 1;
55363 }
55364 }
55365 if ( typeof bins[k][''+binY]['' + triangleIndex] == 'undefined') {
55366 bins[k][''+binY]['' + triangleIndex] = [];
55367 for (var z = 0; z < this.objects.length; z++) {
55368 bins[k][''+binY]['' + triangleIndex].push([]);
55369 }
55370 var r = Math.sqrt(3) / 6 * a;
55371 var x = (triangleIndex - 1) * a / 2 + a / 2 - l;
55372 var y;
55373 if (binY % 2 == 0 && triangleIndex % 2 == 0 || binY % 2 == 1 && triangleIndex % 2 == 1) {
55374 y = binY * h + h - r - l;
55375 } else {
55376 y = binY * h + r - l;
55377 }
55378 binData[k].push({
55379 bin : bins[k][''+binY]['' + triangleIndex],
55380 x : x,
55381 y : y,
55382 a : a,
55383 r : r,
55384 h : h,
55385 binX : triangleIndex,
55386 binY : binY
55387 });
55388 }
55389 bins[k][''+binY][''+triangleIndex][i].push(o);
55390 }
55391 }
55392 }
55393
55394 var hexaBins = [];
55395 var hexaBinData = [];
55396 for (var k = 0; k < this.zoomLevels; k++) {
55397 hexaBins.push([]);
55398 hexaBinData.push([]);
55399 }
55400
55401 for (var i = 0; i < binData.length; i++) {
55402 for (var j = 0; j < binData[i].length; j++) {
55403 var bin = binData[i][j];
55404 var binY = Math.floor(bin.binY / 2);
55405 var binX = Math.floor(bin.binX / 3);
55406 var x, y;
55407 var a = bin.a;
55408 var h = bin.h;
55409 if (bin.binX % 6 < 3) {
55410 if ( typeof hexaBins[i]['' + binY] == 'undefined') {
55411 hexaBins[i]['' + binY] = [];
55412 }
55413 y = binY * 2 * bin.h + bin.h - l;
55414 x = binX * 1.5 * bin.a + a / 2 - l;
55415 } else {
55416 if (bin.binY % 2 == 1) {
55417 binY++;
55418 }
55419 if ( typeof hexaBins[i]['' + binY] == 'undefined') {
55420 hexaBins[i]['' + binY] = [];
55421 }
55422 y = binY * 2 * bin.h - l;
55423 x = binX * 1.5 * bin.a + a / 2 - l;
55424 }
55425 if ( typeof hexaBins[i][''+binY]['' + binX] == 'undefined') {
55426 hexaBins[i][''+binY]['' + binX] = [];
55427 for (var z = 0; z < this.objects.length; z++) {
55428 hexaBins[i][''+binY]['' + binX].push([]);
55429 }
55430 hexaBinData[i].push({
55431 bin : hexaBins[i][''+binY]['' + binX],
55432 x : x,
55433 y : y,
55434 a : bin.a,
55435 r : bin.h
55436 });
55437 }
55438 for (var k = 0; k < bin.bin.length; k++) {
55439 for (var m = 0; m < bin.bin[k].length; m++) {
55440 hexaBins[i][''+binY][''+binX][k].push(bin.bin[k][m]);
55441 }
55442 }
55443 }
55444 }
55445
55446 this.setCircleSet('hexagonal', hexaBinData);
55447
55448 }
55449 }
55450
55451 /*
55452 * MapDataSource.js
55453 *
55454 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
55455 *
55456 * This library is free software; you can redistribute it and/or
55457 * modify it under the terms of the GNU Lesser General Public
55458 * License as published by the Free Software Foundation; either
55459 * version 3 of the License, or (at your option) any later version.
55460 *
55461 * This library is distributed in the hope that it will be useful,
55462 * but WITHOUT ANY WARRANTY; without even the implied warranty of
55463 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
55464 * Lesser General Public License for more details.
55465 *
55466 * You should have received a copy of the GNU Lesser General Public
55467 * License along with this library; if not, write to the Free Software
55468 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
55469 * MA 02110-1301 USA
55470 */
55471
55472 /**
55473 * @class MapDataSource
55474 * implementation for aggregation of map items
55475 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
55476 * @release 1.0
55477 * @release date: 2012-07-27
55478 * @version date: 2012-07-27
55479 *
55480 * @param {MapWidget} parent Widget
55481 * @param {JSON} options map configuration
55482 */
55483 function MapDataSource(parent, options) {
55484
55485 this.parent = parent;
55486 this.olMap = parent.openlayersMap;
55487 this.circleSets = [];
55488 this.binning = new Binning(this.olMap, options);
55489
55490 };
55491
55492 MapDataSource.prototype = {
55493
55494 /**
55495 * initializes the MapDataSource
55496 * @param {MapObject[][]} mapObjects an array of map objects of different sets
55497 */
55498 initialize : function(mapObjects) {
55499
55500 if (mapObjects != this.mapObjects) {
55501 this.binning.reset();
55502 this.binning.setObjects(mapObjects);
55503 }
55504 this.mapObjects = mapObjects;
55505
55506 var set = this.binning.getSet();
55507 this.circleSets = set.circleSets;
55508 this.binSets = set.binSets;
55509 this.hashMapping = set.hashMaps;
55510
55511 },
55512
55513 getObjectsByZoom : function() {
55514 var zoom = Math.floor(this.parent.getZoom());
55515 if (this.circleSets.length < zoom) {
55516 return null;
55517 }
55518 return this.circleSets[zoom];
55519 },
55520
55521 getAllObjects : function() {
55522 if (this.circleSets.length == 0) {
55523 return null;
55524 }
55525 return this.circleSets;
55526 },
55527
55528 getAllBins : function() {
55529 if (this.binSets.length == 0) {
55530 return null;
55531 }
55532 return this.binSets;
55533 },
55534
55535 clearOverlay : function() {
55536 var zoom = Math.floor(this.parent.getZoom());
55537 var circles = this.circleSets[zoom];
55538 for (var i in circles ) {
55539 for (var j in circles[i] ) {
55540 circles[i][j].reset();
55541 }
55542 }
55543 },
55544
55545 setOverlay : function(mapObjects) {
55546 var zoom = Math.floor(this.parent.getZoom());
55547 for (var j in mapObjects ) {
55548 for (var k in mapObjects[j] ) {
55549 var o = mapObjects[j][k];
55550 if (o.isGeospatial) {
55551 this.hashMapping[zoom][j][o.index].overlayElements.push(o);
55552 this.hashMapping[zoom][j][o.index].overlay += o.weight;
55553 }
55554 }
55555 }
55556 },
55557
55558 size : function() {
55559 if (this.circleSets.length == 0) {
55560 return 0;
55561 }
55562 return this.circleSets[0].length;
55563 },
55564
55565 getCircle : function(index, id) {
55566 var zoom = Math.floor(this.parent.getZoom());
55567 return this.hashMapping[zoom][index][id];
55568 }
55569 };
55570 /*
55571 * Clustering.js
55572 *
55573 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
55574 *
55575 * This library is free software; you can redistribute it and/or
55576 * modify it under the terms of the GNU Lesser General Public
55577 * License as published by the Free Software Foundation; either
55578 * version 3 of the License, or (at your option) any later version.
55579 *
55580 * This library is distributed in the hope that it will be useful,
55581 * but WITHOUT ANY WARRANTY; without even the implied warranty of
55582 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
55583 * Lesser General Public License for more details.
55584 *
55585 * You should have received a copy of the GNU Lesser General Public
55586 * License along with this library; if not, write to the Free Software
55587 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
55588 * MA 02110-1301 USA
55589 */
55590
55591 /**
55592 * @class Vertex, Edge, Triangle, Clustering, BinaryHeap
55593 * Dynamic Delaunay clustering algorithm (see GeoTemCo paper)
55594 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
55595 * @release 1.0
55596 * @release date: 2012-07-27
55597 * @version date: 2012-07-27
55598 */
55599
55600 function Vertex(x, y, categories, binning) {
55601 this.x = x;
55602 this.y = y;
55603 this.radius
55604 this.size = 0;
55605 this.elements = [];
55606 this.radii = [];
55607 this.weights = [];
55608 this.legal = true;
55609 this.binning = binning;
55610 if (categories != undefined) {
55611 for (var i = 0; i < categories; i++) {
55612 this.elements.push([]);
55613 this.weights.push(0);
55614 }
55615 }
55616 }
55617
55618 Vertex.prototype.merge = function(v0, v1) {
55619 for (var i = 0; i < v0.elements.length; i++) {
55620 this.elements[i] = v0.elements[i].concat(v1.elements[i]);
55621 this.weights[i] = v0.weights[i] + v1.weights[i];
55622 this.size += this.weights[i];
55623 }
55624 }
55625
55626 Vertex.prototype.CalculateRadius = function(resolution) {
55627 this.radii = [];
55628 for (i in this.elements ) {
55629 this.radii.push(this.binning.getRadius(this.weights[i]));
55630 }
55631 if (this.radii.length == 1) {
55632 this.radius = this.radii[0] * resolution;
55633 } else {
55634 var count = 0;
55635 var max1 = 0;
55636 var max2 = 0;
55637 for (i in this.radii ) {
55638 if (this.radii[i] != 0) {
55639 count++;
55640 }
55641 if (this.radii[i] > max1) {
55642 if (max1 > max2) {
55643 max2 = max1;
55644 }
55645 max1 = this.radii[i];
55646 } else if (this.radii[i] > max2) {
55647 max2 = this.radii[i];
55648 }
55649 }
55650 if (count == 1) {
55651 this.radius = max1 * resolution;
55652 } else if (count == 2) {
55653 this.radius = (max1 + max2) * resolution;
55654 } else if (count == 3) {
55655 var d = (2 / 3 * Math.sqrt(3) - 1) * max1;
55656 this.radius = (d + max1 + max2) * resolution;
55657 } else if (count == 4) {
55658 var d = (Math.sqrt(2) - 1) * max2;
55659 this.radius = (d + max1 + max2) * resolution;
55660 }
55661 }
55662 }
55663
55664 Vertex.prototype.addElement = function(e, weight, index) {
55665 this.elements[index].push(e);
55666 this.size += weight;
55667 this.weights[index] += weight;
55668 }
55669 function Edge(v0, v1) {
55670 this.v0 = v0;
55671 this.v1 = v1;
55672 this.leftFace
55673 this.rightFace
55674 this.legal = true;
55675 this.setLength();
55676 }
55677
55678 Edge.prototype.setLength = function() {
55679 var dx = this.v0.x - this.v1.x;
55680 var dy = this.v0.y - this.v1.y;
55681 this.length = Math.sqrt(dx * dx + dy * dy);
55682 }
55683
55684 Edge.prototype.contains = function(v) {
55685 if (this.v0 == v || this.v1 == v) {
55686 return true;
55687 }
55688 return false;
55689 }
55690
55691 Edge.prototype.replaceFace = function(f_old, f_new) {
55692 if (this.leftFace == f_old) {
55693 this.leftFace = f_new;
55694 } else if (this.rightFace == f_old) {
55695 this.rightFace = f_new;
55696 }
55697 }
55698
55699 Edge.prototype.setFace = function(f) {
55700 if (f.leftOf(this)) {
55701 this.leftFace = f;
55702 } else {
55703 this.rightFace = f;
55704 }
55705 }
55706
55707 Edge.prototype.setFaces = function(f1, f2) {
55708 if (f1.leftOf(this)) {
55709 this.leftFace = f1;
55710 this.rightFace = f2;
55711 } else {
55712 this.leftFace = f2;
55713 this.rightFace = f1;
55714 }
55715 }
55716
55717 Edge.prototype.removeFace = function(f) {
55718 if (this.leftFace == f) {
55719 this.leftFace = null;
55720 } else {
55721 this.rightFace = null;
55722 }
55723 }
55724
55725 Edge.prototype.equals = function(e) {
55726 if (this.v0 == e.v0 && this.v1 == e.v1 || this.v0 == e.v1 && this.v1 == e.v0) {
55727 return true;
55728 }
55729 return false;
55730 }
55731 function Triangle(edges) {
55732 this.edges = edges;
55733 this.setVertices();
55734 this.descendants = [];
55735 }
55736
55737 Triangle.prototype.getTriple = function(e) {
55738 var i = arrayIndex(this.edges, e);
55739 return {
55740 e_s : this.edges[(i + 1) % 3],
55741 e_p : this.edges[(i + 2) % 3],
55742 u : this.vertices[(i + 2) % 3]
55743 };
55744 }
55745
55746 Triangle.prototype.leftOf = function(e) {
55747 var i = arrayIndex(this.edges, e);
55748 if (this.vertices[i].y != this.vertices[(i + 1) % 3].y) {
55749 return this.vertices[i].y > this.vertices[(i + 1) % 3].y;
55750 }
55751 return this.vertices[i].y > this.vertices[(i + 2) % 3].y;
55752 }
55753
55754 Triangle.prototype.getNext = function(v) {
55755 var i = arrayIndex(this.vertices, v);
55756 return this.vertices[(i + 1) % 3];
55757 }
55758
55759 Triangle.prototype.oppositeEdge = function(v) {
55760 var i = arrayIndex(this.vertices, v);
55761 return this.edges[(i + 1) % 3];
55762 }
55763
55764 Triangle.prototype.contains = function(v) {
55765 return arrayIndex(this.vertices, v) != -1;
55766 }
55767
55768 Triangle.prototype.replace = function(e_old, e_new) {
55769 this.edges[arrayIndex(this.edges, e_old)] = e_new;
55770 }
55771
55772 Triangle.prototype.setVertices = function() {
55773 if (this.edges[1].v0 == this.edges[0].v0 || this.edges[1].v1 == this.edges[0].v0) {
55774 this.vertices = [this.edges[0].v1, this.edges[0].v0];
55775 } else {
55776 this.vertices = [this.edges[0].v0, this.edges[0].v1];
55777 }
55778 if (this.edges[2].v0 == this.vertices[0]) {
55779 this.vertices.push(this.edges[2].v1);
55780 } else {
55781 this.vertices.push(this.edges[2].v0);
55782 }
55783 }
55784
55785 Triangle.prototype.replaceBy = function(triangles) {
55786 this.descendants = triangles;
55787 this.edges[0].replaceFace(this, triangles[0]);
55788 this.edges[1].replaceFace(this, triangles[1]);
55789 this.edges[2].replaceFace(this, triangles[2]);
55790 }
55791
55792 Triangle.prototype.CalcCircumcircle = function() {
55793 var v0 = this.vertices[0];
55794 var v1 = this.vertices[1];
55795 var v2 = this.vertices[2];
55796 var A = v1.x - v0.x;
55797 var B = v1.y - v0.y;
55798 var C = v2.x - v0.x;
55799 var D = v2.y - v0.y;
55800 var E = A * (v0.x + v1.x) + B * (v0.y + v1.y);
55801 var F = C * (v0.x + v2.x) + D * (v0.y + v2.y);
55802 var G = 2.0 * (A * (v2.y - v1.y) - B * (v2.x - v1.x));
55803 var cx = (D * E - B * F) / G;
55804 var cy = (A * F - C * E) / G;
55805 this.center = new Vertex(cx, cy);
55806 var dx = this.center.x - v0.x;
55807 var dy = this.center.y - v0.y;
55808 this.radius_squared = dx * dx + dy * dy;
55809 };
55810
55811 Triangle.prototype.inCircumcircle = function(v) {
55812 if (this.radius_squared == undefined) {
55813 this.CalcCircumcircle();
55814 }
55815 var dx = this.center.x - v.x;
55816 var dy = this.center.y - v.y;
55817 var dist_squared = dx * dx + dy * dy;
55818 return (dist_squared <= this.radius_squared );
55819 };
55820
55821 Triangle.prototype.interior = function(v) {
55822 var v0 = this.vertices[0];
55823 var v1 = this.vertices[1];
55824 var v2 = this.vertices[2];
55825 var dotAB = (v.x - v0.x ) * (v0.y - v1.y ) + (v.y - v0.y ) * (v1.x - v0.x );
55826 var dotBC = (v.x - v1.x ) * (v1.y - v2.y ) + (v.y - v1.y ) * (v2.x - v1.x );
55827 var dotCA = (v.x - v2.x ) * (v2.y - v0.y ) + (v.y - v2.y ) * (v0.x - v2.x );
55828 if (dotAB > 0 || dotBC > 0 || dotCA > 0) {
55829 return null;
55830 } else if (dotAB < 0 && dotBC < 0 && dotCA < 0) {
55831 return this;
55832 } else if (dotAB == 0) {
55833 if (dotBC == 0) {
55834 return this.vertices[1];
55835 } else if (dotCA == 0) {
55836 return this.vertices[0];
55837 }
55838 return this.edges[0];
55839 } else if (dotBC == 0) {
55840 if (dotCA == 0) {
55841 return this.vertices[2];
55842 }
55843 return this.edges[1];
55844 } else if (dotCA == 0) {
55845 return this.edges[2];
55846 }
55847 };
55848
55849 function Clustering(xMin, yMin, xMax, yMax) {
55850 this.triangles = [];
55851 this.newTriangles = [];
55852 this.bbox = {
55853 x1 : xMin,
55854 y1 : yMin,
55855 x2 : xMax,
55856 y2 : yMax
55857 };
55858 this.CreateBoundingTriangle();
55859 this.edges = [];
55860 this.vertices = [];
55861 this.legalizes = 0;
55862 this.collapses = 0;
55863 }
55864
55865 Clustering.prototype.locate = function(v) {
55866 if (this.boundingTriangle.descendants.length == 0) {
55867 return this.boundingTriangle;
55868 }
55869 var triangles = this.boundingTriangle.descendants;
55870 while (true) {
55871 for (var i = 0; i < triangles.length; i++) {
55872 var simplex = triangles[i].interior(v);
55873 if (simplex == null) {
55874 continue;
55875 }
55876 if ( simplex instanceof Vertex || this.isLeaf(triangles[i])) {
55877 return simplex;
55878 }
55879 triangles = triangles[i].descendants;
55880 break;
55881 }
55882 }
55883 }
55884
55885 Clustering.prototype.legalize = function(v, e, t0_old) {
55886 if (!e.v0.legal && !e.v1.legal) {
55887 return;
55888 }
55889 this.legalizes++;
55890 var flip = false;
55891 var t1_old, tr1;
55892 if (e.leftFace == t0_old && e.rightFace.inCircumcircle(v)) {
55893 flip = true;
55894 t1_old = e.rightFace;
55895 } else if (e.rightFace == t0_old && e.leftFace.inCircumcircle(v)) {
55896 flip = true;
55897 t1_old = e.leftFace;
55898 }
55899 if (flip) {
55900 var tr0 = t0_old.getTriple(e);
55901 var tr1 = t1_old.getTriple(e);
55902 var e_flip = new Edge(tr0.u, tr1.u);
55903 var poly = [];
55904 poly.push(e.v0);
55905 poly.push(e_flip.v0);
55906 poly.push(e.v1);
55907 poly.push(e_flip.v1);
55908 if (!this.JordanTest(poly, e_flip)) {
55909 return;
55910 }
55911 e.legal = false;
55912 this.edges.push(e_flip);
55913 var t0_new = new Triangle([e_flip, tr0.e_p, tr1.e_s]);
55914 var t1_new = new Triangle([e_flip, tr1.e_p, tr0.e_s]);
55915 e_flip.setFaces(t0_new, t1_new);
55916 tr0.e_p.replaceFace(t0_old, t0_new);
55917 tr1.e_s.replaceFace(t1_old, t0_new);
55918 tr1.e_p.replaceFace(t1_old, t1_new);
55919 tr0.e_s.replaceFace(t0_old, t1_new);
55920 t0_old.descendants = [t0_new, t1_new];
55921 t1_old.descendants = [t0_new, t1_new];
55922 this.legalize(v, t0_new.edges[2], t0_new);
55923 this.legalize(v, t1_new.edges[1], t1_new);
55924 }
55925 }
55926
55927 Clustering.prototype.add = function(v) {
55928 this.addVertex(v, this.locate(v));
55929 }
55930
55931 Clustering.prototype.addVertex = function(v, simplex) {
55932 if ( simplex instanceof Vertex) {
55933 simplex.merge(simplex, v);
55934 } else if ( simplex instanceof Edge) {
55935 this.vertices.push(v);
55936 simplex.legal = false;
55937 var tr0 = simplex.leftFace.getTriple(simplex);
55938 var tr1 = simplex.rightFace.getTriple(simplex);
55939 var e0 = new Edge(v, tr0.u);
55940 var e1 = new Edge(v, simplex.leftFace.getNext(tr0.u));
55941 var e2 = new Edge(v, tr1.u);
55942 var e3 = new Edge(v, simplex.rightFace.getNext(tr1.u));
55943 var t0 = new Triangle([e0, tr0.e_p, e1]);
55944 var t1 = new Triangle([e1, tr1.e_s, e2]);
55945 var t2 = new Triangle([e2, tr1.e_p, e3]);
55946 var t3 = new Triangle([e3, tr0.e_s, e0]);
55947 simplex.leftFace.descendants = [t0, t3];
55948 simplex.rightFace.descendants = [t1, t2];
55949 this.edges.push(e0);
55950 this.edges.push(e1);
55951 this.edges.push(e2);
55952 this.edges.push(e3);
55953 e0.setFaces(t0, t3);
55954 e1.setFaces(t0, t1);
55955 e2.setFaces(t1, t2);
55956 e3.setFaces(t2, t3);
55957 tr0.e_p.replaceFace(simplex.leftFace, t0);
55958 tr1.e_s.replaceFace(simplex.rightFace, t1);
55959 tr1.e_p.replaceFace(simplex.rightFace, t2);
55960 tr0.e_s.replaceFace(simplex.leftFace, t3);
55961 this.legalize(v, tr0.e_p, t0);
55962 this.legalize(v, tr1.e_s, t1);
55963 this.legalize(v, tr1.e_p, t2);
55964 this.legalize(v, tr0.e_s, t3);
55965 } else {
55966 this.vertices.push(v);
55967 var e_i = new Edge(simplex.vertices[0], v);
55968 var e_j = new Edge(simplex.vertices[1], v);
55969 var e_k = new Edge(simplex.vertices[2], v);
55970 this.edges.push(e_i);
55971 this.edges.push(e_j);
55972 this.edges.push(e_k);
55973 var t0 = new Triangle([e_i, simplex.edges[0], e_j]);
55974 var t1 = new Triangle([e_j, simplex.edges[1], e_k]);
55975 var t2 = new Triangle([e_k, simplex.edges[2], e_i]);
55976 e_i.setFaces(t0, t2);
55977 e_j.setFaces(t0, t1);
55978 e_k.setFaces(t1, t2);
55979 simplex.replaceBy([t0, t1, t2]);
55980 this.legalize(v, simplex.edges[0], t0);
55981 this.legalize(v, simplex.edges[1], t1);
55982 this.legalize(v, simplex.edges[2], t2);
55983 }
55984 }
55985
55986 Clustering.prototype.isLeaf = function(t) {
55987 return t.descendants.length == 0;
55988 }
55989
55990 Clustering.prototype.CreateBoundingTriangle = function() {
55991 var dx = (this.bbox.x2 - this.bbox.x1 ) * 10;
55992 var dy = (this.bbox.y2 - this.bbox.y1 ) * 10;
55993 var v0 = new Vertex(this.bbox.x1 - dx, this.bbox.y1 - dy * 3);
55994 var v1 = new Vertex(this.bbox.x2 + dx * 3, this.bbox.y2 + dy);
55995 var v2 = new Vertex(this.bbox.x1 - dx, this.bbox.y2 + dy);
55996 var e0 = new Edge(v1, v0);
55997 var e1 = new Edge(v0, v2);
55998 var e2 = new Edge(v2, v1);
55999 v0.legal = false;
56000 v1.legal = false;
56001 v2.legal = false;
56002 this.boundingTriangle = new Triangle([e0, e1, e2]);
56003 var inf = new Triangle([e0, e1, e2]);
56004 e0.setFaces(this.boundingTriangle, inf);
56005 e1.setFaces(this.boundingTriangle, inf);
56006 e2.setFaces(this.boundingTriangle, inf);
56007 }
56008
56009 Clustering.prototype.mergeVertices = function(e) {
56010 this.collapses++;
56011 var s0 = e.v0.size;
56012 var s1 = e.v1.size;
56013 var x = (e.v0.x * s0 + e.v1.x * s1 ) / (s0 + s1 );
56014 var y = (e.v0.y * s0 + e.v1.y * s1 ) / (s0 + s1 );
56015 var v = new Vertex(x, y, e.v0.elements.length, e.v0.binning);
56016 v.merge(e.v0, e.v1);
56017
56018 e.v0.legal = false;
56019 e.v1.legal = false;
56020
56021 var hole = [];
56022 var oldFacets = [];
56023 e.legal = false;
56024
56025 var vertices = [];
56026 var traverse = function(eLeft, eRight, triangle) {
56027 eLeft.legal = false;
56028 do {
56029 var triple;
56030 if (eLeft.leftFace == triangle) {
56031 triple = eLeft.rightFace.getTriple(eLeft);
56032 oldFacets.push(eLeft.rightFace);
56033 triple.e_s.removeFace(eLeft.rightFace);
56034 triangle = eLeft.rightFace;
56035 } else {
56036 triple = eLeft.leftFace.getTriple(eLeft);
56037 oldFacets.push(eLeft.leftFace);
56038 triple.e_s.removeFace(eLeft.leftFace);
56039 triangle = eLeft.leftFace;
56040 }
56041 if (arrayIndex(hole, triple.e_s) == -1) {
56042 hole.push(triple.e_s);
56043 }
56044 vertices.push(triple.u);
56045 eLeft = triple.e_p;
56046 eLeft.legal = false;
56047 } while( eLeft != eRight );
56048 }
56049 var tr0 = e.leftFace.getTriple(e);
56050 var tr1 = e.rightFace.getTriple(e);
56051 oldFacets.push(e.leftFace);
56052 oldFacets.push(e.rightFace);
56053 traverse(tr0.e_p, tr1.e_s, e.leftFace);
56054 traverse(tr1.e_p, tr0.e_s, e.rightFace);
56055
56056 var hd = new Clustering(this.bbox.x1 - 10, this.bbox.y1 - 10, this.bbox.x2 + 10, this.bbox.y2 + 10);
56057 var hull = [];
56058 for (var i in hole ) {
56059 if (!(hole[i].leftFace == null && hole[i].rightFace == null)) {
56060 hull.push(hole[i].v0);
56061 hull.push(hole[i].v1);
56062 }
56063 }
56064 var hullVertices = [];
56065 var distinct = [];
56066 for (var i in vertices ) {
56067 if (arrayIndex(distinct, vertices[i]) == -1) {
56068 hd.add(vertices[i]);
56069 distinct.push(vertices[i]);
56070 }
56071 if (arrayIndex(hull, vertices[i]) != -1) {
56072 hullVertices.push(vertices[i]);
56073 }
56074 }
56075
56076 var newFacets = [];
56077 var isBoundary = function(e) {
56078 for (var i = 0; i < hole.length; i++) {
56079 if (hole[i].equals(e)) {
56080 return i;
56081 }
56082 }
56083 return -1;
56084 }
56085 var holeEdges = new Array(hole.length);
56086 var nonHoleEdges = [];
56087
56088 for (var i = 0; i < hd.edges.length; i++) {
56089 var e = hd.edges[i];
56090 var b = isBoundary(e);
56091 if (b != -1) {
56092 if (!e.legal) {
56093 var t1 = e.leftFace.getTriple(e);
56094 var t2 = e.rightFace.getTriple(e);
56095 var edge = new Edge(t1.u, t2.u);
56096 for (var j = 0; j < hd.edges.length; j++) {
56097 if (hd.edges[j].equals(edge) && hd.edges[j].legal) {
56098 hd.edges[j].legal = false;
56099 break;
56100 }
56101 }
56102 t1.e_p.setFace(e.leftFace);
56103 t1.e_s.setFace(e.leftFace);
56104 t2.e_p.setFace(e.rightFace);
56105 t2.e_s.setFace(e.rightFace);
56106
56107 e.legal = true;
56108 }
56109 holeEdges[b] = e;
56110 } else {
56111 nonHoleEdges.push(e);
56112 }
56113 }
56114
56115 for (var i = 0; i < holeEdges.length; i++) {
56116 var e = holeEdges[i];
56117 if (hole[i].leftFace == null) {
56118 hole[i].leftFace = e.leftFace;
56119 hole[i].leftFace.replace(e, hole[i]);
56120 if (arrayIndex(newFacets, hole[i].leftFace) == -1) {
56121 newFacets.push(hole[i].leftFace);
56122 }
56123 }
56124 if (hole[i].rightFace == null) {
56125 hole[i].rightFace = e.rightFace;
56126 hole[i].rightFace.replace(e, hole[i]);
56127 if (arrayIndex(newFacets, hole[i].rightFace) == -1) {
56128 newFacets.push(hole[i].rightFace);
56129 }
56130 }
56131 }
56132
56133 for (var i = 0; i < nonHoleEdges.length; i++) {
56134 var e = nonHoleEdges[i];
56135 if (!e.legal) {
56136 continue;
56137 }
56138 if (this.JordanTest(hullVertices, e)) {
56139 this.edges.push(e);
56140 if (arrayIndex(newFacets, e.rightFace) == -1) {
56141 newFacets.push(e.rightFace);
56142 }
56143 if (arrayIndex(newFacets, e.leftFace) == -1) {
56144 newFacets.push(e.leftFace);
56145 }
56146 }
56147 }
56148
56149 for (var i in oldFacets ) {
56150 oldFacets[i].descendants = newFacets;
56151 }
56152
56153 for (var i = 0; i < newFacets.length; i++) {
56154 var simplex = newFacets[i].interior(v);
56155 if (simplex == null) {
56156 continue;
56157 } else {
56158 this.addVertex(v, simplex);
56159 break;
56160 }
56161 }
56162
56163 return v;
56164
56165 }
56166
56167 Clustering.prototype.JordanTest = function(pol, e) {
56168 var p = new Vertex((e.v0.x + e.v1.x) * 0.5, (e.v0.y + e.v1.y) * 0.5);
56169 var inside = false;
56170 var i, j = pol.length - 1;
56171 for ( i = 0; i < pol.length; j = i++) {
56172 var p1 = pol[i];
56173 var p2 = pol[j];
56174 if ((((p1.y <= p.y) && (p.y < p2.y)) || ((p2.y <= p.y) && (p.y < p1.y))) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x))
56175 inside = !inside;
56176 }
56177 return inside;
56178 }
56179
56180 Clustering.prototype.mergeForResolution = function(resolution, circleGap, circleOverlap) {
56181 this.deleteEdges = new BinaryHeap(function(e) {
56182 return e.weight;
56183 });
56184 this.weightEdges(resolution, circleGap, circleOverlap);
56185 var index = 0;
56186 while (this.deleteEdges.size() > 0) {
56187 var e = this.deleteEdges.pop();
56188 if (e.legal) {
56189 var l = this.edges.length;
56190 var newVertex = this.mergeVertices(e);
56191 newVertex.CalculateRadius(resolution);
56192 for (var k = l; k < this.edges.length; k++) {
56193 var eNew = this.edges[k];
56194 if (eNew.legal) {
56195 if( circleGap != 0 ){
56196 eNew.weight = eNew.length / (eNew.v0.radius + eNew.v1.radius + circleGap * resolution );
56197 }
56198 else if( circleOverlap.overlap == 0 ){
56199 eNew.weight = eNew.length / (eNew.v0.radius + eNew.v1.radius);
56200 }
56201 else {
56202 var r1 = eNew.v0.radius;
56203 var r2 = eNew.v1.radius;
56204 var r = eNew.length;
56205 if( r < r1 + r2 ){
56206 if( circleOverlap.type == 'diameter' ){
56207 var ol1 = (r2-(r-r1)) / r1 / 2;
56208 var ol2 = (r1-(r-r2)) / r2 / 2;
56209 var ol = Math.max(ol1,ol2);
56210 eNew.weight = circleOverlap.overlap / ol;
56211 }
56212 if( circleOverlap.type == 'area' ){
56213 if( !(r+r1 < r2 || r+r2 < r1) ){
56214 var A = r2*r2*Math.acos((r*r+r2*r2-r1*r1)/(2*r*r2))+r1*r1*Math.acos((r*r+r1*r1-r2*r2)/(2*r*r1))-1/2*Math.sqrt((-r+r1+r2)*(r-r1+r2)*(r+r1-r2)*(r+r1+r2));
56215 var ol1 = A / (Math.PI*r1*r1);
56216 var ol2 = A / (Math.PI*r2*r2);
56217 var ol = Math.max(ol1,ol2);
56218 eNew.weight = circleOverlap.overlap / ol;
56219 }
56220 else {
56221 eNew.weight = 0;
56222 }
56223 }
56224 }
56225 }
56226 if (eNew.weight < 1) {
56227 this.deleteEdges.push(eNew);
56228 }
56229 }
56230 }
56231 }
56232 }
56233 }
56234
56235 Clustering.prototype.weightEdges = function(resolution, circleGap, circleOverlap) {
56236 for (var i = 0; i < this.vertices.length; i++) {
56237 if (this.vertices[i].legal) {
56238 this.vertices[i].CalculateRadius(resolution);
56239 }
56240 }
56241 var newEdges = [];
56242 for (var i = 0; i < this.edges.length; i++) {
56243 var e = this.edges[i];
56244 if (e.legal) {
56245 if (!e.v0.legal || !e.v1.legal) {
56246 e.weight = 1;
56247 } else {
56248 if( circleGap != 0 ){
56249 e.weight = e.length / (e.v0.radius + e.v1.radius + circleGap * resolution );
56250 }
56251 else if( circleOverlap.overlap == 0 ){
56252 e.weight = e.length / (e.v0.radius + e.v1.radius);
56253 }
56254 else {
56255 var r1 = e.v0.radius;
56256 var r2 = e.v1.radius;
56257 var r = e.length;
56258 if( r < r1 + r2 ){
56259 if( circleOverlap.type == 'diameter' ){
56260 var ol1 = (r2-(r-r1)) / r1 / 2;
56261 var ol2 = (r1-(r-r2)) / r2 / 2;
56262 var ol = Math.max(ol1,ol2);
56263 e.weight = circleOverlap.overlap / ol;
56264 }
56265 if( circleOverlap.type == 'area' ){
56266 if( !(r+r1 < r2 || r+r2 < r1) ){
56267 var A = r2*r2*Math.acos((r*r+r2*r2-r1*r1)/(2*r*r2))+r1*r1*Math.acos((r*r+r1*r1-r2*r2)/(2*r*r1))-1/2*Math.sqrt((-r+r1+r2)*(r-r1+r2)*(r+r1-r2)*(r+r1+r2));
56268 var ol1 = A / (Math.PI*r1*r1);
56269 var ol2 = A / (Math.PI*r2*r2);
56270 var ol = Math.max(ol1,ol2);
56271 e.weight = circleOverlap.overlap / ol;
56272 }
56273 else {
56274 e.weight = 0;
56275 }
56276 }
56277 }
56278 }
56279 if (e.weight < 1) {
56280 this.deleteEdges.push(e);
56281 }
56282 }
56283 newEdges.push(e);
56284 }
56285 }
56286 this.edges = newEdges;
56287 }
56288
56289 Clustering.prototype.ValidityTest = function() {
56290 console.info("Test 1: Valid Delaunay ...");
56291 /*
56292 var leafs = [];
56293 var triangles = this.boundingTriangle.descendants;
56294 var j = 0;
56295 while( triangles.length > j ){
56296 var t = triangles[j];
56297 if( t.taken == undefined ){
56298 t.taken = true;
56299 if( this.isLeaf(t) ){
56300 leafs.push(t);
56301 }
56302 else {
56303 triangles = triangles.concat(t.descendants);
56304 }
56305 }
56306 j++;
56307 }
56308 console.info(" Number of Triangles: "+leafs.length);
56309
56310 var c = 0;
56311 for( i in this.edges ){
56312 if( this.edges[i].legal ){
56313 c++;
56314 }
56315 }
56316 console.info(" Number of Edges: "+c);*/
56317 /*
56318
56319 for( var i=0; i<leafs.length; i++ ){
56320 for( var j=0; j<vertices.length; j++ ){
56321 if( !leafs[i].contains(vertices[j]) && leafs[i].inCircumcircle(vertices[j]) ){
56322 console.info(leafs[i],vertices[j]);
56323
56324 }
56325 }
56326 }
56327 */
56328
56329 //console.info("Test 2: Edges Facets (null) ...");
56330 for (i in this.edges ) {
56331 var e = this.edges[i];
56332 if (e.leftFace == null || e.rightFace == null) {
56333 console.info(e);
56334 alert();
56335 }
56336 }
56337
56338 //console.info("Test 3: Edges Facets ...");
56339 var leftOf = function(v1, v2, v) {
56340 var x2 = v1.x - v2.x;
56341 var x3 = v1.x - v.x;
56342 var y2 = v1.y - v2.y;
56343 var y3 = v1.y - v.y;
56344 if (x2 * y3 - y2 * x3 < 0) {
56345 return true;
56346 }
56347 return false;
56348 }
56349 var c = 0;
56350 for (i in this.edges ) {
56351 var e = this.edges[i];
56352 var t1 = e.leftFace.getTriple(e);
56353 var t2 = e.rightFace.getTriple(e);
56354 if (e.v0.y == e.v1.y) {
56355 if (t1.u.y > t2.u.y) {
56356 console.info("equal y conflict ...");
56357 console.info(e);
56358 alert();
56359 c++;
56360 }
56361 } else {
56362 var v1, v2;
56363 if (e.v0.y > e.v1.y) {
56364 v1 = e.v0;
56365 v2 = e.v1;
56366 } else {
56367 v1 = e.v1;
56368 v2 = e.v0;
56369 }
56370 if (!leftOf(v1, v2, t1.u)) {
56371 console.info("left right conflict ... left is right");
56372 console.info(e);
56373 alert();
56374 c++;
56375 }
56376 if (leftOf(v1, v2, t2.u)) {
56377 console.info("left right conflict ... right is left");
56378 console.info(e);
56379 alert();
56380 c++;
56381 }
56382 }
56383 }
56384 //console.info("Number of Edges: "+this.edges.length);
56385 //console.info("Number of Conflicts: "+c);
56386
56387 for (i in this.edges ) {
56388 if (this.edges[i].legal) {
56389 var e = this.edges[i];
56390 var tr0 = e.leftFace.getTriple(e);
56391 var tr1 = e.rightFace.getTriple(e);
56392 if (!tr0.e_p.legal || !tr0.e_s.legal || !tr1.e_p.legal || !tr1.e_s.legal) {
56393 console.info(e);
56394 console.info("conflict in edge continuity");
56395 return;
56396 }
56397 }
56398 }
56399
56400 }
56401 function BinaryHeap(scoreFunction) {
56402 this.content = [];
56403 this.scoreFunction = scoreFunction;
56404 }
56405
56406 BinaryHeap.prototype = {
56407 push : function(element) {
56408 // Add the new element to the end of the array.
56409 this.content.push(element);
56410 // Allow it to bubble up.
56411 this.bubbleUp(this.content.length - 1);
56412 },
56413
56414 pop : function() {
56415 // Store the first element so we can return it later.
56416 var result = this.content[0];
56417 // Get the element at the end of the array.
56418 var end = this.content.pop();
56419 // If there are any elements left, put the end element at the
56420 // start, and let it sink down.
56421 if (this.content.length > 0) {
56422 this.content[0] = end;
56423 this.sinkDown(0);
56424 }
56425 return result;
56426 },
56427
56428 remove : function(node) {
56429 var len = this.content.length;
56430 // To remove a value, we must search through the array to find
56431 // it.
56432 for (var i = 0; i < len; i++) {
56433 if (this.content[i] == node) {
56434 // When it is found, the process seen in 'pop' is repeated
56435 // to fill up the hole.
56436 var end = this.content.pop();
56437 if (i != len - 1) {
56438 this.content[i] = end;
56439 if (this.scoreFunction(end) < this.scoreFunction(node))
56440 this.bubbleUp(i);
56441 else
56442 this.sinkDown(i);
56443 }
56444 return;
56445 }
56446 }
56447 throw new Error("Node not found.");
56448 },
56449
56450 size : function() {
56451 return this.content.length;
56452 },
56453
56454 bubbleUp : function(n) {
56455 // Fetch the element that has to be moved.
56456 var element = this.content[n];
56457 // When at 0, an element can not go up any further.
56458 while (n > 0) {
56459 // Compute the parent element's index, and fetch it.
56460 var parentN = Math.floor((n + 1) / 2) - 1, parent = this.content[parentN];
56461 // Swap the elements if the parent is greater.
56462 if (this.scoreFunction(element) < this.scoreFunction(parent)) {
56463 this.content[parentN] = element;
56464 this.content[n] = parent;
56465 // Update 'n' to continue at the new position.
56466 n = parentN;
56467
56468 }
56469 // Found a parent that is less, no need to move it further.
56470 else {
56471 break;
56472 }
56473 }
56474 },
56475
56476 sinkDown : function(n) {
56477 // Look up the target element and its score.
56478 var length = this.content.length, element = this.content[n], elemScore = this.scoreFunction(element);
56479
56480 while (true) {
56481 // Compute the indices of the child elements.
56482 var child2N = (n + 1) * 2, child1N = child2N - 1;
56483 // This is used to store the new position of the element,
56484 // if any.
56485 var swap = null;
56486 // If the first child exists (is inside the array)...
56487 if (child1N < length) {
56488 // Look it up and compute its score.
56489 var child1 = this.content[child1N], child1Score = this.scoreFunction(child1);
56490 // If the score is less than our element's, we need to swap.
56491 if (child1Score < elemScore)
56492 swap = child1N;
56493 }
56494 // Do the same checks for the other child.
56495 if (child2N < length) {
56496 var child2 = this.content[child2N], child2Score = this.scoreFunction(child2);
56497 if (child2Score < (swap == null ? elemScore : child1Score))
56498 swap = child2N;
56499 }
56500
56501 // If the element needs to be moved, swap it, and continue.
56502 if (swap != null) {
56503 this.content[n] = this.content[swap];
56504 this.content[swap] = element;
56505 n = swap;
56506 }
56507 // Otherwise, we are done.
56508 else {
56509 break;
56510 }
56511 }
56512 }
56513 };
56514 /*
56515 * Dropdown.js
56516 *
56517 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
56518 *
56519 * This library is free software; you can redistribute it and/or
56520 * modify it under the terms of the GNU Lesser General Public
56521 * License as published by the Free Software Foundation; either
56522 * version 3 of the License, or (at your option) any later version.
56523 *
56524 * This library is distributed in the hope that it will be useful,
56525 * but WITHOUT ANY WARRANTY; without even the implied warranty of
56526 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
56527 * Lesser General Public License for more details.
56528 *
56529 * You should have received a copy of the GNU Lesser General Public
56530 * License along with this library; if not, write to the Free Software
56531 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
56532 * MA 02110-1301 USA
56533 */
56534
56535 /**
56536 * @class Dropdown
56537 * Implementation for Dropdown box
56538 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
56539 * @release 1.0
56540 * @release date: 2012-07-27
56541 * @version date: 2012-07-27
56542 *
56543 * @param {HTML object} parent parent div for the dropdown box
56544 * @param {Array} elements list of dropdown entries
56545 * @param {String} title dropdown button title
56546 */
56547 function Dropdown(parent, elements, title, maxListHeight) {
56548
56549 var dropdown = this;
56550 this.visibility = false;
56551 this.div = document.createElement("div");
56552 this.div.setAttribute('class', 'dropdown');
56553
56554 this.selection = document.createElement("div");
56555 this.selection.setAttribute('class', 'dropdownSelection');
56556 parent.appendChild(this.div);
56557
56558 var leftBorder = document.createElement("div");
56559 leftBorder.setAttribute('class', 'dropdownLeft');
56560 this.div.appendChild(leftBorder);
56561
56562 this.div.appendChild(this.selection);
56563
56564 var dropdownButton = document.createElement("div");
56565 this.div.appendChild(dropdownButton);
56566 if (elements.length > 1) {
56567 dropdownButton.setAttribute('class', 'dropdownButtonEnabled');
56568 } else {
56569 dropdownButton.setAttribute('class', 'dropdownButtonDisabled');
56570 }
56571 dropdownButton.onclick = function() {
56572 if (elements.length > 1) {
56573 dropdown.changeVisibility();
56574 }
56575 }
56576 dropdownButton.title = title;
56577
56578 this.getValue = function() {
56579 return this.selectedEntry.innerHTML;
56580 };
56581
56582 var entryMenu = document.createElement("div");
56583 entryMenu.setAttribute('class', 'dropdownMenu');
56584 this.div.appendChild(entryMenu);
56585 if (typeof maxListHeight !== "undefined")
56586 $(entryMenu).height(maxListHeight);
56587
56588 var entries = document.createElement("dl");
56589 var addEntry = function(e) {
56590 var entry = document.createElement("dt");
56591 entry.setAttribute('class', 'dropdownUnselectedEntry');
56592 entry.innerHTML = e.name;
56593 entry.onclick = function() {
56594 e.onclick();
56595 dropdown.changeVisibility();
56596 dropdown.changeEntries(e);
56597 }
56598 entries.appendChild(entry);
56599 e.entry = entry;
56600 }
56601 for (var i = 0; i < elements.length; i++) {
56602 addEntry(elements[i]);
56603 }
56604 entryMenu.appendChild(entries);
56605 this.selection.style.width = entryMenu.offsetWidth + "px";
56606 entryMenu.style.width = (entryMenu.offsetWidth + leftBorder.offsetWidth + dropdownButton.offsetWidth - 2) + "px";
56607 this.div.style.maxHeight = this.div.offsetHeight + "px";
56608
56609 entryMenu.style.display = 'none';
56610
56611 this.setEntry = function(index) {
56612 if ( typeof (index) == "undefined") {
56613 if ((elements) && elements.length > 0) {
56614 this.changeEntries(elements[0]);
56615 }
56616 } else {
56617 this.changeEntries(elements[index]);
56618 }
56619 }
56620
56621 this.changeEntries = function(element) {
56622 if (this.selectedEntry) {
56623 this.selectedEntry.setAttribute('class', 'dropdownUnselectedEntry');
56624 }
56625 this.selectedEntry = element.entry;
56626 this.selectedEntry.setAttribute('class', 'dropdownSelectedEntry');
56627 this.selection.innerHTML = "<div style='display:inline-block;vertical-align:middle;'>" + element.name + "</div>";
56628 }
56629
56630 this.changeVisibility = function() {
56631 this.visibility = !this.visibility;
56632 if (this.visibility) {
56633 entryMenu.style.display = "block";
56634 } else {
56635 entryMenu.style.display = "none";
56636 }
56637 }
56638 }
56639 /*
56640 * MapZoomSlider.js
56641 *
56642 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
56643 *
56644 * This library is free software; you can redistribute it and/or
56645 * modify it under the terms of the GNU Lesser General Public
56646 * License as published by the Free Software Foundation; either
56647 * version 3 of the License, or (at your option) any later version.
56648 *
56649 * This library is distributed in the hope that it will be useful,
56650 * but WITHOUT ANY WARRANTY; without even the implied warranty of
56651 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
56652 * Lesser General Public License for more details.
56653 *
56654 * You should have received a copy of the GNU Lesser General Public
56655 * License along with this library; if not, write to the Free Software
56656 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
56657 * MA 02110-1301 USA
56658 */
56659
56660 /**
56661 * @class MapZoomSlider
56662 * GeoTemCo style for map zoom control
56663 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
56664 * @release 1.0
56665 * @release date: 2012-07-27
56666 * @version date: 2012-07-27
56667 */
56668 function MapZoomSlider(parent, orientation) {
56669
56670 this.parent = parent;
56671
56672 var zs = this;
56673 this.div = document.createElement("div");
56674 this.div.setAttribute('class', 'sliderStyle-' + orientation);
56675
56676 var sliderContainer = document.createElement("div");
56677 sliderContainer.setAttribute('class', 'zoomSliderContainer-' + orientation);
56678 var sliderDiv = document.createElement("div");
56679 sliderDiv.tabIndex = 1;
56680 var sliderInputDiv = document.createElement("div");
56681 sliderDiv.appendChild(sliderInputDiv);
56682 sliderContainer.appendChild(sliderDiv);
56683 this.slider = new Slider(sliderDiv, sliderInputDiv, orientation);
56684 this.div.appendChild(sliderContainer);
56685
56686 var zoomIn = document.createElement("img");
56687 zoomIn.src = GeoTemConfig.path + "zoom_in.png";
56688 zoomIn.setAttribute('class', 'zoomSliderIn-' + orientation);
56689 zoomIn.onclick = function() {
56690 zs.parent.zoom(1);
56691 }
56692 this.div.appendChild(zoomIn);
56693
56694 var zoomOut = document.createElement("img");
56695 zoomOut.src = GeoTemConfig.path + "zoom_out.png";
56696 zoomOut.setAttribute('class', 'zoomSliderOut-' + orientation);
56697 zoomOut.onclick = function() {
56698 zs.parent.zoom(-1);
56699 }
56700 this.div.appendChild(zoomOut);
56701
56702 this.slider.onclick = function() {
56703 console.info(zs.slider.getValue());
56704 }
56705
56706 this.slider.handle.onmousedown = function() {
56707 var oldValue = zs.slider.getValue();
56708 document.onmouseup = function() {
56709 if (!zs.parent.zoom((zs.slider.getValue() - oldValue) / zs.max * zs.levels)) {
56710 zs.setValue(oldValue);
56711 }
56712 document.onmouseup = null;
56713 }
56714 }
56715
56716 this.setValue = function(value) {
56717 this.slider.setValue(value / this.levels * this.max);
56718 }
56719
56720 this.setMaxAndLevels = function(max, levels) {
56721 this.max = max;
56722 this.levels = levels;
56723 this.slider.setMaximum(max);
56724 }
56725 // this.setMaxAndLevels(1000,parent.openlayersMap.getNumZoomLevels());
56726 // this.setValue(parent.getZoom());
56727
56728 this.setLanguage = function() {
56729 zoomIn.title = GeoTemConfig.getString('zoomIn');
56730 zoomOut.title = GeoTemConfig.getString('zoomOut');
56731 this.slider.handle.title = GeoTemConfig.getString('zoomSlider');
56732 }
56733 }
56734 /*
56735 * MapPopup.js
56736 *
56737 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
56738 *
56739 * This library is free software; you can redistribute it and/or
56740 * modify it under the terms of the GNU Lesser General Public
56741 * License as published by the Free Software Foundation; either
56742 * version 3 of the License, or (at your option) any later version.
56743 *
56744 * This library is distributed in the hope that it will be useful,
56745 * but WITHOUT ANY WARRANTY; without even the implied warranty of
56746 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
56747 * Lesser General Public License for more details.
56748 *
56749 * You should have received a copy of the GNU Lesser General Public
56750 * License along with this library; if not, write to the Free Software
56751 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
56752 * MA 02110-1301 USA
56753 */
56754
56755 /**
56756 * @class MapPopup
56757 * map popup implementaion
56758 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
56759 * @release 1.0
56760 * @release date: 2012-07-27
56761 * @version date: 2012-07-27
56762 */
56763 function MapPopup(parent) {
56764
56765 this.parentDiv = parent.gui.mapWindow;
56766
56767 this.initialize = function(x, y, onclose) {
56768
56769 var popup = this;
56770 this.x = x;
56771 this.y = y;
56772
56773 this.popupDiv = document.createElement("div");
56774 this.popupDiv.setAttribute('class', 'ddbPopupDiv');
56775 this.parentDiv.appendChild(this.popupDiv);
56776
56777 this.cancel = document.createElement("div");
56778 this.cancel.setAttribute('class', 'ddbPopupCancel');
56779 this.cancel.title = GeoTemConfig.getString('close');
56780 this.cancel.onclick = function() {
56781 if ( typeof onclose != 'undefined') {
56782 onclose();
56783 }
56784 popup.reset();
56785 }
56786
56787 this.input = document.createElement("div");
56788 this.input.style.maxWidth = Math.floor(this.parentDiv.offsetWidth * 0.75) + "px";
56789 this.input.style.maxHeight = Math.floor(this.parentDiv.offsetHeight * 0.75) + "px";
56790 this.input.setAttribute('class', 'ddbPopupInput');
56791
56792 this.popupDiv.appendChild(this.input);
56793 this.popupDiv.appendChild(this.cancel);
56794
56795 var peak = document.createElement("div");
56796 peak.setAttribute('class', 'popupPeak');
56797 this.popupDiv.appendChild(peak);
56798 var topRight = document.createElement("div");
56799 topRight.setAttribute('class', 'popupTopRight');
56800 this.popupDiv.appendChild(topRight);
56801 var bottomRight = document.createElement("div");
56802 bottomRight.setAttribute('class', 'popupBottomRight');
56803 this.popupDiv.appendChild(bottomRight);
56804 this.popupRight = document.createElement("div");
56805 this.popupRight.setAttribute('class', 'popupRight');
56806 this.popupDiv.appendChild(this.popupRight);
56807 this.popupBottom = document.createElement("div");
56808 this.popupBottom.setAttribute('class', 'popupBottom');
56809 this.popupDiv.appendChild(this.popupBottom);
56810
56811 }
56812
56813 this.setContent = function(content) {
56814 $(this.input).empty();
56815 this.visible = true;
56816 $(this.input).append(content);
56817 this.decorate();
56818 }
56819
56820 this.reset = function() {
56821 $(this.popupDiv).remove();
56822 this.visible = false;
56823 }
56824
56825 this.decorate = function() {
56826 this.popupRight.style.height = (this.popupDiv.offsetHeight - 14) + "px";
56827 this.popupBottom.style.width = (this.popupDiv.offsetWidth - 22) + "px";
56828 this.left = this.x + 9;
56829 this.top = this.y - 10 - this.popupDiv.offsetHeight;
56830 this.popupDiv.style.left = this.left + "px";
56831 this.popupDiv.style.top = this.top + "px";
56832 var shiftX = 0, shiftY = 0;
56833 if (this.popupDiv.offsetTop < parent.gui.headerHeight + 10) {
56834 shiftY = -1 * (parent.gui.headerHeight + 10 - this.popupDiv.offsetTop);
56835 }
56836 if (this.popupDiv.offsetLeft + this.popupDiv.offsetWidth > parent.gui.headerWidth - 10) {
56837 shiftX = -1 * (parent.gui.headerWidth - 10 - this.popupDiv.offsetLeft - this.popupDiv.offsetWidth);
56838 }
56839 parent.shift(shiftX, shiftY);
56840 }
56841
56842 this.shift = function(x, y) {
56843 this.left = this.left - this.x + x;
56844 this.top = this.top - this.y + y;
56845 this.x = x;
56846 this.y = y;
56847 if (this.left + this.popupDiv.offsetWidth > this.parentDiv.offsetWidth) {
56848 this.popupDiv.style.left = 'auto';
56849 this.popupDiv.style.right = (this.parentDiv.offsetWidth - this.left - this.popupDiv.offsetWidth) + "px";
56850 } else {
56851 this.popupDiv.style.right = 'auto';
56852 this.popupDiv.style.left = this.left + "px";
56853 }
56854 this.popupDiv.style.top = this.top + "px";
56855 }
56856 }
56857 /*
56858 * PlacenamePopup.js
56859 *
56860 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
56861 *
56862 * This library is free software; you can redistribute it and/or
56863 * modify it under the terms of the GNU Lesser General Public
56864 * License as published by the Free Software Foundation; either
56865 * version 3 of the License, or (at your option) any later version.
56866 *
56867 * This library is distributed in the hope that it will be useful,
56868 * but WITHOUT ANY WARRANTY; without even the implied warranty of
56869 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
56870 * Lesser General Public License for more details.
56871 *
56872 * You should have received a copy of the GNU Lesser General Public
56873 * License along with this library; if not, write to the Free Software
56874 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
56875 * MA 02110-1301 USA
56876 */
56877
56878 /**
56879 * @class PlacenamePopup
56880 * specific map popup for showing and interacting on placename labels
56881 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
56882 * @release 1.0
56883 * @release date: 2012-07-27
56884 * @version date: 2012-07-27
56885 */
56886 function PlacenamePopup(parent) {
56887
56888 this.parentDiv = parent.gui.mapWindow;
56889
56890 this.createPopup = function(x, y, labels) {
56891 this.labels = labels;
56892 var pnPopup = this;
56893 var popup = new MapPopup(parent);
56894 var onClose = function() {
56895 parent.deselection();
56896 pnPopup.reset();
56897 }
56898 popup.initialize(x, y, onClose);
56899 $.extend(this, popup);
56900
56901 this.content = document.createElement("div");
56902 this.inner = document.createElement("div");
56903
56904 this.resultsLabel = document.createElement("div");
56905 this.resultsLabel.setAttribute('class', 'popupDDBResults');
56906 this.content.appendChild(this.resultsLabel);
56907 this.backward = document.createElement("div");
56908 this.backward.setAttribute('class', 'prevItem');
56909 this.content.appendChild(this.backward);
56910 this.backward.onclick = function() {
56911 pnPopup.descriptionIndex--;
56912 pnPopup.showDescription();
56913 }
56914
56915 this.number = document.createElement("div");
56916 this.content.appendChild(this.number);
56917 this.number.style.display = 'none';
56918 this.number.style.fontSize = '13px';
56919
56920 this.forward = document.createElement("div");
56921 this.forward.setAttribute('class', 'nextItem');
56922 this.content.appendChild(this.forward);
56923 this.forward.onclick = function() {
56924 pnPopup.descriptionIndex++;
56925 pnPopup.showDescription();
56926 }
56927 if (parent.options.showDescriptions) {
56928 this.descriptions = document.createElement("div");
56929 this.descriptions.setAttribute('class', 'descriptions');
56930 this.descriptions.onclick = function() {
56931 pnPopup.switchToDescriptionMode();
56932 }
56933 }
56934
56935 this.back = document.createElement("div");
56936 this.back.setAttribute('class', 'back');
56937 this.popupDiv.appendChild(this.back);
56938 this.back.onclick = function() {
56939 pnPopup.back.style.display = "none";
56940 pnPopup.backward.style.display = "none";
56941 pnPopup.forward.style.display = "none";
56942 pnPopup.number.style.display = 'none';
56943 pnPopup.showLabels();
56944 }
56945
56946 this.content.appendChild(this.inner);
56947 this.listLabels();
56948 this.showLabels();
56949
56950 };
56951
56952 this.switchToDescriptionMode = function() {
56953 this.descriptionIndex = 0;
56954 this.descriptionContents = this.activeLabel.descriptions;
56955 this.number.style.display = 'inline-block';
56956 this.inner.style.minWidth = "300px";
56957 this.showDescription();
56958 this.count = this.activeLabel.weight;
56959 this.setCount();
56960 this.back.style.display = "inline-block";
56961 }
56962
56963 this.showDescription = function() {
56964 $(this.inner).empty();
56965 this.inner.appendChild(this.descriptionContents[this.descriptionIndex]);
56966 this.setContent(this.content);
56967 if (this.descriptionContents.length == 1) {
56968 this.backward.style.display = "none";
56969 this.forward.style.display = "none";
56970 } else {
56971 if (this.descriptionIndex == 0) {
56972 this.backward.style.display = "none";
56973 } else {
56974 this.backward.style.display = "inline-block";
56975 }
56976 if (this.descriptionIndex == this.descriptionContents.length - 1) {
56977 this.forward.style.display = "none";
56978 } else {
56979 this.forward.style.display = "inline-block";
56980 }
56981 }
56982 if (this.descriptionContents.length > 1) {
56983 this.number.innerHTML = "#" + (this.descriptionIndex + 1);
56984 } else {
56985 this.number.style.display = 'none';
56986 }
56987 this.decorate();
56988 }
56989
56990 this.setCount = function() {
56991 var c = this.count;
56992 if (c > 1) {
56993 this.resultsLabel.innerHTML = c + " " + GeoTemConfig.getString('results');
56994 } else {
56995 this.resultsLabel.innerHTML = c + " " + GeoTemConfig.getString('result');
56996 }
56997 }
56998
56999 this.listLabels = function() {
57000 var pnPopup = this;
57001 this.labelDivs = [];
57002 this.labelCount = 0;
57003 this.labelsWidth = 0;
57004 for (var i = 0; i < this.labels.length; i++) {
57005 var div = document.createElement("div");
57006 var content = document.createElement("div");
57007 this.labels[i].allStyle += "position: relative; white-space: nowrap;";
57008 content.appendChild(this.labels[i].div);
57009 content.setAttribute('class', 'ddbPopupLabel');
57010 div.appendChild(content);
57011 this.labels[i].div.setAttribute('style', this.labels[i].allStyle + "" + this.labels[i].selectedStyle);
57012 this.input.appendChild(div);
57013 if (this.input.offsetWidth > this.labelsWidth) {
57014 this.labelsWidth = this.input.offsetWidth;
57015 }
57016 this.labels[i].div.setAttribute('style', this.labels[i].allStyle + "" + this.labels[i].unselectedStyle);
57017 this.labelDivs.push(div);
57018 var descriptions = [];
57019 for (var j = 0; j < this.labels[i].elements.length; j++) {
57020 var div = document.createElement("div");
57021 div.innerHTML = this.labels[i].elements[j].description;
57022 descriptions.push(div);
57023 }
57024 this.labels[i].descriptions = descriptions;
57025 if (this.labels[i].place != "all" || i == 0) {
57026 this.labelCount += this.labels[i].weight;
57027 }
57028 }
57029 if ( typeof this.descriptions != 'undefined') {
57030 this.labelsWidth += 20;
57031 }
57032 }
57033
57034 this.showLabels = function() {
57035 $(this.inner).empty();
57036 this.count = this.labelCount;
57037 this.setCount();
57038 for (var i = 0; i < this.labelDivs.length; i++) {
57039 this.inner.appendChild(this.labelDivs[i]);
57040 }
57041 this.inner.style.width = this.labelsWidth + "px";
57042 this.inner.style.minWidth = this.labelsWidth + "px";
57043 this.setContent(this.content);
57044 this.decorate();
57045 }
57046
57047 this.showLabelContent = function(label) {
57048 for (var i = 0; i < this.labels.length; i++) {
57049 if (this.labels[i] == label) {
57050 this.activeLabel = this.labels[i];
57051 if ( typeof this.descriptions != 'undefined') {
57052 this.labelDivs[i].appendChild(this.descriptions);
57053 }
57054 this.decorate();
57055 break;
57056 }
57057 }
57058 }
57059
57060 this.setLanguage = function(language) {
57061 this.language = language;
57062 if (this.visible) {
57063 this.updateTexts();
57064 }
57065 }
57066 };
57067 /*
57068 * Dropdown.js
57069 *
57070 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
57071 *
57072 * This library is free software; you can redistribute it and/or
57073 * modify it under the terms of the GNU Lesser General Public
57074 * License as published by the Free Software Foundation; either
57075 * version 3 of the License, or (at your option) any later version.
57076 *
57077 * This library is distributed in the hope that it will be useful,
57078 * but WITHOUT ANY WARRANTY; without even the implied warranty of
57079 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
57080 * Lesser General Public License for more details.
57081 *
57082 * You should have received a copy of the GNU Lesser General Public
57083 * License along with this library; if not, write to the Free Software
57084 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
57085 * MA 02110-1301 USA
57086 */
57087
57088 /**
57089 * @class Publisher
57090 * Publish/Subscribe mechanism
57091 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
57092 * @release 1.0
57093 * @release date: 2012-07-27
57094 * @version date: 2012-07-27
57095 */
57096 if ( typeof Publisher == 'undefined') {
57097
57098 Publisher = function() {
57099
57100 var topics = [];
57101
57102 this.Get = function(topic) {
57103 var value = topics[topic];
57104 if (!value || !(value instanceof Array)) {
57105 value = topics[topic] = [];
57106 }
57107 return value;
57108 };
57109
57110 this.Publish = function(topic, data, publisher) {
57111 var subscribers = this.Get(topic);
57112 for (var i = 0; i < subscribers.length; i++) {
57113 if (publisher == null || subscribers[i].client != publisher) {
57114 subscribers[i].callback(data);
57115 }
57116 }
57117 };
57118
57119 this.Subscribe = function(topic, subscriber, callback) {
57120 var subscribers = this.Get(topic);
57121 subscribers.push({
57122 client : subscriber,
57123 callback : callback
57124 });
57125 };
57126
57127 this.Unsubscribe = function(topic, unsubscriber) {
57128 var subscribers = this.Get(topic);
57129 for (var i = 0; i < subscribers.length; i++) {
57130 if (subscribers[i].client == unsubscriber) {
57131 subscribers.splice(i, 1);
57132 return;
57133 }
57134 }
57135 };
57136
57137 return this;
57138
57139 }();
57140
57141 }
57142 /*
57143 * WidgetWrapper.js
57144 *
57145 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
57146 *
57147 * This library is free software; you can redistribute it and/or
57148 * modify it under the terms of the GNU Lesser General Public
57149 * License as published by the Free Software Foundation; either
57150 * version 3 of the License, or (at your option) any later version.
57151 *
57152 * This library is distributed in the hope that it will be useful,
57153 * but WITHOUT ANY WARRANTY; without even the implied warranty of
57154 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
57155 * Lesser General Public License for more details.
57156 *
57157 * You should have received a copy of the GNU Lesser General Public
57158 * License along with this library; if not, write to the Free Software
57159 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
57160 * MA 02110-1301 USA
57161 */
57162
57163 /**
57164 * @class WidgetWrapper
57165 * Interface-like implementation for widgets interaction to each other; aimed to be modified for dynamic data sources
57166 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
57167 * @release 1.0
57168 * @release date: 2012-07-27
57169 * @version date: 2012-07-27
57170 *
57171 * @param {Object} widget either a map, time or table widget
57172 */
57173 WidgetWrapper = function() {
57174
57175 var wrapper = this;
57176
57177 this.setWidget = function(widget) {
57178 this.widget = widget;
57179 }
57180
57181 this.display = function(data) {
57182 if ( data instanceof Array) {
57183 GeoTemConfig.datasets = data;
57184 if ( typeof wrapper.widget != 'undefined') {
57185 this.widget.initWidget(data);
57186 }
57187 }
57188 };
57189
57190 Publisher.Subscribe('highlight', this, function(data) {
57191 if (data == undefined) {
57192 return;
57193 }
57194 if ( typeof wrapper.widget != 'undefined') {
57195 wrapper.widget.highlightChanged(data);
57196 }
57197 });
57198
57199 Publisher.Subscribe('selection', this, function(data) {
57200 if ( typeof wrapper.widget != 'undefined') {
57201 wrapper.widget.selectionChanged(data);
57202 }
57203 });
57204
57205 Publisher.Subscribe('filterData', this, function(data) {
57206 wrapper.display(data);
57207 });
57208
57209 Publisher.Subscribe('rise', this, function(id) {
57210 if ( typeof wrapper.widget != 'undefined' && typeof wrapper.widget.riseLayer != 'undefined') {
57211 wrapper.widget.riseLayer(id);
57212 }
57213 });
57214
57215 Publisher.Subscribe('resizeWidget', this, function() {
57216 if ( typeof wrapper.widget != 'undefined' && typeof wrapper.widget.gui != 'undefined' && typeof wrapper.widget.gui.resize != 'undefined' ) {
57217 wrapper.widget.gui.resize();
57218 }
57219 });
57220
57221 Publisher.Subscribe('getConfig', this, function(inquiringWidget) {
57222 if (inquiringWidget == undefined) {
57223 return;
57224 }
57225 if ( typeof wrapper.widget != 'undefined') {
57226 if ( typeof wrapper.widget.getConfig != 'undefined') {
57227 wrapper.widget.getConfig(inquiringWidget);
57228 }
57229 }
57230 });
57231
57232 Publisher.Subscribe('setConfig', this, function(config) {
57233 if (config == undefined) {
57234 return;
57235 }
57236 if ( typeof wrapper.widget != 'undefined') {
57237 if ( typeof wrapper.widget.setConfig != 'undefined') {
57238 wrapper.widget.setConfig(config);
57239 }
57240 }
57241 });
57242
57243
57244 this.triggerRefining = function(datasets) {
57245 Publisher.Publish('filterData', datasets, null);
57246 };
57247
57248 this.triggerSelection = function(selectedObjects) {
57249 Publisher.Publish('selection', selectedObjects, this);
57250 };
57251
57252 this.triggerHighlight = function(highlightedObjects) {
57253 Publisher.Publish('highlight', highlightedObjects, this);
57254 };
57255
57256 this.triggerRise = function(id) {
57257 Publisher.Publish('rise', id);
57258 };
57259
57260 };
57261 /*
57262 * final.js
57263 *
57264 * Copyright (c) 2012, Stefan Jänicke. All rights reserved.
57265 *
57266 * This library is free software; you can redistribute it and/or
57267 * modify it under the terms of the GNU Lesser General Public
57268 * License as published by the Free Software Foundation; either
57269 * version 3 of the License, or (at your option) any later version.
57270 *
57271 * This library is distributed in the hope that it will be useful,
57272 * but WITHOUT ANY WARRANTY; without even the implied warranty of
57273 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
57274 * Lesser General Public License for more details.
57275 *
57276 * You should have received a copy of the GNU Lesser General Public
57277 * License along with this library; if not, write to the Free Software
57278 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
57279 * MA 02110-1301 USA
57280 */
57281
57282 /**
57283 * code which is included after all other sources have been included for the minified version
57284 * @author Stefan Jänicke (stjaenicke@informatik.uni-leipzig.de)
57285 * @release 1.0
57286 * @release date: 2012-07-27
57287 * @version date: 2012-07-27
57288 */
57289
57290 OpenLayers.Util.getImagesLocation = function() {
57291 return GeoTemCoMinifier_urlPrefix + "lib/openlayers/img/";
57292 };
57293
57294 OpenLayers._getScriptLocation = function() {
57295 return GeoTemCoMinifier_urlPrefix + "lib/openlayers/";
57296 };
57297
57298 GeoTemConfig.configure(GeoTemCoMinifier_urlPrefix);
57299 })(jQuery);