/*

OpenLayers.js -- OpenLayers Map Viewer Library

Copyright 2005-2011 OpenLayers Contributors, released under the FreeBSD
license. Please see http://svn.openlayers.org/trunk/openlayers/license.txt
for the full text of the license.

Includes compressed code under the following licenses:

(For uncompressed versions of the code used please see the
OpenLayers SVN repository: <http://openlayers.org/>)

*/

/* Contains portions of Prototype.js:
*
* Prototype JavaScript framework, version 1.4.0
*  (c) 2005 Sam Stephenson <sam@conio.net>
*
*  Prototype is freely distributable under the terms of an MIT-style license.
*  For details, see the Prototype web site: http://prototype.conio.net/
*
*--------------------------------------------------------------------------*/

/**  
*  
*  Contains portions of Rico <http://openrico.org/>
* 
*  Copyright 2005 Sabre Airline Solutions  
*  
*  Licensed under the Apache License, Version 2.0 (the "License"); you
*  may not use this file except in compliance with the License. You
*  may obtain a copy of the License at
*  
*         http://www.apache.org/licenses/LICENSE-2.0  
*  
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
*  implied. See the License for the specific language governing
*  permissions and limitations under the License. 
*
**/

/**
* Contains XMLHttpRequest.js <http://code.google.com/p/xmlhttprequest/>
* Copyright 2007 Sergey Ilinsky (http://www.ilinsky.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*/

/**
* Contains portions of Gears <http://code.google.com/apis/gears/>
*
* Copyright 2007, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
*  1. Redistributions of source code must retain the above copyright notice,
*     this list of conditions and the following disclaimer.
*  2. Redistributions in binary form must reproduce the above copyright notice,
*     this list of conditions and the following disclaimer in the documentation
*     and/or other materials provided with the distribution.
*  3. Neither the name of Google Inc. nor the names of its contributors may be
*     used to endorse or promote products derived from this software without
*     specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Sets up google.gears.*, which is *the only* supported way to access Gears.
*
* Circumvent this file at your own risk!
*
* In the future, Gears may automatically define google.gears.* without this
* file. Gears may use these objects to transparently fix bugs and compatibility
* issues. Applications that use the code below will continue to work seamlessly
* when that happens.
*/

/**
* OpenLayers.Util.pagePosition is based on Yahoo's getXY method, which is
* Copyright (c) 2006, Yahoo! Inc.
* All rights reserved.
* 
* Redistribution and use of this software in source and binary forms, with or
* without modification, are permitted provided that the following conditions
* are met:
* 
* * Redistributions of source code must retain the above copyright notice,
*   this list of conditions and the following disclaimer.
* 
* * Redistributions in binary form must reproduce the above copyright notice,
*   this list of conditions and the following disclaimer in the documentation
*   and/or other materials provided with the distribution.
* 
* * Neither the name of Yahoo! Inc. nor the names of its contributors may be
*   used to endorse or promote products derived from this software without
*   specific prior written permission of Yahoo! Inc.
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
* POSSIBILITY OF SUCH DAMAGE.
*/
(function () {
    if (window.google && google.gears) { return; }
    var factory = null; if (typeof GearsFactory != 'undefined') { factory = new GearsFactory(); } else { try { factory = new ActiveXObject('Gears.Factory'); if (factory.getBuildInfo().indexOf('ie_mobile') != -1) { factory.privateSetGlobalObject(this); } } catch (e) { if ((typeof navigator.mimeTypes != 'undefined') && navigator.mimeTypes["application/x-googlegears"]) { factory = document.createElement("object"); factory.style.display = "none"; factory.width = 0; factory.height = 0; factory.type = "application/x-googlegears"; document.documentElement.appendChild(factory); } } }
    if (!factory) { return; }
    if (!window.google) { google = {}; }
    if (!google.gears) { google.gears = { factory: factory }; }
})();
var OpenLayers = {
    VERSION_NUMBER: "Release 2.11",
    singleFile: true,
    _getScriptLocation: (function () {
        var r = new RegExp("(^|(.*?\\/))(OpenLayers\.js)(\\?|$)"), s = document.getElementsByTagName('script'), src, m, l = "";
        for (var i = 0, len = s.length; i < len; i++) {
            src = s[i].getAttribute('src');
            if (src) {
                var m = src.match(r);
                if (m) {
                    l = m[1];
                    break;
                }
            }
        }
        return (function () { return l; });
    })()
};
OpenLayers.Class = function () {
    var len = arguments.length;
    var P = arguments[0];
    var F = arguments[len - 1];
    var C = typeof F.initialize == "function" ? F.initialize : function () {
        P.prototype.initialize.apply(this, arguments);
    };
    if (len > 1) {
        var newArgs = [C, P].concat(Array.prototype.slice.call(arguments).slice(1, len - 1), F);
        OpenLayers.inherit.apply(null, newArgs);
    }
    else {
        C.prototype = F;
    }
    return C;
};
OpenLayers.Class.isPrototype = function () { };
OpenLayers.Class.create = function () { return function () { if (arguments && arguments[0] != OpenLayers.Class.isPrototype) { this.initialize.apply(this, arguments); } }; };
OpenLayers.Class.inherit = function (P) { var C = function () { P.call(this); }; var newArgs = [C].concat(Array.prototype.slice.call(arguments)); OpenLayers.inherit.apply(null, newArgs); return C.prototype; }; OpenLayers.inherit = function (C, P) {
    var F = function () { }; F.prototype = P.prototype; C.prototype = new F; var i, l, o; for (i = 2, l = arguments.length; i < l; i++) {
        o = arguments[i]; if (typeof o === "function") { o = o.prototype; }
        OpenLayers.Util.extend(C.prototype, o);
    }
}; OpenLayers.Util = OpenLayers.Util || {}; OpenLayers.Util.extend = function (destination, source) {
    destination = destination || {}; if (source) {
        for (var property in source) { var value = source[property]; if (value !== undefined) { destination[property] = value; } }
        var sourceIsEvt = typeof window.Event == "function" && source instanceof window.Event; if (!sourceIsEvt && source.hasOwnProperty && source.hasOwnProperty("toString")) { destination.toString = source.toString; }
    }
    return destination;
}; OpenLayers.Protocol = OpenLayers.Class({ format: null, options: null, autoDestroy: true, defaultFilter: null, initialize: function (options) { options = options || {}; OpenLayers.Util.extend(this, options); this.options = options; }, mergeWithDefaultFilter: function (filter) {
    var merged; if (filter && this.defaultFilter) { merged = new OpenLayers.Filter.Logical({ type: OpenLayers.Filter.Logical.AND, filters: [this.defaultFilter, filter] }); } else { merged = filter || this.defaultFilter || undefined; }
    return merged;
}, destroy: function () { this.options = null; this.format = null; }, read: function (options) { options = options || {}; options.filter = this.mergeWithDefaultFilter(options.filter); }, create: function () { }, update: function () { }, "delete": function () { }, commit: function () { }, abort: function (response) { }, createCallback: function (method, response, options) { return OpenLayers.Function.bind(function () { method.apply(this, [response, options]); }, this); }, CLASS_NAME: "OpenLayers.Protocol"
}); OpenLayers.Protocol.Response = OpenLayers.Class({ code: null, requestType: null, last: true, features: null, reqFeatures: null, priv: null, error: null, initialize: function (options) { OpenLayers.Util.extend(this, options); }, success: function () { return this.code > 0; }, CLASS_NAME: "OpenLayers.Protocol.Response" }); OpenLayers.Protocol.Response.SUCCESS = 1; OpenLayers.Protocol.Response.FAILURE = 0; OpenLayers.Protocol.SQL = OpenLayers.Class(OpenLayers.Protocol, { databaseName: 'ol', tableName: "ol_vector_features", postReadFiltering: true, initialize: function (options) { OpenLayers.Protocol.prototype.initialize.apply(this, [options]); }, destroy: function () { OpenLayers.Protocol.prototype.destroy.apply(this); }, supported: function () { return false; }, evaluateFilter: function (feature, filter) { return filter && this.postReadFiltering ? filter.evaluate(feature) : true; }, CLASS_NAME: "OpenLayers.Protocol.SQL" }); OpenLayers.Console = { log: function () { }, debug: function () { }, info: function () { }, warn: function () { }, error: function () { }, userError: function (error) { alert(error); }, assert: function () { }, dir: function () { }, dirxml: function () { }, trace: function () { }, group: function () { }, groupEnd: function () { }, time: function () { }, timeEnd: function () { }, profile: function () { }, profileEnd: function () { }, count: function () { }, CLASS_NAME: "OpenLayers.Console" }; (function () { var scripts = document.getElementsByTagName("script"); for (var i = 0, len = scripts.length; i < len; ++i) { if (scripts[i].src.indexOf("firebug.js") != -1) { if (console) { OpenLayers.Util.extend(OpenLayers.Console, console); break; } } } })(); OpenLayers.Lang = { code: null, defaultCode: "en", getCode: function () {
    if (!OpenLayers.Lang.code) { OpenLayers.Lang.setCode(); }
    return OpenLayers.Lang.code;
}, setCode: function (code) {
    var lang; if (!code) { code = (OpenLayers.BROWSER_NAME == "msie") ? navigator.userLanguage : navigator.language; }
    var parts = code.split('-'); parts[0] = parts[0].toLowerCase(); if (typeof OpenLayers.Lang[parts[0]] == "object") { lang = parts[0]; }
    if (parts[1]) { var testLang = parts[0] + '-' + parts[1].toUpperCase(); if (typeof OpenLayers.Lang[testLang] == "object") { lang = testLang; } }
    if (!lang) { OpenLayers.Console.warn('Failed to find OpenLayers.Lang.' + parts.join("-") + ' dictionary, falling back to default language'); lang = OpenLayers.Lang.defaultCode; }
    OpenLayers.Lang.code = lang;
}, translate: function (key, context) {
    var dictionary = OpenLayers.Lang[OpenLayers.Lang.getCode()]; var message = dictionary && dictionary[key]; if (!message) { message = key; }
    if (context) { message = OpenLayers.String.format(message, context); }
    return message;
}
}; OpenLayers.i18n = OpenLayers.Lang.translate;


OpenLayers.String = { startsWith: function (str, sub) { return (str.indexOf(sub) == 0); }, contains: function (str, sub) { return (str.indexOf(sub) != -1); }, trim: function (str) { return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); }, camelize: function (str) {
    var oStringList = str.split('-'); var camelizedString = oStringList[0]; for (var i = 1, len = oStringList.length; i < len; i++) { var s = oStringList[i]; camelizedString += s.charAt(0).toUpperCase() + s.substring(1); }
    return camelizedString;
},
    format: function (template, context, args) {
        if (!context) {
            context = window;
        }
        var replacer = function (str, match) {
            var replacement;
            var subs = match.split(/\.+/);
            for (var i = 0; i < subs.length; i++) {
                if (i == 0) {
                    replacement = context;
                }
                replacement = replacement[subs[i]];
            }
            if (typeof replacement == "function") {
                replacement = args ? replacement.apply(null, args) : replacement();
            }
            if (typeof replacement == 'undefined') {
                return 'undefined';
            }
            else {
                return replacement;
            }
        };
        return template.replace(OpenLayers.String.tokenRegEx, replacer);
    },
    tokenRegEx: /\$\{([\w.]+?)\}/g, numberRegEx: /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/,
    isNumeric: function (value) {
        return OpenLayers.String.numberRegEx.test(value);
    },
    numericIf: function (value) {
        return OpenLayers.String.isNumeric(value) ? parseFloat(value) : value;
    }
};
if (!String.prototype.startsWith) { String.prototype.startsWith = function (sStart) { OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated", { 'newMethod': 'OpenLayers.String.startsWith' })); return OpenLayers.String.startsWith(this, sStart); }; }
if (!String.prototype.contains) { String.prototype.contains = function (str) { OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated", { 'newMethod': 'OpenLayers.String.contains' })); return OpenLayers.String.contains(this, str); }; }
if (!String.prototype.trim) { String.prototype.trim = function () { OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated", { 'newMethod': 'OpenLayers.String.trim' })); return OpenLayers.String.trim(this); }; }
if (!String.prototype.camelize) { String.prototype.camelize = function () { OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated", { 'newMethod': 'OpenLayers.String.camelize' })); return OpenLayers.String.camelize(this); }; }
OpenLayers.Number = { decimalSeparator: ".", thousandsSeparator: ",", limitSigDigs: function (num, sig) {
    var fig = 0; if (sig > 0) { fig = parseFloat(num.toPrecision(sig)); }
    return fig;
}, format: function (num, dec, tsep, dsep) {
    dec = (typeof dec != "undefined") ? dec : 0; tsep = (typeof tsep != "undefined") ? tsep : OpenLayers.Number.thousandsSeparator; dsep = (typeof dsep != "undefined") ? dsep : OpenLayers.Number.decimalSeparator; if (dec != null) { num = parseFloat(num.toFixed(dec)); }
    var parts = num.toString().split("."); if (parts.length == 1 && dec == null) { dec = 0; }
    var integer = parts[0]; if (tsep) { var thousands = /(-?[0-9]+)([0-9]{3})/; while (thousands.test(integer)) { integer = integer.replace(thousands, "$1" + tsep + "$2"); } }
    var str; if (dec == 0) { str = integer; } else {
        var rem = parts.length > 1 ? parts[1] : "0"; if (dec != null) { rem = rem + new Array(dec - rem.length + 1).join("0"); }
        str = integer + dsep + rem;
    }
    return str;
}
}; if (!Number.prototype.limitSigDigs) { Number.prototype.limitSigDigs = function (sig) { OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated", { 'newMethod': 'OpenLayers.Number.limitSigDigs' })); return OpenLayers.Number.limitSigDigs(this, sig); }; }
OpenLayers.Function = { bind: function (func, object) { var args = Array.prototype.slice.apply(arguments, [2]); return function () { var newArgs = args.concat(Array.prototype.slice.apply(arguments, [0])); return func.apply(object, newArgs); }; }, bindAsEventListener: function (func, object) { return function (event) { return func.call(object, event || window.event); }; }, False: function () { return false; }, True: function () { return true; }, Void: function () { } }; if (!Function.prototype.bind) { Function.prototype.bind = function () { OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated", { 'newMethod': 'OpenLayers.Function.bind' })); Array.prototype.unshift.apply(arguments, [this]); return OpenLayers.Function.bind.apply(null, arguments); }; }
if (!Function.prototype.bindAsEventListener) { Function.prototype.bindAsEventListener = function (object) { OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated", { 'newMethod': 'OpenLayers.Function.bindAsEventListener' })); return OpenLayers.Function.bindAsEventListener(this, object); }; }
OpenLayers.Array = { filter: function (array, callback, caller) {
    var selected = []; if (Array.prototype.filter) { selected = array.filter(callback, caller); } else {
        var len = array.length; if (typeof callback != "function") { throw new TypeError(); }
        for (var i = 0; i < len; i++) { if (i in array) { var val = array[i]; if (callback.call(caller, val, i, array)) { selected.push(val); } } }
    }
    return selected;
}
}; OpenLayers.Bounds = OpenLayers.Class({ left: null, bottom: null, right: null, top: null, centerLonLat: null, initialize: function (left, bottom, right, top) {
    if (left != null) { this.left = OpenLayers.Util.toFloat(left); }
    if (bottom != null) { this.bottom = OpenLayers.Util.toFloat(bottom); }
    if (right != null) { this.right = OpenLayers.Util.toFloat(right); }
    if (top != null) { this.top = OpenLayers.Util.toFloat(top); }
}, clone: function () { return new OpenLayers.Bounds(this.left, this.bottom, this.right, this.top); }, equals: function (bounds) {
    var equals = false; if (bounds != null) { equals = ((this.left == bounds.left) && (this.right == bounds.right) && (this.top == bounds.top) && (this.bottom == bounds.bottom)); }
    return equals;
}, toString: function () { return [this.left, this.bottom, this.right, this.top].join(","); }, toArray: function (reverseAxisOrder) { if (reverseAxisOrder === true) { return [this.bottom, this.left, this.top, this.right]; } else { return [this.left, this.bottom, this.right, this.top]; } }, toBBOX: function (decimal, reverseAxisOrder) {
    if (decimal == null) { decimal = 6; }
    var mult = Math.pow(10, decimal); var xmin = Math.round(this.left * mult) / mult; var ymin = Math.round(this.bottom * mult) / mult; var xmax = Math.round(this.right * mult) / mult; var ymax = Math.round(this.top * mult) / mult; if (reverseAxisOrder === true) { return ymin + "," + xmin + "," + ymax + "," + xmax; } else { return xmin + "," + ymin + "," + xmax + "," + ymax; }
}, toGeometry: function () { return new OpenLayers.Geometry.Polygon([new OpenLayers.Geometry.LinearRing([new OpenLayers.Geometry.Point(this.left, this.bottom), new OpenLayers.Geometry.Point(this.right, this.bottom), new OpenLayers.Geometry.Point(this.right, this.top), new OpenLayers.Geometry.Point(this.left, this.top)])]); }, getWidth: function () { return (this.right - this.left); }, getHeight: function () { return (this.top - this.bottom); }, getSize: function () { return new OpenLayers.Size(this.getWidth(), this.getHeight()); }, getCenterPixel: function () { return new OpenLayers.Pixel((this.left + this.right) / 2, (this.bottom + this.top) / 2); }, getCenterLonLat: function () {
    if (!this.centerLonLat) { this.centerLonLat = new OpenLayers.LonLat((this.left + this.right) / 2, (this.bottom + this.top) / 2); }
    return this.centerLonLat;
}, scale: function (ratio, origin) {
    if (origin == null) { origin = this.getCenterLonLat(); }
    var origx, origy; if (origin.CLASS_NAME == "OpenLayers.LonLat") { origx = origin.lon; origy = origin.lat; } else { origx = origin.x; origy = origin.y; }
    var left = (this.left - origx) * ratio + origx; var bottom = (this.bottom - origy) * ratio + origy; var right = (this.right - origx) * ratio + origx; var top = (this.top - origy) * ratio + origy; return new OpenLayers.Bounds(left, bottom, right, top);
}, add: function (x, y) {
    if ((x == null) || (y == null)) { var msg = OpenLayers.i18n("boundsAddError"); OpenLayers.Console.error(msg); return null; }
    return new OpenLayers.Bounds(this.left + x, this.bottom + y, this.right + x, this.top + y);
}, extend: function (object) {
    var bounds = null; if (object) {
        switch (object.CLASS_NAME) { case "OpenLayers.LonLat": bounds = new OpenLayers.Bounds(object.lon, object.lat, object.lon, object.lat); break; case "OpenLayers.Geometry.Point": bounds = new OpenLayers.Bounds(object.x, object.y, object.x, object.y); break; case "OpenLayers.Bounds": bounds = object; break; }
        if (bounds) {
            this.centerLonLat = null; if ((this.left == null) || (bounds.left < this.left)) { this.left = bounds.left; }
            if ((this.bottom == null) || (bounds.bottom < this.bottom)) { this.bottom = bounds.bottom; }
            if ((this.right == null) || (bounds.right > this.right)) { this.right = bounds.right; }
            if ((this.top == null) || (bounds.top > this.top)) { this.top = bounds.top; }
        }
    }
}, containsLonLat: function (ll, inclusive) { return this.contains(ll.lon, ll.lat, inclusive); }, containsPixel: function (px, inclusive) { return this.contains(px.x, px.y, inclusive); }, contains: function (x, y, inclusive) {
    if (inclusive == null) { inclusive = true; }
    if (x == null || y == null) { return false; }
    x = OpenLayers.Util.toFloat(x); y = OpenLayers.Util.toFloat(y); var contains = false; if (inclusive) { contains = ((x >= this.left) && (x <= this.right) && (y >= this.bottom) && (y <= this.top)); } else { contains = ((x > this.left) && (x < this.right) && (y > this.bottom) && (y < this.top)); }
    return contains;
}, intersectsBounds: function (bounds, inclusive) {
    if (inclusive == null) { inclusive = true; }
    var intersects = false; var mightTouch = (this.left == bounds.right || this.right == bounds.left || this.top == bounds.bottom || this.bottom == bounds.top); if (inclusive || !mightTouch) { var inBottom = (((bounds.bottom >= this.bottom) && (bounds.bottom <= this.top)) || ((this.bottom >= bounds.bottom) && (this.bottom <= bounds.top))); var inTop = (((bounds.top >= this.bottom) && (bounds.top <= this.top)) || ((this.top > bounds.bottom) && (this.top < bounds.top))); var inLeft = (((bounds.left >= this.left) && (bounds.left <= this.right)) || ((this.left >= bounds.left) && (this.left <= bounds.right))); var inRight = (((bounds.right >= this.left) && (bounds.right <= this.right)) || ((this.right >= bounds.left) && (this.right <= bounds.right))); intersects = ((inBottom || inTop) && (inLeft || inRight)); }
    return intersects;
}, containsBounds: function (bounds, partial, inclusive) {
    if (partial == null) { partial = false; }
    if (inclusive == null) { inclusive = true; }
    var bottomLeft = this.contains(bounds.left, bounds.bottom, inclusive); var bottomRight = this.contains(bounds.right, bounds.bottom, inclusive); var topLeft = this.contains(bounds.left, bounds.top, inclusive); var topRight = this.contains(bounds.right, bounds.top, inclusive); return (partial) ? (bottomLeft || bottomRight || topLeft || topRight) : (bottomLeft && bottomRight && topLeft && topRight);
}, determineQuadrant: function (lonlat) { var quadrant = ""; var center = this.getCenterLonLat(); quadrant += (lonlat.lat < center.lat) ? "b" : "t"; quadrant += (lonlat.lon < center.lon) ? "l" : "r"; return quadrant; }, transform: function (source, dest) { this.centerLonLat = null; var ll = OpenLayers.Projection.transform({ 'x': this.left, 'y': this.bottom }, source, dest); var lr = OpenLayers.Projection.transform({ 'x': this.right, 'y': this.bottom }, source, dest); var ul = OpenLayers.Projection.transform({ 'x': this.left, 'y': this.top }, source, dest); var ur = OpenLayers.Projection.transform({ 'x': this.right, 'y': this.top }, source, dest); this.left = Math.min(ll.x, ul.x); this.bottom = Math.min(ll.y, lr.y); this.right = Math.max(lr.x, ur.x); this.top = Math.max(ul.y, ur.y); return this; }, wrapDateLine: function (maxExtent, options) {
    options = options || {}; var leftTolerance = options.leftTolerance || 0; var rightTolerance = options.rightTolerance || 0; var newBounds = this.clone(); if (maxExtent) {
        while (newBounds.left < maxExtent.left && (newBounds.right - rightTolerance) <= maxExtent.left) { newBounds = newBounds.add(maxExtent.getWidth(), 0); }
        while ((newBounds.left + leftTolerance) >= maxExtent.right && newBounds.right > maxExtent.right) { newBounds = newBounds.add(-maxExtent.getWidth(), 0); }
    }
    return newBounds;
}, CLASS_NAME: "OpenLayers.Bounds"
}); OpenLayers.Bounds.fromString = function (str, reverseAxisOrder) { var bounds = str.split(","); return OpenLayers.Bounds.fromArray(bounds, reverseAxisOrder); }; OpenLayers.Bounds.fromArray = function (bbox, reverseAxisOrder) { return reverseAxisOrder === true ? new OpenLayers.Bounds(parseFloat(bbox[1]), parseFloat(bbox[0]), parseFloat(bbox[3]), parseFloat(bbox[2])) : new OpenLayers.Bounds(parseFloat(bbox[0]), parseFloat(bbox[1]), parseFloat(bbox[2]), parseFloat(bbox[3])); }; OpenLayers.Bounds.fromSize = function (size) { return new OpenLayers.Bounds(0, size.h, size.w, 0); }; OpenLayers.Bounds.oppositeQuadrant = function (quadrant) { var opp = ""; opp += (quadrant.charAt(0) == 't') ? 'b' : 't'; opp += (quadrant.charAt(1) == 'l') ? 'r' : 'l'; return opp; }; OpenLayers.Element = { visible: function (element) { return OpenLayers.Util.getElement(element).style.display != 'none'; }, toggle: function () { for (var i = 0, len = arguments.length; i < len; i++) { var element = OpenLayers.Util.getElement(arguments[i]); var display = OpenLayers.Element.visible(element) ? 'hide' : 'show'; OpenLayers.Element[display](element); } }, hide: function () { OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated", { newMethod: "element.style.display = 'none';" })); for (var i = 0, len = arguments.length; i < len; i++) { var element = OpenLayers.Util.getElement(arguments[i]); if (element) { element.style.display = 'none'; } } }, show: function () { OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated", { newMethod: "element.style.display = '';" })); for (var i = 0, len = arguments.length; i < len; i++) { var element = OpenLayers.Util.getElement(arguments[i]); if (element) { element.style.display = ''; } } }, remove: function (element) { element = OpenLayers.Util.getElement(element); element.parentNode.removeChild(element); }, getHeight: function (element) { element = OpenLayers.Util.getElement(element); return element.offsetHeight; }, getDimensions: function (element) {
    element = OpenLayers.Util.getElement(element); if (OpenLayers.Element.getStyle(element, 'display') != 'none') { return { width: element.offsetWidth, height: element.offsetHeight }; }
    var els = element.style; var originalVisibility = els.visibility; var originalPosition = els.position; var originalDisplay = els.display; els.visibility = 'hidden'; els.position = 'absolute'; els.display = ''; var originalWidth = element.clientWidth; var originalHeight = element.clientHeight; els.display = originalDisplay; els.position = originalPosition; els.visibility = originalVisibility; return { width: originalWidth, height: originalHeight };
}, hasClass: function (element, name) { var names = element.className; return (!!names && new RegExp("(^|\\s)" + name + "(\\s|$)").test(names)); }, addClass: function (element, name) {
    if (!OpenLayers.Element.hasClass(element, name)) { element.className += (element.className ? " " : "") + name; }
    return element;
}, removeClass: function (element, name) {
    var names = element.className; if (names) { element.className = OpenLayers.String.trim(names.replace(new RegExp("(^|\\s+)" + name + "(\\s+|$)"), " ")); }
    return element;
}, toggleClass: function (element, name) {
    if (OpenLayers.Element.hasClass(element, name)) { OpenLayers.Element.removeClass(element, name); } else { OpenLayers.Element.addClass(element, name); }
    return element;
}, getStyle: function (element, style) {
    element = OpenLayers.Util.getElement(element); var value = null; if (element && element.style) {
        value = element.style[OpenLayers.String.camelize(style)]; if (!value) { if (document.defaultView && document.defaultView.getComputedStyle) { var css = document.defaultView.getComputedStyle(element, null); value = css ? css.getPropertyValue(style) : null; } else if (element.currentStyle) { value = element.currentStyle[OpenLayers.String.camelize(style)]; } }
        var positions = ['left', 'top', 'right', 'bottom']; if (window.opera && (OpenLayers.Util.indexOf(positions, style) != -1) && (OpenLayers.Element.getStyle(element, 'position') == 'static')) { value = 'auto'; }
    }
    return value == 'auto' ? null : value;
}
}; OpenLayers.LonLat = OpenLayers.Class({ lon: 0.0, lat: 0.0, initialize: function (lon, lat) { this.lon = OpenLayers.Util.toFloat(lon); this.lat = OpenLayers.Util.toFloat(lat); }, toString: function () { return ("lon=" + this.lon + ",lat=" + this.lat); }, toShortString: function () { return (this.lon + ", " + this.lat); }, clone: function () { return new OpenLayers.LonLat(this.lon, this.lat); }, add: function (lon, lat) {
    if ((lon == null) || (lat == null)) { var msg = OpenLayers.i18n("lonlatAddError"); OpenLayers.Console.error(msg); return null; }
    return new OpenLayers.LonLat(this.lon + OpenLayers.Util.toFloat(lon), this.lat + OpenLayers.Util.toFloat(lat));
}, equals: function (ll) {
    var equals = false; if (ll != null) { equals = ((this.lon == ll.lon && this.lat == ll.lat) || (isNaN(this.lon) && isNaN(this.lat) && isNaN(ll.lon) && isNaN(ll.lat))); }
    return equals;
}, transform: function (source, dest) { var point = OpenLayers.Projection.transform({ 'x': this.lon, 'y': this.lat }, source, dest); this.lon = point.x; this.lat = point.y; return this; }, wrapDateLine: function (maxExtent) {
    var newLonLat = this.clone(); if (maxExtent) {
        while (newLonLat.lon < maxExtent.left) { newLonLat.lon += maxExtent.getWidth(); }
        while (newLonLat.lon > maxExtent.right) { newLonLat.lon -= maxExtent.getWidth(); }
    }
    return newLonLat;
}, CLASS_NAME: "OpenLayers.LonLat"
}); OpenLayers.LonLat.fromString = function (str) { var pair = str.split(","); return new OpenLayers.LonLat(pair[0], pair[1]); }; OpenLayers.LonLat.fromArray = function (arr) { var gotArr = OpenLayers.Util.isArray(arr), lon = gotArr && arr[0], lat = gotArr && arr[1]; return new OpenLayers.LonLat(lon, lat); }; OpenLayers.Pixel = OpenLayers.Class({ x: 0.0, y: 0.0, initialize: function (x, y) { this.x = parseFloat(x); this.y = parseFloat(y); }, toString: function () { return ("x=" + this.x + ",y=" + this.y); }, clone: function () { return new OpenLayers.Pixel(this.x, this.y); }, equals: function (px) {
    var equals = false; if (px != null) { equals = ((this.x == px.x && this.y == px.y) || (isNaN(this.x) && isNaN(this.y) && isNaN(px.x) && isNaN(px.y))); }
    return equals;
}, distanceTo: function (px) {
    return Math.sqrt(Math.pow(this.x - px.x, 2) +
Math.pow(this.y - px.y, 2));
}, add: function (x, y) {
    if ((x == null) || (y == null)) { var msg = OpenLayers.i18n("pixelAddError"); OpenLayers.Console.error(msg); return null; }
    return new OpenLayers.Pixel(this.x + x, this.y + y);
}, offset: function (px) {
    var newPx = this.clone(); if (px) { newPx = this.add(px.x, px.y); }
    return newPx;
}, CLASS_NAME: "OpenLayers.Pixel"
}); OpenLayers.Size = OpenLayers.Class({ w: 0.0, h: 0.0, initialize: function (w, h) { this.w = parseFloat(w); this.h = parseFloat(h); }, toString: function () { return ("w=" + this.w + ",h=" + this.h); }, clone: function () { return new OpenLayers.Size(this.w, this.h); }, equals: function (sz) {
    var equals = false; if (sz != null) { equals = ((this.w == sz.w && this.h == sz.h) || (isNaN(this.w) && isNaN(this.h) && isNaN(sz.w) && isNaN(sz.h))); }
    return equals;
}, CLASS_NAME: "OpenLayers.Size"
}); OpenLayers.Util = OpenLayers.Util || {}; OpenLayers.Util.getElement = function () {
    var elements = []; for (var i = 0, len = arguments.length; i < len; i++) {
        var element = arguments[i]; if (typeof element == 'string') { element = document.getElementById(element); }
        if (arguments.length == 1) { return element; }
        elements.push(element);
    }
    return elements;
}; OpenLayers.Util.isElement = function (o) { return !!(o && o.nodeType === 1); }; OpenLayers.Util.isArray = function (a) { return (Object.prototype.toString.call(a) === '[object Array]'); }; if (typeof window.$ === "undefined") { window.$ = OpenLayers.Util.getElement; }
OpenLayers.Util.removeItem = function (array, item) {
    for (var i = array.length - 1; i >= 0; i--) { if (array[i] == item) { array.splice(i, 1); } }
    return array;
}; OpenLayers.Util.clearArray = function (array) { OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated", { 'newMethod': 'array = []' })); array.length = 0; }; OpenLayers.Util.indexOf = function (array, obj) {
    if (typeof array.indexOf == "function") { return array.indexOf(obj); } else {
        for (var i = 0, len = array.length; i < len; i++) { if (array[i] == obj) { return i; } }
        return -1;
    }
}; OpenLayers.Util.modifyDOMElement = function (element, id, px, sz, position, border, overflow, opacity) {
    if (id) { element.id = id; }
    if (px) { element.style.left = px.x + "px"; element.style.top = px.y + "px"; }
    if (sz) { element.style.width = sz.w + "px"; element.style.height = sz.h + "px"; }
    if (position) { element.style.position = position; }
    if (border) { element.style.border = border; }
    if (overflow) { element.style.overflow = overflow; }
    if (parseFloat(opacity) >= 0.0 && parseFloat(opacity) < 1.0) { element.style.filter = 'alpha(opacity=' + (opacity * 100) + ')'; element.style.opacity = opacity; } else if (parseFloat(opacity) == 1.0) { element.style.filter = ''; element.style.opacity = ''; }
}; OpenLayers.Util.createDiv = function (id, px, sz, imgURL, position, border, overflow, opacity) {
    var dom = document.createElement('div'); if (imgURL) { dom.style.backgroundImage = 'url(' + imgURL + ')'; }
    if (!id) { id = OpenLayers.Util.createUniqueID("OpenLayersDiv"); }
    if (!position) { position = "absolute"; }
    OpenLayers.Util.modifyDOMElement(dom, id, px, sz, position, border, overflow, opacity); return dom;
}; OpenLayers.Util.createImage = function (id, px, sz, imgURL, position, border, opacity, delayDisplay) {
    var image = document.createElement("img"); if (!id) { id = OpenLayers.Util.createUniqueID("OpenLayersDiv"); }
    if (!position) { position = "relative"; }
    OpenLayers.Util.modifyDOMElement(image, id, px, sz, position, border, null, opacity); if (delayDisplay) { image.style.display = "none"; OpenLayers.Event.observe(image, "load", OpenLayers.Function.bind(OpenLayers.Util.onImageLoad, image)); OpenLayers.Event.observe(image, "error", OpenLayers.Function.bind(OpenLayers.Util.onImageLoadError, image)); }
    image.style.alt = id; image.galleryImg = "no"; if (imgURL) { image.src = imgURL; }
    return image;
}; OpenLayers.Util.setOpacity = function (element, opacity) { OpenLayers.Util.modifyDOMElement(element, null, null, null, null, null, null, opacity); }; OpenLayers.Util.onImageLoad = function () {
    if (!this.viewRequestID || (this.map && this.viewRequestID == this.map.viewRequestID)) { this.style.display = ""; }
    OpenLayers.Element.removeClass(this, "olImageLoadError");
}; OpenLayers.IMAGE_RELOAD_ATTEMPTS = 0; OpenLayers.Util.onImageLoadError = function () {
    this._attempts = (this._attempts) ? (this._attempts + 1) : 1; if (this._attempts <= OpenLayers.IMAGE_RELOAD_ATTEMPTS) {
        var urls = this.urls; if (urls && OpenLayers.Util.isArray(urls) && urls.length > 1) {
            var src = this.src.toString(); var current_url, k; for (k = 0; current_url = urls[k]; k++) { if (src.indexOf(current_url) != -1) { break; } }
            var guess = Math.floor(urls.length * Math.random()); var new_url = urls[guess]; k = 0; while (new_url == current_url && k++ < 4) { guess = Math.floor(urls.length * Math.random()); new_url = urls[guess]; }
            this.src = src.replace(current_url, new_url);
        } else { this.src = this.src; }
    } else { OpenLayers.Element.addClass(this, "olImageLoadError"); }
    this.style.display = "";
}; OpenLayers.Util.alphaHackNeeded = null; OpenLayers.Util.alphaHack = function () {
    if (OpenLayers.Util.alphaHackNeeded == null) {
        var arVersion = navigator.appVersion.split("MSIE"); var version = parseFloat(arVersion[1]); var filter = false; try { filter = !!(document.body.filters); } catch (e) { }
        OpenLayers.Util.alphaHackNeeded = (filter && (version >= 5.5) && (version < 7));
    }
    return OpenLayers.Util.alphaHackNeeded;
}; OpenLayers.Util.modifyAlphaImageDiv = function (div, id, px, sz, imgURL, position, border, sizing, opacity) {
    OpenLayers.Util.modifyDOMElement(div, id, px, sz, position, null, null, opacity); var img = div.childNodes[0]; if (imgURL) { img.src = imgURL; }
    OpenLayers.Util.modifyDOMElement(img, div.id + "_innerImage", null, sz, "relative", border); if (OpenLayers.Util.alphaHack()) {
        if (div.style.display != "none") { div.style.display = "inline-block"; }
        if (sizing == null) { sizing = "scale"; }
        div.style.filter = "progid:DXImageTransform.Microsoft" + ".AlphaImageLoader(src='" + img.src + "', " + "sizingMethod='" + sizing + "')"; if (parseFloat(div.style.opacity) >= 0.0 && parseFloat(div.style.opacity) < 1.0) { div.style.filter += " alpha(opacity=" + div.style.opacity * 100 + ")"; }
        img.style.filter = "alpha(opacity=0)";
    }
}; OpenLayers.Util.createAlphaImageDiv = function (id, px, sz, imgURL, position, border, sizing, opacity, delayDisplay) {
    var div = OpenLayers.Util.createDiv(); var img = OpenLayers.Util.createImage(null, null, null, null, null, null, null, false); div.appendChild(img); if (delayDisplay) { img.style.display = "none"; OpenLayers.Event.observe(img, "load", OpenLayers.Function.bind(OpenLayers.Util.onImageLoad, div)); OpenLayers.Event.observe(img, "error", OpenLayers.Function.bind(OpenLayers.Util.onImageLoadError, div)); }
    OpenLayers.Util.modifyAlphaImageDiv(div, id, px, sz, imgURL, position, border, sizing, opacity); return div;
}; OpenLayers.Util.upperCaseObject = function (object) {
    var uObject = {}; for (var key in object) { uObject[key.toUpperCase()] = object[key]; }
    return uObject;
}; OpenLayers.Util.applyDefaults = function (to, from) {
    to = to || {}; var fromIsEvt = typeof window.Event == "function" && from instanceof window.Event; for (var key in from) { if (to[key] === undefined || (!fromIsEvt && from.hasOwnProperty && from.hasOwnProperty(key) && !to.hasOwnProperty(key))) { to[key] = from[key]; } }
    if (!fromIsEvt && from && from.hasOwnProperty && from.hasOwnProperty('toString') && !to.hasOwnProperty('toString')) { to.toString = from.toString; }
    return to;
}; OpenLayers.Util.getParameterString = function (params) {
    var paramsArray = []; for (var key in params) {
        var value = params[key]; if ((value != null) && (typeof value != 'function')) {
            var encodedValue; if (typeof value == 'object' && value.constructor == Array) {
                var encodedItemArray = []; var item; for (var itemIndex = 0, len = value.length; itemIndex < len; itemIndex++) { item = value[itemIndex]; encodedItemArray.push(encodeURIComponent((item === null || item === undefined) ? "" : item)); }
                encodedValue = encodedItemArray.join(",");
            }
            else { encodedValue = encodeURIComponent(value); }
            paramsArray.push(encodeURIComponent(key) + "=" + encodedValue);
        }
    }
    return paramsArray.join("&");
}; OpenLayers.Util.urlAppend = function (url, paramStr) {
    var newUrl = url; if (paramStr) { var parts = (url + " ").split(/[?&]/); newUrl += (parts.pop() === " " ? paramStr : parts.length ? "&" + paramStr : "?" + paramStr); }
    return newUrl;
}; OpenLayers.ImgPath = ''; OpenLayers.Util.getImagesLocation = function () { return OpenLayers.ImgPath || (OpenLayers._getScriptLocation() + "img/"); }; OpenLayers.Util.Try = function () {
    var returnValue = null; for (var i = 0, len = arguments.length; i < len; i++) { var lambda = arguments[i]; try { returnValue = lambda(); break; } catch (e) { } }
    return returnValue;
}; OpenLayers.Util.getXmlNodeValue = function (node) {
    var val = null; OpenLayers.Util.Try(function () {
        val = node.text; if (!val) { val = node.textContent; }
        if (!val) { val = node.firstChild.nodeValue; }
    }, function () { val = node.textContent; }); return val;
}; OpenLayers.Util.mouseLeft = function (evt, div) {
    var target = (evt.relatedTarget) ? evt.relatedTarget : evt.toElement; while (target != div && target != null) { target = target.parentNode; }
    return (target != div);
}; OpenLayers.Util.DEFAULT_PRECISION = 14; OpenLayers.Util.toFloat = function (number, precision) {
    if (precision == null) { precision = OpenLayers.Util.DEFAULT_PRECISION; }
    if (typeof number !== "number") { number = parseFloat(number); }
    return precision === 0 ? number : parseFloat(number.toPrecision(precision));
}; OpenLayers.Util.rad = function (x) { return x * Math.PI / 180; }; OpenLayers.Util.deg = function (x) { return x * 180 / Math.PI; }; OpenLayers.Util.VincentyConstants = { a: 6378137, b: 6356752.3142, f: 1 / 298.257223563 }; OpenLayers.Util.distVincenty = function (p1, p2) {
    var ct = OpenLayers.Util.VincentyConstants; var a = ct.a, b = ct.b, f = ct.f; var L = OpenLayers.Util.rad(p2.lon - p1.lon); var U1 = Math.atan((1 - f) * Math.tan(OpenLayers.Util.rad(p1.lat))); var U2 = Math.atan((1 - f) * Math.tan(OpenLayers.Util.rad(p2.lat))); var sinU1 = Math.sin(U1), cosU1 = Math.cos(U1); var sinU2 = Math.sin(U2), cosU2 = Math.cos(U2); var lambda = L, lambdaP = 2 * Math.PI; var iterLimit = 20; while (Math.abs(lambda - lambdaP) > 1e-12 && --iterLimit > 0) {
        var sinLambda = Math.sin(lambda), cosLambda = Math.cos(lambda); var sinSigma = Math.sqrt((cosU2 * sinLambda) * (cosU2 * sinLambda) +
(cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) * (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda)); if (sinSigma == 0) { return 0; }
        var cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda; var sigma = Math.atan2(sinSigma, cosSigma); var alpha = Math.asin(cosU1 * cosU2 * sinLambda / sinSigma); var cosSqAlpha = Math.cos(alpha) * Math.cos(alpha); var cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha; var C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha)); lambdaP = lambda; lambda = L + (1 - C) * f * Math.sin(alpha) * (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));
    }
    if (iterLimit == 0) { return NaN; }
    var uSq = cosSqAlpha * (a * a - b * b) / (b * b); var A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq))); var B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq))); var deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) -
B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM))); var s = b * A * (sigma - deltaSigma); var d = s.toFixed(3) / 1000; return d;
}; OpenLayers.Util.destinationVincenty = function (lonlat, brng, dist) {
    var u = OpenLayers.Util; var ct = u.VincentyConstants; var a = ct.a, b = ct.b, f = ct.f; var lon1 = lonlat.lon; var lat1 = lonlat.lat; var s = dist; var alpha1 = u.rad(brng); var sinAlpha1 = Math.sin(alpha1); var cosAlpha1 = Math.cos(alpha1); var tanU1 = (1 - f) * Math.tan(u.rad(lat1)); var cosU1 = 1 / Math.sqrt((1 + tanU1 * tanU1)), sinU1 = tanU1 * cosU1; var sigma1 = Math.atan2(tanU1, cosAlpha1); var sinAlpha = cosU1 * sinAlpha1; var cosSqAlpha = 1 - sinAlpha * sinAlpha; var uSq = cosSqAlpha * (a * a - b * b) / (b * b); var A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq))); var B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq))); var sigma = s / (b * A), sigmaP = 2 * Math.PI; while (Math.abs(sigma - sigmaP) > 1e-12) {
        var cos2SigmaM = Math.cos(2 * sigma1 + sigma); var sinSigma = Math.sin(sigma); var cosSigma = Math.cos(sigma); var deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) -
B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM))); sigmaP = sigma; sigma = s / (b * A) + deltaSigma;
    }
    var tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1; var lat2 = Math.atan2(sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1, (1 - f) * Math.sqrt(sinAlpha * sinAlpha + tmp * tmp)); var lambda = Math.atan2(sinSigma * sinAlpha1, cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1); var C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha)); var L = lambda - (1 - C) * f * sinAlpha * (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM))); var revAz = Math.atan2(sinAlpha, -tmp); return new OpenLayers.LonLat(lon1 + u.deg(L), u.deg(lat2));
}; OpenLayers.Util.getParameters = function (url) {
    url = (url === null || url === undefined) ? window.location.href : url; var paramsString = ""; if (OpenLayers.String.contains(url, '?')) { var start = url.indexOf('?') + 1; var end = OpenLayers.String.contains(url, "#") ? url.indexOf('#') : url.length; paramsString = url.substring(start, end); }
    var parameters = {}; var pairs = paramsString.split(/[&;]/); for (var i = 0, len = pairs.length; i < len; ++i) {
        var keyValue = pairs[i].split('='); if (keyValue[0]) {
            var key = keyValue[0]; try { key = decodeURIComponent(key); } catch (err) { key = unescape(key); }
            var value = (keyValue[1] || '').replace(/\+/g, " "); try { value = decodeURIComponent(value); } catch (err) { value = unescape(value); }
            value = value.split(","); if (value.length == 1) { value = value[0]; }
            parameters[key] = value;
        }
    }
    return parameters;
}; OpenLayers.Util.getArgs = function (url) { OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated", { 'newMethod': 'OpenLayers.Util.getParameters' })); return OpenLayers.Util.getParameters(url); }; OpenLayers.Util.lastSeqID = 0; OpenLayers.Util.createUniqueID = function (prefix) {
    if (prefix == null) { prefix = "id_"; }
    OpenLayers.Util.lastSeqID += 1; return prefix + OpenLayers.Util.lastSeqID;
}; OpenLayers.INCHES_PER_UNIT = { 'inches': 1.0, 'ft': 12.0, 'mi': 63360.0, 'm': 39.3701, 'km': 39370.1, 'dd': 4374754, 'yd': 36 }; OpenLayers.INCHES_PER_UNIT["in"] = OpenLayers.INCHES_PER_UNIT.inches; OpenLayers.INCHES_PER_UNIT["degrees"] = OpenLayers.INCHES_PER_UNIT.dd; OpenLayers.INCHES_PER_UNIT["nmi"] = 1852 * OpenLayers.INCHES_PER_UNIT.m; OpenLayers.METERS_PER_INCH = 0.02540005080010160020; OpenLayers.Util.extend(OpenLayers.INCHES_PER_UNIT, { "Inch": OpenLayers.INCHES_PER_UNIT.inches, "Meter": 1.0 / OpenLayers.METERS_PER_INCH, "Foot": 0.30480060960121920243 / OpenLayers.METERS_PER_INCH, "IFoot": 0.30480000000000000000 / OpenLayers.METERS_PER_INCH, "ClarkeFoot": 0.3047972651151 / OpenLayers.METERS_PER_INCH, "SearsFoot": 0.30479947153867624624 / OpenLayers.METERS_PER_INCH, "GoldCoastFoot": 0.30479971018150881758 / OpenLayers.METERS_PER_INCH, "IInch": 0.02540000000000000000 / OpenLayers.METERS_PER_INCH, "MicroInch": 0.00002540000000000000 / OpenLayers.METERS_PER_INCH, "Mil": 0.00000002540000000000 / OpenLayers.METERS_PER_INCH, "Centimeter": 0.01000000000000000000 / OpenLayers.METERS_PER_INCH, "Kilometer": 1000.00000000000000000000 / OpenLayers.METERS_PER_INCH, "Yard": 0.91440182880365760731 / OpenLayers.METERS_PER_INCH, "SearsYard": 0.914398414616029 / OpenLayers.METERS_PER_INCH, "IndianYard": 0.91439853074444079983 / OpenLayers.METERS_PER_INCH, "IndianYd37": 0.91439523 / OpenLayers.METERS_PER_INCH, "IndianYd62": 0.9143988 / OpenLayers.METERS_PER_INCH, "IndianYd75": 0.9143985 / OpenLayers.METERS_PER_INCH, "IndianFoot": 0.30479951 / OpenLayers.METERS_PER_INCH, "IndianFt37": 0.30479841 / OpenLayers.METERS_PER_INCH, "IndianFt62": 0.3047996 / OpenLayers.METERS_PER_INCH, "IndianFt75": 0.3047995 / OpenLayers.METERS_PER_INCH, "Mile": 1609.34721869443738887477 / OpenLayers.METERS_PER_INCH, "IYard": 0.91440000000000000000 / OpenLayers.METERS_PER_INCH, "IMile": 1609.34400000000000000000 / OpenLayers.METERS_PER_INCH, "NautM": 1852.00000000000000000000 / OpenLayers.METERS_PER_INCH, "Lat-66": 110943.316488932731 / OpenLayers.METERS_PER_INCH, "Lat-83": 110946.25736872234125 / OpenLayers.METERS_PER_INCH, "Decimeter": 0.10000000000000000000 / OpenLayers.METERS_PER_INCH, "Millimeter": 0.00100000000000000000 / OpenLayers.METERS_PER_INCH, "Dekameter": 10.00000000000000000000 / OpenLayers.METERS_PER_INCH, "Decameter": 10.00000000000000000000 / OpenLayers.METERS_PER_INCH, "Hectometer": 100.00000000000000000000 / OpenLayers.METERS_PER_INCH, "GermanMeter": 1.0000135965 / OpenLayers.METERS_PER_INCH, "CaGrid": 0.999738 / OpenLayers.METERS_PER_INCH, "ClarkeChain": 20.1166194976 / OpenLayers.METERS_PER_INCH, "GunterChain": 20.11684023368047 / OpenLayers.METERS_PER_INCH, "BenoitChain": 20.116782494375872 / OpenLayers.METERS_PER_INCH, "SearsChain": 20.11676512155 / OpenLayers.METERS_PER_INCH, "ClarkeLink": 0.201166194976 / OpenLayers.METERS_PER_INCH, "GunterLink": 0.2011684023368047 / OpenLayers.METERS_PER_INCH, "BenoitLink": 0.20116782494375872 / OpenLayers.METERS_PER_INCH, "SearsLink": 0.2011676512155 / OpenLayers.METERS_PER_INCH, "Rod": 5.02921005842012 / OpenLayers.METERS_PER_INCH, "IntnlChain": 20.1168 / OpenLayers.METERS_PER_INCH, "IntnlLink": 0.201168 / OpenLayers.METERS_PER_INCH, "Perch": 5.02921005842012 / OpenLayers.METERS_PER_INCH, "Pole": 5.02921005842012 / OpenLayers.METERS_PER_INCH, "Furlong": 201.1684023368046 / OpenLayers.METERS_PER_INCH, "Rood": 3.778266898 / OpenLayers.METERS_PER_INCH, "CapeFoot": 0.3047972615 / OpenLayers.METERS_PER_INCH, "Brealey": 375.00000000000000000000 / OpenLayers.METERS_PER_INCH, "ModAmFt": 0.304812252984505969011938 / OpenLayers.METERS_PER_INCH, "Fathom": 1.8288 / OpenLayers.METERS_PER_INCH, "NautM-UK": 1853.184 / OpenLayers.METERS_PER_INCH, "50kilometers": 50000.0 / OpenLayers.METERS_PER_INCH, "150kilometers": 150000.0 / OpenLayers.METERS_PER_INCH }); OpenLayers.Util.extend(OpenLayers.INCHES_PER_UNIT, { "mm": OpenLayers.INCHES_PER_UNIT["Meter"] / 1000.0, "cm": OpenLayers.INCHES_PER_UNIT["Meter"] / 100.0, "dm": OpenLayers.INCHES_PER_UNIT["Meter"] * 100.0, "km": OpenLayers.INCHES_PER_UNIT["Meter"] * 1000.0, "kmi": OpenLayers.INCHES_PER_UNIT["nmi"], "fath": OpenLayers.INCHES_PER_UNIT["Fathom"], "ch": OpenLayers.INCHES_PER_UNIT["IntnlChain"], "link": OpenLayers.INCHES_PER_UNIT["IntnlLink"], "us-in": OpenLayers.INCHES_PER_UNIT["inches"], "us-ft": OpenLayers.INCHES_PER_UNIT["Foot"], "us-yd": OpenLayers.INCHES_PER_UNIT["Yard"], "us-ch": OpenLayers.INCHES_PER_UNIT["GunterChain"], "us-mi": OpenLayers.INCHES_PER_UNIT["Mile"], "ind-yd": OpenLayers.INCHES_PER_UNIT["IndianYd37"], "ind-ft": OpenLayers.INCHES_PER_UNIT["IndianFt37"], "ind-ch": 20.11669506 / OpenLayers.METERS_PER_INCH }); OpenLayers.DOTS_PER_INCH = 72; OpenLayers.Util.normalizeScale = function (scale) { var normScale = (scale > 1.0) ? (1.0 / scale) : scale; return normScale; }; OpenLayers.Util.getResolutionFromScale = function (scale, units) {
    var resolution; if (scale) {
        if (units == null) { units = "degrees"; }
        var normScale = OpenLayers.Util.normalizeScale(scale); resolution = 1 / (normScale * OpenLayers.INCHES_PER_UNIT[units] * OpenLayers.DOTS_PER_INCH);
    }
    return resolution;
}; OpenLayers.Util.getScaleFromResolution = function (resolution, units) {
    if (units == null) { units = "degrees"; }
    var scale = resolution * OpenLayers.INCHES_PER_UNIT[units] * OpenLayers.DOTS_PER_INCH; return scale;
}; OpenLayers.Util.safeStopPropagation = function (evt) { OpenLayers.Event.stop(evt, true); }; OpenLayers.Util.pagePosition = function (forElement) {
    var pos = [0, 0]; var viewportElement = OpenLayers.Util.getViewportElement(); if (!forElement || forElement == window || forElement == viewportElement) { return pos; }
    var BUGGY_GECKO_BOX_OBJECT = OpenLayers.IS_GECKO && document.getBoxObjectFor && OpenLayers.Element.getStyle(forElement, 'position') == 'absolute' && (forElement.style.top == '' || forElement.style.left == ''); var parent = null; var box; if (forElement.getBoundingClientRect) { box = forElement.getBoundingClientRect(); var scrollTop = viewportElement.scrollTop; var scrollLeft = viewportElement.scrollLeft; pos[0] = box.left + scrollLeft; pos[1] = box.top + scrollTop; } else if (document.getBoxObjectFor && !BUGGY_GECKO_BOX_OBJECT) { box = document.getBoxObjectFor(forElement); var vpBox = document.getBoxObjectFor(viewportElement); pos[0] = box.screenX - vpBox.screenX; pos[1] = box.screenY - vpBox.screenY; } else {
        pos[0] = forElement.offsetLeft; pos[1] = forElement.offsetTop; parent = forElement.offsetParent; if (parent != forElement) { while (parent) { pos[0] += parent.offsetLeft; pos[1] += parent.offsetTop; parent = parent.offsetParent; } }
        var browser = OpenLayers.BROWSER_NAME; if (browser == "opera" || (browser == "safari" && OpenLayers.Element.getStyle(forElement, 'position') == 'absolute')) { pos[1] -= document.body.offsetTop; }
        parent = forElement.offsetParent; while (parent && parent != document.body) {
            pos[0] -= parent.scrollLeft; if (browser != "opera" || parent.tagName != 'TR') { pos[1] -= parent.scrollTop; }
            parent = parent.offsetParent;
        }
    }
    return pos;
}; OpenLayers.Util.getViewportElement = function () {
    var viewportElement = arguments.callee.viewportElement; if (viewportElement == undefined) { viewportElement = (OpenLayers.BROWSER_NAME == "msie" && document.compatMode != 'CSS1Compat') ? document.body : document.documentElement; arguments.callee.viewportElement = viewportElement; }
    return viewportElement;
}; OpenLayers.Util.isEquivalentUrl = function (url1, url2, options) {
    options = options || {}; OpenLayers.Util.applyDefaults(options, { ignoreCase: true, ignorePort80: true, ignoreHash: true }); var urlObj1 = OpenLayers.Util.createUrlObject(url1, options); var urlObj2 = OpenLayers.Util.createUrlObject(url2, options); for (var key in urlObj1) { if (key !== "args") { if (urlObj1[key] != urlObj2[key]) { return false; } } }
    for (var key in urlObj1.args) {
        if (urlObj1.args[key] != urlObj2.args[key]) { return false; }
        delete urlObj2.args[key];
    }
    for (var key in urlObj2.args) { return false; }
    return true;
}; OpenLayers.Util.createUrlObject = function (url, options) {
    options = options || {}; if (!(/^\w+:\/\//).test(url)) { var loc = window.location; var port = loc.port ? ":" + loc.port : ""; var fullUrl = loc.protocol + "//" + loc.host.split(":").shift() + port; if (url.indexOf("/") === 0) { url = fullUrl + url; } else { var parts = loc.pathname.split("/"); parts.pop(); url = fullUrl + parts.join("/") + "/" + url; } }
    if (options.ignoreCase) { url = url.toLowerCase(); }
    var a = document.createElement('a'); a.href = url; var urlObject = {}; urlObject.host = a.host.split(":").shift(); urlObject.protocol = a.protocol; if (options.ignorePort80) { urlObject.port = (a.port == "80" || a.port == "0") ? "" : a.port; } else { urlObject.port = (a.port == "" || a.port == "0") ? "80" : a.port; }
    urlObject.hash = (options.ignoreHash || a.hash === "#") ? "" : a.hash; var queryString = a.search; if (!queryString) { var qMark = url.indexOf("?"); queryString = (qMark != -1) ? url.substr(qMark) : ""; }
    urlObject.args = OpenLayers.Util.getParameters(queryString); urlObject.pathname = (a.pathname.charAt(0) == "/") ? a.pathname : "/" + a.pathname; return urlObject;
}; OpenLayers.Util.removeTail = function (url) {
    var head = null; var qMark = url.indexOf("?"); var hashMark = url.indexOf("#"); if (qMark == -1) { head = (hashMark != -1) ? url.substr(0, hashMark) : url; } else { head = (hashMark != -1) ? url.substr(0, Math.min(qMark, hashMark)) : url.substr(0, qMark); }
    return head;
}; OpenLayers.IS_GECKO = (function () { var ua = navigator.userAgent.toLowerCase(); return ua.indexOf("webkit") == -1 && ua.indexOf("gecko") != -1; })(); OpenLayers.BROWSER_NAME = (function () {
    var name = ""; var ua = navigator.userAgent.toLowerCase(); if (ua.indexOf("opera") != -1) { name = "opera"; } else if (ua.indexOf("msie") != -1) { name = "msie"; } else if (ua.indexOf("safari") != -1) { name = "safari"; } else if (ua.indexOf("mozilla") != -1) { if (ua.indexOf("firefox") != -1) { name = "firefox"; } else { name = "mozilla"; } }
    return name;
})(); OpenLayers.Util.getBrowserName = function () { return OpenLayers.BROWSER_NAME; }; OpenLayers.Util.getRenderedDimensions = function (contentHTML, size, options) {
    var w, h; var container = document.createElement("div"); container.style.visibility = "hidden"; var containerElement = (options && options.containerElement) ? options.containerElement : document.body; if (size) { if (size.w) { w = size.w; container.style.width = w + "px"; } else if (size.h) { h = size.h; container.style.height = h + "px"; } }
    if (options && options.displayClass) { container.className = options.displayClass; }
    var content = document.createElement("div"); content.innerHTML = contentHTML; content.style.overflow = "visible"; if (content.childNodes) { for (var i = 0, l = content.childNodes.length; i < l; i++) { if (!content.childNodes[i].style) continue; content.childNodes[i].style.overflow = "visible"; } }
    container.appendChild(content); containerElement.appendChild(container); var parentHasPositionAbsolute = false; var parent = container.parentNode; while (parent && parent.tagName.toLowerCase() != "body") {
        var parentPosition = OpenLayers.Element.getStyle(parent, "position"); if (parentPosition == "absolute") { parentHasPositionAbsolute = true; break; } else if (parentPosition && parentPosition != "static") { break; }
        parent = parent.parentNode;
    }
    if (!parentHasPositionAbsolute) { container.style.position = "absolute"; }
    if (!w) { w = parseInt(content.scrollWidth); container.style.width = w + "px"; }
    if (!h) { h = parseInt(content.scrollHeight); }
    container.removeChild(content); containerElement.removeChild(container); return new OpenLayers.Size(w, h);
}; OpenLayers.Util.getScrollbarWidth = function () {
    var scrollbarWidth = OpenLayers.Util._scrollbarWidth; if (scrollbarWidth == null) { var scr = null; var inn = null; var wNoScroll = 0; var wScroll = 0; scr = document.createElement('div'); scr.style.position = 'absolute'; scr.style.top = '-1000px'; scr.style.left = '-1000px'; scr.style.width = '100px'; scr.style.height = '50px'; scr.style.overflow = 'hidden'; inn = document.createElement('div'); inn.style.width = '100%'; inn.style.height = '200px'; scr.appendChild(inn); document.body.appendChild(scr); wNoScroll = inn.offsetWidth; scr.style.overflow = 'scroll'; wScroll = inn.offsetWidth; document.body.removeChild(document.body.lastChild); OpenLayers.Util._scrollbarWidth = (wNoScroll - wScroll); scrollbarWidth = OpenLayers.Util._scrollbarWidth; }
    return scrollbarWidth;
}; OpenLayers.Util.getFormattedLonLat = function (coordinate, axis, dmsOption) {
    if (!dmsOption) { dmsOption = 'dms'; }
    coordinate = (coordinate + 540) % 360 - 180; var abscoordinate = Math.abs(coordinate); var coordinatedegrees = Math.floor(abscoordinate); var coordinateminutes = (abscoordinate - coordinatedegrees) / (1 / 60); var tempcoordinateminutes = coordinateminutes; coordinateminutes = Math.floor(coordinateminutes); var coordinateseconds = (tempcoordinateminutes - coordinateminutes) / (1 / 60); coordinateseconds = Math.round(coordinateseconds * 10); coordinateseconds /= 10; if (coordinateseconds >= 60) { coordinateseconds -= 60; coordinateminutes += 1; if (coordinateminutes >= 60) { coordinateminutes -= 60; coordinatedegrees += 1; } }
    if (coordinatedegrees < 10) { coordinatedegrees = "0" + coordinatedegrees; }
    var str = coordinatedegrees + "\u00B0"; if (dmsOption.indexOf('dm') >= 0) {
        if (coordinateminutes < 10) { coordinateminutes = "0" + coordinateminutes; }
        str += coordinateminutes + "'"; if (dmsOption.indexOf('dms') >= 0) {
            if (coordinateseconds < 10) { coordinateseconds = "0" + coordinateseconds; }
            str += coordinateseconds + '"';
        }
    }
    if (axis == "lon") { str += coordinate < 0 ? OpenLayers.i18n("W") : OpenLayers.i18n("E"); } else { str += coordinate < 0 ? OpenLayers.i18n("S") : OpenLayers.i18n("N"); }
    return str;
}; OpenLayers.Format = OpenLayers.Class({ options: null, externalProjection: null, internalProjection: null, data: null, keepData: false, initialize: function (options) { OpenLayers.Util.extend(this, options); this.options = options; }, destroy: function () { }, read: function (data) { OpenLayers.Console.userError(OpenLayers.i18n("readNotImplemented")); }, write: function (object) { OpenLayers.Console.userError(OpenLayers.i18n("writeNotImplemented")); }, CLASS_NAME: "OpenLayers.Format" }); OpenLayers.Format.JSON = OpenLayers.Class(OpenLayers.Format, { indent: "    ", space: " ", newline: "\n", level: 0, pretty: false, nativeJSON: (function () { return !!(window.JSON && typeof JSON.parse == "function" && typeof JSON.stringify == "function"); })(), read: function (json, filter) {
    var object; if (this.nativeJSON) { object = JSON.parse(json, filter); } else try {
        if (/^[\],:{}\s]*$/.test(json.replace(/\\["\\\/bfnrtu]/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
            object = eval('(' + json + ')'); if (typeof filter === 'function') {
                function walk(k, v) {
                    if (v && typeof v === 'object') { for (var i in v) { if (v.hasOwnProperty(i)) { v[i] = walk(i, v[i]); } } }
                    return filter(k, v);
                }
                object = walk('', object);
            }
        }
    } catch (e) { }
    if (this.keepData) { this.data = object; }
    return object;
}, write: function (value, pretty) {
    this.pretty = !!pretty; var json = null; var type = typeof value; if (this.serialize[type]) { try { json = (!this.pretty && this.nativeJSON) ? JSON.stringify(value) : this.serialize[type].apply(this, [value]); } catch (err) { OpenLayers.Console.error("Trouble serializing: " + err); } }
    return json;
}, writeIndent: function () {
    var pieces = []; if (this.pretty) { for (var i = 0; i < this.level; ++i) { pieces.push(this.indent); } }
    return pieces.join('');
}, writeNewline: function () { return (this.pretty) ? this.newline : ''; }, writeSpace: function () { return (this.pretty) ? this.space : ''; }, serialize: { 'object': function (object) {
    if (object == null) { return "null"; }
    if (object.constructor == Date) { return this.serialize.date.apply(this, [object]); }
    if (object.constructor == Array) { return this.serialize.array.apply(this, [object]); }
    var pieces = ['{']; this.level += 1; var key, keyJSON, valueJSON; var addComma = false; for (key in object) {
        if (object.hasOwnProperty(key)) {
            keyJSON = OpenLayers.Format.JSON.prototype.write.apply(this, [key, this.pretty]); valueJSON = OpenLayers.Format.JSON.prototype.write.apply(this, [object[key], this.pretty]); if (keyJSON != null && valueJSON != null) {
                if (addComma) { pieces.push(','); }
                pieces.push(this.writeNewline(), this.writeIndent(), keyJSON, ':', this.writeSpace(), valueJSON); addComma = true;
            }
        }
    }
    this.level -= 1; pieces.push(this.writeNewline(), this.writeIndent(), '}'); return pieces.join('');
}, 'array': function (array) {
    var json; var pieces = ['[']; this.level += 1; for (var i = 0, len = array.length; i < len; ++i) {
        json = OpenLayers.Format.JSON.prototype.write.apply(this, [array[i], this.pretty]); if (json != null) {
            if (i > 0) { pieces.push(','); }
            pieces.push(this.writeNewline(), this.writeIndent(), json);
        }
    }
    this.level -= 1; pieces.push(this.writeNewline(), this.writeIndent(), ']'); return pieces.join('');
}, 'string': function (string) {
    var m = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }; if (/["\\\x00-\x1f]/.test(string)) {
        return '"' + string.replace(/([\x00-\x1f\\"])/g, function (a, b) {
            var c = m[b]; if (c) { return c; }
            c = b.charCodeAt(); return '\\u00' +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
        }) + '"';
    }
    return '"' + string + '"';
}, 'number': function (number) { return isFinite(number) ? String(number) : "null"; }, 'boolean': function (bool) { return String(bool); }, 'date': function (date) {
    function format(number) { return (number < 10) ? '0' + number : number; }
    return '"' + date.getFullYear() + '-' +
format(date.getMonth() + 1) + '-' +
format(date.getDate()) + 'T' +
format(date.getHours()) + ':' +
format(date.getMinutes()) + ':' +
format(date.getSeconds()) + '"';
}
}, CLASS_NAME: "OpenLayers.Format.JSON"
}); OpenLayers.Feature = OpenLayers.Class({ layer: null, id: null, lonlat: null, data: null, marker: null, popupClass: null, popup: null, initialize: function (layer, lonlat, data) { this.layer = layer; this.lonlat = lonlat; this.data = (data != null) ? data : {}; this.id = OpenLayers.Util.createUniqueID(this.CLASS_NAME + "_"); }, destroy: function () {
    if ((this.layer != null) && (this.layer.map != null)) { if (this.popup != null) { this.layer.map.removePopup(this.popup); } }
    if (this.layer != null && this.marker != null) { this.layer.removeMarker(this.marker); }
    this.layer = null; this.id = null; this.lonlat = null; this.data = null; if (this.marker != null) { this.destroyMarker(this.marker); this.marker = null; }
    if (this.popup != null) { this.destroyPopup(this.popup); this.popup = null; }
}, onScreen: function () {
    var onScreen = false; if ((this.layer != null) && (this.layer.map != null)) { var screenBounds = this.layer.map.getExtent(); onScreen = screenBounds.containsLonLat(this.lonlat); }
    return onScreen;
}, createMarker: function () {
    if (this.lonlat != null) { this.marker = new OpenLayers.Marker(this.lonlat, this.data.icon); }
    return this.marker;
}, destroyMarker: function () { this.marker.destroy(); }, createPopup: function (closeBox) {
    if (this.lonlat != null) {
        if (!this.popup) { var anchor = (this.marker) ? this.marker.icon : null; var popupClass = this.popupClass ? this.popupClass : OpenLayers.Popup.AnchoredBubble; this.popup = new popupClass(this.id + "_popup", this.lonlat, this.data.popupSize, this.data.popupContentHTML, anchor, closeBox); }
        if (this.data.overflow != null) { this.popup.contentDiv.style.overflow = this.data.overflow; }
        this.popup.feature = this;
    }
    return this.popup;
}, destroyPopup: function () { if (this.popup) { this.popup.feature = null; this.popup.destroy(); this.popup = null; } }, CLASS_NAME: "OpenLayers.Feature"
}); OpenLayers.State = { UNKNOWN: 'Unknown', INSERT: 'Insert', UPDATE: 'Update', DELETE: 'Delete' }; OpenLayers.Feature.Vector = OpenLayers.Class(OpenLayers.Feature, { fid: null, geometry: null, attributes: null, bounds: null, state: null, style: null, url: null, renderIntent: "default", modified: null, initialize: function (geometry, attributes, style) {
    OpenLayers.Feature.prototype.initialize.apply(this, [null, null, attributes]); this.lonlat = null; this.geometry = geometry ? geometry : null; this.state = null; this.attributes = {}; if (attributes) { this.attributes = OpenLayers.Util.extend(this.attributes, attributes); }
    this.style = style ? style : null;
}, destroy: function () {
    if (this.layer) { this.layer.removeFeatures(this); this.layer = null; }
    this.geometry = null; this.modified = null; OpenLayers.Feature.prototype.destroy.apply(this, arguments);
}, clone: function () { return new OpenLayers.Feature.Vector(this.geometry ? this.geometry.clone() : null, this.attributes, this.style); }, onScreen: function (boundsOnly) {
    var onScreen = false; if (this.layer && this.layer.map) { var screenBounds = this.layer.map.getExtent(); if (boundsOnly) { var featureBounds = this.geometry.getBounds(); onScreen = screenBounds.intersectsBounds(featureBounds); } else { var screenPoly = screenBounds.toGeometry(); onScreen = screenPoly.intersects(this.geometry); } }
    return onScreen;
}, getVisibility: function () { return !(this.style && this.style.display == 'none' || !this.layer || this.layer && this.layer.styleMap && this.layer.styleMap.createSymbolizer(this, this.renderIntent).display == 'none' || this.layer && !this.layer.getVisibility()); }, createMarker: function () { return null; }, destroyMarker: function () { }, createPopup: function () { return null; }, atPoint: function (lonlat, toleranceLon, toleranceLat) {
    var atPoint = false; if (this.geometry) { atPoint = this.geometry.atPoint(lonlat, toleranceLon, toleranceLat); }
    return atPoint;
}, destroyPopup: function () { }, move: function (location) {
    if (!this.layer || !this.geometry.move) { return undefined; }
    var pixel; if (location.CLASS_NAME == "OpenLayers.LonLat") { pixel = this.layer.getViewPortPxFromLonLat(location); } else { pixel = location; }
    var lastPixel = this.layer.getViewPortPxFromLonLat(this.geometry.getBounds().getCenterLonLat()); var res = this.layer.map.getResolution(); this.geometry.move(res * (pixel.x - lastPixel.x), res * (lastPixel.y - pixel.y)); this.layer.drawFeature(this); return lastPixel;
}, toState: function (state) { if (state == OpenLayers.State.UPDATE) { switch (this.state) { case OpenLayers.State.UNKNOWN: case OpenLayers.State.DELETE: this.state = state; break; case OpenLayers.State.UPDATE: case OpenLayers.State.INSERT: break; } } else if (state == OpenLayers.State.INSERT) { switch (this.state) { case OpenLayers.State.UNKNOWN: break; default: this.state = state; break; } } else if (state == OpenLayers.State.DELETE) { switch (this.state) { case OpenLayers.State.INSERT: break; case OpenLayers.State.DELETE: break; case OpenLayers.State.UNKNOWN: case OpenLayers.State.UPDATE: this.state = state; break; } } else if (state == OpenLayers.State.UNKNOWN) { this.state = state; } }, CLASS_NAME: "OpenLayers.Feature.Vector"
}); OpenLayers.Feature.Vector.style = { 'default': { fillColor: "#ee9900", fillOpacity: 0.4, hoverFillColor: "white", hoverFillOpacity: 0.8, strokeColor: "#ee9900", strokeOpacity: 1, strokeWidth: 1, strokeLinecap: "round", strokeDashstyle: "solid", hoverStrokeColor: "red", hoverStrokeOpacity: 1, hoverStrokeWidth: 0.2, pointRadius: 6, hoverPointRadius: 1, hoverPointUnit: "%", pointerEvents: "visiblePainted", cursor: "inherit" }, 'select': { fillColor: "blue", fillOpacity: 0.4, hoverFillColor: "white", hoverFillOpacity: 0.8, strokeColor: "blue", strokeOpacity: 1, strokeWidth: 2, strokeLinecap: "round", strokeDashstyle: "solid", hoverStrokeColor: "red", hoverStrokeOpacity: 1, hoverStrokeWidth: 0.2, pointRadius: 6, hoverPointRadius: 1, hoverPointUnit: "%", pointerEvents: "visiblePainted", cursor: "pointer" }, 'temporary': { fillColor: "#66cccc", fillOpacity: 0.2, hoverFillColor: "white", hoverFillOpacity: 0.8, strokeColor: "#66cccc", strokeOpacity: 1, strokeLinecap: "round", strokeWidth: 2, strokeDashstyle: "solid", hoverStrokeColor: "red", hoverStrokeOpacity: 1, hoverStrokeWidth: 0.2, pointRadius: 6, hoverPointRadius: 1, hoverPointUnit: "%", pointerEvents: "visiblePainted", cursor: "inherit" }, 'delete': { display: "none"} }; OpenLayers.Format.WKT = OpenLayers.Class(OpenLayers.Format, { initialize: function (options) { this.regExes = { 'typeStr': /^\s*(\w+)\s*\(\s*(.*)\s*\)\s*$/, 'spaces': /\s+/, 'parenComma': /\)\s*,\s*\(/, 'doubleParenComma': /\)\s*\)\s*,\s*\(\s*\(/, 'trimParens': /^\s*\(?(.*?)\)?\s*$/ }; OpenLayers.Format.prototype.initialize.apply(this, [options]); }, read: function (wkt) {
    var features, type, str; wkt = wkt.replace(/[\n\r]/g, " "); var matches = this.regExes.typeStr.exec(wkt); if (matches) {
        type = matches[1].toLowerCase(); str = matches[2]; if (this.parse[type]) { features = this.parse[type].apply(this, [str]); }
        if (this.internalProjection && this.externalProjection) { if (features && features.CLASS_NAME == "OpenLayers.Feature.Vector") { features.geometry.transform(this.externalProjection, this.internalProjection); } else if (features && type != "geometrycollection" && typeof features == "object") { for (var i = 0, len = features.length; i < len; i++) { var component = features[i]; component.geometry.transform(this.externalProjection, this.internalProjection); } } }
    }
    return features;
}, write: function (features) {
    var collection, geometry, type, data, isCollection; if (features.constructor == Array) { collection = features; isCollection = true; } else { collection = [features]; isCollection = false; }
    var pieces = []; if (isCollection) { pieces.push('GEOMETRYCOLLECTION('); }
    for (var i = 0, len = collection.length; i < len; ++i) {
        if (isCollection && i > 0) { pieces.push(','); }
        geometry = collection[i].geometry; pieces.push(this.extractGeometry(geometry));
    }
    if (isCollection) { pieces.push(')'); }
    return pieces.join('');
}, extractGeometry: function (geometry) {
    var type = geometry.CLASS_NAME.split('.')[2].toLowerCase(); if (!this.extract[type]) { return null; }
    if (this.internalProjection && this.externalProjection) { geometry = geometry.clone(); geometry.transform(this.internalProjection, this.externalProjection); }
    var wktType = type == 'collection' ? 'GEOMETRYCOLLECTION' : type.toUpperCase(); var data = wktType + '(' + this.extract[type].apply(this, [geometry]) + ')'; return data;
}, extract: { 'point': function (point) { return point.x + ' ' + point.y; }, 'multipoint': function (multipoint) {
    var array = []; for (var i = 0, len = multipoint.components.length; i < len; ++i) {
        array.push('(' +
this.extract.point.apply(this, [multipoint.components[i]]) + ')');
    }
    return array.join(',');
}, 'linestring': function (linestring) {
    var array = []; for (var i = 0, len = linestring.components.length; i < len; ++i) { array.push(this.extract.point.apply(this, [linestring.components[i]])); }
    return array.join(',');
}, 'multilinestring': function (multilinestring) {
    var array = []; for (var i = 0, len = multilinestring.components.length; i < len; ++i) {
        array.push('(' +
this.extract.linestring.apply(this, [multilinestring.components[i]]) + ')');
    }
    return array.join(',');
}, 'polygon': function (polygon) {
    var array = []; for (var i = 0, len = polygon.components.length; i < len; ++i) {
        array.push('(' +
this.extract.linestring.apply(this, [polygon.components[i]]) + ')');
    }
    return array.join(',');
}, 'multipolygon': function (multipolygon) {
    var array = []; for (var i = 0, len = multipolygon.components.length; i < len; ++i) {
        array.push('(' +
this.extract.polygon.apply(this, [multipolygon.components[i]]) + ')');
    }
    return array.join(',');
}, 'collection': function (collection) {
    var array = []; for (var i = 0, len = collection.components.length; i < len; ++i) { array.push(this.extractGeometry.apply(this, [collection.components[i]])); }
    return array.join(',');
}
}, parse: { 'point': function (str) { var coords = OpenLayers.String.trim(str).split(this.regExes.spaces); return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(coords[0], coords[1])); }, 'multipoint': function (str) {
    var point; var points = OpenLayers.String.trim(str).split(','); var components = []; for (var i = 0, len = points.length; i < len; ++i) { point = points[i].replace(this.regExes.trimParens, '$1'); components.push(this.parse.point.apply(this, [point]).geometry); }
    return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.MultiPoint(components));
}, 'linestring': function (str) {
    var points = OpenLayers.String.trim(str).split(','); var components = []; for (var i = 0, len = points.length; i < len; ++i) { components.push(this.parse.point.apply(this, [points[i]]).geometry); }
    return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(components));
}, 'multilinestring': function (str) {
    var line; var lines = OpenLayers.String.trim(str).split(this.regExes.parenComma); var components = []; for (var i = 0, len = lines.length; i < len; ++i) { line = lines[i].replace(this.regExes.trimParens, '$1'); components.push(this.parse.linestring.apply(this, [line]).geometry); }
    return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.MultiLineString(components));
}, 'polygon': function (str) {
    var ring, linestring, linearring; var rings = OpenLayers.String.trim(str).split(this.regExes.parenComma); var components = []; for (var i = 0, len = rings.length; i < len; ++i) { ring = rings[i].replace(this.regExes.trimParens, '$1'); linestring = this.parse.linestring.apply(this, [ring]).geometry; linearring = new OpenLayers.Geometry.LinearRing(linestring.components); components.push(linearring); }
    return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon(components));
}, 'multipolygon': function (str) {
    var polygon; var polygons = OpenLayers.String.trim(str).split(this.regExes.doubleParenComma); var components = []; for (var i = 0, len = polygons.length; i < len; ++i) { polygon = polygons[i].replace(this.regExes.trimParens, '$1'); components.push(this.parse.polygon.apply(this, [polygon]).geometry); }
    return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.MultiPolygon(components));
}, 'geometrycollection': function (str) {
    str = str.replace(/,\s*([A-Za-z])/g, '|$1'); var wktArray = OpenLayers.String.trim(str).split('|'); var components = []; for (var i = 0, len = wktArray.length; i < len; ++i) { components.push(OpenLayers.Format.WKT.prototype.read.apply(this, [wktArray[i]])); }
    return components;
}
}, CLASS_NAME: "OpenLayers.Format.WKT"
}); OpenLayers.Protocol.SQL.Gears = OpenLayers.Class(OpenLayers.Protocol.SQL, { FID_PREFIX: '__gears_fid__', NULL_GEOMETRY: '__gears_null_geometry__', NULL_FEATURE_STATE: '__gears_null_feature_state__', jsonParser: null, wktParser: null, fidRegExp: null, saveFeatureState: true, typeOfFid: "string", db: null, initialize: function (options) {
    if (!this.supported()) { return; }
    OpenLayers.Protocol.SQL.prototype.initialize.apply(this, [options]); this.jsonParser = new OpenLayers.Format.JSON(); this.wktParser = new OpenLayers.Format.WKT(); this.fidRegExp = new RegExp('^' + this.FID_PREFIX); this.initializeDatabase();
}, initializeDatabase: function () { this.db = google.gears.factory.create('beta.database'); this.db.open(this.databaseName); this.db.execute("CREATE TABLE IF NOT EXISTS " + this.tableName + " (fid TEXT UNIQUE, geometry TEXT, properties TEXT," + "  state TEXT)"); }, destroy: function () { this.db.close(); this.db = null; this.jsonParser = null; this.wktParser = null; OpenLayers.Protocol.SQL.prototype.destroy.apply(this); }, supported: function () { return !!(window.google && google.gears); }, read: function (options) {
    OpenLayers.Protocol.prototype.read.apply(this, arguments); options = OpenLayers.Util.applyDefaults(options, this.options); var feature, features = []; var rs = this.db.execute("SELECT * FROM " + this.tableName); while (rs.isValidRow()) {
        feature = this.unfreezeFeature(rs); if (this.evaluateFilter(feature, options.filter)) {
            if (!options.noFeatureStateReset) { feature.state = null; }
            features.push(feature);
        }
        rs.next();
    }
    rs.close(); var resp = new OpenLayers.Protocol.Response({ code: OpenLayers.Protocol.Response.SUCCESS, requestType: "read", features: features }); if (options && options.callback) { options.callback.call(options.scope, resp); }
    return resp;
}, unfreezeFeature: function (row) {
    var feature; var wkt = row.fieldByName('geometry'); if (wkt == this.NULL_GEOMETRY) { feature = new OpenLayers.Feature.Vector(); } else { feature = this.wktParser.read(wkt); }
    feature.attributes = this.jsonParser.read(row.fieldByName('properties')); feature.fid = this.extractFidFromField(row.fieldByName('fid')); var state = row.fieldByName('state'); if (state == this.NULL_FEATURE_STATE) { state = null; }
    feature.state = state; return feature;
}, extractFidFromField: function (field) {
    if (!field.match(this.fidRegExp) && this.typeOfFid == "number") { field = parseFloat(field); }
    return field;
}, create: function (features, options) {
    options = OpenLayers.Util.applyDefaults(options, this.options); var resp = this.createOrUpdate(features); resp.requestType = "create"; if (options && options.callback) { options.callback.call(options.scope, resp); }
    return resp;
}, update: function (features, options) {
    options = OpenLayers.Util.applyDefaults(options, this.options); var resp = this.createOrUpdate(features); resp.requestType = "update"; if (options && options.callback) { options.callback.call(options.scope, resp); }
    return resp;
}, createOrUpdate: function (features) {
    if (!(OpenLayers.Util.isArray(features))) { features = [features]; }
    var i, len = features.length, feature; var insertedFeatures = new Array(len); for (i = 0; i < len; i++) { feature = features[i]; var params = this.freezeFeature(feature); this.db.execute("REPLACE INTO " + this.tableName + " (fid, geometry, properties, state)" + " VALUES (?, ?, ?, ?)", params); var clone = feature.clone(); clone.fid = this.extractFidFromField(params[0]); insertedFeatures[i] = clone; }
    return new OpenLayers.Protocol.Response({ code: OpenLayers.Protocol.Response.SUCCESS, features: insertedFeatures, reqFeatures: features });
}, freezeFeature: function (feature) { feature.fid = feature.fid != null ? "" + feature.fid : OpenLayers.Util.createUniqueID(this.FID_PREFIX); var geometry = feature.geometry != null ? feature.geometry.toString() : this.NULL_GEOMETRY; var properties = this.jsonParser.write(feature.attributes); var state = this.getFeatureStateForFreeze(feature); return [feature.fid, geometry, properties, state]; }, getFeatureStateForFreeze: function (feature) {
    var state; if (!this.saveFeatureState) { state = this.NULL_FEATURE_STATE; } else if (this.createdOffline(feature)) { state = OpenLayers.State.INSERT; } else { state = feature.state; }
    return state;
}, "delete": function (features, options) {
    if (!(OpenLayers.Util.isArray(features))) { features = [features]; }
    options = OpenLayers.Util.applyDefaults(options, this.options); var i, len, feature; for (i = 0, len = features.length; i < len; i++) {
        feature = features[i]; if (this.saveFeatureState && !this.createdOffline(feature)) {
            var toDelete = feature.clone(); toDelete.fid = feature.fid; if (toDelete.geometry) { toDelete.geometry.destroy(); toDelete.geometry = null; }
            toDelete.state = feature.state; this.createOrUpdate(toDelete);
        } else { this.db.execute("DELETE FROM " + this.tableName + " WHERE fid = ?", [feature.fid]); }
    }
    var resp = new OpenLayers.Protocol.Response({ code: OpenLayers.Protocol.Response.SUCCESS, requestType: "delete", reqFeatures: features }); if (options && options.callback) { options.callback.call(options.scope, resp); }
    return resp;
}, createdOffline: function (feature) { return (typeof feature.fid == "string" && !!(feature.fid.match(this.fidRegExp))); }, commit: function (features, options) {
    var opt, resp = [], nRequests = 0, nResponses = 0; function callback(resp) {
        if (++nResponses < nRequests) { resp.last = false; }
        this.callUserCallback(options, resp);
    }
    var feature, toCreate = [], toUpdate = [], toDelete = []; for (var i = features.length - 1; i >= 0; i--) { feature = features[i]; switch (feature.state) { case OpenLayers.State.INSERT: toCreate.push(feature); break; case OpenLayers.State.UPDATE: toUpdate.push(feature); break; case OpenLayers.State.DELETE: toDelete.push(feature); break; } }
    if (toCreate.length > 0) { nRequests++; opt = OpenLayers.Util.applyDefaults({ "callback": callback, "scope": this }, options.create); resp.push(this.create(toCreate, opt)); }
    if (toUpdate.length > 0) { nRequests++; opt = OpenLayers.Util.applyDefaults({ "callback": callback, "scope": this }, options.update); resp.push(this.update(toUpdate, opt)); }
    if (toDelete.length > 0) { nRequests++; opt = OpenLayers.Util.applyDefaults({ "callback": callback, "scope": this }, options["delete"]); resp.push(this["delete"](toDelete, opt)); }
    return resp;
}, clear: function () { this.db.execute("DELETE FROM " + this.tableName); }, callUserCallback: function (options, resp) {
    var opt = options[resp.requestType]; if (opt && opt.callback) { opt.callback.call(opt.scope, resp); }
    if (resp.last && options.callback) { options.callback.call(options.scope); }
}, CLASS_NAME: "OpenLayers.Protocol.SQL.Gears"
}); OpenLayers.Event = { observers: false, KEY_BACKSPACE: 8, KEY_TAB: 9, KEY_RETURN: 13, KEY_ESC: 27, KEY_LEFT: 37, KEY_UP: 38, KEY_RIGHT: 39, KEY_DOWN: 40, KEY_DELETE: 46, element: function (event) { return event.target || event.srcElement; }, isSingleTouch: function (event) { return event.touches && event.touches.length == 1; }, isMultiTouch: function (event) { return event.touches && event.touches.length > 1; }, isLeftClick: function (event) { return (((event.which) && (event.which == 1)) || ((event.button) && (event.button == 1))); }, isRightClick: function (event) { return (((event.which) && (event.which == 3)) || ((event.button) && (event.button == 2))); }, stop: function (event, allowDefault) {
    if (!allowDefault) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } }
    if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; }
}, findElement: function (event, tagName) {
    var element = OpenLayers.Event.element(event); while (element.parentNode && (!element.tagName || (element.tagName.toUpperCase() != tagName.toUpperCase()))) { element = element.parentNode; }
    return element;
}, observe: function (elementParam, name, observer, useCapture) {
    var element = OpenLayers.Util.getElement(elementParam); useCapture = useCapture || false; if (name == 'keypress' && (navigator.appVersion.match(/Konqueror|Safari|KHTML/) || element.attachEvent)) { name = 'keydown'; }
    if (!this.observers) { this.observers = {}; }
    if (!element._eventCacheID) {
        var idPrefix = "eventCacheID_"; if (element.id) { idPrefix = element.id + "_" + idPrefix; }
        element._eventCacheID = OpenLayers.Util.createUniqueID(idPrefix);
    }
    var cacheID = element._eventCacheID; if (!this.observers[cacheID]) { this.observers[cacheID] = []; }
    this.observers[cacheID].push({ 'element': element, 'name': name, 'observer': observer, 'useCapture': useCapture }); if (element.addEventListener) { element.addEventListener(name, observer, useCapture); } else if (element.attachEvent) { element.attachEvent('on' + name, observer); }
}, stopObservingElement: function (elementParam) { var element = OpenLayers.Util.getElement(elementParam); var cacheID = element._eventCacheID; this._removeElementObservers(OpenLayers.Event.observers[cacheID]); }, _removeElementObservers: function (elementObservers) { if (elementObservers) { for (var i = elementObservers.length - 1; i >= 0; i--) { var entry = elementObservers[i]; var args = new Array(entry.element, entry.name, entry.observer, entry.useCapture); var removed = OpenLayers.Event.stopObserving.apply(this, args); } } }, stopObserving: function (elementParam, name, observer, useCapture) {
    useCapture = useCapture || false; var element = OpenLayers.Util.getElement(elementParam); var cacheID = element._eventCacheID; if (name == 'keypress') { if (navigator.appVersion.match(/Konqueror|Safari|KHTML/) || element.detachEvent) { name = 'keydown'; } }
    var foundEntry = false; var elementObservers = OpenLayers.Event.observers[cacheID]; if (elementObservers) {
        var i = 0; while (!foundEntry && i < elementObservers.length) {
            var cacheEntry = elementObservers[i]; if ((cacheEntry.name == name) && (cacheEntry.observer == observer) && (cacheEntry.useCapture == useCapture)) {
                elementObservers.splice(i, 1); if (elementObservers.length == 0) { delete OpenLayers.Event.observers[cacheID]; }
                foundEntry = true; break;
            }
            i++;
        }
    }
    if (foundEntry) { if (element.removeEventListener) { element.removeEventListener(name, observer, useCapture); } else if (element && element.detachEvent) { element.detachEvent('on' + name, observer); } }
    return foundEntry;
}, unloadCache: function () {
    if (OpenLayers.Event && OpenLayers.Event.observers) {
        for (var cacheID in OpenLayers.Event.observers) { var elementObservers = OpenLayers.Event.observers[cacheID]; OpenLayers.Event._removeElementObservers.apply(this, [elementObservers]); }
        OpenLayers.Event.observers = false;
    }
}, CLASS_NAME: "OpenLayers.Event"
}; OpenLayers.Event.observe(window, 'unload', OpenLayers.Event.unloadCache, false); if (window.Event) { OpenLayers.Util.applyDefaults(window.Event, OpenLayers.Event); } else { var Event = OpenLayers.Event; }
OpenLayers.Events = OpenLayers.Class({ BROWSER_EVENTS: ["mouseover", "mouseout", "mousedown", "mouseup", "mousemove", "click", "dblclick", "rightclick", "dblrightclick", "resize", "focus", "blur", "touchstart", "touchmove", "touchend"], listeners: null, object: null, element: null, eventTypes: null, eventHandler: null, fallThrough: null, includeXY: false, clearMouseListener: null, initialize: function (object, element, eventTypes, fallThrough, options) {
    OpenLayers.Util.extend(this, options); this.object = object; this.fallThrough = fallThrough; this.listeners = {}; this.eventHandler = OpenLayers.Function.bindAsEventListener(this.handleBrowserEvent, this); this.clearMouseListener = OpenLayers.Function.bind(this.clearMouseCache, this); this.eventTypes = []; if (eventTypes != null) { for (var i = 0, len = eventTypes.length; i < len; i++) { this.addEventType(eventTypes[i]); } }
    if (element != null) { this.attachToElement(element); }
}, destroy: function () {
    if (this.element) { OpenLayers.Event.stopObservingElement(this.element); if (this.element.hasScrollEvent) { OpenLayers.Event.stopObserving(window, "scroll", this.clearMouseListener); } }
    this.element = null; this.listeners = null; this.object = null; this.eventTypes = null; this.fallThrough = null; this.eventHandler = null;
}, addEventType: function (eventName) { if (!this.listeners[eventName]) { this.eventTypes.push(eventName); this.listeners[eventName] = []; } }, attachToElement: function (element) {
    if (this.element) { OpenLayers.Event.stopObservingElement(this.element); }
    this.element = element; for (var i = 0, len = this.BROWSER_EVENTS.length; i < len; i++) { var eventType = this.BROWSER_EVENTS[i]; this.addEventType(eventType); OpenLayers.Event.observe(element, eventType, this.eventHandler); }
    OpenLayers.Event.observe(element, "dragstart", OpenLayers.Event.stop);
}, on: function (object) { for (var type in object) { if (type != "scope") { this.register(type, object.scope, object[type]); } } }, register: function (type, obj, func) {
    if ((func != null) && (OpenLayers.Util.indexOf(this.eventTypes, type) != -1)) {
        if (obj == null) { obj = this.object; }
        var listeners = this.listeners[type]; listeners.push({ obj: obj, func: func });
    }
}, registerPriority: function (type, obj, func) {
    if (func != null) {
        if (obj == null) { obj = this.object; }
        var listeners = this.listeners[type]; if (listeners != null) { listeners.unshift({ obj: obj, func: func }); }
    }
}, un: function (object) { for (var type in object) { if (type != "scope") { this.unregister(type, object.scope, object[type]); } } }, unregister: function (type, obj, func) {
    if (obj == null) { obj = this.object; }
    var listeners = this.listeners[type]; if (listeners != null) { for (var i = 0, len = listeners.length; i < len; i++) { if (listeners[i].obj == obj && listeners[i].func == func) { listeners.splice(i, 1); break; } } }
}, remove: function (type) { if (this.listeners[type] != null) { this.listeners[type] = []; } }, triggerEvent: function (type, evt) {
    var listeners = this.listeners[type]; if (!listeners || listeners.length == 0) { return undefined; }
    if (evt == null) { evt = {}; }
    evt.object = this.object; evt.element = this.element; if (!evt.type) { evt.type = type; }
    listeners = listeners.slice(); var continueChain; for (var i = 0, len = listeners.length; i < len; i++) { var callback = listeners[i]; continueChain = callback.func.apply(callback.obj, [evt]); if ((continueChain != undefined) && (continueChain == false)) { break; } }
    if (!this.fallThrough) { OpenLayers.Event.stop(evt, true); }
    return continueChain;
}, handleBrowserEvent: function (evt) {
    var type = evt.type, listeners = this.listeners[type]; if (!listeners || listeners.length == 0) { return; }
    var touches = evt.touches; if (touches && touches[0]) {
        var x = 0; var y = 0; var num = touches.length; var touch; for (var i = 0; i < num; ++i) { touch = touches[i]; x += touch.clientX; y += touch.clientY; }
        evt.clientX = x / num; evt.clientY = y / num;
    }
    if (this.includeXY) { evt.xy = this.getMousePosition(evt); }
    this.triggerEvent(type, evt);
}, clearMouseCache: function () { this.element.scrolls = null; this.element.lefttop = null; var body = document.body; if (body && !((body.scrollTop != 0 || body.scrollLeft != 0) && navigator.userAgent.match(/iPhone/i))) { this.element.offsets = null; } }, getMousePosition: function (evt) {
    if (!this.includeXY) { this.clearMouseCache(); } else if (!this.element.hasScrollEvent) { OpenLayers.Event.observe(window, "scroll", this.clearMouseListener); this.element.hasScrollEvent = true; }
    if (!this.element.scrolls) { var viewportElement = OpenLayers.Util.getViewportElement(); this.element.scrolls = [viewportElement.scrollLeft, viewportElement.scrollTop]; }
    if (!this.element.lefttop) { this.element.lefttop = [(document.documentElement.clientLeft || 0), (document.documentElement.clientTop || 0)]; }
    if (!this.element.offsets) { this.element.offsets = OpenLayers.Util.pagePosition(this.element); }
    return new OpenLayers.Pixel((evt.clientX + this.element.scrolls[0]) - this.element.offsets[0]
- this.element.lefttop[0], (evt.clientY + this.element.scrolls[1]) - this.element.offsets[1]
- this.element.lefttop[1]);
}, CLASS_NAME: "OpenLayers.Events"
}); OpenLayers.Tween = OpenLayers.Class({ INTERVAL: 10, easing: null, begin: null, finish: null, duration: null, callbacks: null, time: null, interval: null, playing: false, initialize: function (easing) { this.easing = (easing) ? easing : OpenLayers.Easing.Expo.easeOut; }, start: function (begin, finish, duration, options) {
    this.playing = true; this.begin = begin; this.finish = finish; this.duration = duration; this.callbacks = options.callbacks; this.time = 0; if (this.interval) { window.clearInterval(this.interval); this.interval = null; }
    if (this.callbacks && this.callbacks.start) { this.callbacks.start.call(this, this.begin); }
    this.interval = window.setInterval(OpenLayers.Function.bind(this.play, this), this.INTERVAL);
}, stop: function () {
    if (!this.playing) { return; }
    if (this.callbacks && this.callbacks.done) { this.callbacks.done.call(this, this.finish); }
    window.clearInterval(this.interval); this.interval = null; this.playing = false;
}, play: function () {
    var value = {}; for (var i in this.begin) {
        var b = this.begin[i]; var f = this.finish[i]; if (b == null || f == null || isNaN(b) || isNaN(f)) { OpenLayers.Console.error('invalid value for Tween'); }
        var c = f - b; value[i] = this.easing.apply(this, [this.time, b, c, this.duration]);
    }
    this.time++; if (this.callbacks && this.callbacks.eachStep) { this.callbacks.eachStep.call(this, value); }
    if (this.time > this.duration) { this.stop(); }
}, CLASS_NAME: "OpenLayers.Tween"
}); OpenLayers.Easing = { CLASS_NAME: "OpenLayers.Easing" }; OpenLayers.Easing.Linear = { easeIn: function (t, b, c, d) { return c * t / d + b; }, easeOut: function (t, b, c, d) { return c * t / d + b; }, easeInOut: function (t, b, c, d) { return c * t / d + b; }, CLASS_NAME: "OpenLayers.Easing.Linear" }; OpenLayers.Easing.Expo = { easeIn: function (t, b, c, d) { return (t == 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b; }, easeOut: function (t, b, c, d) { return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b; }, easeInOut: function (t, b, c, d) { if (t == 0) return b; if (t == d) return b + c; if ((t /= d / 2) < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b; return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b; }, CLASS_NAME: "OpenLayers.Easing.Expo" }; OpenLayers.Easing.Quad = { easeIn: function (t, b, c, d) { return c * (t /= d) * t + b; }, easeOut: function (t, b, c, d) { return -c * (t /= d) * (t - 2) + b; }, easeInOut: function (t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t + b; return -c / 2 * ((--t) * (t - 2) - 1) + b; }, CLASS_NAME: "OpenLayers.Easing.Quad" }; OpenLayers.Map = OpenLayers.Class({ Z_INDEX_BASE: { BaseLayer: 100, Overlay: 325, Feature: 725, Popup: 750, Control: 1000 }, EVENT_TYPES: ["preaddlayer", "addlayer", "preremovelayer", "removelayer", "changelayer", "movestart", "move", "moveend", "zoomend", "popupopen", "popupclose", "addmarker", "removemarker", "clearmarkers", "mouseover", "mouseout", "mousemove", "dragstart", "drag", "dragend", "changebaselayer"], id: null, fractionalZoom: false, events: null, allOverlays: false, div: null, dragging: false, size: null, viewPortDiv: null, layerContainerOrigin: null, layerContainerDiv: null, layers: null, controls: null, popups: null, baseLayer: null, center: null, resolution: null, zoom: 0, panRatio: 1.5, viewRequestID: 0, tileSize: null, projection: "EPSG:4326", units: 'degrees', resolutions: null, maxResolution: 1.40625, minResolution: null, maxScale: null, minScale: null, maxExtent: null, minExtent: null, restrictedExtent: null, numZoomLevels: 16, theme: null, displayProjection: null, fallThrough: true, panTween: null, eventListeners: null, panMethod: OpenLayers.Easing.Expo.easeOut, panDuration: 50, paddingForPopups: null, minPx: null, maxPx: null, initialize: function (div, options) {
    if (arguments.length === 1 && typeof div === "object") { options = div; div = options && options.div; }
    this.tileSize = new OpenLayers.Size(OpenLayers.Map.TILE_WIDTH, OpenLayers.Map.TILE_HEIGHT); this.maxExtent = new OpenLayers.Bounds(-180, -90, 180, 90); this.paddingForPopups = new OpenLayers.Bounds(15, 15, 15, 15); this.theme = OpenLayers._getScriptLocation() + 'theme/default/style.css'; OpenLayers.Util.extend(this, options); this.layers = []; this.id = OpenLayers.Util.createUniqueID("OpenLayers.Map_"); this.div = OpenLayers.Util.getElement(div); if (!this.div) { this.div = document.createElement("div"); this.div.style.height = "1px"; this.div.style.width = "1px"; }
    OpenLayers.Element.addClass(this.div, 'olMap'); var id = this.id + "_OpenLayers_ViewPort"; this.viewPortDiv = OpenLayers.Util.createDiv(id, null, null, null, "relative", null, "hidden"); this.viewPortDiv.style.width = "100%"; this.viewPortDiv.style.height = "100%"; this.viewPortDiv.className = "olMapViewport"; this.div.appendChild(this.viewPortDiv); var eventsDiv = document.createElement("div"); eventsDiv.id = this.id + "_events"; eventsDiv.style.position = "absolute"; eventsDiv.style.width = "100%"; eventsDiv.style.height = "100%"; eventsDiv.style.zIndex = this.Z_INDEX_BASE.Control - 1; this.viewPortDiv.appendChild(eventsDiv); this.eventsDiv = eventsDiv; this.events = new OpenLayers.Events(this, this.eventsDiv, this.EVENT_TYPES, this.fallThrough, { includeXY: true }); id = this.id + "_OpenLayers_Container"; this.layerContainerDiv = OpenLayers.Util.createDiv(id); this.layerContainerDiv.style.zIndex = this.Z_INDEX_BASE['Popup'] - 1; this.eventsDiv.appendChild(this.layerContainerDiv); this.updateSize(); if (this.eventListeners instanceof Object) { this.events.on(this.eventListeners); }
    this.events.register("movestart", this, this.updateSize); if (OpenLayers.String.contains(navigator.appName, "Microsoft")) { this.events.register("resize", this, this.updateSize); } else { this.updateSizeDestroy = OpenLayers.Function.bind(this.updateSize, this); OpenLayers.Event.observe(window, 'resize', this.updateSizeDestroy); }
    if (this.theme) {
        var addNode = true; var nodes = document.getElementsByTagName('link'); for (var i = 0, len = nodes.length; i < len; ++i) { if (OpenLayers.Util.isEquivalentUrl(nodes.item(i).href, this.theme)) { addNode = false; break; } }
        if (addNode) { var cssNode = document.createElement('link'); cssNode.setAttribute('rel', 'stylesheet'); cssNode.setAttribute('type', 'text/css'); cssNode.setAttribute('href', this.theme); document.getElementsByTagName('head')[0].appendChild(cssNode); }
    }
    if (this.controls == null) { if (OpenLayers.Control != null) { this.controls = [new OpenLayers.Control.Navigation(), new OpenLayers.Control.PanZoom(), new OpenLayers.Control.ArgParser(), new OpenLayers.Control.Attribution()]; } else { this.controls = []; } }
    for (var i = 0, len = this.controls.length; i < len; i++) { this.addControlToMap(this.controls[i]); }
    this.popups = []; this.unloadDestroy = OpenLayers.Function.bind(this.destroy, this); OpenLayers.Event.observe(window, 'unload', this.unloadDestroy); if (options && options.layers) { delete this.center; this.addLayers(options.layers); if (options.center) { this.setCenter(options.center, options.zoom); } }
}, render: function (div) { this.div = OpenLayers.Util.getElement(div); OpenLayers.Element.addClass(this.div, 'olMap'); this.viewPortDiv.parentNode.removeChild(this.viewPortDiv); this.div.appendChild(this.viewPortDiv); this.updateSize(); }, unloadDestroy: null, updateSizeDestroy: null, destroy: function () {
    if (!this.unloadDestroy) { return false; }
    if (this.panTween) { this.panTween.stop(); this.panTween = null; }
    OpenLayers.Event.stopObserving(window, 'unload', this.unloadDestroy); this.unloadDestroy = null; if (this.updateSizeDestroy) { OpenLayers.Event.stopObserving(window, 'resize', this.updateSizeDestroy); } else { this.events.unregister("resize", this, this.updateSize); }
    this.paddingForPopups = null; if (this.controls != null) {
        for (var i = this.controls.length - 1; i >= 0; --i) { this.controls[i].destroy(); }
        this.controls = null;
    }
    if (this.layers != null) {
        for (var i = this.layers.length - 1; i >= 0; --i) { this.layers[i].destroy(false); }
        this.layers = null;
    }
    if (this.viewPortDiv) { this.div.removeChild(this.viewPortDiv); }
    this.viewPortDiv = null; if (this.eventListeners) { this.events.un(this.eventListeners); this.eventListeners = null; }
    this.events.destroy(); this.events = null;
}, setOptions: function (options) { var updatePxExtent = this.minPx && options.restrictedExtent != this.restrictedExtent; OpenLayers.Util.extend(this, options); updatePxExtent && this.moveTo(this.getCachedCenter(), this.zoom, { forceZoomChange: true }); }, getTileSize: function () { return this.tileSize; }, getBy: function (array, property, match) { var test = (typeof match.test == "function"); var found = OpenLayers.Array.filter(this[array], function (item) { return item[property] == match || (test && match.test(item[property])); }); return found; }, getLayersBy: function (property, match) { return this.getBy("layers", property, match); }, getLayersByName: function (match) { return this.getLayersBy("name", match); }, getLayersByClass: function (match) { return this.getLayersBy("CLASS_NAME", match); }, getControlsBy: function (property, match) { return this.getBy("controls", property, match); }, getControlsByClass: function (match) { return this.getControlsBy("CLASS_NAME", match); }, getLayer: function (id) {
    var foundLayer = null; for (var i = 0, len = this.layers.length; i < len; i++) { var layer = this.layers[i]; if (layer.id == id) { foundLayer = layer; break; } }
    return foundLayer;
}, setLayerZIndex: function (layer, zIdx) {
    layer.setZIndex(this.Z_INDEX_BASE[layer.isBaseLayer ? 'BaseLayer' : 'Overlay']
+ zIdx * 5);
}, resetLayersZIndex: function () { for (var i = 0, len = this.layers.length; i < len; i++) { var layer = this.layers[i]; this.setLayerZIndex(layer, i); } }, addLayer: function (layer) {
    for (var i = 0, len = this.layers.length; i < len; i++) { if (this.layers[i] == layer) { var msg = OpenLayers.i18n('layerAlreadyAdded', { 'layerName': layer.name }); OpenLayers.Console.warn(msg); return false; } }
    if (this.events.triggerEvent("preaddlayer", { layer: layer }) === false) { return; }
    if (this.allOverlays) { layer.isBaseLayer = false; }
    layer.div.className = "olLayerDiv"; layer.div.style.overflow = ""; this.setLayerZIndex(layer, this.layers.length); if (layer.isFixed) { this.viewPortDiv.appendChild(layer.div); } else { this.layerContainerDiv.appendChild(layer.div); }
    this.layers.push(layer); layer.setMap(this); if (layer.isBaseLayer || (this.allOverlays && !this.baseLayer)) { if (this.baseLayer == null) { this.setBaseLayer(layer); } else { layer.setVisibility(false); } } else { layer.redraw(); }
    this.events.triggerEvent("addlayer", { layer: layer }); layer.events.triggerEvent("added", { map: this, layer: layer }); layer.afterAdd();
}, addLayers: function (layers) { for (var i = 0, len = layers.length; i < len; i++) { this.addLayer(layers[i]); } }, removeLayer: function (layer, setNewBaseLayer) {
    if (this.events.triggerEvent("preremovelayer", { layer: layer }) === false) { return; }
    if (setNewBaseLayer == null) { setNewBaseLayer = true; }
    if (layer.isFixed) { this.viewPortDiv.removeChild(layer.div); } else { this.layerContainerDiv.removeChild(layer.div); }
    OpenLayers.Util.removeItem(this.layers, layer); layer.removeMap(this); layer.map = null; if (this.baseLayer == layer) { this.baseLayer = null; if (setNewBaseLayer) { for (var i = 0, len = this.layers.length; i < len; i++) { var iLayer = this.layers[i]; if (iLayer.isBaseLayer || this.allOverlays) { this.setBaseLayer(iLayer); break; } } } }
    this.resetLayersZIndex(); this.events.triggerEvent("removelayer", { layer: layer }); layer.events.triggerEvent("removed", { map: this, layer: layer });
}, getNumLayers: function () { return this.layers.length; }, getLayerIndex: function (layer) { return OpenLayers.Util.indexOf(this.layers, layer); }, setLayerIndex: function (layer, idx) {
    var base = this.getLayerIndex(layer); if (idx < 0) { idx = 0; } else if (idx > this.layers.length) { idx = this.layers.length; }
    if (base != idx) {
        this.layers.splice(base, 1); this.layers.splice(idx, 0, layer); for (var i = 0, len = this.layers.length; i < len; i++) { this.setLayerZIndex(this.layers[i], i); }
        this.events.triggerEvent("changelayer", { layer: layer, property: "order" }); if (this.allOverlays) { if (idx === 0) { this.setBaseLayer(layer); } else if (this.baseLayer !== this.layers[0]) { this.setBaseLayer(this.layers[0]); } }
    }
}, raiseLayer: function (layer, delta) { var idx = this.getLayerIndex(layer) + delta; this.setLayerIndex(layer, idx); }, setBaseLayer: function (newBaseLayer) {
    if (newBaseLayer != this.baseLayer) {
        if (OpenLayers.Util.indexOf(this.layers, newBaseLayer) != -1) {
            var center = this.getCachedCenter(); var newResolution = OpenLayers.Util.getResolutionFromScale(this.getScale(), newBaseLayer.units); if (this.baseLayer != null && !this.allOverlays) { this.baseLayer.setVisibility(false); }
            this.baseLayer = newBaseLayer; this.viewRequestID++; if (!this.allOverlays || this.baseLayer.visibility) { this.baseLayer.setVisibility(true); }
            if (center != null) { var newZoom = this.getZoomForResolution(newResolution || this.resolution, true); this.setCenter(center, newZoom, false, true); }
            this.events.triggerEvent("changebaselayer", { layer: this.baseLayer });
        }
    }
}, addControl: function (control, px) { this.controls.push(control); this.addControlToMap(control, px); }, addControls: function (controls, pixels) { var pxs = (arguments.length === 1) ? [] : pixels; for (var i = 0, len = controls.length; i < len; i++) { var ctrl = controls[i]; var px = (pxs[i]) ? pxs[i] : null; this.addControl(ctrl, px); } }, addControlToMap: function (control, px) {
    control.outsideViewport = (control.div != null); if (this.displayProjection && !control.displayProjection) { control.displayProjection = this.displayProjection; }
    control.setMap(this); var div = control.draw(px); if (div) {
        if (!control.outsideViewport) {
            div.style.zIndex = this.Z_INDEX_BASE['Control'] +
this.controls.length; this.viewPortDiv.appendChild(div);
        }
    }
    if (control.autoActivate) { control.activate(); }
}, getControl: function (id) {
    var returnControl = null; for (var i = 0, len = this.controls.length; i < len; i++) { var control = this.controls[i]; if (control.id == id) { returnControl = control; break; } }
    return returnControl;
}, removeControl: function (control) {
    if ((control) && (control == this.getControl(control.id))) {
        if (control.div && (control.div.parentNode == this.viewPortDiv)) { this.viewPortDiv.removeChild(control.div); }
        OpenLayers.Util.removeItem(this.controls, control);
    }
}, addPopup: function (popup, exclusive) {
    if (exclusive) { for (var i = this.popups.length - 1; i >= 0; --i) { this.removePopup(this.popups[i]); } }
    popup.map = this; this.popups.push(popup); var popupDiv = popup.draw(); if (popupDiv) {
        popupDiv.style.zIndex = this.Z_INDEX_BASE['Popup'] +
this.popups.length; this.layerContainerDiv.appendChild(popupDiv);
    }
}, removePopup: function (popup) {
    OpenLayers.Util.removeItem(this.popups, popup); if (popup.div) {
        try { this.layerContainerDiv.removeChild(popup.div); }
        catch (e) { }
    }
    popup.map = null;
}, getSize: function () {
    var size = null; if (this.size != null) { size = this.size.clone(); }
    return size;
}, updateSize: function () {
    var newSize = this.getCurrentSize(); if (newSize && !isNaN(newSize.h) && !isNaN(newSize.w)) {
        this.events.clearMouseCache(); var oldSize = this.getSize(); if (oldSize == null) { this.size = oldSize = newSize; }
        if (!newSize.equals(oldSize)) {
            this.size = newSize; for (var i = 0, len = this.layers.length; i < len; i++) { this.layers[i].onMapResize(); }
            var center = this.getCachedCenter(); if (this.baseLayer != null && center != null) { var zoom = this.getZoom(); this.zoom = null; this.setCenter(center, zoom); }
        }
    }
}, getCurrentSize: function () {
    var size = new OpenLayers.Size(this.div.clientWidth, this.div.clientHeight); if (size.w == 0 && size.h == 0 || isNaN(size.w) && isNaN(size.h)) { size.w = this.div.offsetWidth; size.h = this.div.offsetHeight; }
    if (size.w == 0 && size.h == 0 || isNaN(size.w) && isNaN(size.h)) { size.w = parseInt(this.div.style.width); size.h = parseInt(this.div.style.height); }
    return size;
}, calculateBounds: function (center, resolution) {
    var extent = null; if (center == null) { center = this.getCachedCenter(); }
    if (resolution == null) { resolution = this.getResolution(); }
    if ((center != null) && (resolution != null)) { var size = this.getSize(); var w_deg = size.w * resolution; var h_deg = size.h * resolution; extent = new OpenLayers.Bounds(center.lon - w_deg / 2, center.lat - h_deg / 2, center.lon + w_deg / 2, center.lat + h_deg / 2); }
    return extent;
}, getCenter: function () {
    var center = null; var cachedCenter = this.getCachedCenter(); if (cachedCenter) { center = cachedCenter.clone(); }
    return center;
}, getCachedCenter: function () {
    if (!this.center && this.size) { this.center = this.getLonLatFromViewPortPx(new OpenLayers.Pixel(this.size.w / 2, this.size.h / 2)); }
    return this.center;
}, getZoom: function () { return this.zoom; }, pan: function (dx, dy, options) { options = OpenLayers.Util.applyDefaults(options, { animate: true, dragging: false }); if (options.dragging) { if (dx != 0 || dy != 0) { this.moveByPx(dx, dy); } } else { var centerPx = this.getViewPortPxFromLonLat(this.getCachedCenter()); var newCenterPx = centerPx.add(dx, dy); if (this.dragging || !newCenterPx.equals(centerPx)) { var newCenterLonLat = this.getLonLatFromViewPortPx(newCenterPx); if (options.animate) { this.panTo(newCenterLonLat); } else { this.moveTo(newCenterLonLat); this.dragging = false; this.events.triggerEvent("moveend"); } } } }, panTo: function (lonlat) {
    if (this.panMethod && this.getExtent().scale(this.panRatio).containsLonLat(lonlat)) {
        if (!this.panTween) { this.panTween = new OpenLayers.Tween(this.panMethod); }
        var center = this.getCachedCenter(); if (lonlat.equals(center)) { return; }
        var from = this.getPixelFromLonLat(center); var to = this.getPixelFromLonLat(lonlat); var vector = { x: to.x - from.x, y: to.y - from.y }; var last = { x: 0, y: 0 }; this.panTween.start({ x: 0, y: 0 }, vector, this.panDuration, { callbacks: { eachStep: OpenLayers.Function.bind(function (px) { var x = px.x - last.x, y = px.y - last.y; this.moveByPx(x, y); last.x = Math.round(px.x); last.y = Math.round(px.y); }, this), done: OpenLayers.Function.bind(function (px) { this.moveTo(lonlat); this.dragging = false; this.events.triggerEvent("moveend"); }, this)} });
    } else { this.setCenter(lonlat); }
}, setCenter: function (lonlat, zoom, dragging, forceZoomChange) { this.panTween && this.panTween.stop(); this.moveTo(lonlat, zoom, { 'dragging': dragging, 'forceZoomChange': forceZoomChange }); }, moveByPx: function (dx, dy) {
    var hw = this.size.w / 2; var hh = this.size.h / 2; var x = hw + dx; var y = hh + dy; var wrapDateLine = this.baseLayer.wrapDateLine; var xRestriction = 0; var yRestriction = 0; if (this.restrictedExtent) { xRestriction = hw; yRestriction = hh; wrapDateLine = false; }
    dx = wrapDateLine || x <= this.maxPx.x - xRestriction && x >= this.minPx.x + xRestriction ? Math.round(dx) : 0; dy = y <= this.maxPx.y - yRestriction && y >= this.minPx.y + yRestriction ? Math.round(dy) : 0; var minX = this.minPx.x, maxX = this.maxPx.x; if (dx || dy) {
        if (!this.dragging) { this.dragging = true; this.events.triggerEvent("movestart"); }
        this.center = null; if (dx) {
            this.layerContainerDiv.style.left = parseInt(this.layerContainerDiv.style.left) - dx + "px"; this.minPx.x -= dx; this.maxPx.x -= dx; if (wrapDateLine) {
                if (this.maxPx.x > maxX) { this.maxPx.x -= (maxX - minX); }
                if (this.minPx.x < minX) { this.minPx.x += (maxX - minX); }
            }
        }
        if (dy) { this.layerContainerDiv.style.top = parseInt(this.layerContainerDiv.style.top) - dy + "px"; this.minPx.y -= dy; this.maxPx.y -= dy; }
        var layer, i, len; for (i = 0, len = this.layers.length; i < len; ++i) { layer = this.layers[i]; if (layer.visibility && (layer === this.baseLayer || layer.inRange)) { layer.moveByPx(dx, dy); layer.events.triggerEvent("move"); } }
        this.events.triggerEvent("move");
    }
}, moveTo: function (lonlat, zoom, options) {
    if (!options) { options = {}; }
    if (zoom != null) { zoom = parseFloat(zoom); if (!this.fractionalZoom) { zoom = Math.round(zoom); } }
    var dragging = options.dragging || this.dragging; var forceZoomChange = options.forceZoomChange; if (!this.getCachedCenter() && !this.isValidLonLat(lonlat)) { lonlat = this.maxExtent.getCenterLonLat(); this.center = lonlat.clone(); }
    if (this.restrictedExtent != null) {
        if (lonlat == null) { lonlat = this.center; }
        if (zoom == null) { zoom = this.getZoom(); }
        var resolution = this.getResolutionForZoom(zoom); var extent = this.calculateBounds(lonlat, resolution); if (!this.restrictedExtent.containsBounds(extent)) {
            var maxCenter = this.restrictedExtent.getCenterLonLat(); if (extent.getWidth() > this.restrictedExtent.getWidth()) { lonlat = new OpenLayers.LonLat(maxCenter.lon, lonlat.lat); } else if (extent.left < this.restrictedExtent.left) {
                lonlat = lonlat.add(this.restrictedExtent.left -
extent.left, 0);
            } else if (extent.right > this.restrictedExtent.right) {
                lonlat = lonlat.add(this.restrictedExtent.right -
extent.right, 0);
            }
            if (extent.getHeight() > this.restrictedExtent.getHeight()) { lonlat = new OpenLayers.LonLat(lonlat.lon, maxCenter.lat); } else if (extent.bottom < this.restrictedExtent.bottom) {
                lonlat = lonlat.add(0, this.restrictedExtent.bottom -
extent.bottom);
            }
            else if (extent.top > this.restrictedExtent.top) {
                lonlat = lonlat.add(0, this.restrictedExtent.top -
extent.top);
            }
        }
    }
    var zoomChanged = forceZoomChange || ((this.isValidZoomLevel(zoom)) && (zoom != this.getZoom())); var centerChanged = (this.isValidLonLat(lonlat)) && (!lonlat.equals(this.center)); if (zoomChanged || centerChanged || dragging) {
        dragging || this.events.triggerEvent("movestart"); if (centerChanged) {
            if (!zoomChanged && this.center) { this.centerLayerContainer(lonlat); }
            this.center = lonlat.clone();
        }
        var res = zoomChanged ? this.getResolutionForZoom(zoom) : this.getResolution(); if (zoomChanged || this.layerContainerOrigin == null) { this.layerContainerOrigin = this.getCachedCenter(); this.layerContainerDiv.style.left = "0px"; this.layerContainerDiv.style.top = "0px"; var maxExtent = this.getMaxExtent({ restricted: true }); var maxExtentCenter = maxExtent.getCenterLonLat(); var lonDelta = this.center.lon - maxExtentCenter.lon; var latDelta = maxExtentCenter.lat - this.center.lat; var extentWidth = Math.round(maxExtent.getWidth() / res); var extentHeight = Math.round(maxExtent.getHeight() / res); var left = (this.size.w - extentWidth) / 2 - lonDelta / res; var top = (this.size.h - extentHeight) / 2 - latDelta / res; this.minPx = new OpenLayers.Pixel(left, top); this.maxPx = new OpenLayers.Pixel(left + extentWidth, top + extentHeight); }
        if (zoomChanged) { this.zoom = zoom; this.resolution = res; this.viewRequestID++; }
        var bounds = this.getExtent(); if (this.baseLayer.visibility) { this.baseLayer.moveTo(bounds, zoomChanged, options.dragging); options.dragging || this.baseLayer.events.triggerEvent("moveend", { zoomChanged: zoomChanged }); }
        bounds = this.baseLayer.getExtent(); for (var i = this.layers.length - 1; i >= 0; --i) {
            var layer = this.layers[i]; if (layer !== this.baseLayer && !layer.isBaseLayer) {
                var inRange = layer.calculateInRange(); if (layer.inRange != inRange) {
                    layer.inRange = inRange; if (!inRange) { layer.display(false); }
                    this.events.triggerEvent("changelayer", { layer: layer, property: "visibility" });
                }
                if (inRange && layer.visibility) { layer.moveTo(bounds, zoomChanged, options.dragging); options.dragging || layer.events.triggerEvent("moveend", { zoomChanged: zoomChanged }); }
            }
        }
        this.events.triggerEvent("move"); dragging || this.events.triggerEvent("moveend"); if (zoomChanged) {
            for (var i = 0, len = this.popups.length; i < len; i++) { this.popups[i].updatePosition(); }
            this.events.triggerEvent("zoomend");
        }
    }
}, centerLayerContainer: function (lonlat) { var originPx = this.getViewPortPxFromLonLat(this.layerContainerOrigin); var newPx = this.getViewPortPxFromLonLat(lonlat); if ((originPx != null) && (newPx != null)) { var oldLeft = parseInt(this.layerContainerDiv.style.left); var oldTop = parseInt(this.layerContainerDiv.style.top); var newLeft = Math.round(originPx.x - newPx.x); var newTop = Math.round(originPx.y - newPx.y); this.layerContainerDiv.style.left = newLeft + "px"; this.layerContainerDiv.style.top = newTop + "px"; var dx = oldLeft - newLeft; var dy = oldTop - newTop; this.minPx.x -= dx; this.maxPx.x -= dx; this.minPx.y -= dy; this.maxPx.y -= dy; } }, isValidZoomLevel: function (zoomLevel) { return ((zoomLevel != null) && (zoomLevel >= 0) && (zoomLevel < this.getNumZoomLevels())); }, isValidLonLat: function (lonlat) {
    var valid = false; if (lonlat != null) { var maxExtent = this.getMaxExtent(); valid = maxExtent.containsLonLat(lonlat); }
    return valid;
}, getProjection: function () { var projection = this.getProjectionObject(); return projection ? projection.getCode() : null; }, getProjectionObject: function () {
    var projection = null; if (this.baseLayer != null) { projection = this.baseLayer.projection; }
    return projection;
}, getMaxResolution: function () {
    var maxResolution = null; if (this.baseLayer != null) { maxResolution = this.baseLayer.maxResolution; }
    return maxResolution;
}, getMaxExtent: function (options) {
    var maxExtent = null; if (options && options.restricted && this.restrictedExtent) { maxExtent = this.restrictedExtent; } else if (this.baseLayer != null) { maxExtent = this.baseLayer.maxExtent; }
    return maxExtent;
}, getNumZoomLevels: function () {
    var numZoomLevels = null; if (this.baseLayer != null) { numZoomLevels = this.baseLayer.numZoomLevels; }
    return numZoomLevels;
}, getExtent: function () {
    var extent = null; if (this.baseLayer != null) { extent = this.baseLayer.getExtent(); }
    return extent;
}, getResolution: function () {
    var resolution = null; if (this.baseLayer != null) { resolution = this.baseLayer.getResolution(); } else if (this.allOverlays === true && this.layers.length > 0) { resolution = this.layers[0].getResolution(); }
    return resolution;
}, getUnits: function () {
    var units = null; if (this.baseLayer != null) { units = this.baseLayer.units; }
    return units;
}, getScale: function () {
    var scale = null; if (this.baseLayer != null) { var res = this.getResolution(); var units = this.baseLayer.units; scale = OpenLayers.Util.getScaleFromResolution(res, units); }
    return scale;
}, getZoomForExtent: function (bounds, closest) {
    var zoom = null; if (this.baseLayer != null) { zoom = this.baseLayer.getZoomForExtent(bounds, closest); }
    return zoom;
}, getResolutionForZoom: function (zoom) {
    var resolution = null; if (this.baseLayer) { resolution = this.baseLayer.getResolutionForZoom(zoom); }
    return resolution;
}, getZoomForResolution: function (resolution, closest) {
    var zoom = null; if (this.baseLayer != null) { zoom = this.baseLayer.getZoomForResolution(resolution, closest); }
    return zoom;
}, zoomTo: function (zoom) { if (this.isValidZoomLevel(zoom)) { this.setCenter(null, zoom); } }, zoomIn: function () { this.zoomTo(this.getZoom() + 1); }, zoomOut: function () { this.zoomTo(this.getZoom() - 1); }, zoomToExtent: function (bounds, closest) {
    var center = bounds.getCenterLonLat(); if (this.baseLayer.wrapDateLine) {
        var maxExtent = this.getMaxExtent(); bounds = bounds.clone(); while (bounds.right < bounds.left) { bounds.right += maxExtent.getWidth(); }
        center = bounds.getCenterLonLat().wrapDateLine(maxExtent);
    }
    this.setCenter(center, this.getZoomForExtent(bounds, closest));
}, zoomToMaxExtent: function (options) { var restricted = (options) ? options.restricted : true; var maxExtent = this.getMaxExtent({ 'restricted': restricted }); this.zoomToExtent(maxExtent); }, zoomToScale: function (scale, closest) { var res = OpenLayers.Util.getResolutionFromScale(scale, this.baseLayer.units); var size = this.getSize(); var w_deg = size.w * res; var h_deg = size.h * res; var center = this.getCachedCenter(); var extent = new OpenLayers.Bounds(center.lon - w_deg / 2, center.lat - h_deg / 2, center.lon + w_deg / 2, center.lat + h_deg / 2); this.zoomToExtent(extent, closest); }, getLonLatFromViewPortPx: function (viewPortPx) {
    var lonlat = null; if (this.baseLayer != null) { lonlat = this.baseLayer.getLonLatFromViewPortPx(viewPortPx); }
    return lonlat;
}, getViewPortPxFromLonLat: function (lonlat) {
    var px = null; if (this.baseLayer != null) { px = this.baseLayer.getViewPortPxFromLonLat(lonlat); }
    return px;
}, getLonLatFromPixel: function (px) { return this.getLonLatFromViewPortPx(px); }, getPixelFromLonLat: function (lonlat) { var px = this.getViewPortPxFromLonLat(lonlat); px.x = Math.round(px.x); px.y = Math.round(px.y); return px; }, getGeodesicPixelSize: function (px) {
    var lonlat = px ? this.getLonLatFromPixel(px) : (this.getCachedCenter() || new OpenLayers.LonLat(0, 0)); var res = this.getResolution(); var left = lonlat.add(-res / 2, 0); var right = lonlat.add(res / 2, 0); var bottom = lonlat.add(0, -res / 2); var top = lonlat.add(0, res / 2); var dest = new OpenLayers.Projection("EPSG:4326"); var source = this.getProjectionObject() || dest; if (!source.equals(dest)) { left.transform(source, dest); right.transform(source, dest); bottom.transform(source, dest); top.transform(source, dest); }
    return new OpenLayers.Size(OpenLayers.Util.distVincenty(left, right), OpenLayers.Util.distVincenty(bottom, top));
}, getViewPortPxFromLayerPx: function (layerPx) {
    var viewPortPx = null; if (layerPx != null) { var dX = parseInt(this.layerContainerDiv.style.left); var dY = parseInt(this.layerContainerDiv.style.top); viewPortPx = layerPx.add(dX, dY); }
    return viewPortPx;
}, getLayerPxFromViewPortPx: function (viewPortPx) {
    var layerPx = null; if (viewPortPx != null) { var dX = -parseInt(this.layerContainerDiv.style.left); var dY = -parseInt(this.layerContainerDiv.style.top); layerPx = viewPortPx.add(dX, dY); if (isNaN(layerPx.x) || isNaN(layerPx.y)) { layerPx = null; } }
    return layerPx;
}, getLonLatFromLayerPx: function (px) { px = this.getViewPortPxFromLayerPx(px); return this.getLonLatFromViewPortPx(px); }, getLayerPxFromLonLat: function (lonlat) { var px = this.getPixelFromLonLat(lonlat); return this.getLayerPxFromViewPortPx(px); }, CLASS_NAME: "OpenLayers.Map"
}); OpenLayers.Map.TILE_WIDTH = 256; OpenLayers.Map.TILE_HEIGHT = 256; OpenLayers.Projection = OpenLayers.Class({ proj: null, projCode: null, titleRegEx: /\+title=[^\+]*/, initialize: function (projCode, options) { OpenLayers.Util.extend(this, options); this.projCode = projCode; if (window.Proj4js) { this.proj = new Proj4js.Proj(projCode); } }, getCode: function () { return this.proj ? this.proj.srsCode : this.projCode; }, getUnits: function () { return this.proj ? this.proj.units : null; }, toString: function () { return this.getCode(); }, equals: function (projection) {
    var p = projection, equals = false; if (p) { if (window.Proj4js && this.proj.defData && p.proj.defData) { equals = this.proj.defData.replace(this.titleRegEx, "") == p.proj.defData.replace(this.titleRegEx, ""); } else if (p.getCode) { var source = this.getCode(), target = p.getCode(); equals = source == target || !!OpenLayers.Projection.transforms[source] && OpenLayers.Projection.transforms[source][target] === OpenLayers.Projection.nullTransform; } }
    return equals;
}, destroy: function () { delete this.proj; delete this.projCode; }, CLASS_NAME: "OpenLayers.Projection"
}); OpenLayers.Projection.transforms = {}; OpenLayers.Projection.addTransform = function (from, to, method) {
    if (!OpenLayers.Projection.transforms[from]) { OpenLayers.Projection.transforms[from] = {}; }
    OpenLayers.Projection.transforms[from][to] = method;
}; OpenLayers.Projection.transform = function (point, source, dest) {
    if (source.proj && dest.proj) { point = Proj4js.transform(source.proj, dest.proj, point); } else if (source && dest && OpenLayers.Projection.transforms[source.getCode()] && OpenLayers.Projection.transforms[source.getCode()][dest.getCode()]) { OpenLayers.Projection.transforms[source.getCode()][dest.getCode()](point); }
    return point;
}; OpenLayers.Projection.nullTransform = function (point) { return point; };





OpenLayers.Layer = OpenLayers.Class({ id: null, name: null, div: null, opacity: null, alwaysInRange: null, EVENT_TYPES: ["loadstart", "loadend", "loadcancel", "visibilitychanged", "move", "moveend", "added", "removed"], RESOLUTION_PROPERTIES: ['scales', 'resolutions', 'maxScale', 'minScale', 'maxResolution', 'minResolution', 'numZoomLevels', 'maxZoomLevel'], events: null, map: null, isBaseLayer: false, alpha: false, displayInLayerSwitcher: true, visibility: true, attribution: null, inRange: false, imageSize: null, imageOffset: null, options: null, eventListeners: null, gutter: 0, projection: null, units: null, scales: null, resolutions: null, maxExtent: null, minExtent: null, maxResolution: null, minResolution: null, numZoomLevels: null, minScale: null, maxScale: null, displayOutsideMaxExtent: false, wrapDateLine: false, transitionEffect: null, SUPPORTED_TRANSITIONS: ['resize'], metadata: {}, initialize: function (name, options) {
    this.addOptions(options); this.name = name; if (this.id == null) { this.id = OpenLayers.Util.createUniqueID(this.CLASS_NAME + "_"); this.div = OpenLayers.Util.createDiv(this.id); this.div.style.width = "100%"; this.div.style.height = "100%"; this.div.dir = "ltr"; this.events = new OpenLayers.Events(this, this.div, this.EVENT_TYPES); if (this.eventListeners instanceof Object) { this.events.on(this.eventListeners); } }
    if (this.wrapDateLine) { this.displayOutsideMaxExtent = true; }
}, destroy: function (setNewBaseLayer) {
    if (setNewBaseLayer == null) { setNewBaseLayer = true; }
    if (this.map != null) { this.map.removeLayer(this, setNewBaseLayer); }
    this.projection = null; this.map = null; this.name = null; this.div = null; this.options = null; if (this.events) {
        if (this.eventListeners) { this.events.un(this.eventListeners); }
        this.events.destroy();
    }
    this.eventListeners = null; this.events = null;
}, clone: function (obj) {
    if (obj == null) { obj = new OpenLayers.Layer(this.name, this.getOptions()); }
    OpenLayers.Util.applyDefaults(obj, this); obj.map = null; return obj;
}, getOptions: function () {
    var options = {}; for (var o in this.options) { options[o] = this[o]; }
    return options;
}, setName: function (newName) { if (newName != this.name) { this.name = newName; if (this.map != null) { this.map.events.triggerEvent("changelayer", { layer: this, property: "name" }); } } }, addOptions: function (newOptions, reinitialize) {
    if (this.options == null) { this.options = {}; }
    OpenLayers.Util.extend(this.options, newOptions); OpenLayers.Util.extend(this, newOptions); if (typeof this.projection == "string") { this.projection = new OpenLayers.Projection(this.projection); }
    if (this.projection && this.projection.getUnits()) { this.units = this.projection.getUnits(); }
    if (this.map) {
        var resolution = this.map.getResolution(); var properties = this.RESOLUTION_PROPERTIES.concat(["projection", "units", "minExtent", "maxExtent"]); for (var o in newOptions) {
            if (newOptions.hasOwnProperty(o) && OpenLayers.Util.indexOf(properties, o) >= 0) {
                this.initResolutions(); if (reinitialize && this.map.baseLayer === this) { this.map.setCenter(this.map.getCenter(), this.map.getZoomForResolution(resolution), false, true); this.map.events.triggerEvent("changebaselayer", { layer: this }); }
                break;
            }
        }
    }
}, onMapResize: function () { }, redraw: function () {
    var redrawn = false; if (this.map) { this.inRange = this.calculateInRange(); var extent = this.getExtent(); if (extent && this.inRange && this.visibility) { var zoomChanged = true; this.moveTo(extent, zoomChanged, false); this.events.triggerEvent("moveend", { "zoomChanged": zoomChanged }); redrawn = true; } }
    return redrawn;
}, moveTo: function (bounds, zoomChanged, dragging) {
    var display = this.visibility; if (!this.isBaseLayer) { display = display && this.inRange; }
    this.display(display);
}, moveByPx: function (dx, dy) { }, setMap: function (map) {
    if (this.map == null) {
        this.map = map; this.maxExtent = this.maxExtent || this.map.maxExtent; this.minExtent = this.minExtent || this.map.minExtent; this.projection = this.projection || this.map.projection; if (typeof this.projection == "string") { this.projection = new OpenLayers.Projection(this.projection); }
        this.units = this.projection.getUnits() || this.units || this.map.units; this.initResolutions(); if (!this.isBaseLayer) { this.inRange = this.calculateInRange(); var show = ((this.visibility) && (this.inRange)); this.div.style.display = show ? "" : "none"; }
        this.setTileSize();
    }
}, afterAdd: function () { }, removeMap: function (map) { }, getImageSize: function (bounds) { return (this.imageSize || this.tileSize); }, setTileSize: function (size) { var tileSize = (size) ? size : ((this.tileSize) ? this.tileSize : this.map.getTileSize()); this.tileSize = tileSize; if (this.gutter) { this.imageOffset = new OpenLayers.Pixel(-this.gutter, -this.gutter); this.imageSize = new OpenLayers.Size(tileSize.w + (2 * this.gutter), tileSize.h + (2 * this.gutter)); } }, getVisibility: function () { return this.visibility; }, setVisibility: function (visibility) {
    if (visibility != this.visibility) {
        this.visibility = visibility; this.display(visibility); this.redraw(); if (this.map != null) { this.map.events.triggerEvent("changelayer", { layer: this, property: "visibility" }); }
        this.events.triggerEvent("visibilitychanged");
    }
}, display: function (display) { if (display != (this.div.style.display != "none")) { this.div.style.display = (display && this.calculateInRange()) ? "block" : "none"; } }, calculateInRange: function () {
    var inRange = false; if (this.alwaysInRange) { inRange = true; } else { if (this.map) { var resolution = this.map.getResolution(); inRange = ((resolution >= this.minResolution) && (resolution <= this.maxResolution)); } }
    return inRange;
}, setIsBaseLayer: function (isBaseLayer) { if (isBaseLayer != this.isBaseLayer) { this.isBaseLayer = isBaseLayer; if (this.map != null) { this.map.events.triggerEvent("changebaselayer", { layer: this }); } } }, initResolutions: function () {
    var i, len, p; var props = {}, alwaysInRange = true; for (i = 0, len = this.RESOLUTION_PROPERTIES.length; i < len; i++) { p = this.RESOLUTION_PROPERTIES[i]; props[p] = this.options[p]; if (alwaysInRange && this.options[p]) { alwaysInRange = false; } }
    if (this.alwaysInRange == null) { this.alwaysInRange = alwaysInRange; }
    if (props.resolutions == null) { props.resolutions = this.resolutionsFromScales(props.scales); }
    if (props.resolutions == null) { props.resolutions = this.calculateResolutions(props); }
    if (props.resolutions == null) {
        for (i = 0, len = this.RESOLUTION_PROPERTIES.length; i < len; i++) { p = this.RESOLUTION_PROPERTIES[i]; props[p] = this.options[p] != null ? this.options[p] : this.map[p]; }
        if (props.resolutions == null) { props.resolutions = this.resolutionsFromScales(props.scales); }
        if (props.resolutions == null) { props.resolutions = this.calculateResolutions(props); }
    }
    var maxResolution; if (this.options.maxResolution && this.options.maxResolution !== "auto") { maxResolution = this.options.maxResolution; }
    if (this.options.minScale) { maxResolution = OpenLayers.Util.getResolutionFromScale(this.options.minScale, this.units); }
    var minResolution; if (this.options.minResolution && this.options.minResolution !== "auto") { minResolution = this.options.minResolution; }
    if (this.options.maxScale) { minResolution = OpenLayers.Util.getResolutionFromScale(this.options.maxScale, this.units); }
    if (props.resolutions) {
        props.resolutions.sort(function (a, b) { return (b - a); }); if (!maxResolution) { maxResolution = props.resolutions[0]; }
        if (!minResolution) { var lastIdx = props.resolutions.length - 1; minResolution = props.resolutions[lastIdx]; }
    }
    this.resolutions = props.resolutions; if (this.resolutions) {
        len = this.resolutions.length; this.scales = new Array(len); for (i = 0; i < len; i++) { this.scales[i] = OpenLayers.Util.getScaleFromResolution(this.resolutions[i], this.units); }
        this.numZoomLevels = len;
    }
    this.minResolution = minResolution; if (minResolution) { this.maxScale = OpenLayers.Util.getScaleFromResolution(minResolution, this.units); }
    this.maxResolution = maxResolution; if (maxResolution) { this.minScale = OpenLayers.Util.getScaleFromResolution(maxResolution, this.units); }
}, resolutionsFromScales: function (scales) {
    if (scales == null) { return; }
    var resolutions, i, len; len = scales.length; resolutions = new Array(len); for (i = 0; i < len; i++) { resolutions[i] = OpenLayers.Util.getResolutionFromScale(scales[i], this.units); }
    return resolutions;
}, calculateResolutions: function (props) {
    var viewSize, wRes, hRes; var maxResolution = props.maxResolution; if (props.minScale != null) { maxResolution = OpenLayers.Util.getResolutionFromScale(props.minScale, this.units); } else if (maxResolution == "auto" && this.maxExtent != null) { viewSize = this.map.getSize(); wRes = this.maxExtent.getWidth() / viewSize.w; hRes = this.maxExtent.getHeight() / viewSize.h; maxResolution = Math.max(wRes, hRes); }
    var minResolution = props.minResolution; if (props.maxScale != null) { minResolution = OpenLayers.Util.getResolutionFromScale(props.maxScale, this.units); } else if (props.minResolution == "auto" && this.minExtent != null) { viewSize = this.map.getSize(); wRes = this.minExtent.getWidth() / viewSize.w; hRes = this.minExtent.getHeight() / viewSize.h; minResolution = Math.max(wRes, hRes); }
    var maxZoomLevel = props.maxZoomLevel; var numZoomLevels = props.numZoomLevels; if (typeof minResolution === "number" && typeof maxResolution === "number" && numZoomLevels === undefined) { var ratio = maxResolution / minResolution; numZoomLevels = Math.floor(Math.log(ratio) / Math.log(2)) + 1; } else if (numZoomLevels === undefined && maxZoomLevel != null) { numZoomLevels = maxZoomLevel + 1; }
    if (typeof numZoomLevels !== "number" || numZoomLevels <= 0 || (typeof maxResolution !== "number" && typeof minResolution !== "number")) { return; }
    var resolutions = new Array(numZoomLevels); var base = 2; if (typeof minResolution == "number" && typeof maxResolution == "number") { base = Math.pow((maxResolution / minResolution), (1 / (numZoomLevels - 1))); }
    var i; if (typeof maxResolution === "number") { for (i = 0; i < numZoomLevels; i++) { resolutions[i] = maxResolution / Math.pow(base, i); } } else { for (i = 0; i < numZoomLevels; i++) { resolutions[numZoomLevels - 1 - i] = minResolution * Math.pow(base, i); } }
    return resolutions;
}, getResolution: function () { var zoom = this.map.getZoom(); return this.getResolutionForZoom(zoom); }, getExtent: function () { return this.map.calculateBounds(); }, getZoomForExtent: function (extent, closest) { var viewSize = this.map.getSize(); var idealResolution = Math.max(extent.getWidth() / viewSize.w, extent.getHeight() / viewSize.h); return this.getZoomForResolution(idealResolution, closest); }, getDataExtent: function () { }, getResolutionForZoom: function (zoom) {
    zoom = Math.max(0, Math.min(zoom, this.resolutions.length - 1)); var resolution; if (this.map.fractionalZoom) {
        var low = Math.floor(zoom); var high = Math.ceil(zoom); resolution = this.resolutions[low] -
((zoom - low) * (this.resolutions[low] - this.resolutions[high]));
    } else { resolution = this.resolutions[Math.round(zoom)]; }
    return resolution;
}, getZoomForResolution: function (resolution, closest) {
    var zoom, i, len; if (this.map.fractionalZoom) {
        var lowZoom = 0; var highZoom = this.resolutions.length - 1; var highRes = this.resolutions[lowZoom]; var lowRes = this.resolutions[highZoom]; var res; for (i = 0, len = this.resolutions.length; i < len; ++i) {
            res = this.resolutions[i]; if (res >= resolution) { highRes = res; lowZoom = i; }
            if (res <= resolution) { lowRes = res; highZoom = i; break; }
        }
        var dRes = highRes - lowRes; if (dRes > 0) { zoom = lowZoom + ((highRes - resolution) / dRes); } else { zoom = lowZoom; }
    } else {
        var diff; var minDiff = Number.POSITIVE_INFINITY; for (i = 0, len = this.resolutions.length; i < len; i++) {
            if (closest) {
                diff = Math.abs(this.resolutions[i] - resolution); if (diff > minDiff) { break; }
                minDiff = diff;
            } else { if (this.resolutions[i] < resolution) { break; } }
        }
        zoom = Math.max(0, i - 1);
    }
    return zoom;
}, getLonLatFromViewPortPx: function (viewPortPx) {
    var lonlat = null; var map = this.map; if (viewPortPx != null && map.minPx) { var res = map.getResolution(); var maxExtent = map.getMaxExtent({ restricted: true }); var lon = (viewPortPx.x - map.minPx.x) * res + maxExtent.left; var lat = (map.minPx.y - viewPortPx.y) * res + maxExtent.top; lonlat = new OpenLayers.LonLat(lon, lat); if (this.wrapDateLine) { lonlat = lonlat.wrapDateLine(this.maxExtent); } }
    return lonlat;
}, getViewPortPxFromLonLat: function (lonlat) {
    var px = null; if (lonlat != null) { var resolution = this.map.getResolution(); var extent = this.map.getExtent(); px = new OpenLayers.Pixel((1 / resolution * (lonlat.lon - extent.left)), (1 / resolution * (extent.top - lonlat.lat))); }
    return px;
}, setOpacity: function (opacity) {
    if (opacity != this.opacity) {
        this.opacity = opacity; for (var i = 0, len = this.div.childNodes.length; i < len; ++i) { var element = this.div.childNodes[i].firstChild; OpenLayers.Util.modifyDOMElement(element, null, null, null, null, null, null, opacity); }
        if (this.map != null) { this.map.events.triggerEvent("changelayer", { layer: this, property: "opacity" }); }
    }
}, getZIndex: function () { return this.div.style.zIndex; }, setZIndex: function (zIndex) { this.div.style.zIndex = zIndex; }, adjustBounds: function (bounds) {
    if (this.gutter) { var mapGutter = this.gutter * this.map.getResolution(); bounds = new OpenLayers.Bounds(bounds.left - mapGutter, bounds.bottom - mapGutter, bounds.right + mapGutter, bounds.top + mapGutter); }
    if (this.wrapDateLine) { var wrappingOptions = { 'rightTolerance': this.getResolution(), 'leftTolerance': this.getResolution() }; bounds = bounds.wrapDateLine(this.maxExtent, wrappingOptions); }
    return bounds;
}, CLASS_NAME: "OpenLayers.Layer"
});


OpenLayers.Layer.SphericalMercator = { getExtent: function () {
    var extent = null; if (this.sphericalMercator) { extent = this.map.calculateBounds(); } else { extent = OpenLayers.Layer.FixedZoomLevels.prototype.getExtent.apply(this); }
    return extent;
}, getLonLatFromViewPortPx: function (viewPortPx) { return OpenLayers.Layer.prototype.getLonLatFromViewPortPx.apply(this, arguments); }, getViewPortPxFromLonLat: function (lonlat) { return OpenLayers.Layer.prototype.getViewPortPxFromLonLat.apply(this, arguments); }, initMercatorParameters: function () {
    this.RESOLUTIONS = []; var maxResolution = 156543.03390625; for (var zoom = 0; zoom <= this.MAX_ZOOM_LEVEL; ++zoom) { this.RESOLUTIONS[zoom] = maxResolution / Math.pow(2, zoom); }
    this.units = "m"; this.projection = this.projection || "EPSG:900913";
}, forwardMercator: function (lon, lat) { var x = lon * 20037508.34 / 180; var y = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180); y = y * 20037508.34 / 180; return new OpenLayers.LonLat(x, y); }, inverseMercator: function (x, y) { var lon = (x / 20037508.34) * 180; var lat = (y / 20037508.34) * 180; lat = 180 / Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180)) - Math.PI / 2); return new OpenLayers.LonLat(lon, lat); }, projectForward: function (point) { var lonlat = OpenLayers.Layer.SphericalMercator.forwardMercator(point.x, point.y); point.x = lonlat.lon; point.y = lonlat.lat; return point; }, projectInverse: function (point) { var lonlat = OpenLayers.Layer.SphericalMercator.inverseMercator(point.x, point.y); point.x = lonlat.lon; point.y = lonlat.lat; return point; }
}; (function () { var codes = ["EPSG:900913", "EPSG:3857", "EPSG:102113", "EPSG:102100"]; var add = OpenLayers.Projection.addTransform; var merc = OpenLayers.Layer.SphericalMercator; var same = OpenLayers.Projection.nullTransform; var i, len, code, other, j; for (i = 0, len = codes.length; i < len; ++i) { code = codes[i]; add("EPSG:4326", code, merc.projectForward); add(code, "EPSG:4326", merc.projectInverse); for (j = i + 1; j < len; ++j) { other = codes[j]; add(code, other, same); add(other, code, same); } } })(); OpenLayers.Layer.EventPane = OpenLayers.Class(OpenLayers.Layer, { smoothDragPan: true, isBaseLayer: true, isFixed: true, pane: null, mapObject: null, initialize: function (name, options) { OpenLayers.Layer.prototype.initialize.apply(this, arguments); if (this.pane == null) { this.pane = OpenLayers.Util.createDiv(this.div.id + "_EventPane"); } }, destroy: function () { this.mapObject = null; this.pane = null; OpenLayers.Layer.prototype.destroy.apply(this, arguments); }, setMap: function (map) {
    OpenLayers.Layer.prototype.setMap.apply(this, arguments); this.pane.style.zIndex = parseInt(this.div.style.zIndex) + 1; this.pane.style.display = this.div.style.display; this.pane.style.width = "100%"; this.pane.style.height = "100%"; if (OpenLayers.BROWSER_NAME == "msie") { this.pane.style.background = "url(" + OpenLayers.Util.getImagesLocation() + "blank.gif)"; }
    if (this.isFixed) { this.map.eventsDiv.appendChild(this.pane); } else { this.map.layerContainerDiv.appendChild(this.pane); }
    this.loadMapObject(); if (this.mapObject == null) { this.loadWarningMessage(); }
}, removeMap: function (map) {
    if (this.pane && this.pane.parentNode) { this.pane.parentNode.removeChild(this.pane); }
    OpenLayers.Layer.prototype.removeMap.apply(this, arguments);
}, loadWarningMessage: function () { this.div.style.backgroundColor = "darkblue"; var viewSize = this.map.getSize(); var msgW = Math.min(viewSize.w, 300); var msgH = Math.min(viewSize.h, 200); var size = new OpenLayers.Size(msgW, msgH); var centerPx = new OpenLayers.Pixel(viewSize.w / 2, viewSize.h / 2); var topLeft = centerPx.add(-size.w / 2, -size.h / 2); var div = OpenLayers.Util.createDiv(this.name + "_warning", topLeft, size, null, null, null, "auto"); div.style.padding = "7px"; div.style.backgroundColor = "yellow"; div.innerHTML = this.getWarningHTML(); this.div.appendChild(div); }, getWarningHTML: function () { return ""; }, display: function (display) { OpenLayers.Layer.prototype.display.apply(this, arguments); this.pane.style.display = this.div.style.display; }, setZIndex: function (zIndex) { OpenLayers.Layer.prototype.setZIndex.apply(this, arguments); this.pane.style.zIndex = parseInt(this.div.style.zIndex) + 1; }, moveByPx: function (dx, dy) { OpenLayers.Layer.prototype.moveByPx.apply(this, arguments); if (this.dragPanMapObject) { this.dragPanMapObject(dx, -dy); } else { this.moveTo(this.map.getCachedCenter()); } }, moveTo: function (bounds, zoomChanged, dragging) { OpenLayers.Layer.prototype.moveTo.apply(this, arguments); if (this.mapObject != null) { var newCenter = this.map.getCenter(); var newZoom = this.map.getZoom(); if (newCenter != null) { var moOldCenter = this.getMapObjectCenter(); var oldCenter = this.getOLLonLatFromMapObjectLonLat(moOldCenter); var moOldZoom = this.getMapObjectZoom(); var oldZoom = this.getOLZoomFromMapObjectZoom(moOldZoom); if (!(newCenter.equals(oldCenter)) || !(newZoom == oldZoom)) { if (!zoomChanged && oldCenter && this.dragPanMapObject && this.smoothDragPan) { var oldPx = this.map.getViewPortPxFromLonLat(oldCenter); var newPx = this.map.getViewPortPxFromLonLat(newCenter); this.dragPanMapObject(newPx.x - oldPx.x, oldPx.y - newPx.y); } else { var center = this.getMapObjectLonLatFromOLLonLat(newCenter); var zoom = this.getMapObjectZoomFromOLZoom(newZoom); this.setMapObjectCenter(center, zoom, dragging); } } } } }, getLonLatFromViewPortPx: function (viewPortPx) {
    var lonlat = null; if ((this.mapObject != null) && (this.getMapObjectCenter() != null)) { var moPixel = this.getMapObjectPixelFromOLPixel(viewPortPx); var moLonLat = this.getMapObjectLonLatFromMapObjectPixel(moPixel); lonlat = this.getOLLonLatFromMapObjectLonLat(moLonLat); }
    return lonlat;
}, getViewPortPxFromLonLat: function (lonlat) {
    var viewPortPx = null; if ((this.mapObject != null) && (this.getMapObjectCenter() != null)) { var moLonLat = this.getMapObjectLonLatFromOLLonLat(lonlat); var moPixel = this.getMapObjectPixelFromMapObjectLonLat(moLonLat); viewPortPx = this.getOLPixelFromMapObjectPixel(moPixel); }
    return viewPortPx;
}, getOLLonLatFromMapObjectLonLat: function (moLonLat) {
    var olLonLat = null; if (moLonLat != null) { var lon = this.getLongitudeFromMapObjectLonLat(moLonLat); var lat = this.getLatitudeFromMapObjectLonLat(moLonLat); olLonLat = new OpenLayers.LonLat(lon, lat); }
    return olLonLat;
}, getMapObjectLonLatFromOLLonLat: function (olLonLat) {
    var moLatLng = null; if (olLonLat != null) { moLatLng = this.getMapObjectLonLatFromLonLat(olLonLat.lon, olLonLat.lat); }
    return moLatLng;
}, getOLPixelFromMapObjectPixel: function (moPixel) {
    var olPixel = null; if (moPixel != null) { var x = this.getXFromMapObjectPixel(moPixel); var y = this.getYFromMapObjectPixel(moPixel); olPixel = new OpenLayers.Pixel(x, y); }
    return olPixel;
}, getMapObjectPixelFromOLPixel: function (olPixel) {
    var moPixel = null; if (olPixel != null) { moPixel = this.getMapObjectPixelFromXY(olPixel.x, olPixel.y); }
    return moPixel;
}, CLASS_NAME: "OpenLayers.Layer.EventPane"
}); OpenLayers.Layer.FixedZoomLevels = OpenLayers.Class({ initialize: function () { }, initResolutions: function () {
    var props = new Array('minZoomLevel', 'maxZoomLevel', 'numZoomLevels'); for (var i = 0, len = props.length; i < len; i++) { var property = props[i]; this[property] = (this.options[property] != null) ? this.options[property] : this.map[property]; }
    if ((this.minZoomLevel == null) || (this.minZoomLevel < this.MIN_ZOOM_LEVEL)) { this.minZoomLevel = this.MIN_ZOOM_LEVEL; }
    var desiredZoomLevels; var limitZoomLevels = this.MAX_ZOOM_LEVEL - this.minZoomLevel + 1; if (((this.options.numZoomLevels == null) && (this.options.maxZoomLevel != null)) || ((this.numZoomLevels == null) && (this.maxZoomLevel != null))) { desiredZoomLevels = this.maxZoomLevel - this.minZoomLevel + 1; } else { desiredZoomLevels = this.numZoomLevels; }
    if (desiredZoomLevels != null) { this.numZoomLevels = Math.min(desiredZoomLevels, limitZoomLevels); } else { this.numZoomLevels = limitZoomLevels; }
    this.maxZoomLevel = this.minZoomLevel + this.numZoomLevels - 1; if (this.RESOLUTIONS != null) {
        var resolutionsIndex = 0; this.resolutions = []; for (var i = this.minZoomLevel; i <= this.maxZoomLevel; i++) { this.resolutions[resolutionsIndex++] = this.RESOLUTIONS[i]; }
        this.maxResolution = this.resolutions[0]; this.minResolution = this.resolutions[this.resolutions.length - 1];
    }
}, getResolution: function () {
    if (this.resolutions != null) { return OpenLayers.Layer.prototype.getResolution.apply(this, arguments); } else {
        var resolution = null; var viewSize = this.map.getSize(); var extent = this.getExtent(); if ((viewSize != null) && (extent != null)) { resolution = Math.max(extent.getWidth() / viewSize.w, extent.getHeight() / viewSize.h); }
        return resolution;
    }
}, getExtent: function () {
    var extent = null; var size = this.map.getSize(); var tlPx = new OpenLayers.Pixel(0, 0); var tlLL = this.getLonLatFromViewPortPx(tlPx); var brPx = new OpenLayers.Pixel(size.w, size.h); var brLL = this.getLonLatFromViewPortPx(brPx); if ((tlLL != null) && (brLL != null)) { extent = new OpenLayers.Bounds(tlLL.lon, brLL.lat, brLL.lon, tlLL.lat); }
    return extent;
}, getZoomForResolution: function (resolution) { if (this.resolutions != null) { return OpenLayers.Layer.prototype.getZoomForResolution.apply(this, arguments); } else { var extent = OpenLayers.Layer.prototype.getExtent.apply(this, []); return this.getZoomForExtent(extent); } }, getOLZoomFromMapObjectZoom: function (moZoom) {
    var zoom = null; if (moZoom != null) { zoom = moZoom - this.minZoomLevel; if (this.map.baseLayer !== this) { zoom = this.map.baseLayer.getZoomForResolution(this.getResolutionForZoom(zoom)) } }
    return zoom;
}, getMapObjectZoomFromOLZoom: function (olZoom) {
    var zoom = null; if (olZoom != null) { zoom = olZoom + this.minZoomLevel; if (this.map.baseLayer !== this) { zoom = this.getZoomForResolution(this.map.baseLayer.getResolutionForZoom(zoom)); } }
    return zoom;
}, CLASS_NAME: "OpenLayers.Layer.FixedZoomLevels"
}); OpenLayers.Layer.VirtualEarth = OpenLayers.Class(OpenLayers.Layer.EventPane, OpenLayers.Layer.FixedZoomLevels, { MIN_ZOOM_LEVEL: 1, MAX_ZOOM_LEVEL: 19, RESOLUTIONS: [1.40625, 0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625, 0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625, 0.0006866455078125, 0.00034332275390625, 0.000171661376953125, 0.0000858306884765625, 0.00004291534423828125, 0.00002145767211914062, 0.00001072883605957031, 0.00000536441802978515], type: null, wrapDateLine: true, sphericalMercator: false, animationEnabled: true, initialize: function (name, options) { OpenLayers.Layer.EventPane.prototype.initialize.apply(this, arguments); OpenLayers.Layer.FixedZoomLevels.prototype.initialize.apply(this, arguments); if (this.sphericalMercator) { OpenLayers.Util.extend(this, OpenLayers.Layer.SphericalMercator); this.initMercatorParameters(); } }, loadMapObject: function () {
    var veDiv = OpenLayers.Util.createDiv(this.name); var sz = this.map.getSize(); veDiv.style.width = sz.w + "px"; veDiv.style.height = sz.h + "px"; this.div.appendChild(veDiv); try { this.mapObject = new VEMap(this.name); } catch (e) { }
    if (this.mapObject != null) {
        try { this.mapObject.LoadMap(null, null, this.type, true); this.mapObject.AttachEvent("onmousedown", OpenLayers.Function.True); } catch (e) { }
        this.mapObject.HideDashboard(); if (typeof this.mapObject.SetAnimationEnabled == "function") { this.mapObject.SetAnimationEnabled(this.animationEnabled); }
    }
    if (!this.mapObject || !this.mapObject.vemapcontrol || !this.mapObject.vemapcontrol.PanMap || (typeof this.mapObject.vemapcontrol.PanMap != "function")) { this.dragPanMapObject = null; }
}, onMapResize: function () { this.mapObject.Resize(this.map.size.w, this.map.size.h); }, getWarningHTML: function () { return OpenLayers.i18n("getLayerWarning", { 'layerType': 'VE', 'layerLib': 'VirtualEarth' }); }, setMapObjectCenter: function (center, zoom) { this.mapObject.SetCenterAndZoom(center, zoom); }, getMapObjectCenter: function () { return this.mapObject.GetCenter(); }, dragPanMapObject: function (dX, dY) { this.mapObject.vemapcontrol.PanMap(dX, -dY); }, getMapObjectZoom: function () { return this.mapObject.GetZoomLevel(); }, getMapObjectLonLatFromMapObjectPixel: function (moPixel) { return (typeof VEPixel != 'undefined') ? this.mapObject.PixelToLatLong(moPixel) : this.mapObject.PixelToLatLong(moPixel.x, moPixel.y); }, getMapObjectPixelFromMapObjectLonLat: function (moLonLat) { return this.mapObject.LatLongToPixel(moLonLat); }, getLongitudeFromMapObjectLonLat: function (moLonLat) { return this.sphericalMercator ? this.forwardMercator(moLonLat.Longitude, moLonLat.Latitude).lon : moLonLat.Longitude; }, getLatitudeFromMapObjectLonLat: function (moLonLat) { return this.sphericalMercator ? this.forwardMercator(moLonLat.Longitude, moLonLat.Latitude).lat : moLonLat.Latitude; }, getMapObjectLonLatFromLonLat: function (lon, lat) {
    var veLatLong; if (this.sphericalMercator) { var lonlat = this.inverseMercator(lon, lat); veLatLong = new VELatLong(lonlat.lat, lonlat.lon); } else { veLatLong = new VELatLong(lat, lon); }
    return veLatLong;
}, getXFromMapObjectPixel: function (moPixel) { return moPixel.x; }, getYFromMapObjectPixel: function (moPixel) { return moPixel.y; }, getMapObjectPixelFromXY: function (x, y) { return (typeof VEPixel != 'undefined') ? new VEPixel(x, y) : new Msn.VE.Pixel(x, y); }, CLASS_NAME: "OpenLayers.Layer.VirtualEarth"
}); OpenLayers.Control = OpenLayers.Class({ id: null, map: null, div: null, type: null, allowSelection: false, displayClass: "", title: "", autoActivate: false, active: null, handler: null, eventListeners: null, events: null, EVENT_TYPES: ["activate", "deactivate"], initialize: function (options) {
    this.displayClass = this.CLASS_NAME.replace("OpenLayers.", "ol").replace(/\./g, ""); OpenLayers.Util.extend(this, options); this.events = new OpenLayers.Events(this, null, this.EVENT_TYPES); if (this.eventListeners instanceof Object) { this.events.on(this.eventListeners); }
    if (this.id == null) { this.id = OpenLayers.Util.createUniqueID(this.CLASS_NAME + "_"); }
}, destroy: function () {
    if (this.events) {
        if (this.eventListeners) { this.events.un(this.eventListeners); }
        this.events.destroy(); this.events = null;
    }
    this.eventListeners = null; if (this.handler) { this.handler.destroy(); this.handler = null; }
    if (this.handlers) {
        for (var key in this.handlers) { if (this.handlers.hasOwnProperty(key) && typeof this.handlers[key].destroy == "function") { this.handlers[key].destroy(); } }
        this.handlers = null;
    }
    if (this.map) { this.map.removeControl(this); this.map = null; }
    this.div = null;
}, setMap: function (map) { this.map = map; if (this.handler) { this.handler.setMap(map); } }, draw: function (px) {
    if (this.div == null) {
        this.div = OpenLayers.Util.createDiv(this.id); this.div.className = this.displayClass; if (!this.allowSelection) { this.div.className += " olControlNoSelect"; this.div.setAttribute("unselectable", "on", 0); this.div.onselectstart = OpenLayers.Function.False; }
        if (this.title != "") { this.div.title = this.title; }
    }
    if (px != null) { this.position = px.clone(); }
    this.moveTo(this.position); return this.div;
}, moveTo: function (px) { if ((px != null) && (this.div != null)) { this.div.style.left = px.x + "px"; this.div.style.top = px.y + "px"; } }, activate: function () {
    if (this.active) { return false; }
    if (this.handler) { this.handler.activate(); }
    this.active = true; if (this.map) { OpenLayers.Element.addClass(this.map.viewPortDiv, this.displayClass.replace(/ /g, "") + "Active"); }
    this.events.triggerEvent("activate"); return true;
}, deactivate: function () {
    if (this.active) {
        if (this.handler) { this.handler.deactivate(); }
        this.active = false; if (this.map) { OpenLayers.Element.removeClass(this.map.viewPortDiv, this.displayClass.replace(/ /g, "") + "Active"); }
        this.events.triggerEvent("deactivate"); return true;
    }
    return false;
}, CLASS_NAME: "OpenLayers.Control"
}); OpenLayers.Control.TYPE_BUTTON = 1; OpenLayers.Control.TYPE_TOGGLE = 2; OpenLayers.Control.TYPE_TOOL = 3; OpenLayers.Control.OverviewMap = OpenLayers.Class(OpenLayers.Control, { element: null, ovmap: null, size: new OpenLayers.Size(180, 90), layers: null, minRectSize: 15, minRectDisplayClass: "RectReplacement", minRatio: 8, maxRatio: 32, mapOptions: null, autoPan: false, handlers: null, resolutionFactor: 1, maximized: false, initialize: function (options) { this.layers = []; this.handlers = {}; OpenLayers.Control.prototype.initialize.apply(this, [options]); }, destroy: function () {
    if (!this.mapDiv) { return; }
    if (this.handlers.click) { this.handlers.click.destroy(); }
    if (this.handlers.drag) { this.handlers.drag.destroy(); }
    this.ovmap && this.ovmap.eventsDiv.removeChild(this.extentRectangle); this.extentRectangle = null; if (this.rectEvents) { this.rectEvents.destroy(); this.rectEvents = null; }
    if (this.ovmap) { this.ovmap.destroy(); this.ovmap = null; }
    this.element.removeChild(this.mapDiv); this.mapDiv = null; this.div.removeChild(this.element); this.element = null; if (this.maximizeDiv) { OpenLayers.Event.stopObservingElement(this.maximizeDiv); this.div.removeChild(this.maximizeDiv); this.maximizeDiv = null; }
    if (this.minimizeDiv) { OpenLayers.Event.stopObservingElement(this.minimizeDiv); this.div.removeChild(this.minimizeDiv); this.minimizeDiv = null; }
    this.map.events.un({ "moveend": this.update, "changebaselayer": this.baseLayerDraw, scope: this }); OpenLayers.Control.prototype.destroy.apply(this, arguments);
}, draw: function () {
    OpenLayers.Control.prototype.draw.apply(this, arguments); if (!(this.layers.length > 0)) { if (this.map.baseLayer) { var layer = this.map.baseLayer.clone(); this.layers = [layer]; } else { this.map.events.register("changebaselayer", this, this.baseLayerDraw); return this.div; } }
    this.element = document.createElement('div'); this.element.className = this.displayClass + 'Element'; this.element.style.display = 'none'; this.mapDiv = document.createElement('div'); this.mapDiv.style.width = this.size.w + 'px'; this.mapDiv.style.height = this.size.h + 'px'; this.mapDiv.style.position = 'relative'; this.mapDiv.style.overflow = 'hidden'; this.mapDiv.id = OpenLayers.Util.createUniqueID('overviewMap'); this.extentRectangle = document.createElement('div'); this.extentRectangle.style.position = 'absolute'; this.extentRectangle.style.zIndex = 1000; this.extentRectangle.className = this.displayClass + 'ExtentRectangle'; this.element.appendChild(this.mapDiv); this.div.appendChild(this.element); if (!this.outsideViewport) {
        this.div.className += " " + this.displayClass + 'Container'; var imgLocation = OpenLayers.Util.getImagesLocation(); var img = imgLocation + 'layer-switcher-maximize.png'; this.maximizeDiv = OpenLayers.Util.createAlphaImageDiv(this.displayClass + 'MaximizeButton', null, new OpenLayers.Size(18, 18), img, 'absolute'); this.maximizeDiv.style.display = 'none'; this.maximizeDiv.className = this.displayClass + 'MaximizeButton'; OpenLayers.Event.observe(this.maximizeDiv, 'click', OpenLayers.Function.bindAsEventListener(this.maximizeControl, this)); this.div.appendChild(this.maximizeDiv); var img = imgLocation + 'layer-switcher-minimize.png'; this.minimizeDiv = OpenLayers.Util.createAlphaImageDiv('OpenLayers_Control_minimizeDiv', null, new OpenLayers.Size(18, 18), img, 'absolute'); this.minimizeDiv.style.display = 'none'; this.minimizeDiv.className = this.displayClass + 'MinimizeButton'; OpenLayers.Event.observe(this.minimizeDiv, 'click', OpenLayers.Function.bindAsEventListener(this.minimizeControl, this)); this.div.appendChild(this.minimizeDiv); var eventsToStop = ['dblclick', 'mousedown']; for (var i = 0, len = eventsToStop.length; i < len; i++) { OpenLayers.Event.observe(this.maximizeDiv, eventsToStop[i], OpenLayers.Event.stop); OpenLayers.Event.observe(this.minimizeDiv, eventsToStop[i], OpenLayers.Event.stop); }
        this.minimizeControl();
    } else { this.element.style.display = ''; }
    if (this.map.getExtent()) { this.update(); }
    this.map.events.register('moveend', this, this.update); if (this.maximized) { this.maximizeControl(); }
    return this.div;
}, baseLayerDraw: function () { this.draw(); this.map.events.unregister("changebaselayer", this, this.baseLayerDraw); }, rectDrag: function (px) { var deltaX = this.handlers.drag.last.x - px.x; var deltaY = this.handlers.drag.last.y - px.y; if (deltaX != 0 || deltaY != 0) { var rectTop = this.rectPxBounds.top; var rectLeft = this.rectPxBounds.left; var rectHeight = Math.abs(this.rectPxBounds.getHeight()); var rectWidth = this.rectPxBounds.getWidth(); var newTop = Math.max(0, (rectTop - deltaY)); newTop = Math.min(newTop, this.ovmap.size.h - this.hComp - rectHeight); var newLeft = Math.max(0, (rectLeft - deltaX)); newLeft = Math.min(newLeft, this.ovmap.size.w - this.wComp - rectWidth); this.setRectPxBounds(new OpenLayers.Bounds(newLeft, newTop + rectHeight, newLeft + rectWidth, newTop)); } }, mapDivClick: function (evt) { var pxCenter = this.rectPxBounds.getCenterPixel(); var deltaX = evt.xy.x - pxCenter.x; var deltaY = evt.xy.y - pxCenter.y; var top = this.rectPxBounds.top; var left = this.rectPxBounds.left; var height = Math.abs(this.rectPxBounds.getHeight()); var width = this.rectPxBounds.getWidth(); var newTop = Math.max(0, (top + deltaY)); newTop = Math.min(newTop, this.ovmap.size.h - height); var newLeft = Math.max(0, (left + deltaX)); newLeft = Math.min(newLeft, this.ovmap.size.w - width); this.setRectPxBounds(new OpenLayers.Bounds(newLeft, newTop + height, newLeft + width, newTop)); this.updateMapToRect(); }, maximizeControl: function (e) { this.element.style.display = ''; this.showToggle(false); if (e != null) { OpenLayers.Event.stop(e); } }, minimizeControl: function (e) { this.element.style.display = 'none'; this.showToggle(true); if (e != null) { OpenLayers.Event.stop(e); } }, showToggle: function (minimize) { this.maximizeDiv.style.display = minimize ? '' : 'none'; this.minimizeDiv.style.display = minimize ? 'none' : ''; }, update: function () {
    if (this.ovmap == null) { this.createMap(); }
    if (this.autoPan || !this.isSuitableOverview()) { this.updateOverview(); }
    this.updateRectToMap();
}, isSuitableOverview: function () {
    var mapExtent = this.map.getExtent(); var maxExtent = this.map.maxExtent; var testExtent = new OpenLayers.Bounds(Math.max(mapExtent.left, maxExtent.left), Math.max(mapExtent.bottom, maxExtent.bottom), Math.min(mapExtent.right, maxExtent.right), Math.min(mapExtent.top, maxExtent.top)); if (this.ovmap.getProjection() != this.map.getProjection()) { testExtent = testExtent.transform(this.map.getProjectionObject(), this.ovmap.getProjectionObject()); }
    var resRatio = this.ovmap.getResolution() / this.map.getResolution(); return ((resRatio > this.minRatio) && (resRatio <= this.maxRatio) && (this.ovmap.getExtent().containsBounds(testExtent)));
}, updateOverview: function () {
    var mapRes = this.map.getResolution(); var targetRes = this.ovmap.getResolution(); var resRatio = targetRes / mapRes; if (resRatio > this.maxRatio) { targetRes = this.minRatio * mapRes; } else if (resRatio <= this.minRatio) { targetRes = this.maxRatio * mapRes; }
    var center; if (this.ovmap.getProjection() != this.map.getProjection()) { center = this.map.center.clone(); center.transform(this.map.getProjectionObject(), this.ovmap.getProjectionObject()); } else { center = this.map.center; }
    this.ovmap.setCenter(center, this.ovmap.getZoomForResolution(targetRes * this.resolutionFactor)); this.updateRectToMap();
}, createMap: function () {
    var options = OpenLayers.Util.extend({ controls: [], maxResolution: 'auto', fallThrough: false }, this.mapOptions); this.ovmap = new OpenLayers.Map(this.mapDiv, options); this.ovmap.eventsDiv.appendChild(this.extentRectangle); OpenLayers.Event.stopObserving(window, 'unload', this.ovmap.unloadDestroy); this.ovmap.addLayers(this.layers); this.ovmap.zoomToMaxExtent(); this.wComp = parseInt(OpenLayers.Element.getStyle(this.extentRectangle, 'border-left-width')) +
parseInt(OpenLayers.Element.getStyle(this.extentRectangle, 'border-right-width')); this.wComp = (this.wComp) ? this.wComp : 2; this.hComp = parseInt(OpenLayers.Element.getStyle(this.extentRectangle, 'border-top-width')) +
parseInt(OpenLayers.Element.getStyle(this.extentRectangle, 'border-bottom-width')); this.hComp = (this.hComp) ? this.hComp : 2; this.handlers.drag = new OpenLayers.Handler.Drag(this, { move: this.rectDrag, done: this.updateMapToRect }, { map: this.ovmap }); this.handlers.click = new OpenLayers.Handler.Click(this, { "click": this.mapDivClick }, { "single": true, "double": false, "stopSingle": true, "stopDouble": true, "pixelTolerance": 1, map: this.ovmap }); this.handlers.click.activate(); this.rectEvents = new OpenLayers.Events(this, this.extentRectangle, null, true); this.rectEvents.register("mouseover", this, function (e) { if (!this.handlers.drag.active && !this.map.dragging) { this.handlers.drag.activate(); } }); this.rectEvents.register("mouseout", this, function (e) { if (!this.handlers.drag.dragging) { this.handlers.drag.deactivate(); } }); if (this.ovmap.getProjection() != this.map.getProjection()) { var sourceUnits = this.map.getProjectionObject().getUnits() || this.map.units || this.map.baseLayer.units; var targetUnits = this.ovmap.getProjectionObject().getUnits() || this.ovmap.units || this.ovmap.baseLayer.units; this.resolutionFactor = sourceUnits && targetUnits ? OpenLayers.INCHES_PER_UNIT[sourceUnits] / OpenLayers.INCHES_PER_UNIT[targetUnits] : 1; }
}, updateRectToMap: function () {
    var bounds; if (this.ovmap.getProjection() != this.map.getProjection()) { bounds = this.map.getExtent().transform(this.map.getProjectionObject(), this.ovmap.getProjectionObject()); } else { bounds = this.map.getExtent(); }
    var pxBounds = this.getRectBoundsFromMapBounds(bounds); if (pxBounds) { this.setRectPxBounds(pxBounds); }
}, updateMapToRect: function () {
    var lonLatBounds = this.getMapBoundsFromRectBounds(this.rectPxBounds); if (this.ovmap.getProjection() != this.map.getProjection()) { lonLatBounds = lonLatBounds.transform(this.ovmap.getProjectionObject(), this.map.getProjectionObject()); }
    this.map.panTo(lonLatBounds.getCenterLonLat());
}, setRectPxBounds: function (pxBounds) {
    var top = Math.max(pxBounds.top, 0); var left = Math.max(pxBounds.left, 0); var bottom = Math.min(pxBounds.top + Math.abs(pxBounds.getHeight()), this.ovmap.size.h - this.hComp); var right = Math.min(pxBounds.left + pxBounds.getWidth(), this.ovmap.size.w - this.wComp); var width = Math.max(right - left, 0); var height = Math.max(bottom - top, 0); if (width < this.minRectSize || height < this.minRectSize) {
        this.extentRectangle.className = this.displayClass +
this.minRectDisplayClass; var rLeft = left + (width / 2) - (this.minRectSize / 2); var rTop = top + (height / 2) - (this.minRectSize / 2); this.extentRectangle.style.top = Math.round(rTop) + 'px'; this.extentRectangle.style.left = Math.round(rLeft) + 'px'; this.extentRectangle.style.height = this.minRectSize + 'px'; this.extentRectangle.style.width = this.minRectSize + 'px';
    } else { this.extentRectangle.className = this.displayClass + 'ExtentRectangle'; this.extentRectangle.style.top = Math.round(top) + 'px'; this.extentRectangle.style.left = Math.round(left) + 'px'; this.extentRectangle.style.height = Math.round(height) + 'px'; this.extentRectangle.style.width = Math.round(width) + 'px'; }
    this.rectPxBounds = new OpenLayers.Bounds(Math.round(left), Math.round(bottom), Math.round(right), Math.round(top));
}, getRectBoundsFromMapBounds: function (lonLatBounds) {
    var leftBottomLonLat = new OpenLayers.LonLat(lonLatBounds.left, lonLatBounds.bottom); var rightTopLonLat = new OpenLayers.LonLat(lonLatBounds.right, lonLatBounds.top); var leftBottomPx = this.getOverviewPxFromLonLat(leftBottomLonLat); var rightTopPx = this.getOverviewPxFromLonLat(rightTopLonLat); var bounds = null; if (leftBottomPx && rightTopPx) { bounds = new OpenLayers.Bounds(leftBottomPx.x, leftBottomPx.y, rightTopPx.x, rightTopPx.y); }
    return bounds;
}, getMapBoundsFromRectBounds: function (pxBounds) { var leftBottomPx = new OpenLayers.Pixel(pxBounds.left, pxBounds.bottom); var rightTopPx = new OpenLayers.Pixel(pxBounds.right, pxBounds.top); var leftBottomLonLat = this.getLonLatFromOverviewPx(leftBottomPx); var rightTopLonLat = this.getLonLatFromOverviewPx(rightTopPx); return new OpenLayers.Bounds(leftBottomLonLat.lon, leftBottomLonLat.lat, rightTopLonLat.lon, rightTopLonLat.lat); }, getLonLatFromOverviewPx: function (overviewMapPx) { var size = this.ovmap.size; var res = this.ovmap.getResolution(); var center = this.ovmap.getExtent().getCenterLonLat(); var delta_x = overviewMapPx.x - (size.w / 2); var delta_y = overviewMapPx.y - (size.h / 2); return new OpenLayers.LonLat(center.lon + delta_x * res, center.lat - delta_y * res); }, getOverviewPxFromLonLat: function (lonlat) {
    var res = this.ovmap.getResolution(); var extent = this.ovmap.getExtent(); var px = null; if (extent) { px = new OpenLayers.Pixel(Math.round(1 / res * (lonlat.lon - extent.left)), Math.round(1 / res * (extent.top - lonlat.lat))); }
    return px;
}, CLASS_NAME: 'OpenLayers.Control.OverviewMap'
}); OpenLayers.Layer.Google = OpenLayers.Class(OpenLayers.Layer.EventPane, OpenLayers.Layer.FixedZoomLevels, { MIN_ZOOM_LEVEL: 0, MAX_ZOOM_LEVEL: 21, RESOLUTIONS: [1.40625, 0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625, 0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625, 0.0006866455078125, 0.00034332275390625, 0.000171661376953125, 0.0000858306884765625, 0.00004291534423828125, 0.00002145767211914062, 0.00001072883605957031, 0.00000536441802978515, 0.00000268220901489257, 0.0000013411045074462891, 0.00000067055225372314453], type: null, wrapDateLine: true, sphericalMercator: false, version: null, initialize: function (name, options) {
    options = options || {}; if (!options.version) { options.version = typeof GMap2 === "function" ? "2" : "3"; }
    var mixin = OpenLayers.Layer.Google["v" +
options.version.replace(/\./g, "_")]; if (mixin) { OpenLayers.Util.applyDefaults(options, mixin); } else { throw "Unsupported Google Maps API version: " + options.version; }
    OpenLayers.Util.applyDefaults(options, mixin.DEFAULTS); if (options.maxExtent) { options.maxExtent = options.maxExtent.clone(); }
    OpenLayers.Layer.EventPane.prototype.initialize.apply(this, [name, options]); OpenLayers.Layer.FixedZoomLevels.prototype.initialize.apply(this, [name, options]); if (this.sphericalMercator) { OpenLayers.Util.extend(this, OpenLayers.Layer.SphericalMercator); this.initMercatorParameters(); }
}, clone: function () { return new OpenLayers.Layer.Google(this.name, this.getOptions()); }, setVisibility: function (visible) { var opacity = this.opacity == null ? 1 : this.opacity; OpenLayers.Layer.EventPane.prototype.setVisibility.apply(this, arguments); this.setOpacity(opacity); }, display: function (visible) {
    if (!this._dragging) { this.setGMapVisibility(visible); }
    OpenLayers.Layer.EventPane.prototype.display.apply(this, arguments);
}, moveTo: function (bounds, zoomChanged, dragging) { this._dragging = dragging; OpenLayers.Layer.EventPane.prototype.moveTo.apply(this, arguments); delete this._dragging; }, setOpacity: function (opacity) {
    if (opacity !== this.opacity) {
        if (this.map != null) { this.map.events.triggerEvent("changelayer", { layer: this, property: "opacity" }); }
        this.opacity = opacity;
    }
    if (this.getVisibility()) { var container = this.getMapContainer(); OpenLayers.Util.modifyDOMElement(container, null, null, null, null, null, null, opacity); }
}, destroy: function () {
    if (this.map) { this.setGMapVisibility(false); var cache = OpenLayers.Layer.Google.cache[this.map.id]; if (cache && cache.count <= 1) { this.removeGMapElements(); } }
    OpenLayers.Layer.EventPane.prototype.destroy.apply(this, arguments);
}, removeGMapElements: function () {
    var cache = OpenLayers.Layer.Google.cache[this.map.id]; if (cache) {
        var container = this.mapObject && this.getMapContainer(); if (container && container.parentNode) { container.parentNode.removeChild(container); }
        var termsOfUse = cache.termsOfUse; if (termsOfUse && termsOfUse.parentNode) { termsOfUse.parentNode.removeChild(termsOfUse); }
        var poweredBy = cache.poweredBy; if (poweredBy && poweredBy.parentNode) { poweredBy.parentNode.removeChild(poweredBy); }
    }
}, removeMap: function (map) {
    if (this.visibility && this.mapObject) { this.setGMapVisibility(false); }
    var cache = OpenLayers.Layer.Google.cache[map.id]; if (cache) { if (cache.count <= 1) { this.removeGMapElements(); delete OpenLayers.Layer.Google.cache[map.id]; } else { --cache.count; } }
    delete this.termsOfUse; delete this.poweredBy; delete this.mapObject; delete this.dragObject; OpenLayers.Layer.EventPane.prototype.removeMap.apply(this, arguments);
}, getOLBoundsFromMapObjectBounds: function (moBounds) {
    var olBounds = null; if (moBounds != null) {
        var sw = moBounds.getSouthWest(); var ne = moBounds.getNorthEast(); if (this.sphericalMercator) { sw = this.forwardMercator(sw.lng(), sw.lat()); ne = this.forwardMercator(ne.lng(), ne.lat()); } else { sw = new OpenLayers.LonLat(sw.lng(), sw.lat()); ne = new OpenLayers.LonLat(ne.lng(), ne.lat()); }
        olBounds = new OpenLayers.Bounds(sw.lon, sw.lat, ne.lon, ne.lat);
    }
    return olBounds;
}, getWarningHTML: function () { return OpenLayers.i18n("googleWarning"); }, getMapObjectCenter: function () { return this.mapObject.getCenter(); }, getMapObjectZoom: function () { return this.mapObject.getZoom(); }, getLongitudeFromMapObjectLonLat: function (moLonLat) { return this.sphericalMercator ? this.forwardMercator(moLonLat.lng(), moLonLat.lat()).lon : moLonLat.lng(); }, getLatitudeFromMapObjectLonLat: function (moLonLat) { var lat = this.sphericalMercator ? this.forwardMercator(moLonLat.lng(), moLonLat.lat()).lat : moLonLat.lat(); return lat; }, getXFromMapObjectPixel: function (moPixel) { return moPixel.x; }, getYFromMapObjectPixel: function (moPixel) { return moPixel.y; }, CLASS_NAME: "OpenLayers.Layer.Google"
}); OpenLayers.Layer.Google.cache = {}; OpenLayers.Layer.Google.v2 = { termsOfUse: null, poweredBy: null, dragObject: null, loadMapObject: function () {
    if (!this.type) { this.type = G_NORMAL_MAP; }
    var mapObject, termsOfUse, poweredBy; var cache = OpenLayers.Layer.Google.cache[this.map.id]; if (cache) { mapObject = cache.mapObject; termsOfUse = cache.termsOfUse; poweredBy = cache.poweredBy; ++cache.count; } else {
        var container = this.map.viewPortDiv; var div = document.createElement("div"); div.id = this.map.id + "_GMap2Container"; div.style.position = "absolute"; div.style.width = "100%"; div.style.height = "100%"; container.appendChild(div); try { mapObject = new GMap2(div); termsOfUse = div.lastChild; container.appendChild(termsOfUse); termsOfUse.style.zIndex = "1100"; termsOfUse.style.right = ""; termsOfUse.style.bottom = ""; termsOfUse.className = "olLayerGoogleCopyright"; poweredBy = div.lastChild; container.appendChild(poweredBy); poweredBy.style.zIndex = "1100"; poweredBy.style.right = ""; poweredBy.style.bottom = ""; poweredBy.className = "olLayerGooglePoweredBy gmnoprint"; } catch (e) { throw (e); }
        OpenLayers.Layer.Google.cache[this.map.id] = { mapObject: mapObject, termsOfUse: termsOfUse, poweredBy: poweredBy, count: 1 };
    }
    this.mapObject = mapObject; this.termsOfUse = termsOfUse; this.poweredBy = poweredBy; if (OpenLayers.Util.indexOf(this.mapObject.getMapTypes(), this.type) === -1) { this.mapObject.addMapType(this.type); }
    if (typeof mapObject.getDragObject == "function") { this.dragObject = mapObject.getDragObject(); } else { this.dragPanMapObject = null; }
    if (this.isBaseLayer === false) { this.setGMapVisibility(this.div.style.display !== "none"); }
}, onMapResize: function () {
    if (this.visibility && this.mapObject.isLoaded()) { this.mapObject.checkResize(); } else {
        if (!this._resized) { var layer = this; var handle = GEvent.addListener(this.mapObject, "load", function () { GEvent.removeListener(handle); delete layer._resized; layer.mapObject.checkResize(); layer.moveTo(layer.map.getCenter(), layer.map.getZoom()); }); }
        this._resized = true;
    }
}, setGMapVisibility: function (visible) {
    var cache = OpenLayers.Layer.Google.cache[this.map.id]; if (cache) {
        var container = this.mapObject.getContainer(); if (visible === true) { this.mapObject.setMapType(this.type); container.style.display = ""; this.termsOfUse.style.left = ""; this.termsOfUse.style.display = ""; this.poweredBy.style.display = ""; cache.displayed = this.id; } else {
            if (cache.displayed === this.id) { delete cache.displayed; }
            if (!cache.displayed) { container.style.display = "none"; this.termsOfUse.style.display = "none"; this.termsOfUse.style.left = "-9999px"; this.poweredBy.style.display = "none"; }
        }
    }
}, getMapContainer: function () { return this.mapObject.getContainer(); }, getMapObjectBoundsFromOLBounds: function (olBounds) {
    var moBounds = null; if (olBounds != null) { var sw = this.sphericalMercator ? this.inverseMercator(olBounds.bottom, olBounds.left) : new OpenLayers.LonLat(olBounds.bottom, olBounds.left); var ne = this.sphericalMercator ? this.inverseMercator(olBounds.top, olBounds.right) : new OpenLayers.LonLat(olBounds.top, olBounds.right); moBounds = new GLatLngBounds(new GLatLng(sw.lat, sw.lon), new GLatLng(ne.lat, ne.lon)); }
    return moBounds;
}, setMapObjectCenter: function (center, zoom) { this.mapObject.setCenter(center, zoom); }, dragPanMapObject: function (dX, dY) { this.dragObject.moveBy(new GSize(-dX, dY)); }, getMapObjectLonLatFromMapObjectPixel: function (moPixel) { return this.mapObject.fromContainerPixelToLatLng(moPixel); }, getMapObjectPixelFromMapObjectLonLat: function (moLonLat) { return this.mapObject.fromLatLngToContainerPixel(moLonLat); }, getMapObjectZoomFromMapObjectBounds: function (moBounds) { return this.mapObject.getBoundsZoomLevel(moBounds); }, getMapObjectLonLatFromLonLat: function (lon, lat) {
    var gLatLng; if (this.sphericalMercator) { var lonlat = this.inverseMercator(lon, lat); gLatLng = new GLatLng(lonlat.lat, lonlat.lon); } else { gLatLng = new GLatLng(lat, lon); }
    return gLatLng;
}, getMapObjectPixelFromXY: function (x, y) { return new GPoint(x, y); }
}; OpenLayers.Format.XML = OpenLayers.Class(OpenLayers.Format, { namespaces: null, namespaceAlias: null, defaultPrefix: null, readers: {}, writers: {}, xmldom: null, initialize: function (options) {
    if (window.ActiveXObject) { this.xmldom = new ActiveXObject("Microsoft.XMLDOM"); }
    OpenLayers.Format.prototype.initialize.apply(this, [options]); this.namespaces = OpenLayers.Util.extend({}, this.namespaces); this.namespaceAlias = {}; for (var alias in this.namespaces) { this.namespaceAlias[this.namespaces[alias]] = alias; }
}, destroy: function () { this.xmldom = null; OpenLayers.Format.prototype.destroy.apply(this, arguments); }, setNamespace: function (alias, uri) { this.namespaces[alias] = uri; this.namespaceAlias[uri] = alias; }, read: function (text) {
    var index = text.indexOf('<'); if (index > 0) { text = text.substring(index); }
    var node = OpenLayers.Util.Try(OpenLayers.Function.bind((function () {
        var xmldom; if (window.ActiveXObject && !this.xmldom) { xmldom = new ActiveXObject("Microsoft.XMLDOM"); } else { xmldom = this.xmldom; }
        xmldom.loadXML(text); return xmldom;
    }), this), function () { return new DOMParser().parseFromString(text, 'text/xml'); }, function () {
        var req = new XMLHttpRequest(); req.open("GET", "data:" + "text/xml" + ";charset=utf-8," + encodeURIComponent(text), false); if (req.overrideMimeType) { req.overrideMimeType("text/xml"); }
        req.send(null); return req.responseXML;
    }); if (this.keepData) { this.data = node; }
    return node;
}, write: function (node) {
    var data; if (this.xmldom) { data = node.xml; } else {
        var serializer = new XMLSerializer(); if (node.nodeType == 1) {
            var doc = document.implementation.createDocument("", "", null); if (doc.importNode) { node = doc.importNode(node, true); }
            doc.appendChild(node); data = serializer.serializeToString(doc);
        } else { data = serializer.serializeToString(node); }
    }
    return data;
}, createElementNS: function (uri, name) {
    var element; if (this.xmldom) { if (typeof uri == "string") { element = this.xmldom.createNode(1, name, uri); } else { element = this.xmldom.createNode(1, name, ""); } } else { element = document.createElementNS(uri, name); }
    return element;
}, createTextNode: function (text) {
    var node; if (typeof text !== "string") { text = String(text); }
    if (this.xmldom) { node = this.xmldom.createTextNode(text); } else { node = document.createTextNode(text); }
    return node;
}, getElementsByTagNameNS: function (node, uri, name) {
    var elements = []; if (node.getElementsByTagNameNS) { elements = node.getElementsByTagNameNS(uri, name); } else { var allNodes = node.getElementsByTagName("*"); var potentialNode, fullName; for (var i = 0, len = allNodes.length; i < len; ++i) { potentialNode = allNodes[i]; fullName = (potentialNode.prefix) ? (potentialNode.prefix + ":" + name) : name; if ((name == "*") || (fullName == potentialNode.nodeName)) { if ((uri == "*") || (uri == potentialNode.namespaceURI)) { elements.push(potentialNode); } } } }
    return elements;
}, getAttributeNodeNS: function (node, uri, name) {
    var attributeNode = null; if (node.getAttributeNodeNS) { attributeNode = node.getAttributeNodeNS(uri, name); } else { var attributes = node.attributes; var potentialNode, fullName; for (var i = 0, len = attributes.length; i < len; ++i) { potentialNode = attributes[i]; if (potentialNode.namespaceURI == uri) { fullName = (potentialNode.prefix) ? (potentialNode.prefix + ":" + name) : name; if (fullName == potentialNode.nodeName) { attributeNode = potentialNode; break; } } } }
    return attributeNode;
}, getAttributeNS: function (node, uri, name) {
    var attributeValue = ""; if (node.getAttributeNS) { attributeValue = node.getAttributeNS(uri, name) || ""; } else { var attributeNode = this.getAttributeNodeNS(node, uri, name); if (attributeNode) { attributeValue = attributeNode.nodeValue; } }
    return attributeValue;
}, getChildValue: function (node, def) {
    var value = def || ""; if (node) { for (var child = node.firstChild; child; child = child.nextSibling) { switch (child.nodeType) { case 3: case 4: value += child.nodeValue; } } }
    return value;
}, concatChildValues: function (node, def) {
    var value = ""; var child = node.firstChild; var childValue; while (child) {
        childValue = child.nodeValue; if (childValue) { value += childValue; }
        child = child.nextSibling;
    }
    if (value == "" && def != undefined) { value = def; }
    return value;
}, isSimpleContent: function (node) {
    var simple = true; for (var child = node.firstChild; child; child = child.nextSibling) { if (child.nodeType === 1) { simple = false; break; } }
    return simple;
}, contentType: function (node) {
    var simple = false, complex = false; var type = OpenLayers.Format.XML.CONTENT_TYPE.EMPTY; for (var child = node.firstChild; child; child = child.nextSibling) {
        switch (child.nodeType) { case 1: complex = true; break; case 8: break; default: simple = true; }
        if (complex && simple) { break; }
    }
    if (complex && simple) { type = OpenLayers.Format.XML.CONTENT_TYPE.MIXED; } else if (complex) { return OpenLayers.Format.XML.CONTENT_TYPE.COMPLEX; } else if (simple) { return OpenLayers.Format.XML.CONTENT_TYPE.SIMPLE; }
    return type;
}, hasAttributeNS: function (node, uri, name) {
    var found = false; if (node.hasAttributeNS) { found = node.hasAttributeNS(uri, name); } else { found = !!this.getAttributeNodeNS(node, uri, name); }
    return found;
}, setAttributeNS: function (node, uri, name, value) { if (node.setAttributeNS) { node.setAttributeNS(uri, name, value); } else { if (this.xmldom) { if (uri) { var attribute = node.ownerDocument.createNode(2, name, uri); attribute.nodeValue = value; node.setAttributeNode(attribute); } else { node.setAttribute(name, value); } } else { throw "setAttributeNS not implemented"; } } }, createElementNSPlus: function (name, options) {
    options = options || {}; var uri = options.uri || this.namespaces[options.prefix]; if (!uri) { var loc = name.indexOf(":"); uri = this.namespaces[name.substring(0, loc)]; }
    if (!uri) { uri = this.namespaces[this.defaultPrefix]; }
    var node = this.createElementNS(uri, name); if (options.attributes) { this.setAttributes(node, options.attributes); }
    var value = options.value; if (value != null) { node.appendChild(this.createTextNode(value)); }
    return node;
}, setAttributes: function (node, obj) { var value, uri; for (var name in obj) { if (obj[name] != null && obj[name].toString) { value = obj[name].toString(); uri = this.namespaces[name.substring(0, name.indexOf(":"))] || null; this.setAttributeNS(node, uri, name, value); } } }, readNode: function (node, obj) {
    if (!obj) { obj = {}; }
    var group = this.readers[node.namespaceURI ? this.namespaceAlias[node.namespaceURI] : this.defaultPrefix]; if (group) { var local = node.localName || node.nodeName.split(":").pop(); var reader = group[local] || group["*"]; if (reader) { reader.apply(this, [node, obj]); } }
    return obj;
}, readChildNodes: function (node, obj) {
    if (!obj) { obj = {}; }
    var children = node.childNodes; var child; for (var i = 0, len = children.length; i < len; ++i) { child = children[i]; if (child.nodeType == 1) { this.readNode(child, obj); } }
    return obj;
}, writeNode: function (name, obj, parent) {
    var prefix, local; var split = name.indexOf(":"); if (split > 0) { prefix = name.substring(0, split); local = name.substring(split + 1); } else {
        if (parent) { prefix = this.namespaceAlias[parent.namespaceURI]; } else { prefix = this.defaultPrefix; }
        local = name;
    }
    var child = this.writers[prefix][local].apply(this, [obj]); if (parent) { parent.appendChild(child); }
    return child;
}, getChildEl: function (node, name, uri) { return node && this.getThisOrNextEl(node.firstChild, name, uri); }, getNextEl: function (node, name, uri) { return node && this.getThisOrNextEl(node.nextSibling, name, uri); }, getThisOrNextEl: function (node, name, uri) {
    outer: for (var sibling = node; sibling; sibling = sibling.nextSibling) {
        switch (sibling.nodeType) {
            case 1: if ((!name || name === (sibling.localName || sibling.nodeName.split(":").pop())) && (!uri || uri === sibling.namespaceURI)) { break outer; }
                sibling = null; break outer; case 3: if (/^\s*$/.test(sibling.nodeValue)) { break; }
            case 4: case 6: case 12: case 10: case 11: sibling = null; break outer;
        }
    }
    return sibling || null;
}, lookupNamespaceURI: function (node, prefix) {
    var uri = null; if (node) {
        if (node.lookupNamespaceURI) { uri = node.lookupNamespaceURI(prefix); } else {
            outer: switch (node.nodeType) {
                case 1: if (node.namespaceURI !== null && node.prefix === prefix) { uri = node.namespaceURI; break outer; }
                    var len = node.attributes.length; if (len) { var attr; for (var i = 0; i < len; ++i) { attr = node.attributes[i]; if (attr.prefix === "xmlns" && attr.name === "xmlns:" + prefix) { uri = attr.value || null; break outer; } else if (attr.name === "xmlns" && prefix === null) { uri = attr.value || null; break outer; } } }
                    uri = this.lookupNamespaceURI(node.parentNode, prefix); break outer; case 2: uri = this.lookupNamespaceURI(node.ownerElement, prefix); break outer; case 9: uri = this.lookupNamespaceURI(node.documentElement, prefix); break outer; case 6: case 12: case 10: case 11: break outer; default: uri = this.lookupNamespaceURI(node.parentNode, prefix); break outer;
            }
        }
    }
    return uri;
}, getXMLDoc: function () {
    if (!OpenLayers.Format.XML.document && !this.xmldom) { if (document.implementation && document.implementation.createDocument) { OpenLayers.Format.XML.document = document.implementation.createDocument("", "", null); } else if (!this.xmldom && window.ActiveXObject) { this.xmldom = new ActiveXObject("Microsoft.XMLDOM"); } }
    return OpenLayers.Format.XML.document || this.xmldom;
}, CLASS_NAME: "OpenLayers.Format.XML"
}); OpenLayers.Format.XML.CONTENT_TYPE = { EMPTY: 0, SIMPLE: 1, COMPLEX: 2, MIXED: 3 }; OpenLayers.Format.XML.lookupNamespaceURI = OpenLayers.Function.bind(OpenLayers.Format.XML.prototype.lookupNamespaceURI, OpenLayers.Format.XML.prototype); OpenLayers.Format.XML.document = null; OpenLayers.Format.WFST = function (options) {
    options = OpenLayers.Util.applyDefaults(options, OpenLayers.Format.WFST.DEFAULTS); var cls = OpenLayers.Format.WFST["v" + options.version.replace(/\./g, "_")]; if (!cls) { throw "Unsupported WFST version: " + options.version; }
    return new cls(options);
}; OpenLayers.Format.WFST.DEFAULTS = { "version": "1.0.0" }; OpenLayers.Format.WFST.v1 = OpenLayers.Class(OpenLayers.Format.XML, { namespaces: { xlink: "http://www.w3.org/1999/xlink", xsi: "http://www.w3.org/2001/XMLSchema-instance", wfs: "http://www.opengis.net/wfs", gml: "http://www.opengis.net/gml", ogc: "http://www.opengis.net/ogc", ows: "http://www.opengis.net/ows" }, defaultPrefix: "wfs", version: null, schemaLocations: null, srsName: null, extractAttributes: true, xy: true, stateName: null, initialize: function (options) { this.stateName = {}; this.stateName[OpenLayers.State.INSERT] = "wfs:Insert"; this.stateName[OpenLayers.State.UPDATE] = "wfs:Update"; this.stateName[OpenLayers.State.DELETE] = "wfs:Delete"; OpenLayers.Format.XML.prototype.initialize.apply(this, [options]); }, getSrsName: function (feature, options) {
    var srsName = options && options.srsName; if (!srsName) { if (feature && feature.layer) { srsName = feature.layer.projection.getCode(); } else { srsName = this.srsName; } }
    return srsName;
}, read: function (data, options) {
    options = options || {}; OpenLayers.Util.applyDefaults(options, { output: "features" }); if (typeof data == "string") { data = OpenLayers.Format.XML.prototype.read.apply(this, [data]); }
    if (data && data.nodeType == 9) { data = data.documentElement; }
    var obj = {}; if (data) { this.readNode(data, obj, true); }
    if (obj.features && options.output === "features") { obj = obj.features; }
    return obj;
}, readers: { "wfs": { "FeatureCollection": function (node, obj) { obj.features = []; this.readChildNodes(node, obj); } } }, write: function (features, options) {
    var node = this.writeNode("wfs:Transaction", { features: features, options: options }); var value = this.schemaLocationAttr(); if (value) { this.setAttributeNS(node, this.namespaces["xsi"], "xsi:schemaLocation", value); }
    return OpenLayers.Format.XML.prototype.write.apply(this, [node]);
}, writers: { "wfs": { "GetFeature": function (options) {
    var node = this.createElementNSPlus("wfs:GetFeature", { attributes: { service: "WFS", version: this.version, handle: options && options.handle, outputFormat: options && options.outputFormat, maxFeatures: options && options.maxFeatures, "xsi:schemaLocation": this.schemaLocationAttr(options)} }); if (typeof this.featureType == "string") { this.writeNode("Query", options, node); } else { for (var i = 0, len = this.featureType.length; i < len; i++) { options.featureType = this.featureType[i]; this.writeNode("Query", options, node); } }
    return node;
}, "Transaction": function (obj) {
    obj = obj || {}; var options = obj.options || {}; var node = this.createElementNSPlus("wfs:Transaction", { attributes: { service: "WFS", version: this.version, handle: options.handle} }); var i, len; var features = obj.features; if (features) {
        if (options.multi === true) { OpenLayers.Util.extend(this.geometryTypes, { "OpenLayers.Geometry.Point": "MultiPoint", "OpenLayers.Geometry.LineString": (this.multiCurve === true) ? "MultiCurve" : "MultiLineString", "OpenLayers.Geometry.Polygon": (this.multiSurface === true) ? "MultiSurface" : "MultiPolygon" }); }
        var name, feature; for (i = 0, len = features.length; i < len; ++i) { feature = features[i]; name = this.stateName[feature.state]; if (name) { this.writeNode(name, { feature: feature, options: options }, node); } }
        if (options.multi === true) { this.setGeometryTypes(); }
    }
    if (options.nativeElements) { for (i = 0, len = options.nativeElements.length; i < len; ++i) { this.writeNode("wfs:Native", options.nativeElements[i], node); } }
    return node;
}, "Native": function (nativeElement) { var node = this.createElementNSPlus("wfs:Native", { attributes: { vendorId: nativeElement.vendorId, safeToIgnore: nativeElement.safeToIgnore }, value: nativeElement.value }); return node; }, "Insert": function (obj) { var feature = obj.feature; var options = obj.options; var node = this.createElementNSPlus("wfs:Insert", { attributes: { handle: options && options.handle} }); this.srsName = this.getSrsName(feature); this.writeNode("feature:_typeName", feature, node); return node; }, "Update": function (obj) {
    var feature = obj.feature; var options = obj.options; var node = this.createElementNSPlus("wfs:Update", { attributes: { handle: options && options.handle, typeName: (this.featureNS ? this.featurePrefix + ":" : "") +
this.featureType
    }
    }); if (this.featureNS) { node.setAttribute("xmlns:" + this.featurePrefix, this.featureNS); }
    var modified = feature.modified; if (this.geometryName !== null && (!modified || modified.geometry !== undefined)) { this.srsName = this.getSrsName(feature); this.writeNode("Property", { name: this.geometryName, value: feature.geometry }, node); }
    for (var key in feature.attributes) { if (feature.attributes[key] !== undefined && (!modified || !modified.attributes || (modified.attributes && modified.attributes[key] !== undefined))) { this.writeNode("Property", { name: key, value: feature.attributes[key] }, node); } }
    this.writeNode("ogc:Filter", new OpenLayers.Filter.FeatureId({ fids: [feature.fid] }), node); return node;
}, "Property": function (obj) {
    var node = this.createElementNSPlus("wfs:Property"); this.writeNode("Name", obj.name, node); if (obj.value !== null) { this.writeNode("Value", obj.value, node); }
    return node;
}, "Name": function (name) { return this.createElementNSPlus("wfs:Name", { value: name }); }, "Value": function (obj) {
    var node; if (obj instanceof OpenLayers.Geometry) { node = this.createElementNSPlus("wfs:Value"); var geom = this.writeNode("feature:_geometry", obj).firstChild; node.appendChild(geom); } else { node = this.createElementNSPlus("wfs:Value", { value: obj }); }
    return node;
}, "Delete": function (obj) {
    var feature = obj.feature; var options = obj.options; var node = this.createElementNSPlus("wfs:Delete", { attributes: { handle: options && options.handle, typeName: (this.featureNS ? this.featurePrefix + ":" : "") +
this.featureType
    }
    }); if (this.featureNS) { node.setAttribute("xmlns:" + this.featurePrefix, this.featureNS); }
    this.writeNode("ogc:Filter", new OpenLayers.Filter.FeatureId({ fids: [feature.fid] }), node); return node;
}
}
}, schemaLocationAttr: function (options) {
    options = OpenLayers.Util.extend({ featurePrefix: this.featurePrefix, schema: this.schema }, options); var schemaLocations = OpenLayers.Util.extend({}, this.schemaLocations); if (options.schema) { schemaLocations[options.featurePrefix] = options.schema; }
    var parts = []; var uri; for (var key in schemaLocations) { uri = this.namespaces[key]; if (uri) { parts.push(uri + " " + schemaLocations[key]); } }
    var value = parts.join(" ") || undefined; return value;
}, setFilterProperty: function (filter) { if (filter.filters) { for (var i = 0, len = filter.filters.length; i < len; ++i) { this.setFilterProperty(filter.filters[i]); } } else { if (filter instanceof OpenLayers.Filter.Spatial) { filter.property = this.geometryName; } } }, CLASS_NAME: "OpenLayers.Format.WFST.v1"
}); OpenLayers.Format.OGCExceptionReport = OpenLayers.Class(OpenLayers.Format.XML, { namespaces: { ogc: "http://www.opengis.net/ogc" }, regExes: { trimSpace: (/^\s*|\s*$/g), removeSpace: (/\s*/g), splitSpace: (/\s+/), trimComma: (/\s*,\s*/g) }, defaultPrefix: "ogc", read: function (data) {
    var result; if (typeof data == "string") { data = OpenLayers.Format.XML.prototype.read.apply(this, [data]); }
    var root = data.documentElement; var exceptionInfo = { exceptionReport: null }; if (root) { this.readChildNodes(data, exceptionInfo); if (exceptionInfo.exceptionReport === null) { exceptionInfo = new OpenLayers.Format.OWSCommon().read(data); } }
    return exceptionInfo;
}, readers: { "ogc": { "ServiceExceptionReport": function (node, obj) { obj.exceptionReport = { exceptions: [] }; this.readChildNodes(node, obj.exceptionReport); }, "ServiceException": function (node, exceptionReport) { var exception = { code: node.getAttribute("code"), locator: node.getAttribute("locator"), text: this.getChildValue(node) }; exceptionReport.exceptions.push(exception); } } }, CLASS_NAME: "OpenLayers.Format.OGCExceptionReport"
}); OpenLayers.Format.XML.VersionedOGC = OpenLayers.Class(OpenLayers.Format.XML, { defaultVersion: null, version: null, profile: null, errorProperty: null, name: null, stringifyOutput: false, parser: null, initialize: function (options) { OpenLayers.Format.XML.prototype.initialize.apply(this, [options]); var className = this.CLASS_NAME; this.name = className.substring(className.lastIndexOf(".") + 1); }, getVersion: function (root, options) {
    var version; if (root) { version = this.version; if (!version) { version = root.getAttribute("version"); if (!version) { version = this.defaultVersion; } } } else { version = (options && options.version) || this.version || this.defaultVersion; }
    return version;
}, getParser: function (version) {
    version = version || this.defaultVersion; var profile = this.profile ? "_" + this.profile : ""; if (!this.parser || this.parser.VERSION != version) {
        var format = OpenLayers.Format[this.name]["v" + version.replace(/\./g, "_") + profile]; if (!format) {
            throw "Can't find a " + this.name + " parser for version " +
version + profile;
        }
        this.parser = new format(this.options);
    }
    return this.parser;
}, write: function (obj, options) { var version = this.getVersion(null, options); this.parser = this.getParser(version); var root = this.parser.write(obj, options); if (this.stringifyOutput === false) { return root; } else { return OpenLayers.Format.XML.prototype.write.apply(this, [root]); } }, read: function (data, options) {
    if (typeof data == "string") { data = OpenLayers.Format.XML.prototype.read.apply(this, [data]); }
    var root = data.documentElement; var version = this.getVersion(root); this.parser = this.getParser(version); var obj = this.parser.read(data, options); if (this.errorProperty !== null && obj[this.errorProperty] === undefined) { var format = new OpenLayers.Format.OGCExceptionReport(); obj.error = format.read(data); }
    obj.version = version; return obj;
}, CLASS_NAME: "OpenLayers.Format.XML.VersionedOGC"
}); OpenLayers.Style = OpenLayers.Class({ id: null, name: null, title: null, description: null, layerName: null, isDefault: false, rules: null, context: null, defaultStyle: null, defaultsPerSymbolizer: false, propertyStyles: null, initialize: function (style, options) {
    OpenLayers.Util.extend(this, options); this.rules = []; if (options && options.rules) { this.addRules(options.rules); }
    this.setDefaultStyle(style || OpenLayers.Feature.Vector.style["default"]); this.id = OpenLayers.Util.createUniqueID(this.CLASS_NAME + "_");
}, destroy: function () {
    for (var i = 0, len = this.rules.length; i < len; i++) { this.rules[i].destroy(); this.rules[i] = null; }
    this.rules = null; this.defaultStyle = null;
}, createSymbolizer: function (feature) {
    var style = this.defaultsPerSymbolizer ? {} : this.createLiterals(OpenLayers.Util.extend({}, this.defaultStyle), feature); var rules = this.rules; var rule, context; var elseRules = []; var appliedRules = false; for (var i = 0, len = rules.length; i < len; i++) { rule = rules[i]; var applies = rule.evaluate(feature); if (applies) { if (rule instanceof OpenLayers.Rule && rule.elseFilter) { elseRules.push(rule); } else { appliedRules = true; this.applySymbolizer(rule, style, feature); } } }
    if (appliedRules == false && elseRules.length > 0) { appliedRules = true; for (var i = 0, len = elseRules.length; i < len; i++) { this.applySymbolizer(elseRules[i], style, feature); } }
    if (rules.length > 0 && appliedRules == false) { style.display = "none"; }
    if (style.label && typeof style.label !== "string") { style.label = String(style.label); }
    return style;
}, applySymbolizer: function (rule, style, feature) {
    var symbolizerPrefix = feature.geometry ? this.getSymbolizerPrefix(feature.geometry) : OpenLayers.Style.SYMBOLIZER_PREFIXES[0]; var symbolizer = rule.symbolizer[symbolizerPrefix] || rule.symbolizer; if (this.defaultsPerSymbolizer === true) {
        var defaults = this.defaultStyle; OpenLayers.Util.applyDefaults(symbolizer, { pointRadius: defaults.pointRadius }); if (symbolizer.stroke === true || symbolizer.graphic === true) { OpenLayers.Util.applyDefaults(symbolizer, { strokeWidth: defaults.strokeWidth, strokeColor: defaults.strokeColor, strokeOpacity: defaults.strokeOpacity, strokeDashstyle: defaults.strokeDashstyle, strokeLinecap: defaults.strokeLinecap }); }
        if (symbolizer.fill === true || symbolizer.graphic === true) { OpenLayers.Util.applyDefaults(symbolizer, { fillColor: defaults.fillColor, fillOpacity: defaults.fillOpacity }); }
        if (symbolizer.graphic === true) { OpenLayers.Util.applyDefaults(symbolizer, { pointRadius: this.defaultStyle.pointRadius, externalGraphic: this.defaultStyle.externalGraphic, graphicName: this.defaultStyle.graphicName, graphicOpacity: this.defaultStyle.graphicOpacity, graphicWidth: this.defaultStyle.graphicWidth, graphicHeight: this.defaultStyle.graphicHeight, graphicXOffset: this.defaultStyle.graphicXOffset, graphicYOffset: this.defaultStyle.graphicYOffset }); }
    }
    return this.createLiterals(OpenLayers.Util.extend(style, symbolizer), feature);
}, createLiterals: function (style, feature) {
    var context = OpenLayers.Util.extend({}, feature.attributes || feature.data); OpenLayers.Util.extend(context, this.context); for (var i in this.propertyStyles) { style[i] = OpenLayers.Style.createLiteral(style[i], context, feature, i); }
    return style;
}, findPropertyStyles: function () {
    var propertyStyles = {}; var style = this.defaultStyle; this.addPropertyStyles(propertyStyles, style); var rules = this.rules; var symbolizer, value; for (var i = 0, len = rules.length; i < len; i++) { symbolizer = rules[i].symbolizer; for (var key in symbolizer) { value = symbolizer[key]; if (typeof value == "object") { this.addPropertyStyles(propertyStyles, value); } else { this.addPropertyStyles(propertyStyles, symbolizer); break; } } }
    return propertyStyles;
}, addPropertyStyles: function (propertyStyles, symbolizer) {
    var property; for (var key in symbolizer) { property = symbolizer[key]; if (typeof property == "string" && property.match(/\$\{\w+\}/)) { propertyStyles[key] = true; } }
    return propertyStyles;
}, addRules: function (rules) { Array.prototype.push.apply(this.rules, rules); this.propertyStyles = this.findPropertyStyles(); }, setDefaultStyle: function (style) { this.defaultStyle = style; this.propertyStyles = this.findPropertyStyles(); }, getSymbolizerPrefix: function (geometry) { var prefixes = OpenLayers.Style.SYMBOLIZER_PREFIXES; for (var i = 0, len = prefixes.length; i < len; i++) { if (geometry.CLASS_NAME.indexOf(prefixes[i]) != -1) { return prefixes[i]; } } }, clone: function () {
    var options = OpenLayers.Util.extend({}, this); if (this.rules) { options.rules = []; for (var i = 0, len = this.rules.length; i < len; ++i) { options.rules.push(this.rules[i].clone()); } }
    options.context = this.context && OpenLayers.Util.extend({}, this.context); var defaultStyle = OpenLayers.Util.extend({}, this.defaultStyle); return new OpenLayers.Style(defaultStyle, options);
}, CLASS_NAME: "OpenLayers.Style"
}); OpenLayers.Style.createLiteral = function (value, context, feature, property) {
    if (typeof value == "string" && value.indexOf("${") != -1) { value = OpenLayers.String.format(value, context, [feature, property]); value = (isNaN(value) || !value) ? value : parseFloat(value); }
    return value;
}; OpenLayers.Style.SYMBOLIZER_PREFIXES = ['Point', 'Line', 'Polygon', 'Text', 'Raster']; OpenLayers.Filter = OpenLayers.Class({ initialize: function (options) { OpenLayers.Util.extend(this, options); }, destroy: function () { }, evaluate: function (context) { return true; }, clone: function () { return null; }, CLASS_NAME: "OpenLayers.Filter" }); OpenLayers.Filter.FeatureId = OpenLayers.Class(OpenLayers.Filter, { fids: null, type: "FID", initialize: function (options) { this.fids = []; OpenLayers.Filter.prototype.initialize.apply(this, [options]); }, evaluate: function (feature) {
    for (var i = 0, len = this.fids.length; i < len; i++) { var fid = feature.fid || feature.id; if (fid == this.fids[i]) { return true; } }
    return false;
}, clone: function () { var filter = new OpenLayers.Filter.FeatureId(); OpenLayers.Util.extend(filter, this); filter.fids = this.fids.slice(); return filter; }, CLASS_NAME: "OpenLayers.Filter.FeatureId"
}); OpenLayers.Filter.Logical = OpenLayers.Class(OpenLayers.Filter, { filters: null, type: null, initialize: function (options) { this.filters = []; OpenLayers.Filter.prototype.initialize.apply(this, [options]); }, destroy: function () { this.filters = null; OpenLayers.Filter.prototype.destroy.apply(this); }, evaluate: function (context) {
    var i, len; switch (this.type) {
        case OpenLayers.Filter.Logical.AND: for (i = 0, len = this.filters.length; i < len; i++) { if (this.filters[i].evaluate(context) == false) { return false; } }
            return true; case OpenLayers.Filter.Logical.OR: for (i = 0, len = this.filters.length; i < len; i++) { if (this.filters[i].evaluate(context) == true) { return true; } }
            return false; case OpenLayers.Filter.Logical.NOT: return (!this.filters[0].evaluate(context));
    }
    return undefined;
}, clone: function () {
    var filters = []; for (var i = 0, len = this.filters.length; i < len; ++i) { filters.push(this.filters[i].clone()); }
    return new OpenLayers.Filter.Logical({ type: this.type, filters: filters });
}, CLASS_NAME: "OpenLayers.Filter.Logical"
}); OpenLayers.Filter.Logical.AND = "&&"; OpenLayers.Filter.Logical.OR = "||"; OpenLayers.Filter.Logical.NOT = "!"; OpenLayers.Filter.Comparison = OpenLayers.Class(OpenLayers.Filter, { type: null, property: null, value: null, matchCase: true, lowerBoundary: null, upperBoundary: null, initialize: function (options) { OpenLayers.Filter.prototype.initialize.apply(this, [options]); if (this.type === OpenLayers.Filter.Comparison.LIKE && options.matchCase === undefined) { this.matchCase = null; } }, evaluate: function (context) {
    if (context instanceof OpenLayers.Feature.Vector) { context = context.attributes; }
    var result = false; var got = context[this.property]; var exp; switch (this.type) {
        case OpenLayers.Filter.Comparison.EQUAL_TO: exp = this.value; if (!this.matchCase && typeof got == "string" && typeof exp == "string") { result = (got.toUpperCase() == exp.toUpperCase()); } else { result = (got == exp); }
            break; case OpenLayers.Filter.Comparison.NOT_EQUAL_TO: exp = this.value; if (!this.matchCase && typeof got == "string" && typeof exp == "string") { result = (got.toUpperCase() != exp.toUpperCase()); } else { result = (got != exp); }
            break; case OpenLayers.Filter.Comparison.LESS_THAN: result = got < this.value; break; case OpenLayers.Filter.Comparison.GREATER_THAN: result = got > this.value; break; case OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO: result = got <= this.value; break; case OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO: result = got >= this.value; break; case OpenLayers.Filter.Comparison.BETWEEN: result = (got >= this.lowerBoundary) && (got <= this.upperBoundary); break; case OpenLayers.Filter.Comparison.LIKE: var regexp = new RegExp(this.value, "gi"); result = regexp.test(got); break;
    }
    return result;
}, value2regex: function (wildCard, singleChar, escapeChar) {
    if (wildCard == ".") { var msg = "'.' is an unsupported wildCard character for " + "OpenLayers.Filter.Comparison"; OpenLayers.Console.error(msg); return null; }
    wildCard = wildCard ? wildCard : "*"; singleChar = singleChar ? singleChar : "."; escapeChar = escapeChar ? escapeChar : "!"; this.value = this.value.replace(new RegExp("\\" + escapeChar + "(.|$)", "g"), "\\$1"); this.value = this.value.replace(new RegExp("\\" + singleChar, "g"), "."); this.value = this.value.replace(new RegExp("\\" + wildCard, "g"), ".*"); this.value = this.value.replace(new RegExp("\\\\.\\*", "g"), "\\" + wildCard); this.value = this.value.replace(new RegExp("\\\\\\.", "g"), "\\" + singleChar); return this.value;
}, regex2value: function () { var value = this.value; value = value.replace(/!/g, "!!"); value = value.replace(/(\\)?\\\./g, function ($0, $1) { return $1 ? $0 : "!."; }); value = value.replace(/(\\)?\\\*/g, function ($0, $1) { return $1 ? $0 : "!*"; }); value = value.replace(/\\\\/g, "\\"); value = value.replace(/\.\*/g, "*"); return value; }, clone: function () { return OpenLayers.Util.extend(new OpenLayers.Filter.Comparison(), this); }, CLASS_NAME: "OpenLayers.Filter.Comparison"
}); OpenLayers.Filter.Comparison.EQUAL_TO = "=="; OpenLayers.Filter.Comparison.NOT_EQUAL_TO = "!="; OpenLayers.Filter.Comparison.LESS_THAN = "<"; OpenLayers.Filter.Comparison.GREATER_THAN = ">"; OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO = "<="; OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO = ">="; OpenLayers.Filter.Comparison.BETWEEN = ".."; OpenLayers.Filter.Comparison.LIKE = "~"; OpenLayers.Format.Filter = OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC, { defaultVersion: "1.0.0", CLASS_NAME: "OpenLayers.Format.Filter" }); OpenLayers.Filter.Function = OpenLayers.Class(OpenLayers.Filter, { name: null, params: null, initialize: function (options) { OpenLayers.Filter.prototype.initialize.apply(this, [options]); }, CLASS_NAME: "OpenLayers.Filter.Function" }); OpenLayers.Format.Filter.v1 = OpenLayers.Class(OpenLayers.Format.XML, { namespaces: { ogc: "http://www.opengis.net/ogc", gml: "http://www.opengis.net/gml", xlink: "http://www.w3.org/1999/xlink", xsi: "http://www.w3.org/2001/XMLSchema-instance" }, defaultPrefix: "ogc", schemaLocation: null, initialize: function (options) { OpenLayers.Format.XML.prototype.initialize.apply(this, [options]); }, read: function (data) { var obj = {}; this.readers.ogc["Filter"].apply(this, [data, obj]); return obj.filter; }, readers: { "ogc": { "Filter": function (node, parent) { var obj = { fids: [], filters: [] }; this.readChildNodes(node, obj); if (obj.fids.length > 0) { parent.filter = new OpenLayers.Filter.FeatureId({ fids: obj.fids }); } else if (obj.filters.length > 0) { parent.filter = obj.filters[0]; } }, "FeatureId": function (node, obj) { var fid = node.getAttribute("fid"); if (fid) { obj.fids.push(fid); } }, "And": function (node, obj) { var filter = new OpenLayers.Filter.Logical({ type: OpenLayers.Filter.Logical.AND }); this.readChildNodes(node, filter); obj.filters.push(filter); }, "Or": function (node, obj) { var filter = new OpenLayers.Filter.Logical({ type: OpenLayers.Filter.Logical.OR }); this.readChildNodes(node, filter); obj.filters.push(filter); }, "Not": function (node, obj) { var filter = new OpenLayers.Filter.Logical({ type: OpenLayers.Filter.Logical.NOT }); this.readChildNodes(node, filter); obj.filters.push(filter); }, "PropertyIsLessThan": function (node, obj) { var filter = new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.LESS_THAN }); this.readChildNodes(node, filter); obj.filters.push(filter); }, "PropertyIsGreaterThan": function (node, obj) { var filter = new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.GREATER_THAN }); this.readChildNodes(node, filter); obj.filters.push(filter); }, "PropertyIsLessThanOrEqualTo": function (node, obj) { var filter = new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO }); this.readChildNodes(node, filter); obj.filters.push(filter); }, "PropertyIsGreaterThanOrEqualTo": function (node, obj) { var filter = new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO }); this.readChildNodes(node, filter); obj.filters.push(filter); }, "PropertyIsBetween": function (node, obj) { var filter = new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.BETWEEN }); this.readChildNodes(node, filter); obj.filters.push(filter); }, "Literal": function (node, obj) { obj.value = OpenLayers.String.numericIf(this.getChildValue(node)); }, "PropertyName": function (node, filter) { filter.property = this.getChildValue(node); }, "LowerBoundary": function (node, filter) { filter.lowerBoundary = OpenLayers.String.numericIf(this.readOgcExpression(node)); }, "UpperBoundary": function (node, filter) { filter.upperBoundary = OpenLayers.String.numericIf(this.readOgcExpression(node)); }, "Intersects": function (node, obj) { this.readSpatial(node, obj, OpenLayers.Filter.Spatial.INTERSECTS); }, "Within": function (node, obj) { this.readSpatial(node, obj, OpenLayers.Filter.Spatial.WITHIN); }, "Contains": function (node, obj) { this.readSpatial(node, obj, OpenLayers.Filter.Spatial.CONTAINS); }, "DWithin": function (node, obj) { this.readSpatial(node, obj, OpenLayers.Filter.Spatial.DWITHIN); }, "Distance": function (node, obj) { obj.distance = parseInt(this.getChildValue(node)); obj.distanceUnits = node.getAttribute("units"); }, "Function": function (node, obj) { return; } } }, readSpatial: function (node, obj, type) { var filter = new OpenLayers.Filter.Spatial({ type: type }); this.readChildNodes(node, filter); filter.value = filter.components[0]; delete filter.components; obj.filters.push(filter); }, readOgcExpression: function (node) {
    var obj = {}; this.readChildNodes(node, obj); var value = obj.value; if (value === undefined) { value = this.getChildValue(node); }
    return value;
}, writeOgcExpression: function (value, node) {
    if (value instanceof OpenLayers.Filter.Function) { var child = this.writeNode("Function", value, node); node.appendChild(child); } else { this.writeNode("Literal", value, node); }
    return node;
}, write: function (filter) { return this.writers.ogc["Filter"].apply(this, [filter]); }, writeFeatureIdNodes: function (filter, node) { for (var i = 0, ii = filter.fids.length; i < ii; ++i) { this.writeNode("FeatureId", filter.fids[i], node); } }, writers: { "ogc": { "Filter": function (filter) {
    var node = this.createElementNSPlus("ogc:Filter"); if (filter.type === "FID") { this.writeFeatureIdNodes(filter, node); } else { this.writeNode(this.getFilterType(filter), filter, node); }
    return node;
}, "FeatureId": function (fid) { return this.createElementNSPlus("ogc:FeatureId", { attributes: { fid: fid} }); }, "And": function (filter) {
    var node = this.createElementNSPlus("ogc:And"); var childFilter; for (var i = 0, ii = filter.filters.length; i < ii; ++i) { childFilter = filter.filters[i]; if (childFilter.type === "FID") { this.writeFeatureIdNodes(childFilter, node); } else { this.writeNode(this.getFilterType(childFilter), childFilter, node); } }
    return node;
}, "Or": function (filter) {
    var node = this.createElementNSPlus("ogc:Or"); var childFilter; for (var i = 0, ii = filter.filters.length; i < ii; ++i) { childFilter = filter.filters[i]; if (childFilter.type === "FID") { this.writeFeatureIdNodes(childFilter, node); } else { this.writeNode(this.getFilterType(childFilter), childFilter, node); } }
    return node;
}, "Not": function (filter) {
    var node = this.createElementNSPlus("ogc:Not"); var childFilter = filter.filters[0]; if (childFilter.type === "FID") { this.writeFeatureIdNodes(childFilter, node); } else { this.writeNode(this.getFilterType(childFilter), childFilter, node); }
    return node;
}, "PropertyIsLessThan": function (filter) { var node = this.createElementNSPlus("ogc:PropertyIsLessThan"); this.writeNode("PropertyName", filter, node); this.writeOgcExpression(filter.value, node); return node; }, "PropertyIsGreaterThan": function (filter) { var node = this.createElementNSPlus("ogc:PropertyIsGreaterThan"); this.writeNode("PropertyName", filter, node); this.writeOgcExpression(filter.value, node); return node; }, "PropertyIsLessThanOrEqualTo": function (filter) { var node = this.createElementNSPlus("ogc:PropertyIsLessThanOrEqualTo"); this.writeNode("PropertyName", filter, node); this.writeOgcExpression(filter.value, node); return node; }, "PropertyIsGreaterThanOrEqualTo": function (filter) { var node = this.createElementNSPlus("ogc:PropertyIsGreaterThanOrEqualTo"); this.writeNode("PropertyName", filter, node); this.writeOgcExpression(filter.value, node); return node; }, "PropertyIsBetween": function (filter) { var node = this.createElementNSPlus("ogc:PropertyIsBetween"); this.writeNode("PropertyName", filter, node); this.writeNode("LowerBoundary", filter, node); this.writeNode("UpperBoundary", filter, node); return node; }, "PropertyName": function (filter) { return this.createElementNSPlus("ogc:PropertyName", { value: filter.property }); }, "Literal": function (value) { return this.createElementNSPlus("ogc:Literal", { value: value }); }, "LowerBoundary": function (filter) { var node = this.createElementNSPlus("ogc:LowerBoundary"); this.writeOgcExpression(filter.lowerBoundary, node); return node; }, "UpperBoundary": function (filter) { var node = this.createElementNSPlus("ogc:UpperBoundary"); this.writeNode("Literal", filter.upperBoundary, node); return node; }, "INTERSECTS": function (filter) { return this.writeSpatial(filter, "Intersects"); }, "WITHIN": function (filter) { return this.writeSpatial(filter, "Within"); }, "CONTAINS": function (filter) { return this.writeSpatial(filter, "Contains"); }, "DWITHIN": function (filter) { var node = this.writeSpatial(filter, "DWithin"); this.writeNode("Distance", filter, node); return node; }, "Distance": function (filter) { return this.createElementNSPlus("ogc:Distance", { attributes: { units: filter.distanceUnits }, value: filter.distance }); }, "Function": function (filter) {
    var node = this.createElementNSPlus("ogc:Function", { attributes: { name: filter.name} }); var params = filter.params; for (var i = 0, len = params.length; i < len; i++) { this.writeOgcExpression(params[i], node); }
    return node;
}
}
}, getFilterType: function (filter) {
    var filterType = this.filterMap[filter.type]; if (!filterType) { throw "Filter writing not supported for rule type: " + filter.type; }
    return filterType;
}, filterMap: { "&&": "And", "||": "Or", "!": "Not", "==": "PropertyIsEqualTo", "!=": "PropertyIsNotEqualTo", "<": "PropertyIsLessThan", ">": "PropertyIsGreaterThan", "<=": "PropertyIsLessThanOrEqualTo", ">=": "PropertyIsGreaterThanOrEqualTo", "..": "PropertyIsBetween", "~": "PropertyIsLike", "BBOX": "BBOX", "DWITHIN": "DWITHIN", "WITHIN": "WITHIN", "CONTAINS": "CONTAINS", "INTERSECTS": "INTERSECTS", "FID": "FeatureId" }, CLASS_NAME: "OpenLayers.Format.Filter.v1"
}); OpenLayers.Geometry = OpenLayers.Class({ id: null, parent: null, bounds: null, initialize: function () { this.id = OpenLayers.Util.createUniqueID(this.CLASS_NAME + "_"); }, destroy: function () { this.id = null; this.bounds = null; }, clone: function () { return new OpenLayers.Geometry(); }, setBounds: function (bounds) { if (bounds) { this.bounds = bounds.clone(); } }, clearBounds: function () { this.bounds = null; if (this.parent) { this.parent.clearBounds(); } }, extendBounds: function (newBounds) { var bounds = this.getBounds(); if (!bounds) { this.setBounds(newBounds); } else { this.bounds.extend(newBounds); } }, getBounds: function () {
    if (this.bounds == null) { this.calculateBounds(); }
    return this.bounds;
}, calculateBounds: function () { }, distanceTo: function (geometry, options) { }, getVertices: function (nodes) { }, atPoint: function (lonlat, toleranceLon, toleranceLat) {
    var atPoint = false; var bounds = this.getBounds(); if ((bounds != null) && (lonlat != null)) { var dX = (toleranceLon != null) ? toleranceLon : 0; var dY = (toleranceLat != null) ? toleranceLat : 0; var toleranceBounds = new OpenLayers.Bounds(this.bounds.left - dX, this.bounds.bottom - dY, this.bounds.right + dX, this.bounds.top + dY); atPoint = toleranceBounds.containsLonLat(lonlat); }
    return atPoint;
}, getLength: function () { return 0.0; }, getArea: function () { return 0.0; }, getCentroid: function () { return null; }, toString: function () { return OpenLayers.Format.WKT.prototype.write(new OpenLayers.Feature.Vector(this)); }, CLASS_NAME: "OpenLayers.Geometry"
}); OpenLayers.Geometry.fromWKT = function (wkt) {
    var format = arguments.callee.format; if (!format) { format = new OpenLayers.Format.WKT(); arguments.callee.format = format; }
    var geom; var result = format.read(wkt); if (result instanceof OpenLayers.Feature.Vector) { geom = result.geometry; } else if (OpenLayers.Util.isArray(result)) {
        var len = result.length; var components = new Array(len); for (var i = 0; i < len; ++i) { components[i] = result[i].geometry; }
        geom = new OpenLayers.Geometry.Collection(components);
    }
    return geom;
}; OpenLayers.Geometry.segmentsIntersect = function (seg1, seg2, options) {
    var point = options && options.point; var tolerance = options && options.tolerance; var intersection = false; var x11_21 = seg1.x1 - seg2.x1; var y11_21 = seg1.y1 - seg2.y1; var x12_11 = seg1.x2 - seg1.x1; var y12_11 = seg1.y2 - seg1.y1; var y22_21 = seg2.y2 - seg2.y1; var x22_21 = seg2.x2 - seg2.x1; var d = (y22_21 * x12_11) - (x22_21 * y12_11); var n1 = (x22_21 * y11_21) - (y22_21 * x11_21); var n2 = (x12_11 * y11_21) - (y12_11 * x11_21); if (d == 0) { if (n1 == 0 && n2 == 0) { intersection = true; } } else { var along1 = n1 / d; var along2 = n2 / d; if (along1 >= 0 && along1 <= 1 && along2 >= 0 && along2 <= 1) { if (!point) { intersection = true; } else { var x = seg1.x1 + (along1 * x12_11); var y = seg1.y1 + (along1 * y12_11); intersection = new OpenLayers.Geometry.Point(x, y); } } }
    if (tolerance) {
        var dist; if (intersection) {
            if (point) {
                var segs = [seg1, seg2]; var seg, x, y; outer: for (var i = 0; i < 2; ++i) {
                    seg = segs[i]; for (var j = 1; j < 3; ++j) {
                        x = seg["x" + j]; y = seg["y" + j]; dist = Math.sqrt(Math.pow(x - intersection.x, 2) +
Math.pow(y - intersection.y, 2)); if (dist < tolerance) { intersection.x = x; intersection.y = y; break outer; }
                    }
                }
            }
        } else {
            var segs = [seg1, seg2]; var source, target, x, y, p, result; outer: for (var i = 0; i < 2; ++i) {
                source = segs[i]; target = segs[(i + 1) % 2]; for (var j = 1; j < 3; ++j) {
                    p = { x: source["x" + j], y: source["y" + j] }; result = OpenLayers.Geometry.distanceToSegment(p, target); if (result.distance < tolerance) {
                        if (point) { intersection = new OpenLayers.Geometry.Point(p.x, p.y); } else { intersection = true; }
                        break outer;
                    }
                }
            }
        }
    }
    return intersection;
}; OpenLayers.Geometry.distanceToSegment = function (point, segment) {
    var x0 = point.x; var y0 = point.y; var x1 = segment.x1; var y1 = segment.y1; var x2 = segment.x2; var y2 = segment.y2; var dx = x2 - x1; var dy = y2 - y1; var along = ((dx * (x0 - x1)) + (dy * (y0 - y1))) / (Math.pow(dx, 2) + Math.pow(dy, 2)); var x, y; if (along <= 0.0) { x = x1; y = y1; } else if (along >= 1.0) { x = x2; y = y2; } else { x = x1 + along * dx; y = y1 + along * dy; }
    return { distance: Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2)), x: x, y: y };
}; OpenLayers.Geometry.Point = OpenLayers.Class(OpenLayers.Geometry, { x: null, y: null, initialize: function (x, y) { OpenLayers.Geometry.prototype.initialize.apply(this, arguments); this.x = parseFloat(x); this.y = parseFloat(y); }, clone: function (obj) {
    if (obj == null) { obj = new OpenLayers.Geometry.Point(this.x, this.y); }
    OpenLayers.Util.applyDefaults(obj, this); return obj;
}, calculateBounds: function () { this.bounds = new OpenLayers.Bounds(this.x, this.y, this.x, this.y); }, distanceTo: function (geometry, options) {
    var edge = !(options && options.edge === false); var details = edge && options && options.details; var distance, x0, y0, x1, y1, result; if (geometry instanceof OpenLayers.Geometry.Point) { x0 = this.x; y0 = this.y; x1 = geometry.x; y1 = geometry.y; distance = Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2)); result = !details ? distance : { x0: x0, y0: y0, x1: x1, y1: y1, distance: distance }; } else { result = geometry.distanceTo(this, options); if (details) { result = { x0: result.x1, y0: result.y1, x1: result.x0, y1: result.y0, distance: result.distance }; } }
    return result;
}, equals: function (geom) {
    var equals = false; if (geom != null) { equals = ((this.x == geom.x && this.y == geom.y) || (isNaN(this.x) && isNaN(this.y) && isNaN(geom.x) && isNaN(geom.y))); }
    return equals;
}, toShortString: function () { return (this.x + ", " + this.y); }, move: function (x, y) { this.x = this.x + x; this.y = this.y + y; this.clearBounds(); }, rotate: function (angle, origin) { angle *= Math.PI / 180; var radius = this.distanceTo(origin); var theta = angle + Math.atan2(this.y - origin.y, this.x - origin.x); this.x = origin.x + (radius * Math.cos(theta)); this.y = origin.y + (radius * Math.sin(theta)); this.clearBounds(); }, getCentroid: function () { return new OpenLayers.Geometry.Point(this.x, this.y); }, resize: function (scale, origin, ratio) { ratio = (ratio == undefined) ? 1 : ratio; this.x = origin.x + (scale * ratio * (this.x - origin.x)); this.y = origin.y + (scale * (this.y - origin.y)); this.clearBounds(); return this; }, intersects: function (geometry) {
    var intersect = false; if (geometry.CLASS_NAME == "OpenLayers.Geometry.Point") { intersect = this.equals(geometry); } else { intersect = geometry.intersects(this); }
    return intersect;
}, transform: function (source, dest) {
    if ((source && dest)) { OpenLayers.Projection.transform(this, source, dest); this.bounds = null; }
    return this;
}, getVertices: function (nodes) { return [this]; }, CLASS_NAME: "OpenLayers.Geometry.Point"
}); OpenLayers.Geometry.Collection = OpenLayers.Class(OpenLayers.Geometry, { components: null, componentTypes: null, initialize: function (components) { OpenLayers.Geometry.prototype.initialize.apply(this, arguments); this.components = []; if (components != null) { this.addComponents(components); } }, destroy: function () { this.components.length = 0; this.components = null; OpenLayers.Geometry.prototype.destroy.apply(this, arguments); }, clone: function () {
    var geometry = eval("new " + this.CLASS_NAME + "()"); for (var i = 0, len = this.components.length; i < len; i++) { geometry.addComponent(this.components[i].clone()); }
    OpenLayers.Util.applyDefaults(geometry, this); return geometry;
}, getComponentsString: function () {
    var strings = []; for (var i = 0, len = this.components.length; i < len; i++) { strings.push(this.components[i].toShortString()); }
    return strings.join(",");
}, calculateBounds: function () {
    this.bounds = null; var bounds = new OpenLayers.Bounds(); var components = this.components; if (components) { for (var i = 0, len = components.length; i < len; i++) { bounds.extend(components[i].getBounds()); } }
    if (bounds.left != null && bounds.bottom != null && bounds.right != null && bounds.top != null) { this.setBounds(bounds); }
}, addComponents: function (components) {
    if (!(OpenLayers.Util.isArray(components))) { components = [components]; }
    for (var i = 0, len = components.length; i < len; i++) { this.addComponent(components[i]); }
}, addComponent: function (component, index) {
    var added = false; if (component) {
        if (this.componentTypes == null || (OpenLayers.Util.indexOf(this.componentTypes, component.CLASS_NAME) > -1)) {
            if (index != null && (index < this.components.length)) { var components1 = this.components.slice(0, index); var components2 = this.components.slice(index, this.components.length); components1.push(component); this.components = components1.concat(components2); } else { this.components.push(component); }
            component.parent = this; this.clearBounds(); added = true;
        }
    }
    return added;
}, removeComponents: function (components) {
    var removed = false; if (!(OpenLayers.Util.isArray(components))) { components = [components]; }
    for (var i = components.length - 1; i >= 0; --i) { removed = this.removeComponent(components[i]) || removed; }
    return removed;
}, removeComponent: function (component) { OpenLayers.Util.removeItem(this.components, component); this.clearBounds(); return true; }, getLength: function () {
    var length = 0.0; for (var i = 0, len = this.components.length; i < len; i++) { length += this.components[i].getLength(); }
    return length;
}, getArea: function () {
    var area = 0.0; for (var i = 0, len = this.components.length; i < len; i++) { area += this.components[i].getArea(); }
    return area;
}, getGeodesicArea: function (projection) {
    var area = 0.0; for (var i = 0, len = this.components.length; i < len; i++) { area += this.components[i].getGeodesicArea(projection); }
    return area;
}, getCentroid: function (weighted) {
    if (!weighted) { return this.components.length && this.components[0].getCentroid(); }
    var len = this.components.length; if (!len) { return false; }
    var areas = []; var centroids = []; var areaSum = 0; var minArea = Number.MAX_VALUE; var component; for (var i = 0; i < len; ++i) {
        component = this.components[i]; var area = component.getArea(); var centroid = component.getCentroid(true); if (isNaN(area) || isNaN(centroid.x) || isNaN(centroid.y)) { continue; }
        areas.push(area); areaSum += area; minArea = (area < minArea && area > 0) ? area : minArea; centroids.push(centroid);
    }
    len = areas.length; if (areaSum === 0) {
        for (var i = 0; i < len; ++i) { areas[i] = 1; }
        areaSum = areas.length;
    } else {
        for (var i = 0; i < len; ++i) { areas[i] /= minArea; }
        areaSum /= minArea;
    }
    var xSum = 0, ySum = 0, centroid, area; for (var i = 0; i < len; ++i) { centroid = centroids[i]; area = areas[i]; xSum += centroid.x * area; ySum += centroid.y * area; }
    return new OpenLayers.Geometry.Point(xSum / areaSum, ySum / areaSum);
}, getGeodesicLength: function (projection) {
    var length = 0.0; for (var i = 0, len = this.components.length; i < len; i++) { length += this.components[i].getGeodesicLength(projection); }
    return length;
}, move: function (x, y) { for (var i = 0, len = this.components.length; i < len; i++) { this.components[i].move(x, y); } }, rotate: function (angle, origin) { for (var i = 0, len = this.components.length; i < len; ++i) { this.components[i].rotate(angle, origin); } }, resize: function (scale, origin, ratio) {
    for (var i = 0; i < this.components.length; ++i) { this.components[i].resize(scale, origin, ratio); }
    return this;
}, distanceTo: function (geometry, options) {
    var edge = !(options && options.edge === false); var details = edge && options && options.details; var result, best, distance; var min = Number.POSITIVE_INFINITY; for (var i = 0, len = this.components.length; i < len; ++i) { result = this.components[i].distanceTo(geometry, options); distance = details ? result.distance : result; if (distance < min) { min = distance; best = result; if (min == 0) { break; } } }
    return best;
}, equals: function (geometry) {
    var equivalent = true; if (!geometry || !geometry.CLASS_NAME || (this.CLASS_NAME != geometry.CLASS_NAME)) { equivalent = false; } else if (!(OpenLayers.Util.isArray(geometry.components)) || (geometry.components.length != this.components.length)) { equivalent = false; } else { for (var i = 0, len = this.components.length; i < len; ++i) { if (!this.components[i].equals(geometry.components[i])) { equivalent = false; break; } } }
    return equivalent;
}, transform: function (source, dest) {
    if (source && dest) {
        for (var i = 0, len = this.components.length; i < len; i++) { var component = this.components[i]; component.transform(source, dest); }
        this.bounds = null;
    }
    return this;
}, intersects: function (geometry) {
    var intersect = false; for (var i = 0, len = this.components.length; i < len; ++i) { intersect = geometry.intersects(this.components[i]); if (intersect) { break; } }
    return intersect;
}, getVertices: function (nodes) {
    var vertices = []; for (var i = 0, len = this.components.length; i < len; ++i) { Array.prototype.push.apply(vertices, this.components[i].getVertices(nodes)); }
    return vertices;
}, CLASS_NAME: "OpenLayers.Geometry.Collection"
}); OpenLayers.Geometry.MultiPoint = OpenLayers.Class(OpenLayers.Geometry.Collection, { componentTypes: ["OpenLayers.Geometry.Point"], initialize: function (components) { OpenLayers.Geometry.Collection.prototype.initialize.apply(this, arguments); }, addPoint: function (point, index) { this.addComponent(point, index); }, removePoint: function (point) { this.removeComponent(point); }, CLASS_NAME: "OpenLayers.Geometry.MultiPoint" }); OpenLayers.Geometry.Curve = OpenLayers.Class(OpenLayers.Geometry.MultiPoint, { componentTypes: ["OpenLayers.Geometry.Point"], initialize: function (points) { OpenLayers.Geometry.MultiPoint.prototype.initialize.apply(this, arguments); }, getLength: function () {
    var length = 0.0; if (this.components && (this.components.length > 1)) { for (var i = 1, len = this.components.length; i < len; i++) { length += this.components[i - 1].distanceTo(this.components[i]); } }
    return length;
}, getGeodesicLength: function (projection) {
    var geom = this; if (projection) { var gg = new OpenLayers.Projection("EPSG:4326"); if (!gg.equals(projection)) { geom = this.clone().transform(projection, gg); } }
    var length = 0.0; if (geom.components && (geom.components.length > 1)) { var p1, p2; for (var i = 1, len = geom.components.length; i < len; i++) { p1 = geom.components[i - 1]; p2 = geom.components[i]; length += OpenLayers.Util.distVincenty({ lon: p1.x, lat: p1.y }, { lon: p2.x, lat: p2.y }); } }
    return length * 1000;
}, CLASS_NAME: "OpenLayers.Geometry.Curve"
}); OpenLayers.Geometry.LineString = OpenLayers.Class(OpenLayers.Geometry.Curve, { initialize: function (points) { OpenLayers.Geometry.Curve.prototype.initialize.apply(this, arguments); }, removeComponent: function (point) {
    var removed = this.components && (this.components.length > 2); if (removed) { OpenLayers.Geometry.Collection.prototype.removeComponent.apply(this, arguments); }
    return removed;
}, intersects: function (geometry) {
    var intersect = false; var type = geometry.CLASS_NAME; if (type == "OpenLayers.Geometry.LineString" || type == "OpenLayers.Geometry.LinearRing" || type == "OpenLayers.Geometry.Point") {
        var segs1 = this.getSortedSegments(); var segs2; if (type == "OpenLayers.Geometry.Point") { segs2 = [{ x1: geometry.x, y1: geometry.y, x2: geometry.x, y2: geometry.y}]; } else { segs2 = geometry.getSortedSegments(); }
        var seg1, seg1x1, seg1x2, seg1y1, seg1y2, seg2, seg2y1, seg2y2; outer: for (var i = 0, len = segs1.length; i < len; ++i) {
            seg1 = segs1[i]; seg1x1 = seg1.x1; seg1x2 = seg1.x2; seg1y1 = seg1.y1; seg1y2 = seg1.y2; inner: for (var j = 0, jlen = segs2.length; j < jlen; ++j) {
                seg2 = segs2[j]; if (seg2.x1 > seg1x2) { break; }
                if (seg2.x2 < seg1x1) { continue; }
                seg2y1 = seg2.y1; seg2y2 = seg2.y2; if (Math.min(seg2y1, seg2y2) > Math.max(seg1y1, seg1y2)) { continue; }
                if (Math.max(seg2y1, seg2y2) < Math.min(seg1y1, seg1y2)) { continue; }
                if (OpenLayers.Geometry.segmentsIntersect(seg1, seg2)) { intersect = true; break outer; }
            }
        }
    } else { intersect = geometry.intersects(this); }
    return intersect;
}, getSortedSegments: function () {
    var numSeg = this.components.length - 1; var segments = new Array(numSeg), point1, point2; for (var i = 0; i < numSeg; ++i) { point1 = this.components[i]; point2 = this.components[i + 1]; if (point1.x < point2.x) { segments[i] = { x1: point1.x, y1: point1.y, x2: point2.x, y2: point2.y }; } else { segments[i] = { x1: point2.x, y1: point2.y, x2: point1.x, y2: point1.y }; } }
    function byX1(seg1, seg2) { return seg1.x1 - seg2.x1; }
    return segments.sort(byX1);
}, splitWithSegment: function (seg, options) {
    var edge = !(options && options.edge === false); var tolerance = options && options.tolerance; var lines = []; var verts = this.getVertices(); var points = []; var intersections = []; var split = false; var vert1, vert2, point; var node, vertex, target; var interOptions = { point: true, tolerance: tolerance }; var result = null; for (var i = 0, stop = verts.length - 2; i <= stop; ++i) {
        vert1 = verts[i]; points.push(vert1.clone()); vert2 = verts[i + 1]; target = { x1: vert1.x, y1: vert1.y, x2: vert2.x, y2: vert2.y }; point = OpenLayers.Geometry.segmentsIntersect(seg, target, interOptions); if (point instanceof OpenLayers.Geometry.Point) {
            if ((point.x === seg.x1 && point.y === seg.y1) || (point.x === seg.x2 && point.y === seg.y2) || point.equals(vert1) || point.equals(vert2)) { vertex = true; } else { vertex = false; }
            if (vertex || edge) {
                if (!point.equals(intersections[intersections.length - 1])) { intersections.push(point.clone()); }
                if (i === 0) { if (point.equals(vert1)) { continue; } }
                if (point.equals(vert2)) { continue; }
                split = true; if (!point.equals(vert1)) { points.push(point); }
                lines.push(new OpenLayers.Geometry.LineString(points)); points = [point.clone()];
            }
        }
    }
    if (split) { points.push(vert2.clone()); lines.push(new OpenLayers.Geometry.LineString(points)); }
    if (intersections.length > 0) { var xDir = seg.x1 < seg.x2 ? 1 : -1; var yDir = seg.y1 < seg.y2 ? 1 : -1; result = { lines: lines, points: intersections.sort(function (p1, p2) { return (xDir * p1.x - xDir * p2.x) || (yDir * p1.y - yDir * p2.y); }) }; }
    return result;
}, split: function (target, options) {
    var results = null; var mutual = options && options.mutual; var sourceSplit, targetSplit, sourceParts, targetParts; if (target instanceof OpenLayers.Geometry.LineString) {
        var verts = this.getVertices(); var vert1, vert2, seg, splits, lines, point; var points = []; sourceParts = []; for (var i = 0, stop = verts.length - 2; i <= stop; ++i) {
            vert1 = verts[i]; vert2 = verts[i + 1]; seg = { x1: vert1.x, y1: vert1.y, x2: vert2.x, y2: vert2.y }; targetParts = targetParts || [target]; if (mutual) { points.push(vert1.clone()); }
            for (var j = 0; j < targetParts.length; ++j) {
                splits = targetParts[j].splitWithSegment(seg, options); if (splits) {
                    lines = splits.lines; if (lines.length > 0) { lines.unshift(j, 1); Array.prototype.splice.apply(targetParts, lines); j += lines.length - 2; }
                    if (mutual) { for (var k = 0, len = splits.points.length; k < len; ++k) { point = splits.points[k]; if (!point.equals(vert1)) { points.push(point); sourceParts.push(new OpenLayers.Geometry.LineString(points)); if (point.equals(vert2)) { points = []; } else { points = [point.clone()]; } } } }
                }
            }
        }
        if (mutual && sourceParts.length > 0 && points.length > 0) { points.push(vert2.clone()); sourceParts.push(new OpenLayers.Geometry.LineString(points)); }
    } else { results = target.splitWith(this, options); }
    if (targetParts && targetParts.length > 1) { targetSplit = true; } else { targetParts = []; }
    if (sourceParts && sourceParts.length > 1) { sourceSplit = true; } else { sourceParts = []; }
    if (targetSplit || sourceSplit) { if (mutual) { results = [sourceParts, targetParts]; } else { results = targetParts; } }
    return results;
}, splitWith: function (geometry, options) { return geometry.split(this, options); }, getVertices: function (nodes) {
    var vertices; if (nodes === true) { vertices = [this.components[0], this.components[this.components.length - 1]]; } else if (nodes === false) { vertices = this.components.slice(1, this.components.length - 1); } else { vertices = this.components.slice(); }
    return vertices;
}, distanceTo: function (geometry, options) {
    var edge = !(options && options.edge === false); var details = edge && options && options.details; var result, best = {}; var min = Number.POSITIVE_INFINITY; if (geometry instanceof OpenLayers.Geometry.Point) {
        var segs = this.getSortedSegments(); var x = geometry.x; var y = geometry.y; var seg; for (var i = 0, len = segs.length; i < len; ++i) { seg = segs[i]; result = OpenLayers.Geometry.distanceToSegment(geometry, seg); if (result.distance < min) { min = result.distance; best = result; if (min === 0) { break; } } else { if (seg.x2 > x && ((y > seg.y1 && y < seg.y2) || (y < seg.y1 && y > seg.y2))) { break; } } }
        if (details) { best = { distance: best.distance, x0: best.x, y0: best.y, x1: x, y1: y }; } else { best = best.distance; }
    } else if (geometry instanceof OpenLayers.Geometry.LineString) {
        var segs0 = this.getSortedSegments(); var segs1 = geometry.getSortedSegments(); var seg0, seg1, intersection, x0, y0; var len1 = segs1.length; var interOptions = { point: true }; outer: for (var i = 0, len = segs0.length; i < len; ++i) { seg0 = segs0[i]; x0 = seg0.x1; y0 = seg0.y1; for (var j = 0; j < len1; ++j) { seg1 = segs1[j]; intersection = OpenLayers.Geometry.segmentsIntersect(seg0, seg1, interOptions); if (intersection) { min = 0; best = { distance: 0, x0: intersection.x, y0: intersection.y, x1: intersection.x, y1: intersection.y }; break outer; } else { result = OpenLayers.Geometry.distanceToSegment({ x: x0, y: y0 }, seg1); if (result.distance < min) { min = result.distance; best = { distance: min, x0: x0, y0: y0, x1: result.x, y1: result.y }; } } } }
        if (!details) { best = best.distance; }
        if (min !== 0) { if (seg0) { result = geometry.distanceTo(new OpenLayers.Geometry.Point(seg0.x2, seg0.y2), options); var dist = details ? result.distance : result; if (dist < min) { if (details) { best = { distance: min, x0: result.x1, y0: result.y1, x1: result.x0, y1: result.y0 }; } else { best = dist; } } } }
    } else { best = geometry.distanceTo(this, options); if (details) { best = { distance: best.distance, x0: best.x1, y0: best.y1, x1: best.x0, y1: best.y0 }; } }
    return best;
}, simplify: function (tolerance) {
    if (this && this !== null) {
        var points = this.getVertices(); if (points.length < 3) { return this; }
        var compareNumbers = function (a, b) { return (a - b); }; var douglasPeuckerReduction = function (points, firstPoint, lastPoint, tolerance) {
            var maxDistance = 0; var indexFarthest = 0; for (var index = firstPoint, distance; index < lastPoint; index++) { distance = perpendicularDistance(points[firstPoint], points[lastPoint], points[index]); if (distance > maxDistance) { maxDistance = distance; indexFarthest = index; } }
            if (maxDistance > tolerance && indexFarthest != firstPoint) { pointIndexsToKeep.push(indexFarthest); douglasPeuckerReduction(points, firstPoint, indexFarthest, tolerance); douglasPeuckerReduction(points, indexFarthest, lastPoint, tolerance); }
        }; var perpendicularDistance = function (point1, point2, point) { var area = Math.abs(0.5 * (point1.x * point2.y + point2.x * point.y + point.x * point1.y - point2.x * point1.y - point.x * point2.y - point1.x * point.y)); var bottom = Math.sqrt(Math.pow(point1.x - point2.x, 2) + Math.pow(point1.y - point2.y, 2)); var height = area / bottom * 2; return height; }; var firstPoint = 0; var lastPoint = points.length - 1; var pointIndexsToKeep = []; pointIndexsToKeep.push(firstPoint); pointIndexsToKeep.push(lastPoint); while (points[firstPoint].equals(points[lastPoint])) { lastPoint--; pointIndexsToKeep.push(lastPoint); }
        douglasPeuckerReduction(points, firstPoint, lastPoint, tolerance); var returnPoints = []; pointIndexsToKeep.sort(compareNumbers); for (var index = 0; index < pointIndexsToKeep.length; index++) { returnPoints.push(points[pointIndexsToKeep[index]]); }
        return new OpenLayers.Geometry.LineString(returnPoints);
    }
    else { return this; }
}, CLASS_NAME: "OpenLayers.Geometry.LineString"
}); OpenLayers.Geometry.MultiLineString = OpenLayers.Class(OpenLayers.Geometry.Collection, { componentTypes: ["OpenLayers.Geometry.LineString"], initialize: function (components) { OpenLayers.Geometry.Collection.prototype.initialize.apply(this, arguments); }, split: function (geometry, options) {
    var results = null; var mutual = options && options.mutual; var splits, sourceLine, sourceLines, sourceSplit, targetSplit; var sourceParts = []; var targetParts = [geometry]; for (var i = 0, len = this.components.length; i < len; ++i) {
        sourceLine = this.components[i]; sourceSplit = false; for (var j = 0; j < targetParts.length; ++j) {
            splits = sourceLine.split(targetParts[j], options); if (splits) {
                if (mutual) {
                    sourceLines = splits[0]; for (var k = 0, klen = sourceLines.length; k < klen; ++k) { if (k === 0 && sourceParts.length) { sourceParts[sourceParts.length - 1].addComponent(sourceLines[k]); } else { sourceParts.push(new OpenLayers.Geometry.MultiLineString([sourceLines[k]])); } }
                    sourceSplit = true; splits = splits[1];
                }
                if (splits.length) { splits.unshift(j, 1); Array.prototype.splice.apply(targetParts, splits); break; }
            }
        }
        if (!sourceSplit) { if (sourceParts.length) { sourceParts[sourceParts.length - 1].addComponent(sourceLine.clone()); } else { sourceParts = [new OpenLayers.Geometry.MultiLineString(sourceLine.clone())]; } }
    }
    if (sourceParts && sourceParts.length > 1) { sourceSplit = true; } else { sourceParts = []; }
    if (targetParts && targetParts.length > 1) { targetSplit = true; } else { targetParts = []; }
    if (sourceSplit || targetSplit) { if (mutual) { results = [sourceParts, targetParts]; } else { results = targetParts; } }
    return results;
}, splitWith: function (geometry, options) {
    var results = null; var mutual = options && options.mutual; var splits, targetLine, sourceLines, sourceSplit, targetSplit, sourceParts, targetParts; if (geometry instanceof OpenLayers.Geometry.LineString) {
        targetParts = []; sourceParts = [geometry]; for (var i = 0, len = this.components.length; i < len; ++i) {
            targetSplit = false; targetLine = this.components[i]; for (var j = 0; j < sourceParts.length; ++j) {
                splits = sourceParts[j].split(targetLine, options); if (splits) {
                    if (mutual) {
                        sourceLines = splits[0]; if (sourceLines.length) { sourceLines.unshift(j, 1); Array.prototype.splice.apply(sourceParts, sourceLines); j += sourceLines.length - 2; }
                        splits = splits[1]; if (splits.length === 0) { splits = [targetLine.clone()]; }
                    }
                    for (var k = 0, klen = splits.length; k < klen; ++k) { if (k === 0 && targetParts.length) { targetParts[targetParts.length - 1].addComponent(splits[k]); } else { targetParts.push(new OpenLayers.Geometry.MultiLineString([splits[k]])); } }
                    targetSplit = true;
                }
            }
            if (!targetSplit) { if (targetParts.length) { targetParts[targetParts.length - 1].addComponent(targetLine.clone()); } else { targetParts = [new OpenLayers.Geometry.MultiLineString([targetLine.clone()])]; } }
        }
    } else { results = geometry.split(this); }
    if (sourceParts && sourceParts.length > 1) { sourceSplit = true; } else { sourceParts = []; }
    if (targetParts && targetParts.length > 1) { targetSplit = true; } else { targetParts = []; }
    if (sourceSplit || targetSplit) { if (mutual) { results = [sourceParts, targetParts]; } else { results = targetParts; } }
    return results;
}, CLASS_NAME: "OpenLayers.Geometry.MultiLineString"
}); OpenLayers.Geometry.LinearRing = OpenLayers.Class(OpenLayers.Geometry.LineString, { componentTypes: ["OpenLayers.Geometry.Point"], initialize: function (points) { OpenLayers.Geometry.LineString.prototype.initialize.apply(this, arguments); }, addComponent: function (point, index) {
    var added = false; var lastPoint = this.components.pop(); if (index != null || !point.equals(lastPoint)) { added = OpenLayers.Geometry.Collection.prototype.addComponent.apply(this, arguments); }
    var firstPoint = this.components[0]; OpenLayers.Geometry.Collection.prototype.addComponent.apply(this, [firstPoint]); return added;
}, removeComponent: function (point) {
    var removed = this.components && (this.components.length > 3); if (removed) { this.components.pop(); OpenLayers.Geometry.Collection.prototype.removeComponent.apply(this, arguments); var firstPoint = this.components[0]; OpenLayers.Geometry.Collection.prototype.addComponent.apply(this, [firstPoint]); }
    return removed;
}, move: function (x, y) { for (var i = 0, len = this.components.length; i < len - 1; i++) { this.components[i].move(x, y); } }, rotate: function (angle, origin) { for (var i = 0, len = this.components.length; i < len - 1; ++i) { this.components[i].rotate(angle, origin); } }, resize: function (scale, origin, ratio) {
    for (var i = 0, len = this.components.length; i < len - 1; ++i) { this.components[i].resize(scale, origin, ratio); }
    return this;
}, transform: function (source, dest) {
    if (source && dest) {
        for (var i = 0, len = this.components.length; i < len - 1; i++) { var component = this.components[i]; component.transform(source, dest); }
        this.bounds = null;
    }
    return this;
}, getCentroid: function () {
    if (this.components && (this.components.length > 2)) {
        var sumX = 0.0; var sumY = 0.0; for (var i = 0; i < this.components.length - 1; i++) { var b = this.components[i]; var c = this.components[i + 1]; sumX += (b.x + c.x) * (b.x * c.y - c.x * b.y); sumY += (b.y + c.y) * (b.x * c.y - c.x * b.y); }
        var area = -1 * this.getArea(); var x = sumX / (6 * area); var y = sumY / (6 * area); return new OpenLayers.Geometry.Point(x, y);
    } else { return null; }
}, getArea: function () {
    var area = 0.0; if (this.components && (this.components.length > 2)) {
        var sum = 0.0; for (var i = 0, len = this.components.length; i < len - 1; i++) { var b = this.components[i]; var c = this.components[i + 1]; sum += (b.x + c.x) * (c.y - b.y); }
        area = -sum / 2.0;
    }
    return area;
}, getGeodesicArea: function (projection) {
    var ring = this; if (projection) { var gg = new OpenLayers.Projection("EPSG:4326"); if (!gg.equals(projection)) { ring = this.clone().transform(projection, gg); } }
    var area = 0.0; var len = ring.components && ring.components.length; if (len > 2) {
        var p1, p2; for (var i = 0; i < len - 1; i++) {
            p1 = ring.components[i]; p2 = ring.components[i + 1]; area += OpenLayers.Util.rad(p2.x - p1.x) * (2 + Math.sin(OpenLayers.Util.rad(p1.y)) +
Math.sin(OpenLayers.Util.rad(p2.y)));
        }
        area = area * 6378137.0 * 6378137.0 / 2.0;
    }
    return area;
}, containsPoint: function (point) {
    var approx = OpenLayers.Number.limitSigDigs; var digs = 14; var px = approx(point.x, digs); var py = approx(point.y, digs); function getX(y, x1, y1, x2, y2) { return (((x1 - x2) * y) + ((x2 * y1) - (x1 * y2))) / (y1 - y2); }
    var numSeg = this.components.length - 1; var start, end, x1, y1, x2, y2, cx, cy; var crosses = 0; for (var i = 0; i < numSeg; ++i) {
        start = this.components[i]; x1 = approx(start.x, digs); y1 = approx(start.y, digs); end = this.components[i + 1]; x2 = approx(end.x, digs); y2 = approx(end.y, digs); if (y1 == y2) {
            if (py == y1) { if (x1 <= x2 && (px >= x1 && px <= x2) || x1 >= x2 && (px <= x1 && px >= x2)) { crosses = -1; break; } }
            continue;
        }
        cx = approx(getX(py, x1, y1, x2, y2), digs); if (cx == px) { if (y1 < y2 && (py >= y1 && py <= y2) || y1 > y2 && (py <= y1 && py >= y2)) { crosses = -1; break; } }
        if (cx <= px) { continue; }
        if (x1 != x2 && (cx < Math.min(x1, x2) || cx > Math.max(x1, x2))) { continue; }
        if (y1 < y2 && (py >= y1 && py < y2) || y1 > y2 && (py < y1 && py >= y2)) { ++crosses; }
    }
    var contained = (crosses == -1) ? 1 : !!(crosses & 1); return contained;
}, intersects: function (geometry) {
    var intersect = false; if (geometry.CLASS_NAME == "OpenLayers.Geometry.Point") { intersect = this.containsPoint(geometry); } else if (geometry.CLASS_NAME == "OpenLayers.Geometry.LineString") { intersect = geometry.intersects(this); } else if (geometry.CLASS_NAME == "OpenLayers.Geometry.LinearRing") { intersect = OpenLayers.Geometry.LineString.prototype.intersects.apply(this, [geometry]); } else { for (var i = 0, len = geometry.components.length; i < len; ++i) { intersect = geometry.components[i].intersects(this); if (intersect) { break; } } }
    return intersect;
}, getVertices: function (nodes) { return (nodes === true) ? [] : this.components.slice(0, this.components.length - 1); }, CLASS_NAME: "OpenLayers.Geometry.LinearRing"
}); OpenLayers.Geometry.Polygon = OpenLayers.Class(OpenLayers.Geometry.Collection, { componentTypes: ["OpenLayers.Geometry.LinearRing"], initialize: function (components) { OpenLayers.Geometry.Collection.prototype.initialize.apply(this, arguments); }, getArea: function () {
    var area = 0.0; if (this.components && (this.components.length > 0)) { area += Math.abs(this.components[0].getArea()); for (var i = 1, len = this.components.length; i < len; i++) { area -= Math.abs(this.components[i].getArea()); } }
    return area;
}, getGeodesicArea: function (projection) {
    var area = 0.0; if (this.components && (this.components.length > 0)) { area += Math.abs(this.components[0].getGeodesicArea(projection)); for (var i = 1, len = this.components.length; i < len; i++) { area -= Math.abs(this.components[i].getGeodesicArea(projection)); } }
    return area;
}, containsPoint: function (point) {
    var numRings = this.components.length; var contained = false; if (numRings > 0) {
        contained = this.components[0].containsPoint(point); if (contained !== 1) {
            if (contained && numRings > 1) {
                var hole; for (var i = 1; i < numRings; ++i) {
                    hole = this.components[i].containsPoint(point); if (hole) {
                        if (hole === 1) { contained = 1; } else { contained = false; }
                        break;
                    }
                }
            }
        }
    }
    return contained;
}, intersects: function (geometry) {
    var intersect = false; var i, len; if (geometry.CLASS_NAME == "OpenLayers.Geometry.Point") { intersect = this.containsPoint(geometry); } else if (geometry.CLASS_NAME == "OpenLayers.Geometry.LineString" || geometry.CLASS_NAME == "OpenLayers.Geometry.LinearRing") {
        for (i = 0, len = this.components.length; i < len; ++i) { intersect = geometry.intersects(this.components[i]); if (intersect) { break; } }
        if (!intersect) { for (i = 0, len = geometry.components.length; i < len; ++i) { intersect = this.containsPoint(geometry.components[i]); if (intersect) { break; } } }
    } else { for (i = 0, len = geometry.components.length; i < len; ++i) { intersect = this.intersects(geometry.components[i]); if (intersect) { break; } } }
    if (!intersect && geometry.CLASS_NAME == "OpenLayers.Geometry.Polygon") { var ring = this.components[0]; for (i = 0, len = ring.components.length; i < len; ++i) { intersect = geometry.containsPoint(ring.components[i]); if (intersect) { break; } } }
    return intersect;
}, distanceTo: function (geometry, options) {
    var edge = !(options && options.edge === false); var result; if (!edge && this.intersects(geometry)) { result = 0; } else { result = OpenLayers.Geometry.Collection.prototype.distanceTo.apply(this, [geometry, options]); }
    return result;
}, CLASS_NAME: "OpenLayers.Geometry.Polygon"
}); OpenLayers.Geometry.Polygon.createRegularPolygon = function (origin, radius, sides, rotation) {
    var angle = Math.PI * ((1 / sides) - (1 / 2)); if (rotation) { angle += (rotation / 180) * Math.PI; }
    var rotatedAngle, x, y; var points = []; for (var i = 0; i < sides; ++i) { rotatedAngle = angle + (i * 2 * Math.PI / sides); x = origin.x + (radius * Math.cos(rotatedAngle)); y = origin.y + (radius * Math.sin(rotatedAngle)); points.push(new OpenLayers.Geometry.Point(x, y)); }
    var ring = new OpenLayers.Geometry.LinearRing(points); return new OpenLayers.Geometry.Polygon([ring]);
}; OpenLayers.Geometry.MultiPolygon = OpenLayers.Class(OpenLayers.Geometry.Collection, { componentTypes: ["OpenLayers.Geometry.Polygon"], initialize: function (components) { OpenLayers.Geometry.Collection.prototype.initialize.apply(this, arguments); }, CLASS_NAME: "OpenLayers.Geometry.MultiPolygon" }); OpenLayers.Format.GML = OpenLayers.Class(OpenLayers.Format.XML, { featureNS: "http://mapserver.gis.umn.edu/mapserver", featurePrefix: "feature", featureName: "featureMember", layerName: "features", geometryName: "geometry", collectionName: "FeatureCollection", gmlns: "http://www.opengis.net/gml", extractAttributes: true, xy: true, initialize: function (options) { this.regExes = { trimSpace: (/^\s*|\s*$/g), removeSpace: (/\s*/g), splitSpace: (/\s+/), trimComma: (/\s*,\s*/g) }; OpenLayers.Format.XML.prototype.initialize.apply(this, [options]); }, read: function (data) {
    if (typeof data == "string") { data = OpenLayers.Format.XML.prototype.read.apply(this, [data]); }
    var featureNodes = this.getElementsByTagNameNS(data.documentElement, this.gmlns, this.featureName); var features = []; for (var i = 0; i < featureNodes.length; i++) { var feature = this.parseFeature(featureNodes[i]); if (feature) { features.push(feature); } }
    return features;
}, parseFeature: function (node) {
    var order = ["MultiPolygon", "Polygon", "MultiLineString", "LineString", "MultiPoint", "Point", "Envelope"]; var type, nodeList, geometry, parser; for (var i = 0; i < order.length; ++i) {
        type = order[i]; nodeList = this.getElementsByTagNameNS(node, this.gmlns, type); if (nodeList.length > 0) {
            parser = this.parseGeometry[type.toLowerCase()]; if (parser) { geometry = parser.apply(this, [nodeList[0]]); if (this.internalProjection && this.externalProjection) { geometry.transform(this.externalProjection, this.internalProjection); } } else { OpenLayers.Console.error(OpenLayers.i18n("unsupportedGeometryType", { 'geomType': type })); }
            break;
        }
    }
    var bounds; var boxNodes = this.getElementsByTagNameNS(node, this.gmlns, "Box"); for (i = 0; i < boxNodes.length; ++i) { var boxNode = boxNodes[i]; var box = this.parseGeometry["box"].apply(this, [boxNode]); var parentNode = boxNode.parentNode; var parentName = parentNode.localName || parentNode.nodeName.split(":").pop(); if (parentName === "boundedBy") { bounds = box; } else { geometry = box.toGeometry(); } }
    var attributes; if (this.extractAttributes) { attributes = this.parseAttributes(node); }
    var feature = new OpenLayers.Feature.Vector(geometry, attributes); feature.bounds = bounds; feature.gml = { featureType: node.firstChild.nodeName.split(":")[1], featureNS: node.firstChild.namespaceURI, featureNSPrefix: node.firstChild.prefix }; var childNode = node.firstChild; var fid; while (childNode) {
        if (childNode.nodeType == 1) { fid = childNode.getAttribute("fid") || childNode.getAttribute("id"); if (fid) { break; } }
        childNode = childNode.nextSibling;
    }
    feature.fid = fid; return feature;
}, parseGeometry: { point: function (node) {
    var nodeList, coordString; var coords = []; var nodeList = this.getElementsByTagNameNS(node, this.gmlns, "pos"); if (nodeList.length > 0) { coordString = nodeList[0].firstChild.nodeValue; coordString = coordString.replace(this.regExes.trimSpace, ""); coords = coordString.split(this.regExes.splitSpace); }
    if (coords.length == 0) { nodeList = this.getElementsByTagNameNS(node, this.gmlns, "coordinates"); if (nodeList.length > 0) { coordString = nodeList[0].firstChild.nodeValue; coordString = coordString.replace(this.regExes.removeSpace, ""); coords = coordString.split(","); } }
    if (coords.length == 0) { nodeList = this.getElementsByTagNameNS(node, this.gmlns, "coord"); if (nodeList.length > 0) { var xList = this.getElementsByTagNameNS(nodeList[0], this.gmlns, "X"); var yList = this.getElementsByTagNameNS(nodeList[0], this.gmlns, "Y"); if (xList.length > 0 && yList.length > 0) { coords = [xList[0].firstChild.nodeValue, yList[0].firstChild.nodeValue]; } } }
    if (coords.length == 2) { coords[2] = null; }
    if (this.xy) { return new OpenLayers.Geometry.Point(coords[0], coords[1], coords[2]); }
    else { return new OpenLayers.Geometry.Point(coords[1], coords[0], coords[2]); }
}, multipoint: function (node) {
    var nodeList = this.getElementsByTagNameNS(node, this.gmlns, "Point"); var components = []; if (nodeList.length > 0) { var point; for (var i = 0; i < nodeList.length; ++i) { point = this.parseGeometry.point.apply(this, [nodeList[i]]); if (point) { components.push(point); } } }
    return new OpenLayers.Geometry.MultiPoint(components);
}, linestring: function (node, ring) {
    var nodeList, coordString; var coords = []; var points = []; nodeList = this.getElementsByTagNameNS(node, this.gmlns, "posList"); if (nodeList.length > 0) { coordString = this.getChildValue(nodeList[0]); coordString = coordString.replace(this.regExes.trimSpace, ""); coords = coordString.split(this.regExes.splitSpace); var dim = parseInt(nodeList[0].getAttribute("dimension")); var j, x, y, z; for (var i = 0; i < coords.length / dim; ++i) { j = i * dim; x = coords[j]; y = coords[j + 1]; z = (dim == 2) ? null : coords[j + 2]; if (this.xy) { points.push(new OpenLayers.Geometry.Point(x, y, z)); } else { points.push(new OpenLayers.Geometry.Point(y, x, z)); } } }
    if (coords.length == 0) {
        nodeList = this.getElementsByTagNameNS(node, this.gmlns, "coordinates"); if (nodeList.length > 0) {
            coordString = this.getChildValue(nodeList[0]); coordString = coordString.replace(this.regExes.trimSpace, ""); coordString = coordString.replace(this.regExes.trimComma, ","); var pointList = coordString.split(this.regExes.splitSpace); for (var i = 0; i < pointList.length; ++i) {
                coords = pointList[i].split(","); if (coords.length == 2) { coords[2] = null; }
                if (this.xy) { points.push(new OpenLayers.Geometry.Point(coords[0], coords[1], coords[2])); } else { points.push(new OpenLayers.Geometry.Point(coords[1], coords[0], coords[2])); }
            }
        }
    }
    var line = null; if (points.length != 0) { if (ring) { line = new OpenLayers.Geometry.LinearRing(points); } else { line = new OpenLayers.Geometry.LineString(points); } }
    return line;
}, multilinestring: function (node) {
    var nodeList = this.getElementsByTagNameNS(node, this.gmlns, "LineString"); var components = []; if (nodeList.length > 0) { var line; for (var i = 0; i < nodeList.length; ++i) { line = this.parseGeometry.linestring.apply(this, [nodeList[i]]); if (line) { components.push(line); } } }
    return new OpenLayers.Geometry.MultiLineString(components);
}, polygon: function (node) {
    var nodeList = this.getElementsByTagNameNS(node, this.gmlns, "LinearRing"); var components = []; if (nodeList.length > 0) { var ring; for (var i = 0; i < nodeList.length; ++i) { ring = this.parseGeometry.linestring.apply(this, [nodeList[i], true]); if (ring) { components.push(ring); } } }
    return new OpenLayers.Geometry.Polygon(components);
}, multipolygon: function (node) {
    var nodeList = this.getElementsByTagNameNS(node, this.gmlns, "Polygon"); var components = []; if (nodeList.length > 0) { var polygon; for (var i = 0; i < nodeList.length; ++i) { polygon = this.parseGeometry.polygon.apply(this, [nodeList[i]]); if (polygon) { components.push(polygon); } } }
    return new OpenLayers.Geometry.MultiPolygon(components);
}, envelope: function (node) {
    var components = []; var coordString; var envelope; var lpoint = this.getElementsByTagNameNS(node, this.gmlns, "lowerCorner"); if (lpoint.length > 0) {
        var coords = []; if (lpoint.length > 0) { coordString = lpoint[0].firstChild.nodeValue; coordString = coordString.replace(this.regExes.trimSpace, ""); coords = coordString.split(this.regExes.splitSpace); }
        if (coords.length == 2) { coords[2] = null; }
        if (this.xy) { var lowerPoint = new OpenLayers.Geometry.Point(coords[0], coords[1], coords[2]); } else { var lowerPoint = new OpenLayers.Geometry.Point(coords[1], coords[0], coords[2]); }
    }
    var upoint = this.getElementsByTagNameNS(node, this.gmlns, "upperCorner"); if (upoint.length > 0) {
        var coords = []; if (upoint.length > 0) { coordString = upoint[0].firstChild.nodeValue; coordString = coordString.replace(this.regExes.trimSpace, ""); coords = coordString.split(this.regExes.splitSpace); }
        if (coords.length == 2) { coords[2] = null; }
        if (this.xy) { var upperPoint = new OpenLayers.Geometry.Point(coords[0], coords[1], coords[2]); } else { var upperPoint = new OpenLayers.Geometry.Point(coords[1], coords[0], coords[2]); }
    }
    if (lowerPoint && upperPoint) { components.push(new OpenLayers.Geometry.Point(lowerPoint.x, lowerPoint.y)); components.push(new OpenLayers.Geometry.Point(upperPoint.x, lowerPoint.y)); components.push(new OpenLayers.Geometry.Point(upperPoint.x, upperPoint.y)); components.push(new OpenLayers.Geometry.Point(lowerPoint.x, upperPoint.y)); components.push(new OpenLayers.Geometry.Point(lowerPoint.x, lowerPoint.y)); var ring = new OpenLayers.Geometry.LinearRing(components); envelope = new OpenLayers.Geometry.Polygon([ring]); }
    return envelope;
}, box: function (node) {
    var nodeList = this.getElementsByTagNameNS(node, this.gmlns, "coordinates"); var coordString; var coords, beginPoint = null, endPoint = null; if (nodeList.length > 0) { coordString = nodeList[0].firstChild.nodeValue; coords = coordString.split(" "); if (coords.length == 2) { beginPoint = coords[0].split(","); endPoint = coords[1].split(","); } }
    if (beginPoint !== null && endPoint !== null) { return new OpenLayers.Bounds(parseFloat(beginPoint[0]), parseFloat(beginPoint[1]), parseFloat(endPoint[0]), parseFloat(endPoint[1])); }
}
}, parseAttributes: function (node) {
    var attributes = {}; var childNode = node.firstChild; var children, i, child, grandchildren, grandchild, name, value; while (childNode) {
        if (childNode.nodeType == 1) {
            children = childNode.childNodes; for (i = 0; i < children.length; ++i) { child = children[i]; if (child.nodeType == 1) { grandchildren = child.childNodes; if (grandchildren.length == 1) { grandchild = grandchildren[0]; if (grandchild.nodeType == 3 || grandchild.nodeType == 4) { name = (child.prefix) ? child.nodeName.split(":")[1] : child.nodeName; value = grandchild.nodeValue.replace(this.regExes.trimSpace, ""); attributes[name] = value; } } else { attributes[child.nodeName.split(":").pop()] = null; } } }
            break;
        }
        childNode = childNode.nextSibling;
    }
    return attributes;
}, write: function (features) {
    if (!(OpenLayers.Util.isArray(features))) { features = [features]; }
    var gml = this.createElementNS("http://www.opengis.net/wfs", "wfs:" + this.collectionName); for (var i = 0; i < features.length; i++) { gml.appendChild(this.createFeatureXML(features[i])); }
    return OpenLayers.Format.XML.prototype.write.apply(this, [gml]);
}, createFeatureXML: function (feature) {
    var geometry = feature.geometry; var geometryNode = this.buildGeometryNode(geometry); var geomContainer = this.createElementNS(this.featureNS, this.featurePrefix + ":" +
this.geometryName); geomContainer.appendChild(geometryNode); var featureNode = this.createElementNS(this.gmlns, "gml:" + this.featureName); var featureContainer = this.createElementNS(this.featureNS, this.featurePrefix + ":" +
this.layerName); var fid = feature.fid || feature.id; featureContainer.setAttribute("fid", fid); featureContainer.appendChild(geomContainer); for (var attr in feature.attributes) {
        var attrText = this.createTextNode(feature.attributes[attr]); var nodename = attr.substring(attr.lastIndexOf(":") + 1); var attrContainer = this.createElementNS(this.featureNS, this.featurePrefix + ":" +
nodename); attrContainer.appendChild(attrText); featureContainer.appendChild(attrContainer);
    }
    featureNode.appendChild(featureContainer); return featureNode;
}, buildGeometryNode: function (geometry) {
    if (this.externalProjection && this.internalProjection) { geometry = geometry.clone(); geometry.transform(this.internalProjection, this.externalProjection); }
    var className = geometry.CLASS_NAME; var type = className.substring(className.lastIndexOf(".") + 1); var builder = this.buildGeometry[type.toLowerCase()]; return builder.apply(this, [geometry]);
}, buildGeometry: { point: function (geometry) { var gml = this.createElementNS(this.gmlns, "gml:Point"); gml.appendChild(this.buildCoordinatesNode(geometry)); return gml; }, multipoint: function (geometry) {
    var gml = this.createElementNS(this.gmlns, "gml:MultiPoint"); var points = geometry.components; var pointMember, pointGeom; for (var i = 0; i < points.length; i++) { pointMember = this.createElementNS(this.gmlns, "gml:pointMember"); pointGeom = this.buildGeometry.point.apply(this, [points[i]]); pointMember.appendChild(pointGeom); gml.appendChild(pointMember); }
    return gml;
}, linestring: function (geometry) { var gml = this.createElementNS(this.gmlns, "gml:LineString"); gml.appendChild(this.buildCoordinatesNode(geometry)); return gml; }, multilinestring: function (geometry) {
    var gml = this.createElementNS(this.gmlns, "gml:MultiLineString"); var lines = geometry.components; var lineMember, lineGeom; for (var i = 0; i < lines.length; ++i) { lineMember = this.createElementNS(this.gmlns, "gml:lineStringMember"); lineGeom = this.buildGeometry.linestring.apply(this, [lines[i]]); lineMember.appendChild(lineGeom); gml.appendChild(lineMember); }
    return gml;
}, linearring: function (geometry) { var gml = this.createElementNS(this.gmlns, "gml:LinearRing"); gml.appendChild(this.buildCoordinatesNode(geometry)); return gml; }, polygon: function (geometry) {
    var gml = this.createElementNS(this.gmlns, "gml:Polygon"); var rings = geometry.components; var ringMember, ringGeom, type; for (var i = 0; i < rings.length; ++i) { type = (i == 0) ? "outerBoundaryIs" : "innerBoundaryIs"; ringMember = this.createElementNS(this.gmlns, "gml:" + type); ringGeom = this.buildGeometry.linearring.apply(this, [rings[i]]); ringMember.appendChild(ringGeom); gml.appendChild(ringMember); }
    return gml;
}, multipolygon: function (geometry) {
    var gml = this.createElementNS(this.gmlns, "gml:MultiPolygon"); var polys = geometry.components; var polyMember, polyGeom; for (var i = 0; i < polys.length; ++i) { polyMember = this.createElementNS(this.gmlns, "gml:polygonMember"); polyGeom = this.buildGeometry.polygon.apply(this, [polys[i]]); polyMember.appendChild(polyGeom); gml.appendChild(polyMember); }
    return gml;
}, bounds: function (bounds) { var gml = this.createElementNS(this.gmlns, "gml:Box"); gml.appendChild(this.buildCoordinatesNode(bounds)); return gml; }
}, buildCoordinatesNode: function (geometry) {
    var coordinatesNode = this.createElementNS(this.gmlns, "gml:coordinates"); coordinatesNode.setAttribute("decimal", "."); coordinatesNode.setAttribute("cs", ","); coordinatesNode.setAttribute("ts", " "); var parts = []; if (geometry instanceof OpenLayers.Bounds) { parts.push(geometry.left + "," + geometry.bottom); parts.push(geometry.right + "," + geometry.top); } else { var points = (geometry.components) ? geometry.components : [geometry]; for (var i = 0; i < points.length; i++) { parts.push(points[i].x + "," + points[i].y); } }
    var txtNode = this.createTextNode(parts.join(" ")); coordinatesNode.appendChild(txtNode); return coordinatesNode;
}, CLASS_NAME: "OpenLayers.Format.GML"
}); if (!OpenLayers.Format.GML) { OpenLayers.Format.GML = {}; }
OpenLayers.Format.GML.Base = OpenLayers.Class(OpenLayers.Format.XML, { namespaces: { gml: "http://www.opengis.net/gml", xlink: "http://www.w3.org/1999/xlink", xsi: "http://www.w3.org/2001/XMLSchema-instance", wfs: "http://www.opengis.net/wfs" }, defaultPrefix: "gml", schemaLocation: null, featureType: null, featureNS: null, geometryName: "geometry", extractAttributes: true, srsName: null, xy: true, geometryTypes: null, singleFeatureType: null, regExes: { trimSpace: (/^\s*|\s*$/g), removeSpace: (/\s*/g), splitSpace: (/\s+/), trimComma: (/\s*,\s*/g), featureMember: (/^(.*:)?featureMembers?$/) }, initialize: function (options) {
    OpenLayers.Format.XML.prototype.initialize.apply(this, [options]); this.setGeometryTypes(); if (options && options.featureNS) { this.setNamespace("feature", options.featureNS); }
    this.singleFeatureType = !options || (typeof options.featureType === "string");
}, read: function (data) {
    if (typeof data == "string") { data = OpenLayers.Format.XML.prototype.read.apply(this, [data]); }
    if (data && data.nodeType == 9) { data = data.documentElement; }
    var features = []; this.readNode(data, { features: features }, true); if (features.length == 0) { var elements = this.getElementsByTagNameNS(data, this.namespaces.gml, "featureMember"); if (elements.length) { for (var i = 0, len = elements.length; i < len; ++i) { this.readNode(elements[i], { features: features }, true); } } else { var elements = this.getElementsByTagNameNS(data, this.namespaces.gml, "featureMembers"); if (elements.length) { this.readNode(elements[0], { features: features }, true); } } }
    return features;
}, readNode: function (node, obj, first) {
    if (first === true && this.autoConfig === true) { this.featureType = null; delete this.namespaceAlias[this.featureNS]; delete this.namespaces["feature"]; this.featureNS = null; }
    if (!this.featureNS && (!(node.prefix in this.namespaces) && node.parentNode.namespaceURI == this.namespaces["gml"] && this.regExes.featureMember.test(node.parentNode.nodeName))) { this.featureType = node.nodeName.split(":").pop(); this.setNamespace("feature", node.namespaceURI); this.featureNS = node.namespaceURI; this.autoConfig = true; }
    return OpenLayers.Format.XML.prototype.readNode.apply(this, [node, obj]);
}, readers: { "gml": { "featureMember": function (node, obj) { this.readChildNodes(node, obj); }, "featureMembers": function (node, obj) { this.readChildNodes(node, obj); }, "name": function (node, obj) { obj.name = this.getChildValue(node); }, "boundedBy": function (node, obj) { var container = {}; this.readChildNodes(node, container); if (container.components && container.components.length > 0) { obj.bounds = container.components[0]; } }, "Point": function (node, container) {
    var obj = { points: [] }; this.readChildNodes(node, obj); if (!container.components) { container.components = []; }
    container.components.push(obj.points[0]);
}, "coordinates": function (node, obj) {
    var str = this.getChildValue(node).replace(this.regExes.trimSpace, ""); str = str.replace(this.regExes.trimComma, ","); var pointList = str.split(this.regExes.splitSpace); var coords; var numPoints = pointList.length; var points = new Array(numPoints); for (var i = 0; i < numPoints; ++i) { coords = pointList[i].split(","); if (this.xy) { points[i] = new OpenLayers.Geometry.Point(coords[0], coords[1], coords[2]); } else { points[i] = new OpenLayers.Geometry.Point(coords[1], coords[0], coords[2]); } }
    obj.points = points;
}, "coord": function (node, obj) {
    var coord = {}; this.readChildNodes(node, coord); if (!obj.points) { obj.points = []; }
    obj.points.push(new OpenLayers.Geometry.Point(coord.x, coord.y, coord.z));
}, "X": function (node, coord) { coord.x = this.getChildValue(node); }, "Y": function (node, coord) { coord.y = this.getChildValue(node); }, "Z": function (node, coord) { coord.z = this.getChildValue(node); }, "MultiPoint": function (node, container) { var obj = { components: [] }; this.readChildNodes(node, obj); container.components = [new OpenLayers.Geometry.MultiPoint(obj.components)]; }, "pointMember": function (node, obj) { this.readChildNodes(node, obj); }, "LineString": function (node, container) {
    var obj = {}; this.readChildNodes(node, obj); if (!container.components) { container.components = []; }
    container.components.push(new OpenLayers.Geometry.LineString(obj.points));
}, "MultiLineString": function (node, container) { var obj = { components: [] }; this.readChildNodes(node, obj); container.components = [new OpenLayers.Geometry.MultiLineString(obj.components)]; }, "lineStringMember": function (node, obj) { this.readChildNodes(node, obj); }, "Polygon": function (node, container) {
    var obj = { outer: null, inner: [] }; this.readChildNodes(node, obj); obj.inner.unshift(obj.outer); if (!container.components) { container.components = []; }
    container.components.push(new OpenLayers.Geometry.Polygon(obj.inner));
}, "LinearRing": function (node, obj) { var container = {}; this.readChildNodes(node, container); obj.components = [new OpenLayers.Geometry.LinearRing(container.points)]; }, "MultiPolygon": function (node, container) { var obj = { components: [] }; this.readChildNodes(node, obj); container.components = [new OpenLayers.Geometry.MultiPolygon(obj.components)]; }, "polygonMember": function (node, obj) { this.readChildNodes(node, obj); }, "GeometryCollection": function (node, container) { var obj = { components: [] }; this.readChildNodes(node, obj); container.components = [new OpenLayers.Geometry.Collection(obj.components)]; }, "geometryMember": function (node, obj) { this.readChildNodes(node, obj); }
}, "feature": { "*": function (node, obj) {
    var name; var local = node.localName || node.nodeName.split(":").pop(); if (obj.features) { if (!this.singleFeatureType && (OpenLayers.Util.indexOf(this.featureType, local) !== -1)) { name = "_typeName"; } else if (local === this.featureType) { name = "_typeName"; } } else { if (node.childNodes.length == 0 || (node.childNodes.length == 1 && node.firstChild.nodeType == 3)) { if (this.extractAttributes) { name = "_attribute"; } } else { name = "_geometry"; } }
    if (name) { this.readers.feature[name].apply(this, [node, obj]); }
}, "_typeName": function (node, obj) {
    var container = { components: [], attributes: {} }; this.readChildNodes(node, container); if (container.name) { container.attributes.name = container.name; }
    var feature = new OpenLayers.Feature.Vector(container.components[0], container.attributes); if (!this.singleFeatureType) { feature.type = node.nodeName.split(":").pop(); feature.namespace = node.namespaceURI; }
    var fid = node.getAttribute("fid") || this.getAttributeNS(node, this.namespaces["gml"], "id"); if (fid) { feature.fid = fid; }
    if (this.internalProjection && this.externalProjection && feature.geometry) { feature.geometry.transform(this.externalProjection, this.internalProjection); }
    if (container.bounds) { feature.bounds = container.bounds; }
    obj.features.push(feature);
}, "_geometry": function (node, obj) {
    if (!this.geometryName) { this.geometryName = node.nodeName.split(":").pop(); }
    this.readChildNodes(node, obj);
}, "_attribute": function (node, obj) { var local = node.localName || node.nodeName.split(":").pop(); var value = this.getChildValue(node); obj.attributes[local] = value; }
}, "wfs": { "FeatureCollection": function (node, obj) { this.readChildNodes(node, obj); } }
}, write: function (features) {
    var name; if (OpenLayers.Util.isArray(features)) { name = "featureMembers"; } else { name = "featureMember"; }
    var root = this.writeNode("gml:" + name, features); this.setAttributeNS(root, this.namespaces["xsi"], "xsi:schemaLocation", this.schemaLocation); return OpenLayers.Format.XML.prototype.write.apply(this, [root]);
}, writers: { "gml": { "featureMember": function (feature) { var node = this.createElementNSPlus("gml:featureMember"); this.writeNode("feature:_typeName", feature, node); return node; }, "MultiPoint": function (geometry) {
    var node = this.createElementNSPlus("gml:MultiPoint"); var components = geometry.components || [geometry]; for (var i = 0, ii = components.length; i < ii; ++i) { this.writeNode("pointMember", components[i], node); }
    return node;
}, "pointMember": function (geometry) { var node = this.createElementNSPlus("gml:pointMember"); this.writeNode("Point", geometry, node); return node; }, "MultiLineString": function (geometry) {
    var node = this.createElementNSPlus("gml:MultiLineString"); var components = geometry.components || [geometry]; for (var i = 0, ii = components.length; i < ii; ++i) { this.writeNode("lineStringMember", components[i], node); }
    return node;
}, "lineStringMember": function (geometry) { var node = this.createElementNSPlus("gml:lineStringMember"); this.writeNode("LineString", geometry, node); return node; }, "MultiPolygon": function (geometry) {
    var node = this.createElementNSPlus("gml:MultiPolygon"); var components = geometry.components || [geometry]; for (var i = 0, ii = components.length; i < ii; ++i) { this.writeNode("polygonMember", components[i], node); }
    return node;
}, "polygonMember": function (geometry) { var node = this.createElementNSPlus("gml:polygonMember"); this.writeNode("Polygon", geometry, node); return node; }, "GeometryCollection": function (geometry) {
    var node = this.createElementNSPlus("gml:GeometryCollection"); for (var i = 0, len = geometry.components.length; i < len; ++i) { this.writeNode("geometryMember", geometry.components[i], node); }
    return node;
}, "geometryMember": function (geometry) { var node = this.createElementNSPlus("gml:geometryMember"); var child = this.writeNode("feature:_geometry", geometry); node.appendChild(child.firstChild); return node; }
}, "feature": { "_typeName": function (feature) {
    var node = this.createElementNSPlus("feature:" + this.featureType, { attributes: { fid: feature.fid} }); if (feature.geometry) { this.writeNode("feature:_geometry", feature.geometry, node); }
    for (var name in feature.attributes) { var value = feature.attributes[name]; if (value != null) { this.writeNode("feature:_attribute", { name: name, value: value }, node); } }
    return node;
}, "_geometry": function (geometry) {
    if (this.externalProjection && this.internalProjection) { geometry = geometry.clone().transform(this.internalProjection, this.externalProjection); }
    var node = this.createElementNSPlus("feature:" + this.geometryName); var type = this.geometryTypes[geometry.CLASS_NAME]; var child = this.writeNode("gml:" + type, geometry, node); if (this.srsName) { child.setAttribute("srsName", this.srsName); }
    return node;
}, "_attribute": function (obj) { return this.createElementNSPlus("feature:" + obj.name, { value: obj.value }); }
}, "wfs": { "FeatureCollection": function (features) {
    var node = this.createElementNSPlus("wfs:FeatureCollection"); for (var i = 0, len = features.length; i < len; ++i) { this.writeNode("gml:featureMember", features[i], node); }
    return node;
}
}
}, setGeometryTypes: function () { this.geometryTypes = { "OpenLayers.Geometry.Point": "Point", "OpenLayers.Geometry.MultiPoint": "MultiPoint", "OpenLayers.Geometry.LineString": "LineString", "OpenLayers.Geometry.MultiLineString": "MultiLineString", "OpenLayers.Geometry.Polygon": "Polygon", "OpenLayers.Geometry.MultiPolygon": "MultiPolygon", "OpenLayers.Geometry.Collection": "GeometryCollection" }; }, CLASS_NAME: "OpenLayers.Format.GML.Base"
}); OpenLayers.Format.GML.v3 = OpenLayers.Class(OpenLayers.Format.GML.Base, { schemaLocation: "http://www.opengis.net/gml http://schemas.opengis.net/gml/3.1.1/profiles/gmlsfProfile/1.0.0/gmlsf.xsd", curve: false, multiCurve: true, surface: false, multiSurface: true, initialize: function (options) { OpenLayers.Format.GML.Base.prototype.initialize.apply(this, [options]); }, readers: { "gml": OpenLayers.Util.applyDefaults({ "featureMembers": function (node, obj) { this.readChildNodes(node, obj); }, "Curve": function (node, container) {
    var obj = { points: [] }; this.readChildNodes(node, obj); if (!container.components) { container.components = []; }
    container.components.push(new OpenLayers.Geometry.LineString(obj.points));
}, "segments": function (node, obj) { this.readChildNodes(node, obj); }, "LineStringSegment": function (node, container) { var obj = {}; this.readChildNodes(node, obj); if (obj.points) { Array.prototype.push.apply(container.points, obj.points); } }, "pos": function (node, obj) {
    var str = this.getChildValue(node).replace(this.regExes.trimSpace, ""); var coords = str.split(this.regExes.splitSpace); var point; if (this.xy) { point = new OpenLayers.Geometry.Point(coords[0], coords[1], coords[2]); } else { point = new OpenLayers.Geometry.Point(coords[1], coords[0], coords[2]); }
    obj.points = [point];
}, "posList": function (node, obj) {
    var str = this.getChildValue(node).replace(this.regExes.trimSpace, ""); var coords = str.split(this.regExes.splitSpace); var dim = parseInt(node.getAttribute("dimension")) || 2; var j, x, y, z; var numPoints = coords.length / dim; var points = new Array(numPoints); for (var i = 0, len = coords.length; i < len; i += dim) { x = coords[i]; y = coords[i + 1]; z = (dim == 2) ? undefined : coords[i + 2]; if (this.xy) { points[i / dim] = new OpenLayers.Geometry.Point(x, y, z); } else { points[i / dim] = new OpenLayers.Geometry.Point(y, x, z); } }
    obj.points = points;
}, "Surface": function (node, obj) { this.readChildNodes(node, obj); }, "patches": function (node, obj) { this.readChildNodes(node, obj); }, "PolygonPatch": function (node, obj) { this.readers.gml.Polygon.apply(this, [node, obj]); }, "exterior": function (node, container) { var obj = {}; this.readChildNodes(node, obj); container.outer = obj.components[0]; }, "interior": function (node, container) { var obj = {}; this.readChildNodes(node, obj); container.inner.push(obj.components[0]); }, "MultiCurve": function (node, container) { var obj = { components: [] }; this.readChildNodes(node, obj); if (obj.components.length > 0) { container.components = [new OpenLayers.Geometry.MultiLineString(obj.components)]; } }, "curveMember": function (node, obj) { this.readChildNodes(node, obj); }, "MultiSurface": function (node, container) { var obj = { components: [] }; this.readChildNodes(node, obj); if (obj.components.length > 0) { container.components = [new OpenLayers.Geometry.MultiPolygon(obj.components)]; } }, "surfaceMember": function (node, obj) { this.readChildNodes(node, obj); }, "surfaceMembers": function (node, obj) { this.readChildNodes(node, obj); }, "pointMembers": function (node, obj) { this.readChildNodes(node, obj); }, "lineStringMembers": function (node, obj) { this.readChildNodes(node, obj); }, "polygonMembers": function (node, obj) { this.readChildNodes(node, obj); }, "geometryMembers": function (node, obj) { this.readChildNodes(node, obj); }, "Envelope": function (node, container) {
    var obj = { points: new Array(2) }; this.readChildNodes(node, obj); if (!container.components) { container.components = []; }
    var min = obj.points[0]; var max = obj.points[1]; container.components.push(new OpenLayers.Bounds(min.x, min.y, max.x, max.y));
}, "lowerCorner": function (node, container) { var obj = {}; this.readers.gml.pos.apply(this, [node, obj]); container.points[0] = obj.points[0]; }, "upperCorner": function (node, container) { var obj = {}; this.readers.gml.pos.apply(this, [node, obj]); container.points[1] = obj.points[0]; }
}, OpenLayers.Format.GML.Base.prototype.readers["gml"]), "feature": OpenLayers.Format.GML.Base.prototype.readers["feature"], "wfs": OpenLayers.Format.GML.Base.prototype.readers["wfs"]
}, write: function (features) {
    var name; if (OpenLayers.Util.isArray(features)) { name = "featureMembers"; } else { name = "featureMember"; }
    var root = this.writeNode("gml:" + name, features); this.setAttributeNS(root, this.namespaces["xsi"], "xsi:schemaLocation", this.schemaLocation); return OpenLayers.Format.XML.prototype.write.apply(this, [root]);
}, writers: { "gml": OpenLayers.Util.applyDefaults({ "featureMembers": function (features) {
    var node = this.createElementNSPlus("gml:featureMembers"); for (var i = 0, len = features.length; i < len; ++i) { this.writeNode("feature:_typeName", features[i], node); }
    return node;
}, "Point": function (geometry) { var node = this.createElementNSPlus("gml:Point"); this.writeNode("pos", geometry, node); return node; }, "pos": function (point) { var pos = (this.xy) ? (point.x + " " + point.y) : (point.y + " " + point.x); return this.createElementNSPlus("gml:pos", { value: pos }); }, "LineString": function (geometry) { var node = this.createElementNSPlus("gml:LineString"); this.writeNode("posList", geometry.components, node); return node; }, "Curve": function (geometry) { var node = this.createElementNSPlus("gml:Curve"); this.writeNode("segments", geometry, node); return node; }, "segments": function (geometry) { var node = this.createElementNSPlus("gml:segments"); this.writeNode("LineStringSegment", geometry, node); return node; }, "LineStringSegment": function (geometry) { var node = this.createElementNSPlus("gml:LineStringSegment"); this.writeNode("posList", geometry.components, node); return node; }, "posList": function (points) {
    var len = points.length; var parts = new Array(len); var point; for (var i = 0; i < len; ++i) { point = points[i]; if (this.xy) { parts[i] = point.x + " " + point.y; } else { parts[i] = point.y + " " + point.x; } }
    return this.createElementNSPlus("gml:posList", { value: parts.join(" ") });
}, "Surface": function (geometry) { var node = this.createElementNSPlus("gml:Surface"); this.writeNode("patches", geometry, node); return node; }, "patches": function (geometry) { var node = this.createElementNSPlus("gml:patches"); this.writeNode("PolygonPatch", geometry, node); return node; }, "PolygonPatch": function (geometry) {
    var node = this.createElementNSPlus("gml:PolygonPatch", { attributes: { interpolation: "planar"} }); this.writeNode("exterior", geometry.components[0], node); for (var i = 1, len = geometry.components.length; i < len; ++i) { this.writeNode("interior", geometry.components[i], node); }
    return node;
}, "Polygon": function (geometry) {
    var node = this.createElementNSPlus("gml:Polygon"); this.writeNode("exterior", geometry.components[0], node); for (var i = 1, len = geometry.components.length; i < len; ++i) { this.writeNode("interior", geometry.components[i], node); }
    return node;
}, "exterior": function (ring) { var node = this.createElementNSPlus("gml:exterior"); this.writeNode("LinearRing", ring, node); return node; }, "interior": function (ring) { var node = this.createElementNSPlus("gml:interior"); this.writeNode("LinearRing", ring, node); return node; }, "LinearRing": function (ring) { var node = this.createElementNSPlus("gml:LinearRing"); this.writeNode("posList", ring.components, node); return node; }, "MultiCurve": function (geometry) {
    var node = this.createElementNSPlus("gml:MultiCurve"); var components = geometry.components || [geometry]; for (var i = 0, len = components.length; i < len; ++i) { this.writeNode("curveMember", components[i], node); }
    return node;
}, "curveMember": function (geometry) {
    var node = this.createElementNSPlus("gml:curveMember"); if (this.curve) { this.writeNode("Curve", geometry, node); } else { this.writeNode("LineString", geometry, node); }
    return node;
}, "MultiSurface": function (geometry) {
    var node = this.createElementNSPlus("gml:MultiSurface"); var components = geometry.components || [geometry]; for (var i = 0, len = components.length; i < len; ++i) { this.writeNode("surfaceMember", components[i], node); }
    return node;
}, "surfaceMember": function (polygon) {
    var node = this.createElementNSPlus("gml:surfaceMember"); if (this.surface) { this.writeNode("Surface", polygon, node); } else { this.writeNode("Polygon", polygon, node); }
    return node;
}, "Envelope": function (bounds) {
    var node = this.createElementNSPlus("gml:Envelope"); this.writeNode("lowerCorner", bounds, node); this.writeNode("upperCorner", bounds, node); if (this.srsName) { node.setAttribute("srsName", this.srsName); }
    return node;
}, "lowerCorner": function (bounds) { var pos = (this.xy) ? (bounds.left + " " + bounds.bottom) : (bounds.bottom + " " + bounds.left); return this.createElementNSPlus("gml:lowerCorner", { value: pos }); }, "upperCorner": function (bounds) { var pos = (this.xy) ? (bounds.right + " " + bounds.top) : (bounds.top + " " + bounds.right); return this.createElementNSPlus("gml:upperCorner", { value: pos }); }
}, OpenLayers.Format.GML.Base.prototype.writers["gml"]), "feature": OpenLayers.Format.GML.Base.prototype.writers["feature"], "wfs": OpenLayers.Format.GML.Base.prototype.writers["wfs"]
}, setGeometryTypes: function () { this.geometryTypes = { "OpenLayers.Geometry.Point": "Point", "OpenLayers.Geometry.MultiPoint": "MultiPoint", "OpenLayers.Geometry.LineString": (this.curve === true) ? "Curve" : "LineString", "OpenLayers.Geometry.MultiLineString": (this.multiCurve === false) ? "MultiLineString" : "MultiCurve", "OpenLayers.Geometry.Polygon": (this.surface === true) ? "Surface" : "Polygon", "OpenLayers.Geometry.MultiPolygon": (this.multiSurface === false) ? "MultiPolygon" : "MultiSurface", "OpenLayers.Geometry.Collection": "GeometryCollection" }; }, CLASS_NAME: "OpenLayers.Format.GML.v3"
}); OpenLayers.Format.Filter.v1_1_0 = OpenLayers.Class(OpenLayers.Format.GML.v3, OpenLayers.Format.Filter.v1, { VERSION: "1.1.0", schemaLocation: "http://www.opengis.net/ogc/filter/1.1.0/filter.xsd", initialize: function (options) { OpenLayers.Format.GML.v3.prototype.initialize.apply(this, [options]); }, readers: { "ogc": OpenLayers.Util.applyDefaults({ "PropertyIsEqualTo": function (node, obj) { var matchCase = node.getAttribute("matchCase"); var filter = new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.EQUAL_TO, matchCase: !(matchCase === "false" || matchCase === "0") }); this.readChildNodes(node, filter); obj.filters.push(filter); }, "PropertyIsNotEqualTo": function (node, obj) { var matchCase = node.getAttribute("matchCase"); var filter = new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.NOT_EQUAL_TO, matchCase: !(matchCase === "false" || matchCase === "0") }); this.readChildNodes(node, filter); obj.filters.push(filter); }, "PropertyIsLike": function (node, obj) { var filter = new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.LIKE }); this.readChildNodes(node, filter); var wildCard = node.getAttribute("wildCard"); var singleChar = node.getAttribute("singleChar"); var esc = node.getAttribute("escapeChar"); filter.value2regex(wildCard, singleChar, esc); obj.filters.push(filter); } }, OpenLayers.Format.Filter.v1.prototype.readers["ogc"]), "gml": OpenLayers.Format.GML.v3.prototype.readers["gml"], "feature": OpenLayers.Format.GML.v3.prototype.readers["feature"] }, writers: { "ogc": OpenLayers.Util.applyDefaults({ "PropertyIsEqualTo": function (filter) { var node = this.createElementNSPlus("ogc:PropertyIsEqualTo", { attributes: { matchCase: filter.matchCase} }); this.writeNode("PropertyName", filter, node); this.writeOgcExpression(filter.value, node); return node; }, "PropertyIsNotEqualTo": function (filter) { var node = this.createElementNSPlus("ogc:PropertyIsNotEqualTo", { attributes: { matchCase: filter.matchCase} }); this.writeNode("PropertyName", filter, node); this.writeOgcExpression(filter.value, node); return node; }, "PropertyIsLike": function (filter) { var node = this.createElementNSPlus("ogc:PropertyIsLike", { attributes: { matchCase: filter.matchCase, wildCard: "*", singleChar: ".", escapeChar: "!"} }); this.writeNode("PropertyName", filter, node); this.writeNode("Literal", filter.regex2value(), node); return node; }, "BBOX": function (filter) {
    var node = this.createElementNSPlus("ogc:BBOX"); filter.property && this.writeNode("PropertyName", filter, node); var box = this.writeNode("gml:Envelope", filter.value); if (filter.projection) { box.setAttribute("srsName", filter.projection); }
    node.appendChild(box); return node;
}, "SortBy": function (sortProperties) {
    var node = this.createElementNSPlus("ogc:SortBy"); for (var i = 0, l = sortProperties.length; i < l; i++) { this.writeNode("ogc:SortProperty", sortProperties[i], node); }
    return node;
}, "SortProperty": function (sortProperty) { var node = this.createElementNSPlus("ogc:SortProperty"); this.writeNode("ogc:PropertyName", sortProperty, node); this.writeNode("ogc:SortOrder", (sortProperty.order == 'DESC') ? 'DESC' : 'ASC', node); return node; }, "SortOrder": function (value) { var node = this.createElementNSPlus("ogc:SortOrder", { value: value }); return node; }
}, OpenLayers.Format.Filter.v1.prototype.writers["ogc"]), "gml": OpenLayers.Format.GML.v3.prototype.writers["gml"], "feature": OpenLayers.Format.GML.v3.prototype.writers["feature"]
}, writeSpatial: function (filter, name) {
    var node = this.createElementNSPlus("ogc:" + name); this.writeNode("PropertyName", filter, node); if (filter.value instanceof OpenLayers.Filter.Function) { this.writeNode("Function", filter.value, node); } else {
        var child; if (filter.value instanceof OpenLayers.Geometry) { child = this.writeNode("feature:_geometry", filter.value).firstChild; } else { child = this.writeNode("gml:Envelope", filter.value); }
        if (filter.projection) { child.setAttribute("srsName", filter.projection); }
        node.appendChild(child);
    }
    return node;
}, CLASS_NAME: "OpenLayers.Format.Filter.v1_1_0"
}); OpenLayers.Format.OWSCommon = OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC, { defaultVersion: "1.0.0", getVersion: function (root, options) {
    var version = this.version; if (!version) {
        var uri = root.getAttribute("xmlns:ows"); if (uri && uri.substring(uri.lastIndexOf("/") + 1) === "1.1") { version = "1.1.0"; }
        if (!version) { version = this.defaultVersion; }
    }
    return version;
}, CLASS_NAME: "OpenLayers.Format.OWSCommon"
}); OpenLayers.Format.OWSCommon.v1 = OpenLayers.Class(OpenLayers.Format.XML, { regExes: { trimSpace: (/^\s*|\s*$/g), removeSpace: (/\s*/g), splitSpace: (/\s+/), trimComma: (/\s*,\s*/g) }, read: function (data, options) { options = OpenLayers.Util.applyDefaults(options, this.options); var ows = {}; this.readChildNodes(data, ows); return ows; }, readers: { "ows": { "Exception": function (node, exceptionReport) { var exception = { code: node.getAttribute('exceptionCode'), locator: node.getAttribute('locator'), texts: [] }; exceptionReport.exceptions.push(exception); this.readChildNodes(node, exception); }, "ExceptionText": function (node, exception) { var text = this.getChildValue(node); exception.texts.push(text); }, "ServiceIdentification": function (node, obj) { obj.serviceIdentification = {}; this.readChildNodes(node, obj.serviceIdentification); }, "Title": function (node, obj) { obj.title = this.getChildValue(node); }, "Abstract": function (node, serviceIdentification) { serviceIdentification["abstract"] = this.getChildValue(node); }, "Keywords": function (node, serviceIdentification) { serviceIdentification.keywords = {}; this.readChildNodes(node, serviceIdentification.keywords); }, "Keyword": function (node, keywords) { keywords[this.getChildValue(node)] = true; }, "ServiceType": function (node, serviceIdentification) { serviceIdentification.serviceType = { codeSpace: node.getAttribute('codeSpace'), value: this.getChildValue(node) }; }, "ServiceTypeVersion": function (node, serviceIdentification) { serviceIdentification.serviceTypeVersion = this.getChildValue(node); }, "Fees": function (node, serviceIdentification) { serviceIdentification.fees = this.getChildValue(node); }, "AccessConstraints": function (node, serviceIdentification) { serviceIdentification.accessConstraints = this.getChildValue(node); }, "ServiceProvider": function (node, obj) { obj.serviceProvider = {}; this.readChildNodes(node, obj.serviceProvider); }, "ProviderName": function (node, serviceProvider) { serviceProvider.providerName = this.getChildValue(node); }, "ProviderSite": function (node, serviceProvider) { serviceProvider.providerSite = this.getAttributeNS(node, this.namespaces.xlink, "href"); }, "ServiceContact": function (node, serviceProvider) { serviceProvider.serviceContact = {}; this.readChildNodes(node, serviceProvider.serviceContact); }, "IndividualName": function (node, serviceContact) { serviceContact.individualName = this.getChildValue(node); }, "PositionName": function (node, serviceContact) { serviceContact.positionName = this.getChildValue(node); }, "ContactInfo": function (node, serviceContact) { serviceContact.contactInfo = {}; this.readChildNodes(node, serviceContact.contactInfo); }, "Phone": function (node, contactInfo) { contactInfo.phone = {}; this.readChildNodes(node, contactInfo.phone); }, "Voice": function (node, phone) { phone.voice = this.getChildValue(node); }, "Address": function (node, contactInfo) { contactInfo.address = {}; this.readChildNodes(node, contactInfo.address); }, "DeliveryPoint": function (node, address) { address.deliveryPoint = this.getChildValue(node); }, "City": function (node, address) { address.city = this.getChildValue(node); }, "AdministrativeArea": function (node, address) { address.administrativeArea = this.getChildValue(node); }, "PostalCode": function (node, address) { address.postalCode = this.getChildValue(node); }, "Country": function (node, address) { address.country = this.getChildValue(node); }, "ElectronicMailAddress": function (node, address) { address.electronicMailAddress = this.getChildValue(node); }, "Role": function (node, serviceContact) { serviceContact.role = this.getChildValue(node); }, "OperationsMetadata": function (node, obj) { obj.operationsMetadata = {}; this.readChildNodes(node, obj.operationsMetadata); }, "Operation": function (node, operationsMetadata) { var name = node.getAttribute("name"); operationsMetadata[name] = {}; this.readChildNodes(node, operationsMetadata[name]); }, "DCP": function (node, operation) { operation.dcp = {}; this.readChildNodes(node, operation.dcp); }, "HTTP": function (node, dcp) { dcp.http = {}; this.readChildNodes(node, dcp.http); }, "Get": function (node, http) { http.get = this.getAttributeNS(node, this.namespaces.xlink, "href"); }, "Post": function (node, http) { http.post = this.getAttributeNS(node, this.namespaces.xlink, "href"); }, "Parameter": function (node, operation) {
    if (!operation.parameters) { operation.parameters = {}; }
    var name = node.getAttribute("name"); operation.parameters[name] = {}; this.readChildNodes(node, operation.parameters[name]);
}, "Value": function (node, allowedValues) { allowedValues[this.getChildValue(node)] = true; }, "OutputFormat": function (node, obj) { obj.formats.push({ value: this.getChildValue(node) }); this.readChildNodes(node, obj); }, "WGS84BoundingBox": function (node, obj) {
    var boundingBox = {}; boundingBox.crs = node.getAttribute("crs"); if (obj.BoundingBox) { obj.BoundingBox.push(boundingBox); } else { obj.projection = boundingBox.crs; boundingBox = obj; }
    this.readChildNodes(node, boundingBox);
}, "BoundingBox": function (node, obj) { this.readers['ows']['WGS84BoundingBox'].apply(this, [node, obj]); }, "LowerCorner": function (node, obj) { var str = this.getChildValue(node).replace(this.regExes.trimSpace, ""); str = str.replace(this.regExes.trimComma, ","); var pointList = str.split(this.regExes.splitSpace); obj.left = pointList[0]; obj.bottom = pointList[1]; }, "UpperCorner": function (node, obj) { var str = this.getChildValue(node).replace(this.regExes.trimSpace, ""); str = str.replace(this.regExes.trimComma, ","); var pointList = str.split(this.regExes.splitSpace); obj.right = pointList[0]; obj.top = pointList[1]; obj.bounds = new OpenLayers.Bounds(obj.left, obj.bottom, obj.right, obj.top); delete obj.left; delete obj.bottom; delete obj.right; delete obj.top; }, "Language": function (node, obj) { obj.language = this.getChildValue(node); }
}
}, writers: { "ows": { "BoundingBox": function (options) { var node = this.createElementNSPlus("ows:BoundingBox", { attributes: { crs: options.projection} }); this.writeNode("ows:LowerCorner", options, node); this.writeNode("ows:UpperCorner", options, node); return node; }, "LowerCorner": function (options) { var node = this.createElementNSPlus("ows:LowerCorner", { value: options.bounds.left + " " + options.bounds.bottom }); return node; }, "UpperCorner": function (options) { var node = this.createElementNSPlus("ows:UpperCorner", { value: options.bounds.right + " " + options.bounds.top }); return node; }, "Identifier": function (identifier) { var node = this.createElementNSPlus("ows:Identifier", { value: identifier }); return node; }, "Title": function (title) { var node = this.createElementNSPlus("ows:Title", { value: title }); return node; }, "Abstract": function (abstractValue) { var node = this.createElementNSPlus("ows:Abstract", { value: abstractValue }); return node; }, "OutputFormat": function (format) { var node = this.createElementNSPlus("ows:OutputFormat", { value: format }); return node; } } }, CLASS_NAME: "OpenLayers.Format.OWSCommon.v1"
}); OpenLayers.Format.OWSCommon.v1_0_0 = OpenLayers.Class(OpenLayers.Format.OWSCommon.v1, { namespaces: { ows: "http://www.opengis.net/ows", xlink: "http://www.w3.org/1999/xlink" }, readers: { "ows": OpenLayers.Util.applyDefaults({ "ExceptionReport": function (node, obj) { obj.success = false; obj.exceptionReport = { version: node.getAttribute('version'), language: node.getAttribute('language'), exceptions: [] }; this.readChildNodes(node, obj.exceptionReport); } }, OpenLayers.Format.OWSCommon.v1.prototype.readers.ows) }, writers: { "ows": OpenLayers.Format.OWSCommon.v1.prototype.writers.ows }, CLASS_NAME: "OpenLayers.Format.OWSCommon.v1_0_0" }); OpenLayers.Format.WFST.v1_1_0 = OpenLayers.Class(OpenLayers.Format.Filter.v1_1_0, OpenLayers.Format.WFST.v1, { version: "1.1.0", schemaLocations: { "wfs": "http://schemas.opengis.net/wfs/1.1.0/wfs.xsd" }, initialize: function (options) { OpenLayers.Format.Filter.v1_1_0.prototype.initialize.apply(this, [options]); OpenLayers.Format.WFST.v1.prototype.initialize.apply(this, [options]); }, readNode: function (node, obj, first) { return OpenLayers.Format.GML.v3.prototype.readNode.apply(this, [node, obj]); }, readers: { "wfs": OpenLayers.Util.applyDefaults({ "FeatureCollection": function (node, obj) { obj.numberOfFeatures = parseInt(node.getAttribute("numberOfFeatures")); OpenLayers.Format.WFST.v1.prototype.readers["wfs"]["FeatureCollection"].apply(this, arguments); }, "TransactionResponse": function (node, obj) { obj.insertIds = []; obj.success = false; this.readChildNodes(node, obj); }, "TransactionSummary": function (node, obj) { obj.success = true; }, "InsertResults": function (node, obj) { this.readChildNodes(node, obj); }, "Feature": function (node, container) { var obj = { fids: [] }; this.readChildNodes(node, obj); container.insertIds.push(obj.fids[0]); } }, OpenLayers.Format.WFST.v1.prototype.readers["wfs"]), "gml": OpenLayers.Format.GML.v3.prototype.readers["gml"], "feature": OpenLayers.Format.GML.v3.prototype.readers["feature"], "ogc": OpenLayers.Format.Filter.v1_1_0.prototype.readers["ogc"], "ows": OpenLayers.Format.OWSCommon.v1_0_0.prototype.readers["ows"] }, writers: { "wfs": OpenLayers.Util.applyDefaults({ "GetFeature": function (options) { var node = OpenLayers.Format.WFST.v1.prototype.writers["wfs"]["GetFeature"].apply(this, arguments); options && this.setAttributes(node, { resultType: options.resultType, startIndex: options.startIndex, count: options.count }); return node; }, "Query": function (options) {
    options = OpenLayers.Util.extend({ featureNS: this.featureNS, featurePrefix: this.featurePrefix, featureType: this.featureType, srsName: this.srsName }, options); var prefix = options.featurePrefix; var node = this.createElementNSPlus("wfs:Query", { attributes: { typeName: (prefix ? prefix + ":" : "") +
options.featureType, srsName: options.srsName
    }
    }); if (options.featureNS) { node.setAttribute("xmlns:" + prefix, options.featureNS); }
    if (options.propertyNames) { for (var i = 0, len = options.propertyNames.length; i < len; i++) { this.writeNode("wfs:PropertyName", { property: options.propertyNames[i] }, node); } }
    if (options.filter) { this.setFilterProperty(options.filter); this.writeNode("ogc:Filter", options.filter, node); }
    return node;
}, "PropertyName": function (obj) { return this.createElementNSPlus("wfs:PropertyName", { value: obj.property }); }
}, OpenLayers.Format.WFST.v1.prototype.writers["wfs"]), "gml": OpenLayers.Format.GML.v3.prototype.writers["gml"], "feature": OpenLayers.Format.GML.v3.prototype.writers["feature"], "ogc": OpenLayers.Format.Filter.v1_1_0.prototype.writers["ogc"]
}, CLASS_NAME: "OpenLayers.Format.WFST.v1_1_0"
}); OpenLayers.Format.GeoJSON = OpenLayers.Class(OpenLayers.Format.JSON, { ignoreExtraDims: false, read: function (json, type, filter) {
    type = (type) ? type : "FeatureCollection"; var results = null; var obj = null; if (typeof json == "string") { obj = OpenLayers.Format.JSON.prototype.read.apply(this, [json, filter]); } else { obj = json; }
    if (!obj) { OpenLayers.Console.error("Bad JSON: " + json); } else if (typeof (obj.type) != "string") { OpenLayers.Console.error("Bad GeoJSON - no type: " + json); } else if (this.isValidType(obj, type)) {
        switch (type) {
            case "Geometry": try { results = this.parseGeometry(obj); } catch (err) { OpenLayers.Console.error(err); }
                break; case "Feature": try { results = this.parseFeature(obj); results.type = "Feature"; } catch (err) { OpenLayers.Console.error(err); }
                break; case "FeatureCollection": results = []; switch (obj.type) {
                    case "Feature": try { results.push(this.parseFeature(obj)); } catch (err) { results = null; OpenLayers.Console.error(err); }
                        break; case "FeatureCollection": for (var i = 0, len = obj.features.length; i < len; ++i) { try { results.push(this.parseFeature(obj.features[i])); } catch (err) { results = null; OpenLayers.Console.error(err); } }
                        break; default: try { var geom = this.parseGeometry(obj); results.push(new OpenLayers.Feature.Vector(geom)); } catch (err) { results = null; OpenLayers.Console.error(err); }
                }
                break;
        }
    }
    return results;
}, isValidType: function (obj, type) {
    var valid = false; switch (type) {
        case "Geometry": if (OpenLayers.Util.indexOf(["Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "Box", "GeometryCollection"], obj.type) == -1) {
                OpenLayers.Console.error("Unsupported geometry type: " +
obj.type);
            } else { valid = true; }
            break; case "FeatureCollection": valid = true; break; default: if (obj.type == type) { valid = true; } else {
                OpenLayers.Console.error("Cannot convert types from " +
obj.type + " to " + type);
            }
    }
    return valid;
}, parseFeature: function (obj) {
    var feature, geometry, attributes, bbox; attributes = (obj.properties) ? obj.properties : {}; bbox = (obj.geometry && obj.geometry.bbox) || obj.bbox; try { geometry = this.parseGeometry(obj.geometry); } catch (err) { throw err; }
    feature = new OpenLayers.Feature.Vector(geometry, attributes); if (bbox) { feature.bounds = OpenLayers.Bounds.fromArray(bbox); }
    if (obj.id) { feature.fid = obj.id; }
    return feature;
}, parseGeometry: function (obj) {
    if (obj == null) { return null; }
    var geometry, collection = false; if (obj.type == "GeometryCollection") {
        if (!(OpenLayers.Util.isArray(obj.geometries))) { throw "GeometryCollection must have geometries array: " + obj; }
        var numGeom = obj.geometries.length; var components = new Array(numGeom); for (var i = 0; i < numGeom; ++i) { components[i] = this.parseGeometry.apply(this, [obj.geometries[i]]); }
        geometry = new OpenLayers.Geometry.Collection(components); collection = true;
    } else {
        if (!(OpenLayers.Util.isArray(obj.coordinates))) { throw "Geometry must have coordinates array: " + obj; }
        if (!this.parseCoords[obj.type.toLowerCase()]) { throw "Unsupported geometry type: " + obj.type; }
        try { geometry = this.parseCoords[obj.type.toLowerCase()].apply(this, [obj.coordinates]); } catch (err) { throw err; }
    }
    if (this.internalProjection && this.externalProjection && !collection) { geometry.transform(this.externalProjection, this.internalProjection); }
    return geometry;
}, parseCoords: { "point": function (array) {
    if (this.ignoreExtraDims == false && array.length != 2) { throw "Only 2D points are supported: " + array; }
    return new OpenLayers.Geometry.Point(array[0], array[1]);
}, "multipoint": function (array) {
    var points = []; var p = null; for (var i = 0, len = array.length; i < len; ++i) {
        try { p = this.parseCoords["point"].apply(this, [array[i]]); } catch (err) { throw err; }
        points.push(p);
    }
    return new OpenLayers.Geometry.MultiPoint(points);
}, "linestring": function (array) {
    var points = []; var p = null; for (var i = 0, len = array.length; i < len; ++i) {
        try { p = this.parseCoords["point"].apply(this, [array[i]]); } catch (err) { throw err; }
        points.push(p);
    }
    return new OpenLayers.Geometry.LineString(points);
}, "multilinestring": function (array) {
    var lines = []; var l = null; for (var i = 0, len = array.length; i < len; ++i) {
        try { l = this.parseCoords["linestring"].apply(this, [array[i]]); } catch (err) { throw err; }
        lines.push(l);
    }
    return new OpenLayers.Geometry.MultiLineString(lines);
}, "polygon": function (array) {
    var rings = []; var r, l; for (var i = 0, len = array.length; i < len; ++i) {
        try { l = this.parseCoords["linestring"].apply(this, [array[i]]); } catch (err) { throw err; }
        r = new OpenLayers.Geometry.LinearRing(l.components); rings.push(r);
    }
    return new OpenLayers.Geometry.Polygon(rings);
}, "multipolygon": function (array) {
    var polys = []; var p = null; for (var i = 0, len = array.length; i < len; ++i) {
        try { p = this.parseCoords["polygon"].apply(this, [array[i]]); } catch (err) { throw err; }
        polys.push(p);
    }
    return new OpenLayers.Geometry.MultiPolygon(polys);
}, "box": function (array) {
    if (array.length != 2) { throw "GeoJSON box coordinates must have 2 elements"; }
    return new OpenLayers.Geometry.Polygon([new OpenLayers.Geometry.LinearRing([new OpenLayers.Geometry.Point(array[0][0], array[0][1]), new OpenLayers.Geometry.Point(array[1][0], array[0][1]), new OpenLayers.Geometry.Point(array[1][0], array[1][1]), new OpenLayers.Geometry.Point(array[0][0], array[1][1]), new OpenLayers.Geometry.Point(array[0][0], array[0][1])])]);
}
}, write: function (obj, pretty) {
    var geojson = { "type": null }; if (OpenLayers.Util.isArray(obj)) {
        geojson.type = "FeatureCollection"; var numFeatures = obj.length; geojson.features = new Array(numFeatures); for (var i = 0; i < numFeatures; ++i) {
            var element = obj[i]; if (!element instanceof OpenLayers.Feature.Vector) { var msg = "FeatureCollection only supports collections " + "of features: " + element; throw msg; }
            geojson.features[i] = this.extract.feature.apply(this, [element]);
        }
    } else if (obj.CLASS_NAME.indexOf("OpenLayers.Geometry") == 0) { geojson = this.extract.geometry.apply(this, [obj]); } else if (obj instanceof OpenLayers.Feature.Vector) { geojson = this.extract.feature.apply(this, [obj]); if (obj.layer && obj.layer.projection) { geojson.crs = this.createCRSObject(obj); } }
    return OpenLayers.Format.JSON.prototype.write.apply(this, [geojson, pretty]);
}, createCRSObject: function (object) {
    var proj = object.layer.projection.toString(); var crs = {}; if (proj.match(/epsg:/i)) { var code = parseInt(proj.substring(proj.indexOf(":") + 1)); if (code == 4326) { crs = { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84"} }; } else { crs = { "type": "name", "properties": { "name": "EPSG:" + code} }; } }
    return crs;
}, extract: { 'feature': function (feature) {
    var geom = this.extract.geometry.apply(this, [feature.geometry]); var json = { "type": "Feature", "properties": feature.attributes, "geometry": geom }; if (feature.fid != null) { json.id = feature.fid; }
    return json;
}, 'geometry': function (geometry) {
    if (geometry == null) { return null; }
    if (this.internalProjection && this.externalProjection) { geometry = geometry.clone(); geometry.transform(this.internalProjection, this.externalProjection); }
    var geometryType = geometry.CLASS_NAME.split('.')[2]; var data = this.extract[geometryType.toLowerCase()].apply(this, [geometry]); var json; if (geometryType == "Collection") { json = { "type": "GeometryCollection", "geometries": data }; } else { json = { "type": geometryType, "coordinates": data }; }
    return json;
}, 'point': function (point) { return [point.x, point.y]; }, 'multipoint': function (multipoint) {
    var array = []; for (var i = 0, len = multipoint.components.length; i < len; ++i) { array.push(this.extract.point.apply(this, [multipoint.components[i]])); }
    return array;
}, 'linestring': function (linestring) {
    var array = []; for (var i = 0, len = linestring.components.length; i < len; ++i) { array.push(this.extract.point.apply(this, [linestring.components[i]])); }
    return array;
}, 'multilinestring': function (multilinestring) {
    var array = []; for (var i = 0, len = multilinestring.components.length; i < len; ++i) { array.push(this.extract.linestring.apply(this, [multilinestring.components[i]])); }
    return array;
}, 'polygon': function (polygon) {
    var array = []; for (var i = 0, len = polygon.components.length; i < len; ++i) { array.push(this.extract.linestring.apply(this, [polygon.components[i]])); }
    return array;
}, 'multipolygon': function (multipolygon) {
    var array = []; for (var i = 0, len = multipolygon.components.length; i < len; ++i) { array.push(this.extract.polygon.apply(this, [multipolygon.components[i]])); }
    return array;
}, 'collection': function (collection) {
    var len = collection.components.length; var array = new Array(len); for (var i = 0; i < len; ++i) { array[i] = this.extract.geometry.apply(this, [collection.components[i]]); }
    return array;
}
}, CLASS_NAME: "OpenLayers.Format.GeoJSON"
}); OpenLayers.Protocol.Script = OpenLayers.Class(OpenLayers.Protocol, { url: null, params: null, callback: null, scope: null, format: null, callbackKey: "callback", callbackPrefix: "", pendingRequests: null, srsInBBOX: false, initialize: function (options) {
    options = options || {}; this.params = {}; this.pendingRequests = {}; OpenLayers.Protocol.prototype.initialize.apply(this, arguments); if (!this.format) { this.format = new OpenLayers.Format.GeoJSON(); }
    if (!this.filterToParams && OpenLayers.Format.QueryStringFilter) { var format = new OpenLayers.Format.QueryStringFilter({ srsInBBOX: this.srsInBBOX }); this.filterToParams = function (filter, params) { return format.write(filter, params); } }
}, read: function (options) {
    OpenLayers.Protocol.prototype.read.apply(this, arguments); options = OpenLayers.Util.applyDefaults(options, this.options); options.params = OpenLayers.Util.applyDefaults(options.params, this.options.params); if (options.filter && this.filterToParams) { options.params = this.filterToParams(options.filter, options.params); }
    var response = new OpenLayers.Protocol.Response({ requestType: "read" }); var request = this.createRequest(options.url, options.params, OpenLayers.Function.bind(function (data) { response.data = data; this.handleRead(response, options); }, this)); response.priv = request; return response;
}, createRequest: function (url, params, callback) { var id = OpenLayers.Protocol.Script.register(callback); var name = "OpenLayers.Protocol.Script.registry[" + id + "]"; params = OpenLayers.Util.extend({}, params); params[this.callbackKey] = this.callbackPrefix + name; url = OpenLayers.Util.urlAppend(url, OpenLayers.Util.getParameterString(params)); var script = document.createElement("script"); script.type = "text/javascript"; script.src = url; script.id = "OpenLayers_Protocol_Script_" + id; this.pendingRequests[script.id] = script; var head = document.getElementsByTagName("head")[0]; head.appendChild(script); return script; }, destroyRequest: function (script) { OpenLayers.Protocol.Script.unregister(script.id.split("_").pop()); delete this.pendingRequests[script.id]; if (script.parentNode) { script.parentNode.removeChild(script); } }, handleRead: function (response, options) { this.handleResponse(response, options); }, handleResponse: function (response, options) {
    if (options.callback) {
        if (response.data) { response.features = this.parseFeatures(response.data); response.code = OpenLayers.Protocol.Response.SUCCESS; } else { response.code = OpenLayers.Protocol.Response.FAILURE; }
        this.destroyRequest(response.priv); options.callback.call(options.scope, response);
    }
}, parseFeatures: function (data) { return this.format.read(data); }, abort: function (response) { if (response) { this.destroyRequest(response.priv); } else { for (var key in this.pendingRequests) { this.destroyRequest(this.pendingRequests[key]); } } }, destroy: function () { this.abort(); delete this.params; delete this.format; OpenLayers.Protocol.prototype.destroy.apply(this); }, CLASS_NAME: "OpenLayers.Protocol.Script"
}); (function () { var o = OpenLayers.Protocol.Script; var counter = 0; o.registry = []; o.register = function (callback) { var id = ++counter; o.registry[id] = function () { o.unregister(id); callback.apply(this, arguments); }; return id; }; o.unregister = function (id) { delete o.registry[id]; }; })(); OpenLayers.Format.CSWGetRecords = function (options) {
    options = OpenLayers.Util.applyDefaults(options, OpenLayers.Format.CSWGetRecords.DEFAULTS); var cls = OpenLayers.Format.CSWGetRecords["v" + options.version.replace(/\./g, "_")]; if (!cls) { throw "Unsupported CSWGetRecords version: " + options.version; }
    return new cls(options);
}; OpenLayers.Format.CSWGetRecords.DEFAULTS = { "version": "2.0.2" }; OpenLayers.Control.Panel = OpenLayers.Class(OpenLayers.Control, { controls: null, autoActivate: true, defaultControl: null, saveState: false, allowDepress: false, activeState: null, initialize: function (options) { OpenLayers.Control.prototype.initialize.apply(this, [options]); this.controls = []; this.activeState = {}; }, destroy: function () {
    OpenLayers.Control.prototype.destroy.apply(this, arguments); for (var ctl, i = this.controls.length - 1; i >= 0; i--) {
        ctl = this.controls[i]; if (ctl.events) { ctl.events.un({ activate: this.iconOn, deactivate: this.iconOff }); }
        OpenLayers.Event.stopObservingElement(ctl.panel_div); ctl.panel_div = null;
    }
    this.activeState = null;
}, activate: function () {
    if (OpenLayers.Control.prototype.activate.apply(this, arguments)) {
        var control; for (var i = 0, len = this.controls.length; i < len; i++) { control = this.controls[i]; if (control === this.defaultControl || (this.saveState && this.activeState[control.id])) { control.activate(); } }
        if (this.saveState === true) { this.defaultControl = null; }
        this.redraw(); return true;
    } else { return false; }
}, deactivate: function () {
    if (OpenLayers.Control.prototype.deactivate.apply(this, arguments)) {
        var control; for (var i = 0, len = this.controls.length; i < len; i++) { control = this.controls[i]; this.activeState[control.id] = control.deactivate(); }
        this.redraw(); return true;
    } else { return false; }
}, draw: function () { OpenLayers.Control.prototype.draw.apply(this, arguments); this.addControlsToMap(this.controls); return this.div; }, redraw: function () {
    for (var l = this.div.childNodes.length, i = l - 1; i >= 0; i--) { this.div.removeChild(this.div.childNodes[i]); }
    this.div.innerHTML = ""; if (this.active) { for (var i = 0, len = this.controls.length; i < len; i++) { this.div.appendChild(this.controls[i].panel_div); } }
}, activateControl: function (control) {
    if (!this.active) { return false; }
    if (control.type == OpenLayers.Control.TYPE_BUTTON) { control.trigger(); return; }
    if (control.type == OpenLayers.Control.TYPE_TOGGLE) {
        if (control.active) { control.deactivate(); } else { control.activate(); }
        return;
    }
    if (this.allowDepress && control.active) { control.deactivate(); } else {
        var c; for (var i = 0, len = this.controls.length; i < len; i++) { c = this.controls[i]; if (c != control && (c.type === OpenLayers.Control.TYPE_TOOL || c.type == null)) { c.deactivate(); } }
        control.activate();
    }
}, addControls: function (controls) {
    if (!(OpenLayers.Util.isArray(controls))) { controls = [controls]; }
    this.controls = this.controls.concat(controls); for (var i = 0, len = controls.length; i < len; i++) {
        var element = document.createElement("div"); element.className = controls[i].displayClass + "ItemInactive"; controls[i].panel_div = element; if (controls[i].title != "") { controls[i].panel_div.title = controls[i].title; }
        OpenLayers.Event.observe(controls[i].panel_div, "click", OpenLayers.Function.bind(this.onClick, this, controls[i])); OpenLayers.Event.observe(controls[i].panel_div, "dblclick", OpenLayers.Function.bind(this.onDoubleClick, this, controls[i])); OpenLayers.Event.observe(controls[i].panel_div, "mousedown", OpenLayers.Function.bindAsEventListener(OpenLayers.Event.stop));
    }
    if (this.map) { this.addControlsToMap(controls); this.redraw(); }
}, addControlsToMap: function (controls) {
    var control; for (var i = 0, len = controls.length; i < len; i++) {
        control = controls[i]; if (control.autoActivate === true) { control.autoActivate = false; this.map.addControl(control); control.autoActivate = true; } else { this.map.addControl(control); control.deactivate(); }
        control.events.on({ activate: this.iconOn, deactivate: this.iconOff });
    }
}, iconOn: function () { var d = this.panel_div; d.className = d.className.replace(/ItemInactive$/, "ItemActive"); }, iconOff: function () { var d = this.panel_div; d.className = d.className.replace(/ItemActive$/, "ItemInactive"); }, onClick: function (ctrl, evt) { OpenLayers.Event.stop(evt ? evt : window.event); this.activateControl(ctrl); }, onDoubleClick: function (ctrl, evt) { OpenLayers.Event.stop(evt ? evt : window.event); }, getControlsBy: function (property, match) { var test = (typeof match.test == "function"); var found = OpenLayers.Array.filter(this.controls, function (item) { return item[property] == match || (test && match.test(item[property])); }); return found; }, getControlsByName: function (match) { return this.getControlsBy("name", match); }, getControlsByClass: function (match) { return this.getControlsBy("CLASS_NAME", match); }, CLASS_NAME: "OpenLayers.Control.Panel"
}); OpenLayers.Control.ZoomIn = OpenLayers.Class(OpenLayers.Control, { type: OpenLayers.Control.TYPE_BUTTON, trigger: function () { this.map.zoomIn(); }, CLASS_NAME: "OpenLayers.Control.ZoomIn" }); OpenLayers.Control.ZoomOut = OpenLayers.Class(OpenLayers.Control, { type: OpenLayers.Control.TYPE_BUTTON, trigger: function () { this.map.zoomOut(); }, CLASS_NAME: "OpenLayers.Control.ZoomOut" }); OpenLayers.Control.ZoomToMaxExtent = OpenLayers.Class(OpenLayers.Control, { type: OpenLayers.Control.TYPE_BUTTON, trigger: function () { if (this.map) { this.map.zoomToMaxExtent(); } }, CLASS_NAME: "OpenLayers.Control.ZoomToMaxExtent" }); OpenLayers.Control.ZoomPanel = OpenLayers.Class(OpenLayers.Control.Panel, { initialize: function (options) { OpenLayers.Control.Panel.prototype.initialize.apply(this, [options]); this.addControls([new OpenLayers.Control.ZoomIn(), new OpenLayers.Control.ZoomToMaxExtent(), new OpenLayers.Control.ZoomOut()]); }, CLASS_NAME: "OpenLayers.Control.ZoomPanel" });


OpenLayers.Layer.HTTPRequest = OpenLayers.Class(OpenLayers.Layer, { URL_HASH_FACTOR: (Math.sqrt(5) - 1) / 2, url: null, params: null, reproject: false, initialize: function (name, url, params, options) { OpenLayers.Layer.prototype.initialize.apply(this, [name, options]); this.url = url; this.params = OpenLayers.Util.extend({}, params); }, destroy: function () { this.url = null; this.params = null; OpenLayers.Layer.prototype.destroy.apply(this, arguments); }, clone: function (obj) {
    if (obj == null) { obj = new OpenLayers.Layer.HTTPRequest(this.name, this.url, this.params, this.getOptions()); }
    obj = OpenLayers.Layer.prototype.clone.apply(this, [obj]); return obj;
}, setUrl: function (newUrl) { this.url = newUrl; }, mergeNewParams: function (newParams) {
    this.params = OpenLayers.Util.extend(this.params, newParams); var ret = this.redraw(); if (this.map != null) { this.map.events.triggerEvent("changelayer", { layer: this, property: "params" }); }
    return ret;
}, redraw: function (force) { if (force) { return this.mergeNewParams({ "_olSalt": Math.random() }); } else { return OpenLayers.Layer.prototype.redraw.apply(this, []); } },
    selectUrl: function (paramString, urls) {
        var product = 1;
        for (var i = 0, len = paramString.length; i < len; i++) {
            product *= paramString.charCodeAt(i) * this.URL_HASH_FACTOR;
            product -= Math.floor(product);
        }
        return urls[Math.floor(product * urls.length)];
    }, getFullRequestString: function (newParams, altUrl) {
        var url = altUrl || this.url; var allParams = OpenLayers.Util.extend({}, this.params); allParams = OpenLayers.Util.extend(allParams, newParams); var paramsString = OpenLayers.Util.getParameterString(allParams); if (OpenLayers.Util.isArray(url)) { url = this.selectUrl(paramsString, url); }
        var urlParams = OpenLayers.Util.upperCaseObject(OpenLayers.Util.getParameters(url)); for (var key in allParams) { if (key.toUpperCase() in urlParams) { delete allParams[key]; } }
        paramsString = OpenLayers.Util.getParameterString(allParams); return OpenLayers.Util.urlAppend(url, paramsString);
    }, CLASS_NAME: "OpenLayers.Layer.HTTPRequest"
});


OpenLayers.Layer.Grid = OpenLayers.Class(OpenLayers.Layer.HTTPRequest, {
    tileSize: null,
    tileOriginCorner: "bl", tileOrigin: null, tileOptions: null, grid: null, singleTile: false, ratio: 1.5, buffer: 0, numLoadingTiles: 0, tileLoadingDelay: 100, timerId: null, initialize: function (name, url, params, options) { OpenLayers.Layer.HTTPRequest.prototype.initialize.apply(this, arguments); this.events.addEventType("tileloaded"); this.grid = []; this._moveGriddedTiles = OpenLayers.Function.bind(this.moveGriddedTiles, this); }, removeMap: function (map) { if (this.timerId != null) { window.clearTimeout(this.timerId); this.timerId = null; } }, destroy: function () { this.clearGrid(); this.grid = null; this.tileSize = null; OpenLayers.Layer.HTTPRequest.prototype.destroy.apply(this, arguments); }, clearGrid: function () {
        if (this.grid) {
            for (var iRow = 0, len = this.grid.length; iRow < len; iRow++) { var row = this.grid[iRow]; for (var iCol = 0, clen = row.length; iCol < clen; iCol++) { var tile = row[iCol]; this.removeTileMonitoringHooks(tile); tile.destroy(); } }
            this.grid = [];
        }
    }, clone: function (obj) {
        if (obj == null) { obj = new OpenLayers.Layer.Grid(this.name, this.url, this.params, this.getOptions()); }
        obj = OpenLayers.Layer.HTTPRequest.prototype.clone.apply(this, [obj]); if (this.tileSize != null) { obj.tileSize = this.tileSize.clone(); }
        obj.grid = []; return obj;
    }, moveTo: function (bounds, zoomChanged, dragging) { OpenLayers.Layer.HTTPRequest.prototype.moveTo.apply(this, arguments); bounds = bounds || this.map.getExtent(); if (bounds != null) { var forceReTile = !this.grid.length || zoomChanged; var tilesBounds = this.getTilesBounds(); if (this.singleTile) { if (forceReTile || (!dragging && !tilesBounds.containsBounds(bounds))) { this.initSingleTile(bounds); } } else { if (forceReTile || !tilesBounds.containsBounds(bounds, true)) { this.initGriddedTiles(bounds); } else { this.scheduleMoveGriddedTiles(); } } } }, moveByPx: function (dx, dy) { if (!this.singleTile) { this.scheduleMoveGriddedTiles(); } }, scheduleMoveGriddedTiles: function () {
        if (this.timerId != null) { window.clearTimeout(this.timerId); }
        this.timerId = window.setTimeout(this._moveGriddedTiles, this.tileLoadingDelay);
    }, setTileSize: function (size) {
        if (this.singleTile) { size = this.map.getSize(); size.h = parseInt(size.h * this.ratio); size.w = parseInt(size.w * this.ratio); }
        OpenLayers.Layer.HTTPRequest.prototype.setTileSize.apply(this, [size]);
    }, getGridBounds: function () { var msg = "The getGridBounds() function is deprecated. It will be " + "removed in 3.0. Please use getTilesBounds() instead."; OpenLayers.Console.warn(msg); return this.getTilesBounds(); }, getTilesBounds: function () {
        var bounds = null; if (this.grid.length) { var bottom = this.grid.length - 1; var bottomLeftTile = this.grid[bottom][0]; var right = this.grid[0].length - 1; var topRightTile = this.grid[0][right]; bounds = new OpenLayers.Bounds(bottomLeftTile.bounds.left, bottomLeftTile.bounds.bottom, topRightTile.bounds.right, topRightTile.bounds.top); }
        return bounds;
    }, initSingleTile: function (bounds) {
        var center = bounds.getCenterLonLat(); var tileWidth = bounds.getWidth() * this.ratio; var tileHeight = bounds.getHeight() * this.ratio; var tileBounds = new OpenLayers.Bounds(center.lon - (tileWidth / 2), center.lat - (tileHeight / 2), center.lon + (tileWidth / 2), center.lat + (tileHeight / 2)); var ul = new OpenLayers.LonLat(tileBounds.left, tileBounds.top); var px = this.map.getLayerPxFromLonLat(ul); if (!this.grid.length) { this.grid[0] = []; }
        var tile = this.grid[0][0]; if (!tile) { tile = this.addTile(tileBounds, px); this.addTileMonitoringHooks(tile); tile.draw(); this.grid[0][0] = tile; } else { tile.moveTo(tileBounds, px); }
        this.removeExcessTiles(1, 1);
    }, calculateGridLayout: function (bounds, origin, resolution) { var tilelon = resolution * this.tileSize.w; var tilelat = resolution * this.tileSize.h; var offsetlon = bounds.left - origin.lon; var tilecol = Math.floor(offsetlon / tilelon) - this.buffer; var tilecolremain = offsetlon / tilelon - tilecol; var tileoffsetx = -tilecolremain * this.tileSize.w; var tileoffsetlon = origin.lon + tilecol * tilelon; var offsetlat = bounds.top - (origin.lat + tilelat); var tilerow = Math.ceil(offsetlat / tilelat) + this.buffer; var tilerowremain = tilerow - offsetlat / tilelat; var tileoffsety = -tilerowremain * this.tileSize.h; var tileoffsetlat = origin.lat + tilerow * tilelat; return { tilelon: tilelon, tilelat: tilelat, tileoffsetlon: tileoffsetlon, tileoffsetlat: tileoffsetlat, tileoffsetx: tileoffsetx, tileoffsety: tileoffsety }; }, getTileOrigin: function () {
        var origin = this.tileOrigin; if (!origin) { var extent = this.getMaxExtent(); var edges = ({ "tl": ["left", "top"], "tr": ["right", "top"], "bl": ["left", "bottom"], "br": ["right", "bottom"] })[this.tileOriginCorner]; origin = new OpenLayers.LonLat(extent[edges[0]], extent[edges[1]]); }
        return origin;
    },
    initGriddedTiles: function (bounds) {
        var viewSize = this.map.getSize();
        var minRows = Math.ceil(viewSize.h / this.tileSize.h) +
Math.max(1, 2 * this.buffer);
        var minCols = Math.ceil(viewSize.w / this.tileSize.w) +
Math.max(1, 2 * this.buffer);
        var origin = this.getTileOrigin();
        var resolution = this.map.getResolution();
        var tileLayout = this.calculateGridLayout(bounds, origin, resolution);
        var tileoffsetx = Math.round(tileLayout.tileoffsetx);
        var tileoffsety = Math.round(tileLayout.tileoffsety);
        var tileoffsetlon = tileLayout.tileoffsetlon;
        var tileoffsetlat = tileLayout.tileoffsetlat;
        var tilelon = tileLayout.tilelon;
        var tilelat = tileLayout.tilelat;
        this.origin = new OpenLayers.Pixel(tileoffsetx, tileoffsety);
        var startX = tileoffsetx;
        var startLon = tileoffsetlon;
        var rowidx = 0;
        var layerContainerDivLeft = parseInt(this.map.layerContainerDiv.style.left);
        var layerContainerDivTop = parseInt(this.map.layerContainerDiv.style.top);
        do {
            var row = this.grid[rowidx++];
            if (!row) {
                row = [];
                this.grid.push(row);
            }
            tileoffsetlon = startLon;
            tileoffsetx = startX;
            var colidx = 0;
            do {
                var tileBounds = new OpenLayers.Bounds(tileoffsetlon, tileoffsetlat, tileoffsetlon + tilelon, tileoffsetlat + tilelat);
                var x = tileoffsetx;
                x -= layerContainerDivLeft;
                var y = tileoffsety;
                y -= layerContainerDivTop;
                var px = new OpenLayers.Pixel(x, y);
                var tile = row[colidx++];
                if (!tile) {
                    tile = this.addTile(tileBounds, px);
                    this.addTileMonitoringHooks(tile);
                    row.push(tile);
                } else {
                    tile.moveTo(tileBounds, px, false);
                }
                tileoffsetlon += tilelon;
                tileoffsetx += this.tileSize.w;
            } while ((tileoffsetlon <= bounds.right + tilelon * this.buffer) || colidx < minCols);
            tileoffsetlat -= tilelat;
            tileoffsety += this.tileSize.h;
        } while ((tileoffsetlat >= bounds.bottom - tilelat * this.buffer) || rowidx < minRows);
        this.removeExcessTiles(rowidx, colidx);
        this.spiralTileLoad();
    },
    getMaxExtent: function () {
        return this.maxExtent;
    },
    spiralTileLoad: function () {
        var tileQueue = [];
        var directions = ["right", "down", "left", "up"];
        var iRow = 0;
        var iCell = -1;
        var direction = OpenLayers.Util.indexOf(directions, "right");
        var directionsTried = 0;
        while (directionsTried < directions.length) {
            var testRow = iRow; var testCell = iCell; switch (directions[direction]) { case "right": testCell++; break; case "down": testRow++; break; case "left": testCell--; break; case "up": testRow--; break; }
            var tile = null; if ((testRow < this.grid.length) && (testRow >= 0) && (testCell < this.grid[0].length) && (testCell >= 0)) { tile = this.grid[testRow][testCell]; }
            if ((tile != null) && (!tile.queued)) { tileQueue.unshift(tile); tile.queued = true; directionsTried = 0; iRow = testRow; iCell = testCell; } else { direction = (direction + 1) % 4; directionsTried++; }
        }
        for (var i = 0, len = tileQueue.length; i < len; i++) {
            var tile = tileQueue[i];
            tile.draw();
            tile.queued = false;
        }
    }, addTile: function (bounds, position) { return new OpenLayers.Tile.Image(this, position, bounds, null, this.tileSize, this.tileOptions); }, addTileMonitoringHooks: function (tile) {
        tile.onLoadStart = function () {
            if (this.numLoadingTiles == 0) { this.events.triggerEvent("loadstart"); }
            this.numLoadingTiles++;
        }; tile.events.register("loadstart", this, tile.onLoadStart); tile.onLoadEnd = function () { this.numLoadingTiles--; this.events.triggerEvent("tileloaded"); if (this.numLoadingTiles == 0) { this.events.triggerEvent("loadend"); } }; tile.events.register("loadend", this, tile.onLoadEnd); tile.events.register("unload", this, tile.onLoadEnd);
    }, removeTileMonitoringHooks: function (tile) { tile.unload(); tile.events.un({ "loadstart": tile.onLoadStart, "loadend": tile.onLoadEnd, "unload": tile.onLoadEnd, scope: this }); }, moveGriddedTiles: function () {
        var shifted = true; var buffer = this.buffer || 1; var tlLayer = this.grid[0][0].position; var offsetX = parseInt(this.map.layerContainerDiv.style.left); var offsetY = parseInt(this.map.layerContainerDiv.style.top); var tlViewPort = tlLayer.add(offsetX, offsetY); if (tlViewPort.x > -this.tileSize.w * (buffer - 1)) { this.shiftColumn(true); } else if (tlViewPort.x < -this.tileSize.w * buffer) { this.shiftColumn(false); } else if (tlViewPort.y > -this.tileSize.h * (buffer - 1)) { this.shiftRow(true); } else if (tlViewPort.y < -this.tileSize.h * buffer) { this.shiftRow(false); } else { shifted = false; }
        if (shifted) { this.timerId = window.setTimeout(this._moveGriddedTiles, 0); }
    }, shiftRow: function (prepend) {
        var modelRowIndex = (prepend) ? 0 : (this.grid.length - 1); var grid = this.grid; var modelRow = grid[modelRowIndex]; var resolution = this.map.getResolution(); var deltaY = (prepend) ? -this.tileSize.h : this.tileSize.h; var deltaLat = resolution * -deltaY; var row = (prepend) ? grid.pop() : grid.shift(); for (var i = 0, len = modelRow.length; i < len; i++) { var modelTile = modelRow[i]; var bounds = modelTile.bounds.clone(); var position = modelTile.position.clone(); bounds.bottom = bounds.bottom + deltaLat; bounds.top = bounds.top + deltaLat; position.y = position.y + deltaY; row[i].moveTo(bounds, position); }
        if (prepend) { grid.unshift(row); } else { grid.push(row); }
    }, shiftColumn: function (prepend) { var deltaX = (prepend) ? -this.tileSize.w : this.tileSize.w; var resolution = this.map.getResolution(); var deltaLon = resolution * deltaX; for (var i = 0, len = this.grid.length; i < len; i++) { var row = this.grid[i]; var modelTileIndex = (prepend) ? 0 : (row.length - 1); var modelTile = row[modelTileIndex]; var bounds = modelTile.bounds.clone(); var position = modelTile.position.clone(); bounds.left = bounds.left + deltaLon; bounds.right = bounds.right + deltaLon; position.x = position.x + deltaX; var tile = prepend ? this.grid[i].pop() : this.grid[i].shift(); tile.moveTo(bounds, position); if (prepend) { row.unshift(tile); } else { row.push(tile); } } }, removeExcessTiles: function (rows, columns) {
        while (this.grid.length > rows) { var row = this.grid.pop(); for (var i = 0, l = row.length; i < l; i++) { var tile = row[i]; this.removeTileMonitoringHooks(tile); tile.destroy(); } }
        while (this.grid[0].length > columns) { for (var i = 0, l = this.grid.length; i < l; i++) { var row = this.grid[i]; var tile = row.pop(); this.removeTileMonitoringHooks(tile); tile.destroy(); } }
    }, onMapResize: function () { if (this.singleTile) { this.clearGrid(); this.setTileSize(); } }, getTileBounds: function (viewPortPx) {
        var maxExtent = this.maxExtent; var resolution = this.getResolution(); var tileMapWidth = resolution * this.tileSize.w; var tileMapHeight = resolution * this.tileSize.h; var mapPoint = this.getLonLatFromViewPortPx(viewPortPx); var tileLeft = maxExtent.left + (tileMapWidth * Math.floor((mapPoint.lon -
maxExtent.left) / tileMapWidth)); var tileBottom = maxExtent.bottom + (tileMapHeight * Math.floor((mapPoint.lat -
maxExtent.bottom) / tileMapHeight)); return new OpenLayers.Bounds(tileLeft, tileBottom, tileLeft + tileMapWidth, tileBottom + tileMapHeight);
    }, CLASS_NAME: "OpenLayers.Layer.Grid"
});







OpenLayers.Tile = OpenLayers.Class({ EVENT_TYPES: ["loadstart", "loadend", "reload", "unload"], events: null, id: null, layer: null, url: null, bounds: null, size: null, position: null, isLoading: false, initialize: function (layer, position, bounds, url, size, options) {
    this.layer = layer; this.position = position.clone(); this.bounds = bounds.clone(); this.url = url; if (size) { this.size = size.clone(); }
    this.id = OpenLayers.Util.createUniqueID("Tile_"); this.events = new OpenLayers.Events(this, null, this.EVENT_TYPES); OpenLayers.Util.extend(this, options);
}, unload: function () { if (this.isLoading) { this.isLoading = false; this.events.triggerEvent("unload"); } }, destroy: function () { this.layer = null; this.bounds = null; this.size = null; this.position = null; this.events.destroy(); this.events = null; }, clone: function (obj) {
    if (obj == null) { obj = new OpenLayers.Tile(this.layer, this.position, this.bounds, this.url, this.size); }
    OpenLayers.Util.applyDefaults(obj, this); return obj;
}, draw: function () { var maxExtent = this.layer.maxExtent; var withinMaxExtent = (maxExtent && this.bounds.intersectsBounds(maxExtent, false)); this.shouldDraw = (withinMaxExtent || this.layer.displayOutsideMaxExtent); this.clear(); return this.shouldDraw; }, moveTo: function (bounds, position, redraw) {
    if (redraw == null) { redraw = true; }
    this.bounds = bounds.clone(); this.position = position.clone(); if (redraw) { this.draw(); }
}, clear: function () { }, getBoundsFromBaseLayer: function (position) {
    var msg = OpenLayers.i18n('reprojectDeprecated', { 'layerName': this.layer.name }); OpenLayers.Console.warn(msg); var topLeft = this.layer.map.getLonLatFromLayerPx(position); var bottomRightPx = position.clone(); bottomRightPx.x += this.size.w; bottomRightPx.y += this.size.h; var bottomRight = this.layer.map.getLonLatFromLayerPx(bottomRightPx); if (topLeft.lon > bottomRight.lon) { if (topLeft.lon < 0) { topLeft.lon = -180 - (topLeft.lon + 180); } else { bottomRight.lon = 180 + bottomRight.lon + 180; } }
    var bounds = new OpenLayers.Bounds(topLeft.lon, bottomRight.lat, bottomRight.lon, topLeft.lat); return bounds;
}, showTile: function () { if (this.shouldDraw) { this.show(); } }, show: function () { }, hide: function () { }, CLASS_NAME: "OpenLayers.Tile"
});
OpenLayers.Tile.Image = OpenLayers.Class(OpenLayers.Tile, { url: null, imgDiv: null, frame: null, layerAlphaHack: null, isBackBuffer: false, isFirstDraw: true, backBufferTile: null, maxGetUrlLength: null, initialize: function (layer, position, bounds, url, size, options) {
    OpenLayers.Tile.prototype.initialize.apply(this, arguments); if (this.maxGetUrlLength != null) { OpenLayers.Util.extend(this, OpenLayers.Tile.Image.IFrame); }
    this.url = url; this.frame = document.createElement('div'); this.frame.style.overflow = 'hidden'; this.frame.style.position = 'absolute'; this.layerAlphaHack = this.layer.alpha && OpenLayers.Util.alphaHack();
}, destroy: function () {
    if (this.imgDiv != null) { this.removeImgDiv(); }
    this.imgDiv = null; if ((this.frame != null) && (this.frame.parentNode == this.layer.div)) { this.layer.div.removeChild(this.frame); }
    this.frame = null; if (this.backBufferTile) { this.backBufferTile.destroy(); this.backBufferTile = null; }
    this.layer.events.unregister("loadend", this, this.resetBackBuffer); OpenLayers.Tile.prototype.destroy.apply(this, arguments);
}, clone: function (obj) {
    if (obj == null) { obj = new OpenLayers.Tile.Image(this.layer, this.position, this.bounds, this.url, this.size); }
    obj = OpenLayers.Tile.prototype.clone.apply(this, [obj]); obj.imgDiv = null; return obj;
}, draw: function () {
    if (this.layer != this.layer.map.baseLayer && this.layer.reproject) { this.bounds = this.getBoundsFromBaseLayer(this.position); }
    var drawTile = OpenLayers.Tile.prototype.draw.apply(this, arguments); if ((OpenLayers.Util.indexOf(this.layer.SUPPORTED_TRANSITIONS, this.layer.transitionEffect) != -1) || this.layer.singleTile) {
        if (drawTile) {
            if (!this.backBufferTile) { this.backBufferTile = this.clone(); this.backBufferTile.hide(); this.backBufferTile.isBackBuffer = true; this.events.register('loadend', this, this.resetBackBuffer); this.layer.events.register("loadend", this, this.resetBackBuffer); }
            this.startTransition();
        } else { if (this.backBufferTile) { this.backBufferTile.clear(); } }
    } else { if (drawTile && this.isFirstDraw) { this.events.register('loadend', this, this.showTile); this.isFirstDraw = false; } }
    if (!drawTile) { return false; }
    if (this.isLoading) { this.events.triggerEvent("reload"); } else { this.isLoading = true; this.events.triggerEvent("loadstart"); }
    return this.renderTile();
}, resetBackBuffer: function () {
    this.showTile(); if (this.backBufferTile && (this.isFirstDraw || !this.layer.numLoadingTiles)) {
        this.isFirstDraw = false; var maxExtent = this.layer.maxExtent; var withinMaxExtent = (maxExtent && this.bounds.intersectsBounds(maxExtent, false)); if (withinMaxExtent) { this.backBufferTile.position = this.position; this.backBufferTile.bounds = this.bounds; this.backBufferTile.size = this.size; this.backBufferTile.imageSize = this.layer.getImageSize(this.bounds) || this.size; this.backBufferTile.imageOffset = this.layer.imageOffset; this.backBufferTile.resolution = this.layer.getResolution(); this.backBufferTile.renderTile(); }
        this.backBufferTile.hide();
    }
}, renderTile: function () {
    if (this.layer.async) {
        this.initImgDiv();
        this.layer.getURLasync(this.bounds, this, "url", this.positionImage);
    } else {
        this.url = this.layer.getURL(this.bounds); this.initImgDiv(); this.positionImage();
    }
    return true;
}, positionImage: function () {
    if (this.layer === null) { return; }
    OpenLayers.Util.modifyDOMElement(this.frame, null, this.position, this.size); var imageSize = this.layer.getImageSize(this.bounds); if (this.layerAlphaHack) { OpenLayers.Util.modifyAlphaImageDiv(this.imgDiv, null, null, imageSize, this.url); } else { OpenLayers.Util.modifyDOMElement(this.imgDiv, null, null, imageSize); this.imgDiv.src = this.url; }
}, clear: function () { if (this.imgDiv) { this.hide(); if (OpenLayers.Tile.Image.useBlankTile) { this.imgDiv.src = OpenLayers.Util.getImagesLocation() + "blank.gif"; } } }, initImgDiv: function () {
    if (this.imgDiv == null) {
        var offset = this.layer.imageOffset; var size = this.layer.getImageSize(this.bounds); if (this.layerAlphaHack) { this.imgDiv = OpenLayers.Util.createAlphaImageDiv(null, offset, size, null, "relative", null, null, null, true); } else { this.imgDiv = OpenLayers.Util.createImage(null, offset, size, null, "relative", null, null, true); }
        if (OpenLayers.Util.isArray(this.layer.url)) { this.imgDiv.urls = this.layer.url.slice(); }
        this.imgDiv.className = 'olTileImage'; this.frame.style.zIndex = this.isBackBuffer ? 0 : 1; this.frame.appendChild(this.imgDiv); this.layer.div.appendChild(this.frame); if (this.layer.opacity != null) { OpenLayers.Util.modifyDOMElement(this.imgDiv, null, null, null, null, null, null, this.layer.opacity); }
        this.imgDiv.map = this.layer.map; var onload = function () { if (this.isLoading) { this.isLoading = false; this.events.triggerEvent("loadend"); } }; if (this.layerAlphaHack) { OpenLayers.Event.observe(this.imgDiv.childNodes[0], 'load', OpenLayers.Function.bind(onload, this)); } else { OpenLayers.Event.observe(this.imgDiv, 'load', OpenLayers.Function.bind(onload, this)); }
        var onerror = function () { if (this.imgDiv._attempts > OpenLayers.IMAGE_RELOAD_ATTEMPTS) { onload.call(this); } }; OpenLayers.Event.observe(this.imgDiv, "error", OpenLayers.Function.bind(onerror, this));
    }
    this.imgDiv.viewRequestID = this.layer.map.viewRequestID;
}, removeImgDiv: function () {
    OpenLayers.Event.stopObservingElement(this.imgDiv); if (this.imgDiv.parentNode == this.frame) { this.frame.removeChild(this.imgDiv); this.imgDiv.map = null; }
    this.imgDiv.urls = null; var child = this.imgDiv.firstChild; if (child) { OpenLayers.Event.stopObservingElement(child); this.imgDiv.removeChild(child); delete child; } else { this.imgDiv.src = OpenLayers.Util.getImagesLocation() + "blank.gif"; }
}, checkImgURL: function () { if (this.layer) { var loaded = this.layerAlphaHack ? this.imgDiv.firstChild.src : this.imgDiv.src; if (!OpenLayers.Util.isEquivalentUrl(loaded, this.url)) { this.hide(); } } }, startTransition: function () {
    if (!this.backBufferTile || !this.backBufferTile.imgDiv) { return; }
    var ratio = 1; if (this.backBufferTile.resolution) { ratio = this.backBufferTile.resolution / this.layer.getResolution(); }
    if (ratio != 1) {
        if (this.layer.transitionEffect == 'resize') {
            var upperLeft = new OpenLayers.LonLat(this.backBufferTile.bounds.left, this.backBufferTile.bounds.top); var size = new OpenLayers.Size(this.backBufferTile.size.w * ratio, this.backBufferTile.size.h * ratio); var px = this.layer.map.getLayerPxFromLonLat(upperLeft); OpenLayers.Util.modifyDOMElement(this.backBufferTile.frame, null, px, size); var imageSize = this.backBufferTile.imageSize; imageSize = new OpenLayers.Size(imageSize.w * ratio, imageSize.h * ratio); var imageOffset = this.backBufferTile.imageOffset; if (imageOffset) { imageOffset = new OpenLayers.Pixel(imageOffset.x * ratio, imageOffset.y * ratio); }
            OpenLayers.Util.modifyDOMElement(this.backBufferTile.imgDiv, null, imageOffset, imageSize); this.backBufferTile.show();
        }
    } else { if (this.layer.singleTile) { this.backBufferTile.show(); } else { this.backBufferTile.hide(); } }
}, show: function () { this.frame.style.display = ''; if (OpenLayers.Util.indexOf(this.layer.SUPPORTED_TRANSITIONS, this.layer.transitionEffect) != -1) { if (OpenLayers.IS_GECKO === true) { this.frame.scrollLeft = this.frame.scrollLeft; } } }, hide: function () { this.frame.style.display = 'none'; }, CLASS_NAME: "OpenLayers.Tile.Image"
});
OpenLayers.Tile.Image.useBlankTile = (OpenLayers.BROWSER_NAME == "safari" || OpenLayers.BROWSER_NAME == "opera");
OpenLayers.Format.ArcXML = OpenLayers.Class(OpenLayers.Format.XML, { fontStyleKeys: ['antialiasing', 'blockout', 'font', 'fontcolor', 'fontsize', 'fontstyle', 'glowing', 'interval', 'outline', 'printmode', 'shadow', 'transparency'], request: null, response: null, initialize: function (options) {
    this.request = new OpenLayers.Format.ArcXML.Request(); this.response = new OpenLayers.Format.ArcXML.Response(); if (options) { if (options.requesttype == "feature") { this.request.get_image = null; var qry = this.request.get_feature.query; this.addCoordSys(qry.featurecoordsys, options.featureCoordSys); this.addCoordSys(qry.filtercoordsys, options.filterCoordSys); if (options.polygon) { qry.isspatial = true; qry.spatialfilter.polygon = options.polygon; } else if (options.envelope) { qry.isspatial = true; qry.spatialfilter.envelope = { minx: 0, miny: 0, maxx: 0, maxy: 0 }; this.parseEnvelope(qry.spatialfilter.envelope, options.envelope); } } else if (options.requesttype == "image") { this.request.get_feature = null; var props = this.request.get_image.properties; this.parseEnvelope(props.envelope, options.envelope); this.addLayers(props.layerlist, options.layers); this.addImageSize(props.imagesize, options.tileSize); this.addCoordSys(props.featurecoordsys, options.featureCoordSys); this.addCoordSys(props.filtercoordsys, options.filterCoordSys); } else { this.request = null; } }
    OpenLayers.Format.XML.prototype.initialize.apply(this, [options]);
}, parseEnvelope: function (env, arr) { if (arr && arr.length == 4) { env.minx = arr[0]; env.miny = arr[1]; env.maxx = arr[2]; env.maxy = arr[3]; } }, addLayers: function (ll, lyrs) { for (var lind = 0, len = lyrs.length; lind < len; lind++) { ll.push(lyrs[lind]); } }, addImageSize: function (imsize, olsize) { if (olsize !== null) { imsize.width = olsize.w; imsize.height = olsize.h; imsize.printwidth = olsize.w; imsize.printheight = olsize.h; } }, addCoordSys: function (featOrFilt, fsys) {
    if (typeof fsys == "string") { featOrFilt.id = parseInt(fsys); featOrFilt.string = fsys; }
    else if (typeof fsys == "object" && fsys.proj !== null) { featOrFilt.id = fsys.proj.srsProjNumber; featOrFilt.string = fsys.proj.srsCode; } else { featOrFilt = fsys; }
}, iserror: function (data) {
    var ret = null; if (!data) { ret = (this.response.error !== ''); } else { data = OpenLayers.Format.XML.prototype.read.apply(this, [data]); var errorNodes = data.documentElement.getElementsByTagName("ERROR"); ret = (errorNodes !== null && errorNodes.length > 0); }
    return ret;
}, read: function (data) {
    if (typeof data == "string") { data = OpenLayers.Format.XML.prototype.read.apply(this, [data]); }
    var arcNode = null; if (data && data.documentElement) { if (data.documentElement.nodeName == "ARCXML") { arcNode = data.documentElement; } else { arcNode = data.documentElement.getElementsByTagName("ARCXML")[0]; } }
    if (!arcNode || arcNode.firstChild.nodeName === 'parsererror') {
        var error, source; try { error = data.firstChild.nodeValue; source = data.firstChild.childNodes[1].firstChild.nodeValue; } catch (err) { }
        throw { message: "Error parsing the ArcXML request", error: error, source: source };
    }
    var response = this.parseResponse(arcNode); return response;
}, write: function (request) {
    if (!request) { request = this.request; }
    var root = this.createElementNS("", "ARCXML"); root.setAttribute("version", "1.1"); var reqElem = this.createElementNS("", "REQUEST"); if (request.get_image != null) {
        var getElem = this.createElementNS("", "GET_IMAGE"); reqElem.appendChild(getElem); var propElem = this.createElementNS("", "PROPERTIES"); getElem.appendChild(propElem); var props = request.get_image.properties; if (props.featurecoordsys != null) {
            var feat = this.createElementNS("", "FEATURECOORDSYS"); propElem.appendChild(feat); if (props.featurecoordsys.id === 0) { feat.setAttribute("string", props.featurecoordsys['string']); }
            else { feat.setAttribute("id", props.featurecoordsys.id); }
        }
        if (props.filtercoordsys != null) {
            var filt = this.createElementNS("", "FILTERCOORDSYS"); propElem.appendChild(filt); if (props.filtercoordsys.id === 0) { filt.setAttribute("string", props.filtercoordsys.string); }
            else { filt.setAttribute("id", props.filtercoordsys.id); }
        }
        if (props.envelope != null) { var env = this.createElementNS("", "ENVELOPE"); propElem.appendChild(env); env.setAttribute("minx", props.envelope.minx); env.setAttribute("miny", props.envelope.miny); env.setAttribute("maxx", props.envelope.maxx); env.setAttribute("maxy", props.envelope.maxy); }
        var imagesz = this.createElementNS("", "IMAGESIZE"); propElem.appendChild(imagesz); imagesz.setAttribute("height", props.imagesize.height); imagesz.setAttribute("width", props.imagesize.width); if (props.imagesize.height != props.imagesize.printheight || props.imagesize.width != props.imagesize.printwidth) { imagesz.setAttribute("printheight", props.imagesize.printheight); imagesz.setArrtibute("printwidth", props.imagesize.printwidth); }
        if (props.background != null) {
            var backgrnd = this.createElementNS("", "BACKGROUND"); propElem.appendChild(backgrnd); backgrnd.setAttribute("color", props.background.color.r + "," +
props.background.color.g + "," +
props.background.color.b); if (props.background.transcolor !== null) {
                backgrnd.setAttribute("transcolor", props.background.transcolor.r + "," +
props.background.transcolor.g + "," +
props.background.transcolor.b);
            }
        }
        if (props.layerlist != null && props.layerlist.length > 0) {
            var layerlst = this.createElementNS("", "LAYERLIST"); propElem.appendChild(layerlst); for (var ld = 0; ld < props.layerlist.length; ld++) {
                var ldef = this.createElementNS("", "LAYERDEF"); layerlst.appendChild(ldef); ldef.setAttribute("id", props.layerlist[ld].id); ldef.setAttribute("visible", props.layerlist[ld].visible); if (typeof props.layerlist[ld].query == "object") {
                    var query = props.layerlist[ld].query; if (query.where.length < 0) { continue; }
                    var queryElem = null; if (typeof query.spatialfilter == "boolean" && query.spatialfilter) { queryElem = this.createElementNS("", "SPATIALQUERY"); }
                    else { queryElem = this.createElementNS("", "QUERY"); }
                    queryElem.setAttribute("where", query.where); if (typeof query.accuracy == "number" && query.accuracy > 0) { queryElem.setAttribute("accuracy", query.accuracy); }
                    if (typeof query.featurelimit == "number" && query.featurelimit < 2000) { queryElem.setAttribute("featurelimit", query.featurelimit); }
                    if (typeof query.subfields == "string" && query.subfields != "#ALL#") { queryElem.setAttribute("subfields", query.subfields); }
                    if (typeof query.joinexpression == "string" && query.joinexpression.length > 0) { queryElem.setAttribute("joinexpression", query.joinexpression); }
                    if (typeof query.jointables == "string" && query.jointables.length > 0) { queryElem.setAttribute("jointables", query.jointables); }
                    ldef.appendChild(queryElem);
                }
                if (typeof props.layerlist[ld].renderer == "object") { this.addRenderer(ldef, props.layerlist[ld].renderer); }
            }
        }
    } else if (request.get_feature != null) {
        var getElem = this.createElementNS("", "GET_FEATURES"); getElem.setAttribute("outputmode", "newxml"); getElem.setAttribute("checkesc", "true"); if (request.get_feature.geometry) { getElem.setAttribute("geometry", request.get_feature.geometry); }
        else { getElem.setAttribute("geometry", "false"); }
        if (request.get_feature.compact) { getElem.setAttribute("compact", request.get_feature.compact); }
        if (request.get_feature.featurelimit == "number") { getElem.setAttribute("featurelimit", request.get_feature.featurelimit); }
        getElem.setAttribute("globalenvelope", "true"); reqElem.appendChild(getElem); if (request.get_feature.layer != null && request.get_feature.layer.length > 0) { var lyrElem = this.createElementNS("", "LAYER"); lyrElem.setAttribute("id", request.get_feature.layer); getElem.appendChild(lyrElem); }
        var fquery = request.get_feature.query; if (fquery != null) {
            var qElem = null; if (fquery.isspatial) { qElem = this.createElementNS("", "SPATIALQUERY"); } else { qElem = this.createElementNS("", "QUERY"); }
            getElem.appendChild(qElem); if (typeof fquery.accuracy == "number") { qElem.setAttribute("accuracy", fquery.accuracy); }
            if (fquery.featurecoordsys != null) {
                var fcsElem1 = this.createElementNS("", "FEATURECOORDSYS"); if (fquery.featurecoordsys.id == 0) { fcsElem1.setAttribute("string", fquery.featurecoordsys.string); } else { fcsElem1.setAttribute("id", fquery.featurecoordsys.id); }
                qElem.appendChild(fcsElem1);
            }
            if (fquery.filtercoordsys != null) {
                var fcsElem2 = this.createElementNS("", "FILTERCOORDSYS"); if (fquery.filtercoordsys.id === 0) { fcsElem2.setAttribute("string", fquery.filtercoordsys.string); } else { fcsElem2.setAttribute("id", fquery.filtercoordsys.id); }
                qElem.appendChild(fcsElem2);
            }
            if (fquery.buffer > 0) { var bufElem = this.createElementNS("", "BUFFER"); bufElem.setAttribute("distance", fquery.buffer); qElem.appendChild(bufElem); }
            if (fquery.isspatial) { var spfElem = this.createElementNS("", "SPATIALFILTER"); spfElem.setAttribute("relation", fquery.spatialfilter.relation); qElem.appendChild(spfElem); if (fquery.spatialfilter.envelope) { var envElem = this.createElementNS("", "ENVELOPE"); envElem.setAttribute("minx", fquery.spatialfilter.envelope.minx); envElem.setAttribute("miny", fquery.spatialfilter.envelope.miny); envElem.setAttribute("maxx", fquery.spatialfilter.envelope.maxx); envElem.setAttribute("maxy", fquery.spatialfilter.envelope.maxy); spfElem.appendChild(envElem); } else if (typeof fquery.spatialfilter.polygon == "object") { spfElem.appendChild(this.writePolygonGeometry(fquery.spatialfilter.polygon)); } }
            if (fquery.where != null && fquery.where.length > 0) { qElem.setAttribute("where", fquery.where); }
        }
    }
    root.appendChild(reqElem); return OpenLayers.Format.XML.prototype.write.apply(this, [root]);
}, addGroupRenderer: function (ldef, toprenderer) { var topRelem = this.createElementNS("", "GROUPRENDERER"); ldef.appendChild(topRelem); for (var rind = 0; rind < toprenderer.length; rind++) { var renderer = toprenderer[rind]; this.addRenderer(topRelem, renderer); } }, addRenderer: function (topRelem, renderer) { if (OpenLayers.Util.isArray(renderer)) { this.addGroupRenderer(topRelem, renderer); } else { var renderElem = this.createElementNS("", renderer.type.toUpperCase() + "RENDERER"); topRelem.appendChild(renderElem); if (renderElem.tagName == "VALUEMAPRENDERER") { this.addValueMapRenderer(renderElem, renderer); } else if (renderElem.tagName == "VALUEMAPLABELRENDERER") { this.addValueMapLabelRenderer(renderElem, renderer); } else if (renderElem.tagName == "SIMPLELABELRENDERER") { this.addSimpleLabelRenderer(renderElem, renderer); } else if (renderElem.tagName == "SCALEDEPENDENTRENDERER") { this.addScaleDependentRenderer(renderElem, renderer); } } }, addScaleDependentRenderer: function (renderElem, renderer) {
    if (typeof renderer.lower == "string" || typeof renderer.lower == "number") { renderElem.setAttribute("lower", renderer.lower); }
    if (typeof renderer.upper == "string" || typeof renderer.upper == "number") { renderElem.setAttribute("upper", renderer.upper); }
    this.addRenderer(renderElem, renderer.renderer);
}, addValueMapLabelRenderer: function (renderElem, renderer) {
    renderElem.setAttribute("lookupfield", renderer.lookupfield); renderElem.setAttribute("labelfield", renderer.labelfield); if (typeof renderer.exacts == "object") {
        for (var ext = 0, extlen = renderer.exacts.length; ext < extlen; ext++) {
            var exact = renderer.exacts[ext]; var eelem = this.createElementNS("", "EXACT"); if (typeof exact.value == "string") { eelem.setAttribute("value", exact.value); }
            if (typeof exact.label == "string") { eelem.setAttribute("label", exact.label); }
            if (typeof exact.method == "string") { eelem.setAttribute("method", exact.method); }
            renderElem.appendChild(eelem); if (typeof exact.symbol == "object") {
                var selem = null; if (exact.symbol.type == "text") { selem = this.createElementNS("", "TEXTSYMBOL"); }
                if (selem != null) {
                    var keys = this.fontStyleKeys; for (var i = 0, len = keys.length; i < len; i++) { var key = keys[i]; if (exact.symbol[key]) { selem.setAttribute(key, exact.symbol[key]); } }
                    eelem.appendChild(selem);
                }
            }
        }
    }
}, addValueMapRenderer: function (renderElem, renderer) {
    renderElem.setAttribute("lookupfield", renderer.lookupfield); if (typeof renderer.ranges == "object") {
        for (var rng = 0, rnglen = renderer.ranges.length; rng < rnglen; rng++) {
            var range = renderer.ranges[rng]; var relem = this.createElementNS("", "RANGE"); relem.setAttribute("lower", range.lower); relem.setAttribute("upper", range.upper); renderElem.appendChild(relem); if (typeof range.symbol == "object") {
                var selem = null; if (range.symbol.type == "simplepolygon") { selem = this.createElementNS("", "SIMPLEPOLYGONSYMBOL"); }
                if (selem != null) {
                    if (typeof range.symbol.boundarycolor == "string") { selem.setAttribute("boundarycolor", range.symbol.boundarycolor); }
                    if (typeof range.symbol.fillcolor == "string") { selem.setAttribute("fillcolor", range.symbol.fillcolor); }
                    if (typeof range.symbol.filltransparency == "number") { selem.setAttribute("filltransparency", range.symbol.filltransparency); }
                    relem.appendChild(selem);
                }
            }
        }
    } else if (typeof renderer.exacts == "object") {
        for (var ext = 0, extlen = renderer.exacts.length; ext < extlen; ext++) {
            var exact = renderer.exacts[ext]; var eelem = this.createElementNS("", "EXACT"); if (typeof exact.value == "string") { eelem.setAttribute("value", exact.value); }
            if (typeof exact.label == "string") { eelem.setAttribute("label", exact.label); }
            if (typeof exact.method == "string") { eelem.setAttribute("method", exact.method); }
            renderElem.appendChild(eelem); if (typeof exact.symbol == "object") {
                var selem = null; if (exact.symbol.type == "simplemarker") { selem = this.createElementNS("", "SIMPLEMARKERSYMBOL"); }
                if (selem != null) {
                    if (typeof exact.symbol.antialiasing == "string") { selem.setAttribute("antialiasing", exact.symbol.antialiasing); }
                    if (typeof exact.symbol.color == "string") { selem.setAttribute("color", exact.symbol.color); }
                    if (typeof exact.symbol.outline == "string") { selem.setAttribute("outline", exact.symbol.outline); }
                    if (typeof exact.symbol.overlap == "string") { selem.setAttribute("overlap", exact.symbol.overlap); }
                    if (typeof exact.symbol.shadow == "string") { selem.setAttribute("shadow", exact.symbol.shadow); }
                    if (typeof exact.symbol.transparency == "number") { selem.setAttribute("transparency", exact.symbol.transparency); }
                    if (typeof exact.symbol.usecentroid == "string") { selem.setAttribute("usecentroid", exact.symbol.usecentroid); }
                    if (typeof exact.symbol.width == "number") { selem.setAttribute("width", exact.symbol.width); }
                    eelem.appendChild(selem);
                }
            }
        }
    }
}, addSimpleLabelRenderer: function (renderElem, renderer) {
    renderElem.setAttribute("field", renderer.field); var keys = ['featureweight', 'howmanylabels', 'labelbufferratio', 'labelpriorities', 'labelweight', 'linelabelposition', 'rotationalangles']; for (var i = 0, len = keys.length; i < len; i++) { var key = keys[i]; if (renderer[key]) { renderElem.setAttribute(key, renderer[key]); } }
    if (renderer.symbol.type == "text") { var symbol = renderer.symbol; var selem = this.createElementNS("", "TEXTSYMBOL"); renderElem.appendChild(selem); var keys = this.fontStyleKeys; for (var i = 0, len = keys.length; i < len; i++) { var key = keys[i]; if (symbol[key]) { selem.setAttribute(key, renderer[key]); } } }
}, writePolygonGeometry: function (polygon) {
    if (!(polygon instanceof OpenLayers.Geometry.Polygon)) {
        throw { message: 'Cannot write polygon geometry to ArcXML with an ' +
polygon.CLASS_NAME + ' object.', geometry: polygon
        };
    }
    var polyElem = this.createElementNS("", "POLYGON"); for (var ln = 0, lnlen = polygon.components.length; ln < lnlen; ln++) {
        var ring = polygon.components[ln]; var ringElem = this.createElementNS("", "RING"); for (var rn = 0, rnlen = ring.components.length; rn < rnlen; rn++) { var point = ring.components[rn]; var pointElem = this.createElementNS("", "POINT"); pointElem.setAttribute("x", point.x); pointElem.setAttribute("y", point.y); ringElem.appendChild(pointElem); }
        polyElem.appendChild(ringElem);
    }
    return polyElem;
}, parseResponse: function (data) {
    if (typeof data == "string") { var newData = new OpenLayers.Format.XML(); data = newData.read(data); }
    var response = new OpenLayers.Format.ArcXML.Response(); var errorNode = data.getElementsByTagName("ERROR"); if (errorNode != null && errorNode.length > 0) { response.error = this.getChildValue(errorNode, "Unknown error."); } else {
        var responseNode = data.getElementsByTagName("RESPONSE"); if (responseNode == null || responseNode.length == 0) { response.error = "No RESPONSE tag found in ArcXML response."; return response; }
        var rtype = responseNode[0].firstChild.nodeName; if (rtype == "#text") { rtype = responseNode[0].firstChild.nextSibling.nodeName; }
        if (rtype == "IMAGE") { var envelopeNode = data.getElementsByTagName("ENVELOPE"); var outputNode = data.getElementsByTagName("OUTPUT"); if (envelopeNode == null || envelopeNode.length == 0) { response.error = "No ENVELOPE tag found in ArcXML response."; } else if (outputNode == null || outputNode.length == 0) { response.error = "No OUTPUT tag found in ArcXML response."; } else { var envAttr = this.parseAttributes(envelopeNode[0]); var outputAttr = this.parseAttributes(outputNode[0]); if (typeof outputAttr.type == "string") { response.image = { envelope: envAttr, output: { type: outputAttr.type, data: this.getChildValue(outputNode[0])} }; } else { response.image = { envelope: envAttr, output: outputAttr }; } } } else if (rtype == "FEATURES") {
            var features = responseNode[0].getElementsByTagName("FEATURES"); var featureCount = features[0].getElementsByTagName("FEATURECOUNT"); response.features.featurecount = featureCount[0].getAttribute("count"); if (response.features.featurecount > 0) {
                var envelope = features[0].getElementsByTagName("ENVELOPE"); response.features.envelope = this.parseAttributes(envelope[0], typeof (0)); var featureList = features[0].getElementsByTagName("FEATURE"); for (var fn = 0; fn < featureList.length; fn++) {
                    var feature = new OpenLayers.Feature.Vector(); var fields = featureList[fn].getElementsByTagName("FIELD"); for (var fdn = 0; fdn < fields.length; fdn++) { var fieldName = fields[fdn].getAttribute("name"); var fieldValue = fields[fdn].getAttribute("value"); feature.attributes[fieldName] = fieldValue; }
                    var geom = featureList[fn].getElementsByTagName("POLYGON"); if (geom.length > 0) {
                        var ring = geom[0].getElementsByTagName("RING"); var polys = []; for (var rn = 0; rn < ring.length; rn++) {
                            var linearRings = []; linearRings.push(this.parsePointGeometry(ring[rn])); var holes = ring[rn].getElementsByTagName("HOLE"); for (var hn = 0; hn < holes.length; hn++) { linearRings.push(this.parsePointGeometry(holes[hn])); }
                            holes = null; polys.push(new OpenLayers.Geometry.Polygon(linearRings)); linearRings = null;
                        }
                        ring = null; if (polys.length == 1) { feature.geometry = polys[0]; } else
                        { feature.geometry = new OpenLayers.Geometry.MultiPolygon(polys); }
                    }
                    response.features.feature.push(feature);
                }
            }
        } else { response.error = "Unidentified response type."; }
    }
    return response;
}, parseAttributes: function (node, type) {
    var attributes = {}; for (var attr = 0; attr < node.attributes.length; attr++) { if (type == "number") { attributes[node.attributes[attr].nodeName] = parseFloat(node.attributes[attr].nodeValue); } else { attributes[node.attributes[attr].nodeName] = node.attributes[attr].nodeValue; } }
    return attributes;
}, parsePointGeometry: function (node) {
    var ringPoints = []; var coords = node.getElementsByTagName("COORDS"); if (coords.length > 0) {
        var coordArr = this.getChildValue(coords[0]); coordArr = coordArr.split(/;/); for (var cn = 0; cn < coordArr.length; cn++) { var coordItems = coordArr[cn].split(/ /); ringPoints.push(new OpenLayers.Geometry.Point(parseFloat(coordItems[0]), parseFloat(coordItems[1]))); }
        coords = null;
    } else {
        var point = node.getElementsByTagName("POINT"); if (point.length > 0) { for (var pn = 0; pn < point.length; pn++) { ringPoints.push(new OpenLayers.Geometry.Point(parseFloat(point[pn].getAttribute("x")), parseFloat(point[pn].getAttribute("y")))); } }
        point = null;
    }
    return new OpenLayers.Geometry.LinearRing(ringPoints);
}, CLASS_NAME: "OpenLayers.Format.ArcXML"
});



OpenLayers.Format.ArcXML.Request = OpenLayers.Class({ initialize: function (params) { var defaults = { get_image: { properties: { background: null, draw: true, envelope: { minx: 0, miny: 0, maxx: 0, maxy: 0 }, featurecoordsys: { id: 0, string: "", datumtransformid: 0, datumtransformstring: "" }, filtercoordsys: { id: 0, string: "", datumtransformid: 0, datumtransformstring: "" }, imagesize: { height: 0, width: 0, dpi: 96, printheight: 0, printwidth: 0, scalesymbols: false }, layerlist: [], output: { baseurl: "", legendbaseurl: "", legendname: "", legendpath: "", legendurl: "", name: "", path: "", type: "jpg", url: ""}} }, get_feature: { layer: "", query: { isspatial: false, featurecoordsys: { id: 0, string: "", datumtransformid: 0, datumtransformstring: "" }, filtercoordsys: { id: 0, string: "", datumtransformid: 0, datumtransformstring: "" }, buffer: 0, where: "", spatialfilter: { relation: "envelope_intersection", envelope: null}} }, environment: { separators: { cs: " ", ts: ";"} }, layer: [], workspaces: [] }; return OpenLayers.Util.extend(this, defaults); }, CLASS_NAME: "OpenLayers.Format.ArcXML.Request" }); OpenLayers.Format.ArcXML.Response = OpenLayers.Class({ initialize: function (params) { var defaults = { image: { envelope: null, output: '' }, features: { featurecount: 0, envelope: null, feature: [] }, error: '' }; return OpenLayers.Util.extend(this, defaults); }, CLASS_NAME: "OpenLayers.Format.ArcXML.Response" }); OpenLayers.Request = { DEFAULT_CONFIG: { method: "GET", url: window.location.href, async: true, user: undefined, password: undefined, params: null, proxy: OpenLayers.ProxyHost, headers: {}, data: null, callback: function () { }, success: null, failure: null, scope: null }, URL_SPLIT_REGEX: /([^:]*:)\/\/([^:]*:?[^@]*@)?([^:\/\?]*):?([^\/\?]*)/, events: new OpenLayers.Events(this, null, ["complete", "success", "failure"]), issue: function (config) {
    var defaultConfig = OpenLayers.Util.extend(this.DEFAULT_CONFIG, { proxy: OpenLayers.ProxyHost }); config = OpenLayers.Util.applyDefaults(config, defaultConfig); var request = new OpenLayers.Request.XMLHttpRequest(); var url = OpenLayers.Util.urlAppend(config.url, OpenLayers.Util.getParameterString(config.params || {})); var sameOrigin = !(url.indexOf("http") == 0); var urlParts = !sameOrigin && url.match(this.URL_SPLIT_REGEX); if (urlParts) { var location = window.location; sameOrigin = urlParts[1] == location.protocol && urlParts[3] == location.hostname; var uPort = urlParts[4], lPort = location.port; if (uPort != 80 && uPort != "" || lPort != "80" && lPort != "") { sameOrigin = sameOrigin && uPort == lPort; } }
    if (!sameOrigin) { if (config.proxy) { if (typeof config.proxy == "function") { url = config.proxy(url); } else { url = config.proxy + encodeURIComponent(url); } } else { OpenLayers.Console.warn(OpenLayers.i18n("proxyNeeded"), { url: url }); } }
    request.open(config.method, url, config.async, config.user, config.password); for (var header in config.headers) { request.setRequestHeader(header, config.headers[header]); }
    var events = this.events; var self = this; request.onreadystatechange = function () { if (request.readyState == OpenLayers.Request.XMLHttpRequest.DONE) { var proceed = events.triggerEvent("complete", { request: request, config: config, requestUrl: url }); if (proceed !== false) { self.runCallbacks({ request: request, config: config, requestUrl: url }); } } }; if (config.async === false) { request.send(config.data); } else { window.setTimeout(function () { if (request.readyState !== 0) { request.send(config.data); } }, 0); }
    return request;
}, runCallbacks: function (options) {
    var request = options.request; var config = options.config; var complete = (config.scope) ? OpenLayers.Function.bind(config.callback, config.scope) : config.callback; var success; if (config.success) { success = (config.scope) ? OpenLayers.Function.bind(config.success, config.scope) : config.success; }
    var failure; if (config.failure) { failure = (config.scope) ? OpenLayers.Function.bind(config.failure, config.scope) : config.failure; }
    if (OpenLayers.Util.createUrlObject(config.url).protocol == "file:" && request.responseText) { request.status = 200; }
    complete(request); if (!request.status || (request.status >= 200 && request.status < 300)) { this.events.triggerEvent("success", options); if (success) { success(request); } }
    if (request.status && (request.status < 200 || request.status >= 300)) { this.events.triggerEvent("failure", options); if (failure) { failure(request); } }
}, GET: function (config) { config = OpenLayers.Util.extend(config, { method: "GET" }); return OpenLayers.Request.issue(config); }, POST: function (config) {
    config = OpenLayers.Util.extend(config, { method: "POST" }); config.headers = config.headers ? config.headers : {}; if (!("CONTENT-TYPE" in OpenLayers.Util.upperCaseObject(config.headers))) { config.headers["Content-Type"] = "application/xml"; }
    return OpenLayers.Request.issue(config);
}, PUT: function (config) {
    config = OpenLayers.Util.extend(config, { method: "PUT" }); config.headers = config.headers ? config.headers : {}; if (!("CONTENT-TYPE" in OpenLayers.Util.upperCaseObject(config.headers))) { config.headers["Content-Type"] = "application/xml"; }
    return OpenLayers.Request.issue(config);
}, DELETE: function (config) { config = OpenLayers.Util.extend(config, { method: "DELETE" }); return OpenLayers.Request.issue(config); }, HEAD: function (config) { config = OpenLayers.Util.extend(config, { method: "HEAD" }); return OpenLayers.Request.issue(config); }, OPTIONS: function (config) { config = OpenLayers.Util.extend(config, { method: "OPTIONS" }); return OpenLayers.Request.issue(config); }
}; OpenLayers.Layer.ArcIMS = OpenLayers.Class(OpenLayers.Layer.Grid, { DEFAULT_PARAMS: { ClientVersion: "9.2", ServiceName: '' }, tileSize: null, featureCoordSys: "4326", filterCoordSys: "4326", layers: null, async: true, name: "ArcIMS", isBaseLayer: true, DEFAULT_OPTIONS: { tileSize: new OpenLayers.Size(512, 512), featureCoordSys: "4326", filterCoordSys: "4326", layers: null, isBaseLayer: true, async: true, name: "ArcIMS" }, initialize: function (name, url, options) {
    this.tileSize = new OpenLayers.Size(512, 512); this.params = OpenLayers.Util.applyDefaults({ ServiceName: options.serviceName }, this.DEFAULT_PARAMS); this.options = OpenLayers.Util.applyDefaults(options, this.DEFAULT_OPTIONS); OpenLayers.Layer.Grid.prototype.initialize.apply(this, [name, url, this.params, options]); if (this.transparent) {
        if (!this.isBaseLayer) { this.isBaseLayer = false; }
        if (this.format == "image/jpeg") { this.format = OpenLayers.Util.alphaHack() ? "image/gif" : "image/png"; }
    }
    if (this.options.layers === null) { this.options.layers = []; }
}, destroy: function () { OpenLayers.Layer.Grid.prototype.destroy.apply(this, arguments); }, getURL: function (bounds) {
    var url = ""; bounds = this.adjustBounds(bounds); var axlReq = new OpenLayers.Format.ArcXML(OpenLayers.Util.extend(this.options, { requesttype: "image", envelope: bounds.toArray(), tileSize: this.tileSize })); var req = new OpenLayers.Request.POST({ url: this.getFullRequestString(), data: axlReq.write(), async: false }); if (req != null) {
        var doc = req.responseXML; if (!doc || !doc.documentElement) { doc = req.responseText; }
        var axlResp = new OpenLayers.Format.ArcXML(); var arcxml = axlResp.read(doc); url = this.getUrlOrImage(arcxml.image.output);
    }
    return url;
}, getURLasync: function (bounds, scope, prop, callback) {
    bounds = this.adjustBounds(bounds); var axlReq = new OpenLayers.Format.ArcXML(OpenLayers.Util.extend(this.options, { requesttype: "image", envelope: bounds.toArray(), tileSize: this.tileSize })); OpenLayers.Request.POST({ url: this.getFullRequestString(), async: true, data: axlReq.write(), callback: function (req) {
        var doc = req.responseXML; if (!doc || !doc.documentElement) { doc = req.responseText; }
        var axlResp = new OpenLayers.Format.ArcXML(); var arcxml = axlResp.read(doc); scope[prop] = this.getUrlOrImage(arcxml.image.output); callback.apply(scope);
    }, scope: this
    });
}, getUrlOrImage: function (output) {
    var ret = ""; if (output.url) { ret = output.url; } else if (output.data) { ret = "data:image/" + output.type + ";base64," + output.data; }
    return ret;
}, setLayerQuery: function (id, querydef) {
    for (var lyr = 0; lyr < this.options.layers.length; lyr++) { if (id == this.options.layers[lyr].id) { this.options.layers[lyr].query = querydef; return; } }
    this.options.layers.push({ id: id, visible: true, query: querydef });
}, getFeatureInfo: function (geometry, layer, options) {
    var buffer = options.buffer || 1; var callback = options.callback || function () { }; var scope = options.scope || window; var requestOptions = {}; OpenLayers.Util.extend(requestOptions, this.options); requestOptions.requesttype = "feature"; if (geometry instanceof OpenLayers.LonLat) { requestOptions.polygon = null; requestOptions.envelope = [geometry.lon - buffer, geometry.lat - buffer, geometry.lon + buffer, geometry.lat + buffer]; } else if (geometry instanceof OpenLayers.Geometry.Polygon) { requestOptions.envelope = null; requestOptions.polygon = geometry; }
    var arcxml = new OpenLayers.Format.ArcXML(requestOptions); OpenLayers.Util.extend(arcxml.request.get_feature, options); arcxml.request.get_feature.layer = layer.id; if (typeof layer.query.accuracy == "number") { arcxml.request.get_feature.query.accuracy = layer.query.accuracy; } else { var mapCenter = this.map.getCenter(); var viewPx = this.map.getViewPortPxFromLonLat(mapCenter); viewPx.x++; var mapOffCenter = this.map.getLonLatFromPixel(viewPx); arcxml.request.get_feature.query.accuracy = mapOffCenter.lon - mapCenter.lon; }
    arcxml.request.get_feature.query.where = layer.query.where; arcxml.request.get_feature.query.spatialfilter.relation = "area_intersection"; OpenLayers.Request.POST({ url: this.getFullRequestString({ 'CustomService': 'Query' }), data: arcxml.write(), callback: function (request) { var response = arcxml.parseResponse(request.responseText); if (!arcxml.iserror()) { callback.call(scope, response.features); } else { callback.call(scope, null); } } });
}, clone: function (obj) {
    if (obj == null) { obj = new OpenLayers.Layer.ArcIMS(this.name, this.url, this.getOptions()); }
    obj = OpenLayers.Layer.Grid.prototype.clone.apply(this, [obj]); return obj;
}, CLASS_NAME: "OpenLayers.Layer.ArcIMS"
}); OpenLayers.Format.OWSCommon.v1_1_0 = OpenLayers.Class(OpenLayers.Format.OWSCommon.v1, { namespaces: { ows: "http://www.opengis.net/ows/1.1", xlink: "http://www.w3.org/1999/xlink" }, readers: { "ows": OpenLayers.Util.applyDefaults({ "ExceptionReport": function (node, obj) { obj.exceptionReport = { version: node.getAttribute('version'), language: node.getAttribute('xml:lang'), exceptions: [] }; this.readChildNodes(node, obj.exceptionReport); }, "AllowedValues": function (node, parameter) { parameter.allowedValues = {}; this.readChildNodes(node, parameter.allowedValues); }, "AnyValue": function (node, parameter) { parameter.anyValue = true; }, "DataType": function (node, parameter) { parameter.dataType = this.getChildValue(node); }, "Range": function (node, allowedValues) { allowedValues.range = {}; this.readChildNodes(node, allowedValues.range); }, "MinimumValue": function (node, range) { range.minValue = this.getChildValue(node); }, "MaximumValue": function (node, range) { range.maxValue = this.getChildValue(node); }, "Identifier": function (node, obj) { obj.identifier = this.getChildValue(node); }, "SupportedCRS": function (node, obj) { obj.supportedCRS = this.getChildValue(node); } }, OpenLayers.Format.OWSCommon.v1.prototype.readers["ows"]) }, writers: { "ows": OpenLayers.Util.applyDefaults({ "Range": function (range) { var node = this.createElementNSPlus("ows:Range", { attributes: { 'ows:rangeClosure': range.closure} }); this.writeNode("ows:MinimumValue", range.minValue, node); this.writeNode("ows:MaximumValue", range.maxValue, node); return node; }, "MinimumValue": function (minValue) { var node = this.createElementNSPlus("ows:MinimumValue", { value: minValue }); return node; }, "MaximumValue": function (maxValue) { var node = this.createElementNSPlus("ows:MaximumValue", { value: maxValue }); return node; }, "Value": function (value) { var node = this.createElementNSPlus("ows:Value", { value: value }); return node; } }, OpenLayers.Format.OWSCommon.v1.prototype.writers["ows"]) }, CLASS_NAME: "OpenLayers.Format.OWSCommon.v1_1_0" }); OpenLayers.Format.WCSGetCoverage = OpenLayers.Class(OpenLayers.Format.XML, { namespaces: { ows: "http://www.opengis.net/ows/1.1", wcs: "http://www.opengis.net/wcs/1.1", xlink: "http://www.w3.org/1999/xlink", xsi: "http://www.w3.org/2001/XMLSchema-instance" }, regExes: { trimSpace: (/^\s*|\s*$/g), removeSpace: (/\s*/g), splitSpace: (/\s+/), trimComma: (/\s*,\s*/g) }, VERSION: "1.1.2", schemaLocation: "http://www.opengis.net/wcs/1.1 http://schemas.opengis.net/wcs/1.1/wcsGetCoverage.xsd", write: function (options) { var node = this.writeNode("wcs:GetCoverage", options); this.setAttributeNS(node, this.namespaces.xsi, "xsi:schemaLocation", this.schemaLocation); return OpenLayers.Format.XML.prototype.write.apply(this, [node]); }, writers: { "wcs": { "GetCoverage": function (options) { var node = this.createElementNSPlus("wcs:GetCoverage", { attributes: { version: options.version || this.VERSION, service: 'WCS'} }); this.writeNode("ows:Identifier", options.identifier, node); this.writeNode("wcs:DomainSubset", options.domainSubset, node); this.writeNode("wcs:Output", options.output, node); return node; }, "DomainSubset": function (domainSubset) {
    var node = this.createElementNSPlus("wcs:DomainSubset", {}); this.writeNode("ows:BoundingBox", domainSubset.boundingBox, node); if (domainSubset.temporalSubset) { this.writeNode("wcs:TemporalSubset", domainSubset.temporalSubset, node); }
    return node;
}, "TemporalSubset": function (temporalSubset) {
    var node = this.createElementNSPlus("wcs:TemporalSubset", {}); for (var i = 0, len = temporalSubset.timePeriods.length; i < len; ++i) { this.writeNode("wcs:TimePeriod", temporalSubset.timePeriods[i], node); }
    return node;
}, "TimePeriod": function (timePeriod) {
    var node = this.createElementNSPlus("wcs:TimePeriod", {}); this.writeNode("wcs:BeginPosition", timePeriod.begin, node); this.writeNode("wcs:EndPosition", timePeriod.end, node); if (timePeriod.resolution) { this.writeNode("wcs:TimeResolution", timePeriod.resolution, node); }
    return node;
}, "BeginPosition": function (begin) { var node = this.createElementNSPlus("wcs:BeginPosition", { value: begin }); return node; }, "EndPosition": function (end) { var node = this.createElementNSPlus("wcs:EndPosition", { value: end }); return node; }, "TimeResolution": function (resolution) { var node = this.createElementNSPlus("wcs:TimeResolution", { value: resolution }); return node; }, "Output": function (output) {
    var node = this.createElementNSPlus("wcs:Output", { attributes: { format: output.format, store: output.store} }); if (output.gridCRS) { this.writeNode("wcs:GridCRS", output.gridCRS, node); }
    return node;
}, "GridCRS": function (gridCRS) {
    var node = this.createElementNSPlus("wcs:GridCRS", {}); this.writeNode("wcs:GridBaseCRS", gridCRS.baseCRS, node); if (gridCRS.type) { this.writeNode("wcs:GridType", gridCRS.type, node); }
    if (gridCRS.origin) { this.writeNode("wcs:GridOrigin", gridCRS.origin, node); }
    this.writeNode("wcs:GridOffsets", gridCRS.offsets, node); if (gridCRS.CS) { this.writeNode("wcs:GridCS", gridCRS.CS, node); }
    return node;
}, "GridBaseCRS": function (baseCRS) { return this.createElementNSPlus("wcs:GridBaseCRS", { value: baseCRS }); }, "GridOrigin": function (origin) { return this.createElementNSPlus("wcs:GridOrigin", { value: origin }); }, "GridType": function (type) { return this.createElementNSPlus("wcs:GridType", { value: type }); }, "GridOffsets": function (offsets) { return this.createElementNSPlus("wcs:GridOffsets", { value: offsets }); }, "GridCS": function (CS) { return this.createElementNSPlus("wcs:GridCS", { value: CS }); }
}, "ows": OpenLayers.Format.OWSCommon.v1_1_0.prototype.writers.ows
}, CLASS_NAME: "OpenLayers.Format.WCSGetCoverage"
}); OpenLayers.Format.WPSExecute = OpenLayers.Class(OpenLayers.Format.XML, { namespaces: { ows: "http://www.opengis.net/ows/1.1", gml: "http://www.opengis.net/gml", wps: "http://www.opengis.net/wps/1.0.0", wfs: "http://www.opengis.net/wfs", ogc: "http://www.opengis.net/ogc", wcs: "http://www.opengis.net/wcs", xlink: "http://www.w3.org/1999/xlink", xsi: "http://www.w3.org/2001/XMLSchema-instance" }, regExes: { trimSpace: (/^\s*|\s*$/g), removeSpace: (/\s*/g), splitSpace: (/\s+/), trimComma: (/\s*,\s*/g) }, VERSION: "1.0.0", schemaLocation: "http://www.opengis.net/wps/1.0.0 http://schemas.opengis.net/wps/1.0.0/wpsAll.xsd", schemaLocationAttr: function (options) { return undefined; }, write: function (options) {
    var doc; if (window.ActiveXObject) { doc = new ActiveXObject("Microsoft.XMLDOM"); this.xmldom = doc; } else { doc = document.implementation.createDocument("", "", null); }
    var node = this.writeNode("wps:Execute", options, doc); this.setAttributeNS(node, this.namespaces.xsi, "xsi:schemaLocation", this.schemaLocation); return OpenLayers.Format.XML.prototype.write.apply(this, [node]);
}, writers: { "wps": { "Execute": function (options) { var node = this.createElementNSPlus("wps:Execute", { attributes: { version: this.VERSION, service: 'WPS'} }); this.writeNode("ows:Identifier", options.identifier, node); this.writeNode("wps:DataInputs", options.dataInputs, node); this.writeNode("wps:ResponseForm", options.responseForm, node); return node; }, "ResponseForm": function (responseForm) {
    var node = this.createElementNSPlus("wps:ResponseForm", {}); if (responseForm.rawDataOutput) { this.writeNode("wps:RawDataOutput", responseForm.rawDataOutput, node); }
    if (responseForm.responseDocument) { this.writeNode("wps:ResponseDocument", responseForm.responseDocument, node); }
    return node;
}, "ResponseDocument": function (responseDocument) {
    var node = this.createElementNSPlus("wps:ResponseDocument", { attributes: { storeExecuteResponse: responseDocument.storeExecuteResponse, lineage: responseDocument.lineage, status: responseDocument.status} }); if (responseDocument.output) { this.writeNode("wps:Output", responseDocument.output, node); }
    return node;
}, "Output": function (output) { var node = this.createElementNSPlus("wps:Output", { attributes: { asReference: output.asReference} }); this.writeNode("ows:Identifier", output.identifier, node); this.writeNode("ows:Title", output.title, node); this.writeNode("ows:Abstract", output["abstract"], node); return node; }, "RawDataOutput": function (rawDataOutput) { var node = this.createElementNSPlus("wps:RawDataOutput", { attributes: { mimeType: rawDataOutput.mimeType} }); this.writeNode("ows:Identifier", rawDataOutput.identifier, node); return node; }, "DataInputs": function (dataInputs) {
    var node = this.createElementNSPlus("wps:DataInputs", {}); for (var i = 0, ii = dataInputs.length; i < ii; ++i) { this.writeNode("wps:Input", dataInputs[i], node); }
    return node;
}, "Input": function (input) {
    var node = this.createElementNSPlus("wps:Input", {}); this.writeNode("ows:Identifier", input.identifier, node); if (input.title) { this.writeNode("ows:Title", input.title, node); }
    if (input.data) { this.writeNode("wps:Data", input.data, node); }
    if (input.reference) { this.writeNode("wps:Reference", input.reference, node); }
    return node;
}, "Data": function (data) {
    var node = this.createElementNSPlus("wps:Data", {}); if (data.literalData) { this.writeNode("wps:LiteralData", data.literalData, node); } else if (data.complexData) { this.writeNode("wps:ComplexData", data.complexData, node); }
    return node;
}, "LiteralData": function (literalData) { var node = this.createElementNSPlus("wps:LiteralData", { attributes: { uom: literalData.uom }, value: literalData.value }); return node; }, "ComplexData": function (complexData) { var node = this.createElementNSPlus("wps:ComplexData", { attributes: { mimeType: complexData.mimeType, encoding: complexData.encoding, schema: complexData.schema} }); node.appendChild(this.getXMLDoc().createCDATASection(complexData.value)); return node; }, "Reference": function (reference) {
    var node = this.createElementNSPlus("wps:Reference", { attributes: { mimeType: reference.mimeType, "xlink:href": reference.href, method: reference.method, encoding: reference.encoding, schema: reference.schema} }); if (reference.body) { this.writeNode("wps:Body", reference.body, node); }
    return node;
}, "Body": function (body) {
    var node = this.createElementNSPlus("wps:Body", {}); if (body.wcs) { this.writeNode("wcs:GetCoverage", body.wcs, node); }
    else if (body.wfs) { this.featureType = body.wfs.featureType; this.version = body.wfs.version; this.writeNode("wfs:GetFeature", body.wfs, node); } else { this.writeNode("wps:Execute", body, node); }
    return node;
}
}, "wcs": OpenLayers.Format.WCSGetCoverage.prototype.writers.wcs, "wfs": OpenLayers.Format.WFST.v1_1_0.prototype.writers.wfs, "ows": OpenLayers.Format.OWSCommon.v1_1_0.prototype.writers.ows
}, CLASS_NAME: "OpenLayers.Format.WPSExecute"
}); OpenLayers.Control.PanZoom = OpenLayers.Class(OpenLayers.Control, { slideFactor: 50, slideRatio: null, buttons: null, position: null, initialize: function (options) { this.position = new OpenLayers.Pixel(OpenLayers.Control.PanZoom.X, OpenLayers.Control.PanZoom.Y); OpenLayers.Control.prototype.initialize.apply(this, arguments); }, destroy: function () { this.removeButtons(); this.buttons = null; this.position = null; OpenLayers.Control.prototype.destroy.apply(this, arguments); }, draw: function (px) { OpenLayers.Control.prototype.draw.apply(this, arguments); px = this.position; this.buttons = []; var sz = new OpenLayers.Size(18, 18); var centered = new OpenLayers.Pixel(px.x + sz.w / 2, px.y); this._addButton("panup", "north-mini.png", centered, sz); px.y = centered.y + sz.h; this._addButton("panleft", "west-mini.png", px, sz); this._addButton("panright", "east-mini.png", px.add(sz.w, 0), sz); this._addButton("pandown", "south-mini.png", centered.add(0, sz.h * 2), sz); this._addButton("zoomin", "zoom-plus-mini.png", centered.add(0, sz.h * 3 + 5), sz); this._addButton("zoomworld", "zoom-world-mini.png", centered.add(0, sz.h * 4 + 5), sz); this._addButton("zoomout", "zoom-minus-mini.png", centered.add(0, sz.h * 5 + 5), sz); return this.div; }, _addButton: function (id, img, xy, sz) {
    var imgLocation = OpenLayers.Util.getImagesLocation() + img; var btn = OpenLayers.Util.createAlphaImageDiv(this.id + "_" + id, xy, sz, imgLocation, "absolute"); btn.style.cursor = "pointer"; this.div.appendChild(btn); OpenLayers.Event.observe(btn, "mousedown", OpenLayers.Function.bindAsEventListener(this.buttonDown, btn)); OpenLayers.Event.observe(btn, "dblclick", OpenLayers.Function.bindAsEventListener(this.doubleClick, btn)); OpenLayers.Event.observe(btn, "click", OpenLayers.Function.bindAsEventListener(this.doubleClick, btn)); btn.action = id; btn.map = this.map; if (!this.slideRatio) { var slideFactorPixels = this.slideFactor; var getSlideFactor = function () { return slideFactorPixels; }; } else { var slideRatio = this.slideRatio; var getSlideFactor = function (dim) { return this.map.getSize()[dim] * slideRatio; }; }
    btn.getSlideFactor = getSlideFactor; this.buttons.push(btn); return btn;
}, _removeButton: function (btn) { OpenLayers.Event.stopObservingElement(btn); btn.map = null; btn.getSlideFactor = null; this.div.removeChild(btn); OpenLayers.Util.removeItem(this.buttons, btn); }, removeButtons: function () { for (var i = this.buttons.length - 1; i >= 0; --i) { this._removeButton(this.buttons[i]); } }, doubleClick: function (evt) { OpenLayers.Event.stop(evt); return false; }, buttonDown: function (evt) {
    if (!OpenLayers.Event.isLeftClick(evt)) { return; }
    switch (this.action) { case "panup": this.map.pan(0, -this.getSlideFactor("h")); break; case "pandown": this.map.pan(0, this.getSlideFactor("h")); break; case "panleft": this.map.pan(-this.getSlideFactor("w"), 0); break; case "panright": this.map.pan(this.getSlideFactor("w"), 0); break; case "zoomin": this.map.zoomIn(); break; case "zoomout": this.map.zoomOut(); break; case "zoomworld": this.map.zoomToMaxExtent(); break; }
    OpenLayers.Event.stop(evt);
}, CLASS_NAME: "OpenLayers.Control.PanZoom"
}); OpenLayers.Control.PanZoom.X = 4; OpenLayers.Control.PanZoom.Y = 4; OpenLayers.Control.PanZoomBar = OpenLayers.Class(OpenLayers.Control.PanZoom, { zoomStopWidth: 18, zoomStopHeight: 11, slider: null, sliderEvents: null, zoombarDiv: null, divEvents: null, zoomWorldIcon: false, panIcons: true, forceFixedZoomLevel: false, mouseDragStart: null, deltaY: null, zoomStart: null, destroy: function () { this._removeZoomBar(); this.map.events.un({ "changebaselayer": this.redraw, scope: this }); OpenLayers.Control.PanZoom.prototype.destroy.apply(this, arguments); delete this.mouseDragStart; delete this.zoomStart; }, setMap: function (map) { OpenLayers.Control.PanZoom.prototype.setMap.apply(this, arguments); this.map.events.register("changebaselayer", this, this.redraw); }, redraw: function () {
    if (this.div != null) { this.removeButtons(); this._removeZoomBar(); }
    this.draw();
}, draw: function (px) {
    OpenLayers.Control.prototype.draw.apply(this, arguments); px = this.position.clone(); this.buttons = []; var sz = new OpenLayers.Size(18, 18); if (this.panIcons) {
        var centered = new OpenLayers.Pixel(px.x + sz.w / 2, px.y); var wposition = sz.w; if (this.zoomWorldIcon) { centered = new OpenLayers.Pixel(px.x + sz.w, px.y); }
        this._addButton("panup", "north-mini.png", centered, sz); px.y = centered.y + sz.h; this._addButton("panleft", "west-mini.png", px, sz); if (this.zoomWorldIcon) { this._addButton("zoomworld", "zoom-world-mini.png", px.add(sz.w, 0), sz); wposition *= 2; }
        this._addButton("panright", "east-mini.png", px.add(wposition, 0), sz); this._addButton("pandown", "south-mini.png", centered.add(0, sz.h * 2), sz); this._addButton("zoomin", "zoom-plus-mini.png", centered.add(0, sz.h * 3 + 5), sz); centered = this._addZoomBar(centered.add(0, sz.h * 4 + 5)); this._addButton("zoomout", "zoom-minus-mini.png", centered, sz);
    }
    else { this._addButton("zoomin", "zoom-plus-mini.png", px, sz); centered = this._addZoomBar(px.add(0, sz.h)); this._addButton("zoomout", "zoom-minus-mini.png", centered, sz); if (this.zoomWorldIcon) { centered = centered.add(0, sz.h + 3); this._addButton("zoomworld", "zoom-world-mini.png", centered, sz); } }
    return this.div;
}, _addZoomBar: function (centered) {
    var imgLocation = OpenLayers.Util.getImagesLocation(); var id = this.id + "_" + this.map.id; var zoomsToEnd = this.map.getNumZoomLevels() - 1 - this.map.getZoom(); var slider = OpenLayers.Util.createAlphaImageDiv(id, centered.add(-1, zoomsToEnd * this.zoomStopHeight), new OpenLayers.Size(20, 9), imgLocation + "slider.png", "absolute"); slider.style.cursor = "move"; this.slider = slider; this.sliderEvents = new OpenLayers.Events(this, slider, null, true, { includeXY: true }); this.sliderEvents.on({ "touchstart": this.zoomBarDown, "touchmove": this.zoomBarDrag, "touchend": this.zoomBarUp, "mousedown": this.zoomBarDown, "mousemove": this.zoomBarDrag, "mouseup": this.zoomBarUp, "dblclick": this.doubleClick, "click": this.doubleClick }); var sz = new OpenLayers.Size(); sz.h = this.zoomStopHeight * this.map.getNumZoomLevels(); sz.w = this.zoomStopWidth; var div = null; if (OpenLayers.Util.alphaHack()) { var id = this.id + "_" + this.map.id; div = OpenLayers.Util.createAlphaImageDiv(id, centered, new OpenLayers.Size(sz.w, this.zoomStopHeight), imgLocation + "zoombar.png", "absolute", null, "crop"); div.style.height = sz.h + "px"; } else { div = OpenLayers.Util.createDiv('OpenLayers_Control_PanZoomBar_Zoombar' + this.map.id, centered, sz, imgLocation + "zoombar.png"); }
    div.style.cursor = "pointer"; this.zoombarDiv = div; this.divEvents = new OpenLayers.Events(this, div, null, true, { includeXY: true }); this.divEvents.on({ "touchmove": this.passEventToSlider, "mousedown": this.divClick, "mousemove": this.passEventToSlider, "dblclick": this.doubleClick, "click": this.doubleClick }); this.div.appendChild(div); this.startTop = parseInt(div.style.top); this.div.appendChild(slider); this.map.events.register("zoomend", this, this.moveZoomBar); centered = centered.add(0, this.zoomStopHeight * this.map.getNumZoomLevels()); return centered;
}, _removeZoomBar: function () { this.sliderEvents.un({ "touchmove": this.zoomBarDrag, "mousedown": this.zoomBarDown, "mousemove": this.zoomBarDrag, "mouseup": this.zoomBarUp, "dblclick": this.doubleClick, "click": this.doubleClick }); this.sliderEvents.destroy(); this.divEvents.un({ "touchmove": this.passEventToSlider, "mousedown": this.divClick, "mousemove": this.passEventToSlider, "dblclick": this.doubleClick, "click": this.doubleClick }); this.divEvents.destroy(); this.div.removeChild(this.zoombarDiv); this.zoombarDiv = null; this.div.removeChild(this.slider); this.slider = null; this.map.events.unregister("zoomend", this, this.moveZoomBar); }, passEventToSlider: function (evt) { this.sliderEvents.handleBrowserEvent(evt); }, divClick: function (evt) {
    if (!OpenLayers.Event.isLeftClick(evt)) { return; }
    var levels = evt.xy.y / this.zoomStopHeight; if (this.forceFixedZoomLevel || !this.map.fractionalZoom) { levels = Math.floor(levels); }
    var zoom = (this.map.getNumZoomLevels() - 1) - levels; zoom = Math.min(Math.max(zoom, 0), this.map.getNumZoomLevels() - 1); this.map.zoomTo(zoom); OpenLayers.Event.stop(evt);
}, zoomBarDown: function (evt) {
    if (!OpenLayers.Event.isLeftClick(evt) && !OpenLayers.Event.isSingleTouch(evt)) { return; }
    this.map.events.on({ "touchmove": this.passEventToSlider, "mousemove": this.passEventToSlider, "mouseup": this.passEventToSlider, scope: this }); this.mouseDragStart = evt.xy.clone(); this.zoomStart = evt.xy.clone(); this.div.style.cursor = "move"; this.zoombarDiv.offsets = null; OpenLayers.Event.stop(evt);
}, zoomBarDrag: function (evt) {
    if (this.mouseDragStart != null) {
        var deltaY = this.mouseDragStart.y - evt.xy.y; var offsets = OpenLayers.Util.pagePosition(this.zoombarDiv); if ((evt.clientY - offsets[1]) > 0 && (evt.clientY - offsets[1]) < parseInt(this.zoombarDiv.style.height) - 2) { var newTop = parseInt(this.slider.style.top) - deltaY; this.slider.style.top = newTop + "px"; this.mouseDragStart = evt.xy.clone(); }
        this.deltaY = this.zoomStart.y - evt.xy.y; OpenLayers.Event.stop(evt);
    }
}, zoomBarUp: function (evt) {
    if (!OpenLayers.Event.isLeftClick(evt) && evt.type !== "touchend") { return; }
    if (this.mouseDragStart) {
        this.div.style.cursor = ""; this.map.events.un({ "touchmove": this.passEventToSlider, "mouseup": this.passEventToSlider, "mousemove": this.passEventToSlider, scope: this }); var zoomLevel = this.map.zoom; if (!this.forceFixedZoomLevel && this.map.fractionalZoom) { zoomLevel += this.deltaY / this.zoomStopHeight; zoomLevel = Math.min(Math.max(zoomLevel, 0), this.map.getNumZoomLevels() - 1); } else { zoomLevel += this.deltaY / this.zoomStopHeight; zoomLevel = Math.max(Math.round(zoomLevel), 0); }
        this.map.zoomTo(zoomLevel); this.mouseDragStart = null; this.zoomStart = null; this.deltaY = 0; OpenLayers.Event.stop(evt);
    }
}, moveZoomBar: function () { var newTop = ((this.map.getNumZoomLevels() - 1) - this.map.getZoom()) * this.zoomStopHeight + this.startTop + 1; this.slider.style.top = newTop + "px"; }, CLASS_NAME: "OpenLayers.Control.PanZoomBar"
}); OpenLayers.Layer.Image = OpenLayers.Class(OpenLayers.Layer, { isBaseLayer: true, url: null, extent: null, size: null, tile: null, aspectRatio: null, initialize: function (name, url, extent, size, options) { this.url = url; this.extent = extent; this.maxExtent = extent; this.size = size; OpenLayers.Layer.prototype.initialize.apply(this, [name, options]); this.aspectRatio = (this.extent.getHeight() / this.size.h) / (this.extent.getWidth() / this.size.w); }, destroy: function () {
    if (this.tile) { this.removeTileMonitoringHooks(this.tile); this.tile.destroy(); this.tile = null; }
    OpenLayers.Layer.prototype.destroy.apply(this, arguments);
}, clone: function (obj) {
    if (obj == null) { obj = new OpenLayers.Layer.Image(this.name, this.url, this.extent, this.size, this.getOptions()); }
    obj = OpenLayers.Layer.prototype.clone.apply(this, [obj]); return obj;
}, setMap: function (map) {
    if (this.options.maxResolution == null) { this.options.maxResolution = this.aspectRatio * this.extent.getWidth() / this.size.w; }
    OpenLayers.Layer.prototype.setMap.apply(this, arguments);
}, moveTo: function (bounds, zoomChanged, dragging) {
    OpenLayers.Layer.prototype.moveTo.apply(this, arguments); var firstRendering = (this.tile == null); if (zoomChanged || firstRendering) {
        this.setTileSize(); var ul = new OpenLayers.LonLat(this.extent.left, this.extent.top); var ulPx = this.map.getLayerPxFromLonLat(ul); if (firstRendering) { this.tile = new OpenLayers.Tile.Image(this, ulPx, this.extent, null, this.tileSize); this.addTileMonitoringHooks(this.tile); } else { this.tile.size = this.tileSize.clone(); this.tile.position = ulPx.clone(); }
        this.tile.draw();
    }
}, setTileSize: function () { var tileWidth = this.extent.getWidth() / this.map.getResolution(); var tileHeight = this.extent.getHeight() / this.map.getResolution(); this.tileSize = new OpenLayers.Size(tileWidth, tileHeight); }, addTileMonitoringHooks: function (tile) { tile.onLoadStart = function () { this.events.triggerEvent("loadstart"); }; tile.events.register("loadstart", this, tile.onLoadStart); tile.onLoadEnd = function () { this.events.triggerEvent("loadend"); }; tile.events.register("loadend", this, tile.onLoadEnd); tile.events.register("unload", this, tile.onLoadEnd); }, removeTileMonitoringHooks: function (tile) { tile.unload(); tile.events.un({ "loadstart": tile.onLoadStart, "loadend": tile.onLoadEnd, "unload": tile.onLoadEnd, scope: this }); }, setUrl: function (newUrl) { this.url = newUrl; this.tile.draw(); }, getURL: function (bounds) { return this.url; }, CLASS_NAME: "OpenLayers.Layer.Image"
}); OpenLayers.Strategy = OpenLayers.Class({ layer: null, options: null, active: null, autoActivate: true, autoDestroy: true, initialize: function (options) { OpenLayers.Util.extend(this, options); this.options = options; this.active = false; }, destroy: function () { this.deactivate(); this.layer = null; this.options = null; }, setLayer: function (layer) { this.layer = layer; }, activate: function () {
    if (!this.active) { this.active = true; return true; }
    return false;
}, deactivate: function () {
    if (this.active) { this.active = false; return true; }
    return false;
}, CLASS_NAME: "OpenLayers.Strategy"
}); OpenLayers.Strategy.Save = OpenLayers.Class(OpenLayers.Strategy, { EVENT_TYPES: ["start", "success", "fail"], events: null, auto: false, timer: null, initialize: function (options) { OpenLayers.Strategy.prototype.initialize.apply(this, [options]); this.events = new OpenLayers.Events(this, null, this.EVENT_TYPES); }, activate: function () {
    var activated = OpenLayers.Strategy.prototype.activate.call(this); if (activated) { if (this.auto) { if (typeof this.auto === "number") { this.timer = window.setInterval(OpenLayers.Function.bind(this.save, this), this.auto * 1000); } else { this.layer.events.on({ "featureadded": this.triggerSave, "afterfeaturemodified": this.triggerSave, scope: this }); } } }
    return activated;
}, deactivate: function () {
    var deactivated = OpenLayers.Strategy.prototype.deactivate.call(this); if (deactivated) { if (this.auto) { if (typeof this.auto === "number") { window.clearInterval(this.timer); } else { this.layer.events.un({ "featureadded": this.triggerSave, "afterfeaturemodified": this.triggerSave, scope: this }); } } }
    return deactivated;
}, triggerSave: function (event) { var feature = event.feature; if (feature.state === OpenLayers.State.INSERT || feature.state === OpenLayers.State.UPDATE || feature.state === OpenLayers.State.DELETE) { this.save([event.feature]); } }, save: function (features) {
    if (!features) { features = this.layer.features; }
    this.events.triggerEvent("start", { features: features }); var remote = this.layer.projection; var local = this.layer.map.getProjectionObject(); if (!local.equals(remote)) {
        var len = features.length; var clones = new Array(len); var orig, clone; for (var i = 0; i < len; ++i) {
            orig = features[i]; clone = orig.clone(); clone.fid = orig.fid; clone.state = orig.state; if (orig.url) { clone.url = orig.url; }
            clone._original = orig; clone.geometry.transform(local, remote); clones[i] = clone;
        }
        features = clones;
    }
    this.layer.protocol.commit(features, { callback: this.onCommit, scope: this });
}, onCommit: function (response) {
    var evt = { "response": response }; if (response.success()) {
        var features = response.reqFeatures; var state, feature; var destroys = []; var insertIds = response.insertIds || []; var j = 0; for (var i = 0, len = features.length; i < len; ++i) {
            feature = features[i]; feature = feature._original || feature; state = feature.state; if (state) {
                if (state == OpenLayers.State.DELETE) { destroys.push(feature); } else if (state == OpenLayers.State.INSERT) { feature.fid = insertIds[j]; ++j; }
                feature.state = null;
            }
        }
        if (destroys.length > 0) { this.layer.destroyFeatures(destroys); }
        this.events.triggerEvent("success", evt);
    } else { this.events.triggerEvent("fail", evt); }
}, CLASS_NAME: "OpenLayers.Strategy.Save"
}); OpenLayers.Format.GPX = OpenLayers.Class(OpenLayers.Format.XML, { extractWaypoints: true, extractTracks: true, extractRoutes: true, extractAttributes: true, initialize: function (options) { this.externalProjection = new OpenLayers.Projection("EPSG:4326"); OpenLayers.Format.XML.prototype.initialize.apply(this, [options]); }, read: function (doc) {
    if (typeof doc == "string") { doc = OpenLayers.Format.XML.prototype.read.apply(this, [doc]); }
    var features = []; if (this.extractTracks) {
        var tracks = doc.getElementsByTagName("trk"); for (var i = 0, len = tracks.length; i < len; i++) {
            var attrs = {}; if (this.extractAttributes) { attrs = this.parseAttributes(tracks[i]); }
            var segs = this.getElementsByTagNameNS(tracks[i], tracks[i].namespaceURI, "trkseg"); for (var j = 0, seglen = segs.length; j < seglen; j++) { var track = this.extractSegment(segs[j], "trkpt"); features.push(new OpenLayers.Feature.Vector(track, attrs)); }
        }
    }
    if (this.extractRoutes) {
        var routes = doc.getElementsByTagName("rte"); for (var k = 0, klen = routes.length; k < klen; k++) {
            var attrs = {}; if (this.extractAttributes) { attrs = this.parseAttributes(routes[k]); }
            var route = this.extractSegment(routes[k], "rtept"); features.push(new OpenLayers.Feature.Vector(route, attrs));
        }
    }
    if (this.extractWaypoints) {
        var waypoints = doc.getElementsByTagName("wpt"); for (var l = 0, len = waypoints.length; l < len; l++) {
            var attrs = {}; if (this.extractAttributes) { attrs = this.parseAttributes(waypoints[l]); }
            var wpt = new OpenLayers.Geometry.Point(waypoints[l].getAttribute("lon"), waypoints[l].getAttribute("lat")); features.push(new OpenLayers.Feature.Vector(wpt, attrs));
        }
    }
    if (this.internalProjection && this.externalProjection) { for (var g = 0, featLength = features.length; g < featLength; g++) { features[g].geometry.transform(this.externalProjection, this.internalProjection); } }
    return features;
}, extractSegment: function (segment, segmentType) {
    var points = this.getElementsByTagNameNS(segment, segment.namespaceURI, segmentType); var point_features = []; for (var i = 0, len = points.length; i < len; i++) { point_features.push(new OpenLayers.Geometry.Point(points[i].getAttribute("lon"), points[i].getAttribute("lat"))); }
    return new OpenLayers.Geometry.LineString(point_features);
}, parseAttributes: function (node) {
    var attributes = {}; var attrNode = node.firstChild, value, name; while (attrNode) {
        if (attrNode.nodeType == 1) { value = attrNode.firstChild; if (value.nodeType == 3 || value.nodeType == 4) { name = (attrNode.prefix) ? attrNode.nodeName.split(":")[1] : attrNode.nodeName; if (name != "trkseg" && name != "rtept") { attributes[name] = value.nodeValue; } } }
        attrNode = attrNode.nextSibling;
    }
    return attributes;
}, CLASS_NAME: "OpenLayers.Format.GPX"
}); OpenLayers.Format.WMSDescribeLayer = OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC, { defaultVersion: "1.1.1", getVersion: function (root, options) {
    var version = OpenLayers.Format.XML.VersionedOGC.prototype.getVersion.apply(this, arguments); if (version == "1.1.1" || version == "1.1.0") { version = "1.1"; }
    return version;
}, CLASS_NAME: "OpenLayers.Format.WMSDescribeLayer"
}); OpenLayers.Format.WMSDescribeLayer.v1_1 = OpenLayers.Class(OpenLayers.Format.WMSDescribeLayer, { initialize: function (options) { OpenLayers.Format.WMSDescribeLayer.prototype.initialize.apply(this, [options]); }, read: function (data) {
    if (typeof data == "string") { data = OpenLayers.Format.XML.prototype.read.apply(this, [data]); }
    var root = data.documentElement; var children = root.childNodes; var describelayer = []; var childNode, nodeName; for (var i = 0; i < children.length; ++i) {
        childNode = children[i]; nodeName = childNode.nodeName; if (nodeName == 'LayerDescription') {
            var layerName = childNode.getAttribute('name'); var owsType = ''; var owsURL = ''; var typeName = ''; if (childNode.getAttribute('owsType')) { owsType = childNode.getAttribute('owsType'); owsURL = childNode.getAttribute('owsURL'); } else { if (childNode.getAttribute('wfs') != '') { owsType = 'WFS'; owsURL = childNode.getAttribute('wfs'); } else if (childNode.getAttribute('wcs') != '') { owsType = 'WCS'; owsURL = childNode.getAttribute('wcs'); } }
            var query = childNode.getElementsByTagName('Query'); if (query.length > 0) { typeName = query[0].getAttribute('typeName'); if (!typeName) { typeName = query[0].getAttribute('typename'); } }
            describelayer.push({ layerName: layerName, owsType: owsType, owsURL: owsURL, typeName: typeName });
        }
    }
    return describelayer;
}, CLASS_NAME: "OpenLayers.Format.WMSDescribeLayer.v1_1"
}); OpenLayers.Format.XLS = OpenLayers.Class(OpenLayers.Format.XML.VersionedOGC, { defaultVersion: "1.1.0", stringifyOutput: true, CLASS_NAME: "OpenLayers.Format.XLS" }); OpenLayers.Format.XLS.v1 = OpenLayers.Class(OpenLayers.Format.XML, { namespaces: { xls: "http://www.opengis.net/xls", gml: "http://www.opengis.net/gml", xsi: "http://www.w3.org/2001/XMLSchema-instance" }, regExes: { trimSpace: (/^\s*|\s*$/g), removeSpace: (/\s*/g), splitSpace: (/\s+/), trimComma: (/\s*,\s*/g) }, xy: true, defaultPrefix: "xls", schemaLocation: null, initialize: function (options) { OpenLayers.Format.XML.prototype.initialize.apply(this, [options]); }, read: function (data, options) { options = OpenLayers.Util.applyDefaults(options, this.options); var xls = {}; this.readChildNodes(data, xls); return xls; }, readers: { "xls": { "XLS": function (node, xls) { xls.version = node.getAttribute("version"); this.readChildNodes(node, xls); }, "Response": function (node, xls) { this.readChildNodes(node, xls); }, "GeocodeResponse": function (node, xls) { xls.responseLists = []; this.readChildNodes(node, xls); }, "GeocodeResponseList": function (node, xls) { var responseList = { features: [], numberOfGeocodedAddresses: parseInt(node.getAttribute("numberOfGeocodedAddresses")) }; xls.responseLists.push(responseList); this.readChildNodes(node, responseList); }, "GeocodedAddress": function (node, responseList) { var feature = new OpenLayers.Feature.Vector(); responseList.features.push(feature); this.readChildNodes(node, feature); feature.geometry = feature.components[0]; }, "GeocodeMatchCode": function (node, feature) { feature.attributes.matchCode = { accuracy: parseFloat(node.getAttribute("accuracy")), matchType: node.getAttribute("matchType") }; }, "Address": function (node, feature) { var address = { countryCode: node.getAttribute("countryCode"), addressee: node.getAttribute("addressee"), street: [], place: [] }; feature.attributes.address = address; this.readChildNodes(node, address); }, "freeFormAddress": function (node, address) { address.freeFormAddress = this.getChildValue(node); }, "StreetAddress": function (node, address) { this.readChildNodes(node, address); }, "Building": function (node, address) { address.building = { 'number': node.getAttribute("number"), subdivision: node.getAttribute("subdivision"), buildingName: node.getAttribute("buildingName") }; }, "Street": function (node, address) { address.street.push(this.getChildValue(node)); }, "Place": function (node, address) { address.place[node.getAttribute("type")] = this.getChildValue(node); }, "PostalCode": function (node, address) { address.postalCode = this.getChildValue(node); } }, "gml": OpenLayers.Format.GML.v3.prototype.readers.gml }, write: function (request) { return this.writers.xls.XLS.apply(this, [request]); }, writers: { "xls": { "XLS": function (request) { var root = this.createElementNSPlus("xls:XLS", { attributes: { "version": this.VERSION, "xsi:schemaLocation": this.schemaLocation} }); this.writeNode("RequestHeader", request.header, root); this.writeNode("Request", request, root); return root; }, "RequestHeader": function (header) { return this.createElementNSPlus("xls:RequestHeader"); }, "Request": function (request) { var node = this.createElementNSPlus("xls:Request", { attributes: { methodName: "GeocodeRequest", requestID: request.requestID || "", version: this.VERSION} }); this.writeNode("GeocodeRequest", request.addresses, node); return node; }, "GeocodeRequest": function (addresses) {
    var node = this.createElementNSPlus("xls:GeocodeRequest"); for (var i = 0, len = addresses.length; i < len; i++) { this.writeNode("Address", addresses[i], node); }
    return node;
}, "Address": function (address) {
    var node = this.createElementNSPlus("xls:Address", { attributes: { countryCode: address.countryCode} }); if (address.freeFormAddress) { this.writeNode("freeFormAddess", address.freeFormAddress, node); } else {
        if (address.street) { this.writeNode("StreetAddress", address, node); }
        if (address.municipality) { this.writeNode("Municipality", address.municipality, node); }
        if (address.countrySubdivision) { this.writeNode("CountrySubdivision", address.countrySubdivision, node); }
        if (address.postalCode) { this.writeNode("PostalCode", address.postalCode, node); }
    }
    return node;
}, "freeFormAddress": function (freeFormAddress) { return this.createElementNSPlus("freeFormAddress", { value: freeFormAddress }); }, "StreetAddress": function (address) {
    var node = this.createElementNSPlus("xls:StreetAddress"); if (address.building) { this.writeNode(node, "Building", address.building); }
    var street = address.street; if (!(OpenLayers.Util.isArray(street))) { street = [street]; }
    for (var i = 0, len = street.length; i < len; i++) { this.writeNode("Street", street[i], node); }
    return node;
}, "Building": function (building) { return this.createElementNSPlus("xls:Building", { attributes: { "number": building["number"], "subdivision": building.subdivision, "buildingName": building.buildingName} }); }, "Street": function (street) { return this.createElementNSPlus("xls:Street", { value: street }); }, "Municipality": function (municipality) { return this.createElementNSPlus("xls:Place", { attributes: { type: "Municipality" }, value: municipality }); }, "CountrySubdivision": function (countrySubdivision) { return this.createElementNSPlus("xls:Place", { attributes: { type: "CountrySubdivision" }, value: countrySubdivision }); }, "PostalCode": function (postalCode) { return this.createElementNSPlus("xls:PostalCode", { value: postalCode }); }
}
}, CLASS_NAME: "OpenLayers.Format.XLS.v1"
}); OpenLayers.Renderer = OpenLayers.Class({ container: null, root: null, extent: null, locked: false, size: null, resolution: null, map: null, initialize: function (containerID, options) { this.container = OpenLayers.Util.getElement(containerID); OpenLayers.Util.extend(this, options); }, destroy: function () { this.container = null; this.extent = null; this.size = null; this.resolution = null; this.map = null; }, supported: function () { return false; }, setExtent: function (extent, resolutionChanged) { this.extent = extent.clone(); if (resolutionChanged) { this.resolution = null; } }, setSize: function (size) { this.size = size.clone(); this.resolution = null; }, getResolution: function () { this.resolution = this.resolution || this.map.getResolution(); return this.resolution; }, drawFeature: function (feature, style) {
    if (style == null) { style = feature.style; }
    if (feature.geometry) {
        var bounds = feature.geometry.getBounds(); if (bounds) {
            if (!bounds.intersectsBounds(this.extent)) { style = { display: "none" }; }
            var rendered = this.drawGeometry(feature.geometry, style, feature.id); if (style.display != "none" && style.label && rendered !== false) {
                var location = feature.geometry.getCentroid(); if (style.labelXOffset || style.labelYOffset) { var xOffset = isNaN(style.labelXOffset) ? 0 : style.labelXOffset; var yOffset = isNaN(style.labelYOffset) ? 0 : style.labelYOffset; var res = this.getResolution(); location.move(xOffset * res, yOffset * res); }
                this.drawText(feature.id, style, location);
            } else { this.removeText(feature.id); }
            return rendered;
        }
    }
}, drawGeometry: function (geometry, style, featureId) { }, drawText: function (featureId, style, location) { }, removeText: function (featureId) { }, clear: function () { }, getFeatureIdFromEvent: function (evt) { }, eraseFeatures: function (features) {
    if (!(OpenLayers.Util.isArray(features))) { features = [features]; }
    for (var i = 0, len = features.length; i < len; ++i) { var feature = features[i]; this.eraseGeometry(feature.geometry, feature.id); this.removeText(feature.id); }
}, eraseGeometry: function (geometry, featureId) { }, moveRoot: function (renderer) { }, getRenderLayerId: function () { return this.container.id; }, applyDefaultSymbolizer: function (symbolizer) {
    var result = OpenLayers.Util.extend({}, OpenLayers.Renderer.defaultSymbolizer); if (symbolizer.stroke === false) { delete result.strokeWidth; delete result.strokeColor; }
    if (symbolizer.fill === false) { delete result.fillColor; }
    OpenLayers.Util.extend(result, symbolizer); return result;
}, CLASS_NAME: "OpenLayers.Renderer"
}); OpenLayers.Renderer.defaultSymbolizer = { fillColor: "#000000", strokeColor: "#000000", strokeWidth: 2, fillOpacity: 1, strokeOpacity: 1, pointRadius: 0 }; OpenLayers.Renderer.Canvas = OpenLayers.Class(OpenLayers.Renderer, { hitDetection: true, hitOverflow: 0, canvas: null, features: null, pendingRedraw: false, initialize: function (containerID, options) { OpenLayers.Renderer.prototype.initialize.apply(this, arguments); this.root = document.createElement("canvas"); this.container.appendChild(this.root); this.canvas = this.root.getContext("2d"); this.features = {}; if (this.hitDetection) { this.hitCanvas = document.createElement("canvas"); this.hitContext = this.hitCanvas.getContext("2d"); } }, eraseGeometry: function (geometry, featureId) { this.eraseFeatures(this.features[featureId][0]); }, supported: function () { var canvas = document.createElement("canvas"); return !!canvas.getContext; }, setSize: function (size) { this.size = size.clone(); var root = this.root; root.style.width = size.w + "px"; root.style.height = size.h + "px"; root.width = size.w; root.height = size.h; this.resolution = null; if (this.hitDetection) { var hitCanvas = this.hitCanvas; hitCanvas.style.width = size.w + "px"; hitCanvas.style.height = size.h + "px"; hitCanvas.width = size.w; hitCanvas.height = size.h; } }, drawFeature: function (feature, style) {
    var rendered; if (feature.geometry) {
        style = this.applyDefaultSymbolizer(style || feature.style); var bounds = feature.geometry.getBounds(); rendered = (style.display !== "none") && !!bounds && bounds.intersectsBounds(this.extent); if (rendered) { this.features[feature.id] = [feature, style]; }
        else { delete (this.features[feature.id]); }
        this.pendingRedraw = true;
    }
    if (this.pendingRedraw && !this.locked) { this.redraw(); this.pendingRedraw = false; }
    return rendered;
}, drawGeometry: function (geometry, style, featureId) {
    var className = geometry.CLASS_NAME; if ((className == "OpenLayers.Geometry.Collection") || (className == "OpenLayers.Geometry.MultiPoint") || (className == "OpenLayers.Geometry.MultiLineString") || (className == "OpenLayers.Geometry.MultiPolygon")) {
        for (var i = 0; i < geometry.components.length; i++) { this.drawGeometry(geometry.components[i], style, featureId); }
        return;
    }
    switch (geometry.CLASS_NAME) { case "OpenLayers.Geometry.Point": this.drawPoint(geometry, style, featureId); break; case "OpenLayers.Geometry.LineString": this.drawLineString(geometry, style, featureId); break; case "OpenLayers.Geometry.LinearRing": this.drawLinearRing(geometry, style, featureId); break; case "OpenLayers.Geometry.Polygon": this.drawPolygon(geometry, style, featureId); break; default: break; }
}, drawExternalGraphic: function (geometry, style, featureId) {
    var img = new Image(); if (style.graphicTitle) { img.title = style.graphicTitle; }
    var width = style.graphicWidth || style.graphicHeight; var height = style.graphicHeight || style.graphicWidth; width = width ? width : style.pointRadius * 2; height = height ? height : style.pointRadius * 2; var xOffset = (style.graphicXOffset != undefined) ? style.graphicXOffset : -(0.5 * width); var yOffset = (style.graphicYOffset != undefined) ? style.graphicYOffset : -(0.5 * height); var opacity = style.graphicOpacity || style.fillOpacity; var onLoad = function () {
        if (!this.features[featureId]) { return; }
        var pt = this.getLocalXY(geometry); var p0 = pt[0]; var p1 = pt[1]; if (!isNaN(p0) && !isNaN(p1)) { var x = (p0 + xOffset) | 0; var y = (p1 + yOffset) | 0; var canvas = this.canvas; canvas.globalAlpha = opacity; var factor = OpenLayers.Renderer.Canvas.drawImageScaleFactor || (OpenLayers.Renderer.Canvas.drawImageScaleFactor = /android 2.1/.test(navigator.userAgent.toLowerCase()) ? 320 / window.screen.width : 1); canvas.drawImage(img, x * factor, y * factor, width * factor, height * factor); if (this.hitDetection) { this.setHitContextStyle("fill", featureId); this.hitContext.fillRect(x, y, width, height); } }
    }; img.onload = OpenLayers.Function.bind(onLoad, this); img.src = style.externalGraphic;
}, setCanvasStyle: function (type, style) { if (type === "fill") { this.canvas.globalAlpha = style['fillOpacity']; this.canvas.fillStyle = style['fillColor']; } else if (type === "stroke") { this.canvas.globalAlpha = style['strokeOpacity']; this.canvas.strokeStyle = style['strokeColor']; this.canvas.lineWidth = style['strokeWidth']; } else { this.canvas.globalAlpha = 0; this.canvas.lineWidth = 1; } }, featureIdToHex: function (featureId) {
    var id = Number(featureId.split("_").pop()) + 1; if (id >= 16777216) { this.hitOverflow = id - 16777215; id = id % 16777216 + 1; }
    var hex = "000000" + id.toString(16); var len = hex.length; hex = "#" + hex.substring(len - 6, len); return hex;
}, setHitContextStyle: function (type, featureId, symbolizer) { var hex = this.featureIdToHex(featureId); if (type == "fill") { this.hitContext.globalAlpha = 1.0; this.hitContext.fillStyle = hex; } else if (type == "stroke") { this.hitContext.globalAlpha = 1.0; this.hitContext.strokeStyle = hex; this.hitContext.lineWidth = symbolizer.strokeWidth + 2; } else { this.hitContext.globalAlpha = 0; this.hitContext.lineWidth = 1; } }, drawPoint: function (geometry, style, featureId) {
    if (style.graphic !== false) {
        if (style.externalGraphic) { this.drawExternalGraphic(geometry, style, featureId); } else {
            var pt = this.getLocalXY(geometry); var p0 = pt[0]; var p1 = pt[1]; if (!isNaN(p0) && !isNaN(p1)) {
                var twoPi = Math.PI * 2; var radius = style.pointRadius; if (style.fill !== false) { this.setCanvasStyle("fill", style); this.canvas.beginPath(); this.canvas.arc(p0, p1, radius, 0, twoPi, true); this.canvas.fill(); if (this.hitDetection) { this.setHitContextStyle("fill", featureId, style); this.hitContext.beginPath(); this.hitContext.arc(p0, p1, radius, 0, twoPi, true); this.hitContext.fill(); } }
                if (style.stroke !== false) {
                    this.setCanvasStyle("stroke", style); this.canvas.beginPath(); this.canvas.arc(p0, p1, radius, 0, twoPi, true); this.canvas.stroke(); if (this.hitDetection) { this.setHitContextStyle("stroke", featureId, style); this.hitContext.beginPath(); this.hitContext.arc(p0, p1, radius, 0, twoPi, true); this.hitContext.stroke(); }
                    this.setCanvasStyle("reset");
                }
            }
        }
    }
}, drawLineString: function (geometry, style, featureId) { style = OpenLayers.Util.applyDefaults({ fill: false }, style); this.drawLinearRing(geometry, style, featureId); }, drawLinearRing: function (geometry, style, featureId) {
    if (style.fill !== false) { this.setCanvasStyle("fill", style); this.renderPath(this.canvas, geometry, style, featureId, "fill"); if (this.hitDetection) { this.setHitContextStyle("fill", featureId, style); this.renderPath(this.hitContext, geometry, style, featureId, "fill"); } }
    if (style.stroke !== false) { this.setCanvasStyle("stroke", style); this.renderPath(this.canvas, geometry, style, featureId, "stroke"); if (this.hitDetection) { this.setHitContextStyle("stroke", featureId, style); this.renderPath(this.hitContext, geometry, style, featureId, "stroke"); } }
    this.setCanvasStyle("reset");
}, renderPath: function (context, geometry, style, featureId, type) {
    var components = geometry.components; var len = components.length; context.beginPath(); var start = this.getLocalXY(components[0]); var x = start[0]; var y = start[1]; if (!isNaN(x) && !isNaN(y)) {
        context.moveTo(start[0], start[1]); for (var i = 1; i < len; ++i) { var pt = this.getLocalXY(components[i]); context.lineTo(pt[0], pt[1]); }
        if (type === "fill") { context.fill(); } else { context.stroke(); }
    }
}, drawPolygon: function (geometry, style, featureId) {
    var components = geometry.components; var len = components.length; this.drawLinearRing(components[0], style, featureId); for (var i = 1; i < len; ++i) {
        this.canvas.globalCompositeOperation = "destination-out"; if (this.hitDetection) { this.hitContext.globalCompositeOperation = "destination-out"; }
        this.drawLinearRing(components[i], OpenLayers.Util.applyDefaults({ stroke: false, fillOpacity: 1.0 }, style), featureId); this.canvas.globalCompositeOperation = "source-over"; if (this.hitDetection) { this.hitContext.globalCompositeOperation = "source-over"; }
        this.drawLinearRing(components[i], OpenLayers.Util.applyDefaults({ fill: false }, style), featureId);
    }
}, drawText: function (location, style) {
    style = OpenLayers.Util.extend({ fontColor: "#000000", labelAlign: "cm" }, style); var pt = this.getLocalXY(location); this.setCanvasStyle("reset"); this.canvas.fillStyle = style.fontColor; this.canvas.globalAlpha = style.fontOpacity || 1.0; var fontStyle = [style.fontStyle ? style.fontStyle : "normal", "normal", style.fontWeight ? style.fontWeight : "normal", style.fontSize ? style.fontSize : "1em", style.fontFamily ? style.fontFamily : "sans-serif"].join(" "); var labelRows = style.label.split('\n'); var numRows = labelRows.length; if (this.canvas.fillText) {
        this.canvas.font = fontStyle; this.canvas.textAlign = OpenLayers.Renderer.Canvas.LABEL_ALIGN[style.labelAlign[0]] || "center"; this.canvas.textBaseline = OpenLayers.Renderer.Canvas.LABEL_ALIGN[style.labelAlign[1]] || "middle"; var vfactor = OpenLayers.Renderer.Canvas.LABEL_FACTOR[style.labelAlign[1]]; if (vfactor == null) { vfactor = -.5; }
        var lineHeight = this.canvas.measureText('Mg').height || this.canvas.measureText('xx').width; pt[1] += lineHeight * vfactor * (numRows - 1); for (var i = 0; i < numRows; i++) { this.canvas.fillText(labelRows[i], pt[0], pt[1] + (lineHeight * i)); }
    } else if (this.canvas.mozDrawText) {
        this.canvas.mozTextStyle = fontStyle; var hfactor = OpenLayers.Renderer.Canvas.LABEL_FACTOR[style.labelAlign[0]]; if (hfactor == null) { hfactor = -.5; }
        var vfactor = OpenLayers.Renderer.Canvas.LABEL_FACTOR[style.labelAlign[1]]; if (vfactor == null) { vfactor = -.5; }
        var lineHeight = this.canvas.mozMeasureText('xx'); pt[1] += lineHeight * (1 + (vfactor * numRows)); for (var i = 0; i < numRows; i++) { var x = pt[0] + (hfactor * this.canvas.mozMeasureText(labelRows[i])); var y = pt[1] + (i * lineHeight); this.canvas.translate(x, y); this.canvas.mozDrawText(labelRows[i]); this.canvas.translate(-x, -y); }
    }
    this.setCanvasStyle("reset");
}, getLocalXY: function (point) { var resolution = this.getResolution(); var extent = this.extent; var x = (point.x / resolution + (-extent.left / resolution)); var y = ((extent.top / resolution) - point.y / resolution); return [x, y]; }, clear: function () { var height = this.root.height; var width = this.root.width; this.canvas.clearRect(0, 0, width, height); this.features = {}; if (this.hitDetection) { this.hitContext.clearRect(0, 0, width, height); } }, getFeatureIdFromEvent: function (evt) {
    var feature = null; if (this.hitDetection) { if (!this.map.dragging) { var xy = evt.xy; var x = xy.x | 0; var y = xy.y | 0; var data = this.hitContext.getImageData(x, y, 1, 1).data; if (data[3] === 255) { var id = data[2] + (256 * (data[1] + (256 * data[0]))); if (id) { feature = this.features["OpenLayers.Feature.Vector_" + (id - 1 + this.hitOverflow)][0]; } } } }
    return feature;
}, eraseFeatures: function (features) {
    if (!(OpenLayers.Util.isArray(features))) { features = [features]; }
    for (var i = 0; i < features.length; ++i) { delete this.features[features[i].id]; }
    this.redraw();
}, redraw: function () {
    if (!this.locked) {
        var height = this.root.height; var width = this.root.width; this.canvas.clearRect(0, 0, width, height); if (this.hitDetection) { this.hitContext.clearRect(0, 0, width, height); }
        var labelMap = []; var feature, style; for (var id in this.features) {
            if (!this.features.hasOwnProperty(id)) { continue; }
            feature = this.features[id][0]; style = this.features[id][1]; this.drawGeometry(feature.geometry, style, feature.id); if (style.label) { labelMap.push([feature, style]); }
        }
        var item; for (var i = 0, len = labelMap.length; i < len; ++i) { item = labelMap[i]; this.drawText(item[0].geometry.getCentroid(), item[1]); }
    }
}, CLASS_NAME: "OpenLayers.Renderer.Canvas"
}); OpenLayers.Renderer.Canvas.LABEL_ALIGN = { "l": "left", "r": "right", "t": "top", "b": "bottom" }; OpenLayers.Renderer.Canvas.LABEL_FACTOR = { "l": 0, "r": -1, "t": 0, "b": -1 }; OpenLayers.Renderer.Canvas.drawImageScaleFactor = null; OpenLayers.Format.OSM = OpenLayers.Class(OpenLayers.Format.XML, { checkTags: false, interestingTagsExclude: null, areaTags: null, initialize: function (options) {
    var layer_defaults = { 'interestingTagsExclude': ['source', 'source_ref', 'source:ref', 'history', 'attribution', 'created_by'], 'areaTags': ['area', 'building', 'leisure', 'tourism', 'ruins', 'historic', 'landuse', 'military', 'natural', 'sport'] }; layer_defaults = OpenLayers.Util.extend(layer_defaults, options); var interesting = {}; for (var i = 0; i < layer_defaults.interestingTagsExclude.length; i++) { interesting[layer_defaults.interestingTagsExclude[i]] = true; }
    layer_defaults.interestingTagsExclude = interesting; var area = {}; for (var i = 0; i < layer_defaults.areaTags.length; i++) { area[layer_defaults.areaTags[i]] = true; }
    layer_defaults.areaTags = area; this.externalProjection = new OpenLayers.Projection("EPSG:4326"); OpenLayers.Format.XML.prototype.initialize.apply(this, [layer_defaults]);
}, read: function (doc) {
    if (typeof doc == "string") { doc = OpenLayers.Format.XML.prototype.read.apply(this, [doc]); }
    var nodes = this.getNodes(doc); var ways = this.getWays(doc); var feat_list = new Array(ways.length); for (var i = 0; i < ways.length; i++) {
        var point_list = new Array(ways[i].nodes.length); var poly = this.isWayArea(ways[i]) ? 1 : 0; for (var j = 0; j < ways[i].nodes.length; j++) { var node = nodes[ways[i].nodes[j]]; var point = new OpenLayers.Geometry.Point(node.lon, node.lat); point.osm_id = parseInt(ways[i].nodes[j]); point_list[j] = point; node.used = true; }
        var geometry = null; if (poly) { geometry = new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(point_list)); } else { geometry = new OpenLayers.Geometry.LineString(point_list); }
        if (this.internalProjection && this.externalProjection) { geometry.transform(this.externalProjection, this.internalProjection); }
        var feat = new OpenLayers.Feature.Vector(geometry, ways[i].tags); feat.osm_id = parseInt(ways[i].id); feat.fid = "way." + feat.osm_id; feat_list[i] = feat;
    }
    for (var node_id in nodes) {
        var node = nodes[node_id]; if (!node.used || this.checkTags) {
            var tags = null; if (this.checkTags) {
                var result = this.getTags(node.node, true); if (node.used && !result[1]) { continue; }
                tags = result[0];
            } else { tags = this.getTags(node.node); }
            var feat = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(node['lon'], node['lat']), tags); if (this.internalProjection && this.externalProjection) { feat.geometry.transform(this.externalProjection, this.internalProjection); }
            feat.osm_id = parseInt(node_id); feat.fid = "node." + feat.osm_id; feat_list.push(feat);
        }
        node.node = null;
    }
    return feat_list;
}, getNodes: function (doc) {
    var node_list = doc.getElementsByTagName("node"); var nodes = {}; for (var i = 0; i < node_list.length; i++) { var node = node_list[i]; var id = node.getAttribute("id"); nodes[id] = { 'lat': node.getAttribute("lat"), 'lon': node.getAttribute("lon"), 'node': node }; }
    return nodes;
}, getWays: function (doc) {
    var way_list = doc.getElementsByTagName("way"); var return_ways = []; for (var i = 0; i < way_list.length; i++) {
        var way = way_list[i]; var way_object = { id: way.getAttribute("id") }; way_object.tags = this.getTags(way); var node_list = way.getElementsByTagName("nd"); way_object.nodes = new Array(node_list.length); for (var j = 0; j < node_list.length; j++) { way_object.nodes[j] = node_list[j].getAttribute("ref"); }
        return_ways.push(way_object);
    }
    return return_ways;
}, getTags: function (dom_node, interesting_tags) {
    var tag_list = dom_node.getElementsByTagName("tag"); var tags = {}; var interesting = false; for (var j = 0; j < tag_list.length; j++) { var key = tag_list[j].getAttribute("k"); tags[key] = tag_list[j].getAttribute("v"); if (interesting_tags) { if (!this.interestingTagsExclude[key]) { interesting = true; } } }
    return interesting_tags ? [tags, interesting] : tags;
}, isWayArea: function (way) {
    var poly_shaped = false; var poly_tags = false; if (way.nodes[0] == way.nodes[way.nodes.length - 1]) { poly_shaped = true; }
    if (this.checkTags) { for (var key in way.tags) { if (this.areaTags[key]) { poly_tags = true; break; } } }
    return poly_shaped && (this.checkTags ? poly_tags : true);
}, write: function (features) {
    if (!(OpenLayers.Util.isArray(features))) { features = [features]; }
    this.osm_id = 1; this.created_nodes = {}; var root_node = this.createElementNS(null, "osm"); root_node.setAttribute("version", "0.5"); root_node.setAttribute("generator", "OpenLayers " + OpenLayers.VERSION_NUMBER); for (var i = features.length - 1; i >= 0; i--) { var nodes = this.createFeatureNodes(features[i]); for (var j = 0; j < nodes.length; j++) { root_node.appendChild(nodes[j]); } }
    return OpenLayers.Format.XML.prototype.write.apply(this, [root_node]);
}, createFeatureNodes: function (feature) {
    var nodes = []; var className = feature.geometry.CLASS_NAME; var type = className.substring(className.lastIndexOf(".") + 1); type = type.toLowerCase(); var builder = this.createXML[type]; if (builder) { nodes = builder.apply(this, [feature]); }
    return nodes;
}, createXML: { 'point': function (point) {
    var id = null; var geometry = point.geometry ? point.geometry : point; if (this.internalProjection && this.externalProjection) { geometry = geometry.clone(); geometry.transform(this.internalProjection, this.externalProjection); }
    var already_exists = false; if (point.osm_id) { id = point.osm_id; if (this.created_nodes[id]) { already_exists = true; } } else { id = -this.osm_id; this.osm_id++; }
    if (already_exists) { node = this.created_nodes[id]; } else { var node = this.createElementNS(null, "node"); }
    this.created_nodes[id] = node; node.setAttribute("id", id); node.setAttribute("lon", geometry.x); node.setAttribute("lat", geometry.y); if (point.attributes) { this.serializeTags(point, node); }
    this.setState(point, node); return already_exists ? [] : [node];
}, linestring: function (feature) {
    var id; var nodes = []; var geometry = feature.geometry; if (feature.osm_id) { id = feature.osm_id; } else { id = -this.osm_id; this.osm_id++; }
    var way = this.createElementNS(null, "way"); way.setAttribute("id", id); for (var i = 0; i < geometry.components.length; i++) {
        var node = this.createXML['point'].apply(this, [geometry.components[i]]); if (node.length) { node = node[0]; var node_ref = node.getAttribute("id"); nodes.push(node); } else { node_ref = geometry.components[i].osm_id; node = this.created_nodes[node_ref]; }
        this.setState(feature, node); var nd_dom = this.createElementNS(null, "nd"); nd_dom.setAttribute("ref", node_ref); way.appendChild(nd_dom);
    }
    this.serializeTags(feature, way); nodes.push(way); return nodes;
}, polygon: function (feature) { var attrs = OpenLayers.Util.extend({ 'area': 'yes' }, feature.attributes); var feat = new OpenLayers.Feature.Vector(feature.geometry.components[0], attrs); feat.osm_id = feature.osm_id; return this.createXML['linestring'].apply(this, [feat]); }
}, serializeTags: function (feature, node) { for (var key in feature.attributes) { var tag = this.createElementNS(null, "tag"); tag.setAttribute("k", key); tag.setAttribute("v", feature.attributes[key]); node.appendChild(tag); } }, setState: function (feature, node) {
    if (feature.state) {
        var state = null; switch (feature.state) { case OpenLayers.State.UPDATE: state = "modify"; case OpenLayers.State.DELETE: state = "delete"; }
        if (state) { node.setAttribute("action", state); }
    }
}, CLASS_NAME: "OpenLayers.Format.OSM"
}); OpenLayers.Handler = OpenLayers.Class({ id: null, control: null, map: null, keyMask: null, active: false, evt: null, initialize: function (control, callbacks, options) {
    OpenLayers.Util.extend(this, options); this.control = control; this.callbacks = callbacks; var map = this.map || control.map; if (map) { this.setMap(map); }
    this.id = OpenLayers.Util.createUniqueID(this.CLASS_NAME + "_");
}, setMap: function (map) { this.map = map; }, checkModifiers: function (evt) {
    if (this.keyMask == null) { return true; }
    var keyModifiers = (evt.shiftKey ? OpenLayers.Handler.MOD_SHIFT : 0) | (evt.ctrlKey ? OpenLayers.Handler.MOD_CTRL : 0) | (evt.altKey ? OpenLayers.Handler.MOD_ALT : 0); return (keyModifiers == this.keyMask);
}, activate: function () {
    if (this.active) { return false; }
    var events = OpenLayers.Events.prototype.BROWSER_EVENTS; for (var i = 0, len = events.length; i < len; i++) { if (this[events[i]]) { this.register(events[i], this[events[i]]); } }
    this.active = true; return true;
}, deactivate: function () {
    if (!this.active) { return false; }
    var events = OpenLayers.Events.prototype.BROWSER_EVENTS; for (var i = 0, len = events.length; i < len; i++) { if (this[events[i]]) { this.unregister(events[i], this[events[i]]); } }
    this.active = false; return true;
}, callback: function (name, args) { if (name && this.callbacks[name]) { this.callbacks[name].apply(this.control, args); } }, register: function (name, method) { this.map.events.registerPriority(name, this, method); this.map.events.registerPriority(name, this, this.setEvent); }, unregister: function (name, method) { this.map.events.unregister(name, this, method); this.map.events.unregister(name, this, this.setEvent); }, setEvent: function (evt) { this.evt = evt; return true; }, destroy: function () { this.deactivate(); this.control = this.map = null; }, CLASS_NAME: "OpenLayers.Handler"
}); OpenLayers.Handler.MOD_NONE = 0; OpenLayers.Handler.MOD_SHIFT = 1; OpenLayers.Handler.MOD_CTRL = 2; OpenLayers.Handler.MOD_ALT = 4; OpenLayers.Handler.Drag = OpenLayers.Class(OpenLayers.Handler, { started: false, stopDown: true, dragging: false, touch: false, last: null, start: null, lastMoveEvt: null, oldOnselectstart: null, interval: 0, timeoutId: null, documentDrag: false, documentEvents: null, initialize: function (control, callbacks, options) { OpenLayers.Handler.prototype.initialize.apply(this, arguments); if (this.documentDrag === true) { var me = this; this._docMove = function (evt) { me.mousemove({ xy: { x: evt.clientX, y: evt.clientY }, element: document }); }; this._docUp = function (evt) { me.mouseup({ xy: { x: evt.clientX, y: evt.clientY} }); }; } }, dragstart: function (evt) {
    var propagate = true; this.dragging = false; if (this.checkModifiers(evt) && (OpenLayers.Event.isLeftClick(evt) || OpenLayers.Event.isSingleTouch(evt))) {
        this.started = true; this.start = evt.xy; this.last = evt.xy; OpenLayers.Element.addClass(this.map.viewPortDiv, "olDragDown"); this.down(evt); this.callback("down", [evt.xy]); OpenLayers.Event.stop(evt); if (!this.oldOnselectstart) { this.oldOnselectstart = document.onselectstart ? document.onselectstart : OpenLayers.Function.True; }
        document.onselectstart = OpenLayers.Function.False; propagate = !this.stopDown;
    } else { this.started = false; this.start = null; this.last = null; }
    return propagate;
}, dragmove: function (evt) {
    this.lastMoveEvt = evt; if (this.started && !this.timeoutId && (evt.xy.x != this.last.x || evt.xy.y != this.last.y)) {
        if (this.documentDrag === true && this.documentEvents) { if (evt.element === document) { this.adjustXY(evt); this.setEvent(evt); } else { this.removeDocumentEvents(); } }
        if (this.interval > 0) { this.timeoutId = setTimeout(OpenLayers.Function.bind(this.removeTimeout, this), this.interval); }
        this.dragging = true; this.move(evt); this.callback("move", [evt.xy]); if (!this.oldOnselectstart) { this.oldOnselectstart = document.onselectstart; document.onselectstart = OpenLayers.Function.False; }
        this.last = evt.xy;
    }
    return true;
}, dragend: function (evt) {
    if (this.started) {
        if (this.documentDrag === true && this.documentEvents) { this.adjustXY(evt); this.removeDocumentEvents(); }
        var dragged = (this.start != this.last); this.started = false; this.dragging = false; OpenLayers.Element.removeClass(this.map.viewPortDiv, "olDragDown"); this.up(evt); this.callback("up", [evt.xy]); if (dragged) { this.callback("done", [evt.xy]); }
        document.onselectstart = this.oldOnselectstart;
    }
    return true;
}, down: function (evt) { }, move: function (evt) { }, up: function (evt) { }, out: function (evt) { }, mousedown: function (evt) { return this.dragstart(evt); }, touchstart: function (evt) {
    if (!this.touch) { this.touch = true; this.map.events.un({ mousedown: this.mousedown, mouseup: this.mouseup, mousemove: this.mousemove, click: this.click, scope: this }); }
    return this.dragstart(evt);
}, mousemove: function (evt) { return this.dragmove(evt); }, touchmove: function (evt) { return this.dragmove(evt); }, removeTimeout: function () { this.timeoutId = null; if (this.dragging) { this.mousemove(this.lastMoveEvt); } }, mouseup: function (evt) { return this.dragend(evt); }, touchend: function (evt) { evt.xy = this.last; return this.dragend(evt); }, mouseout: function (evt) {
    if (this.started && OpenLayers.Util.mouseLeft(evt, this.map.eventsDiv)) {
        if (this.documentDrag === true) { this.addDocumentEvents(); } else {
            var dragged = (this.start != this.last); this.started = false; this.dragging = false; OpenLayers.Element.removeClass(this.map.viewPortDiv, "olDragDown"); this.out(evt); this.callback("out", []); if (dragged) { this.callback("done", [evt.xy]); }
            if (document.onselectstart) { document.onselectstart = this.oldOnselectstart; }
        }
    }
    return true;
}, click: function (evt) { return (this.start == this.last); }, activate: function () {
    var activated = false; if (OpenLayers.Handler.prototype.activate.apply(this, arguments)) { this.dragging = false; activated = true; }
    return activated;
}, deactivate: function () {
    var deactivated = false; if (OpenLayers.Handler.prototype.deactivate.apply(this, arguments)) { this.touch = false; this.started = false; this.dragging = false; this.start = null; this.last = null; deactivated = true; OpenLayers.Element.removeClass(this.map.viewPortDiv, "olDragDown"); }
    return deactivated;
}, adjustXY: function (evt) { var pos = OpenLayers.Util.pagePosition(this.map.viewPortDiv); evt.xy.x -= pos[0]; evt.xy.y -= pos[1]; }, addDocumentEvents: function () { OpenLayers.Element.addClass(document.body, "olDragDown"); this.documentEvents = true; OpenLayers.Event.observe(document, "mousemove", this._docMove); OpenLayers.Event.observe(document, "mouseup", this._docUp); }, removeDocumentEvents: function () { OpenLayers.Element.removeClass(document.body, "olDragDown"); this.documentEvents = false; OpenLayers.Event.stopObserving(document, "mousemove", this._docMove); OpenLayers.Event.stopObserving(document, "mouseup", this._docUp); }, CLASS_NAME: "OpenLayers.Handler.Drag"
}); OpenLayers.Handler.Feature = OpenLayers.Class(OpenLayers.Handler, { EVENTMAP: { 'click': { 'in': 'click', 'out': 'clickout' }, 'mousemove': { 'in': 'over', 'out': 'out' }, 'dblclick': { 'in': 'dblclick', 'out': null }, 'mousedown': { 'in': null, 'out': null }, 'mouseup': { 'in': null, 'out': null }, 'touchstart': { 'in': 'click', 'out': 'clickout'} }, feature: null, lastFeature: null, down: null, up: null, touch: false, clickTolerance: 4, geometryTypes: null, stopClick: true, stopDown: true, stopUp: false, initialize: function (control, layer, callbacks, options) { OpenLayers.Handler.prototype.initialize.apply(this, [control, callbacks, options]); this.layer = layer; }, touchstart: function (evt) {
    if (!this.touch) { this.touch = true; this.map.events.un({ mousedown: this.mousedown, mouseup: this.mouseup, mousemove: this.mousemove, click: this.click, dblclick: this.dblclick, scope: this }); }
    return OpenLayers.Event.isMultiTouch(evt) ? true : this.mousedown(evt);
}, touchmove: function (evt) { OpenLayers.Event.stop(evt); }, mousedown: function (evt) { this.down = evt.xy; return this.handle(evt) ? !this.stopDown : true; }, mouseup: function (evt) { this.up = evt.xy; return this.handle(evt) ? !this.stopUp : true; }, click: function (evt) { return this.handle(evt) ? !this.stopClick : true; }, mousemove: function (evt) {
    if (!this.callbacks['over'] && !this.callbacks['out']) { return true; }
    this.handle(evt); return true;
}, dblclick: function (evt) { return !this.handle(evt); }, geometryTypeMatches: function (feature) { return this.geometryTypes == null || OpenLayers.Util.indexOf(this.geometryTypes, feature.geometry.CLASS_NAME) > -1; }, handle: function (evt) {
    if (this.feature && !this.feature.layer) { this.feature = null; }
    var type = evt.type; var handled = false; var previouslyIn = !!(this.feature); var click = (type == "click" || type == "dblclick" || type == "touchstart"); this.feature = this.layer.getFeatureFromEvent(evt); if (this.feature && !this.feature.layer) { this.feature = null; }
    if (this.lastFeature && !this.lastFeature.layer) { this.lastFeature = null; }
    if (this.feature) {
        if (type === "touchstart") { OpenLayers.Event.stop(evt); }
        var inNew = (this.feature != this.lastFeature); if (this.geometryTypeMatches(this.feature)) {
            if (previouslyIn && inNew) {
                if (this.lastFeature) { this.triggerCallback(type, 'out', [this.lastFeature]); }
                this.triggerCallback(type, 'in', [this.feature]);
            } else if (!previouslyIn || click) { this.triggerCallback(type, 'in', [this.feature]); }
            this.lastFeature = this.feature; handled = true;
        } else {
            if (this.lastFeature && (previouslyIn && inNew || click)) { this.triggerCallback(type, 'out', [this.lastFeature]); }
            this.feature = null;
        }
    } else { if (this.lastFeature && (previouslyIn || click)) { this.triggerCallback(type, 'out', [this.lastFeature]); } }
    return handled;
}, triggerCallback: function (type, mode, args) {
    var key = this.EVENTMAP[type][mode]; if (key) {
        if (type == 'click' && this.up && this.down) {
            var dpx = Math.sqrt(Math.pow(this.up.x - this.down.x, 2) +
Math.pow(this.up.y - this.down.y, 2)); if (dpx <= this.clickTolerance) { this.callback(key, args); }
        } else { this.callback(key, args); }
    }
}, activate: function () {
    var activated = false; if (OpenLayers.Handler.prototype.activate.apply(this, arguments)) { this.moveLayerToTop(); this.map.events.on({ "removelayer": this.handleMapEvents, "changelayer": this.handleMapEvents, scope: this }); activated = true; }
    return activated;
}, deactivate: function () {
    var deactivated = false; if (OpenLayers.Handler.prototype.deactivate.apply(this, arguments)) { this.moveLayerBack(); this.feature = null; this.lastFeature = null; this.down = null; this.up = null; this.touch = false; this.map.events.un({ "removelayer": this.handleMapEvents, "changelayer": this.handleMapEvents, scope: this }); deactivated = true; }
    return deactivated;
}, handleMapEvents: function (evt) { if (evt.type == "removelayer" || evt.property == "order") { this.moveLayerToTop(); } }, moveLayerToTop: function () { var index = Math.max(this.map.Z_INDEX_BASE['Feature'] - 1, this.layer.getZIndex()) + 1; this.layer.setZIndex(index); }, moveLayerBack: function () { var index = this.layer.getZIndex() - 1; if (index >= this.map.Z_INDEX_BASE['Feature']) { this.layer.setZIndex(index); } else { this.map.setLayerZIndex(this.layer, this.map.getLayerIndex(this.layer)); } }, CLASS_NAME: "OpenLayers.Handler.Feature"
}); OpenLayers.Control.DragFeature = OpenLayers.Class(OpenLayers.Control, { geometryTypes: null, onStart: function (feature, pixel) { }, onDrag: function (feature, pixel) { }, onComplete: function (feature, pixel) { }, onEnter: function (feature) { }, onLeave: function (feature) { }, documentDrag: false, layer: null, feature: null, dragCallbacks: {}, featureCallbacks: {}, lastPixel: null, initialize: function (layer, options) { OpenLayers.Control.prototype.initialize.apply(this, [options]); this.layer = layer; this.handlers = { drag: new OpenLayers.Handler.Drag(this, OpenLayers.Util.extend({ down: this.downFeature, move: this.moveFeature, up: this.upFeature, out: this.cancel, done: this.doneDragging }, this.dragCallbacks), { documentDrag: this.documentDrag }), feature: new OpenLayers.Handler.Feature(this, this.layer, OpenLayers.Util.extend({ click: this.clickFeature, clickout: this.clickoutFeature, over: this.overFeature, out: this.outFeature }, this.featureCallbacks), { geometryTypes: this.geometryTypes }) }; }, clickFeature: function (feature) { if (this.handlers.feature.touch && !this.over && this.overFeature(feature)) { this.handlers.drag.dragstart(this.handlers.feature.evt); this.handlers.drag.stopDown = false; } }, clickoutFeature: function (feature) { if (this.handlers.feature.touch && this.over) { this.outFeature(feature); this.handlers.drag.stopDown = true; } }, destroy: function () { this.layer = null; OpenLayers.Control.prototype.destroy.apply(this, []); }, activate: function () { return (this.handlers.feature.activate() && OpenLayers.Control.prototype.activate.apply(this, arguments)); }, deactivate: function () { this.handlers.drag.deactivate(); this.handlers.feature.deactivate(); this.feature = null; this.dragging = false; this.lastPixel = null; OpenLayers.Element.removeClass(this.map.viewPortDiv, this.displayClass + "Over"); return OpenLayers.Control.prototype.deactivate.apply(this, arguments); }, overFeature: function (feature) {
    var activated = false; if (!this.handlers.drag.dragging) { this.feature = feature; this.handlers.drag.activate(); activated = true; this.over = true; OpenLayers.Element.addClass(this.map.viewPortDiv, this.displayClass + "Over"); this.onEnter(feature); } else { if (this.feature.id == feature.id) { this.over = true; } else { this.over = false; } }
    return activated;
}, downFeature: function (pixel) { this.lastPixel = pixel; this.onStart(this.feature, pixel); }, moveFeature: function (pixel) { var res = this.map.getResolution(); this.feature.geometry.move(res * (pixel.x - this.lastPixel.x), res * (this.lastPixel.y - pixel.y)); this.layer.drawFeature(this.feature); this.lastPixel = pixel; this.onDrag(this.feature, pixel); }, upFeature: function (pixel) { if (!this.over) { this.handlers.drag.deactivate(); } }, doneDragging: function (pixel) { this.onComplete(this.feature, pixel); }, outFeature: function (feature) { if (!this.handlers.drag.dragging) { this.over = false; this.handlers.drag.deactivate(); OpenLayers.Element.removeClass(this.map.viewPortDiv, this.displayClass + "Over"); this.onLeave(feature); this.feature = null; } else { if (this.feature.id == feature.id) { this.over = false; } } }, cancel: function () { this.handlers.drag.deactivate(); this.over = false; }, setMap: function (map) { this.handlers.drag.setMap(map); this.handlers.feature.setMap(map); OpenLayers.Control.prototype.setMap.apply(this, arguments); }, CLASS_NAME: "OpenLayers.Control.DragFeature"
}); OpenLayers.StyleMap = OpenLayers.Class({ styles: null, extendDefault: true, initialize: function (style, options) {
    this.styles = { "default": new OpenLayers.Style(OpenLayers.Feature.Vector.style["default"]), "select": new OpenLayers.Style(OpenLayers.Feature.Vector.style["select"]), "temporary": new OpenLayers.Style(OpenLayers.Feature.Vector.style["temporary"]), "delete": new OpenLayers.Style(OpenLayers.Feature.Vector.style["delete"]) }; if (style instanceof OpenLayers.Style) { this.styles["default"] = style; this.styles["select"] = style; this.styles["temporary"] = style; this.styles["delete"] = style; } else if (typeof style == "object") { for (var key in style) { if (style[key] instanceof OpenLayers.Style) { this.styles[key] = style[key]; } else if (typeof style[key] == "object") { this.styles[key] = new OpenLayers.Style(style[key]); } else { this.styles["default"] = new OpenLayers.Style(style); this.styles["select"] = new OpenLayers.Style(style); this.styles["temporary"] = new OpenLayers.Style(style); this.styles["delete"] = new OpenLayers.Style(style); break; } } }
    OpenLayers.Util.extend(this, options);
}, destroy: function () {
    for (var key in this.styles) { this.styles[key].destroy(); }
    this.styles = null;
}, createSymbolizer: function (feature, intent) {
    if (!feature) { feature = new OpenLayers.Feature.Vector(); }
    if (!this.styles[intent]) { intent = "default"; }
    feature.renderIntent = intent; var defaultSymbolizer = {}; if (this.extendDefault && intent != "default") { defaultSymbolizer = this.styles["default"].createSymbolizer(feature); }
    return OpenLayers.Util.extend(defaultSymbolizer, this.styles[intent].createSymbolizer(feature));
}, addUniqueValueRules: function (renderIntent, property, symbolizers, context) {
    var rules = []; for (var value in symbolizers) { rules.push(new OpenLayers.Rule({ symbolizer: symbolizers[value], context: context, filter: new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.EQUAL_TO, property: property, value: value }) })); }
    this.styles[renderIntent].addRules(rules);
}, CLASS_NAME: "OpenLayers.StyleMap"
}); OpenLayers.Layer.Vector = OpenLayers.Class(OpenLayers.Layer, { EVENT_TYPES: ["beforefeatureadded", "beforefeaturesadded", "featureadded", "featuresadded", "beforefeatureremoved", "beforefeaturesremoved", "featureremoved", "featuresremoved", "beforefeatureselected", "featureselected", "featureunselected", "beforefeaturemodified", "featuremodified", "afterfeaturemodified", "vertexmodified", "vertexremoved", "sketchstarted", "sketchmodified", "sketchcomplete", "refresh"], isBaseLayer: false, isFixed: false, features: null, filter: null, selectedFeatures: null, unrenderedFeatures: null, reportError: true, style: null, styleMap: null, strategies: null, protocol: null, renderers: ['SVG', 'VML', 'Canvas'], renderer: null, rendererOptions: null, geometryType: null, drawn: false, initialize: function (name, options) {
    this.EVENT_TYPES = OpenLayers.Layer.Vector.prototype.EVENT_TYPES.concat(OpenLayers.Layer.prototype.EVENT_TYPES); OpenLayers.Layer.prototype.initialize.apply(this, arguments); if (!this.renderer || !this.renderer.supported()) { this.assignRenderer(); }
    if (!this.renderer || !this.renderer.supported()) { this.renderer = null; this.displayError(); }
    if (!this.styleMap) { this.styleMap = new OpenLayers.StyleMap(); }
    this.features = []; this.selectedFeatures = []; this.unrenderedFeatures = {}; if (this.strategies) { for (var i = 0, len = this.strategies.length; i < len; i++) { this.strategies[i].setLayer(this); } }
}, destroy: function () {
    if (this.strategies) {
        var strategy, i, len; for (i = 0, len = this.strategies.length; i < len; i++) { strategy = this.strategies[i]; if (strategy.autoDestroy) { strategy.destroy(); } }
        this.strategies = null;
    }
    if (this.protocol) {
        if (this.protocol.autoDestroy) { this.protocol.destroy(); }
        this.protocol = null;
    }
    this.destroyFeatures(); this.features = null; this.selectedFeatures = null; this.unrenderedFeatures = null; if (this.renderer) { this.renderer.destroy(); }
    this.renderer = null; this.geometryType = null; this.drawn = null; OpenLayers.Layer.prototype.destroy.apply(this, arguments);
}, clone: function (obj) {
    if (obj == null) { obj = new OpenLayers.Layer.Vector(this.name, this.getOptions()); }
    obj = OpenLayers.Layer.prototype.clone.apply(this, [obj]); var features = this.features; var len = features.length; var clonedFeatures = new Array(len); for (var i = 0; i < len; ++i) { clonedFeatures[i] = features[i].clone(); }
    obj.features = clonedFeatures; return obj;
}, refresh: function (obj) { if (this.calculateInRange() && this.visibility) { this.events.triggerEvent("refresh", obj); } }, assignRenderer: function () { for (var i = 0, len = this.renderers.length; i < len; i++) { var rendererClass = this.renderers[i]; var renderer = (typeof rendererClass == "function") ? rendererClass : OpenLayers.Renderer[rendererClass]; if (renderer && renderer.prototype.supported()) { this.renderer = new renderer(this.div, this.rendererOptions); break; } } }, displayError: function () { if (this.reportError) { OpenLayers.Console.userError(OpenLayers.i18n("browserNotSupported", { 'renderers': this.renderers.join("\n") })); } }, setMap: function (map) { OpenLayers.Layer.prototype.setMap.apply(this, arguments); if (!this.renderer) { this.map.removeLayer(this); } else { this.renderer.map = this.map; this.renderer.setSize(this.map.getSize()); } }, afterAdd: function () { if (this.strategies) { var strategy, i, len; for (i = 0, len = this.strategies.length; i < len; i++) { strategy = this.strategies[i]; if (strategy.autoActivate) { strategy.activate(); } } } }, removeMap: function (map) { this.drawn = false; if (this.strategies) { var strategy, i, len; for (i = 0, len = this.strategies.length; i < len; i++) { strategy = this.strategies[i]; if (strategy.autoActivate) { strategy.deactivate(); } } } }, onMapResize: function () { OpenLayers.Layer.prototype.onMapResize.apply(this, arguments); this.renderer.setSize(this.map.getSize()); }, moveTo: function (bounds, zoomChanged, dragging) {
    OpenLayers.Layer.prototype.moveTo.apply(this, arguments); var ng = (OpenLayers.Renderer.NG && this.renderer instanceof OpenLayers.Renderer.NG); if (ng) { dragging || this.renderer.updateDimensions(zoomChanged); } else {
        var coordSysUnchanged = true; if (!dragging) {
            this.renderer.root.style.visibility = "hidden"; this.div.style.left = -parseInt(this.map.layerContainerDiv.style.left) + "px"; this.div.style.top = -parseInt(this.map.layerContainerDiv.style.top) + "px"; var extent = this.map.getExtent(); coordSysUnchanged = this.renderer.setExtent(extent, zoomChanged); this.renderer.root.style.visibility = "visible"; if (OpenLayers.IS_GECKO === true) { this.div.scrollLeft = this.div.scrollLeft; }
            if (!zoomChanged && coordSysUnchanged) { for (var i in this.unrenderedFeatures) { var feature = this.unrenderedFeatures[i]; this.drawFeature(feature); } }
        }
    }
    if (!this.drawn || (!ng && (zoomChanged || !coordSysUnchanged))) { this.drawn = true; var feature; for (var i = 0, len = this.features.length; i < len; i++) { this.renderer.locked = (i !== (len - 1)); feature = this.features[i]; this.drawFeature(feature); } }
}, redraw: function () {
    if (OpenLayers.Renderer.NG && this.renderer instanceof OpenLayers.Renderer.NG) { this.drawn = false; }
    return OpenLayers.Layer.prototype.redraw.apply(this, arguments);
}, display: function (display) { OpenLayers.Layer.prototype.display.apply(this, arguments); var currentDisplay = this.div.style.display; if (currentDisplay != this.renderer.root.style.display) { this.renderer.root.style.display = currentDisplay; } }, addFeatures: function (features, options) {
    if (!(OpenLayers.Util.isArray(features))) { features = [features]; }
    var notify = !options || !options.silent; if (notify) {
        var event = { features: features }; var ret = this.events.triggerEvent("beforefeaturesadded", event); if (ret === false) { return; }
        features = event.features;
    }
    var featuresAdded = []; for (var i = 0, len = features.length; i < len; i++) {
        if (i != (features.length - 1)) { this.renderer.locked = true; } else { this.renderer.locked = false; }
        var feature = features[i]; if (this.geometryType && !(feature.geometry instanceof this.geometryType)) { var throwStr = OpenLayers.i18n('componentShouldBe', { 'geomType': this.geometryType.prototype.CLASS_NAME }); throw throwStr; }
        feature.layer = this; if (!feature.style && this.style) { feature.style = OpenLayers.Util.extend({}, this.style); }
        if (notify) {
            if (this.events.triggerEvent("beforefeatureadded", { feature: feature }) === false) { continue; }
            this.preFeatureInsert(feature);
        }
        featuresAdded.push(feature); this.features.push(feature); this.drawFeature(feature); if (notify) { this.events.triggerEvent("featureadded", { feature: feature }); this.onFeatureInsert(feature); }
    }
    if (notify) { this.events.triggerEvent("featuresadded", { features: featuresAdded }); }
}, removeFeatures: function (features, options) {
    if (!features || features.length === 0) { return; }
    if (features === this.features) { return this.removeAllFeatures(options); }
    if (!(OpenLayers.Util.isArray(features))) { features = [features]; }
    if (features === this.selectedFeatures) { features = features.slice(); }
    var notify = !options || !options.silent; if (notify) { this.events.triggerEvent("beforefeaturesremoved", { features: features }); }
    for (var i = features.length - 1; i >= 0; i--) {
        if (i != 0 && features[i - 1].geometry) { this.renderer.locked = true; } else { this.renderer.locked = false; }
        var feature = features[i]; delete this.unrenderedFeatures[feature.id]; if (notify) { this.events.triggerEvent("beforefeatureremoved", { feature: feature }); }
        this.features = OpenLayers.Util.removeItem(this.features, feature); feature.layer = null; if (feature.geometry) { this.renderer.eraseFeatures(feature); }
        if (OpenLayers.Util.indexOf(this.selectedFeatures, feature) != -1) { OpenLayers.Util.removeItem(this.selectedFeatures, feature); }
        if (notify) { this.events.triggerEvent("featureremoved", { feature: feature }); }
    }
    if (notify) { this.events.triggerEvent("featuresremoved", { features: features }); }
}, removeAllFeatures: function (options) {
    var notify = !options || !options.silent; var features = this.features; if (notify) { this.events.triggerEvent("beforefeaturesremoved", { features: features }); }
    var feature; for (var i = features.length - 1; i >= 0; i--) {
        feature = features[i]; if (notify) { this.events.triggerEvent("beforefeatureremoved", { feature: feature }); }
        feature.layer = null; if (notify) { this.events.triggerEvent("featureremoved", { feature: feature }); }
    }
    this.renderer.clear(); this.features = []; this.unrenderedFeatures = {}; this.selectedFeatures = []; if (notify) { this.events.triggerEvent("featuresremoved", { features: features }); }
}, destroyFeatures: function (features, options) {
    var all = (features == undefined); if (all) { features = this.features; }
    if (features) { this.removeFeatures(features, options); for (var i = features.length - 1; i >= 0; i--) { features[i].destroy(); } }
}, drawFeature: function (feature, style) {
    if (!this.drawn) { return; }
    if (typeof style != "object") {
        if (!style && feature.state === OpenLayers.State.DELETE) { style = "delete"; }
        var renderIntent = style || feature.renderIntent; style = feature.style || this.style; if (!style) { style = this.styleMap.createSymbolizer(feature, renderIntent); }
    }
    var drawn = this.renderer.drawFeature(feature, style); if (drawn === false || drawn === null) { this.unrenderedFeatures[feature.id] = feature; } else { delete this.unrenderedFeatures[feature.id]; }
}, eraseFeatures: function (features) { this.renderer.eraseFeatures(features); }, getFeatureFromEvent: function (evt) {
    if (!this.renderer) { OpenLayers.Console.error(OpenLayers.i18n("getFeatureError")); return null; }
    var feature = null; var featureId = this.renderer.getFeatureIdFromEvent(evt); if (featureId) { if (typeof featureId === "string") { feature = this.getFeatureById(featureId); } else { feature = featureId; } }
    return feature;
}, getFeatureBy: function (property, value) {
    var feature = null; for (var i = 0, len = this.features.length; i < len; ++i) { if (this.features[i][property] == value) { feature = this.features[i]; break; } }
    return feature;
}, getFeatureById: function (featureId) { return this.getFeatureBy('id', featureId); }, getFeatureByFid: function (featureFid) { return this.getFeatureBy('fid', featureFid); }, getFeaturesByAttribute: function (attrName, attrValue) {
    var i, feature, len = this.features.length, foundFeatures = []; for (i = 0; i < len; i++) { feature = this.features[i]; if (feature && feature.attributes) { if (feature.attributes[attrName] === attrValue) { foundFeatures.push(feature); } } }
    return foundFeatures;
}, onFeatureInsert: function (feature) { }, preFeatureInsert: function (feature) { }, getDataExtent: function () {
    var maxExtent = null; var features = this.features; if (features && (features.length > 0)) {
        var geometry = null; for (var i = 0, len = features.length; i < len; i++) {
            geometry = features[i].geometry; if (geometry) {
                if (maxExtent === null) { maxExtent = new OpenLayers.Bounds(); }
                maxExtent.extend(geometry.getBounds());
            }
        }
    }
    return maxExtent;
}, CLASS_NAME: "OpenLayers.Layer.Vector"
}); OpenLayers.Layer.Vector.RootContainer = OpenLayers.Class(OpenLayers.Layer.Vector, { displayInLayerSwitcher: false, layers: null, initialize: function (name, options) { OpenLayers.Layer.Vector.prototype.initialize.apply(this, arguments); }, display: function () { }, getFeatureFromEvent: function (evt) { var layers = this.layers; var feature; for (var i = 0; i < layers.length; i++) { feature = layers[i].getFeatureFromEvent(evt); if (feature) { return feature; } } }, setMap: function (map) { OpenLayers.Layer.Vector.prototype.setMap.apply(this, arguments); this.collectRoots(); map.events.register("changelayer", this, this.handleChangeLayer); }, removeMap: function (map) { map.events.unregister("changelayer", this, this.handleChangeLayer); this.resetRoots(); OpenLayers.Layer.Vector.prototype.removeMap.apply(this, arguments); }, collectRoots: function () { var layer; for (var i = 0; i < this.map.layers.length; ++i) { layer = this.map.layers[i]; if (OpenLayers.Util.indexOf(this.layers, layer) != -1) { layer.renderer.moveRoot(this.renderer); } } }, resetRoots: function () { var layer; for (var i = 0; i < this.layers.length; ++i) { layer = this.layers[i]; if (this.renderer && layer.renderer.getRenderLayerId() == this.id) { this.renderer.moveRoot(layer.renderer); } } }, handleChangeLayer: function (evt) { var layer = evt.layer; if (evt.property == "order" && OpenLayers.Util.indexOf(this.layers, layer) != -1) { this.resetRoots(); this.collectRoots(); } }, CLASS_NAME: "OpenLayers.Layer.Vector.RootContainer" }); OpenLayers.Control.SelectFeature = OpenLayers.Class(OpenLayers.Control, { EVENT_TYPES: ["beforefeaturehighlighted", "featurehighlighted", "featureunhighlighted"], multipleKey: null, toggleKey: null, multiple: false, clickout: true, toggle: false, hover: false, highlightOnly: false, box: false, onBeforeSelect: function () { }, onSelect: function () { }, onUnselect: function () { }, scope: null, geometryTypes: null, layer: null, layers: null, callbacks: null, selectStyle: null, renderIntent: "select", handlers: null, initialize: function (layers, options) {
    this.EVENT_TYPES = OpenLayers.Control.SelectFeature.prototype.EVENT_TYPES.concat(OpenLayers.Control.prototype.EVENT_TYPES); OpenLayers.Control.prototype.initialize.apply(this, [options]); if (this.scope === null) { this.scope = this; }
    this.initLayer(layers); var callbacks = { click: this.clickFeature, clickout: this.clickoutFeature }; if (this.hover) { callbacks.over = this.overFeature; callbacks.out = this.outFeature; }
    this.callbacks = OpenLayers.Util.extend(callbacks, this.callbacks); this.handlers = { feature: new OpenLayers.Handler.Feature(this, this.layer, this.callbacks, { geometryTypes: this.geometryTypes }) }; if (this.box) { this.handlers.box = new OpenLayers.Handler.Box(this, { done: this.selectBox }, { boxDivClassName: "olHandlerBoxSelectFeature" }); }
}, initLayer: function (layers) { if (OpenLayers.Util.isArray(layers)) { this.layers = layers; this.layer = new OpenLayers.Layer.Vector.RootContainer(this.id + "_container", { layers: layers }); } else { this.layer = layers; } }, destroy: function () {
    if (this.active && this.layers) { this.map.removeLayer(this.layer); }
    OpenLayers.Control.prototype.destroy.apply(this, arguments); if (this.layers) { this.layer.destroy(); }
}, activate: function () {
    if (!this.active) {
        if (this.layers) { this.map.addLayer(this.layer); }
        this.handlers.feature.activate(); if (this.box && this.handlers.box) { this.handlers.box.activate(); }
    }
    return OpenLayers.Control.prototype.activate.apply(this, arguments);
}, deactivate: function () {
    if (this.active) {
        this.handlers.feature.deactivate(); if (this.handlers.box) { this.handlers.box.deactivate(); }
        if (this.layers) { this.map.removeLayer(this.layer); }
    }
    return OpenLayers.Control.prototype.deactivate.apply(this, arguments);
}, unselectAll: function (options) { var layers = this.layers || [this.layer]; var layer, feature; for (var l = 0; l < layers.length; ++l) { layer = layers[l]; for (var i = layer.selectedFeatures.length - 1; i >= 0; --i) { feature = layer.selectedFeatures[i]; if (!options || options.except != feature) { this.unselect(feature); } } } }, clickFeature: function (feature) {
    if (!this.hover) {
        var selected = (OpenLayers.Util.indexOf(feature.layer.selectedFeatures, feature) > -1); if (selected) { if (this.toggleSelect()) { this.unselect(feature); } else if (!this.multipleSelect()) { this.unselectAll({ except: feature }); } } else {
            if (!this.multipleSelect()) { this.unselectAll({ except: feature }); }
            this.select(feature);
        }
    }
}, multipleSelect: function () { return this.multiple || (this.handlers.feature.evt && this.handlers.feature.evt[this.multipleKey]); }, toggleSelect: function () { return this.toggle || (this.handlers.feature.evt && this.handlers.feature.evt[this.toggleKey]); }, clickoutFeature: function (feature) { if (!this.hover && this.clickout) { this.unselectAll(); } }, overFeature: function (feature) { var layer = feature.layer; if (this.hover) { if (this.highlightOnly) { this.highlight(feature); } else if (OpenLayers.Util.indexOf(layer.selectedFeatures, feature) == -1) { this.select(feature); } } }, outFeature: function (feature) { if (this.hover) { if (this.highlightOnly) { if (feature._lastHighlighter == this.id) { if (feature._prevHighlighter && feature._prevHighlighter != this.id) { delete feature._lastHighlighter; var control = this.map.getControl(feature._prevHighlighter); if (control) { control.highlight(feature); } } else { this.unhighlight(feature); } } } else { this.unselect(feature); } } }, highlight: function (feature) { var layer = feature.layer; var cont = this.events.triggerEvent("beforefeaturehighlighted", { feature: feature }); if (cont !== false) { feature._prevHighlighter = feature._lastHighlighter; feature._lastHighlighter = this.id; var style = this.selectStyle || this.renderIntent; layer.drawFeature(feature, style); this.events.triggerEvent("featurehighlighted", { feature: feature }); } }, unhighlight: function (feature) {
    var layer = feature.layer; if (feature._prevHighlighter == undefined) { delete feature._lastHighlighter; } else if (feature._prevHighlighter == this.id) { delete feature._prevHighlighter; } else { feature._lastHighlighter = feature._prevHighlighter; delete feature._prevHighlighter; }
    layer.drawFeature(feature, feature.style || feature.layer.style || "default"); this.events.triggerEvent("featureunhighlighted", { feature: feature });
}, select: function (feature) {
    var cont = this.onBeforeSelect.call(this.scope, feature); var layer = feature.layer; if (cont !== false) {
        cont = layer.events.triggerEvent("beforefeatureselected", { feature: feature }); if (cont !== false) {
            layer.selectedFeatures.push(feature); this.highlight(feature); if (!this.handlers.feature.lastFeature) { this.handlers.feature.lastFeature = layer.selectedFeatures[0]; }
            layer.events.triggerEvent("featureselected", { feature: feature }); this.onSelect.call(this.scope, feature);
        }
    }
}, unselect: function (feature) { var layer = feature.layer; this.unhighlight(feature); OpenLayers.Util.removeItem(layer.selectedFeatures, feature); layer.events.triggerEvent("featureunselected", { feature: feature }); this.onUnselect.call(this.scope, feature); }, selectBox: function (position) {
    if (position instanceof OpenLayers.Bounds) {
        var minXY = this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.left, position.bottom)); var maxXY = this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.right, position.top)); var bounds = new OpenLayers.Bounds(minXY.lon, minXY.lat, maxXY.lon, maxXY.lat); if (!this.multipleSelect()) { this.unselectAll(); }
        var prevMultiple = this.multiple; this.multiple = true; var layers = this.layers || [this.layer]; var layer; for (var l = 0; l < layers.length; ++l) {
            layer = layers[l]; for (var i = 0, len = layer.features.length; i < len; ++i) {
                var feature = layer.features[i]; if (!feature.getVisibility()) { continue; }
                if (this.geometryTypes == null || OpenLayers.Util.indexOf(this.geometryTypes, feature.geometry.CLASS_NAME) > -1) { if (bounds.toGeometry().intersects(feature.geometry)) { if (OpenLayers.Util.indexOf(layer.selectedFeatures, feature) == -1) { this.select(feature); } } }
            }
        }
        this.multiple = prevMultiple;
    }
}, setMap: function (map) {
    this.handlers.feature.setMap(map); if (this.box) { this.handlers.box.setMap(map); }
    OpenLayers.Control.prototype.setMap.apply(this, arguments);
}, setLayer: function (layers) {
    var isActive = this.active; this.unselectAll(); this.deactivate(); if (this.layers) { this.layer.destroy(); this.layers = null; }
    this.initLayer(layers); this.handlers.feature.layer = this.layer; if (isActive) { this.activate(); }
}, CLASS_NAME: "OpenLayers.Control.SelectFeature"
}); OpenLayers.Handler.Keyboard = OpenLayers.Class(OpenLayers.Handler, { KEY_EVENTS: ["keydown", "keyup"], eventListener: null, initialize: function (control, callbacks, options) { OpenLayers.Handler.prototype.initialize.apply(this, arguments); this.eventListener = OpenLayers.Function.bindAsEventListener(this.handleKeyEvent, this); }, destroy: function () { this.deactivate(); this.eventListener = null; OpenLayers.Handler.prototype.destroy.apply(this, arguments); }, activate: function () {
    if (OpenLayers.Handler.prototype.activate.apply(this, arguments)) {
        for (var i = 0, len = this.KEY_EVENTS.length; i < len; i++) { OpenLayers.Event.observe(document, this.KEY_EVENTS[i], this.eventListener); }
        return true;
    } else { return false; }
}, deactivate: function () {
    var deactivated = false; if (OpenLayers.Handler.prototype.deactivate.apply(this, arguments)) {
        for (var i = 0, len = this.KEY_EVENTS.length; i < len; i++) { OpenLayers.Event.stopObserving(document, this.KEY_EVENTS[i], this.eventListener); }
        deactivated = true;
    }
    return deactivated;
}, handleKeyEvent: function (evt) { if (this.checkModifiers(evt)) { this.callback(evt.type, [evt]); } }, CLASS_NAME: "OpenLayers.Handler.Keyboard"
}); OpenLayers.Control.ModifyFeature = OpenLayers.Class(OpenLayers.Control, { geometryTypes: null, clickout: true, toggle: true, standalone: false, layer: null, feature: null, vertices: null, virtualVertices: null, selectControl: null, dragControl: null, handlers: null, deleteCodes: null, virtualStyle: null, vertexRenderIntent: null, mode: null, modified: false, radiusHandle: null, dragHandle: null, onModificationStart: function () { }, onModification: function () { }, onModificationEnd: function () { }, initialize: function (layer, options) {
    options = options || {}; this.layer = layer; this.vertices = []; this.virtualVertices = []; this.virtualStyle = OpenLayers.Util.extend({}, this.layer.style || this.layer.styleMap.createSymbolizer(null, options.vertexRenderIntent)); this.virtualStyle.fillOpacity = 0.3; this.virtualStyle.strokeOpacity = 0.3; this.deleteCodes = [46, 68]; this.mode = OpenLayers.Control.ModifyFeature.RESHAPE; OpenLayers.Control.prototype.initialize.apply(this, [options]); if (!(OpenLayers.Util.isArray(this.deleteCodes))) { this.deleteCodes = [this.deleteCodes]; }
    var control = this; var selectOptions = { geometryTypes: this.geometryTypes, clickout: this.clickout, toggle: this.toggle, onBeforeSelect: this.beforeSelectFeature, onSelect: this.selectFeature, onUnselect: this.unselectFeature, scope: this }; if (this.standalone === false) { this.selectControl = new OpenLayers.Control.SelectFeature(layer, selectOptions); }
    var dragOptions = { geometryTypes: ["OpenLayers.Geometry.Point"], snappingOptions: this.snappingOptions, onStart: function (feature, pixel) { control.dragStart.apply(control, [feature, pixel]); }, onDrag: function (feature, pixel) { control.dragVertex.apply(control, [feature, pixel]); }, onComplete: function (feature) { control.dragComplete.apply(control, [feature]); }, featureCallbacks: { over: function (feature) { if (control.standalone !== true || feature._sketch || control.feature === feature) { control.dragControl.overFeature.apply(control.dragControl, [feature]); } } } }; this.dragControl = new OpenLayers.Control.DragFeature(layer, dragOptions); var keyboardOptions = { keydown: this.handleKeypress }; this.handlers = { keyboard: new OpenLayers.Handler.Keyboard(this, keyboardOptions) };
}, destroy: function () { this.layer = null; this.standalone || this.selectControl.destroy(); this.dragControl.destroy(); OpenLayers.Control.prototype.destroy.apply(this, []); }, activate: function () { return ((this.standalone || this.selectControl.activate()) && this.handlers.keyboard.activate() && OpenLayers.Control.prototype.activate.apply(this, arguments)); }, deactivate: function () {
    var deactivated = false; if (OpenLayers.Control.prototype.deactivate.apply(this, arguments)) {
        this.layer.removeFeatures(this.vertices, { silent: true }); this.layer.removeFeatures(this.virtualVertices, { silent: true }); this.vertices = []; this.dragControl.deactivate(); var feature = this.feature; var valid = feature && feature.geometry && feature.layer; if (this.standalone === false) {
            if (valid) { this.selectControl.unselect.apply(this.selectControl, [feature]); }
            this.selectControl.deactivate();
        } else { if (valid) { this.unselectFeature(feature); } }
        this.handlers.keyboard.deactivate(); deactivated = true;
    }
    return deactivated;
}, beforeSelectFeature: function (feature) { return this.layer.events.triggerEvent("beforefeaturemodified", { feature: feature }); }, selectFeature: function (feature) {
    if (!this.standalone || this.beforeSelectFeature(feature) !== false) { this.feature = feature; this.modified = false; this.resetVertices(); this.dragControl.activate(); this.onModificationStart(this.feature); }
    var modified = feature.modified; if (feature.geometry && !(modified && modified.geometry)) { this._originalGeometry = feature.geometry.clone(); }
}, unselectFeature: function (feature) {
    this.layer.removeFeatures(this.vertices, { silent: true }); this.vertices = []; this.layer.destroyFeatures(this.virtualVertices, { silent: true }); this.virtualVertices = []; if (this.dragHandle) { this.layer.destroyFeatures([this.dragHandle], { silent: true }); delete this.dragHandle; }
    if (this.radiusHandle) { this.layer.destroyFeatures([this.radiusHandle], { silent: true }); delete this.radiusHandle; }
    this.feature = null; this.dragControl.deactivate(); this.onModificationEnd(feature); this.layer.events.triggerEvent("afterfeaturemodified", { feature: feature, modified: this.modified }); this.modified = false;
}, dragStart: function (feature, pixel) {
    if (feature != this.feature && !feature.geometry.parent && feature != this.dragHandle && feature != this.radiusHandle) {
        if (this.standalone === false && this.feature) { this.selectControl.clickFeature.apply(this.selectControl, [this.feature]); }
        if (this.geometryTypes == null || OpenLayers.Util.indexOf(this.geometryTypes, feature.geometry.CLASS_NAME) != -1) { this.standalone || this.selectControl.clickFeature.apply(this.selectControl, [feature]); this.dragControl.overFeature.apply(this.dragControl, [feature]); this.dragControl.lastPixel = pixel; this.dragControl.handlers.drag.started = true; this.dragControl.handlers.drag.start = pixel; this.dragControl.handlers.drag.last = pixel; }
    }
}, dragVertex: function (vertex, pixel) {
    this.modified = true; if (this.feature.geometry.CLASS_NAME == "OpenLayers.Geometry.Point") {
        if (this.feature != vertex) { this.feature = vertex; }
        this.layer.events.triggerEvent("vertexmodified", { vertex: vertex.geometry, feature: this.feature, pixel: pixel });
    } else {
        if (vertex._index) { vertex.geometry.parent.addComponent(vertex.geometry, vertex._index); delete vertex._index; OpenLayers.Util.removeItem(this.virtualVertices, vertex); this.vertices.push(vertex); } else if (vertex == this.dragHandle) { this.layer.removeFeatures(this.vertices, { silent: true }); this.vertices = []; if (this.radiusHandle) { this.layer.destroyFeatures([this.radiusHandle], { silent: true }); this.radiusHandle = null; } } else if (vertex !== this.radiusHandle) { this.layer.events.triggerEvent("vertexmodified", { vertex: vertex.geometry, feature: this.feature, pixel: pixel }); }
        if (this.virtualVertices.length > 0) { this.layer.destroyFeatures(this.virtualVertices, { silent: true }); this.virtualVertices = []; }
        this.layer.drawFeature(this.feature, this.standalone ? undefined : this.selectControl.renderIntent);
    }
    this.layer.drawFeature(vertex);
}, dragComplete: function (vertex) { this.resetVertices(); this.setFeatureState(); this.onModification(this.feature); this.layer.events.triggerEvent("featuremodified", { feature: this.feature }); }, setFeatureState: function () { if (this.feature.state != OpenLayers.State.INSERT && this.feature.state != OpenLayers.State.DELETE) { this.feature.state = OpenLayers.State.UPDATE; if (this.modified && this._originalGeometry) { var feature = this.feature; feature.modified = OpenLayers.Util.extend(feature.modified, { geometry: this._originalGeometry }); delete this._originalGeometry; } } }, resetVertices: function () {
    if (this.dragControl.feature) { this.dragControl.outFeature(this.dragControl.feature); }
    if (this.vertices.length > 0) { this.layer.removeFeatures(this.vertices, { silent: true }); this.vertices = []; }
    if (this.virtualVertices.length > 0) { this.layer.removeFeatures(this.virtualVertices, { silent: true }); this.virtualVertices = []; }
    if (this.dragHandle) { this.layer.destroyFeatures([this.dragHandle], { silent: true }); this.dragHandle = null; }
    if (this.radiusHandle) { this.layer.destroyFeatures([this.radiusHandle], { silent: true }); this.radiusHandle = null; }
    if (this.feature && this.feature.geometry.CLASS_NAME != "OpenLayers.Geometry.Point") {
        if ((this.mode & OpenLayers.Control.ModifyFeature.DRAG)) { this.collectDragHandle(); }
        if ((this.mode & (OpenLayers.Control.ModifyFeature.ROTATE | OpenLayers.Control.ModifyFeature.RESIZE))) { this.collectRadiusHandle(); }
        if (this.mode & OpenLayers.Control.ModifyFeature.RESHAPE) { if (!(this.mode & OpenLayers.Control.ModifyFeature.RESIZE)) { this.collectVertices(); } }
    }
}, handleKeypress: function (evt) { var code = evt.keyCode; if (this.feature && OpenLayers.Util.indexOf(this.deleteCodes, code) != -1) { var vertex = this.dragControl.feature; if (vertex && OpenLayers.Util.indexOf(this.vertices, vertex) != -1 && !this.dragControl.handlers.drag.dragging && vertex.geometry.parent) { vertex.geometry.parent.removeComponent(vertex.geometry); this.layer.events.triggerEvent("vertexremoved", { vertex: vertex.geometry, feature: this.feature, pixel: evt.xy }); this.layer.drawFeature(this.feature, this.standalone ? undefined : this.selectControl.renderIntent); this.modified = true; this.resetVertices(); this.setFeatureState(); this.onModification(this.feature); this.layer.events.triggerEvent("featuremodified", { feature: this.feature }); } } }, collectVertices: function () {
    this.vertices = []; this.virtualVertices = []; var control = this; function collectComponentVertices(geometry) {
        var i, vertex, component, len; if (geometry.CLASS_NAME == "OpenLayers.Geometry.Point") { vertex = new OpenLayers.Feature.Vector(geometry); vertex._sketch = true; vertex.renderIntent = control.vertexRenderIntent; control.vertices.push(vertex); } else {
            var numVert = geometry.components.length; if (geometry.CLASS_NAME == "OpenLayers.Geometry.LinearRing") { numVert -= 1; }
            for (i = 0; i < numVert; ++i) { component = geometry.components[i]; if (component.CLASS_NAME == "OpenLayers.Geometry.Point") { vertex = new OpenLayers.Feature.Vector(component); vertex._sketch = true; vertex.renderIntent = control.vertexRenderIntent; control.vertices.push(vertex); } else { collectComponentVertices(component); } }
            if (geometry.CLASS_NAME != "OpenLayers.Geometry.MultiPoint") { for (i = 0, len = geometry.components.length; i < len - 1; ++i) { var prevVertex = geometry.components[i]; var nextVertex = geometry.components[i + 1]; if (prevVertex.CLASS_NAME == "OpenLayers.Geometry.Point" && nextVertex.CLASS_NAME == "OpenLayers.Geometry.Point") { var x = (prevVertex.x + nextVertex.x) / 2; var y = (prevVertex.y + nextVertex.y) / 2; var point = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(x, y), null, control.virtualStyle); point.geometry.parent = geometry; point._index = i + 1; point._sketch = true; control.virtualVertices.push(point); } } }
        }
    }
    collectComponentVertices.call(this, this.feature.geometry); this.layer.addFeatures(this.virtualVertices, { silent: true }); this.layer.addFeatures(this.vertices, { silent: true });
}, collectDragHandle: function () { var geometry = this.feature.geometry; var center = geometry.getBounds().getCenterLonLat(); var originGeometry = new OpenLayers.Geometry.Point(center.lon, center.lat); var origin = new OpenLayers.Feature.Vector(originGeometry); originGeometry.move = function (x, y) { OpenLayers.Geometry.Point.prototype.move.call(this, x, y); geometry.move(x, y); }; origin._sketch = true; this.dragHandle = origin; this.layer.addFeatures([this.dragHandle], { silent: true }); }, collectRadiusHandle: function () {
    var geometry = this.feature.geometry; var bounds = geometry.getBounds(); var center = bounds.getCenterLonLat(); var originGeometry = new OpenLayers.Geometry.Point(center.lon, center.lat); var radiusGeometry = new OpenLayers.Geometry.Point(bounds.right, bounds.bottom); var radius = new OpenLayers.Feature.Vector(radiusGeometry); var resize = (this.mode & OpenLayers.Control.ModifyFeature.RESIZE); var reshape = (this.mode & OpenLayers.Control.ModifyFeature.RESHAPE); var rotate = (this.mode & OpenLayers.Control.ModifyFeature.ROTATE); radiusGeometry.move = function (x, y) {
        OpenLayers.Geometry.Point.prototype.move.call(this, x, y); var dx1 = this.x - originGeometry.x; var dy1 = this.y - originGeometry.y; var dx0 = dx1 - x; var dy0 = dy1 - y; if (rotate) { var a0 = Math.atan2(dy0, dx0); var a1 = Math.atan2(dy1, dx1); var angle = a1 - a0; angle *= 180 / Math.PI; geometry.rotate(angle, originGeometry); }
        if (resize) {
            var scale, ratio; if (reshape) { scale = dy1 / dy0; ratio = (dx1 / dx0) / scale; } else { var l0 = Math.sqrt((dx0 * dx0) + (dy0 * dy0)); var l1 = Math.sqrt((dx1 * dx1) + (dy1 * dy1)); scale = l1 / l0; }
            geometry.resize(scale, originGeometry, ratio);
        }
    }; radius._sketch = true; this.radiusHandle = radius; this.layer.addFeatures([this.radiusHandle], { silent: true });
}, setMap: function (map) { this.standalone || this.selectControl.setMap(map); this.dragControl.setMap(map); OpenLayers.Control.prototype.setMap.apply(this, arguments); }, CLASS_NAME: "OpenLayers.Control.ModifyFeature"
}); OpenLayers.Control.ModifyFeature.RESHAPE = 1; OpenLayers.Control.ModifyFeature.RESIZE = 2; OpenLayers.Control.ModifyFeature.ROTATE = 4; OpenLayers.Control.ModifyFeature.DRAG = 8;



OpenLayers.Layer.XYZ = OpenLayers.Class(OpenLayers.Layer.Grid, {
    isBaseLayer: true,
    sphericalMercator: false,
    zoomOffset: 0,
    serverResolutions: null,
    initialize: function (name, url, options) {
        if (options && options.sphericalMercator || this.sphericalMercator) {
            options = OpenLayers.Util.extend({ maxExtent: new OpenLayers.Bounds(-128 * 156543.03390625, -128 * 156543.03390625, 128 * 156543.03390625, 128 * 156543.03390625),
                maxResolution: 156543.03390625,
                numZoomLevels: 19,
                units: "m",
                projection: "EPSG:900913"
            }, options);
        }
        url = url || this.url;
        name = name || this.name;
        var newArguments = [name, url, {}, options];
        OpenLayers.Layer.Grid.prototype.initialize.apply(this, newArguments);
    },
    clone: function (obj) {
        if (obj == null) {
            obj = new OpenLayers.Layer.XYZ(this.name, this.url, this.getOptions());
        }
        obj = OpenLayers.Layer.Grid.prototype.clone.apply(this, [obj]);
        return obj;
    }, getURL: function (bounds) {
        var xyz = this.getXYZ(bounds);
        var url = this.url;
        if (OpenLayers.Util.isArray(url)) {
            var s = '' + xyz.x + xyz.y + xyz.z;
            url = this.selectUrl(s, url);
        }
        return OpenLayers.String.format(url, xyz);
    }, getXYZ: function (bounds) {
        var res = this.map.getResolution();
        var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
        var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
        var z = this.serverResolutions != null ? OpenLayers.Util.indexOf(this.serverResolutions, res) : this.map.getZoom() + this.zoomOffset;
        var limit = Math.pow(2, z);
        if (this.wrapDateLine) {
            x = ((x % limit) + limit) % limit;
        }
        return { 'x': x, 'y': y, 'z': z };
    },
    setMap: function (map) {
        OpenLayers.Layer.Grid.prototype.setMap.apply(this, arguments);
        if (!this.tileOrigin) {
            this.tileOrigin = new OpenLayers.LonLat(this.maxExtent.left, this.maxExtent.bottom);
        }
    },
    CLASS_NAME: "OpenLayers.Layer.XYZ"
});



OpenLayers.Layer.OSM = OpenLayers.Class(OpenLayers.Layer.XYZ, {
    name: "OpenStreetMap",
    attribution: "Data CC-By-SA by <a href='http://openstreetmap.org/'>OpenStreetMap</a>",
    sphericalMercator: true,
    url: 'http://tile.openstreetmap.org/${z}/${x}/${y}.png',
    clone: function (obj) {
        if (obj == null) {
            obj = new OpenLayers.Layer.OSM(this.name, this.url, this.getOptions());
        }
        obj = OpenLayers.Layer.XYZ.prototype.clone.apply(this, [obj]);
        return obj;
    },
    wrapDateLine: true,
    CLASS_NAME: "OpenLayers.Layer.OSM"
});











OpenLayers.Layer.Bing = OpenLayers.Class(OpenLayers.Layer.XYZ, {
    serverResolutions: [156543.03390625, 78271.516953125, 39135.7584765625, 19567.87923828125, 9783.939619140625, 4891.9698095703125, 2445.9849047851562, 1222.9924523925781, 611.4962261962891, 305.74811309814453, 152.87405654907226, 76.43702827453613, 38.218514137268066, 19.109257068634033, 9.554628534317017, 4.777314267158508, 2.388657133579254, 1.194328566789627, 0.5971642833948135, 0.29858214169740677, 0.14929107084870338, 0.07464553542435169],
    attributionTemplate: '<span class="olBingAttribution ${type}">' + '<div><a target="_blank" href="http://www.bing.com/maps/">' + '<img src="${logo}" /></a></div>${copyrights}' + '<a style="white-space: nowrap" target="_blank" ' + 'href="http://www.microsoft.com/maps/product/terms.html">' + 'Terms of Use</a></span>',
    metadata: null,
    type: "Road",
    metadataParams: null,
    initialize: function (options) {
        options = OpenLayers.Util.applyDefaults({ sphericalMercator: true }, options);
        var name = options.name || "Bing " + (options.type || this.type);
        var newArgs = [name, null, options];
        OpenLayers.Layer.XYZ.prototype.initialize.apply(this, newArgs);
        this.loadMetadata();
    },
    loadMetadata: function () {
        this._callbackId = "_callback_" + this.id.replace(/\./g, "_");
        window[this._callbackId] = OpenLayers.Function.bind(OpenLayers.Layer.Bing.processMetadata, this);
        var params = OpenLayers.Util.applyDefaults({ key: this.key, jsonp: this._callbackId, include: "ImageryProviders" }, this.metadataParams);
        var url = "http://dev.virtualearth.net/REST/v1/Imagery/Metadata/" + this.type + "?" + OpenLayers.Util.getParameterString(params);
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = url;
        script.id = this._callbackId;
        document.getElementsByTagName("head")[0].appendChild(script);
    },
    initLayer: function () {
        var res = this.metadata.resourceSets[0].resources[0];
        var url = res.imageUrl.replace("{quadkey}", "${quadkey}");
        this.url = [];
        for (var i = 0; i < res.imageUrlSubdomains.length; ++i) {
            this.url.push(url.replace("{subdomain}", res.imageUrlSubdomains[i]));
        };
        this.addOptions({ maxResolution: Math.min(this.serverResolutions[res.zoomMin], this.maxResolution),
            zoomOffset: res.zoomMin,
            numZoomLevels: Math.min(res.zoomMax + 1 - res.zoomMin, this.numZoomLevels)
        },
           true);
    },
    getURL: function (bounds) {
        if (!this.url) {
            return OpenLayers.Util.getImagesLocation() + "blank.gif";
        }
        var xyz = this.getXYZ(bounds),
         x = xyz.x,
         y = xyz.y,
         z = xyz.z;
        var quadDigits = [];
        for (var i = z; i > 0; --i) {
            var digit = '0';
            var mask = 1 << (i - 1);
            if ((x & mask) != 0) {
                digit++;
            }
            if ((y & mask) != 0) {
                digit++;
                digit++;
            }
            quadDigits.push(digit);
        }
        var quadKey = quadDigits.join("");
        var url = this.selectUrl('' + x + y + z, this.url);
        return OpenLayers.String.format(url, { 'quadkey': quadKey });
    },
    updateAttribution: function () {
        var metadata = this.metadata;
        if (!metadata || !this.map || !this.map.center) {
            return;
        }
        var res = metadata.resourceSets[0].resources[0];
        var extent = this.map.getExtent().transform(this.map.getProjectionObject(), new OpenLayers.Projection("EPSG:4326"));
        var providers = res.imageryProviders,
        zoom = this.map.getZoom() + 1,
        copyrights = "",
        provider, i, ii, j, jj, bbox, coverage;
        for (i = 0, ii = providers.length; i < ii; ++i) {
            provider = providers[i];
            for (j = 0, jj = provider.coverageAreas.length; j < jj; ++j) {
                coverage = provider.coverageAreas[j];
                bbox = OpenLayers.Bounds.fromArray(coverage.bbox);
                if (extent.intersectsBounds(bbox) && zoom <= coverage.zoomMax && zoom >= coverage.zoomMin) {
                    copyrights += provider.attribution + " ";
                }
            }
        }
        this.attribution = OpenLayers.String.format(this.attributionTemplate, { type: this.type.toLowerCase(), logo: metadata.brandLogoUri, copyrights: copyrights });
        this.map && this.map.events.triggerEvent("changelayer", { layer: this, property: "attribution" });
    },
    setMap: function () {
        OpenLayers.Layer.XYZ.prototype.setMap.apply(this, arguments);
        this.updateAttribution();
        this.map.events.register("moveend", this, this.updateAttribution);
    },
    clone: function (obj) {
        if (obj == null) {
            obj = new OpenLayers.Layer.Bing(this.options);
        }
        obj = OpenLayers.Layer.XYZ.prototype.clone.apply(this, [obj]); return obj;
    },
    destroy: function () {
        this.map && this.map.events.unregister("moveend", this, this.updateAttribution);
        OpenLayers.Layer.XYZ.prototype.destroy.apply(this, arguments);
    },
    CLASS_NAME: "OpenLayers.Layer.Bing"
});
OpenLayers.Layer.Bing.processMetadata = function (metadata) {
    this.metadata = metadata;
    this.initLayer();
    var script = document.getElementById(this._callbackId);
    script.parentNode.removeChild(script);
    window[this._callbackId] = undefined;
    delete this._callbackId;
};





/*TrackRoad*/
OpenLayers.Layer.TR = OpenLayers.Class(OpenLayers.Layer.XYZ, {
    serverResolutions: [156543.03390625, 78271.516953125, 39135.7584765625, 19567.87923828125, 9783.939619140625, 4891.9698095703125, 2445.9849047851562, 1222.9924523925781, 611.4962261962891, 305.74811309814453, 152.87405654907226, 76.43702827453613, 38.218514137268066, 19.109257068634033, 9.554628534317017, 4.777314267158508, 2.388657133579254, 1.194328566789627, 0.5971642833948135, 0.29858214169740677, 0.14929107084870338, 0.07464553542435169],
    attribution: "Data CC-By-SA by <a href='http://openstreetmap.org/'>OpenStreetMap</a>",
    url: 'http://tile.trackroad.com/tiles/v2/${quadkey}.png',
    name: "TrackRoad",
    type: "",
    initialize: function (options) {
        options = OpenLayers.Util.applyDefaults({ sphericalMercator: true }, options);
        var name = options.name || "TrackRoad " + (options.type || this.type);
        var newArgs = [name, null, options];
        OpenLayers.Layer.XYZ.prototype.initialize.apply(this, newArgs);
        this.initLayer();
    },
    initLayer: function () {
        var res = { zoomMin: 1, zoomMax: 16 };
        this.addOptions({
            maxResolution: Math.min(this.serverResolutions[res.zoomMin], this.maxResolution),
            zoomOffset: res.zoomMin,
            numZoomLevels: Math.min(res.zoomMax + 1 - res.zoomMin, this.numZoomLevels)
        }, true);
    },
    getURL: function (bounds) {
        if (!this.url) {
            return OpenLayers.Util.getImagesLocation() + "blank.gif";
        }
        var xyz = this.getXYZ(bounds),
             x = xyz.x,
             y = xyz.y,
             z = xyz.z;
        var quadDigits = [];
        for (var i = z; i > 0; --i) {
            var digit = '0';
            var mask = 1 << (i - 1);
            if ((x & mask) != 0) {
                digit++;
            }
            if ((y & mask) != 0) {
                digit++;
                digit++;
            }
            quadDigits.push(digit);
        }
        var quadKey = quadDigits.join("");

        return OpenLayers.String.format(this.url, { 'quadkey': quadKey });
    },
    clone: function (obj) {
        if (obj == null) {
            obj = new OpenLayers.Layer.TR(this.options);
        }
        obj = OpenLayers.Layer.XYZ.prototype.clone.apply(this, [obj]);
        return obj;
    },
    destroy: function () {

        OpenLayers.Layer.XYZ.prototype.destroy.apply(this, arguments);
    },
    CLASS_NAME: "OpenLayers.Layer.TR"
});
/*End TrackRoad*/
















OpenLayers.Layer.PointGrid = OpenLayers.Class(OpenLayers.Layer.Vector, { dx: null, dy: null, ratio: 1.5, maxFeatures: 250, rotation: 0, origin: null, gridBounds: null, initialize: function (config) { config = config || {}; OpenLayers.Layer.Vector.prototype.initialize.apply(this, [config.name, config]); }, setMap: function (map) { OpenLayers.Layer.Vector.prototype.setMap.apply(this, arguments); map.events.register("moveend", this, this.onMoveEnd); }, removeMap: function (map) { map.events.unregister("moveend", this, this.onMoveEnd); OpenLayers.Layer.Vector.prototype.removeMap.apply(this, arguments); }, setRatio: function (ratio) { this.ratio = ratio; this.updateGrid(true); }, setMaxFeatures: function (maxFeatures) { this.maxFeatures = maxFeatures; this.updateGrid(true); }, setSpacing: function (dx, dy) { this.dx = dx; this.dy = dy || dx; this.updateGrid(true); }, setOrigin: function (origin) { this.origin = origin; this.updateGrid(true); }, getOrigin: function () {
    if (!this.origin) { this.origin = this.map.getExtent().getCenterLonLat(); }
    return this.origin;
}, setRotation: function (rotation) { this.rotation = rotation; this.updateGrid(true); }, onMoveEnd: function () { this.updateGrid(); }, getViewBounds: function () {
    var bounds = this.map.getExtent(); if (this.rotation) { var origin = this.getOrigin(); var rotationOrigin = new OpenLayers.Geometry.Point(origin.lon, origin.lat); var rect = bounds.toGeometry(); rect.rotate(-this.rotation, rotationOrigin); bounds = rect.getBounds(); }
    return bounds;
}, updateGrid: function (force) {
    if (force || this.invalidBounds()) {
        var viewBounds = this.getViewBounds(); var origin = this.getOrigin(); var rotationOrigin = new OpenLayers.Geometry.Point(origin.lon, origin.lat); var viewBoundsWidth = viewBounds.getWidth(); var viewBoundsHeight = viewBounds.getHeight(); var aspectRatio = viewBoundsWidth / viewBoundsHeight; var maxHeight = Math.sqrt(this.dx * this.dy * this.maxFeatures / aspectRatio); var maxWidth = maxHeight * aspectRatio; var gridWidth = Math.min(viewBoundsWidth * this.ratio, maxWidth); var gridHeight = Math.min(viewBoundsHeight * this.ratio, maxHeight); var center = viewBounds.getCenterLonLat(); this.gridBounds = new OpenLayers.Bounds(center.lon - (gridWidth / 2), c
