// KortInfo API version 1.0
var KortInfoApi_BaseUrl = "https://nirasmap.niras.dk/";
// --- [easyXDM/json2.js] ---------------------------------
/*
http://www.JSON.org/json2.js
2010-03-20
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, strict: false */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (!this.JSON) {
this.JSON = {};
}
(function () {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ?
'"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' :
'"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0 ? '[]' :
gap ? '[\n' + gap +
partial.join(',\n' + gap) + '\n' +
mind + ']' :
'[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
k = rep[i];
if (typeof k === 'string') {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0 ? '{}' :
gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
mind + '}' : '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
// --- [easyXDM/easyXDM.js] ---------------------------------
/**
* easyXDM
* http://easyxdm.net/
* Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
(function (window, document, location, setTimeout, decodeURIComponent, encodeURIComponent) {
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global JSON, XMLHttpRequest, window, escape, unescape, ActiveXObject */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
var global = this;
var channelId = Math.floor(Math.random() * 10000); // randomize the initial id in case of multiple closures loaded
var emptyFn = Function.prototype;
var reURI = /^((http.?:)\/\/([^:\/\s]+)(:\d+)*)/; // returns groups for protocol (2), domain (3) and port (4)
var reParent = /[\-\w]+\/\.\.\//; // matches a foo/../ expression
var reDoubleSlash = /([^:])\/\//g; // matches // anywhere but in the protocol
var namespace = ""; // stores namespace under which easyXDM object is stored on the page (empty if object is global)
var easyXDM = {};
var _easyXDM = window.easyXDM; // map over global easyXDM in case of overwrite
var IFRAME_PREFIX = "easyXDM_";
var HAS_NAME_PROPERTY_BUG;
var useHash = false; // whether to use the hash over the query
var flashVersion; // will be set if using flash
var HAS_FLASH_THROTTLED_BUG;
// http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
function isHostMethod(object, property){
var t = typeof object[property];
return t == 'function' ||
(!!(t == 'object' && object[property])) ||
t == 'unknown';
}
function isHostObject(object, property){
return !!(typeof(object[property]) == 'object' && object[property]);
}
// end
// http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
function isArray(o){
return Object.prototype.toString.call(o) === '[object Array]';
}
// end
function hasFlash(){
try {
var activeX = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
flashVersion = Array.prototype.slice.call(activeX.GetVariable("$version").match(/(\d+),(\d+),(\d+),(\d+)/), 1);
HAS_FLASH_THROTTLED_BUG = parseInt(flashVersion[0], 10) > 9 && parseInt(flashVersion[1], 10) > 0;
activeX = null;
return true;
}
catch (notSupportedException) {
return false;
}
}
/*
* Cross Browser implementation for adding and removing event listeners.
*/
var on, un;
if (isHostMethod(window, "addEventListener")) {
on = function(target, type, listener){
target.addEventListener(type, listener, false);
};
un = function(target, type, listener){
target.removeEventListener(type, listener, false);
};
}
else if (isHostMethod(window, "attachEvent")) {
on = function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
un = function(object, sEvent, fpNotify){
object.detachEvent("on" + sEvent, fpNotify);
};
}
else {
throw new Error("Browser not supported");
}
/*
* Cross Browser implementation of DOMContentLoaded.
*/
var domIsReady = false, domReadyQueue = [], readyState;
if ("readyState" in document) {
// If browser is WebKit-powered, check for both 'loaded' (legacy browsers) and
// 'interactive' (HTML5 specs, recent WebKit builds) states.
// https://bugs.webkit.org/show_bug.cgi?id=45119
readyState = document.readyState;
domIsReady = readyState == "complete" || (~ navigator.userAgent.indexOf('AppleWebKit/') && (readyState == "loaded" || readyState == "interactive"));
}
else {
// If readyState is not supported in the browser, then in order to be able to fire whenReady functions apropriately
// when added dynamically _after_ DOM load, we have to deduce wether the DOM is ready or not.
// We only need a body to add elements to, so the existence of document.body is enough for us.
domIsReady = !!document.body;
}
function dom_onReady(){
if (domIsReady) {
return;
}
domIsReady = true;
for (var i = 0; i < domReadyQueue.length; i++) {
domReadyQueue[i]();
}
domReadyQueue.length = 0;
}
if (!domIsReady) {
if (isHostMethod(window, "addEventListener")) {
on(document, "DOMContentLoaded", dom_onReady);
}
else {
on(document, "readystatechange", function(){
if (document.readyState == "complete") {
dom_onReady();
}
});
if (document.documentElement.doScroll && window === top) {
var doScrollCheck = function(){
if (domIsReady) {
return;
}
// http://javascript.nwbox.com/IEContentLoaded/
try {
document.documentElement.doScroll("left");
}
catch (e) {
setTimeout(doScrollCheck, 1);
return;
}
dom_onReady();
};
doScrollCheck();
}
}
// A fallback to window.onload, that will always work
on(window, "load", dom_onReady);
}
/**
* This will add a function to the queue of functions to be run once the DOM reaches a ready state.
* If functions are added after this event then they will be executed immediately.
* @param {function} fn The function to add
* @param {Object} scope An optional scope for the function to be called with.
*/
function whenReady(fn, scope){
if (domIsReady) {
fn.call(scope);
return;
}
domReadyQueue.push(function(){
fn.call(scope);
});
}
/**
* Returns an instance of easyXDM from the parent window with
* respect to the namespace.
*
* @return An instance of easyXDM (in the parent window)
*/
function getParentObject(){
var obj = parent;
if (namespace !== "") {
for (var i = 0, ii = namespace.split("."); i < ii.length; i++) {
obj = obj[ii[i]];
}
}
return obj.easyXDM;
}
/**
* Removes easyXDM variable from the global scope. It also returns control
* of the easyXDM variable to whatever code used it before.
*
* @param {String} ns A string representation of an object that will hold
* an instance of easyXDM.
* @return An instance of easyXDM
*/
function noConflict(ns){
window.easyXDM = _easyXDM;
namespace = ns;
if (namespace) {
IFRAME_PREFIX = "easyXDM_" + namespace.replace(".", "_") + "_";
}
return easyXDM;
}
/*
* Methods for working with URLs
*/
/**
* Get the domain name from a url.
* @param {String} url The url to extract the domain from.
* @return The domain part of the url.
* @type {String}
*/
function getDomainName(url){
return url.match(reURI)[3];
}
/**
* Get the port for a given URL, or "" if none
* @param {String} url The url to extract the port from.
* @return The port part of the url.
* @type {String}
*/
function getPort(url){
return url.match(reURI)[4] || "";
}
/**
* Returns a string containing the schema, domain and if present the port
* @param {String} url The url to extract the location from
* @return {String} The location part of the url
*/
function getLocation(url){
var m = url.toLowerCase().match(reURI);
var proto = m[2], domain = m[3], port = m[4] || "";
if ((proto == "http:" && port == ":80") || (proto == "https:" && port == ":443")) {
port = "";
}
return proto + "//" + domain + port;
}
/**
* Resolves a relative url into an absolute one.
* @param {String} url The path to resolve.
* @return {String} The resolved url.
*/
function resolveUrl(url){
// replace all // except the one in proto with /
url = url.replace(reDoubleSlash, "$1/");
// If the url is a valid url we do nothing
if (!url.match(/^(http||https):\/\//)) {
// If this is a relative path
var path = (url.substring(0, 1) === "/") ? "" : location.pathname;
if (path.substring(path.length - 1) !== "/") {
path = path.substring(0, path.lastIndexOf("/") + 1);
}
url = location.protocol + "//" + location.host + path + url;
}
// reduce all 'xyz/../' to just ''
while (reParent.test(url)) {
url = url.replace(reParent, "");
}
return url;
}
/**
* Appends the parameters to the given url.
* The base url can contain existing query parameters.
* @param {String} url The base url.
* @param {Object} parameters The parameters to add.
* @return {String} A new valid url with the parameters appended.
*/
function appendQueryParameters(url, parameters){
var hash = "", indexOf = url.indexOf("#");
if (indexOf !== -1) {
hash = url.substring(indexOf);
url = url.substring(0, indexOf);
}
var q = [];
for (var key in parameters) {
if (parameters.hasOwnProperty(key)) {
q.push(key + "=" + encodeURIComponent(parameters[key]));
}
}
return url + (useHash ? "#" : (url.indexOf("?") == -1 ? "?" : "&")) + q.join("&") + hash;
}
// build the query object either from location.query, if it contains the xdm_e argument, or from location.hash
var query = (function(input){
input = input.substring(1).split("&");
var data = {}, pair, i = input.length;
while (i--) {
pair = input[i].split("=");
data[pair[0]] = decodeURIComponent(pair[1]);
}
return data;
}(/xdm_e=/.test(location.search) ? location.search : location.hash));
/*
* Helper methods
*/
/**
* Helper for checking if a variable/property is undefined
* @param {Object} v The variable to test
* @return {Boolean} True if the passed variable is undefined
*/
function undef(v){
return typeof v === "undefined";
}
/**
* A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works.
* @return {JSON} A valid JSON conforming object, or null if not found.
*/
var getJSON = function(){
var cached = {};
var obj = {
a: [1, 2, 3]
}, json = "{\"a\":[1,2,3]}";
if (typeof JSON != "undefined" && typeof JSON.stringify === "function" && JSON.stringify(obj).replace((/\s/g), "") === json) {
// this is a working JSON instance
return JSON;
}
if (Object.toJSON) {
if (Object.toJSON(obj).replace((/\s/g), "") === json) {
// this is a working stringify method
cached.stringify = Object.toJSON;
}
}
if (typeof String.prototype.evalJSON === "function") {
obj = json.evalJSON();
if (obj.a && obj.a.length === 3 && obj.a[2] === 3) {
// this is a working parse method
cached.parse = function(str){
return str.evalJSON();
};
}
}
if (cached.stringify && cached.parse) {
// Only memoize the result if we have valid instance
getJSON = function(){
return cached;
};
return cached;
}
return null;
};
/**
* Applies properties from the source object to the target object.
* @param {Object} target The target of the properties.
* @param {Object} source The source of the properties.
* @param {Boolean} noOverwrite Set to True to only set non-existing properties.
*/
function apply(destination, source, noOverwrite){
var member;
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
if (prop in destination) {
member = source[prop];
if (typeof member === "object") {
apply(destination[prop], member, noOverwrite);
}
else if (!noOverwrite) {
destination[prop] = source[prop];
}
}
else {
destination[prop] = source[prop];
}
}
}
return destination;
}
// This tests for the bug in IE where setting the [name] property using javascript causes the value to be redirected into [submitName].
function testForNamePropertyBug(){
var form = document.body.appendChild(document.createElement("form")), input = form.appendChild(document.createElement("input"));
input.name = IFRAME_PREFIX + "TEST" + channelId; // append channelId in order to avoid caching issues
HAS_NAME_PROPERTY_BUG = input !== form.elements[input.name];
document.body.removeChild(form);
}
/**
* Creates a frame and appends it to the DOM.
* @param config {object} This object can have the following properties
*
*
{object} prop The properties that should be set on the frame. This should include the 'src' property.
*
{object} attr The attributes that should be set on the frame.
*
{DOMElement} container Its parent element (Optional).
*
{function} onLoad A method that should be called with the frames contentWindow as argument when the frame is fully loaded. (Optional)
*
* @return The frames DOMElement
* @type DOMElement
*/
function createFrame(config){
if (undef(HAS_NAME_PROPERTY_BUG)) {
testForNamePropertyBug();
}
var frame;
// This is to work around the problems in IE6/7 with setting the name property.
// Internally this is set as 'submitName' instead when using 'iframe.name = ...'
// This is not required by easyXDM itself, but is to facilitate other use cases
if (HAS_NAME_PROPERTY_BUG) {
frame = document.createElement("");
}
else {
frame = document.createElement("IFRAME");
frame.name = config.props.name;
}
frame.id = frame.name = config.props.name;
delete config.props.name;
if (config.onLoad) {
on(frame, "load", config.onLoad);
}
if (typeof config.container == "string") {
config.container = document.getElementById(config.container);
}
if (!config.container) {
// This needs to be hidden like this, simply setting display:none and the like will cause failures in some browsers.
apply(frame.style, {
position: "absolute",
top: "-2000px"
});
config.container = document.body;
}
// HACK for some reason, IE needs the source set
// after the frame has been appended into the DOM
// so remove the src, and set it afterwards
var src = config.props.src;
delete config.props.src;
// transfer properties to the frame
apply(frame, config.props);
frame.border = frame.frameBorder = 0;
frame.allowTransparency = true;
config.container.appendChild(frame);
// HACK see above
frame.src = src;
config.props.src = src;
return frame;
}
/**
* Check whether a domain is allowed using an Access Control List.
* The ACL can contain * and ? as wildcards, or can be regular expressions.
* If regular expressions they need to begin with ^ and end with $.
* @param {Array/String} acl The list of allowed domains
* @param {String} domain The domain to test.
* @return {Boolean} True if the domain is allowed, false if not.
*/
function checkAcl(acl, domain){
// normalize into an array
if (typeof acl == "string") {
acl = [acl];
}
var re, i = acl.length;
while (i--) {
re = acl[i];
re = new RegExp(re.substr(0, 1) == "^" ? re : ("^" + re.replace(/(\*)/g, ".$1").replace(/\?/g, ".") + "$"));
if (re.test(domain)) {
return true;
}
}
return false;
}
/*
* Functions related to stacks
*/
/**
* Prepares an array of stack-elements suitable for the current configuration
* @param {Object} config The Transports configuration. See easyXDM.Socket for more.
* @return {Array} An array of stack-elements with the TransportElement at index 0.
*/
function prepareTransportStack(config){
var protocol = config.protocol, stackEls;
config.isHost = config.isHost || undef(query.xdm_p);
useHash = config.hash || false;
if (!config.props) {
config.props = {};
}
if (!config.isHost) {
config.channel = query.xdm_c;
config.secret = query.xdm_s;
config.remote = query.xdm_e;
protocol = query.xdm_p;
if (config.acl && !checkAcl(config.acl, config.remote)) {
throw new Error("Access denied for " + config.remote);
}
}
else {
config.remote = resolveUrl(config.remote);
config.channel = config.channel || "default" + channelId++;
config.secret = Math.random().toString(16).substring(2);
if (undef(protocol)) {
if (getLocation(window.location.href) == getLocation(config.remote)) {
/*
* Both documents has the same origin, lets use direct access.
*/
protocol = "4";
}
else if (isHostMethod(window, "postMessage") || isHostMethod(document, "postMessage")) {
/*
* This is supported in IE8+, Firefox 3+, Opera 9+, Chrome 2+ and Safari 4+
*/
protocol = "1";
}
else if (config.swf && isHostMethod(window, "ActiveXObject") && hasFlash()) {
/*
* The Flash transport superseedes the NixTransport as the NixTransport has been blocked by MS
*/
protocol = "6";
}
else if (navigator.product === "Gecko" && "frameElement" in window && navigator.userAgent.indexOf('WebKit') == -1) {
/*
* This is supported in Gecko (Firefox 1+)
*/
protocol = "5";
}
else if (config.remoteHelper) {
/*
* This is supported in all browsers that retains the value of window.name when
* navigating from one domain to another, and where parent.frames[foo] can be used
* to get access to a frame from the same domain
*/
config.remoteHelper = resolveUrl(config.remoteHelper);
protocol = "2";
}
else {
/*
* This is supported in all browsers where [window].location is writable for all
* The resize event will be used if resize is supported and the iframe is not put
* into a container, else polling will be used.
*/
protocol = "0";
}
}
}
config.protocol = protocol; // for conditional branching
switch (protocol) {
case "0":// 0 = HashTransport
apply(config, {
interval: 100,
delay: 2000,
useResize: true,
useParent: false,
usePolling: false
}, true);
if (config.isHost) {
if (!config.local) {
// If no local is set then we need to find an image hosted on the current domain
var domain = location.protocol + "//" + location.host, images = document.body.getElementsByTagName("img"), image;
var i = images.length;
while (i--) {
image = images[i];
if (image.src.substring(0, domain.length) === domain) {
config.local = image.src;
break;
}
}
if (!config.local) {
// If no local was set, and we are unable to find a suitable file, then we resort to using the current window
config.local = window;
}
}
var parameters = {
xdm_c: config.channel,
xdm_p: 0
};
if (config.local === window) {
// We are using the current window to listen to
config.usePolling = true;
config.useParent = true;
config.local = location.protocol + "//" + location.host + location.pathname + location.search;
parameters.xdm_e = config.local;
parameters.xdm_pa = 1; // use parent
}
else {
parameters.xdm_e = resolveUrl(config.local);
}
if (config.container) {
config.useResize = false;
parameters.xdm_po = 1; // use polling
}
config.remote = appendQueryParameters(config.remote, parameters);
}
else {
apply(config, {
channel: query.xdm_c,
remote: query.xdm_e,
useParent: !undef(query.xdm_pa),
usePolling: !undef(query.xdm_po),
useResize: config.useParent ? false : config.useResize
});
}
stackEls = [new easyXDM.stack.HashTransport(config), new easyXDM.stack.ReliableBehavior({}), new easyXDM.stack.QueueBehavior({
encode: true,
maxLength: 4000 - config.remote.length
}), new easyXDM.stack.VerifyBehavior({
initiate: config.isHost
})];
break;
case "1":
stackEls = [new easyXDM.stack.PostMessageTransport(config)];
break;
case "2":
stackEls = [new easyXDM.stack.NameTransport(config), new easyXDM.stack.QueueBehavior(), new easyXDM.stack.VerifyBehavior({
initiate: config.isHost
})];
break;
case "3":
stackEls = [new easyXDM.stack.NixTransport(config)];
break;
case "4":
stackEls = [new easyXDM.stack.SameOriginTransport(config)];
break;
case "5":
stackEls = [new easyXDM.stack.FrameElementTransport(config)];
break;
case "6":
if (!flashVersion) {
hasFlash();
}
stackEls = [new easyXDM.stack.FlashTransport(config)];
break;
}
// this behavior is responsible for buffering outgoing messages, and for performing lazy initialization
stackEls.push(new easyXDM.stack.QueueBehavior({
lazy: config.lazy,
remove: true
}));
return stackEls;
}
/**
* Chains all the separate stack elements into a single usable stack.
* If an element is missing a necessary method then it will have a pass-through method applied.
* @param {Array} stackElements An array of stack elements to be linked.
* @return {easyXDM.stack.StackElement} The last element in the chain.
*/
function chainStack(stackElements){
var stackEl, defaults = {
incoming: function(message, origin){
this.up.incoming(message, origin);
},
outgoing: function(message, recipient){
this.down.outgoing(message, recipient);
},
callback: function(success){
this.up.callback(success);
},
init: function(){
this.down.init();
},
destroy: function(){
this.down.destroy();
}
};
for (var i = 0, len = stackElements.length; i < len; i++) {
stackEl = stackElements[i];
apply(stackEl, defaults, true);
if (i !== 0) {
stackEl.down = stackElements[i - 1];
}
if (i !== len - 1) {
stackEl.up = stackElements[i + 1];
}
}
return stackEl;
}
/**
* This will remove a stackelement from its stack while leaving the stack functional.
* @param {Object} element The elment to remove from the stack.
*/
function removeFromStack(element){
element.up.down = element.down;
element.down.up = element.up;
element.up = element.down = null;
}
/*
* Export the main object and any other methods applicable
*/
/**
* @class easyXDM
* A javascript library providing cross-browser, cross-domain messaging/RPC.
* @version 2.4.15.118
* @singleton
*/
apply(easyXDM, {
/**
* The version of the library
* @type {string}
*/
version: "2.4.15.118",
/**
* This is a map containing all the query parameters passed to the document.
* All the values has been decoded using decodeURIComponent.
* @type {object}
*/
query: query,
/**
* @private
*/
stack: {},
/**
* Applies properties from the source object to the target object.
* @param {object} target The target of the properties.
* @param {object} source The source of the properties.
* @param {boolean} noOverwrite Set to True to only set non-existing properties.
*/
apply: apply,
/**
* A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works.
* @return {JSON} A valid JSON conforming object, or null if not found.
*/
getJSONObject: getJSON,
/**
* This will add a function to the queue of functions to be run once the DOM reaches a ready state.
* If functions are added after this event then they will be executed immediately.
* @param {function} fn The function to add
* @param {object} scope An optional scope for the function to be called with.
*/
whenReady: whenReady,
/**
* Removes easyXDM variable from the global scope. It also returns control
* of the easyXDM variable to whatever code used it before.
*
* @param {String} ns A string representation of an object that will hold
* an instance of easyXDM.
* @return An instance of easyXDM
*/
noConflict: noConflict
});
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global console, _FirebugCommandLine, easyXDM, window, escape, unescape, isHostObject, undef, _trace, domIsReady, emptyFn, namespace */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, isHostObject, isHostMethod, un, on, createFrame, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.DomHelper
* Contains methods for dealing with the DOM
* @singleton
*/
easyXDM.DomHelper = {
/**
* Provides a consistent interface for adding eventhandlers
* @param {Object} target The target to add the event to
* @param {String} type The name of the event
* @param {Function} listener The listener
*/
on: on,
/**
* Provides a consistent interface for removing eventhandlers
* @param {Object} target The target to remove the event from
* @param {String} type The name of the event
* @param {Function} listener The listener
*/
un: un,
/**
* Checks for the presence of the JSON object.
* If it is not present it will use the supplied path to load the JSON2 library.
* This should be called in the documents head right after the easyXDM script tag.
* http://json.org/json2.js
* @param {String} path A valid path to json2.js
*/
requiresJSON: function(path){
if (!isHostObject(window, "JSON")) {
// we need to encode the < in order to avoid an illegal token error
// when the script is inlined in a document.
document.write('<' + 'script type="text/javascript" src="' + path + '"><' + '/script>');
}
}
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
(function(){
// The map containing the stored functions
var _map = {};
/**
* @class easyXDM.Fn
* This contains methods related to function handling, such as storing callbacks.
* @singleton
* @namespace easyXDM
*/
easyXDM.Fn = {
/**
* Stores a function using the given name for reference
* @param {String} name The name that the function should be referred by
* @param {Function} fn The function to store
* @namespace easyXDM.fn
*/
set: function(name, fn){
_map[name] = fn;
},
/**
* Retrieves the function referred to by the given name
* @param {String} name The name of the function to retrieve
* @param {Boolean} del If the function should be deleted after retrieval
* @return {Function} The stored function
* @namespace easyXDM.fn
*/
get: function(name, del){
var fn = _map[name];
if (del) {
delete _map[name];
}
return fn;
}
};
}());
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, chainStack, prepareTransportStack, getLocation, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.Socket
* This class creates a transport channel between two domains that is usable for sending and receiving string-based messages.
* The channel is reliable, supports queueing, and ensures that the message originates from the expected domain.
* Internally different stacks will be used depending on the browsers features and the available parameters.
*
How to set up
* Setting up the provider:
*
* var socket = new easyXDM.Socket({
* local: "name.html",
* onReady: function(){
* // you need to wait for the onReady callback before using the socket
* socket.postMessage("foo-message");
* },
* onMessage: function(message, origin) {
* alert("received " + message + " from " + origin);
* }
* });
*
* Setting up the consumer:
*
* var socket = new easyXDM.Socket({
* remote: "http://remotedomain/page.html",
* remoteHelper: "http://remotedomain/name.html",
* onReady: function(){
* // you need to wait for the onReady callback before using the socket
* socket.postMessage("foo-message");
* },
* onMessage: function(message, origin) {
* alert("received " + message + " from " + origin);
* }
* });
*
* If you are unable to upload the name.html file to the consumers domain then remove the remoteHelper property
* and easyXDM will fall back to using the HashTransport instead of the NameTransport when not able to use any of the primary transports.
* @namespace easyXDM
* @constructor
* @cfg {String/Window} local The url to the local name.html document, a local static file, or a reference to the local window.
* @cfg {Boolean} lazy (Consumer only) Set this to true if you want easyXDM to defer creating the transport until really needed.
* @cfg {String} remote (Consumer only) The url to the providers document.
* @cfg {String} remoteHelper (Consumer only) The url to the remote name.html file. This is to support NameTransport as a fallback. Optional.
* @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window. Optional, defaults to 2000.
* @cfg {Number} interval The interval used when polling for messages. Optional, defaults to 300.
* @cfg {String} channel (Consumer only) The name of the channel to use. Can be used to set consistent iframe names. Must be unique. Optional.
* @cfg {Function} onMessage The method that should handle incoming messages. This method should accept two arguments, the message as a string, and the origin as a string. Optional.
* @cfg {Function} onReady A method that should be called when the transport is ready. Optional.
* @cfg {DOMElement|String} container (Consumer only) The element, or the id of the element that the primary iframe should be inserted into. If not set then the iframe will be positioned off-screen. Optional.
* @cfg {Array/String} acl (Provider only) Here you can specify which '[protocol]://[domain]' patterns that should be allowed to act as the consumer towards this provider.
* This can contain the wildcards ? and *. Examples are 'http://example.com', '*.foo.com' and '*dom?.com'. If you want to use reqular expressions then you pattern needs to start with ^ and end with $.
* If none of the patterns match an Error will be thrown.
* @cfg {Object} props (Consumer only) Additional properties that should be applied to the iframe. This can also contain nested objects e.g: {style:{width:"100px", height:"100px"}}.
* Properties such as 'name' and 'src' will be overrided. Optional.
*/
easyXDM.Socket = function(config){
// create the stack
var stack = chainStack(prepareTransportStack(config).concat([{
incoming: function(message, origin){
config.onMessage(message, origin);
},
callback: function(success){
if (config.onReady) {
config.onReady(success);
}
}
}])), recipient = getLocation(config.remote);
// set the origin
this.origin = getLocation(config.remote);
/**
* Initiates the destruction of the stack.
*/
this.destroy = function(){
stack.destroy();
};
/**
* Posts a message to the remote end of the channel
* @param {String} message The message to send
*/
this.postMessage = function(message){
stack.outgoing(message, recipient);
};
stack.init();
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef,, chainStack, prepareTransportStack, debug, getLocation */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.Rpc
* Creates a proxy object that can be used to call methods implemented on the remote end of the channel, and also to provide the implementation
* of methods to be called from the remote end.
* The instantiated object will have methods matching those specified in config.remote.
* This requires the JSON object present in the document, either natively, using json.org's json2 or as a wrapper around library spesific methods.
*
How to set up
*
* var rpc = new easyXDM.Rpc({
* // this configuration is equal to that used by the Socket.
* remote: "http://remotedomain/...",
* onReady: function(){
* // you need to wait for the onReady callback before using the proxy
* rpc.foo(...
* }
* },{
* local: {..},
* remote: {..}
* });
*
* The function referenced by [method] will receive the passed arguments followed by the callback functions success and error.
* To send a successfull result back you can use
*
* Both the success and errror callbacks are optional.
* When called with no callback a JSON-RPC 2.0 notification will be executed.
* Be aware that you will not be notified of any errors with this method.
*
*
Specifying a custom serializer
* If you do not want to use the JSON2 library for non-native JSON support, but instead capabilities provided by some other library
* then you can specify a custom serializer using serializer: foo
*
* If serializer is set then the class will not attempt to use the native implementation.
* @namespace easyXDM
* @constructor
* @param {Object} config The underlying transports configuration. See easyXDM.Socket for available parameters.
* @param {Object} jsonRpcConfig The description of the interface to implement.
*/
easyXDM.Rpc = function(config, jsonRpcConfig){
// expand shorthand notation
if (jsonRpcConfig.local) {
for (var method in jsonRpcConfig.local) {
if (jsonRpcConfig.local.hasOwnProperty(method)) {
var member = jsonRpcConfig.local[method];
if (typeof member === "function") {
jsonRpcConfig.local[method] = {
method: member
};
}
}
}
}
// create the stack
var stack = chainStack(prepareTransportStack(config).concat([new easyXDM.stack.RpcBehavior(this, jsonRpcConfig), {
callback: function(success){
if (config.onReady) {
config.onReady(success);
}
}
}]));
// set the origin
this.origin = getLocation(config.remote);
/**
* Initiates the destruction of the stack.
*/
this.destroy = function(){
stack.destroy();
};
stack.init();
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, getParentObject, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.SameOriginTransport
* SameOriginTransport is a transport class that can be used when both domains have the same origin.
* This can be useful for testing and for when the main application supports both internal and external sources.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote document to communicate with.
*/
easyXDM.stack.SameOriginTransport = function(config){
var pub, frame, send, targetOrigin;
return (pub = {
outgoing: function(message, domain, fn){
send(message);
if (fn) {
fn();
}
},
destroy: function(){
if (frame) {
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = getLocation(config.remote);
if (config.isHost) {
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: window.location.protocol + "//" + window.location.host + window.location.pathname,
xdm_c: config.channel,
xdm_p: 4 // 4 = SameOriginTransport
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
easyXDM.Fn.set(config.channel, function(sendFn){
send = sendFn;
setTimeout(function(){
pub.up.callback(true);
}, 0);
return function(msg){
pub.up.incoming(msg, targetOrigin);
};
});
}
else {
send = getParentObject().Fn.get(config.channel, true)(function(msg){
pub.up.incoming(msg, targetOrigin);
});
setTimeout(function(){
pub.up.callback(true);
}, 0);
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global global, easyXDM, window, getLocation, appendQueryParameters, createFrame, debug, apply, whenReady, IFRAME_PREFIX, namespace, resolveUrl, getDomainName, HAS_FLASH_THROTTLED_BUG, getPort, query*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.FlashTransport
* FlashTransport is a transport class that uses an SWF with LocalConnection to pass messages back and forth.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote domain to communicate with.
* @cfg {String} secret the pre-shared secret used to secure the communication.
* @cfg {String} swf The path to the swf file
* @cfg {Boolean} swfNoThrottle Set this to true if you want to take steps to avoid beeing throttled when hidden.
* @cfg {String || DOMElement} swfContainer Set this if you want to control where the swf is placed
*/
easyXDM.stack.FlashTransport = function(config){
var pub, // the public interface
frame, send, targetOrigin, swf, swfContainer;
function onMessage(message, origin){
setTimeout(function(){
pub.up.incoming(message, targetOrigin);
}, 0);
}
/**
* This method adds the SWF to the DOM and prepares the initialization of the channel
*/
function addSwf(domain){
// the differentiating query argument is needed in Flash9 to avoid a caching issue where LocalConnection would throw an error.
var url = config.swf + "?host=" + config.isHost;
var id = "easyXDM_swf_" + Math.floor(Math.random() * 10000);
// prepare the init function that will fire once the swf is ready
easyXDM.Fn.set("flash_loaded" + domain.replace(/[\-.]/g, "_"), function(){
easyXDM.stack.FlashTransport[domain].swf = swf = swfContainer.firstChild;
var queue = easyXDM.stack.FlashTransport[domain].queue;
for (var i = 0; i < queue.length; i++) {
queue[i]();
}
queue.length = 0;
});
if (config.swfContainer) {
swfContainer = (typeof config.swfContainer == "string") ? document.getElementById(config.swfContainer) : config.swfContainer;
}
else {
// create the container that will hold the swf
swfContainer = document.createElement('div');
// http://bugs.adobe.com/jira/browse/FP-4796
// http://tech.groups.yahoo.com/group/flexcoders/message/162365
// https://groups.google.com/forum/#!topic/easyxdm/mJZJhWagoLc
apply(swfContainer.style, HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle ? {
height: "20px",
width: "20px",
position: "fixed",
right: 0,
top: 0
} : {
height: "1px",
width: "1px",
position: "absolute",
overflow: "hidden",
right: 0,
top: 0
});
document.body.appendChild(swfContainer);
}
// create the object/embed
var flashVars = "callback=flash_loaded" + domain.replace(/[\-.]/g, "_") + "&proto=" + global.location.protocol + "&domain=" + getDomainName(global.location.href) + "&port=" + getPort(global.location.href) + "&ns=" + namespace;
swfContainer.innerHTML = "";
}
return (pub = {
outgoing: function(message, domain, fn){
swf.postMessage(config.channel, message.toString());
if (fn) {
fn();
}
},
destroy: function(){
try {
swf.destroyChannel(config.channel);
}
catch (e) {
}
swf = null;
if (frame) {
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = config.remote;
// Prepare the code that will be run after the swf has been intialized
easyXDM.Fn.set("flash_" + config.channel + "_init", function(){
setTimeout(function(){
pub.up.callback(true);
});
});
// set up the omMessage handler
easyXDM.Fn.set("flash_" + config.channel + "_onMessage", onMessage);
config.swf = resolveUrl(config.swf); // reports have been made of requests gone rogue when using relative paths
var swfdomain = getDomainName(config.swf);
var fn = function(){
// set init to true in case the fn was called was invoked from a separate instance
easyXDM.stack.FlashTransport[swfdomain].init = true;
swf = easyXDM.stack.FlashTransport[swfdomain].swf;
// create the channel
swf.createChannel(config.channel, config.secret, getLocation(config.remote), config.isHost);
if (config.isHost) {
// if Flash is going to be throttled and we want to avoid this
if (HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle) {
apply(config.props, {
position: "fixed",
right: 0,
top: 0,
height: "20px",
width: "20px"
});
}
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: getLocation(location.href),
xdm_c: config.channel,
xdm_p: 6, // 6 = FlashTransport
xdm_s: config.secret
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
}
};
if (easyXDM.stack.FlashTransport[swfdomain] && easyXDM.stack.FlashTransport[swfdomain].init) {
// if the swf is in place and we are the consumer
fn();
}
else {
// if the swf does not yet exist
if (!easyXDM.stack.FlashTransport[swfdomain]) {
// add the queue to hold the init fn's
easyXDM.stack.FlashTransport[swfdomain] = {
queue: [fn]
};
addSwf(swfdomain);
}
else {
easyXDM.stack.FlashTransport[swfdomain].queue.push(fn);
}
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.PostMessageTransport
* PostMessageTransport is a transport class that uses HTML5 postMessage for communication.
* http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx
* https://developer.mozilla.org/en/DOM/window.postMessage
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote domain to communicate with.
*/
easyXDM.stack.PostMessageTransport = function(config){
var pub, // the public interface
frame, // the remote frame, if any
callerWindow, // the window that we will call with
targetOrigin; // the domain to communicate with
/**
* Resolves the origin from the event object
* @private
* @param {Object} event The messageevent
* @return {String} The scheme, host and port of the origin
*/
function _getOrigin(event){
if (event.origin) {
// This is the HTML5 property
return getLocation(event.origin);
}
if (event.uri) {
// From earlier implementations
return getLocation(event.uri);
}
if (event.domain) {
// This is the last option and will fail if the
// origin is not using the same schema as we are
return location.protocol + "//" + event.domain;
}
throw "Unable to retrieve the origin of the event";
}
/**
* This is the main implementation for the onMessage event.
* It checks the validity of the origin and passes the message on if appropriate.
* @private
* @param {Object} event The messageevent
*/
function _window_onMessage(event){
var origin = _getOrigin(event);
if (origin == targetOrigin && event.data.substring(0, config.channel.length + 1) == config.channel + " ") {
pub.up.incoming(event.data.substring(config.channel.length + 1), origin);
}
}
return (pub = {
outgoing: function(message, domain, fn){
callerWindow.postMessage(config.channel + " " + message, domain || targetOrigin);
if (fn) {
fn();
}
},
destroy: function(){
un(window, "message", _window_onMessage);
if (frame) {
callerWindow = null;
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = getLocation(config.remote);
if (config.isHost) {
// add the event handler for listening
var waitForReady = function(event){
if (event.data == config.channel + "-ready") {
// replace the eventlistener
callerWindow = ("postMessage" in frame.contentWindow) ? frame.contentWindow : frame.contentWindow.document;
un(window, "message", waitForReady);
on(window, "message", _window_onMessage);
setTimeout(function(){
pub.up.callback(true);
}, 0);
}
};
on(window, "message", waitForReady);
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: getLocation(window.location.href),
xdm_c: config.channel,
xdm_p: 1 // 1 = PostMessage
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
}
else {
// add the event handler for listening
on(window, "message", _window_onMessage);
callerWindow = ("postMessage" in window.parent) ? window.parent : window.parent.document;
callerWindow.postMessage(config.channel + "-ready", targetOrigin);
setTimeout(function(){
pub.up.callback(true);
}, 0);
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, apply, query, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.FrameElementTransport
* FrameElementTransport is a transport class that can be used with Gecko-browser as these allow passing variables using the frameElement property.
* Security is maintained as Gecho uses Lexical Authorization to determine under which scope a function is running.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote document to communicate with.
*/
easyXDM.stack.FrameElementTransport = function(config){
var pub, frame, send, targetOrigin;
return (pub = {
outgoing: function(message, domain, fn){
send.call(this, message);
if (fn) {
fn();
}
},
destroy: function(){
if (frame) {
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = getLocation(config.remote);
if (config.isHost) {
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: getLocation(location.href),
xdm_c: config.channel,
xdm_p: 5 // 5 = FrameElementTransport
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
frame.fn = function(sendFn){
delete frame.fn;
send = sendFn;
setTimeout(function(){
pub.up.callback(true);
}, 0);
// remove the function so that it cannot be used to overwrite the send function later on
return function(msg){
pub.up.incoming(msg, targetOrigin);
};
};
}
else {
// This is to mitigate origin-spoofing
if (document.referrer && getLocation(document.referrer) != query.xdm_e) {
window.top.location = query.xdm_e;
}
send = window.frameElement.fn(function(msg){
pub.up.incoming(msg, targetOrigin);
});
pub.up.callback(true);
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef, getLocation, appendQueryParameters, resolveUrl, createFrame, debug, un, apply, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.NameTransport
* NameTransport uses the window.name property to relay data.
* The local parameter needs to be set on both the consumer and provider,
* and the remoteHelper parameter needs to be set on the consumer.
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remoteHelper The url to the remote instance of hash.html - this is only needed for the host.
* @namespace easyXDM.stack
*/
easyXDM.stack.NameTransport = function(config){
var pub; // the public interface
var isHost, callerWindow, remoteWindow, readyCount, callback, remoteOrigin, remoteUrl;
function _sendMessage(message){
var url = config.remoteHelper + (isHost ? "#_3" : "#_2") + config.channel;
callerWindow.contentWindow.sendMessage(message, url);
}
function _onReady(){
if (isHost) {
if (++readyCount === 2 || !isHost) {
pub.up.callback(true);
}
}
else {
_sendMessage("ready");
pub.up.callback(true);
}
}
function _onMessage(message){
pub.up.incoming(message, remoteOrigin);
}
function _onLoad(){
if (callback) {
setTimeout(function(){
callback(true);
}, 0);
}
}
return (pub = {
outgoing: function(message, domain, fn){
callback = fn;
_sendMessage(message);
},
destroy: function(){
callerWindow.parentNode.removeChild(callerWindow);
callerWindow = null;
if (isHost) {
remoteWindow.parentNode.removeChild(remoteWindow);
remoteWindow = null;
}
},
onDOMReady: function(){
isHost = config.isHost;
readyCount = 0;
remoteOrigin = getLocation(config.remote);
config.local = resolveUrl(config.local);
if (isHost) {
// Register the callback
easyXDM.Fn.set(config.channel, function(message){
if (isHost && message === "ready") {
// Replace the handler
easyXDM.Fn.set(config.channel, _onMessage);
_onReady();
}
});
// Set up the frame that points to the remote instance
remoteUrl = appendQueryParameters(config.remote, {
xdm_e: config.local,
xdm_c: config.channel,
xdm_p: 2
});
apply(config.props, {
src: remoteUrl + '#' + config.channel,
name: IFRAME_PREFIX + config.channel + "_provider"
});
remoteWindow = createFrame(config);
}
else {
config.remoteHelper = config.remote;
easyXDM.Fn.set(config.channel, _onMessage);
}
// Set up the iframe that will be used for the transport
callerWindow = createFrame({
props: {
src: config.local + "#_4" + config.channel
},
onLoad: function onLoad(){
// Remove the handler
var w = callerWindow || this;
un(w, "load", onLoad);
easyXDM.Fn.set(config.channel + "_load", _onLoad);
(function test(){
if (typeof w.contentWindow.sendMessage == "function") {
_onReady();
}
else {
setTimeout(test, 50);
}
}());
}
});
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.HashTransport
* HashTransport is a transport class that uses the IFrame URL Technique for communication.
* http://msdn.microsoft.com/en-us/library/bb735305.aspx
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String/Window} local The url to the local file used for proxying messages, or the local window.
* @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window.
* @cfg {Number} interval The interval used when polling for messages.
*/
easyXDM.stack.HashTransport = function(config){
var pub;
var me = this, isHost, _timer, pollInterval, _lastMsg, _msgNr, _listenerWindow, _callerWindow;
var useParent, _remoteOrigin;
function _sendMessage(message){
if (!_callerWindow) {
return;
}
var url = config.remote + "#" + (_msgNr++) + "_" + message;
((isHost || !useParent) ? _callerWindow.contentWindow : _callerWindow).location = url;
}
function _handleHash(hash){
_lastMsg = hash;
pub.up.incoming(_lastMsg.substring(_lastMsg.indexOf("_") + 1), _remoteOrigin);
}
/**
* Checks location.hash for a new message and relays this to the receiver.
* @private
*/
function _pollHash(){
if (!_listenerWindow) {
return;
}
var href = _listenerWindow.location.href, hash = "", indexOf = href.indexOf("#");
if (indexOf != -1) {
hash = href.substring(indexOf);
}
if (hash && hash != _lastMsg) {
_handleHash(hash);
}
}
function _attachListeners(){
_timer = setInterval(_pollHash, pollInterval);
}
return (pub = {
outgoing: function(message, domain){
_sendMessage(message);
},
destroy: function(){
window.clearInterval(_timer);
if (isHost || !useParent) {
_callerWindow.parentNode.removeChild(_callerWindow);
}
_callerWindow = null;
},
onDOMReady: function(){
isHost = config.isHost;
pollInterval = config.interval;
_lastMsg = "#" + config.channel;
_msgNr = 0;
useParent = config.useParent;
_remoteOrigin = getLocation(config.remote);
if (isHost) {
config.props = {
src: config.remote,
name: IFRAME_PREFIX + config.channel + "_provider"
};
if (useParent) {
config.onLoad = function(){
_listenerWindow = window;
_attachListeners();
pub.up.callback(true);
};
}
else {
var tries = 0, max = config.delay / 50;
(function getRef(){
if (++tries > max) {
throw new Error("Unable to reference listenerwindow");
}
try {
_listenerWindow = _callerWindow.contentWindow.frames[IFRAME_PREFIX + config.channel + "_consumer"];
}
catch (ex) {
}
if (_listenerWindow) {
_attachListeners();
pub.up.callback(true);
}
else {
setTimeout(getRef, 50);
}
}());
}
_callerWindow = createFrame(config);
}
else {
_listenerWindow = window;
_attachListeners();
if (useParent) {
_callerWindow = parent;
pub.up.callback(true);
}
else {
apply(config, {
props: {
src: config.remote + "#" + config.channel + new Date(),
name: IFRAME_PREFIX + config.channel + "_consumer"
},
onLoad: function(){
pub.up.callback(true);
}
});
_callerWindow = createFrame(config);
}
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.ReliableBehavior
* This is a behavior that tries to make the underlying transport reliable by using acknowledgements.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The behaviors configuration.
*/
easyXDM.stack.ReliableBehavior = function(config){
var pub, // the public interface
callback; // the callback to execute when we have a confirmed success/failure
var idOut = 0, idIn = 0, currentMessage = "";
return (pub = {
incoming: function(message, origin){
var indexOf = message.indexOf("_"), ack = message.substring(0, indexOf).split(",");
message = message.substring(indexOf + 1);
if (ack[0] == idOut) {
currentMessage = "";
if (callback) {
callback(true);
}
}
if (message.length > 0) {
pub.down.outgoing(ack[1] + "," + idOut + "_" + currentMessage, origin);
if (idIn != ack[1]) {
idIn = ack[1];
pub.up.incoming(message, origin);
}
}
},
outgoing: function(message, origin, fn){
currentMessage = message;
callback = fn;
pub.down.outgoing(idIn + "," + (++idOut) + "_" + message, origin);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, debug, undef, removeFromStack*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.QueueBehavior
* This is a behavior that enables queueing of messages.
* It will buffer incoming messages and dispach these as fast as the underlying transport allows.
* This will also fragment/defragment messages so that the outgoing message is never bigger than the
* set length.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The behaviors configuration. Optional.
* @cfg {Number} maxLength The maximum length of each outgoing message. Set this to enable fragmentation.
*/
easyXDM.stack.QueueBehavior = function(config){
var pub, queue = [], waiting = true, incoming = "", destroying, maxLength = 0, lazy = false, doFragment = false;
function dispatch(){
if (config.remove && queue.length === 0) {
removeFromStack(pub);
return;
}
if (waiting || queue.length === 0 || destroying) {
return;
}
waiting = true;
var message = queue.shift();
pub.down.outgoing(message.data, message.origin, function(success){
waiting = false;
if (message.callback) {
setTimeout(function(){
message.callback(success);
}, 0);
}
dispatch();
});
}
return (pub = {
init: function(){
if (undef(config)) {
config = {};
}
if (config.maxLength) {
maxLength = config.maxLength;
doFragment = true;
}
if (config.lazy) {
lazy = true;
}
else {
pub.down.init();
}
},
callback: function(success){
waiting = false;
var up = pub.up; // in case dispatch calls removeFromStack
dispatch();
up.callback(success);
},
incoming: function(message, origin){
if (doFragment) {
var indexOf = message.indexOf("_"), seq = parseInt(message.substring(0, indexOf), 10);
incoming += message.substring(indexOf + 1);
if (seq === 0) {
if (config.encode) {
incoming = decodeURIComponent(incoming);
}
pub.up.incoming(incoming, origin);
incoming = "";
}
}
else {
pub.up.incoming(message, origin);
}
},
outgoing: function(message, origin, fn){
if (config.encode) {
message = encodeURIComponent(message);
}
var fragments = [], fragment;
if (doFragment) {
// fragment into chunks
while (message.length !== 0) {
fragment = message.substring(0, maxLength);
message = message.substring(fragment.length);
fragments.push(fragment);
}
// enqueue the chunks
while ((fragment = fragments.shift())) {
queue.push({
data: fragments.length + "_" + fragment,
origin: origin,
callback: fragments.length === 0 ? fn : null
});
}
}
else {
queue.push({
data: message,
origin: origin,
callback: fn
});
}
if (lazy) {
pub.down.init();
}
else {
dispatch();
}
},
destroy: function(){
destroying = true;
pub.down.destroy();
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.VerifyBehavior
* This behavior will verify that communication with the remote end is possible, and will also sign all outgoing,
* and verify all incoming messages. This removes the risk of someone hijacking the iframe to send malicious messages.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The behaviors configuration.
* @cfg {Boolean} initiate If the verification should be initiated from this end.
*/
easyXDM.stack.VerifyBehavior = function(config){
var pub, mySecret, theirSecret, verified = false;
function startVerification(){
mySecret = Math.random().toString(16).substring(2);
pub.down.outgoing(mySecret);
}
return (pub = {
incoming: function(message, origin){
var indexOf = message.indexOf("_");
if (indexOf === -1) {
if (message === mySecret) {
pub.up.callback(true);
}
else if (!theirSecret) {
theirSecret = message;
if (!config.initiate) {
startVerification();
}
pub.down.outgoing(message);
}
}
else {
if (message.substring(0, indexOf) === theirSecret) {
pub.up.incoming(message.substring(indexOf + 1), origin);
}
}
},
outgoing: function(message, origin, fn){
pub.down.outgoing(mySecret + "_" + message, origin, fn);
},
callback: function(success){
if (config.initiate) {
startVerification();
}
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef, getJSON, debug, emptyFn, isArray */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.RpcBehavior
* This uses JSON-RPC 2.0 to expose local methods and to invoke remote methods and have responses returned over the the string based transport stack.
* Exposed methods can return values synchronous, asyncronous, or bet set up to not return anything.
* @namespace easyXDM.stack
* @constructor
* @param {Object} proxy The object to apply the methods to.
* @param {Object} config The definition of the local and remote interface to implement.
* @cfg {Object} local The local interface to expose.
* @cfg {Object} remote The remote methods to expose through the proxy.
* @cfg {Object} serializer The serializer to use for serializing and deserializing the JSON. Should be compatible with the HTML5 JSON object. Optional, will default to JSON.
*/
easyXDM.stack.RpcBehavior = function(proxy, config){
var pub, serializer = config.serializer || getJSON();
var _callbackCounter = 0, _callbacks = {};
/**
* Serializes and sends the message
* @private
* @param {Object} data The JSON-RPC message to be sent. The jsonrpc property will be added.
*/
function _send(data){
data.jsonrpc = "2.0";
pub.down.outgoing(serializer.stringify(data));
}
/**
* Creates a method that implements the given definition
* @private
* @param {Object} The method configuration
* @param {String} method The name of the method
* @return {Function} A stub capable of proxying the requested method call
*/
function _createMethod(definition, method){
var slice = Array.prototype.slice;
return function(){
var l = arguments.length, callback, message = {
method: method
};
if (l > 0 && typeof arguments[l - 1] === "function") {
//with callback, procedure
if (l > 1 && typeof arguments[l - 2] === "function") {
// two callbacks, success and error
callback = {
success: arguments[l - 2],
error: arguments[l - 1]
};
message.params = slice.call(arguments, 0, l - 2);
}
else {
// single callback, success
callback = {
success: arguments[l - 1]
};
message.params = slice.call(arguments, 0, l - 1);
}
_callbacks["" + (++_callbackCounter)] = callback;
message.id = _callbackCounter;
}
else {
// no callbacks, a notification
message.params = slice.call(arguments, 0);
}
if (definition.namedParams && message.params.length === 1) {
message.params = message.params[0];
}
// Send the method request
_send(message);
};
}
/**
* Executes the exposed method
* @private
* @param {String} method The name of the method
* @param {Number} id The callback id to use
* @param {Function} method The exposed implementation
* @param {Array} params The parameters supplied by the remote end
*/
function _executeMethod(method, id, fn, params){
if (!fn) {
if (id) {
_send({
id: id,
error: {
code: -32601,
message: "Procedure not found."
}
});
}
return;
}
var success, error;
if (id) {
success = function(result){
success = emptyFn;
_send({
id: id,
result: result
});
};
error = function(message, data){
error = emptyFn;
var msg = {
id: id,
error: {
code: -32099,
message: message
}
};
if (data) {
msg.error.data = data;
}
_send(msg);
};
}
else {
success = error = emptyFn;
}
// Call local method
if (!isArray(params)) {
params = [params];
}
try {
var result = fn.method.apply(fn.scope, params.concat([success, error]));
if (!undef(result)) {
success(result);
}
}
catch (ex1) {
error(ex1.message);
}
}
return (pub = {
incoming: function(message, origin){
var data = serializer.parse(message);
if (data.method) {
// A method call from the remote end
if (config.handle) {
config.handle(data, _send);
}
else {
_executeMethod(data.method, data.id, config.local[data.method], data.params);
}
}
else {
// A method response from the other end
var callback = _callbacks[data.id];
if (data.error) {
if (callback.error) {
callback.error(data.error);
}
}
else if (callback.success) {
callback.success(data.result);
}
delete _callbacks[data.id];
}
},
init: function(){
if (config.remote) {
// Implement the remote sides exposed methods
for (var method in config.remote) {
if (config.remote.hasOwnProperty(method)) {
proxy[method] = _createMethod(config.remote[method], method);
}
}
}
pub.down.init();
},
destroy: function(){
for (var method in config.remote) {
if (config.remote.hasOwnProperty(method) && proxy.hasOwnProperty(method)) {
delete proxy[method];
}
}
pub.down.destroy();
}
});
};
global.easyXDM = easyXDM;
})(window, document, location, window.setTimeout, decodeURIComponent, encodeURIComponent);
// --- [KortInfoApi.js] ---------------------------------
// Namespace
var KortInfo = {};
// --- [Exceptions] ---------------------------------------------------------------------------------
KortInfo.NotReadyException = function () {
};
KortInfo.NotReadyException.prototype.toString = function () {
return "KortInfo Instance is not ready. (KortInfo API)";
};
KortInfo.NotImplementedException = function () {
};
KortInfo.NotImplementedException.prototype.toString = function () {
return "Method has not yet been implemented. (KortInfo API)";
};
KortInfo.InvalidOperationException = function (message) {
this.message = message;
};
KortInfo.InvalidOperationException.prototype.toString = function () {
if (this.message == null) {
return "InvalidOperationException (KortInfo API)";
}
return this.message;
};
KortInfo.ArgumentException = function (message) {
this.message = message;
if (this.message == null) {
this.message = "ArgumentException (KortInfo API)";
}
};
KortInfo.ArgumentException.prototype.toString = function () {
return this.message;
};
// --------------------------------------------------------------------------------------------------
// --- [Begin class KortInfo.Instance] --------------------------------------------------------------
// public constructor
KortInfo.Instance = function (siteName, pageName) {
// private fields
this.baseUrl = KortInfoApi_BaseUrl;
this.urlArgs = {};
this.siteName = siteName;
this.pageName = pageName;
this.ready = false;
this.readyListener = null;
this.initializeFlag = false;
this._callbackIdCounter = 1;
this._callbacks = {};
this._listenerIdCounter = 1;
this._listeners = {};
// public properties
this.Map = new KortInfo.MapClass(this);
this.ThemeTrees = new KortInfo.ThemeTreesClass(this);
this.BackgroundLayers = new KortInfo.BackgroundLayersClass(this);
this.Lite = {};
this.Lite.ThemeTrees = new KortInfo.Lite.ThemeTreesClass(this);
};
KortInfo.Instance.prototype.private_checkReady = function () {
if (!this.ready) throw new KortInfo.NotReadyException();
};
KortInfo.Instance.prototype.setUrlArgsByString = function (argsStr) {
var argPairs = argsStr.split("&");
for (var k = 0; k < argPairs.length; k++) {
var argPair = argPairs[k];
var j = argPair.indexOf("=");
if (j >= 0) {
setUrlArg(decodeURIComponent(argPair.substr(0, j)), decodeURIComponent(argPair.substr(j + 1)));
} else {
setUrlArg(decodeURIComponent(argPair, ""));
}
}
};
KortInfo.Instance.prototype.setUrlArg = function (arg, value) {
arg = arg.toLowerCase();
if (arg == "page" || arg == "site" || arg == "apiversion") {
throw new KortInfo.ArgumentException("'" + arg + "' is a reserved URL argument.");
}
this.urlArgs[arg] = value;
};
KortInfo.Instance.prototype.getUrlArgsAsString = function () {
var s = "";
for (var k in this.urlArgs) {
if (s.length > 0) s += "&";
s += encodeURIComponent(k);
var v = this.urlArgs[k];
if (v != null) {
s += "=" + encodeURIComponent(v);
}
}
return s;
};
KortInfo.Instance.prototype.setBaseUrl = function (url) {
if (url.indexOf("?") >= 0 || url.indexOf("&") >= 0) {
throw new KortInfo.ArgumentException("Base URL may not contain arguments.");
}
if (url.length == 0 || url[url.length - 1] != "/") url += "/";
this.baseUrl = url;
};
KortInfo.Instance.prototype.getBaseUrl = function () {
return this.baseUrl;
};
KortInfo.Instance.prototype.initializeDebug = function (debugUrl, container) {
if (this.initializeFlag) throw new KortInfo.InvalidOperationException("Instance is already initialized.");
this.initializeFlag = true;
var args = this.getUrlArgsAsString();
if (args.length > 0) args = "&" + args;
var url = debugUrl + "?" + "site=" + this.siteName + "&page=" + this.pageName + "&apiversion=1" + args;
KortInfoApi_initializeDebug(this, url, container);
};
KortInfo.Instance.prototype.initializeNested = function (container) {
if (this.initializeFlag) throw new KortInfo.InvalidOperationException("Instance is already initialized.");
this.initializeFlag = true;
var args = this.getUrlArgsAsString();
if (args.length > 0) args = "&" + args;
var url = this.baseUrl + "Map.aspx?site=" + this.siteName + "&page=" + this.pageName + "&apiversion=1" + args;
KortInfoApi_initializeNested(this, url, container);
};
function KortInfoApi_initializeNested(api, url, container) {
var xdmConfig = {
remote: url,
container: container,
props: {
style: {
width: "100%", height: "100%"
}
}
};
KortInfoApi_initialize(api, xdmConfig);
}
function KortInfoApi_initializeDebug(api, url, container) {
var xdmConfig = {
remote: url,
container: container
};
KortInfoApi_initialize(api, xdmConfig);
}
/*
NOTE: windowed fungerer ikke
IE8 understøtter kun postMessage til iframes og ikke vinduer!
http://blogs.msdn.com/b/ieinternals/archive/2009/09/16/bugs-in-ie8-support-for-html5-postmessage-sessionstorage-and-localstorage.aspx
*/
KortInfo.Instance.prototype.private_setMethods = function (methods) {
this.methods = methods;
};
KortInfo.Instance.prototype.isReady = function () {
return this.ready;
};
KortInfo.Instance.prototype.setReadyListener = function (listener) {
this.readyListener = listener;
if (this.ready && listener != null) {
listener();
}
};
// ------ [Callbacks] ----------
KortInfo.Instance.prototype.callback_onReady = function () {
this.ready = true;
if (this.readyListener != null) {
this.readyListener();
}
};
KortInfo.Instance.prototype.callback_onCallback = function (cbId, argsArray) {
var cb = this._callbacks[cbId];
delete this._callbacks[cbId];
if (cb.result != null) {
cb.result.apply({}, argsArray);
}
};
KortInfo.Instance.prototype.callback_onCallbackError = function (cbId, argsArray) {
var cb = this._callbacks[cbId];
delete this._callbacks[cbId];
if (cb.error != null) {
cb.error.apply({}, argsArray);
}
};
KortInfo.Instance.prototype.callback_onListener = function (listenerId, argsArray) {
var listener = this._listeners[listenerId];
listener.apply({}, argsArray);
};
// -----------------------------
KortInfo.Instance.prototype._createCallback = function (resultCallback, errorCallback) {
var id = this._callbackIdCounter++;
this._callbacks[id] = { result: resultCallback, error: errorCallback };
return id;
};
KortInfo.Instance.prototype._createListener = function (listener) {
var id = this._listenerIdCounter++;
this._listeners[id] = listener;
return id;
};
KortInfo.Instance.prototype._destroyListener = function (id) {
delete this._listeners[id];
};
// -----------------------------
// --- [End class KortInfo.Instance] --------------------------------------------------------------
// --- [KortInfoApi_Tools.js] ---------------------------------
function delegate(instance, method) {
return function () { return method.apply(instance, arguments); };
}
Array.prototype.removeItem = function (itemToRemove) {
for (var i = 0; i < this.length; i++) {
if (this[i] == itemToRemove) {
this.splice(i, 1);
return i;
}
}
return -1;
};
Array.prototype.clone = function () {
var c = new Array();
for (var i = 0; i < this.length; ++i) {
c[i] = this[i];
}
return c;
};
KortInfo.Tools = {};
KortInfo.Tools.createNamespace = function(ns)
{
var splitNs = ns.split('.');
var i, base = window;
for (i = 0; i < splitNs.length; i++) {
if (typeof(base[splitNs[i]]) == 'undefined') base[splitNs[i]] = {};
base = base[splitNs[i]];
}
};
KortInfo.Tools.createNamespace('KortInfo.Tools.UrlTools');
KortInfo.Tools.UrlTools.parseUrl = function (url) {
var j = url.indexOf("?");
var baseUrl;
var urlArgs = new Array();
if (j >= 0) {
baseUrl = url.substr(0, j);
var argPairs = url.substr(j + 1).split("&");
for (var k = 0; k < argPairs.length; k++) {
var argPair = argPairs[k];
var j2 = argPair.indexOf("=");
var urlArg = {};
urlArg.key = decodeURIComponent(argPair.substr(0, j2));
urlArg.value = decodeURIComponent(argPair.substr(j2 + 1));
urlArgs.push(urlArg);
}
} else {
baseUrl = url;
}
var rv = {};
rv.baseUrl = baseUrl;
rv.urlArgs = urlArgs;
return rv;
};
// --- [KortInfoApi_Backgrounds.js] ---------------------------------
// --- [Begin class KortInfo.BackgroundLayersClass] -----------------------------------------------
// private constructor
KortInfo.BackgroundLayersClass = function (instance) {
this._instance = instance;
this.backgrounds = {}; // Dictionary
};
// resultCallback returns the active backgroundlayer if exists, else null
KortInfo.BackgroundLayersClass.prototype.getActiveBackgroundLayer = function (resultCallback) {
this._instance.private_checkReady();
this._instance.methods.kortinfo_background_getActiveBackgroundLayer(delegate(this, function (layer) {
var background = null;
if (layer != null) {
background = new KortInfo.BackgroundLayer(this._instance, layer.id, layer.key, layer.name);
this.backgrounds[layer.id] = background;
}
if (resultCallback != null)
resultCallback(background);
}));
};
//
// resultCallback returns the backgroundlayer if exists, else null
// key is the apiKey of the backgroundlayer
KortInfo.BackgroundLayersClass.prototype.getByKey = function (key, resultCallback) {
this._instance.private_checkReady();
var background = null;
for (var layer in this.backgrounds) {
if (this.backgrounds[layer] == key) {
background = this.backgrounds[layer];
}
}
if (background == null) {
this._instance.methods.kortinfo_background_getBackgroundLayerByKey(key, delegate(this, function (layer) {
background = null;
if (layer != null) {
background = new KortInfo.BackgroundLayer(this._instance, layer.id, layer.key, layer.name);
this.backgrounds[layer.id] = background;
}
if (resultCallback != null)
resultCallback(background);
}));
} else {
if (resultCallback != null)
resultCallback(background);
}
};
// resultCallback returns true for success or false for faliure.
// key is the apiKey of the backgroundlayer
KortInfo.BackgroundLayersClass.prototype.activateByKey = function (key, resultCallback) {
this.getByKey(key, function (bgLayer) {
if (bgLayer != null) {
bgLayer.activate();
}
if (resultCallback != null)
resultCallback(bgLayer != null);
});
};
// --- [Begin "Not implemented"] ------------------------------------------------------------------
// returns an array of all BackgroundLayers in resultCallback
KortInfo.BackgroundLayersClass.prototype.getBackgroundLayers = function (resultCallback) {
this._instance.private_checkReady();
throw new KortInfo.NotImplementedException();
};
// --- [End "Not implemented"] ----------------------------------------------------------------
// --- [End class KortInfo.BackgroundLayersClass] ---------------------------------------------
// --- [Begin class KortInfo.BackgroundLayer] -------------------------------------------------
// private constructor
// id: Integer - KortInfo backgroundlayer config id
// key: String - KortInfo backgroundlayer apikey
// name: String - KortInfo backgroundlayer config name
KortInfo.BackgroundLayer = function (instance, id, key, name) {
this._instance = instance;
this.id = id;
this.key = key;
this.name = name;
};
KortInfo.BackgroundLayer.prototype.getId = function () {
return this.id;
};
KortInfo.BackgroundLayer.prototype.getName = function () {
return this.name;
};
KortInfo.BackgroundLayer.prototype.getKey = function () {
return this.key;
};
// resultCallback returns true for success or false for faliure.
KortInfo.BackgroundLayer.prototype.activate = function (resultCallback) {
this._instance.methods.kortinfo_background_activateByKey(this.key, delegate(this, function (result) {
if (resultCallback != null)
resultCallback(result);
}));
};
// resultCallback returns true for success or false for faliure.
KortInfo.BackgroundLayer.prototype.isActive = function (resultCallback) {
this._instance.methods.kortinfo_background_isActive(this.key, delegate(this, function (result) {
if (resultCallback != null)
resultCallback(result);
}));
};
// --- [End class KortInfo.BackgroundLayer] ---------------------------------------------------
// --- [KortInfoApi_ThemeTrees.js] ---------------------------------
// --- [Begin class KortInfo.ThemeTreesClass] -----------------------------------------------------
// private constructor
KortInfo.ThemeTreesClass = function (instance) {
this._instance = instance;
this.themeTrees = new Object(); // Dictionary
};
// returns null if the themetree doesn't exist.
// themeTreeKey is the KortInfo apiKey of the Tree
KortInfo.ThemeTreesClass.prototype.getThemeTreeByKey = function (themeTreeKey, resultCallback) {
this._instance.methods.kortinfo_themetrees_getThemeTreeByKey(themeTreeKey, delegate(this, function (themeTree) {
if (themeTree == null || themeTree.themeTreeId <= 0) {
if(resultCallback != null)
resultCallback(null);
return;
}
var tmpThemeTree = this.themeTrees[themeTree.themeTreeId];
if (tmpThemeTree == null) {
tmpThemeTree = new KortInfo.ThemeTree(this._instance, themeTree.themeTreeId, themeTree.themeTreeKey);
this.themeTrees[themeTree.themeTreeId] = tmpThemeTree;
}
if(resultCallback != null)
resultCallback(tmpThemeTree);
}));
};
// --- [Begin "Not implemented"] ------------------------------------------------------------------
// resultCallback returns ??
KortInfo.ThemeTreesClass.prototype.getDefaultThemeTree = function (resultCallback) {
this._instance.private_checkReady();
throw new KortInfo.NotImplementedException();
};
// --- [End "Not implemented"] --------------------------------------------------------------------
// --- [End class KortInfo.ThemeTreesClass] -------------------------------------------------------
// --- [Begin class KortInfo.ThemeTree] -----------------------------------------------------------
// private constructor
// themeTreeId: Integer - KortInfo theme tree config id
// themeTreeKey: String - KortInfo theme apikey
KortInfo.ThemeTree = function (instance, themeTreeId, themeTreeKey) {
this._instance = instance;
this.themeTreeId = themeTreeId;
this._themeTreeKey = themeTreeKey;
};
KortInfo.ThemeTree.prototype.getThemeTreeKey = function () {
return this._themeTreeKey;
};
KortInfo.ThemeTree.prototype.getThemeTreeId = function () {
return this.themeTreeId;
};
// resultCallback returns the layer, null if layer doesn't exists
// themeLayerKey is apikey of the theme
KortInfo.ThemeTree.prototype.getLayerByKey = function (themeLayerKey, resultCallback) {
this._instance.private_checkReady();
this._instance.methods.kortinfo_themetrees_getThemeByKey(this._themeTreeKey, themeLayerKey, delegate(this, function (themeLayer) {
if (themeLayer == null) {
if (resultCallback != null)
resultCallback(null);
return;
}
var tmpThemeLayer = new KortInfo.ThemeTreeLayer(this._instance, this._themeTreeKey, themeLayer.themeLayerId, themeLayer.themeLayerKey)
if (resultCallback != null)
resultCallback(tmpThemeLayer);
}));
};
// --- [End class KortInfo.ThemeTree] ------------------------------------------------------------
// --- [Begin class KortInfo.ThemeTreeLayer] -----------------------------------------------------
// private constructor
// themeLayerId: Integer - KortInfo theme layer config id
// themeLayerKey: String - KortInfo theme apikey
// themeTreeKey: String - KortInfo themeTree apikey
KortInfo.ThemeTreeLayer = function (instance, themeTreeKey, themeLayerId, themeLayerKey) {
this._instance = instance;
this._themeLayerId = themeLayerId;
this._themeLayerKey = themeLayerKey;
this._themeTreeKey = themeTreeKey;
};
KortInfo.ThemeTreeLayer.prototype.getThemeLayerKey = function () {
return this._themeLayerKey;
};
KortInfo.ThemeTreeLayer.prototype.getThemeLayerId = function () {
return this._themeLayerId;
};
// resultCallback returns the result of the action
// active determines whether the layer should be activated or not
KortInfo.ThemeTreeLayer.prototype.setActive = function (active, resultCallback) {
this._instance.private_checkReady();
this._instance.methods.kortinfo_themetrees_activateTheme(this._themeLayerId, active, delegate(this, function (result) {
if (resultCallback != null)
resultCallback(result);
}));
};
// resultCallback returns the result of the action
KortInfo.ThemeTreeLayer.prototype.isActive = function (resultCallback) {
this._instance.private_checkReady();
this._instance.methods.kortinfo_themetrees_isThemeActive(this._themeLayerId, delegate(this, function (result) {
if (resultCallback != null)
resultCallback(result);
}));
};
KortInfo.ThemeTreeLayer.prototype.getFeaturesByPoint = function (point, pointEpsg, pointRadius, wantGeometry, outputEpsg, columns, maxCount, resultCallback, errorCallback) {
this._instance.private_checkReady();
var cb = function (features) {
if (resultCallback != null) {
resultCallback(KortInfo.Features._createFeatureCollection(features));
}
};
var callbackId = this._instance._createCallback(cb, errorCallback);
if (maxCount == null) maxCount = -1;
this._instance.methods.kortinfo_themetrees_getFeaturesByPoint(this._themeLayerId, point, pointEpsg, pointRadius, wantGeometry, outputEpsg, columns, maxCount, callbackId);
};
// expression: String
KortInfo.ThemeTreeLayer.prototype.getFeaturesByExpression = function (expression, wantGeometry, outputEpsg, columns, maxCount, resultCallback, errorCallback) {
this._instance.private_checkReady();
var cb = function (features) {
if (resultCallback != null) {
resultCallback(KortInfo.Features._createFeatureCollection(features));
}
};
var callbackId = this._instance._createCallback(cb, errorCallback);
if (maxCount == null) maxCount = -1;
this._instance.methods.kortinfo_themetrees_getFeaturesByExpression(this._themeLayerId, expression, wantGeometry, outputEpsg, columns, maxCount, callbackId);
};
// Predicate is applied to map visibility, tooltip, featureinfo and print
// expression: String
KortInfo.ThemeTreeLayer.prototype.setPredicateExpression = function (expression) {
this._instance.private_checkReady();
this._instance.methods.kortinfo_themetrees_setPredicateExpression(this._themeLayerId, expression);
};
// --- [End class KortInfo.ThemeTreeLayer] --------------------------------------------------------
// --- [KortInfoApi_Map.js] ---------------------------------
// Namespace
KortInfo.Map = {};
// --- [Begin class KortInfo.MapClass] ------------------------------------------------------------
/*KortInfo.MapTools = {
None: { private_key : "None" },
Custom: { private_key : "Custom" }, // F.eks. modulspecifikke værktøjer, som ikke kan sættes vha setMapTool
FeatureInfo: { private_key : "FeatureInfo" },
Pan: { private_key : "Pan" },
ZoomIn: { private_key : "ZoomIn" },
ZoomOut: { private_key : "ZoomOut" },
SelectPoint : { private_key : "SelectPoint" },
SelectPolygon : { private_key : "SelectPolygon" },
SelectRectangle : { private_key : "SelectRectangle" }
};*/
// private constructor
KortInfo.MapClass = function (instance) {
this._instance = instance;
this._navigateListenerId = null;
this._navigateListeners = new Array();
this._graphicsLayerId = 1;
this.Tools = new KortInfo.Map.ToolClass(instance);
};
KortInfo.MapClass.prototype.navigateTo = function (center, unitsPrPixel, instant) {
this._instance.private_checkReady();
this._instance.methods.kortinfo_map_navigateTo(center.getX(), center.getY(), unitsPrPixel, instant);
};
// area : KortInfo.Geometry.Rectangle2
// instance : boolean
KortInfo.MapClass.prototype.navigateToArea = function (area, instant) {
this._instance.private_checkReady();
this._instance.methods.kortinfo_map_navigateToArea(area.getMinX(), area.getMinY(), area.getMaxX(), area.getMaxY(), instant);
};
// returns KortInfo.Geometry.Rectangle2 in resultCallback
KortInfo.MapClass.prototype.getDisplayBounds = function (resultCallback) {
this._instance.private_checkReady();
this._instance.methods.kortinfo_map_getDisplayBounds(function (rv) {
resultCallback(new KortInfo.Geometry.Rectangle2(rv.minX, rv.minY, rv.maxX, rv.maxY)); // NOTE: rv er ikke af typen Rectangle2, så brug ikke getMinX()
});
};
// returns width,height in resultCallback
KortInfo.MapClass.prototype.getDisplaySize = function (resultCallback) {
this._instance.private_checkReady();
this._instance.methods.kortinfo_map_getDisplaySize(function (rv) {
resultCallback(rv.width, rv.height);
});
};
KortInfo.MapClass.prototype.refresh = function (themeLayers, backgroundLayer) {
this._instance.private_checkReady();
this._instance.methods.kortinfo_map_refresh(themeLayers, backgroundLayer);
};
// tool : Anvend værdierne fra KortInfo.MapTools
// toolListener er optional og forskellig for de forskellige tools
/*KortInfo.MapClass.prototype.setMapTool = function (tool, toolListener) {
this._instance.private_checkReady();
this.toolListener = toolListener;
this._instance.methods.kortinfo_map_setMapTool(tool.private_key);
};
KortInfo.MapClass.prototype.getMapTool = function (resultCallback) {
this._instance.private_checkReady();
throw new KortInfo.NotImplementedException();
};*/
KortInfo.MapClass.prototype.addGraphicsLayer = function () {
this._instance.private_checkReady();
var id = this._graphicsLayerId++;
this._instance.methods.kortinfo_map_addGraphicsLayer(id);
return new KortInfo.Map.GraphicsLayer.GfxLayer(this._instance, id);
};
KortInfo.MapClass.prototype.removeGraphicsLayer = function (gfxLayer) {
this._instance.private_checkReady();
var id = gfxLayer._id;
this._instance.methods.kortinfo_map_removeGraphicsLayer(id);
};
//---------------------
// Navigate Listeners
// returns (KortInfo.Geometry.Vector2 center, double unitsPrPixel) in navigateCallback every time the bounds changes
KortInfo.MapClass.prototype.addNavigateListener = function (navigateCallback) {
this._navigateListeners.push(navigateCallback);
if (this._navigateListenerId != null) return;
var listenerHandler = delegate(this, function (center, unitsPrPixel) {
this._notifyNavigateListeners(new KortInfo.Geometry.Vector2(center.x, center.y), unitsPrPixel);
});
this._navigateListenerId = this._instance._createListener(listenerHandler);
this._instance.methods.kortinfo_map_addNavigateListener(this._navigateListenerId);
};
KortInfo.MapClass.prototype.removeNavigateListener = function (navigateCallback) {
this._navigateListeners.removeItem(navigateCallback);
if (this._navigateListeners.length > 0) return;
this._instance.methods.kortinfo_map_removeNavigateListener(this._navigateListenerId);
this._navigateListenerId = null;
};
KortInfo.MapClass.prototype._notifyNavigateListeners = function (center, unitsPrPixel) {
for (var i = 0; i < this._navigateListeners.length; ++i) {
this._navigateListeners[i](center, unitsPrPixel);
}
};
//---------------------
// --- [End class KortInfo.MapClass] ------------------------------------------------------------
// --- [KortInfoApi_Map_GraphicsLayer.js] ---------------------------------
// Namespace
KortInfo.Map.GraphicsLayer = {};
// ---------
KortInfo.Map.GraphicsLayer.GfxLayer = function (instance, id) {
this._instance = instance;
this._id = id;
this._graphicsObjectId = 1;
};
KortInfo.Map.GraphicsLayer.GfxLayer.prototype.beginManipulate = function () {
this._instance.methods.kortinfo_map_graphicslayer_beginManipulate(this._id);
};
KortInfo.Map.GraphicsLayer.GfxLayer.prototype.endManipulate = function () {
this._instance.methods.kortinfo_map_graphicslayer_endManipulate(this._id);
};
// point : KortInfo.Geometry.Vector2
// symbolStyle : KortInfo.Map.GraphicsLayer.GfxCircleSymbolStyle
// return : KortInfo.Map.GraphicsLayer.GfxSymbol
KortInfo.Map.GraphicsLayer.GfxLayer.prototype.addSymbol = function (point, symbolStyle) {
var layerId = this._id;
var objectId = this._graphicsObjectId++;
this._instance.methods.kortinfo_map_graphicslayer_addSymbol(layerId, objectId, point, symbolStyle);
return new KortInfo.Map.GraphicsLayer.GfxSymbol(this._instance, objectId);
};
// polyline : KortInfo.Geometry.Polyline2
// lineStyle : KortInfo.Map.GraphicsLayer.GfxSolidLineStyle
// symbolStyle : KortInfo.Map.GraphicsLayer.GfxCircleSymbolStyle
// return : KortInfo.Map.GraphicsLayer.GfxPolyline
KortInfo.Map.GraphicsLayer.GfxLayer.prototype.addPolyline = function (polyline, lineStyle, symbolStyle) {
var layerId = this._id;
var objectId = this._graphicsObjectId++;
this._instance.methods.kortinfo_map_graphicslayer_addPolyline(layerId, objectId, polyline, lineStyle, symbolStyle);
return new KortInfo.Map.GraphicsLayer.GfxPolyline(this._instance, objectId);
};
// region : KortInfo.Geometry.Region2
// interiorStyle : KortInfo.Map.GraphicsLayer.GfxSolidInteriorStyle
// lineStyle : KortInfo.Map.GraphicsLayer.GfxSolidLineStyle
// symbolStyle : KortInfo.Map.GraphicsLayer.GfxCircleSymbolStyle
// return : KortInfo.Map.GraphicsLayer.GfxPolygon
KortInfo.Map.GraphicsLayer.GfxLayer.prototype.addPolygon = function (region, interiorStyle, lineStyle, symbolStyle) {
var layerId = this._id;
var objectId = this._graphicsObjectId++;
this._instance.methods.kortinfo_map_graphicslayer_addPolygon(layerId, objectId, region, interiorStyle, lineStyle, symbolStyle);
return new KortInfo.Map.GraphicsLayer.GfxPolygon(this._instance, objectId);
};
// gfxObject : KortInfo.Map.GraphicsLayer.GfxSymbol, KortInfo.Map.GraphicsLayer.GfxPolyline, KortInfo.Map.GraphicsLayer.GfxPolygon
KortInfo.Map.GraphicsLayer.GfxLayer.prototype.remove = function (gfxObject) {
var layerId = this._id;
var objectId = gfxObject._id;
this._instance.methods.kortinfo_map_graphicslayer_remove(layerId, objectId);
};
KortInfo.Map.GraphicsLayer.GfxLayer.prototype.clear = function () {
var layerId = this._id;
this._instance.methods.kortinfo_map_graphicslayer_clear(layerId);
};
// ---------
// class GfxColor
KortInfo.Map.GraphicsLayer.GfxColor = function (r, g, b, a) {
this._r = r;
this._g = g;
this._b = b;
this._a = a;
};
// ---------
// class KortInfo.Map.GraphicsLayer.GfxSymbol
KortInfo.Map.GraphicsLayer.GfxSymbol = function (instance, id) {
this._instance = instance;
this._id = id;
};
// style : KortInfo.Map.GraphicsLayer.GfxCircleSymbolStyle
KortInfo.Map.GraphicsLayer.GfxSymbol.prototype.setSymbolStyle = function (style) {
this._instance.methods.kortinfo_map_graphicslayer_symbol_setSymbolStyle(this._id, style);
};
// visible : boolean
KortInfo.Map.GraphicsLayer.GfxSymbol.prototype.setVisible = function (visible) {
this._instance.methods.kortinfo_map_graphicslayer_object_setVisible(this._id, visible);
};
// index : int
KortInfo.Map.GraphicsLayer.GfxSymbol.prototype.setZIndex = function (index) {
this._instance.methods.kortinfo_map_graphicslayer_object_setZIndex(this._id, index);
};
// ---------
// class KortInfo.Map.GraphicsLayer.GfxPolyline
KortInfo.Map.GraphicsLayer.GfxPolyline = function (instance, id) {
this._instance = instance;
this._id = id;
};
// style : KortInfo.Map.GraphicsLayer.GfxSolidLineStyle
KortInfo.Map.GraphicsLayer.GfxPolyline.prototype.setLineStyle = function (style) {
this._instance.methods.kortinfo_map_graphicslayer_polyline_setLineStyle(this._id, style);
};
// style : KortInfo.Map.GraphicsLayer.GfxCircleSymbolStyle
KortInfo.Map.GraphicsLayer.GfxPolyline.prototype.setSymbolStyle = function (style) {
this._instance.methods.kortinfo_map_graphicslayer_polyline_setSymbolStyle(this._id, style);
};
// visible : boolean
KortInfo.Map.GraphicsLayer.GfxPolyline.prototype.setVisible = function (visible) {
this._instance.methods.kortinfo_map_graphicslayer_object_setVisible(this._id, visible);
};
// index : int
KortInfo.Map.GraphicsLayer.GfxPolyline.prototype.setZIndex = function (index) {
this._instance.methods.kortinfo_map_graphicslayer_object_setZIndex(this._id, index);
};
// ---------
// class KortInfo.Map.GraphicsLayer.GfxPolygon
KortInfo.Map.GraphicsLayer.GfxPolygon = function (instance, id) {
this._instance = instance;
this._id = id;
};
// style : KortInfo.Map.GraphicsLayer.GfxSolidInteriorStyle
KortInfo.Map.GraphicsLayer.GfxPolygon.prototype.setInteriorStyle = function (style) {
this._instance.methods.kortinfo_map_graphicslayer_polygon_setInteriorStyle(this._id, style);
};
// style : KortInfo.Map.GraphicsLayer.GfxSolidLineStyle
KortInfo.Map.GraphicsLayer.GfxPolygon.prototype.setLineStyle = function (style) {
this._instance.methods.kortinfo_map_graphicslayer_polygon_setLineStyle(this._id, style);
};
// style : KortInfo.Map.GraphicsLayer.GfxCircleSymbolStyle
KortInfo.Map.GraphicsLayer.GfxPolygon.prototype.setSymbolStyle = function (style) {
this._instance.methods.kortinfo_map_graphicslayer_polygon_setSymbolStyle(this._id, style);
};
// visible : boolean
KortInfo.Map.GraphicsLayer.GfxPolygon.prototype.setVisible = function (visible) {
this._instance.methods.kortinfo_map_graphicslayer_object_setVisible(this._id, visible);
};
// index : int
KortInfo.Map.GraphicsLayer.GfxPolygon.prototype.setZIndex = function (index) {
this._instance.methods.kortinfo_map_graphicslayer_object_setZIndex(this._id, index);
};
// ---------
KortInfo.Map.GraphicsLayer.GfxSolidInteriorStyle = function (color) {
this._color = color;
};
// ---------
KortInfo.Map.GraphicsLayer.GfxSolidLineStyle = function (color, width) {
this._color = color;
this._width = width;
};
// ---------
KortInfo.Map.GraphicsLayer.GfxCircleSymbolStyle = function (color, radius, edgeColor, edgeWidth) {
this._color = color;
this._radius = radius;
this._edgeColor = edgeColor;
this._edgeWidth = edgeWidth;
};
// ---------
// --- [KortInfoApi_Map_Tools.js] ---------------------------------
// Namespace
KortInfo.Map.Tools = {};
// private constructor
KortInfo.Map.ToolClass = function (instance) {
this._instance = instance;
};
KortInfo.Map.ToolClass.prototype.beginPointSelection = function (valueListener, endListener) {
this._instance.private_checkReady();
var valueHandler = function (value) {
valueListener(new KortInfo.Geometry.Vector2(value.x, value.y));
};
var valueListenerId = this._instance._createListener(valueHandler);
var endHandler = delegate(this, function () {
this._instance._destroyListener(valueListenerId);
if (endListener != null) endListener();
});
var endHandlerId = this._instance._createCallback(endHandler, null);
this._instance.methods.kortinfo_map_tools_beginPointSelection(valueListenerId, endHandlerId);
};
KortInfo.Map.ToolClass.prototype.beginPolylineSelection = function (valueListener, endListener) {
this._instance.private_checkReady();
var valueHandler = function (value) {
valueListener(KortInfo.Geometry._parseGeometry(value));
};
var valueListenerId = this._instance._createListener(valueHandler);
var endHandler = delegate(this, function () {
this._instance._destroyListener(valueListenerId);
if (endListener != null) endListener();
});
var endHandlerId = this._instance._createCallback(endHandler, null);
this._instance.methods.kortinfo_map_tools_beginPolylineSelection(valueListenerId, endHandlerId);
};
KortInfo.Map.ToolClass.prototype.beginPolygonSelection = function (valueListener, endListener) {
this._instance.private_checkReady();
var valueHandler = function (value) {
valueListener(KortInfo.Geometry._parseGeometry(value));
};
var valueListenerId = this._instance._createListener(valueHandler);
var endHandler = delegate(this, function () {
this._instance._destroyListener(valueListenerId);
if (endListener != null) endListener();
});
var endHandlerId = this._instance._createCallback(endHandler, null);
this._instance.methods.kortinfo_map_tools_beginPolygonSelection(valueListenerId, endHandlerId);
};
// --- [KortInfoApi_Geometry.js] ---------------------------------
// Namespace
KortInfo.Geometry = {};
// ---[Begin class GeometryCollection2]----------------------------------------------------------------------------
// GeometryCollection2 is immutable
// geometries : Array
KortInfo.Geometry.GeometryCollection2 = function (geometries, clone) {
if (arguments.length == 1) clone = true;
this._geometries = clone ? geometries.clone() : geometries;
};
KortInfo.Geometry.GeometryCollection2.prototype.getCount = function () {
return this._geometries.length;
};
KortInfo.Geometry.GeometryCollection2.prototype.get = function (index) {
return this._geometries[index];
};
// may return null
KortInfo.Geometry.GeometryCollection2.prototype.getBounds = function () {
var bounds = KortInfo.Geometry.Rectangle2.InverseInfinity;
for (var i = 0; i < this.getCount(); i++) {
var b = this.get(i).getBounds();
if (b != null) {
bounds = bounds.combine(b);
}
}
return bounds.isValid() ? bounds : null;
};
// ---[End class GeometryCollection2]----------------------------------------------------------------------------
// ---[Begin class Vector2]----------------------------------------------------------------------------
// Vector2 is immutable
KortInfo.Geometry.Vector2 = function (x, y) {
this._x = x;
this._y = y;
};
KortInfo.Geometry.Vector2.prototype.getX = function () {
return this._x;
};
KortInfo.Geometry.Vector2.prototype.getY = function () {
return this._y;
};
KortInfo.Geometry.Vector2.prototype.getLength = function () {
return Math.sqrt(this._x * this._x + this._y * this._y);
};
KortInfo.Geometry.Vector2.prototype.distanceToSq = function (p) {
var dx = this._x - p._x;
var dy = this._y - p._y;
return dx * dx + dy * dy;
};
KortInfo.Geometry.Vector2.prototype.distanceTo = function (p) {
return Math.sqrt(this.distanceToSq(p));
};
KortInfo.Geometry.Vector2.prototype.toString = function () {
return this._x + "," + this._y;
};
KortInfo.Geometry.Vector2.prototype.getBounds = function () {
return new KortInfo.Geometry.Rectangle2(_x, _y, _x, _y);
};
// ---[End class Vector2]----------------------------------------------------------------------------
// ---[Begin class Point2]----------------------------------------------------------------------------
// Point2 is immutable
KortInfo.Geometry.Point2 = function (x, y) {
this._x = x;
this._y = y;
};
KortInfo.Geometry.Point2.prototype.getX = function () {
return this._x;
};
KortInfo.Geometry.Point2.prototype.getY = function () {
return this._y;
};
KortInfo.Geometry.Point2.prototype.getPosition = function () {
return new KortInfo.Geometry.Vector2(this._x, this._y);
};
KortInfo.Geometry.Point2.prototype.getBounds = function () {
return new KortInfo.Geometry.Rectangle2(_x, _y, _x, _y);
};
// ---[End class Point2]----------------------------------------------------------------------------
// ---[Begin class Rectangle2]----------------------------------------------------------------------------
// Rectangle2 is immutable
KortInfo.Geometry.Rectangle2 = function (minX, minY, maxX, maxY) {
this._minX = minX;
this._minY = minY;
this._maxX = maxX;
this._maxY = maxY;
};
KortInfo.Geometry.Rectangle2.InverseInfinity = new KortInfo.Geometry.Rectangle2(Infinity,Infinity,-Infinity,-Infinity);
KortInfo.Geometry.Rectangle2.prototype.toString = function () {
return this._minX + "," + this._minY + "," + this._maxX + "," + this._maxY;
};
KortInfo.Geometry.Rectangle2.prototype.getMinX = function () {
return this._minX;
};
KortInfo.Geometry.Rectangle2.prototype.getMinY = function () {
return this._minY;
};
KortInfo.Geometry.Rectangle2.prototype.getMaxX = function () {
return this._maxX;
};
KortInfo.Geometry.Rectangle2.prototype.getMaxY = function () {
return this._maxY;
};
KortInfo.Geometry.Rectangle2.prototype.isValid = function () {
return this._minX <= this._maxX && this._minY <= this._maxY;
};
KortInfo.Geometry.Rectangle2.prototype.combine = function (rect) {
var minX = Math.min(this._minX, rect._minX);
var minY = Math.min(this._minY, rect._minY);
var maxX = Math.max(this._maxX, rect._maxX);
var maxY = Math.max(this._maxY, rect._maxY);
return new KortInfo.Geometry.Rectangle2(minX, minY, maxX, maxY);
};
KortInfo.Geometry.Rectangle2.prototype.getBounds = function () {
return this;
};
// ---[End class Rectangle2]----------------------------------------------------------------------------
// ---[Begin class Ring2]----------------------------------------------------------------------------
// Ring2 is immutable
// points : Array
KortInfo.Geometry.Ring2 = function (points, clonePoints) {
if (arguments.length == 1) clonePoints = true;
this._points = clonePoints ? points.clone() : points;
};
KortInfo.Geometry.Ring2.prototype.getPointCount = function () {
return this._points.length;
};
KortInfo.Geometry.Ring2.prototype.getPoint = function (index) {
return this._points[index];
};
KortInfo.Geometry.Ring2.prototype.toRegion = function () {
return new KortInfo.Geometry.Region2(this, new Array());
};
KortInfo.Geometry.Ring2.prototype.getBounds = function () {
var minX = Infinity;
var minY = Infinity;
var maxX = -Infinity;
var maxY = -Infinity;
var count = this.getPointCount();
if (count == 0) return null;
for (var i = 0; i < this.getPointCount(); i++) {
var p = this.getPoint(i);
minX = Math.min(minX, p.getX());
minY = Math.min(minY, p.getY());
maxX = Math.max(maxX, p.getX());
maxY = Math.max(maxY, p.getY());
}
return new KortInfo.Geometry.Rectangle2(minX, minY, maxX, maxY);
};
// ---[End class Ring2]----------------------------------------------------------------------------
// ---[Begin class Polyline2]----------------------------------------------------------------------------
// Polyline2 is immutable
// points : Array
KortInfo.Geometry.Polyline2 = function (points, clonePoints) {
if (arguments.length == 1) clonePoints = true;
this._points = clonePoints ? points.clone() : points;
};
KortInfo.Geometry.Polyline2.prototype.getPointCount = function () {
return this._points.length;
};
KortInfo.Geometry.Polyline2.prototype.getPoint = function (index) {
return this._points[index];
};
KortInfo.Geometry.Polyline2.prototype.getBounds = function () {
var minX = Infinity;
var minY = Infinity;
var maxX = -Infinity;
var maxY = -Infinity;
var count = this.getPointCount();
if (count == 0) return null;
for (var i = 0; i < this.getPointCount(); i++) {
var p = this.getPoint(i);
minX = Math.min(minX, p.getX());
minY = Math.min(minY, p.getY());
maxX = Math.max(maxX, p.getX());
maxY = Math.max(maxY, p.getY());
}
return new KortInfo.Geometry.Rectangle2(minX, minY, maxX, maxY);
};
// ---[End class Ring2]----------------------------------------------------------------------------
// ---[Begin class Region2]----------------------------------------------------------------------------
// shell : Ring2
// holes : Array
KortInfo.Geometry.Region2 = function (shell, holes, cloneHoles) {
if (arguments.length <= 2) cloneHoles = true;
this._shell = shell;
if (holes != null) this._holes = cloneHoles ? holes.clone() : holes;
else this._holes = [];
};
KortInfo.Geometry.Region2.prototype.getShell = function () {
return this._shell;
};
KortInfo.Geometry.Region2.prototype.getHoleCount = function () {
return this._holes.length;
};
KortInfo.Geometry.Region2.prototype.getHole = function (index) {
return this._holes[index];
};
KortInfo.Geometry.Region2.prototype.getBounds = function () {
return this._shell.getBounds();
};
// ---[End class Region2]----------------------------------------------------------------------------
KortInfo.Geometry.Tools = {};
// returns Array
KortInfo.Geometry.Tools.getPrimitives = function (geometry) {
var arr = new Array();
if (geometry != null) {
if (geometry instanceof KortInfo.Geometry.GeometryCollection2) {
for (var i = 0; i < geometry.getCount(); i++) {
var arr2 = KortInfo.Geometry.Tools.getPrimitives(geometry.get(i));
for (var j = 0; j < arr2.length; j++) {
arr.push(arr2[j]);
}
}
} else {
arr.push(geometry);
}
}
return arr;
};
// ----------------------------------------------------------------------------------------
// private methods
KortInfo.Geometry._parseVector2 = function (obj) {
return new KortInfo.Geometry.Vector2(obj.x, obj.y);
};
KortInfo.Geometry._parseArrayOf = function (obj, parseFunc) {
var arr = new Array();
arr.length = obj.length;
for (var i = 0; i < obj.length; i++) {
arr[i] = parseFunc(obj[i]);
}
return arr;
};
KortInfo.Geometry._parseVector2Array = function (obj) {
return KortInfo.Geometry._parseArrayOf(obj, KortInfo.Geometry._parseVector2);
};
KortInfo.Geometry._parseRing2 = function (obj) {
var points = KortInfo.Geometry._parseVector2Array(obj);
return new KortInfo.Geometry.Ring2(points,false);
};
// Konverterer objekter fra GWT klienten til JavaScript API objekter
KortInfo.Geometry._parseGeometry = function (obj) {
if (obj == null) return null;
if (obj.type == "Point2") {
return new KortInfo.Geometry.Point2(obj.x, obj.y);
} else if (obj.type == "Polyline2") {
return new KortInfo.Geometry.Polyline2(KortInfo.Geometry._parseVector2Array(obj.points));
} else if (obj.type == "Region2") {
var shell = KortInfo.Geometry._parseRing2(obj.shell);
var holes = KortInfo.Geometry._parseArrayOf(obj.holes, KortInfo.Geometry._parseRing2);
return new KortInfo.Geometry.Region2(shell, holes);
} else if (obj.type == "GeometryCollection2") {
var arr = KortInfo.Geometry._parseArrayOf(obj.objects, KortInfo.Geometry._parseGeometry);
return new KortInfo.Geometry.GeometryCollection2(arr, false);
}
};
// --- [KortInfoApi_Ogc_Wkt.js] ---------------------------------
KortInfo.Tools.createNamespace('KortInfo.Ogc.Wkt');
KortInfo.Ogc.Wkt.fromGeometry = function (geometry) {
if (geometry instanceof KortInfo.Geometry.Point2) return KortInfo.Ogc.Wkt._fromGeometry_Point2(geometry);
if (geometry instanceof KortInfo.Geometry.Polyline2) return KortInfo.Ogc.Wkt._fromGeometry_Polyline2(geometry);
if (geometry instanceof KortInfo.Geometry.Region2) return KortInfo.Ogc.Wkt._fromGeometry_Region2(geometry);
if (geometry instanceof KortInfo.Geometry.GeometryCollection2) return KortInfo.Ogc.Wkt._fromGeometry_Polyline2(geometry);
throw new KortInfo.ArgumentException('Unknown geometry type');
};
KortInfo.Ogc.Wkt._fromGeometry_Point2 = function (geometry) {
return 'POINT(' + geometry.getX() + ' ' + geometry.getY() + ' )';
};
KortInfo.Ogc.Wkt._fromGeometry_Polyline2 = function (geometry) {
return 'LINESTRING(' + KortInfo.Ogc.Wkt._fromGeometry_Coordinates(geometry) + ')';
};
KortInfo.Ogc.Wkt._fromGeometry_Region2 = function (geometry) {
var subStrings = new Array();
subStrings.push('POLYGON(');
subStrings.push('(' + KortInfo.Ogc.Wkt._fromGeometry_Coordinates(geometry.getShell()) + ')');
for (var i = 0; i < geometry.getHoleCount; ++i) {
subStrings.push(',(' + KortInfo.Ogc.Wkt._fromGeometry_Coordinates(geometry.getHole(i)) + ')');
}
subStrings.push(")");
return subStrings.join('');
};
KortInfo.Ogc.Wkt._fromGeometry_GeometryCollection = function (geometry) {
var subStrings = new Array();
subStrings.push('GEOMETRYCOLLECTION(');
for (var i = 0; i < geometry.getCount(); ++i) {
if (i > 0) subStrings.push(",");
subStrings.Append(KortInfo.Ogc.Wkt.fromGeometry(geometry.get(i)));
}
subStrings.Append(")");
};
KortInfo.Ogc.Wkt._fromGeometry_Coordinates = function (coordinates) {
var subStrings = new Array();
var coordinate = null;
for (var i = 0; i < coordinates.getPointCount(); ++i) {
if (coordinate != null) subStrings.push(',');
coordinate = coordinates.getPoint(i);
subStrings.push(coordinate.getX() + ' ' + coordinate.getY());
}
if (coordinates instanceof KortInfo.Geometry.Ring2 && coordinates.getPointCount() > 0) {
coordinate = coordinates.getPoint(0);
subStrings.push(',' + coordinate.getX() + ' ' + coordinate.getY());
}
return subStrings.join('');
};
KortInfo.Ogc.Wkt.Parser = function (wkt) {
this._wkt = wkt;
this._index = 0;
var types = new Array();
types.push({ identifier: 'POINT', func: delegate(this, this._parseType_Point) });
types.push({ identifier: 'LINESTRING', func: delegate(this, this._parseType_LineString) });
types.push({ identifier: 'POLYGON', func: delegate(this, this._parseType_Polygon) });
types.push({ identifier: 'MULTIPOINT', func: delegate(this, this._parseType_MultiPoint) });
types.push({ identifier: 'MULTILINESTRING', func: delegate(this, this._parseType_MultiLineString) });
types.push({ identifier: 'MULTIPOLYGON', func: delegate(this, this._parseType_MultiPolygon) });
types.push({ identifier: 'GEOMETRYCOLLECTION', func: delegate(this, this._parseType_GeometryCollection) });
this._types = types;
};
KortInfo.Ogc.Wkt.Parser.prototype.parse = function () {
if (this._wkt == null || this._wkt.length == 0) throw new KortInfo.ArgumentException('Invalid WKT string');
return this._parseType();
};
KortInfo.Ogc.Wkt.Parser.prototype._parseType = function () {
this._skipWhitespace();
var type = null;
for (var i = 0; i < this._types.length; ++i) {
var t = this._types[i];
var identifier = t.identifier;
if (this._wkt.slice(this._index, this._index + identifier.length) == identifier) {
type = t;
break;
}
}
if (type == null) throw new KortInfo.ArgumentException('Invalid WKT string');
this._index += type.identifier.length;
this._skipWhitespace();
return type.func();
};
KortInfo.Ogc.Wkt.Parser.prototype._parseType_Point = function () {
var container = this._isContainerBegin();
if (container) this._skipContainer();
var point = this._parseCoordinate();
if (container) this._skipContainer();
return point;
};
KortInfo.Ogc.Wkt.Parser.prototype._parseType_LineString = function () {
var points = this._parseElementList(delegate(this, function () { return this._parseCoordinate(); }));
return new KortInfo.Geometry.Polyline2(points, false);
};
KortInfo.Ogc.Wkt.Parser.prototype._parseType_Polygon = function () {
var rings = this._parseElementList(delegate(this, function () { return this._parseRing(); }));
var shell = rings[0];
rings.splice(0, 1);
var holes = rings;
return new KortInfo.Geometry.Region2(shell, holes, false);
};
KortInfo.Ogc.Wkt.Parser.prototype._parseType_MultiPoint = function () {
var points = this._parseElementList(delegate(this, function () { return this._parseType_Point(); }));
return new KortInfo.Geometry.GeometryCollection2(points, false);
};
KortInfo.Ogc.Wkt.Parser.prototype._parseType_MultiLineString = function () {
var lineStrings = this._parseElementList(delegate(this, function () { return this._parseType_LineString(); }));
return new KortInfo.Geometry.GeometryCollection2(lineStrings, false);
};
KortInfo.Ogc.Wkt.Parser.prototype._parseType_MultiPolygon = function () {
var polygons = this._parseElementList(delegate(this, function () { return this._parseType_Polygon(); }));
return new KortInfo.Geometry.GeometryCollection2(polygons, false);
};
KortInfo.Ogc.Wkt.Parser.prototype._parseType_GeometryCollection = function () {
var geometries = this._parseElementList(delegate(this, function () { return this._parseType(); }));
return new KortInfo.Geometry.GeometryCollection2(geometries, false);
};
KortInfo.Ogc.Wkt.Parser.prototype._parseElementList = function (elementFunc) {
this._skipContainer();
var elements = new Array();
while (!this._isContainerEnd()) {
if (elements.length != 0) this._skipSeperator();
elements.push(elementFunc());
}
this._skipContainer();
return elements;
};
KortInfo.Ogc.Wkt.Parser.prototype._parseCoordinate = function () {
var x = parseFloat(this._wkt.substring(this._index));
var y = parseFloat(this._wkt.substring(this._wkt.indexOf(' ', this._index)));
while (!this._isSeperator() && !this._isContainer()) ++this._index;
return new KortInfo.Geometry.Vector2(x, y);
};
KortInfo.Ogc.Wkt.Parser.prototype._parseRing = function () {
var points = this._parseElementList(delegate(this, function () { return this._parseCoordinate(); }));
points.pop();
return new KortInfo.Geometry.Ring2(points, false);
};
KortInfo.Ogc.Wkt.Parser.prototype._skipWhitespace = function () {
while (this._wkt.charAt(this._index) == ' ') ++this._index;
};
KortInfo.Ogc.Wkt.Parser.prototype._isSeperator = function () {
var c = this._wkt.charAt(this._index);
return c == ',';
};
KortInfo.Ogc.Wkt.Parser.prototype._skipSeperator = function () {
this._skipWhitespace();
var c = this._wkt.charAt(this._index);
if (c != ',') throw new KortInfo.ArgumentException('Invalid WKT string');
++this._index;
this._skipWhitespace();
};
KortInfo.Ogc.Wkt.Parser.prototype._isContainer = function () {
var c = this._wkt.charAt(this._index);
return c == '(' || c == ')';
};
KortInfo.Ogc.Wkt.Parser.prototype._isContainerBegin = function () {
var c = this._wkt.charAt(this._index);
return c == '(';
};
KortInfo.Ogc.Wkt.Parser.prototype._isContainerEnd = function () {
var c = this._wkt.charAt(this._index);
return c == ')';
};
KortInfo.Ogc.Wkt.Parser.prototype._skipContainer = function () {
this._skipWhitespace();
var c = this._wkt.charAt(this._index);
if (c != '(' && c != ')') throw new KortInfo.ArgumentException('Invalid WKT string');
++this._index;
this._skipWhitespace();
};
// --- [KortInfoApi_Features.js] ---------------------------------
KortInfo.Features = {};
KortInfo.Features.FeatureCollection = function (features, columns) {
this._features = features;
this._columns = columns;
};
KortInfo.Features.FeatureCollection.prototype.getFeatureCount = function () {
return this._features.length;
};
KortInfo.Features.FeatureCollection.prototype.getFeature = function (index) {
return this._features[index];
};
KortInfo.Features.FeatureCollection.prototype.getColumnCount = function () {
return this._columns.length;
};
KortInfo.Features.FeatureCollection.prototype.getColumn = function (index) {
return this._columns[index];
};
KortInfo.Features.FeatureCollection.prototype.getColumnIndex = function (columnName) {
columnName = columnName.toLowerCase();
for(var i=0;i