]> dev.renevier.net Git - syp.git/blob - openlayers/lib/OpenLayers/Util.js
initial commit
[syp.git] / openlayers / lib / OpenLayers / Util.js
1 /* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
2  * license.  See http://svn.openlayers.org/trunk/openlayers/license.txt for the
3  * full text of the license. */
4
5 /**
6  * @requires OpenLayers/Console.js
7  */
8
9 /**
10  * Namespace: Util
11  */
12 OpenLayers.Util = {};
13
14 /** 
15  * Function: getElement
16  * This is the old $() from prototype
17  */
18 OpenLayers.Util.getElement = function() {
19     var elements = [];
20
21     for (var i=0, len=arguments.length; i<len; i++) {
22         var element = arguments[i];
23         if (typeof element == 'string') {
24             element = document.getElementById(element);
25         }
26         if (arguments.length == 1) {
27             return element;
28         }
29         elements.push(element);
30     }
31     return elements;
32 };
33
34 /** 
35  * Maintain existing definition of $.
36  */
37 if(typeof window.$  === "undefined") {
38     window.$ = OpenLayers.Util.getElement;
39 }
40
41 /**
42  * APIFunction: extend
43  * Copy all properties of a source object to a destination object.  Modifies
44  *     the passed in destination object.  Any properties on the source object
45  *     that are set to undefined will not be (re)set on the destination object.
46  *
47  * Parameters:
48  * destination - {Object} The object that will be modified
49  * source - {Object} The object with properties to be set on the destination
50  *
51  * Returns:
52  * {Object} The destination object.
53  */
54 OpenLayers.Util.extend = function(destination, source) {
55     destination = destination || {};
56     if(source) {
57         for(var property in source) {
58             var value = source[property];
59             if(value !== undefined) {
60                 destination[property] = value;
61             }
62         }
63
64         /**
65          * IE doesn't include the toString property when iterating over an object's
66          * properties with the for(property in object) syntax.  Explicitly check if
67          * the source has its own toString property.
68          */
69
70         /*
71          * FF/Windows < 2.0.0.13 reports "Illegal operation on WrappedNative
72          * prototype object" when calling hawOwnProperty if the source object
73          * is an instance of window.Event.
74          */
75
76         var sourceIsEvt = typeof window.Event == "function"
77                           && source instanceof window.Event;
78
79         if(!sourceIsEvt
80            && source.hasOwnProperty && source.hasOwnProperty('toString')) {
81             destination.toString = source.toString;
82         }
83     }
84     return destination;
85 };
86
87
88 /** 
89  * Function: removeItem
90  * Remove an object from an array. Iterates through the array
91  *     to find the item, then removes it.
92  *
93  * Parameters:
94  * array - {Array}
95  * item - {Object}
96  * 
97  * Return
98  * {Array} A reference to the array
99  */
100 OpenLayers.Util.removeItem = function(array, item) {
101     for(var i = array.length - 1; i >= 0; i--) {
102         if(array[i] == item) {
103             array.splice(i,1);
104             //break;more than once??
105         }
106     }
107     return array;
108 };
109
110 /**
111  * Function: clearArray
112  * *Deprecated*. This function will disappear in 3.0.
113  * Please use "array.length = 0" instead.
114  * 
115  * Parameters:
116  * array - {Array}
117  */
118 OpenLayers.Util.clearArray = function(array) {
119     OpenLayers.Console.warn(
120         OpenLayers.i18n(
121             "methodDeprecated", {'newMethod': 'array = []'}
122         )
123     );
124     array.length = 0;
125 };
126
127 /** 
128  * Function: indexOf
129  * Seems to exist already in FF, but not in MOZ.
130  * 
131  * Parameters:
132  * array - {Array}
133  * obj - {Object}
134  * 
135  * Returns:
136  * {Integer} The index at, which the object was found in the array.
137  *           If not found, returns -1.
138  */
139 OpenLayers.Util.indexOf = function(array, obj) {
140
141     for(var i=0, len=array.length; i<len; i++) {
142         if (array[i] == obj) {
143             return i;
144         }
145     }
146     return -1;   
147 };
148
149
150
151 /**
152  * Function: modifyDOMElement
153  * 
154  * Modifies many properties of a DOM element all at once.  Passing in 
155  * null to an individual parameter will avoid setting the attribute.
156  *
157  * Parameters:
158  * id - {String} The element id attribute to set.
159  * px - {<OpenLayers.Pixel>} The left and top style position.
160  * sz - {<OpenLayers.Size>}  The width and height style attributes.
161  * position - {String}       The position attribute.  eg: absolute, 
162  *                           relative, etc.
163  * border - {String}         The style.border attribute.  eg:
164  *                           solid black 2px
165  * overflow - {String}       The style.overview attribute.  
166  * opacity - {Float}         Fractional value (0.0 - 1.0)
167  */
168 OpenLayers.Util.modifyDOMElement = function(element, id, px, sz, position, 
169                                             border, overflow, opacity) {
170
171     if (id) {
172         element.id = id;
173     }
174     if (px) {
175         element.style.left = px.x + "px";
176         element.style.top = px.y + "px";
177     }
178     if (sz) {
179         element.style.width = sz.w + "px";
180         element.style.height = sz.h + "px";
181     }
182     if (position) {
183         element.style.position = position;
184     }
185     if (border) {
186         element.style.border = border;
187     }
188     if (overflow) {
189         element.style.overflow = overflow;
190     }
191     if (parseFloat(opacity) >= 0.0 && parseFloat(opacity) < 1.0) {
192         element.style.filter = 'alpha(opacity=' + (opacity * 100) + ')';
193         element.style.opacity = opacity;
194     } else if (parseFloat(opacity) == 1.0) {
195         element.style.filter = '';
196         element.style.opacity = '';
197     }
198 };
199
200 /** 
201  * Function: createDiv
202  * Creates a new div and optionally set some standard attributes.
203  * Null may be passed to each parameter if you do not wish to
204  * set a particular attribute.
205  * Note - zIndex is NOT set on the resulting div.
206  * 
207  * Parameters:
208  * id - {String} An identifier for this element.  If no id is
209  *               passed an identifier will be created 
210  *               automatically.
211  * px - {<OpenLayers.Pixel>} The element left and top position. 
212  * sz - {<OpenLayers.Size>} The element width and height.
213  * imgURL - {String} A url pointing to an image to use as a 
214  *                   background image.
215  * position - {String} The style.position value. eg: absolute,
216  *                     relative etc.
217  * border - {String} The the style.border value. 
218  *                   eg: 2px solid black
219  * overflow - {String} The style.overflow value. Eg. hidden
220  * opacity - {Float} Fractional value (0.0 - 1.0)
221  * 
222  * Returns: 
223  * {DOMElement} A DOM Div created with the specified attributes.
224  */
225 OpenLayers.Util.createDiv = function(id, px, sz, imgURL, position, 
226                                      border, overflow, opacity) {
227
228     var dom = document.createElement('div');
229
230     if (imgURL) {
231         dom.style.backgroundImage = 'url(' + imgURL + ')';
232     }
233
234     //set generic properties
235     if (!id) {
236         id = OpenLayers.Util.createUniqueID("OpenLayersDiv");
237     }
238     if (!position) {
239         position = "absolute";
240     }
241     OpenLayers.Util.modifyDOMElement(dom, id, px, sz, position, 
242                                      border, overflow, opacity);
243
244     return dom;
245 };
246
247 /**
248  * Function: createImage
249  * Creates an img element with specific attribute values.
250  *  
251  * Parameters:
252  * id - {String} The id field for the img.  If none assigned one will be
253  *               automatically generated.
254  * px - {<OpenLayers.Pixel>} The left and top positions.
255  * sz - {<OpenLayers.Size>} The style.width and style.height values.
256  * imgURL - {String} The url to use as the image source.
257  * position - {String} The style.position value.
258  * border - {String} The border to place around the image.
259  * opacity - {Float} Fractional value (0.0 - 1.0)
260  * delayDisplay - {Boolean} If true waits until the image has been
261  *                          loaded.
262  * 
263  * Returns:
264  * {DOMElement} A DOM Image created with the specified attributes.
265  */
266 OpenLayers.Util.createImage = function(id, px, sz, imgURL, position, border,
267                                        opacity, delayDisplay) {
268
269     var image = document.createElement("img");
270
271     //set generic properties
272     if (!id) {
273         id = OpenLayers.Util.createUniqueID("OpenLayersDiv");
274     }
275     if (!position) {
276         position = "relative";
277     }
278     OpenLayers.Util.modifyDOMElement(image, id, px, sz, position, 
279                                      border, null, opacity);
280
281     if(delayDisplay) {
282         image.style.display = "none";
283         OpenLayers.Event.observe(image, "load", 
284             OpenLayers.Function.bind(OpenLayers.Util.onImageLoad, image));
285         OpenLayers.Event.observe(image, "error", 
286             OpenLayers.Function.bind(OpenLayers.Util.onImageLoadError, image));
287         
288     }
289     
290     //set special properties
291     image.style.alt = id;
292     image.galleryImg = "no";
293     if (imgURL) {
294         image.src = imgURL;
295     }
296
297
298         
299     return image;
300 };
301
302 /**
303  * Function: setOpacity
304  * *Deprecated*.  This function has been deprecated. Instead, please use 
305  *     <OpenLayers.Util.modifyDOMElement> 
306  *     or 
307  *     <OpenLayers.Util.modifyAlphaImageDiv>
308  * 
309  * Set the opacity of a DOM Element
310  *     Note that for this function to work in IE, elements must "have layout"
311  *     according to:
312  *     http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/haslayout.asp
313  *
314  * Parameters:
315  * element - {DOMElement} Set the opacity on this DOM element
316  * opacity - {Float} Opacity value (0.0 - 1.0)
317  */
318 OpenLayers.Util.setOpacity = function(element, opacity) {
319     OpenLayers.Util.modifyDOMElement(element, null, null, null,
320                                      null, null, null, opacity);
321 };
322
323 /**
324  * Function: onImageLoad
325  * Bound to image load events.  For all images created with <createImage> or
326  *     <createAlphaImageDiv>, this function will be bound to the load event.
327  */
328 OpenLayers.Util.onImageLoad = function() {
329     // The complex check here is to solve issues described in #480.
330     // Every time a map view changes, it increments the 'viewRequestID' 
331     // property. As the requests for the images for the new map view are sent
332     // out, they are tagged with this unique viewRequestID. 
333     // 
334     // If an image has no viewRequestID property set, we display it regardless, 
335     // but if it does have a viewRequestID property, we check that it matches 
336     // the viewRequestID set on the map.
337     // 
338     // If the viewRequestID on the map has changed, that means that the user
339     // has changed the map view since this specific request was sent out, and
340     // therefore this tile does not need to be displayed (so we do not execute
341     // this code that turns its display on).
342     //
343     if (!this.viewRequestID ||
344         (this.map && this.viewRequestID == this.map.viewRequestID)) { 
345         this.style.backgroundColor ="transparent";
346         this.style.display = "";  
347     }
348 };
349
350 /**
351  * Property: onImageLoadErrorColor
352  * {String} The color tiles with load errors will turn.
353  *          Default is "pink"
354  */
355 OpenLayers.Util.onImageLoadErrorColor = "pink";
356
357 /**
358  * Property: IMAGE_RELOAD_ATTEMPTS
359  * {Integer} How many times should we try to reload an image before giving up?
360  *           Default is 0
361  */
362 OpenLayers.IMAGE_RELOAD_ATTEMPTS = 0;
363
364 /**
365  * Function: onImageLoadError 
366  */
367 OpenLayers.Util.onImageLoadError = function() {
368     this._attempts = (this._attempts) ? (this._attempts + 1) : 1;
369     if (this._attempts <= OpenLayers.IMAGE_RELOAD_ATTEMPTS) {
370         var urls = this.urls;
371         if (urls && urls instanceof Array && urls.length > 1){
372             var src = this.src.toString();
373             var current_url, k;
374             for (k = 0; current_url = urls[k]; k++){
375                 if(src.indexOf(current_url) != -1){
376                     break;
377                 }
378             }
379             var guess = Math.floor(urls.length * Math.random());
380             var new_url = urls[guess];
381             k = 0;
382             while(new_url == current_url && k++ < 4){
383                 guess = Math.floor(urls.length * Math.random());
384                 new_url = urls[guess];
385             }
386             this.src = src.replace(current_url, new_url);
387         } else {
388             this.src = this.src;
389         }
390     } else {
391         this.style.backgroundColor = OpenLayers.Util.onImageLoadErrorColor;
392     }
393     this.style.display = "";
394 };
395
396 /**
397  * Property: alphaHackNeeded
398  * {Boolean} true if the png alpha hack is necessary and possible, false otherwise.
399  */
400 OpenLayers.Util.alphaHackNeeded = null;
401
402 /**
403  * Function: alphaHack
404  * Checks whether it's necessary (and possible) to use the png alpha
405  * hack which allows alpha transparency for png images under Internet
406  * Explorer.
407  * 
408  * Returns:
409  * {Boolean} true if the png alpha hack is necessary and possible, false otherwise.
410  */
411 OpenLayers.Util.alphaHack = function() {
412     if (OpenLayers.Util.alphaHackNeeded == null) {
413         var arVersion = navigator.appVersion.split("MSIE");
414         var version = parseFloat(arVersion[1]);
415         var filter = false;
416     
417         // IEs4Lin dies when trying to access document.body.filters, because 
418         // the property is there, but requires a DLL that can't be provided. This
419         // means that we need to wrap this in a try/catch so that this can
420         // continue.
421     
422         try { 
423             filter = !!(document.body.filters);
424         } catch (e) {}    
425     
426         OpenLayers.Util.alphaHackNeeded = (filter && 
427                                            (version >= 5.5) && (version < 7));
428     }
429     return OpenLayers.Util.alphaHackNeeded;
430 };
431
432 /** 
433  * Function: modifyAlphaImageDiv
434  * 
435  * div - {DOMElement} Div containing Alpha-adjusted Image
436  * id - {String}
437  * px - {<OpenLayers.Pixel>}
438  * sz - {<OpenLayers.Size>}
439  * imgURL - {String}
440  * position - {String}
441  * border - {String}
442  * sizing {String} 'crop', 'scale', or 'image'. Default is "scale"
443  * opacity - {Float} Fractional value (0.0 - 1.0)
444  */ 
445 OpenLayers.Util.modifyAlphaImageDiv = function(div, id, px, sz, imgURL, 
446                                                position, border, sizing, 
447                                                opacity) {
448
449     OpenLayers.Util.modifyDOMElement(div, id, px, sz, position,
450                                      null, null, opacity);
451
452     var img = div.childNodes[0];
453
454     if (imgURL) {
455         img.src = imgURL;
456     }
457     OpenLayers.Util.modifyDOMElement(img, div.id + "_innerImage", null, sz, 
458                                      "relative", border);
459     
460     if (OpenLayers.Util.alphaHack()) {
461         if(div.style.display != "none") {
462             div.style.display = "inline-block";
463         }
464         if (sizing == null) {
465             sizing = "scale";
466         }
467         
468         div.style.filter = "progid:DXImageTransform.Microsoft" +
469                            ".AlphaImageLoader(src='" + img.src + "', " +
470                            "sizingMethod='" + sizing + "')";
471         if (parseFloat(div.style.opacity) >= 0.0 && 
472             parseFloat(div.style.opacity) < 1.0) {
473             div.style.filter += " alpha(opacity=" + div.style.opacity * 100 + ")";
474         }
475
476         img.style.filter = "alpha(opacity=0)";
477     }
478 };
479
480 /** 
481  * Function: createAlphaImageDiv
482  * 
483  * id - {String}
484  * px - {<OpenLayers.Pixel>}
485  * sz - {<OpenLayers.Size>}
486  * imgURL - {String}
487  * position - {String}
488  * border - {String}
489  * sizing - {String} 'crop', 'scale', or 'image'. Default is "scale"
490  * opacity - {Float} Fractional value (0.0 - 1.0)
491  * delayDisplay - {Boolean} If true waits until the image has been
492  *                          loaded.
493  * 
494  * Returns:
495  * {DOMElement} A DOM Div created with a DOM Image inside it. If the hack is 
496  *              needed for transparency in IE, it is added.
497  */ 
498 OpenLayers.Util.createAlphaImageDiv = function(id, px, sz, imgURL, 
499                                                position, border, sizing, 
500                                                opacity, delayDisplay) {
501     
502     var div = OpenLayers.Util.createDiv();
503     var img = OpenLayers.Util.createImage(null, null, null, null, null, null, 
504                                           null, false);
505     div.appendChild(img);
506
507     if (delayDisplay) {
508         img.style.display = "none";
509         OpenLayers.Event.observe(img, "load",
510             OpenLayers.Function.bind(OpenLayers.Util.onImageLoad, div));
511         OpenLayers.Event.observe(img, "error",
512             OpenLayers.Function.bind(OpenLayers.Util.onImageLoadError, div));
513     }
514
515     OpenLayers.Util.modifyAlphaImageDiv(div, id, px, sz, imgURL, position, 
516                                         border, sizing, opacity);
517     
518     return div;
519 };
520
521
522 /** 
523  * Function: upperCaseObject
524  * Creates a new hashtable and copies over all the keys from the 
525  *     passed-in object, but storing them under an uppercased
526  *     version of the key at which they were stored.
527  * 
528  * Parameters: 
529  * object - {Object}
530  * 
531  * Returns: 
532  * {Object} A new Object with all the same keys but uppercased
533  */
534 OpenLayers.Util.upperCaseObject = function (object) {
535     var uObject = {};
536     for (var key in object) {
537         uObject[key.toUpperCase()] = object[key];
538     }
539     return uObject;
540 };
541
542 /** 
543  * Function: applyDefaults
544  * Takes an object and copies any properties that don't exist from
545  *     another properties, by analogy with OpenLayers.Util.extend() from
546  *     Prototype.js.
547  * 
548  * Parameters:
549  * to - {Object} The destination object.
550  * from - {Object} The source object.  Any properties of this object that
551  *     are undefined in the to object will be set on the to object.
552  *
553  * Returns:
554  * {Object} A reference to the to object.  Note that the to argument is modified
555  *     in place and returned by this function.
556  */
557 OpenLayers.Util.applyDefaults = function (to, from) {
558     to = to || {};
559     /*
560      * FF/Windows < 2.0.0.13 reports "Illegal operation on WrappedNative
561      * prototype object" when calling hawOwnProperty if the source object is an
562      * instance of window.Event.
563      */
564     var fromIsEvt = typeof window.Event == "function"
565                     && from instanceof window.Event;
566
567     for (var key in from) {
568         if (to[key] === undefined ||
569             (!fromIsEvt && from.hasOwnProperty
570              && from.hasOwnProperty(key) && !to.hasOwnProperty(key))) {
571             to[key] = from[key];
572         }
573     }
574     /**
575      * IE doesn't include the toString property when iterating over an object's
576      * properties with the for(property in object) syntax.  Explicitly check if
577      * the source has its own toString property.
578      */
579     if(!fromIsEvt && from && from.hasOwnProperty
580        && from.hasOwnProperty('toString') && !to.hasOwnProperty('toString')) {
581         to.toString = from.toString;
582     }
583     
584     return to;
585 };
586
587 /**
588  * Function: getParameterString
589  * 
590  * Parameters:
591  * params - {Object}
592  * 
593  * Returns:
594  * {String} A concatenation of the properties of an object in 
595  *          http parameter notation. 
596  *          (ex. <i>"key1=value1&key2=value2&key3=value3"</i>)
597  *          If a parameter is actually a list, that parameter will then
598  *          be set to a comma-seperated list of values (foo,bar) instead
599  *          of being URL escaped (foo%3Abar). 
600  */
601 OpenLayers.Util.getParameterString = function(params) {
602     var paramsArray = [];
603     
604     for (var key in params) {
605       var value = params[key];
606       if ((value != null) && (typeof value != 'function')) {
607         var encodedValue;
608         if (typeof value == 'object' && value.constructor == Array) {
609           /* value is an array; encode items and separate with "," */
610           var encodedItemArray = [];
611           for (var itemIndex=0, len=value.length; itemIndex<len; itemIndex++) {
612             encodedItemArray.push(encodeURIComponent(value[itemIndex]));
613           }
614           encodedValue = encodedItemArray.join(",");
615         }
616         else {
617           /* value is a string; simply encode */
618           encodedValue = encodeURIComponent(value);
619         }
620         paramsArray.push(encodeURIComponent(key) + "=" + encodedValue);
621       }
622     }
623     
624     return paramsArray.join("&");
625 };
626
627 /**
628  * Property: ImgPath
629  * {String} Default is ''.
630  */
631 OpenLayers.ImgPath = '';
632
633 /** 
634  * Function: getImagesLocation
635  * 
636  * Returns:
637  * {String} The fully formatted image location string
638  */
639 OpenLayers.Util.getImagesLocation = function() {
640     return OpenLayers.ImgPath || (OpenLayers._getScriptLocation() + "img/");
641 };
642
643
644 /** 
645  * Function: Try
646  * Execute functions until one of them doesn't throw an error. 
647  *     Capitalized because "try" is a reserved word in JavaScript.
648  *     Taken directly from OpenLayers.Util.Try()
649  * 
650  * Parameters:
651  * [*] - {Function} Any number of parameters may be passed to Try()
652  *    It will attempt to execute each of them until one of them 
653  *    successfully executes. 
654  *    If none executes successfully, returns null.
655  * 
656  * Returns:
657  * {*} The value returned by the first successfully executed function.
658  */
659 OpenLayers.Util.Try = function() {
660     var returnValue = null;
661
662     for (var i=0, len=arguments.length; i<len; i++) {
663       var lambda = arguments[i];
664       try {
665         returnValue = lambda();
666         break;
667       } catch (e) {}
668     }
669
670     return returnValue;
671 };
672
673
674 /** 
675  * Function: getNodes
676  * 
677  * These could/should be made namespace aware?
678  * 
679  * Parameters:
680  * p - {}
681  * tagName - {String}
682  * 
683  * Returns:
684  * {Array}
685  */
686 OpenLayers.Util.getNodes=function(p, tagName) {
687     var nodes = OpenLayers.Util.Try(
688         function () {
689             return OpenLayers.Util._getNodes(p.documentElement.childNodes,
690                                             tagName);
691         },
692         function () {
693             return OpenLayers.Util._getNodes(p.childNodes, tagName);
694         }
695     );
696     return nodes;
697 };
698
699 /**
700  * Function: _getNodes
701  * 
702  * Parameters:
703  * nodes - {Array}
704  * tagName - {String}
705  * 
706  * Returns:
707  * {Array}
708  */
709 OpenLayers.Util._getNodes=function(nodes, tagName) {
710     var retArray = [];
711     for (var i=0, len=nodes.length; i<len; i++) {
712         if (nodes[i].nodeName==tagName) {
713             retArray.push(nodes[i]);
714         }
715     }
716
717     return retArray;
718 };
719
720
721
722 /**
723  * Function: getTagText
724  * 
725  * Parameters:
726  * parent - {}
727  * item - {String}
728  * index - {Integer}
729  * 
730  * Returns:
731  * {String}
732  */
733 OpenLayers.Util.getTagText = function (parent, item, index) {
734     var result = OpenLayers.Util.getNodes(parent, item);
735     if (result && (result.length > 0))
736     {
737         if (!index) {
738             index=0;
739         }
740         if (result[index].childNodes.length > 1) {
741             return result.childNodes[1].nodeValue; 
742         }
743         else if (result[index].childNodes.length == 1) {
744             return result[index].firstChild.nodeValue; 
745         }
746     } else { 
747         return ""; 
748     }
749 };
750
751 /**
752  * Function: getXmlNodeValue
753  * 
754  * Parameters:
755  * node - {XMLNode}
756  * 
757  * Returns:
758  * {String} The text value of the given node, without breaking in firefox or IE
759  */
760 OpenLayers.Util.getXmlNodeValue = function(node) {
761     var val = null;
762     OpenLayers.Util.Try( 
763         function() {
764             val = node.text;
765             if (!val) {
766                 val = node.textContent;
767             }
768             if (!val) {
769                 val = node.firstChild.nodeValue;
770             }
771         }, 
772         function() {
773             val = node.textContent;
774         }); 
775     return val;
776 };
777
778 /** 
779  * Function: mouseLeft
780  * 
781  * Parameters:
782  * evt - {Event}
783  * div - {HTMLDivElement}
784  * 
785  * Returns:
786  * {Boolean}
787  */
788 OpenLayers.Util.mouseLeft = function (evt, div) {
789     // start with the element to which the mouse has moved
790     var target = (evt.relatedTarget) ? evt.relatedTarget : evt.toElement;
791     // walk up the DOM tree.
792     while (target != div && target != null) {
793         target = target.parentNode;
794     }
795     // if the target we stop at isn't the div, then we've left the div.
796     return (target != div);
797 };
798
799 /**
800  * Property: precision
801  * {Number} The number of significant digits to retain to avoid
802  * floating point precision errors.
803  *
804  * We use 14 as a "safe" default because, although IEEE 754 double floats
805  * (standard on most modern operating systems) support up to about 16
806  * significant digits, 14 significant digits are sufficient to represent
807  * sub-millimeter accuracy in any coordinate system that anyone is likely to
808  * use with OpenLayers.
809  *
810  * If DEFAULT_PRECISION is set to 0, the original non-truncating behavior
811  * of OpenLayers <2.8 is preserved. Be aware that this will cause problems
812  * with certain projections, e.g. spherical Mercator.
813  *
814  */
815 OpenLayers.Util.DEFAULT_PRECISION = 14;
816
817 /**
818  * Function: toFloat
819  * Convenience method to cast an object to a Number, rounded to the
820  * desired floating point precision.
821  *
822  * Parameters:
823  * number    - {Number} The number to cast and round.
824  * precision - {Number} An integer suitable for use with
825  *      Number.toPrecision(). Defaults to OpenLayers.Util.DEFAULT_PRECISION.
826  *      If set to 0, no rounding is performed.
827  *
828  * Returns:
829  * {Number} The cast, rounded number.
830  */
831 OpenLayers.Util.toFloat = function (number, precision) {
832     if (precision == null) {
833         precision = OpenLayers.Util.DEFAULT_PRECISION;
834     }
835     var number;
836     if (precision == 0) {
837         number = parseFloat(number);
838     } else {
839         number = parseFloat(parseFloat(number).toPrecision(precision));
840     }
841     return number;
842 };
843
844 /**
845  * Function: rad
846  * 
847  * Parameters:
848  * x - {Float}
849  * 
850  * Returns:
851  * {Float}
852  */
853 OpenLayers.Util.rad = function(x) {return x*Math.PI/180;};
854
855 /**
856  * Function: distVincenty
857  * Given two objects representing points with geographic coordinates, this
858  *     calculates the distance between those points on the surface of an
859  *     ellipsoid.
860  * 
861  * Parameters:
862  * p1 - {<OpenLayers.LonLat>} (or any object with both .lat, .lon properties)
863  * p2 - {<OpenLayers.LonLat>} (or any object with both .lat, .lon properties)
864  * 
865  * Returns:
866  * {Float} The distance (in km) between the two input points as measured on an
867  *     ellipsoid.  Note that the input point objects must be in geographic
868  *     coordinates (decimal degrees) and the return distance is in kilometers.
869  */
870 OpenLayers.Util.distVincenty=function(p1, p2) {
871     var a = 6378137, b = 6356752.3142,  f = 1/298.257223563;
872     var L = OpenLayers.Util.rad(p2.lon - p1.lon);
873     var U1 = Math.atan((1-f) * Math.tan(OpenLayers.Util.rad(p1.lat)));
874     var U2 = Math.atan((1-f) * Math.tan(OpenLayers.Util.rad(p2.lat)));
875     var sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);
876     var sinU2 = Math.sin(U2), cosU2 = Math.cos(U2);
877     var lambda = L, lambdaP = 2*Math.PI;
878     var iterLimit = 20;
879     while (Math.abs(lambda-lambdaP) > 1e-12 && --iterLimit>0) {
880         var sinLambda = Math.sin(lambda), cosLambda = Math.cos(lambda);
881         var sinSigma = Math.sqrt((cosU2*sinLambda) * (cosU2*sinLambda) +
882         (cosU1*sinU2-sinU1*cosU2*cosLambda) * (cosU1*sinU2-sinU1*cosU2*cosLambda));
883         if (sinSigma==0) {
884             return 0;  // co-incident points
885         }
886         var cosSigma = sinU1*sinU2 + cosU1*cosU2*cosLambda;
887         var sigma = Math.atan2(sinSigma, cosSigma);
888         var alpha = Math.asin(cosU1 * cosU2 * sinLambda / sinSigma);
889         var cosSqAlpha = Math.cos(alpha) * Math.cos(alpha);
890         var cos2SigmaM = cosSigma - 2*sinU1*sinU2/cosSqAlpha;
891         var C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));
892         lambdaP = lambda;
893         lambda = L + (1-C) * f * Math.sin(alpha) *
894         (sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));
895     }
896     if (iterLimit==0) {
897         return NaN;  // formula failed to converge
898     }
899     var uSq = cosSqAlpha * (a*a - b*b) / (b*b);
900     var A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));
901     var B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)));
902     var deltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-
903         B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));
904     var s = b*A*(sigma-deltaSigma);
905     var d = s.toFixed(3)/1000; // round to 1mm precision
906     return d;
907 };
908
909 /**
910  * Function: getParameters
911  * Parse the parameters from a URL or from the current page itself into a 
912  *     JavaScript Object. Note that parameter values with commas are separated
913  *     out into an Array.
914  * 
915  * Parameters:
916  * url - {String} Optional url used to extract the query string.
917  *                If null, query string is taken from page location.
918  * 
919  * Returns:
920  * {Object} An object of key/value pairs from the query string.
921  */
922 OpenLayers.Util.getParameters = function(url) {
923     // if no url specified, take it from the location bar
924     url = url || window.location.href;
925
926     //parse out parameters portion of url string
927     var paramsString = "";
928     if (OpenLayers.String.contains(url, '?')) {
929         var start = url.indexOf('?') + 1;
930         var end = OpenLayers.String.contains(url, "#") ?
931                     url.indexOf('#') : url.length;
932         paramsString = url.substring(start, end);
933     }
934         
935     var parameters = {};
936     var pairs = paramsString.split(/[&;]/);
937     for(var i=0, len=pairs.length; i<len; ++i) {
938         var keyValue = pairs[i].split('=');
939         if (keyValue[0]) {
940             var key = decodeURIComponent(keyValue[0]);
941             var value = keyValue[1] || ''; //empty string if no value
942
943             //decode individual values
944             value = value.split(",");
945             for(var j=0, jlen=value.length; j<jlen; j++) {
946                 value[j] = decodeURIComponent(value[j]);
947             }
948
949             //if there's only one value, do not return as array                    
950             if (value.length == 1) {
951                 value = value[0];
952             }                
953             
954             parameters[key] = value;
955          }
956      }
957     return parameters;
958 };
959
960 /**
961  * Function: getArgs
962  * *Deprecated*.  Will be removed in 3.0.  Please use instead
963  *     <OpenLayers.Util.getParameters>
964  * 
965  * Parameters:
966  * url - {String} Optional url used to extract the query string.
967  *                If null, query string is taken from page location.
968  * 
969  * Returns:
970  * {Object} An object of key/value pairs from the query string.
971  */
972 OpenLayers.Util.getArgs = function(url) {
973     OpenLayers.Console.warn(
974         OpenLayers.i18n(
975             "methodDeprecated", {'newMethod': 'OpenLayers.Util.getParameters'}
976         )
977     );
978     return OpenLayers.Util.getParameters(url);
979 };
980
981 /**
982  * Property: lastSeqID
983  * {Integer} The ever-incrementing count variable.
984  *           Used for generating unique ids.
985  */
986 OpenLayers.Util.lastSeqID = 0;
987
988 /**
989  * Function: createUniqueID
990  * Create a unique identifier for this session.  Each time this function
991  *     is called, a counter is incremented.  The return will be the optional
992  *     prefix (defaults to "id_") appended with the counter value.
993  * 
994  * Parameters:
995  * prefix {String} Optionsal string to prefix unique id. Default is "id_".
996  * 
997  * Returns:
998  * {String} A unique id string, built on the passed in prefix.
999  */
1000 OpenLayers.Util.createUniqueID = function(prefix) {
1001     if (prefix == null) {
1002         prefix = "id_";
1003     }
1004     OpenLayers.Util.lastSeqID += 1; 
1005     return prefix + OpenLayers.Util.lastSeqID;        
1006 };
1007
1008 /**
1009  * Constant: INCHES_PER_UNIT
1010  * {Object} Constant inches per unit -- borrowed from MapServer mapscale.c
1011  * derivation of nautical miles from http://en.wikipedia.org/wiki/Nautical_mile
1012  * Includes the full set of units supported by CS-MAP (http://trac.osgeo.org/csmap/)
1013  * and PROJ.4 (http://trac.osgeo.org/proj/)
1014  * The hardcoded table is maintain in a CS-MAP source code module named CSdataU.c
1015  * The hardcoded table of PROJ.4 units are in pj_units.c.
1016  */
1017 OpenLayers.INCHES_PER_UNIT = { 
1018     'inches': 1.0,
1019     'ft': 12.0,
1020     'mi': 63360.0,
1021     'm': 39.3701,
1022     'km': 39370.1,
1023     'dd': 4374754,
1024     'yd': 36
1025 };
1026 OpenLayers.INCHES_PER_UNIT["in"]= OpenLayers.INCHES_PER_UNIT.inches;
1027 OpenLayers.INCHES_PER_UNIT["degrees"] = OpenLayers.INCHES_PER_UNIT.dd;
1028 OpenLayers.INCHES_PER_UNIT["nmi"] = 1852 * OpenLayers.INCHES_PER_UNIT.m;
1029
1030 // Units from CS-Map
1031 OpenLayers.METERS_PER_INCH = 0.02540005080010160020;
1032 OpenLayers.Util.extend(OpenLayers.INCHES_PER_UNIT, {
1033     "Inch": OpenLayers.INCHES_PER_UNIT.inches,
1034     "Meter": 1.0 / OpenLayers.METERS_PER_INCH,   //EPSG:9001
1035     "Foot": 0.30480060960121920243 / OpenLayers.METERS_PER_INCH,   //EPSG:9003
1036     "IFoot": 0.30480000000000000000 / OpenLayers.METERS_PER_INCH,   //EPSG:9002
1037     "ClarkeFoot": 0.3047972651151 / OpenLayers.METERS_PER_INCH,   //EPSG:9005
1038     "SearsFoot": 0.30479947153867624624 / OpenLayers.METERS_PER_INCH,   //EPSG:9041
1039     "GoldCoastFoot": 0.30479971018150881758 / OpenLayers.METERS_PER_INCH,   //EPSG:9094
1040     "IInch": 0.02540000000000000000 / OpenLayers.METERS_PER_INCH,
1041     "MicroInch": 0.00002540000000000000 / OpenLayers.METERS_PER_INCH,
1042     "Mil": 0.00000002540000000000 / OpenLayers.METERS_PER_INCH,
1043     "Centimeter": 0.01000000000000000000 / OpenLayers.METERS_PER_INCH,
1044     "Kilometer": 1000.00000000000000000000 / OpenLayers.METERS_PER_INCH,   //EPSG:9036
1045     "Yard": 0.91440182880365760731 / OpenLayers.METERS_PER_INCH,
1046     "SearsYard": 0.914398414616029 / OpenLayers.METERS_PER_INCH,   //EPSG:9040
1047     "IndianYard": 0.91439853074444079983 / OpenLayers.METERS_PER_INCH,   //EPSG:9084
1048     "IndianYd37": 0.91439523 / OpenLayers.METERS_PER_INCH,   //EPSG:9085
1049     "IndianYd62": 0.9143988 / OpenLayers.METERS_PER_INCH,   //EPSG:9086
1050     "IndianYd75": 0.9143985 / OpenLayers.METERS_PER_INCH,   //EPSG:9087
1051     "IndianFoot": 0.30479951 / OpenLayers.METERS_PER_INCH,   //EPSG:9080
1052     "IndianFt37": 0.30479841 / OpenLayers.METERS_PER_INCH,   //EPSG:9081
1053     "IndianFt62": 0.3047996 / OpenLayers.METERS_PER_INCH,   //EPSG:9082
1054     "IndianFt75": 0.3047995 / OpenLayers.METERS_PER_INCH,   //EPSG:9083
1055     "Mile": 1609.34721869443738887477 / OpenLayers.METERS_PER_INCH,
1056     "IYard": 0.91440000000000000000 / OpenLayers.METERS_PER_INCH,   //EPSG:9096
1057     "IMile": 1609.34400000000000000000 / OpenLayers.METERS_PER_INCH,   //EPSG:9093
1058     "NautM": 1852.00000000000000000000 / OpenLayers.METERS_PER_INCH,   //EPSG:9030
1059     "Lat-66": 110943.316488932731 / OpenLayers.METERS_PER_INCH,
1060     "Lat-83": 110946.25736872234125 / OpenLayers.METERS_PER_INCH,
1061     "Decimeter": 0.10000000000000000000 / OpenLayers.METERS_PER_INCH,
1062     "Millimeter": 0.00100000000000000000 / OpenLayers.METERS_PER_INCH,
1063     "Dekameter": 10.00000000000000000000 / OpenLayers.METERS_PER_INCH,
1064     "Decameter": 10.00000000000000000000 / OpenLayers.METERS_PER_INCH,
1065     "Hectometer": 100.00000000000000000000 / OpenLayers.METERS_PER_INCH,
1066     "GermanMeter": 1.0000135965 / OpenLayers.METERS_PER_INCH,   //EPSG:9031
1067     "CaGrid": 0.999738 / OpenLayers.METERS_PER_INCH,
1068     "ClarkeChain": 20.1166194976 / OpenLayers.METERS_PER_INCH,   //EPSG:9038
1069     "GunterChain": 20.11684023368047 / OpenLayers.METERS_PER_INCH,   //EPSG:9033
1070     "BenoitChain": 20.116782494375872 / OpenLayers.METERS_PER_INCH,   //EPSG:9062
1071     "SearsChain": 20.11676512155 / OpenLayers.METERS_PER_INCH,   //EPSG:9042
1072     "ClarkeLink": 0.201166194976 / OpenLayers.METERS_PER_INCH,   //EPSG:9039
1073     "GunterLink": 0.2011684023368047 / OpenLayers.METERS_PER_INCH,   //EPSG:9034
1074     "BenoitLink": 0.20116782494375872 / OpenLayers.METERS_PER_INCH,   //EPSG:9063
1075     "SearsLink": 0.2011676512155 / OpenLayers.METERS_PER_INCH,   //EPSG:9043
1076     "Rod": 5.02921005842012 / OpenLayers.METERS_PER_INCH,
1077     "IntnlChain": 20.1168 / OpenLayers.METERS_PER_INCH,   //EPSG:9097
1078     "IntnlLink": 0.201168 / OpenLayers.METERS_PER_INCH,   //EPSG:9098
1079     "Perch": 5.02921005842012 / OpenLayers.METERS_PER_INCH,
1080     "Pole": 5.02921005842012 / OpenLayers.METERS_PER_INCH,
1081     "Furlong": 201.1684023368046 / OpenLayers.METERS_PER_INCH,
1082     "Rood": 3.778266898 / OpenLayers.METERS_PER_INCH,
1083     "CapeFoot": 0.3047972615 / OpenLayers.METERS_PER_INCH,
1084     "Brealey": 375.00000000000000000000 / OpenLayers.METERS_PER_INCH,
1085     "ModAmFt": 0.304812252984505969011938 / OpenLayers.METERS_PER_INCH,
1086     "Fathom": 1.8288 / OpenLayers.METERS_PER_INCH,
1087     "NautM-UK": 1853.184 / OpenLayers.METERS_PER_INCH,
1088     "50kilometers": 50000.0 / OpenLayers.METERS_PER_INCH,
1089     "150kilometers": 150000.0 / OpenLayers.METERS_PER_INCH
1090 });
1091
1092 //unit abbreviations supported by PROJ.4
1093 OpenLayers.Util.extend(OpenLayers.INCHES_PER_UNIT, {
1094     "mm": OpenLayers.INCHES_PER_UNIT["Meter"] / 1000.0,
1095     "cm": OpenLayers.INCHES_PER_UNIT["Meter"] / 100.0,
1096     "dm": OpenLayers.INCHES_PER_UNIT["Meter"] * 100.0,
1097     "km": OpenLayers.INCHES_PER_UNIT["Meter"] * 1000.0,
1098     "kmi": OpenLayers.INCHES_PER_UNIT["nmi"],    //International Nautical Mile
1099     "fath": OpenLayers.INCHES_PER_UNIT["Fathom"], //International Fathom
1100     "ch": OpenLayers.INCHES_PER_UNIT["IntnlChain"],  //International Chain
1101     "link": OpenLayers.INCHES_PER_UNIT["IntnlLink"], //International Link
1102     "us-in": OpenLayers.INCHES_PER_UNIT["inches"], //U.S. Surveyor's Inch
1103     "us-ft": OpenLayers.INCHES_PER_UNIT["Foot"],        //U.S. Surveyor's Foot
1104     "us-yd": OpenLayers.INCHES_PER_UNIT["Yard"],        //U.S. Surveyor's Yard
1105     "us-ch": OpenLayers.INCHES_PER_UNIT["GunterChain"], //U.S. Surveyor's Chain
1106     "us-mi": OpenLayers.INCHES_PER_UNIT["Mile"],   //U.S. Surveyor's Statute Mile
1107     "ind-yd": OpenLayers.INCHES_PER_UNIT["IndianYd37"],  //Indian Yard
1108     "ind-ft": OpenLayers.INCHES_PER_UNIT["IndianFt37"],  //Indian Foot
1109     "ind-ch": 20.11669506 / OpenLayers.METERS_PER_INCH  //Indian Chain
1110 });
1111
1112 /** 
1113  * Constant: DOTS_PER_INCH
1114  * {Integer} 72 (A sensible default)
1115  */
1116 OpenLayers.DOTS_PER_INCH = 72;
1117
1118 /**
1119  * Function: normalizeScale
1120  * 
1121  * Parameters:
1122  * scale - {float}
1123  * 
1124  * Returns:
1125  * {Float} A normalized scale value, in 1 / X format. 
1126  *         This means that if a value less than one ( already 1/x) is passed
1127  *         in, it just returns scale directly. Otherwise, it returns 
1128  *         1 / scale
1129  */
1130 OpenLayers.Util.normalizeScale = function (scale) {
1131     var normScale = (scale > 1.0) ? (1.0 / scale) 
1132                                   : scale;
1133     return normScale;
1134 };
1135
1136 /**
1137  * Function: getResolutionFromScale
1138  * 
1139  * Parameters:
1140  * scale - {Float}
1141  * units - {String} Index into OpenLayers.INCHES_PER_UNIT hashtable.
1142  *                  Default is degrees
1143  * 
1144  * Returns:
1145  * {Float} The corresponding resolution given passed-in scale and unit 
1146  *         parameters.
1147  */
1148 OpenLayers.Util.getResolutionFromScale = function (scale, units) {
1149
1150     if (units == null) {
1151         units = "degrees";
1152     }
1153
1154     var normScale = OpenLayers.Util.normalizeScale(scale);
1155
1156     var resolution = 1 / (normScale * OpenLayers.INCHES_PER_UNIT[units]
1157                                     * OpenLayers.DOTS_PER_INCH);
1158     return resolution;
1159 };
1160
1161 /**
1162  * Function: getScaleFromResolution
1163  * 
1164  * Parameters:
1165  * resolution - {Float}
1166  * units - {String} Index into OpenLayers.INCHES_PER_UNIT hashtable.
1167  *                  Default is degrees
1168  * 
1169  * Returns:
1170  * {Float} The corresponding scale given passed-in resolution and unit 
1171  *         parameters.
1172  */
1173 OpenLayers.Util.getScaleFromResolution = function (resolution, units) {
1174
1175     if (units == null) {
1176         units = "degrees";
1177     }
1178
1179     var scale = resolution * OpenLayers.INCHES_PER_UNIT[units] *
1180                     OpenLayers.DOTS_PER_INCH;
1181     return scale;
1182 };
1183
1184 /**
1185  * Function: safeStopPropagation
1186  * *Deprecated*. This function has been deprecated. Please use directly 
1187  *     <OpenLayers.Event.stop> passing 'true' as the 2nd 
1188  *     argument (preventDefault)
1189  * 
1190  * Safely stop the propagation of an event *without* preventing
1191  *   the default browser action from occurring.
1192  * 
1193  * Parameter:
1194  * evt - {Event}
1195  */
1196 OpenLayers.Util.safeStopPropagation = function(evt) {
1197     OpenLayers.Event.stop(evt, true);
1198 };
1199
1200 /**
1201  * Function: pagePositon
1202  * Calculates the position of an element on the page. 
1203  *
1204  * Parameters:
1205  * forElement - {DOMElement}
1206  * 
1207  * Returns:
1208  * {Array} two item array, L value then T value.
1209  */
1210 OpenLayers.Util.pagePosition = function(forElement) {
1211     var valueT = 0, valueL = 0;
1212
1213     var element = forElement;
1214     var child = forElement;
1215     while(element) {
1216
1217         if(element == document.body) {
1218             if(OpenLayers.Element.getStyle(child, 'position') == 'absolute') {
1219                 break;
1220             }
1221         }
1222         
1223         valueT += element.offsetTop  || 0;
1224         valueL += element.offsetLeft || 0;
1225
1226         child = element;
1227         try {
1228             // wrapping this in a try/catch because IE chokes on the offsetParent
1229             element = element.offsetParent;
1230         } catch(e) {
1231             OpenLayers.Console.error(OpenLayers.i18n(
1232                                   "pagePositionFailed",{'elemId':element.id}));
1233             break;
1234         }
1235     }
1236
1237     element = forElement;
1238     while(element) {
1239         valueT -= element.scrollTop  || 0;
1240         valueL -= element.scrollLeft || 0;
1241         element = element.parentNode;
1242     }
1243     
1244     return [valueL, valueT];
1245 };
1246
1247
1248 /** 
1249  * Function: isEquivalentUrl
1250  * Test two URLs for equivalence. 
1251  * 
1252  * Setting 'ignoreCase' allows for case-independent comparison.
1253  * 
1254  * Comparison is based on: 
1255  *  - Protocol
1256  *  - Host (evaluated without the port)
1257  *  - Port (set 'ignorePort80' to ignore "80" values)
1258  *  - Hash ( set 'ignoreHash' to disable)
1259  *  - Pathname (for relative <-> absolute comparison) 
1260  *  - Arguments (so they can be out of order)
1261  *  
1262  * Parameters:
1263  * url1 - {String}
1264  * url2 - {String}
1265  * options - {Object} Allows for customization of comparison:
1266  *                    'ignoreCase' - Default is True
1267  *                    'ignorePort80' - Default is True
1268  *                    'ignoreHash' - Default is True
1269  *
1270  * Returns:
1271  * {Boolean} Whether or not the two URLs are equivalent
1272  */
1273 OpenLayers.Util.isEquivalentUrl = function(url1, url2, options) {
1274     options = options || {};
1275
1276     OpenLayers.Util.applyDefaults(options, {
1277         ignoreCase: true,
1278         ignorePort80: true,
1279         ignoreHash: true
1280     });
1281
1282     var urlObj1 = OpenLayers.Util.createUrlObject(url1, options);
1283     var urlObj2 = OpenLayers.Util.createUrlObject(url2, options);
1284
1285     //compare all keys except for "args" (treated below)
1286     for(var key in urlObj1) {
1287         if(key !== "args") {
1288             if(urlObj1[key] != urlObj2[key]) {
1289                 return false;
1290             }
1291         }
1292     }
1293
1294     // compare search args - irrespective of order
1295     for(var key in urlObj1.args) {
1296         if(urlObj1.args[key] != urlObj2.args[key]) {
1297             return false;
1298         }
1299         delete urlObj2.args[key];
1300     }
1301     // urlObj2 shouldn't have any args left
1302     for(var key in urlObj2.args) {
1303         return false;
1304     }
1305     
1306     return true;
1307 };
1308
1309 /**
1310  * Function: createUrlObject
1311  * 
1312  * Parameters:
1313  * url - {String}
1314  * options - {Object} A hash of options.  Can be one of:
1315  *            ignoreCase: lowercase url,
1316  *            ignorePort80: don't include explicit port if port is 80,
1317  *            ignoreHash: Don't include part of url after the hash (#).
1318  * 
1319  * Returns:
1320  * {Object} An object with separate url, a, port, host, and args parsed out 
1321  *          and ready for comparison
1322  */
1323 OpenLayers.Util.createUrlObject = function(url, options) {
1324     options = options || {};
1325
1326     // deal with relative urls first
1327     if(!(/^\w+:\/\//).test(url)) {
1328         var loc = window.location;
1329         var port = loc.port ? ":" + loc.port : "";
1330         var fullUrl = loc.protocol + "//" + loc.host.split(":").shift() + port;
1331         if(url.indexOf("/") === 0) {
1332             // full pathname
1333             url = fullUrl + url;
1334         } else {
1335             // relative to current path
1336             var parts = loc.pathname.split("/");
1337             parts.pop();
1338             url = fullUrl + parts.join("/") + "/" + url;
1339         }
1340     }
1341   
1342     if (options.ignoreCase) {
1343         url = url.toLowerCase(); 
1344     }
1345
1346     var a = document.createElement('a');
1347     a.href = url;
1348     
1349     var urlObject = {};
1350     
1351     //host (without port)
1352     urlObject.host = a.host.split(":").shift();
1353
1354     //protocol
1355     urlObject.protocol = a.protocol;  
1356
1357     //port (get uniform browser behavior with port 80 here)
1358     if(options.ignorePort80) {
1359         urlObject.port = (a.port == "80" || a.port == "0") ? "" : a.port;
1360     } else {
1361         urlObject.port = (a.port == "" || a.port == "0") ? "80" : a.port;
1362     }
1363
1364     //hash
1365     urlObject.hash = (options.ignoreHash || a.hash === "#") ? "" : a.hash;  
1366     
1367     //args
1368     var queryString = a.search;
1369     if (!queryString) {
1370         var qMark = url.indexOf("?");
1371         queryString = (qMark != -1) ? url.substr(qMark) : "";
1372     }
1373     urlObject.args = OpenLayers.Util.getParameters(queryString);
1374
1375     //pathname (uniform browser behavior with leading "/")
1376     urlObject.pathname = (a.pathname.charAt(0) == "/") ? a.pathname : "/" + a.pathname;
1377     
1378     return urlObject; 
1379 };
1380  
1381 /**
1382  * Function: removeTail
1383  * Takes a url and removes everything after the ? and #
1384  * 
1385  * Parameters:
1386  * url - {String} The url to process
1387  * 
1388  * Returns:
1389  * {String} The string with all queryString and Hash removed
1390  */
1391 OpenLayers.Util.removeTail = function(url) {
1392     var head = null;
1393     
1394     var qMark = url.indexOf("?");
1395     var hashMark = url.indexOf("#");
1396
1397     if (qMark == -1) {
1398         head = (hashMark != -1) ? url.substr(0,hashMark) : url;
1399     } else {
1400         head = (hashMark != -1) ? url.substr(0,Math.min(qMark, hashMark)) 
1401                                   : url.substr(0, qMark);
1402     }
1403     return head;
1404 };
1405
1406
1407 /**
1408  * Function: getBrowserName
1409  * 
1410  * Returns:
1411  * {String} A string which specifies which is the current 
1412  *          browser in which we are running. 
1413  * 
1414  *          Currently-supported browser detection and codes:
1415  *           * 'opera' -- Opera
1416  *           * 'msie'  -- Internet Explorer
1417  *           * 'safari' -- Safari
1418  *           * 'firefox' -- FireFox
1419  *           * 'mozilla' -- Mozilla
1420  * 
1421  *          If we are unable to property identify the browser, we 
1422  *           return an empty string.
1423  */
1424 OpenLayers.Util.getBrowserName = function() {
1425     var browserName = "";
1426     
1427     var ua = navigator.userAgent.toLowerCase();
1428     if ( ua.indexOf( "opera" ) != -1 ) {
1429         browserName = "opera";
1430     } else if ( ua.indexOf( "msie" ) != -1 ) {
1431         browserName = "msie";
1432     } else if ( ua.indexOf( "safari" ) != -1 ) {
1433         browserName = "safari";
1434     } else if ( ua.indexOf( "mozilla" ) != -1 ) {
1435         if ( ua.indexOf( "firefox" ) != -1 ) {
1436             browserName = "firefox";
1437         } else {
1438             browserName = "mozilla";
1439         }
1440     }
1441     
1442     return browserName;
1443 };
1444
1445
1446
1447     
1448 /**
1449  * Method: getRenderedDimensions
1450  * Renders the contentHTML offscreen to determine actual dimensions for
1451  *     popup sizing. As we need layout to determine dimensions the content
1452  *     is rendered -9999px to the left and absolute to ensure the 
1453  *     scrollbars do not flicker
1454  *     
1455  * Parameters:
1456  * contentHTML
1457  * size - {<OpenLayers.Size>} If either the 'w' or 'h' properties is 
1458  *     specified, we fix that dimension of the div to be measured. This is 
1459  *     useful in the case where we have a limit in one dimension and must 
1460  *     therefore meaure the flow in the other dimension.
1461  * options - {Object}
1462  *     displayClass - {String} Optional parameter.  A CSS class name(s) string
1463  *         to provide the CSS context of the rendered content.
1464  *     containerElement - {DOMElement} Optional parameter. Insert the HTML to 
1465  *         this node instead of the body root when calculating dimensions. 
1466  * 
1467  * Returns:
1468  * {OpenLayers.Size}
1469  */
1470 OpenLayers.Util.getRenderedDimensions = function(contentHTML, size, options) {
1471     
1472     var w, h;
1473     
1474     // create temp container div with restricted size
1475     var container = document.createElement("div");
1476     container.style.visibility = "hidden";
1477         
1478     var containerElement = (options && options.containerElement) 
1479         ? options.containerElement : document.body;
1480
1481     //fix a dimension, if specified.
1482     if (size) {
1483         if (size.w) {
1484             w = size.w;
1485             container.style.width = w + "px";
1486         } else if (size.h) {
1487             h = size.h;
1488             container.style.height = h + "px";
1489         }
1490     }
1491
1492     //add css classes, if specified
1493     if (options && options.displayClass) {
1494         container.className = options.displayClass;
1495     }
1496     
1497     // create temp content div and assign content
1498     var content = document.createElement("div");
1499     content.innerHTML = contentHTML;
1500     
1501     // we need overflow visible when calculating the size
1502     content.style.overflow = "visible";
1503     if (content.childNodes) {
1504         for (var i=0, l=content.childNodes.length; i<l; i++) {
1505             if (!content.childNodes[i].style) continue;
1506             content.childNodes[i].style.overflow = "visible";
1507         }
1508     }
1509     
1510     // add content to restricted container 
1511     container.appendChild(content);
1512     
1513     // append container to body for rendering
1514     containerElement.appendChild(container);
1515     
1516     // Opera and IE7 can't handle a node with position:aboslute if it inherits
1517     // position:absolute from a parent.
1518     var parentHasPositionAbsolute = false;
1519     var parent = container.parentNode;
1520     while (parent && parent.tagName.toLowerCase()!="body") {
1521         var parentPosition = OpenLayers.Element.getStyle(parent, "position");
1522         if(parentPosition == "absolute") {
1523             parentHasPositionAbsolute = true;
1524             break;
1525         } else if (parentPosition && parentPosition != "static") {
1526             break;
1527         }
1528         parent = parent.parentNode;
1529     }
1530
1531     if(!parentHasPositionAbsolute) {
1532         container.style.position = "absolute";
1533     }
1534     
1535     // calculate scroll width of content and add corners and shadow width
1536     if (!w) {
1537         w = parseInt(content.scrollWidth);
1538     
1539         // update container width to allow height to adjust
1540         container.style.width = w + "px";
1541     }        
1542     // capture height and add shadow and corner image widths
1543     if (!h) {
1544         h = parseInt(content.scrollHeight);
1545     }
1546
1547     // remove elements
1548     container.removeChild(content);
1549     containerElement.removeChild(container);
1550     
1551     return new OpenLayers.Size(w, h);
1552 };
1553
1554 /**
1555  * APIFunction: getScrollbarWidth
1556  * This function has been modified by the OpenLayers from the original version,
1557  *     written by Matthew Eernisse and released under the Apache 2 
1558  *     license here:
1559  * 
1560  *     http://www.fleegix.org/articles/2006/05/30/getting-the-scrollbar-width-in-pixels
1561  * 
1562  *     It has been modified simply to cache its value, since it is physically 
1563  *     impossible that this code could ever run in more than one browser at 
1564  *     once. 
1565  * 
1566  * Returns:
1567  * {Integer}
1568  */
1569 OpenLayers.Util.getScrollbarWidth = function() {
1570     
1571     var scrollbarWidth = OpenLayers.Util._scrollbarWidth;
1572     
1573     if (scrollbarWidth == null) {
1574         var scr = null;
1575         var inn = null;
1576         var wNoScroll = 0;
1577         var wScroll = 0;
1578     
1579         // Outer scrolling div
1580         scr = document.createElement('div');
1581         scr.style.position = 'absolute';
1582         scr.style.top = '-1000px';
1583         scr.style.left = '-1000px';
1584         scr.style.width = '100px';
1585         scr.style.height = '50px';
1586         // Start with no scrollbar
1587         scr.style.overflow = 'hidden';
1588     
1589         // Inner content div
1590         inn = document.createElement('div');
1591         inn.style.width = '100%';
1592         inn.style.height = '200px';
1593     
1594         // Put the inner div in the scrolling div
1595         scr.appendChild(inn);
1596         // Append the scrolling div to the doc
1597         document.body.appendChild(scr);
1598     
1599         // Width of the inner div sans scrollbar
1600         wNoScroll = inn.offsetWidth;
1601     
1602         // Add the scrollbar
1603         scr.style.overflow = 'scroll';
1604         // Width of the inner div width scrollbar
1605         wScroll = inn.offsetWidth;
1606     
1607         // Remove the scrolling div from the doc
1608         document.body.removeChild(document.body.lastChild);
1609     
1610         // Pixel width of the scroller
1611         OpenLayers.Util._scrollbarWidth = (wNoScroll - wScroll);
1612         scrollbarWidth = OpenLayers.Util._scrollbarWidth;
1613     }
1614
1615     return scrollbarWidth;
1616 };