Project

General

Profile

Download (59 KB) Statistics
| Branch: | Tag: | Revision:
1
/* Copyright (c) 2006-2013 by OpenLayers Contributors (see authors.txt for
2
 * full list of contributors). Published under the 2-clause BSD license.
3
 * See license.txt in the OpenLayers distribution or repository for the
4
 * full text of the license. */
5

    
6
/**
7
 * @requires OpenLayers/BaseTypes.js
8
 * @requires OpenLayers/BaseTypes/Bounds.js
9
 * @requires OpenLayers/BaseTypes/Element.js
10
 * @requires OpenLayers/BaseTypes/LonLat.js
11
 * @requires OpenLayers/BaseTypes/Pixel.js
12
 * @requires OpenLayers/BaseTypes/Size.js
13
 * @requires OpenLayers/Lang.js
14
 */
15

    
16
/**
17
 * Namespace: Util
18
 */
19
OpenLayers.Util = OpenLayers.Util || {};
20

    
21
/** 
22
 * Function: getElement
23
 * This is the old $() from prototype
24
 *
25
 * Parameters:
26
 * e - {String or DOMElement or Window}
27
 *
28
 * Returns:
29
 * {Array(DOMElement) or DOMElement}
30
 */
31
OpenLayers.Util.getElement = function() {
32
    var elements = [];
33

    
34
    for (var i=0, len=arguments.length; i<len; i++) {
35
        var element = arguments[i];
36
        if (typeof element == 'string') {
37
            element = document.getElementById(element);
38
        }
39
        if (arguments.length == 1) {
40
            return element;
41
        }
42
        elements.push(element);
43
    }
44
    return elements;
45
};
46

    
47
/**
48
 * Function: isElement
49
 * A cross-browser implementation of "e instanceof Element".
50
 *
51
 * Parameters:
52
 * o - {Object} The object to test.
53
 *
54
 * Returns:
55
 * {Boolean}
56
 */
57
OpenLayers.Util.isElement = function(o) {
58
    return !!(o && o.nodeType === 1);
59
};
60

    
61
/**
62
 * Function: isArray
63
 * Tests that the provided object is an array.
64
 * This test handles the cross-IFRAME case not caught
65
 * by "a instanceof Array" and should be used instead.
66
 * 
67
 * Parameters:
68
 * a - {Object} the object test.
69
 * 
70
 * Returns:
71
 * {Boolean} true if the object is an array.
72
 */
73
OpenLayers.Util.isArray = function(a) {
74
    return (Object.prototype.toString.call(a) === '[object Array]');
75
};
76

    
77
/** 
78
 * Function: removeItem
79
 * Remove an object from an array. Iterates through the array
80
 *     to find the item, then removes it.
81
 *
82
 * Parameters:
83
 * array - {Array}
84
 * item - {Object}
85
 * 
86
 * Returns:
87
 * {Array} A reference to the array
88
 */
89
OpenLayers.Util.removeItem = function(array, item) {
90
    for(var i = array.length - 1; i >= 0; i--) {
91
        if(array[i] == item) {
92
            array.splice(i,1);
93
            //break;more than once??
94
        }
95
    }
96
    return array;
97
};
98

    
99
/** 
100
 * Function: indexOf
101
 * Seems to exist already in FF, but not in MOZ.
102
 * 
103
 * Parameters:
104
 * array - {Array}
105
 * obj - {*}
106
 * 
107
 * Returns:
108
 * {Integer} The index at which the first object was found in the array.
109
 *           If not found, returns -1.
110
 */
111
OpenLayers.Util.indexOf = function(array, obj) {
112
    // use the build-in function if available.
113
    if (typeof array.indexOf == "function") {
114
        return array.indexOf(obj);
115
    } else {
116
        for (var i = 0, len = array.length; i < len; i++) {
117
            if (array[i] == obj) {
118
                return i;
119
            }
120
        }
121
        return -1;   
122
    }
123
};
124

    
125

    
126
/**
127
 * Property: dotless
128
 * {RegExp}
129
 * Compiled regular expression to match dots (".").  This is used for replacing
130
 *     dots in identifiers.  Because object identifiers are frequently used for
131
 *     DOM element identifiers by the library, we avoid using dots to make for
132
 *     more sensible CSS selectors.
133
 *
134
 * TODO: Use a module pattern to avoid bloating the API with stuff like this.
135
 */
136
OpenLayers.Util.dotless = /\./g;
137

    
138
/**
139
 * Function: modifyDOMElement
140
 * 
141
 * Modifies many properties of a DOM element all at once.  Passing in 
142
 * null to an individual parameter will avoid setting the attribute.
143
 *
144
 * Parameters:
145
 * element - {DOMElement} DOM element to modify.
146
 * id - {String} The element id attribute to set.  Note that dots (".") will be
147
 *     replaced with underscore ("_") in setting the element id.
148
 * px - {<OpenLayers.Pixel>|Object} The element left and top position,
149
 *                                  OpenLayers.Pixel or an object with
150
 *                                  a 'x' and 'y' properties.
151
 * sz - {<OpenLayers.Size>|Object} The element width and height,
152
 *                                 OpenLayers.Size or an object with a
153
 *                                 'w' and 'h' properties.
154
 * position - {String}       The position attribute.  eg: absolute, 
155
 *                           relative, etc.
156
 * border - {String}         The style.border attribute.  eg:
157
 *                           solid black 2px
158
 * overflow - {String}       The style.overview attribute.  
159
 * opacity - {Float}         Fractional value (0.0 - 1.0)
160
 */
161
OpenLayers.Util.modifyDOMElement = function(element, id, px, sz, position, 
162
                                            border, overflow, opacity) {
163

    
164
    if (id) {
165
        element.id = id.replace(OpenLayers.Util.dotless, "_");
166
    }
167
    if (px) {
168
        element.style.left = px.x + "px";
169
        element.style.top = px.y + "px";
170
    }
171
    if (sz) {
172
        element.style.width = sz.w + "px";
173
        element.style.height = sz.h + "px";
174
    }
175
    if (position) {
176
        element.style.position = position;
177
    }
178
    if (border) {
179
        element.style.border = border;
180
    }
181
    if (overflow) {
182
        element.style.overflow = overflow;
183
    }
184
    if (parseFloat(opacity) >= 0.0 && parseFloat(opacity) < 1.0) {
185
        element.style.filter = 'alpha(opacity=' + (opacity * 100) + ')';
186
        element.style.opacity = opacity;
187
    } else if (parseFloat(opacity) == 1.0) {
188
        element.style.filter = '';
189
        element.style.opacity = '';
190
    }
191
};
192

    
193
/** 
194
 * Function: createDiv
195
 * Creates a new div and optionally set some standard attributes.
196
 * Null may be passed to each parameter if you do not wish to
197
 * set a particular attribute.
198
 * Note - zIndex is NOT set on the resulting div.
199
 * 
200
 * Parameters:
201
 * id - {String} An identifier for this element.  If no id is
202
 *               passed an identifier will be created 
203
 *               automatically.  Note that dots (".") will be replaced with
204
 *               underscore ("_") when generating ids.
205
 * px - {<OpenLayers.Pixel>|Object} The element left and top position,
206
 *                                  OpenLayers.Pixel or an object with
207
 *                                  a 'x' and 'y' properties.
208
 * sz - {<OpenLayers.Size>|Object} The element width and height,
209
 *                                 OpenLayers.Size or an object with a
210
 *                                 'w' and 'h' properties.
211
 * imgURL - {String} A url pointing to an image to use as a 
212
 *                   background image.
213
 * position - {String} The style.position value. eg: absolute,
214
 *                     relative etc.
215
 * border - {String} The the style.border value. 
216
 *                   eg: 2px solid black
217
 * overflow - {String} The style.overflow value. Eg. hidden
218
 * opacity - {Float} Fractional value (0.0 - 1.0)
219
 * 
220
 * Returns: 
221
 * {DOMElement} A DOM Div created with the specified attributes.
222
 */
223
OpenLayers.Util.createDiv = function(id, px, sz, imgURL, position, 
224
                                     border, overflow, opacity) {
225

    
226
    var dom = document.createElement('div');
227

    
228
    if (imgURL) {
229
        dom.style.backgroundImage = 'url(' + imgURL + ')';
230
    }
231

    
232
    //set generic properties
233
    if (!id) {
234
        id = OpenLayers.Util.createUniqueID("OpenLayersDiv");
235
    }
236
    if (!position) {
237
        position = "absolute";
238
    }
239
    OpenLayers.Util.modifyDOMElement(dom, id, px, sz, position, 
240
                                     border, overflow, opacity);
241

    
242
    return dom;
243
};
244

    
245
/**
246
 * Function: createImage
247
 * Creates an img element with specific attribute values.
248
 *  
249
 * Parameters:
250
 * id - {String} The id field for the img.  If none assigned one will be
251
 *               automatically generated.
252
 * px - {<OpenLayers.Pixel>|Object} The element left and top position,
253
 *                                  OpenLayers.Pixel or an object with
254
 *                                  a 'x' and 'y' properties.
255
 * sz - {<OpenLayers.Size>|Object} The element width and height,
256
 *                                 OpenLayers.Size or an object with a
257
 *                                 'w' and 'h' properties.
258
 * imgURL - {String} The url to use as the image source.
259
 * position - {String} The style.position value.
260
 * border - {String} The border to place around the image.
261
 * opacity - {Float} Fractional value (0.0 - 1.0)
262
 * delayDisplay - {Boolean} If true waits until the image has been
263
 *                          loaded.
264
 * 
265
 * Returns:
266
 * {DOMElement} A DOM Image created with the specified attributes.
267
 */
268
OpenLayers.Util.createImage = function(id, px, sz, imgURL, position, border,
269
                                       opacity, delayDisplay) {
270

    
271
    var image = document.createElement("img");
272

    
273
    //set generic properties
274
    if (!id) {
275
        id = OpenLayers.Util.createUniqueID("OpenLayersDiv");
276
    }
277
    if (!position) {
278
        position = "relative";
279
    }
280
    OpenLayers.Util.modifyDOMElement(image, id, px, sz, position, 
281
                                     border, null, opacity);
282

    
283
    if (delayDisplay) {
284
        image.style.display = "none";
285
        function display() {
286
            image.style.display = "";
287
            OpenLayers.Event.stopObservingElement(image);
288
        }
289
        OpenLayers.Event.observe(image, "load", display);
290
        OpenLayers.Event.observe(image, "error", display);
291
    }
292
    
293
    //set special properties
294
    image.style.alt = id;
295
    image.galleryImg = "no";
296
    if (imgURL) {
297
        image.src = imgURL;
298
    }
299
        
300
    return image;
301
};
302

    
303
/**
304
 * Property: IMAGE_RELOAD_ATTEMPTS
305
 * {Integer} How many times should we try to reload an image before giving up?
306
 *           Default is 0
307
 */
308
OpenLayers.IMAGE_RELOAD_ATTEMPTS = 0;
309

    
310
/**
311
 * Property: alphaHackNeeded
312
 * {Boolean} true if the png alpha hack is necessary and possible, false otherwise.
313
 */
314
OpenLayers.Util.alphaHackNeeded = null;
315

    
316
/**
317
 * Function: alphaHack
318
 * Checks whether it's necessary (and possible) to use the png alpha
319
 * hack which allows alpha transparency for png images under Internet
320
 * Explorer.
321
 * 
322
 * Returns:
323
 * {Boolean} true if the png alpha hack is necessary and possible, false otherwise.
324
 */
325
OpenLayers.Util.alphaHack = function() {
326
    if (OpenLayers.Util.alphaHackNeeded == null) {
327
        var arVersion = navigator.appVersion.split("MSIE");
328
        var version = parseFloat(arVersion[1]);
329
        var filter = false;
330
    
331
        // IEs4Lin dies when trying to access document.body.filters, because 
332
        // the property is there, but requires a DLL that can't be provided. This
333
        // means that we need to wrap this in a try/catch so that this can
334
        // continue.
335
    
336
        try { 
337
            filter = !!(document.body.filters);
338
        } catch (e) {}    
339
    
340
        OpenLayers.Util.alphaHackNeeded = (filter && 
341
                                           (version >= 5.5) && (version < 7));
342
    }
343
    return OpenLayers.Util.alphaHackNeeded;
344
};
345

    
346
/** 
347
 * Function: modifyAlphaImageDiv
348
 * 
349
 * Parameters:
350
 * div - {DOMElement} Div containing Alpha-adjusted Image
351
 * id - {String}
352
 * px - {<OpenLayers.Pixel>|Object} OpenLayers.Pixel or an object with
353
 *                                  a 'x' and 'y' properties.
354
 * sz - {<OpenLayers.Size>|Object} OpenLayers.Size or an object with
355
 *                                 a 'w' and 'h' properties.
356
 * imgURL - {String}
357
 * position - {String}
358
 * border - {String}
359
 * sizing - {String} 'crop', 'scale', or 'image'. Default is "scale"
360
 * opacity - {Float} Fractional value (0.0 - 1.0)
361
 */ 
362
OpenLayers.Util.modifyAlphaImageDiv = function(div, id, px, sz, imgURL, 
363
                                               position, border, sizing, 
364
                                               opacity) {
365

    
366
    OpenLayers.Util.modifyDOMElement(div, id, px, sz, position,
367
                                     null, null, opacity);
368

    
369
    var img = div.childNodes[0];
370

    
371
    if (imgURL) {
372
        img.src = imgURL;
373
    }
374
    OpenLayers.Util.modifyDOMElement(img, div.id + "_innerImage", null, sz, 
375
                                     "relative", border);
376
    
377
    if (OpenLayers.Util.alphaHack()) {
378
        if(div.style.display != "none") {
379
            div.style.display = "inline-block";
380
        }
381
        if (sizing == null) {
382
            sizing = "scale";
383
        }
384
        
385
        div.style.filter = "progid:DXImageTransform.Microsoft" +
386
                           ".AlphaImageLoader(src='" + img.src + "', " +
387
                           "sizingMethod='" + sizing + "')";
388
        if (parseFloat(div.style.opacity) >= 0.0 && 
389
            parseFloat(div.style.opacity) < 1.0) {
390
            div.style.filter += " alpha(opacity=" + div.style.opacity * 100 + ")";
391
        }
392

    
393
        img.style.filter = "alpha(opacity=0)";
394
    }
395
};
396

    
397
/** 
398
 * Function: createAlphaImageDiv
399
 * 
400
 * Parameters:
401
 * id - {String}
402
 * px - {<OpenLayers.Pixel>|Object} OpenLayers.Pixel or an object with
403
 *                                  a 'x' and 'y' properties.
404
 * sz - {<OpenLayers.Size>|Object} OpenLayers.Size or an object with
405
 *                                 a 'w' and 'h' properties.
406
 * imgURL - {String}
407
 * position - {String}
408
 * border - {String}
409
 * sizing - {String} 'crop', 'scale', or 'image'. Default is "scale"
410
 * opacity - {Float} Fractional value (0.0 - 1.0)
411
 * delayDisplay - {Boolean} If true waits until the image has been
412
 *                          loaded.
413
 * 
414
 * Returns:
415
 * {DOMElement} A DOM Div created with a DOM Image inside it. If the hack is 
416
 *              needed for transparency in IE, it is added.
417
 */ 
418
OpenLayers.Util.createAlphaImageDiv = function(id, px, sz, imgURL, 
419
                                               position, border, sizing, 
420
                                               opacity, delayDisplay) {
421
    
422
    var div = OpenLayers.Util.createDiv();
423
    var img = OpenLayers.Util.createImage(null, null, null, null, null, null, 
424
                                          null, delayDisplay);
425
    img.className = "olAlphaImg";
426
    div.appendChild(img);
427

    
428
    OpenLayers.Util.modifyAlphaImageDiv(div, id, px, sz, imgURL, position, 
429
                                        border, sizing, opacity);
430
    
431
    return div;
432
};
433

    
434

    
435
/** 
436
 * Function: upperCaseObject
437
 * Creates a new hashtable and copies over all the keys from the 
438
 *     passed-in object, but storing them under an uppercased
439
 *     version of the key at which they were stored.
440
 * 
441
 * Parameters: 
442
 * object - {Object}
443
 * 
444
 * Returns: 
445
 * {Object} A new Object with all the same keys but uppercased
446
 */
447
OpenLayers.Util.upperCaseObject = function (object) {
448
    var uObject = {};
449
    for (var key in object) {
450
        uObject[key.toUpperCase()] = object[key];
451
    }
452
    return uObject;
453
};
454

    
455
/** 
456
 * Function: applyDefaults
457
 * Takes an object and copies any properties that don't exist from
458
 *     another properties, by analogy with OpenLayers.Util.extend() from
459
 *     Prototype.js.
460
 * 
461
 * Parameters:
462
 * to - {Object} The destination object.
463
 * from - {Object} The source object.  Any properties of this object that
464
 *     are undefined in the to object will be set on the to object.
465
 *
466
 * Returns:
467
 * {Object} A reference to the to object.  Note that the to argument is modified
468
 *     in place and returned by this function.
469
 */
470
OpenLayers.Util.applyDefaults = function (to, from) {
471
    to = to || {};
472
    /*
473
     * FF/Windows < 2.0.0.13 reports "Illegal operation on WrappedNative
474
     * prototype object" when calling hawOwnProperty if the source object is an
475
     * instance of window.Event.
476
     */
477
    var fromIsEvt = typeof window.Event == "function"
478
                    && from instanceof window.Event;
479

    
480
    for (var key in from) {
481
        if (to[key] === undefined ||
482
            (!fromIsEvt && from.hasOwnProperty
483
             && from.hasOwnProperty(key) && !to.hasOwnProperty(key))) {
484
            to[key] = from[key];
485
        }
486
    }
487
    /**
488
     * IE doesn't include the toString property when iterating over an object's
489
     * properties with the for(property in object) syntax.  Explicitly check if
490
     * the source has its own toString property.
491
     */
492
    if(!fromIsEvt && from && from.hasOwnProperty
493
       && from.hasOwnProperty('toString') && !to.hasOwnProperty('toString')) {
494
        to.toString = from.toString;
495
    }
496
    
497
    return to;
498
};
499

    
500
/**
501
 * Function: getParameterString
502
 * 
503
 * Parameters:
504
 * params - {Object}
505
 * 
506
 * Returns:
507
 * {String} A concatenation of the properties of an object in 
508
 *          http parameter notation. 
509
 *          (ex. <i>"key1=value1&key2=value2&key3=value3"</i>)
510
 *          If a parameter is actually a list, that parameter will then
511
 *          be set to a comma-seperated list of values (foo,bar) instead
512
 *          of being URL escaped (foo%3Abar). 
513
 */
514
OpenLayers.Util.getParameterString = function(params) {
515
    var paramsArray = [];
516
    
517
    for (var key in params) {
518
      var value = params[key];
519
      if ((value != null) && (typeof value != 'function')) {
520
        var encodedValue;
521
        if (typeof value == 'object' && value.constructor == Array) {
522
          /* value is an array; encode items and separate with "," */
523
          var encodedItemArray = [];
524
          var item;
525
          for (var itemIndex=0, len=value.length; itemIndex<len; itemIndex++) {
526
            item = value[itemIndex];
527
            encodedItemArray.push(encodeURIComponent(
528
                (item === null || item === undefined) ? "" : item)
529
            );
530
          }
531
          encodedValue = encodedItemArray.join(",");
532
        }
533
        else {
534
          /* value is a string; simply encode */
535
          encodedValue = encodeURIComponent(value);
536
        }
537
        paramsArray.push(encodeURIComponent(key) + "=" + encodedValue);
538
      }
539
    }
540
    
541
    return paramsArray.join("&");
542
};
543

    
544
/**
545
 * Function: urlAppend
546
 * Appends a parameter string to a url. This function includes the logic for
547
 * using the appropriate character (none, & or ?) to append to the url before
548
 * appending the param string.
549
 * 
550
 * Parameters:
551
 * url - {String} The url to append to
552
 * paramStr - {String} The param string to append
553
 * 
554
 * Returns:
555
 * {String} The new url
556
 */
557
OpenLayers.Util.urlAppend = function(url, paramStr) {
558
    var newUrl = url;
559
    if(paramStr) {
560
        var parts = (url + " ").split(/[?&]/);
561
        newUrl += (parts.pop() === " " ?
562
            paramStr :
563
            parts.length ? "&" + paramStr : "?" + paramStr);
564
    }
565
    return newUrl;
566
};
567

    
568
/** 
569
 * Function: getImagesLocation
570
 * 
571
 * Returns:
572
 * {String} The fully formatted image location string
573
 */
574
OpenLayers.Util.getImagesLocation = function() {
575
    return OpenLayers.ImgPath || (OpenLayers._getScriptLocation() + "img/");
576
};
577

    
578
/** 
579
 * Function: getImageLocation
580
 * 
581
 * Returns:
582
 * {String} The fully formatted location string for a specified image
583
 */
584
OpenLayers.Util.getImageLocation = function(image) {
585
    return OpenLayers.Util.getImagesLocation() + image;
586
};
587

    
588

    
589
/** 
590
 * Function: Try
591
 * Execute functions until one of them doesn't throw an error. 
592
 *     Capitalized because "try" is a reserved word in JavaScript.
593
 *     Taken directly from OpenLayers.Util.Try()
594
 * 
595
 * Parameters:
596
 * [*] - {Function} Any number of parameters may be passed to Try()
597
 *    It will attempt to execute each of them until one of them 
598
 *    successfully executes. 
599
 *    If none executes successfully, returns null.
600
 * 
601
 * Returns:
602
 * {*} The value returned by the first successfully executed function.
603
 */
604
OpenLayers.Util.Try = function() {
605
    var returnValue = null;
606

    
607
    for (var i=0, len=arguments.length; i<len; i++) {
608
      var lambda = arguments[i];
609
      try {
610
        returnValue = lambda();
611
        break;
612
      } catch (e) {}
613
    }
614

    
615
    return returnValue;
616
};
617

    
618
/**
619
 * Function: getXmlNodeValue
620
 * 
621
 * Parameters:
622
 * node - {XMLNode}
623
 * 
624
 * Returns:
625
 * {String} The text value of the given node, without breaking in firefox or IE
626
 */
627
OpenLayers.Util.getXmlNodeValue = function(node) {
628
    var val = null;
629
    OpenLayers.Util.Try( 
630
        function() {
631
            val = node.text;
632
            if (!val) {
633
                val = node.textContent;
634
            }
635
            if (!val) {
636
                val = node.firstChild.nodeValue;
637
            }
638
        }, 
639
        function() {
640
            val = node.textContent;
641
        }); 
642
    return val;
643
};
644

    
645
/** 
646
 * Function: mouseLeft
647
 * 
648
 * Parameters:
649
 * evt - {Event}
650
 * div - {HTMLDivElement}
651
 * 
652
 * Returns:
653
 * {Boolean}
654
 */
655
OpenLayers.Util.mouseLeft = function (evt, div) {
656
    // start with the element to which the mouse has moved
657
    var target = (evt.relatedTarget) ? evt.relatedTarget : evt.toElement;
658
    // walk up the DOM tree.
659
    while (target != div && target != null) {
660
        target = target.parentNode;
661
    }
662
    // if the target we stop at isn't the div, then we've left the div.
663
    return (target != div);
664
};
665

    
666
/**
667
 * Property: precision
668
 * {Number} The number of significant digits to retain to avoid
669
 * floating point precision errors.
670
 *
671
 * We use 14 as a "safe" default because, although IEEE 754 double floats
672
 * (standard on most modern operating systems) support up to about 16
673
 * significant digits, 14 significant digits are sufficient to represent
674
 * sub-millimeter accuracy in any coordinate system that anyone is likely to
675
 * use with OpenLayers.
676
 *
677
 * If DEFAULT_PRECISION is set to 0, the original non-truncating behavior
678
 * of OpenLayers <2.8 is preserved. Be aware that this will cause problems
679
 * with certain projections, e.g. spherical Mercator.
680
 *
681
 */
682
OpenLayers.Util.DEFAULT_PRECISION = 14;
683

    
684
/**
685
 * Function: toFloat
686
 * Convenience method to cast an object to a Number, rounded to the
687
 * desired floating point precision.
688
 *
689
 * Parameters:
690
 * number    - {Number} The number to cast and round.
691
 * precision - {Number} An integer suitable for use with
692
 *      Number.toPrecision(). Defaults to OpenLayers.Util.DEFAULT_PRECISION.
693
 *      If set to 0, no rounding is performed.
694
 *
695
 * Returns:
696
 * {Number} The cast, rounded number.
697
 */
698
OpenLayers.Util.toFloat = function (number, precision) {
699
    if (precision == null) {
700
        precision = OpenLayers.Util.DEFAULT_PRECISION;
701
    }
702
    if (typeof number !== "number") {
703
        number = parseFloat(number);
704
    }
705
    return precision === 0 ? number :
706
                             parseFloat(number.toPrecision(precision));
707
};
708

    
709
/**
710
 * Function: rad
711
 * 
712
 * Parameters:
713
 * x - {Float}
714
 * 
715
 * Returns:
716
 * {Float}
717
 */
718
OpenLayers.Util.rad = function(x) {return x*Math.PI/180;};
719

    
720
/**
721
 * Function: deg
722
 *
723
 * Parameters:
724
 * x - {Float}
725
 *
726
 * Returns:
727
 * {Float}
728
 */
729
OpenLayers.Util.deg = function(x) {return x*180/Math.PI;};
730

    
731
/**
732
 * Property: VincentyConstants
733
 * {Object} Constants for Vincenty functions.
734
 */
735
OpenLayers.Util.VincentyConstants = {
736
    a: 6378137,
737
    b: 6356752.3142,
738
    f: 1/298.257223563
739
};
740

    
741
/**
742
 * APIFunction: distVincenty
743
 * Given two objects representing points with geographic coordinates, this
744
 *     calculates the distance between those points on the surface of an
745
 *     ellipsoid.
746
 *
747
 * Parameters:
748
 * p1 - {<OpenLayers.LonLat>} (or any object with both .lat, .lon properties)
749
 * p2 - {<OpenLayers.LonLat>} (or any object with both .lat, .lon properties)
750
 *
751
 * Returns:
752
 * {Float} The distance (in km) between the two input points as measured on an
753
 *     ellipsoid.  Note that the input point objects must be in geographic
754
 *     coordinates (decimal degrees) and the return distance is in kilometers.
755
 */
756
OpenLayers.Util.distVincenty = function(p1, p2) {
757
    var ct = OpenLayers.Util.VincentyConstants;
758
    var a = ct.a, b = ct.b, f = ct.f;
759

    
760
    var L = OpenLayers.Util.rad(p2.lon - p1.lon);
761
    var U1 = Math.atan((1-f) * Math.tan(OpenLayers.Util.rad(p1.lat)));
762
    var U2 = Math.atan((1-f) * Math.tan(OpenLayers.Util.rad(p2.lat)));
763
    var sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);
764
    var sinU2 = Math.sin(U2), cosU2 = Math.cos(U2);
765
    var lambda = L, lambdaP = 2*Math.PI;
766
    var iterLimit = 20;
767
    while (Math.abs(lambda-lambdaP) > 1e-12 && --iterLimit>0) {
768
        var sinLambda = Math.sin(lambda), cosLambda = Math.cos(lambda);
769
        var sinSigma = Math.sqrt((cosU2*sinLambda) * (cosU2*sinLambda) +
770
        (cosU1*sinU2-sinU1*cosU2*cosLambda) * (cosU1*sinU2-sinU1*cosU2*cosLambda));
771
        if (sinSigma==0) {
772
            return 0;  // co-incident points
773
        }
774
        var cosSigma = sinU1*sinU2 + cosU1*cosU2*cosLambda;
775
        var sigma = Math.atan2(sinSigma, cosSigma);
776
        var alpha = Math.asin(cosU1 * cosU2 * sinLambda / sinSigma);
777
        var cosSqAlpha = Math.cos(alpha) * Math.cos(alpha);
778
        var cos2SigmaM = cosSigma - 2*sinU1*sinU2/cosSqAlpha;
779
        var C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));
780
        lambdaP = lambda;
781
        lambda = L + (1-C) * f * Math.sin(alpha) *
782
        (sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));
783
    }
784
    if (iterLimit==0) {
785
        return NaN;  // formula failed to converge
786
    }
787
    var uSq = cosSqAlpha * (a*a - b*b) / (b*b);
788
    var A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));
789
    var B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)));
790
    var deltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-
791
        B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));
792
    var s = b*A*(sigma-deltaSigma);
793
    var d = s.toFixed(3)/1000; // round to 1mm precision
794
    return d;
795
};
796

    
797
/**
798
 * APIFunction: destinationVincenty
799
 * Calculate destination point given start point lat/long (numeric degrees),
800
 * bearing (numeric degrees) & distance (in m).
801
 * Adapted from Chris Veness work, see
802
 * http://www.movable-type.co.uk/scripts/latlong-vincenty-direct.html
803
 *
804
 * Parameters:
805
 * lonlat  - {<OpenLayers.LonLat>} (or any object with both .lat, .lon
806
 *     properties) The start point.
807
 * brng     - {Float} The bearing (degrees).
808
 * dist     - {Float} The ground distance (meters).
809
 *
810
 * Returns:
811
 * {<OpenLayers.LonLat>} The destination point.
812
 */
813
OpenLayers.Util.destinationVincenty = function(lonlat, brng, dist) {
814
    var u = OpenLayers.Util;
815
    var ct = u.VincentyConstants;
816
    var a = ct.a, b = ct.b, f = ct.f;
817

    
818
    var lon1 = lonlat.lon;
819
    var lat1 = lonlat.lat;
820

    
821
    var s = dist;
822
    var alpha1 = u.rad(brng);
823
    var sinAlpha1 = Math.sin(alpha1);
824
    var cosAlpha1 = Math.cos(alpha1);
825

    
826
    var tanU1 = (1-f) * Math.tan(u.rad(lat1));
827
    var cosU1 = 1 / Math.sqrt((1 + tanU1*tanU1)), sinU1 = tanU1*cosU1;
828
    var sigma1 = Math.atan2(tanU1, cosAlpha1);
829
    var sinAlpha = cosU1 * sinAlpha1;
830
    var cosSqAlpha = 1 - sinAlpha*sinAlpha;
831
    var uSq = cosSqAlpha * (a*a - b*b) / (b*b);
832
    var A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));
833
    var B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)));
834

    
835
    var sigma = s / (b*A), sigmaP = 2*Math.PI;
836
    while (Math.abs(sigma-sigmaP) > 1e-12) {
837
        var cos2SigmaM = Math.cos(2*sigma1 + sigma);
838
        var sinSigma = Math.sin(sigma);
839
        var cosSigma = Math.cos(sigma);
840
        var deltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-
841
            B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));
842
        sigmaP = sigma;
843
        sigma = s / (b*A) + deltaSigma;
844
    }
845

    
846
    var tmp = sinU1*sinSigma - cosU1*cosSigma*cosAlpha1;
847
    var lat2 = Math.atan2(sinU1*cosSigma + cosU1*sinSigma*cosAlpha1,
848
        (1-f)*Math.sqrt(sinAlpha*sinAlpha + tmp*tmp));
849
    var lambda = Math.atan2(sinSigma*sinAlpha1, cosU1*cosSigma - sinU1*sinSigma*cosAlpha1);
850
    var C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));
851
    var L = lambda - (1-C) * f * sinAlpha *
852
        (sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));
853

    
854
    var revAz = Math.atan2(sinAlpha, -tmp);  // final bearing
855

    
856
    return new OpenLayers.LonLat(lon1+u.deg(L), u.deg(lat2));
857
};
858

    
859
/**
860
 * Function: getParameters
861
 * Parse the parameters from a URL or from the current page itself into a 
862
 *     JavaScript Object. Note that parameter values with commas are separated
863
 *     out into an Array.
864
 * 
865
 * Parameters:
866
 * url - {String} Optional url used to extract the query string.
867
 *                If url is null or is not supplied, query string is taken 
868
 *                from the page location.
869
 * options - {Object} Additional options. Optional.
870
 *
871
 * Valid options:
872
 *   splitArgs - {Boolean} Split comma delimited params into arrays? Default is
873
 *       true.
874
 * 
875
 * Returns:
876
 * {Object} An object of key/value pairs from the query string.
877
 */
878
OpenLayers.Util.getParameters = function(url, options) {
879
    options = options || {};
880
    // if no url specified, take it from the location bar
881
    url = (url === null || url === undefined) ? window.location.href : url;
882

    
883
    //parse out parameters portion of url string
884
    var paramsString = "";
885
    if (OpenLayers.String.contains(url, '?')) {
886
        var start = url.indexOf('?') + 1;
887
        var end = OpenLayers.String.contains(url, "#") ?
888
                    url.indexOf('#') : url.length;
889
        paramsString = url.substring(start, end);
890
    }
891

    
892
    var parameters = {};
893
    var pairs = paramsString.split(/[&;]/);
894
    for(var i=0, len=pairs.length; i<len; ++i) {
895
        var keyValue = pairs[i].split('=');
896
        if (keyValue[0]) {
897

    
898
            var key = keyValue[0];
899
            try {
900
                key = decodeURIComponent(key);
901
            } catch (err) {
902
                key = unescape(key);
903
            }
904
            
905
            // being liberal by replacing "+" with " "
906
            var value = (keyValue[1] || '').replace(/\+/g, " ");
907

    
908
            try {
909
                value = decodeURIComponent(value);
910
            } catch (err) {
911
                value = unescape(value);
912
            }
913
            
914
            // follow OGC convention of comma delimited values
915
            if (options.splitArgs !== false) {
916
                value = value.split(",");
917
            }
918

    
919
            //if there's only one value, do not return as array                    
920
            if (value.length == 1) {
921
                value = value[0];
922
            }                
923
            
924
            parameters[key] = value;
925
         }
926
     }
927
    return parameters;
928
};
929

    
930
/**
931
 * Property: lastSeqID
932
 * {Integer} The ever-incrementing count variable.
933
 *           Used for generating unique ids.
934
 */
935
OpenLayers.Util.lastSeqID = 0;
936

    
937
/**
938
 * Function: createUniqueID
939
 * Create a unique identifier for this session.  Each time this function
940
 *     is called, a counter is incremented.  The return will be the optional
941
 *     prefix (defaults to "id_") appended with the counter value.
942
 * 
943
 * Parameters:
944
 * prefix - {String} Optional string to prefix unique id. Default is "id_".
945
 *     Note that dots (".") in the prefix will be replaced with underscore ("_").
946
 * 
947
 * Returns:
948
 * {String} A unique id string, built on the passed in prefix.
949
 */
950
OpenLayers.Util.createUniqueID = function(prefix) {
951
    if (prefix == null) {
952
        prefix = "id_";
953
    } else {
954
        prefix = prefix.replace(OpenLayers.Util.dotless, "_");
955
    }
956
    OpenLayers.Util.lastSeqID += 1; 
957
    return prefix + OpenLayers.Util.lastSeqID;        
958
};
959

    
960
/**
961
 * Constant: INCHES_PER_UNIT
962
 * {Object} Constant inches per unit -- borrowed from MapServer mapscale.c
963
 * derivation of nautical miles from http://en.wikipedia.org/wiki/Nautical_mile
964
 * Includes the full set of units supported by CS-MAP (http://trac.osgeo.org/csmap/)
965
 * and PROJ.4 (http://trac.osgeo.org/proj/)
966
 * The hardcoded table is maintain in a CS-MAP source code module named CSdataU.c
967
 * The hardcoded table of PROJ.4 units are in pj_units.c.
968
 */
969
OpenLayers.INCHES_PER_UNIT = { 
970
    'inches': 1.0,
971
    'ft': 12.0,
972
    'mi': 63360.0,
973
    'm': 39.37,
974
    'km': 39370,
975
    'dd': 4374754,
976
    'yd': 36
977
};
978
OpenLayers.INCHES_PER_UNIT["in"]= OpenLayers.INCHES_PER_UNIT.inches;
979
OpenLayers.INCHES_PER_UNIT["degrees"] = OpenLayers.INCHES_PER_UNIT.dd;
980
OpenLayers.INCHES_PER_UNIT["nmi"] = 1852 * OpenLayers.INCHES_PER_UNIT.m;
981

    
982
// Units from CS-Map
983
OpenLayers.METERS_PER_INCH = 0.02540005080010160020;
984
OpenLayers.Util.extend(OpenLayers.INCHES_PER_UNIT, {
985
    "Inch": OpenLayers.INCHES_PER_UNIT.inches,
986
    "Meter": 1.0 / OpenLayers.METERS_PER_INCH,   //EPSG:9001
987
    "Foot": 0.30480060960121920243 / OpenLayers.METERS_PER_INCH,   //EPSG:9003
988
    "IFoot": 0.30480000000000000000 / OpenLayers.METERS_PER_INCH,   //EPSG:9002
989
    "ClarkeFoot": 0.3047972651151 / OpenLayers.METERS_PER_INCH,   //EPSG:9005
990
    "SearsFoot": 0.30479947153867624624 / OpenLayers.METERS_PER_INCH,   //EPSG:9041
991
    "GoldCoastFoot": 0.30479971018150881758 / OpenLayers.METERS_PER_INCH,   //EPSG:9094
992
    "IInch": 0.02540000000000000000 / OpenLayers.METERS_PER_INCH,
993
    "MicroInch": 0.00002540000000000000 / OpenLayers.METERS_PER_INCH,
994
    "Mil": 0.00000002540000000000 / OpenLayers.METERS_PER_INCH,
995
    "Centimeter": 0.01000000000000000000 / OpenLayers.METERS_PER_INCH,
996
    "Kilometer": 1000.00000000000000000000 / OpenLayers.METERS_PER_INCH,   //EPSG:9036
997
    "Yard": 0.91440182880365760731 / OpenLayers.METERS_PER_INCH,
998
    "SearsYard": 0.914398414616029 / OpenLayers.METERS_PER_INCH,   //EPSG:9040
999
    "IndianYard": 0.91439853074444079983 / OpenLayers.METERS_PER_INCH,   //EPSG:9084
1000
    "IndianYd37": 0.91439523 / OpenLayers.METERS_PER_INCH,   //EPSG:9085
1001
    "IndianYd62": 0.9143988 / OpenLayers.METERS_PER_INCH,   //EPSG:9086
1002
    "IndianYd75": 0.9143985 / OpenLayers.METERS_PER_INCH,   //EPSG:9087
1003
    "IndianFoot": 0.30479951 / OpenLayers.METERS_PER_INCH,   //EPSG:9080
1004
    "IndianFt37": 0.30479841 / OpenLayers.METERS_PER_INCH,   //EPSG:9081
1005
    "IndianFt62": 0.3047996 / OpenLayers.METERS_PER_INCH,   //EPSG:9082
1006
    "IndianFt75": 0.3047995 / OpenLayers.METERS_PER_INCH,   //EPSG:9083
1007
    "Mile": 1609.34721869443738887477 / OpenLayers.METERS_PER_INCH,
1008
    "IYard": 0.91440000000000000000 / OpenLayers.METERS_PER_INCH,   //EPSG:9096
1009
    "IMile": 1609.34400000000000000000 / OpenLayers.METERS_PER_INCH,   //EPSG:9093
1010
    "NautM": 1852.00000000000000000000 / OpenLayers.METERS_PER_INCH,   //EPSG:9030
1011
    "Lat-66": 110943.316488932731 / OpenLayers.METERS_PER_INCH,
1012
    "Lat-83": 110946.25736872234125 / OpenLayers.METERS_PER_INCH,
1013
    "Decimeter": 0.10000000000000000000 / OpenLayers.METERS_PER_INCH,
1014
    "Millimeter": 0.00100000000000000000 / OpenLayers.METERS_PER_INCH,
1015
    "Dekameter": 10.00000000000000000000 / OpenLayers.METERS_PER_INCH,
1016
    "Decameter": 10.00000000000000000000 / OpenLayers.METERS_PER_INCH,
1017
    "Hectometer": 100.00000000000000000000 / OpenLayers.METERS_PER_INCH,
1018
    "GermanMeter": 1.0000135965 / OpenLayers.METERS_PER_INCH,   //EPSG:9031
1019
    "CaGrid": 0.999738 / OpenLayers.METERS_PER_INCH,
1020
    "ClarkeChain": 20.1166194976 / OpenLayers.METERS_PER_INCH,   //EPSG:9038
1021
    "GunterChain": 20.11684023368047 / OpenLayers.METERS_PER_INCH,   //EPSG:9033
1022
    "BenoitChain": 20.116782494375872 / OpenLayers.METERS_PER_INCH,   //EPSG:9062
1023
    "SearsChain": 20.11676512155 / OpenLayers.METERS_PER_INCH,   //EPSG:9042
1024
    "ClarkeLink": 0.201166194976 / OpenLayers.METERS_PER_INCH,   //EPSG:9039
1025
    "GunterLink": 0.2011684023368047 / OpenLayers.METERS_PER_INCH,   //EPSG:9034
1026
    "BenoitLink": 0.20116782494375872 / OpenLayers.METERS_PER_INCH,   //EPSG:9063
1027
    "SearsLink": 0.2011676512155 / OpenLayers.METERS_PER_INCH,   //EPSG:9043
1028
    "Rod": 5.02921005842012 / OpenLayers.METERS_PER_INCH,
1029
    "IntnlChain": 20.1168 / OpenLayers.METERS_PER_INCH,   //EPSG:9097
1030
    "IntnlLink": 0.201168 / OpenLayers.METERS_PER_INCH,   //EPSG:9098
1031
    "Perch": 5.02921005842012 / OpenLayers.METERS_PER_INCH,
1032
    "Pole": 5.02921005842012 / OpenLayers.METERS_PER_INCH,
1033
    "Furlong": 201.1684023368046 / OpenLayers.METERS_PER_INCH,
1034
    "Rood": 3.778266898 / OpenLayers.METERS_PER_INCH,
1035
    "CapeFoot": 0.3047972615 / OpenLayers.METERS_PER_INCH,
1036
    "Brealey": 375.00000000000000000000 / OpenLayers.METERS_PER_INCH,
1037
    "ModAmFt": 0.304812252984505969011938 / OpenLayers.METERS_PER_INCH,
1038
    "Fathom": 1.8288 / OpenLayers.METERS_PER_INCH,
1039
    "NautM-UK": 1853.184 / OpenLayers.METERS_PER_INCH,
1040
    "50kilometers": 50000.0 / OpenLayers.METERS_PER_INCH,
1041
    "150kilometers": 150000.0 / OpenLayers.METERS_PER_INCH
1042
});
1043

    
1044
//unit abbreviations supported by PROJ.4
1045
OpenLayers.Util.extend(OpenLayers.INCHES_PER_UNIT, {
1046
    "mm": OpenLayers.INCHES_PER_UNIT["Meter"] / 1000.0,
1047
    "cm": OpenLayers.INCHES_PER_UNIT["Meter"] / 100.0,
1048
    "dm": OpenLayers.INCHES_PER_UNIT["Meter"] * 100.0,
1049
    "km": OpenLayers.INCHES_PER_UNIT["Meter"] * 1000.0,
1050
    "kmi": OpenLayers.INCHES_PER_UNIT["nmi"],    //International Nautical Mile
1051
    "fath": OpenLayers.INCHES_PER_UNIT["Fathom"], //International Fathom
1052
    "ch": OpenLayers.INCHES_PER_UNIT["IntnlChain"],  //International Chain
1053
    "link": OpenLayers.INCHES_PER_UNIT["IntnlLink"], //International Link
1054
    "us-in": OpenLayers.INCHES_PER_UNIT["inches"], //U.S. Surveyor's Inch
1055
    "us-ft": OpenLayers.INCHES_PER_UNIT["Foot"], //U.S. Surveyor's Foot
1056
    "us-yd": OpenLayers.INCHES_PER_UNIT["Yard"], //U.S. Surveyor's Yard
1057
    "us-ch": OpenLayers.INCHES_PER_UNIT["GunterChain"], //U.S. Surveyor's Chain
1058
    "us-mi": OpenLayers.INCHES_PER_UNIT["Mile"],   //U.S. Surveyor's Statute Mile
1059
    "ind-yd": OpenLayers.INCHES_PER_UNIT["IndianYd37"],  //Indian Yard
1060
    "ind-ft": OpenLayers.INCHES_PER_UNIT["IndianFt37"],  //Indian Foot
1061
    "ind-ch": 20.11669506 / OpenLayers.METERS_PER_INCH  //Indian Chain
1062
});
1063

    
1064
/** 
1065
 * Constant: DOTS_PER_INCH
1066
 * {Integer} 72 (A sensible default)
1067
 */
1068
OpenLayers.DOTS_PER_INCH = 72;
1069

    
1070
/**
1071
 * Function: normalizeScale
1072
 * 
1073
 * Parameters:
1074
 * scale - {float}
1075
 * 
1076
 * Returns:
1077
 * {Float} A normalized scale value, in 1 / X format. 
1078
 *         This means that if a value less than one ( already 1/x) is passed
1079
 *         in, it just returns scale directly. Otherwise, it returns 
1080
 *         1 / scale
1081
 */
1082
OpenLayers.Util.normalizeScale = function (scale) {
1083
    var normScale = (scale > 1.0) ? (1.0 / scale) 
1084
                                  : scale;
1085
    return normScale;
1086
};
1087

    
1088
/**
1089
 * Function: getResolutionFromScale
1090
 * 
1091
 * Parameters:
1092
 * scale - {Float}
1093
 * units - {String} Index into OpenLayers.INCHES_PER_UNIT hashtable.
1094
 *                  Default is degrees
1095
 * 
1096
 * Returns:
1097
 * {Float} The corresponding resolution given passed-in scale and unit 
1098
 *     parameters.  If the given scale is falsey, the returned resolution will
1099
 *     be undefined.
1100
 */
1101
OpenLayers.Util.getResolutionFromScale = function (scale, units) {
1102
    var resolution;
1103
    if (scale) {
1104
        if (units == null) {
1105
            units = "degrees";
1106
        }
1107
        var normScale = OpenLayers.Util.normalizeScale(scale);
1108
        resolution = 1 / (normScale * OpenLayers.INCHES_PER_UNIT[units]
1109
                                        * OpenLayers.DOTS_PER_INCH);        
1110
    }
1111
    return resolution;
1112
};
1113

    
1114
/**
1115
 * Function: getScaleFromResolution
1116
 * 
1117
 * Parameters:
1118
 * resolution - {Float}
1119
 * units - {String} Index into OpenLayers.INCHES_PER_UNIT hashtable.
1120
 *                  Default is degrees
1121
 * 
1122
 * Returns:
1123
 * {Float} The corresponding scale given passed-in resolution and unit 
1124
 *         parameters.
1125
 */
1126
OpenLayers.Util.getScaleFromResolution = function (resolution, units) {
1127

    
1128
    if (units == null) {
1129
        units = "degrees";
1130
    }
1131

    
1132
    var scale = resolution * OpenLayers.INCHES_PER_UNIT[units] *
1133
                    OpenLayers.DOTS_PER_INCH;
1134
    return scale;
1135
};
1136

    
1137
/**
1138
 * Function: pagePosition
1139
 * Calculates the position of an element on the page (see
1140
 * http://code.google.com/p/doctype/wiki/ArticlePageOffset)
1141
 *
1142
 * OpenLayers.Util.pagePosition is based on Yahoo's getXY method, which is
1143
 * Copyright (c) 2006, Yahoo! Inc.
1144
 * All rights reserved.
1145
 * 
1146
 * Redistribution and use of this software in source and binary forms, with or
1147
 * without modification, are permitted provided that the following conditions
1148
 * are met:
1149
 * 
1150
 * * Redistributions of source code must retain the above copyright notice,
1151
 *   this list of conditions and the following disclaimer.
1152
 * 
1153
 * * Redistributions in binary form must reproduce the above copyright notice,
1154
 *   this list of conditions and the following disclaimer in the documentation
1155
 *   and/or other materials provided with the distribution.
1156
 * 
1157
 * * Neither the name of Yahoo! Inc. nor the names of its contributors may be
1158
 *   used to endorse or promote products derived from this software without
1159
 *   specific prior written permission of Yahoo! Inc.
1160
 * 
1161
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
1162
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1163
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1164
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
1165
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
1166
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
1167
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
1168
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
1169
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
1170
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
1171
 * POSSIBILITY OF SUCH DAMAGE.
1172
 *
1173
 * Parameters:
1174
 * forElement - {DOMElement}
1175
 * 
1176
 * Returns:
1177
 * {Array} two item array, Left value then Top value.
1178
 */
1179
OpenLayers.Util.pagePosition =  function(forElement) {
1180
    // NOTE: If element is hidden (display none or disconnected or any the
1181
    // ancestors are hidden) we get (0,0) by default but we still do the
1182
    // accumulation of scroll position.
1183

    
1184
    var pos = [0, 0];
1185
    var viewportElement = OpenLayers.Util.getViewportElement();
1186
    if (!forElement || forElement == window || forElement == viewportElement) {
1187
        // viewport is always at 0,0 as that defined the coordinate system for
1188
        // this function - this avoids special case checks in the code below
1189
        return pos;
1190
    }
1191

    
1192
    // Gecko browsers normally use getBoxObjectFor to calculate the position.
1193
    // When invoked for an element with an implicit absolute position though it
1194
    // can be off by one. Therefore the recursive implementation is used in
1195
    // those (relatively rare) cases.
1196
    var BUGGY_GECKO_BOX_OBJECT =
1197
        OpenLayers.IS_GECKO && document.getBoxObjectFor &&
1198
        OpenLayers.Element.getStyle(forElement, 'position') == 'absolute' &&
1199
        (forElement.style.top == '' || forElement.style.left == '');
1200

    
1201
    var parent = null;
1202
    var box;
1203

    
1204
    if (forElement.getBoundingClientRect) { // IE
1205
        box = forElement.getBoundingClientRect();
1206
        var scrollTop = window.pageYOffset || viewportElement.scrollTop;
1207
        var scrollLeft = window.pageXOffset || viewportElement.scrollLeft;
1208
        
1209
        pos[0] = box.left + scrollLeft;
1210
        pos[1] = box.top + scrollTop;
1211

    
1212
    } else if (document.getBoxObjectFor && !BUGGY_GECKO_BOX_OBJECT) { // gecko
1213
        // Gecko ignores the scroll values for ancestors, up to 1.9.  See:
1214
        // https://bugzilla.mozilla.org/show_bug.cgi?id=328881 and
1215
        // https://bugzilla.mozilla.org/show_bug.cgi?id=330619
1216

    
1217
        box = document.getBoxObjectFor(forElement);
1218
        var vpBox = document.getBoxObjectFor(viewportElement);
1219
        pos[0] = box.screenX - vpBox.screenX;
1220
        pos[1] = box.screenY - vpBox.screenY;
1221

    
1222
    } else { // safari/opera
1223
        pos[0] = forElement.offsetLeft;
1224
        pos[1] = forElement.offsetTop;
1225
        parent = forElement.offsetParent;
1226
        if (parent != forElement) {
1227
            while (parent) {
1228
                pos[0] += parent.offsetLeft;
1229
                pos[1] += parent.offsetTop;
1230
                parent = parent.offsetParent;
1231
            }
1232
        }
1233

    
1234
        var browser = OpenLayers.BROWSER_NAME;
1235

    
1236
        // opera & (safari absolute) incorrectly account for body offsetTop
1237
        if (browser == "opera" || (browser == "safari" &&
1238
              OpenLayers.Element.getStyle(forElement, 'position') == 'absolute')) {
1239
            pos[1] -= document.body.offsetTop;
1240
        }
1241

    
1242
        // accumulate the scroll positions for everything but the body element
1243
        parent = forElement.offsetParent;
1244
        while (parent && parent != document.body) {
1245
            pos[0] -= parent.scrollLeft;
1246
            // see https://bugs.opera.com/show_bug.cgi?id=249965
1247
            if (browser != "opera" || parent.tagName != 'TR') {
1248
                pos[1] -= parent.scrollTop;
1249
            }
1250
            parent = parent.offsetParent;
1251
        }
1252
    }
1253
    
1254
    return pos;
1255
};
1256

    
1257
/**
1258
 * Function: getViewportElement
1259
 * Returns die viewport element of the document. The viewport element is
1260
 * usually document.documentElement, except in IE,where it is either
1261
 * document.body or document.documentElement, depending on the document's
1262
 * compatibility mode (see
1263
 * http://code.google.com/p/doctype/wiki/ArticleClientViewportElement)
1264
 *
1265
 * Returns:
1266
 * {DOMElement}
1267
 */
1268
OpenLayers.Util.getViewportElement = function() {
1269
    var viewportElement = arguments.callee.viewportElement;
1270
    if (viewportElement == undefined) {
1271
        viewportElement = (OpenLayers.BROWSER_NAME == "msie" &&
1272
            document.compatMode != 'CSS1Compat') ? document.body :
1273
            document.documentElement;
1274
        arguments.callee.viewportElement = viewportElement;
1275
    }
1276
    return viewportElement;
1277
};
1278

    
1279
/** 
1280
 * Function: isEquivalentUrl
1281
 * Test two URLs for equivalence. 
1282
 * 
1283
 * Setting 'ignoreCase' allows for case-independent comparison.
1284
 * 
1285
 * Comparison is based on: 
1286
 *  - Protocol
1287
 *  - Host (evaluated without the port)
1288
 *  - Port (set 'ignorePort80' to ignore "80" values)
1289
 *  - Hash ( set 'ignoreHash' to disable)
1290
 *  - Pathname (for relative <-> absolute comparison) 
1291
 *  - Arguments (so they can be out of order)
1292
 *  
1293
 * Parameters:
1294
 * url1 - {String}
1295
 * url2 - {String}
1296
 * options - {Object} Allows for customization of comparison:
1297
 *                    'ignoreCase' - Default is True
1298
 *                    'ignorePort80' - Default is True
1299
 *                    'ignoreHash' - Default is True
1300
 *
1301
 * Returns:
1302
 * {Boolean} Whether or not the two URLs are equivalent
1303
 */
1304
OpenLayers.Util.isEquivalentUrl = function(url1, url2, options) {
1305
    options = options || {};
1306

    
1307
    OpenLayers.Util.applyDefaults(options, {
1308
        ignoreCase: true,
1309
        ignorePort80: true,
1310
        ignoreHash: true,
1311
        splitArgs: false
1312
    });
1313

    
1314
    var urlObj1 = OpenLayers.Util.createUrlObject(url1, options);
1315
    var urlObj2 = OpenLayers.Util.createUrlObject(url2, options);
1316

    
1317
    //compare all keys except for "args" (treated below)
1318
    for(var key in urlObj1) {
1319
        if(key !== "args") {
1320
            if(urlObj1[key] != urlObj2[key]) {
1321
                return false;
1322
            }
1323
        }
1324
    }
1325

    
1326
    // compare search args - irrespective of order
1327
    for(var key in urlObj1.args) {
1328
        if(urlObj1.args[key] != urlObj2.args[key]) {
1329
            return false;
1330
        }
1331
        delete urlObj2.args[key];
1332
    }
1333
    // urlObj2 shouldn't have any args left
1334
    for(var key in urlObj2.args) {
1335
        return false;
1336
    }
1337
    
1338
    return true;
1339
};
1340

    
1341
/**
1342
 * Function: createUrlObject
1343
 * 
1344
 * Parameters:
1345
 * url - {String}
1346
 * options - {Object} A hash of options.
1347
 *
1348
 * Valid options:
1349
 *   ignoreCase - {Boolean} lowercase url,
1350
 *   ignorePort80 - {Boolean} don't include explicit port if port is 80,
1351
 *   ignoreHash - {Boolean} Don't include part of url after the hash (#).
1352
 *   splitArgs - {Boolean} Split comma delimited params into arrays? Default is
1353
 *       true.
1354
 * 
1355
 * Returns:
1356
 * {Object} An object with separate url, a, port, host, and args parsed out 
1357
 *          and ready for comparison
1358
 */
1359
OpenLayers.Util.createUrlObject = function(url, options) {
1360
    options = options || {};
1361

    
1362
    // deal with relative urls first
1363
    if(!(/^\w+:\/\//).test(url)) {
1364
        var loc = window.location;
1365
        var port = loc.port ? ":" + loc.port : "";
1366
        var fullUrl = loc.protocol + "//" + loc.host.split(":").shift() + port;
1367
        if(url.indexOf("/") === 0) {
1368
            // full pathname
1369
            url = fullUrl + url;
1370
        } else {
1371
            // relative to current path
1372
            var parts = loc.pathname.split("/");
1373
            parts.pop();
1374
            url = fullUrl + parts.join("/") + "/" + url;
1375
        }
1376
    }
1377
  
1378
    if (options.ignoreCase) {
1379
        url = url.toLowerCase(); 
1380
    }
1381

    
1382
    var a = document.createElement('a');
1383
    a.href = url;
1384
    
1385
    var urlObject = {};
1386
    
1387
    //host (without port)
1388
    urlObject.host = a.host.split(":").shift();
1389

    
1390
    //protocol
1391
    urlObject.protocol = a.protocol;  
1392

    
1393
    //port (get uniform browser behavior with port 80 here)
1394
    if(options.ignorePort80) {
1395
        urlObject.port = (a.port == "80" || a.port == "0") ? "" : a.port;
1396
    } else {
1397
        urlObject.port = (a.port == "" || a.port == "0") ? "80" : a.port;
1398
    }
1399

    
1400
    //hash
1401
    urlObject.hash = (options.ignoreHash || a.hash === "#") ? "" : a.hash;  
1402
    
1403
    //args
1404
    var queryString = a.search;
1405
    if (!queryString) {
1406
        var qMark = url.indexOf("?");
1407
        queryString = (qMark != -1) ? url.substr(qMark) : "";
1408
    }
1409
    urlObject.args = OpenLayers.Util.getParameters(queryString,
1410
            {splitArgs: options.splitArgs});
1411

    
1412
    // pathname
1413
    //
1414
    // This is a workaround for Internet Explorer where
1415
    // window.location.pathname has a leading "/", but
1416
    // a.pathname has no leading "/".
1417
    urlObject.pathname = (a.pathname.charAt(0) == "/") ? a.pathname : "/" + a.pathname;
1418
    
1419
    return urlObject; 
1420
};
1421
 
1422
/**
1423
 * Function: removeTail
1424
 * Takes a url and removes everything after the ? and #
1425
 * 
1426
 * Parameters:
1427
 * url - {String} The url to process
1428
 * 
1429
 * Returns:
1430
 * {String} The string with all queryString and Hash removed
1431
 */
1432
OpenLayers.Util.removeTail = function(url) {
1433
    var head = null;
1434
    
1435
    var qMark = url.indexOf("?");
1436
    var hashMark = url.indexOf("#");
1437

    
1438
    if (qMark == -1) {
1439
        head = (hashMark != -1) ? url.substr(0,hashMark) : url;
1440
    } else {
1441
        head = (hashMark != -1) ? url.substr(0,Math.min(qMark, hashMark)) 
1442
                                  : url.substr(0, qMark);
1443
    }
1444
    return head;
1445
};
1446

    
1447
/**
1448
 * Constant: IS_GECKO
1449
 * {Boolean} True if the userAgent reports the browser to use the Gecko engine
1450
 */
1451
OpenLayers.IS_GECKO = (function() {
1452
    var ua = navigator.userAgent.toLowerCase();
1453
    return ua.indexOf("webkit") == -1 && ua.indexOf("gecko") != -1;
1454
})();
1455

    
1456
/**
1457
 * Constant: CANVAS_SUPPORTED
1458
 * {Boolean} True if canvas 2d is supported.
1459
 */
1460
OpenLayers.CANVAS_SUPPORTED = (function() {
1461
    var elem = document.createElement('canvas');
1462
    return !!(elem.getContext && elem.getContext('2d'));
1463
})();
1464

    
1465
/**
1466
 * Constant: BROWSER_NAME
1467
 * {String}
1468
 * A substring of the navigator.userAgent property.  Depending on the userAgent
1469
 *     property, this will be the empty string or one of the following:
1470
 *     * "opera" -- Opera
1471
 *     * "msie"  -- Internet Explorer
1472
 *     * "safari" -- Safari
1473
 *     * "firefox" -- Firefox
1474
 *     * "mozilla" -- Mozilla
1475
 */
1476
OpenLayers.BROWSER_NAME = (function() {
1477
    var name = "";
1478
    var ua = navigator.userAgent.toLowerCase();
1479
    if (ua.indexOf("opera") != -1) {
1480
        name = "opera";
1481
    } else if (ua.indexOf("msie") != -1) {
1482
        name = "msie";
1483
    } else if (ua.indexOf("safari") != -1) {
1484
        name = "safari";
1485
    } else if (ua.indexOf("mozilla") != -1) {
1486
        if (ua.indexOf("firefox") != -1) {
1487
            name = "firefox";
1488
        } else {
1489
            name = "mozilla";
1490
        }
1491
    }
1492
    return name;
1493
})();
1494

    
1495
/**
1496
 * Function: getBrowserName
1497
 * 
1498
 * Returns:
1499
 * {String} A string which specifies which is the current 
1500
 *          browser in which we are running. 
1501
 * 
1502
 *          Currently-supported browser detection and codes:
1503
 *           * 'opera' -- Opera
1504
 *           * 'msie'  -- Internet Explorer
1505
 *           * 'safari' -- Safari
1506
 *           * 'firefox' -- Firefox
1507
 *           * 'mozilla' -- Mozilla
1508
 * 
1509
 *          If we are unable to property identify the browser, we 
1510
 *           return an empty string.
1511
 */
1512
OpenLayers.Util.getBrowserName = function() {
1513
    return OpenLayers.BROWSER_NAME;
1514
};
1515

    
1516
/**
1517
 * Method: getRenderedDimensions
1518
 * Renders the contentHTML offscreen to determine actual dimensions for
1519
 *     popup sizing. As we need layout to determine dimensions the content
1520
 *     is rendered -9999px to the left and absolute to ensure the 
1521
 *     scrollbars do not flicker
1522
 *     
1523
 * Parameters:
1524
 * contentHTML
1525
 * size - {<OpenLayers.Size>} If either the 'w' or 'h' properties is 
1526
 *     specified, we fix that dimension of the div to be measured. This is 
1527
 *     useful in the case where we have a limit in one dimension and must 
1528
 *     therefore meaure the flow in the other dimension.
1529
 * options - {Object}
1530
 *
1531
 * Allowed Options:
1532
 *     displayClass - {String} Optional parameter.  A CSS class name(s) string
1533
 *         to provide the CSS context of the rendered content.
1534
 *     containerElement - {DOMElement} Optional parameter. Insert the HTML to 
1535
 *         this node instead of the body root when calculating dimensions. 
1536
 * 
1537
 * Returns:
1538
 * {<OpenLayers.Size>}
1539
 */
1540
OpenLayers.Util.getRenderedDimensions = function(contentHTML, size, options) {
1541
    
1542
    var w, h;
1543
    
1544
    // create temp container div with restricted size
1545
    var container = document.createElement("div");
1546
    container.style.visibility = "hidden";
1547
        
1548
    var containerElement = (options && options.containerElement) 
1549
        ? options.containerElement : document.body;
1550
    
1551
    // Opera and IE7 can't handle a node with position:aboslute if it inherits
1552
    // position:absolute from a parent.
1553
    var parentHasPositionAbsolute = false;
1554
    var superContainer = null;
1555
    var parent = containerElement;
1556
    while (parent && parent.tagName.toLowerCase()!="body") {
1557
        var parentPosition = OpenLayers.Element.getStyle(parent, "position");
1558
        if(parentPosition == "absolute") {
1559
            parentHasPositionAbsolute = true;
1560
            break;
1561
        } else if (parentPosition && parentPosition != "static") {
1562
            break;
1563
        }
1564
        parent = parent.parentNode;
1565
    }
1566
    if(parentHasPositionAbsolute && (containerElement.clientHeight === 0 || 
1567
                                     containerElement.clientWidth === 0) ){
1568
        superContainer = document.createElement("div");
1569
        superContainer.style.visibility = "hidden";
1570
        superContainer.style.position = "absolute";
1571
        superContainer.style.overflow = "visible";
1572
        superContainer.style.width = document.body.clientWidth + "px";
1573
        superContainer.style.height = document.body.clientHeight + "px";
1574
        superContainer.appendChild(container);
1575
    }
1576
    container.style.position = "absolute";
1577

    
1578
    //fix a dimension, if specified.
1579
    if (size) {
1580
        if (size.w) {
1581
            w = size.w;
1582
            container.style.width = w + "px";
1583
        } else if (size.h) {
1584
            h = size.h;
1585
            container.style.height = h + "px";
1586
        }
1587
    }
1588

    
1589
    //add css classes, if specified
1590
    if (options && options.displayClass) {
1591
        container.className = options.displayClass;
1592
    }
1593
    
1594
    // create temp content div and assign content
1595
    var content = document.createElement("div");
1596
    content.innerHTML = contentHTML;
1597
    
1598
    // we need overflow visible when calculating the size
1599
    content.style.overflow = "visible";
1600
    if (content.childNodes) {
1601
        for (var i=0, l=content.childNodes.length; i<l; i++) {
1602
            if (!content.childNodes[i].style) continue;
1603
            content.childNodes[i].style.overflow = "visible";
1604
        }
1605
    }
1606
    
1607
    // add content to restricted container 
1608
    container.appendChild(content);
1609
    
1610
    // append container to body for rendering
1611
    if (superContainer) {
1612
        containerElement.appendChild(superContainer);
1613
    } else {
1614
        containerElement.appendChild(container);
1615
    }
1616
    
1617
    // calculate scroll width of content and add corners and shadow width
1618
    if (!w) {
1619
        w = parseInt(content.scrollWidth);
1620
    
1621
        // update container width to allow height to adjust
1622
        container.style.width = w + "px";
1623
    }        
1624
    // capture height and add shadow and corner image widths
1625
    if (!h) {
1626
        h = parseInt(content.scrollHeight);
1627
    }
1628

    
1629
    // remove elements
1630
    container.removeChild(content);
1631
    if (superContainer) {
1632
        superContainer.removeChild(container);
1633
        containerElement.removeChild(superContainer);
1634
    } else {
1635
        containerElement.removeChild(container);
1636
    }
1637
    
1638
    return new OpenLayers.Size(w, h);
1639
};
1640

    
1641
/**
1642
 * APIFunction: getScrollbarWidth
1643
 * This function has been modified by the OpenLayers from the original version,
1644
 *     written by Matthew Eernisse and released under the Apache 2 
1645
 *     license here:
1646
 * 
1647
 *     http://www.fleegix.org/articles/2006/05/30/getting-the-scrollbar-width-in-pixels
1648
 * 
1649
 *     It has been modified simply to cache its value, since it is physically 
1650
 *     impossible that this code could ever run in more than one browser at 
1651
 *     once. 
1652
 * 
1653
 * Returns:
1654
 * {Integer}
1655
 */
1656
OpenLayers.Util.getScrollbarWidth = function() {
1657
    
1658
    var scrollbarWidth = OpenLayers.Util._scrollbarWidth;
1659
    
1660
    if (scrollbarWidth == null) {
1661
        var scr = null;
1662
        var inn = null;
1663
        var wNoScroll = 0;
1664
        var wScroll = 0;
1665
    
1666
        // Outer scrolling div
1667
        scr = document.createElement('div');
1668
        scr.style.position = 'absolute';
1669
        scr.style.top = '-1000px';
1670
        scr.style.left = '-1000px';
1671
        scr.style.width = '100px';
1672
        scr.style.height = '50px';
1673
        // Start with no scrollbar
1674
        scr.style.overflow = 'hidden';
1675
    
1676
        // Inner content div
1677
        inn = document.createElement('div');
1678
        inn.style.width = '100%';
1679
        inn.style.height = '200px';
1680
    
1681
        // Put the inner div in the scrolling div
1682
        scr.appendChild(inn);
1683
        // Append the scrolling div to the doc
1684
        document.body.appendChild(scr);
1685
    
1686
        // Width of the inner div sans scrollbar
1687
        wNoScroll = inn.offsetWidth;
1688
    
1689
        // Add the scrollbar
1690
        scr.style.overflow = 'scroll';
1691
        // Width of the inner div width scrollbar
1692
        wScroll = inn.offsetWidth;
1693
    
1694
        // Remove the scrolling div from the doc
1695
        document.body.removeChild(document.body.lastChild);
1696
    
1697
        // Pixel width of the scroller
1698
        OpenLayers.Util._scrollbarWidth = (wNoScroll - wScroll);
1699
        scrollbarWidth = OpenLayers.Util._scrollbarWidth;
1700
    }
1701

    
1702
    return scrollbarWidth;
1703
};
1704

    
1705
/**
1706
 * APIFunction: getFormattedLonLat
1707
 * This function will return latitude or longitude value formatted as 
1708
 *
1709
 * Parameters:
1710
 * coordinate - {Float} the coordinate value to be formatted
1711
 * axis - {String} value of either 'lat' or 'lon' to indicate which axis is to
1712
 *          to be formatted (default = lat)
1713
 * dmsOption - {String} specify the precision of the output can be one of:
1714
 *           'dms' show degrees minutes and seconds
1715
 *           'dm' show only degrees and minutes
1716
 *           'd' show only degrees
1717
 * 
1718
 * Returns:
1719
 * {String} the coordinate value formatted as a string
1720
 */
1721
OpenLayers.Util.getFormattedLonLat = function(coordinate, axis, dmsOption) {
1722
    if (!dmsOption) {
1723
        dmsOption = 'dms';    //default to show degree, minutes, seconds
1724
    }
1725

    
1726
    coordinate = (coordinate+540)%360 - 180; // normalize for sphere being round
1727

    
1728
    var abscoordinate = Math.abs(coordinate);
1729
    var coordinatedegrees = Math.floor(abscoordinate);
1730

    
1731
    var coordinateminutes = (abscoordinate - coordinatedegrees)/(1/60);
1732
    var tempcoordinateminutes = coordinateminutes;
1733
    coordinateminutes = Math.floor(coordinateminutes);
1734
    var coordinateseconds = (tempcoordinateminutes - coordinateminutes)/(1/60);
1735
    coordinateseconds =  Math.round(coordinateseconds*10);
1736
    coordinateseconds /= 10;
1737

    
1738
    if( coordinateseconds >= 60) { 
1739
        coordinateseconds -= 60; 
1740
        coordinateminutes += 1; 
1741
        if( coordinateminutes >= 60) { 
1742
            coordinateminutes -= 60; 
1743
            coordinatedegrees += 1; 
1744
        } 
1745
    }
1746
    
1747
    if( coordinatedegrees < 10 ) {
1748
        coordinatedegrees = "0" + coordinatedegrees;
1749
    }
1750
    var str = coordinatedegrees + "\u00B0";
1751

    
1752
    if (dmsOption.indexOf('dm') >= 0) {
1753
        if( coordinateminutes < 10 ) {
1754
            coordinateminutes = "0" + coordinateminutes;
1755
        }
1756
        str += coordinateminutes + "'";
1757
  
1758
        if (dmsOption.indexOf('dms') >= 0) {
1759
            if( coordinateseconds < 10 ) {
1760
                coordinateseconds = "0" + coordinateseconds;
1761
            }
1762
            str += coordinateseconds + '"';
1763
        }
1764
    }
1765
    
1766
    if (axis == "lon") {
1767
        str += coordinate < 0 ? OpenLayers.i18n("W") : OpenLayers.i18n("E");
1768
    } else {
1769
        str += coordinate < 0 ? OpenLayers.i18n("S") : OpenLayers.i18n("N");
1770
    }
1771
    return str;
1772
};
1773

    
(33-33/35)