Skip to content

Instantly share code, notes, and snippets.

@juntalis
Created September 27, 2012 20:31
Show Gist options
  • Save juntalis/3796295 to your computer and use it in GitHub Desktop.
Save juntalis/3796295 to your computer and use it in GitHub Desktop.
// ==ClosureCompiler==
// @output_file_name vos365.sp.js
// @compilation_level SIMPLE_OPTIMIZATIONS
// ==/ClosureCompiler==
(function(global, doc, handler) {
/* Utility one-liners for checking types, values, etc */
var prims = ['string', 'number', 'boolean', 'function', 'array'],
// Type checks
typof = function(x) { var s, t = typeof (x); return t === 'object' ? (s = Object.prototype.toString.call(x)).substring(8, s.length - 1).toLowerCase() : t; },
undef = function(x) { return typeof (x) === 'undefined' || x == undefined; },
defined = function(x) { return !undef(x); },
/* Simpler checks are prefixed with an S before the type. */
isStr = function(x) { return typof(x) === prims[0]; },
isSStr = function(x) { return typeof (x) === prims[0]; },
isNum = function(x) { return typof(x) === prims[1]; },
isSNum = function(x) { return typeof (x) === prims[1]; },
isBool = function(x) { return typof(x) === prims[2]; },
isSBool = function(x) { return typeof (x) === prims[2]; },
isFunc = function(x) { return typof(x) === prims[3]; },
isSFunc = function(x) { return typeof (x) === prims[3]; },
isArr = function(x) { return typof(x) === prims[4]; },
isObj = function(x) { return prims.indexOf(typof(x)) === -1; },
isSObj = function(x) { return typeof (x) === 'object'; },
// Value checks - Case insensitive variations are prefixed with an i.
noVal = function(x) { return undef(x) || typof(x) === 'null' || x == null || isNaN(x); },
hasVal = function(x) { return !noVal(x); },
empty = function(x) { return !isStr(x) || x.length === 0; },
istrcmp = function(x, y) { return !empty(x) && !empty(y) && (x.toLowerCase() === y.toLowerCase()); },
contains = function(x, y) { return !empty(x) && !empty(y) && x.indexOf(y) !== -1; },
icontains = function(x, y) { return !empty(x) && !empty(y) && x.toLowerCase().indexOf(y.toLowerCase()) !== -1; },
// Func Utils
fcaller = function(a) { return a.callee.caller; },
fthis = function(a) { return a.callee; },
timeout = global.setTimeout,
jsmin,
initCompat = function() {
/* region: JSON2 */
if(undef(global['JSON'])) {
(function(JSON) {
function f(n) { return n < 10 ? '0' + n : n; }
if(!isSFunc(Date.prototype.toJSON)) {
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 = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, rep; function quote(string) { 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) {
var i, k, v, length, mind = gap, partial, value = holder[key]; if(value && isSObj(value) && isSFunc(value.toJSON)) value = value.toJSON(key);
if(typeof rep === 'function') value = rep.call(holder, key, value);
switch(typeof value) {
case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if(!value) return 'null';
gap += indent; partial = []; if(isArr(value)) {
length = value.length; for(i = 0; i < length; i += 1) partial[i] = str(i, value) || 'null';
v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v;
}
if(rep && typeof rep === 'object') { length = rep.length; for(i = 0; i < length; i += 1) { if(isSStr(rep[i])) { k = rep[i]; v = str(k, value); if(v) partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } else { for(k in value) { if(Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if(v) partial.push(quote(k) + (gap ? ': ' : ':') + v); } } }
v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v;
}
return "";
}
if(!isSFunc(JSON.stringify)) {
JSON.stringify = function(value, replacer, space) {
var i; gap = ''; indent = ''; if(isSNum(space)) { for(i = 0; i < space; i += 1) { indent += ' '; } } else if(isSStr(space)) { indent = space; }
rep = replacer; if(replacer && !isSFunc(replacer) && (!isSObj(replacer) || !isSNum(replacer.length))) { throw new Error('JSON.stringify'); }
return str('', { '': value });
};
}
if(!isSFunc(JSON.parse)) {
JSON.parse = function(text, reviver) {
var j; function walk(holder, key) {
var k, v, value = holder[key]; if(value && typeof value === 'object') { for(k in value) { if(Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if(v !== undefined) { value[k] = v; } else { delete value[k]; } } } }
return reviver.call(holder, key, value);
}
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);
});
}
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, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({ '': j }, '') : j; }
throw new SyntaxError('JSON.parse');
};
}
})(global.JSON = {});
}
/* endregion: JSON2 */
/* Region: Store.js */
/* Copyright (c) 2010-2012 Marcus Westin */
(function() {
var store = {},
localStorageName = 'localStorage',
globalStorageName = 'globalStorage',
namespace = '__storejs__',
storage;
store.disabled = false;
store.set = function(key, value) { };
store.get = function(key) { };
store.remove = function(key) { };
store.clear = function() { };
store.transact = function(key, defaultVal, transactionFn) {
var val = store.get(key);
if(transactionFn == null) {
transactionFn = defaultVal;
defaultVal = null;
}
if(typeof val === 'undefined') {
val = defaultVal || {};
}
transactionFn(val);
store.set(key, val);
};
store.getAll = function() { };
store.serialize = function(value) {
return JSON.stringify(value);
};
store.deserialize = function(value) {
if(typeof value !== 'string') {
return undefined;
}
try {
return JSON.parse(value);
} catch(err) {
return value || undefined;
}
};
// Functions to encapsulate questionable FireFox 3.6.13 behavior
// when about.config::dom.storage.enabled === false
// See https://github.com/marcuswestin/store.js/issues#issue/13
function isLocalStorageNameSupported() {
try {
return (localStorageName in global && global[localStorageName]);
} catch(err) {
return false;
}
}
function isGlobalStorageNameSupported() {
try {
return (globalStorageName in global && global[globalStorageName] && global[globalStorageName][global.location.hostname]);
} catch(err) {
return false;
}
}
if(isLocalStorageNameSupported()) {
storage = global[localStorageName];
store.set = function(key, val) {
if(val === undefined) { return store.remove(key); }
storage.setItem(key, store.serialize(val));
return val;
};
store.get = function(key) {
return store.deserialize(storage.getItem(key));
};
store.remove = function(key) {
storage.removeItem(key);
};
store.clear = function() {
storage.clear();
};
store.getAll = function() {
var ret = {};
for(var i = 0; i < storage.length; ++i) {
var key = storage.key(i);
ret[key] = store.get(key);
}
return ret;
};
} else if(isGlobalStorageNameSupported()) {
storage = global[globalStorageName][global.location.hostname];
store.set = function(key, val) {
if(val === undefined) { return store.remove(key); }
storage[key] = store.serialize(val);
return val;
};
store.get = function(key) {
return store.deserialize(storage[key] && storage[key].value);
};
store.remove = function(key) {
delete storage[key];
};
store.clear = function() {
for(var key in storage) {
delete storage[key];
}
};
store.getAll = function() {
var ret = {};
for(var i = 0; i < storage.length; ++i) {
var key = storage.key(i);
ret[key] = store.get(key);
}
return ret;
};
} else if(doc.documentElement.addBehavior) {
var storageOwner,
storageContainer;
// Since #userData storage applies only to specific paths, we need to
// somehow link our data to a specific path. We choose /favicon.ico
// as a pretty safe option, since all browsers already make a request to
// this URL anyway and being a 404 will not hurt us here. We wrap an
// iframe pointing to the favicon in an ActiveXObject(htmlfile) object
// (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx)
// since the iframe access rules appear to allow direct access and
// manipulation of the document element, even for a 404 page. This
// document can be used instead of the current document (which would
// have been limited to the current path) to perform #userData storage.
try {
storageContainer = new ActiveXObject('htmlfile');
storageContainer.open();
storageContainer.write('<s' + 'cript>document.w=window</s' + 'cript><iframe src="/favicon.ico"></frame>');
storageContainer.close();
storageOwner = storageContainer.w.frames[0].document;
storage = storageOwner.createElement('div');
} catch(e) {
// somehow ActiveXObject instantiation failed (perhaps some special
// security settings or otherwse), fall back to per-path storage
storage = doc.createElement('div');
storageOwner = doc.body;
}
function withIEStorage(storeFunction) {
return function() {
var args = Array.prototype.slice.call(arguments, 0);
args.unshift(storage);
// See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx
// and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx
storageOwner.appendChild(storage);
storage.addBehavior('#default#userData');
storage.load(localStorageName);
var result = storeFunction.apply(store, args);
storageOwner.removeChild(storage);
return result;
};
}
// In IE7, keys may not contain special chars. See all of https://github.com/marcuswestin/store.js/issues/40
var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g");
function ieKeyFix(key) {
return key.replace(forbiddenCharsRegex, '___');
}
store.set = withIEStorage(function(lstorage, key, val) {
key = ieKeyFix(key);
if(val === undefined) { return store.remove(key); }
lstorage.setAttribute(key, store.serialize(val));
lstorage.save(localStorageName);
return val;
});
store.get = withIEStorage(function(lstorage, key) {
key = ieKeyFix(key);
return store.deserialize(lstorage.getAttribute(key));
});
store.remove = withIEStorage(function(lstorage, key) {
key = ieKeyFix(key);
lstorage.removeAttribute(key);
lstorage.save(localStorageName);
});
store.clear = withIEStorage(function(lstorage) {
var attributes = lstorage.XMLDocument.documentElement.attributes;
lstorage.load(localStorageName);
for(var i = 0, attr; attr = attributes[i]; i++) {
lstorage.removeAttribute(attr.name);
}
lstorage.save(localStorageName);
});
store.getAll = withIEStorage(function(lstorage) {
var attributes = lstorage.XMLDocument.documentElement.attributes,
ret = {};
lstorage.load(localStorageName);
for(var i = 0, attr; attr = attributes[i]; ++i) {
ret[attr] = store.get(attr);
}
return ret;
});
}
try {
store.set(namespace, namespace);
if(store.get(namespace) != namespace) {
store.disabled = true;
}
store.remove(namespace);
} catch(e) {
store.disabled = true;
}
store.enabled = !store.disabled;
global.store = store;
})();
/* endregion: Store.js */
/* region: jsmin - declared only if localStorage is usable. */
if(store.enabled && VOS.browser.isIE && VOS.browser.version <= 7) {
(function() {
// ReSharper disable StatementIsNotTerminated
// ReSharper disable DuplicatingLocalDeclaration
// ReSharper disable AssignToImplicitGlobalInFunctionScope
String.prototype.has=function(f){return-1<this.indexOf(f)};
jsmin=function(f,i,g){function j(a){return a!=h&&(p.has(a)||126<a.charCodeAt(0))}function e(){var a=k;if(l==q)return h;k=h;a==h&&(a=i.charAt(l++));return" "<=a||"\n"==a?a:"\r"==a?"\n":" "}function m(){return k=e()}function n(){var a=e();if("/"==a)switch(m()){case "/":for(;;)if(a=e(),"\n">=a)return a;break;case "*":for(e();;)switch(e()){case "*":if("/"==m())return e()," ";break;case h:throw"Error: Unterminated comment.";}}return a}function b(c){var b=[];1==c&&b.push(a);if(3>c&&(a=d,"'"==a||'"'==
a))for(;;){b.push(a);a=e();if(a==d)break;if("\n">=a)throw"Error: unterminated string literal: "+a;"\\"==a&&(b.push(a),a=e())}d=n();if("/"==d&&"(,=:[!&|".has(a)){b.push(a);for(b.push(d);;){a=e();if("/"==a)break;else if("\\"==a)b.push(a),a=e();else if("\n">=a)throw"Error: unterminated Regular Expression literal";b.push(a)}d=n()}return b.join("")}if(void 0===i)i=f,f="",g=2;else if(void 0===g||1>g||3<g)g=2;0<f.length&&(f+="\n");var a="",d="",h=-1,p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_$\\",
k=h,l=0,q=i.length;jsmin.oldSize=i.length;var c=[],a="\n";for(c.push(b(3));a!=h;)switch(a){case " ":j(d)?c.push(b(1)):c.push(b(2));break;case "\n":switch(d){case "{":case "[":case "(":case "+":case "-":c.push(b(1));break;case " ":c.push(b(3));break;default:j(d)?c.push(b(1)):1==g&&"\n"!=d?c.push(b(1)):c.push(b(2))}break;default:switch(d){case " ":if(j(a)){c.push(b(1));break}c.push(b(3));break;case "\n":if(1==g&&"\n"!=a)c.push(b(1));else switch(a){case "}":case "]":case ")":case "+":case "-":case '"':case "'":3==
g?c.push(b(3)):c.push(b(1));break;default:j(a)?c.push(b(1)):c.push(b(3))}break;default:c.push(b(1))}}ret=c.join("");jsmin.newSize=ret.length;return f+ret};
// ReSharper restore AssignToImplicitGlobalInFunctionScope
// ReSharper restore DuplicatingLocalDeclaration
// ReSharper restore StatementIsNotTerminated
})();
}
/* Region: Requwest */
global.vos.ajax = global.VOS.ajax = (function() {
var twoHundo = /^20\d$/,
byTag = 'getElementsByTagName',
readyState = 'readyState',
contentType = 'Content-Type',
requestedWith = 'X-Requested-With',
uniqid = 0,
lastValue // data stored by the most recent JSONP callback
,
xmlHttpRequest = 'XMLHttpRequest',
isArray = typeof Array.isArray == 'function' ? Array.isArray : function (a) {
return a instanceof Array;
},
defaultHeaders = {
contentType: 'application/x-www-form-urlencoded',
accept: {
'*': 'text/javascript, text/html, application/xml, text/xml, */*',
xml: 'application/xml, text/xml',
html: 'text/html',
text: 'text/plain',
json: 'application/json, text/javascript',
js: 'application/javascript, text/javascript'
},
requestedWith: xmlHttpRequest
},
xhr = global[xmlHttpRequest] ? function () {
return new XMLHttpRequest();
} : function () {
return new ActiveXObject('Microsoft.XMLHTTP');
};
function handleReadyState(o, success, error) {
return function () {
if (o && o[readyState] == 4) {
if (twoHundo.test(o.status)) success(o); else error(o);
}
};
}
function setHeaders(http, o) {
var headers = o.headers || {}, h;
headers.Accept = headers.Accept || defaultHeaders.accept[o.type] || defaultHeaders.accept['*'];
// breaks cross-origin requests with legacy browsers
if (!o.crossOrigin && !headers[requestedWith]) headers[requestedWith] = defaultHeaders.requestedWith;
if (!headers[contentType]) headers[contentType] = o.contentType || defaultHeaders.contentType;
for (h in headers) headers.hasOwnProperty(h) && http.setRequestHeader(h, headers[h]);
}
function generalCallback(data) {
lastValue = data;
}
function urlappend(url, s) {
return url + (/\?/.test(url) ? '&' : '?') + s;
}
function handleJsonp(o, fn, err, url) {
var reqId = uniqid++,
cbkey = o.jsonpCallback || 'callback' // the 'callback' key
,
cbval = o.jsonpCallbackName || ('ajax_' + reqId) // the 'callback' value
,
cbreg = new RegExp('((^|\\?|&)' + cbkey + ')=([^&]+)'),
match = url.match(cbreg),
script = doc.createElement('script'),
loaded = 0;
if (match) {
if (match[3] === '?') url = url.replace(cbreg, '$1=' + cbval); // wildcard callback func name else cbval = match[3]; // provided callback func name
} else url = urlappend(url, cbkey + '=' + cbval); // no callback details, add 'em
global[cbval] = generalCallback;
script.type = 'text/javascript';
script.src = url;
script.async = true;
if (typeof script.onreadystatechange !== 'undefined') {
// need this for IE due to out-of-order onreadystatechange(), binding script
// execution to an event listener gives us control over when the script
// is executed. See http://jaubourg.net/2010/07/loading-script-as-onclick-handler-of.html
script.event = 'onclick';
script.htmlFor = script.id = '_ajax_' + reqId;
}
script.onload = script.onreadystatechange = function () {
if ((script[readyState] && script[readyState] !== 'complete' && script[readyState] !== 'loaded') || loaded) {return false;}
script.onload = script.onreadystatechange = null;
script.onclick && script.onclick();
// Call the user callback with the last value stored and clean up values and scripts.
o.success && o.success(lastValue);
lastValue = undefined;
head.removeChild(script);
loaded = 1;
return undefined;
};
// Add the script to the DOM head
head.appendChild(script);
}
function getRequest(o, fn, err) {
var method = (o.method || 'GET').toUpperCase(),
url = typeof o === 'string' ? o : o.url,
// convert non-string objects to query-string form unless o.processData is false
data = (o.processData !== false && o.data && typeof o.data !== 'string') ? reqwest.toQueryString(o.data) : (o.data || null),
http;
// if we're working on a GET request and we have data then we should append
// query string to end of URL and not post data
if ((o.type == 'jsonp' || method == 'GET') && data) {
url = urlappend(url, data);
data = null;
}
if (o.type == 'jsonp') return handleJsonp(o, fn, err, url);
http = xhr();
http.open(method, url, true);
setHeaders(http, o);
http.onreadystatechange = handleReadyState(http, fn, err);
o.before && o.before(http);
http.send(data);
return http;
}
function Reqwest(o, fn) {
this.o = o;
this.fn = fn;
init.apply(this, arguments);
}
function setType(url) {
var m = url.match(/\.(json|jsonp|html|xml)(\?|$)/);
return m ? m[1] : 'js';
}
function init(o, fn) {
this.url = typeof o == 'string' ? o : o.url;
this.timeout = null;
var type = o.type || setType(this.url),
self = this;
fn = fn || function () {};
if (o.timeout) {
this.timeout = setTimeout(function () {
self.abort();
}, o.timeout);
}
function complete(resp) {
o.timeout && clearTimeout(self.timeout);
self.timeout = null;
o.complete && o.complete(resp);
}
function success(resp) {
var r = resp.responseText;
if (r) {
switch (type) {
case 'json':
try {
resp = global.JSON ? global.JSON.parse(r) : eval('(' + r + ')');
} catch (err) {
return error(resp, 'Could not parse JSON in response', err);
}
break;
case 'js':
resp = eval(r);
break;
case 'html':
resp = r;
break;
}
}
fn(resp);
o.success && o.success(resp);
complete(resp);
return undefined;
}
function error(resp, msg, t) {
o.error && o.error(resp, msg, t);
complete(resp);
}
this.request = getRequest(o, success, error);
}
Reqwest.prototype = {
abort: function() {
this.request.abort();
},
retry: function() {
init.call(this, this.o, this.fn);
}
};
function reqwest(o, fn) {
return new Reqwest(o, fn);
}
// normalize newline variants according to spec -> CRLF
function normalize(s) {
return s ? s.replace(/\r?\n/g, '\r\n') : '';
}
function serial(el, cb) {
var n = el.name,
t = el.tagName.toLowerCase(),
optCb = function (o) {
// IE gives value="" even where there is no value attribute
// 'specified' ref: http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-862529273
if (o && !o.disabled) cb(n, normalize(o.attributes.value && o.attributes.value.specified ? o.value : o.text));
};
// don't serialize elements that are disabled or without a name
if (el.disabled || !n) return;
switch (t) {
case 'input':
if (!/reset|button|image|file/i.test(el.type)) {
var ch = /checkbox/i.test(el.type),
ra = /radio/i.test(el.type),
val = el.value;
// WebKit gives us "" instead of "on" if a checkbox has no value, so correct it here
(!(ch || ra) || el.checked) && cb(n, normalize(ch && val === '' ? 'on' : val));
}
break;
case 'textarea':
cb(n, normalize(el.value));
break;
case 'select':
if (el.type.toLowerCase() === 'select-one') optCb(el.selectedIndex >= 0 ? el.options[el.selectedIndex] : null); else {
for (var i = 0; el.length && i < el.length; i++) el.options[i].selected && optCb(el.options[i]);
}
break;
}
}
// collect up all form elements found from the passed argument elements all
// the way down to child elements; pass a '<form>' or form fields.
// called with 'this'=callback to use for serial() on each element
function eachFormElement() {
var cb = this,
e,
i,
j,
serializeSubtags = function (el, tags) {
for (var ic = 0; ic < tags.length; ic++) {
var fa = el[byTag](tags[ic]);
for (j = 0; j < fa.length; j++) { serial(fa[j], cb); }
}
};
for (i = 0; i < arguments.length; i++) {
e = arguments[i];
if (/input|select|textarea/i.test(e.tagName)) { serial(e, cb); }
serializeSubtags(e, ['input', 'select', 'textarea']);
}
}
// standard query string style serialization
function serializeQueryString() {
return reqwest.toQueryString(reqwest.serializeArray.apply(null, arguments));
}
// { 'name': 'value', ... } style serialization
function serializeHash() {
var hash = {};
eachFormElement.apply(function(name, value) {
if(name in hash) {
hash[name] && !isArray(hash[name]) && (hash[name] = [hash[name]]);
hash[name].push(value);
} else hash[name] = value;
}, arguments);
return hash;
}
// [ { name: 'name', value: 'value' }, ... ] style serialization
reqwest.serializeArray = function() {
var arr = [];
eachFormElement.apply(function(name, value) {
arr.push({
name: name,
value: value
});
}, arguments);
return arr;
};
reqwest.serialize = function() {
if(arguments.length === 0) return '';
var opt, fn, args = Array.prototype.slice.call(arguments, 0);
opt = args.pop();
opt && opt.nodeType && args.push(opt) && (opt = null);
opt && (opt = opt.type);
if(opt == 'map') fn = serializeHash;
else if(opt == 'array') fn = reqwest.serializeArray;
else fn = serializeQueryString;
return fn.apply(null, args);
};
reqwest.toQueryString = function (o) {
var qs = '',
i,
enc = encodeURIComponent,
push = function (kc, vc) {
qs += enc(kc) + '=' + enc(vc) + '&';
};
if (isArray(o)) {
for (i = 0; o && i < o.length; i++) push(o[i].name, o[i].value);
} else {
for (var k in o) {
if (!Object.hasOwnProperty.call(o, k)) { continue; }
var v = o[k];
if (isArray(v)) {
for (i = 0; i < v.length; i++) {push(k, v[i]);}
} else { push(k, o[k]); }
}
}
// spaces should be + according to spec
return qs.replace(/&$/, '')
.replace(/%20/g, '+');
};
// jQuery and Zepto compatibility, differences can be remapped here so you can call
// .ajax.compat(options, callback)
reqwest.compat = function(o, fn) {
if(o) {
o.type && (o.method = o.type) && delete o.type;
o.dataType && (o.type = o.dataType);
o.jsonpCallback && (o.jsonpCallbackName = o.jsonpCallback) && delete o.jsonpCallback;
o.jsonp && (o.jsonpCallback = o.jsonp);
}
return new Reqwest(o, fn);
};
return reqwest;
})();
/* endregion */
/* DOM Compatibility stuff */
if(undef(doc['getElementsByClassName'])) {
doc.getElementsByClassName = function(className) {
className = className.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
var element,
hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)"),
allElements = doc.getElementsByTagName("*"),
results = [];
for(var i = 0; (element = allElements[i]) != null; i++) {
var elementClass = element.className;
if(elementClass && contains(elementClass, className) && hasClassName.test(elementClass)) {
results.push(element);
}
}
return results;
};
}
},
/* General stuff dealing with the page itself. */
head = (function() {
var h = doc.head || doc.getElementsByTagName('head');
if("item" in h) {
if(!h[0]) { setTimeout(arguments.callee, 25); return null; }
h = h[0];
}
return head = h;
})(),
// This script element.
thisScript = (thisScript = document.scripts)[thisScript.length - 1],
/* Our global constants */
jsFolder = global._VosAssets + "js/",
modsFolder = jsFolder + "modules/",
localVosFolder = global._SPWebRoot + "_vos/",
localVosConfig = localVosFolder + "config/",
consts = (function(c) {
c.jquery = global.location.protocol + "//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.1.min.js";
c.medley = jsFolder + "140medley.js";
return c;
})({}),
/* Utility Stuff */
trim = global.TrimSpaces || function(s) { return s.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); },
isUrl = function(s) { return /^((?:https?:)?(?:\/\/[\w\d_.-]+)?\/?(?:[\w%+\d.=_-]+\/)*?[\w+%\d_.-]+\.[\w\d_-]+(?:\?[\w%\d+=&_.{}!$#@~()-]+)?)$/i.test(s); },
/* DOM manipulation */
insertAfter = function(target, newChild) {
if(undef(newChild)) {
newChild = target;
target = thisScript;
}
target.parentNode.insertBefore(newChild, target.nextSibling);
},
newE = function() {
if(arguments.length === 0) { return null; }
var result = doc.createElement(arguments[0]);
if(arguments.length > 1) {
var attrs = arguments[1];
for(var prop in attrs) {
result[prop] = attrs[prop];
}
}
return result;
},
firstE = (function() {
var dummy = newE("div");
return ('firstElementChild' in dummy)
? function(el) {
return el.firstElementChild;
}
: function(el) {
el = el.firstChild;
while(el && el.nodeType !== 1)
el = el.nextSibling;
return el;
};
})(),
removeE = function(e) { e.parentNode.removeChild(e); },
/* Asynchronous Loaders */
loadedResources = [],
loader = function(resources, complete) {
var resource,
node,
headAppend = function(n) { head.appendChild(n); return n; },
onreadystatechange = 'onreadystatechange',
styleSheet = 'styleSheet',
i,
scriptsToLoad,
ten = 10,
// Watch if all resources have been loaded
isComplete = function() {
if(--scriptsToLoad < 1 && complete && complete() === false) {
timeout(isComplete, ten);
}
},
// Watch if a CSS resource has been loaded
watchStylesheet = function(n) {
if(n.sheet || n[styleSheet]) {
isComplete();
} else {
timeout(function() { watchStylesheet(n); }, ten);
}
},
// Watch if a script has been loaded
watchScript = function() {
if(/ded|co/.test(this.readyState)) { isComplete(); }
},
// Watch a resource list
watchResourceList = function(localRes, globalRes) {
return function() {
if(localRes) { localRes(); }
globalRes();
};
};
// Waiting for DOM readiness
if(head || timeout(loader, ten)) {
// Format
if(resources === '' + resources) { resources = [resources]; }
// Load resources
i = scriptsToLoad = resources.length;
while(resource = resources[--i]) {
// Points out to another resource list
if(resource.pop) {
loader(resource[0], watchResourceList(resource[1], isComplete));
} else {
var key = resource.toLowerCase();
if(loadedResources.indexOf(key) !== -1) {
isComplete();
continue;
}
loadedResources.push(key);
if(/\.css$/.test(resource)) { // CSS
// Create LINK element
headAppend(node = newE('link', {
rel: styleSheet,
href: resource
}));
// Watching loading state
watchStylesheet(node);
} else { // JS
// Create SCRIPT element
if(resource in consts && !empty(consts[resource])) {
resource = consts[resource];
}
headAppend(node = newE('script', {
type: 'text/javascript',
src: resource
}));
// Watching loading state
if(node[onreadystatechange] === null) {
// Trident, Presto
node[onreadystatechange] = watchScript;
} else {
// Webkit, Gecko (also IE>=9 and Presto)
node.onload = isComplete;
}
}
}
}
}
};
/* Module Stuff */
var storedModuleData = null,
VOSModule = function(name) {
this.name = name;
this.url = modsFolder + "mod." + name + ".js";
var noop = function() { return null; };
/* Events */
this.onLoad = Array(); // Expects a callback as function(module)
this.onConfigLoad = Array(); // Expects a callback as function(module)
/* Methods */
this.Execute = noop;
this.SetupConfig = noop;
/* Properties (Sorta) */
this.handlesLocation = noop;
this.needsSP = true;
/* Private properties */
this._shouldLoad = null;
this._configObj = null;
this._loaded = false;
this._configLoaded = false;
this._executed = false;
this.Setup();
};
(function(m) {
m.prototype.getConfig = function(key, defaultValue) {
if(empty(key)) { return defaultValue; }
var parts = key.split('.'),
result = this._configObj;
for(var i = 0; i < parts.length; i++) {
key = parts[i];
if(empty(key)) { continue; }
if(undef(result[key])) { return defaultValue; }
result = result[key];
}
return result;
};
m.prototype.setConfig = function(key, val) {
if(empty(key)) { return; }
var parts = key.split('.'),
previous = 'config',
jsBody = '';
for(var i = 0; i < parts.length - 1; i++) {
if(empty(parts[i])) { continue; }
previous += '.' + parts[i];
jsBody += 'if(typeof(' + previous + ') === "undefined") { ';
jsBody += previous + ' = {};';
jsBody += '}\n';
}
previous += '.' + parts[i];
jsBody += previous + ' = val;';
var setConfigFunc = new Function('config', 'val', jsBody);
setConfigFunc(this._configObj, val);
};
m.prototype.isConfigured = function() { return this._configLoaded; };
m.prototype.isLoaded = function() { return this._loaded; };
m.prototype.hasExecuted = function() { return this._executed; };
m.prototype.shouldLoad = function() {
return this._shouldLoad = (undef(
this._shouldLoad = undef(this._shouldLoad) ?
this.handlesLocation() : this._shouldLoad
) || this._shouldLoad);
};
m.prototype.Setup = function() {
if(this.hasExecuted()) { return; }
if(!this.isLoaded()) {
var thisModule = this,
vm = 'vos.mods',
vc = 'vos.clear_mods',
executeModule = function(data) {
var modSetup = new Function('module', data);
modSetup.apply(thisModule, [thisModule]);
thisModule._loaded = true;
for(var i = 0; i < thisModule.onLoad.length; i++) {
thisModule.onLoad[i].apply(thisModule, [thisModule]);
}
thisModule.LoadConfig();
};
if(store.enabled) {
if(store.get(vc)) { storedModuleData = store.remove(vm); store.remove(vc); }
if(undef(storedModuleData)) { storedModuleData = store.get(vm); }
if(defined(storedModuleData) && defined(storedModuleData[this.name])) { executeModule(storedModuleData[this.name]); return; }
}
VOS.ajax({
url: this.url, method: 'get', type: 'html',
success: function(data) {
if(store.enabled) {
if(defined(jsmin)) { data = jsmin(data); }
if(!VOS.browser.isIE || VOS.browser.version > 7 || data.length <= 1048576) {
if(undef(storedModuleData)) { storedModuleData = {}; }
storedModuleData[thisModule.name] = data;
store.set(vm, storedModuleData);
}
}
executeModule(data);
},
error: function(data) { throw 'Could not load module: ' + thisModule.name; }
});
} else {
this.LoadConfig();
}
};
m.prototype.LoadConfig = function() {
if(this.hasExecuted()) { return; }
if(!this.isConfigured()) {
this._configObj = this.SetupConfig() || {};
var thisModule = this;
VOS.ajax({
url: localVosConfig + 'mod.' + this.name + '.config.js',
type: 'html',
method: 'get',
success: function(data) {
var modConfig = new Function('module', 'config', data);
modConfig(thisModule, thisModule._configObj);
thisModule._configLoaded = true;
for(var i = 0; i < thisModule.onConfigLoad.length; i++) { thisModule.onConfigLoad[i].apply(thisModule, [thisModule]); }
},
error: function(data) {
console.log('WARNING: Could not load configuration for module: ' + thisModule.name);
console.dir(thisModule);
thisModule.MaybeExecute();
}
});
} else {
this.MaybeExecute();
}
};
m.prototype.MaybeExecute = function() {
if(this.shouldLoad()) {
if(this.needsSP) {
ExecuteOrDelayUntilScriptLoaded(this.Execute, "sp.js");
this._executed = true;
} else {
this.Execute();
this._executed = true;
}
}
};
})(VOSModule);
var loadModule = function(n) {
if(!global.vos.modules.processed) {
global.vos.modules.queue.push(n);
} else {
global.vos.modules.loaded[n] = new VOSModule(n);
}
},
initModules = function() {
loader(localVosConfig + 'vos365.config.js', function() {
var module;
global.vos.modules.processed = true;
while(module = global.vos.modules.queue.shift()) {
if(module in global.vos.modules.loaded) { continue; }
loadModule(module);
}
});
},
/* Logic Stuff */
bootstrap = function() {
initCompat();
initModules();
//ExecuteOrDelayUntilScriptLoaded(onLoad, "sp.js");
};
global.vos = (function(o) {
o.undef = undef;
o.def = defined;
o.empty = empty;
o.loader = loader;
o.browser = (function(b) {
b.name = global.navigator.appName;
b.ua = navigator.userAgent.toLowerCase();
b.isIE = contains(b.name, 'Internet Explorer');
b.isGecko = contains(b.ua, 'gecko');
b.version = parseFloat(navigator.appVersion.substr(21)) ||
parseFloat(navigator.appVersion);
return b;
})({});
o.modules = (function(m) {
m.loaded = {};
m.load = loadModule;
m.queue = [];
m.processed = false;
m.Module = VOSModule;
return m;
})({});
o.is = (function(c) {
c.empty = empty;
c.def = defined;
c.undef = undef;
c.noval = noVal;
c.val = hasVal;
c.url = isUrl;
c.str = isStr;
c.sstr = isSStr;
c.num = isNum;
c.snum = isSNum;
c.bool = isBool;
c.sbool = isSBool;
c.func = isFunc;
c.sfunc = isSFunc;
c.arr = isArr;
c.obj = isObj;
c.sobj = isSObj;
return c;
})({});
o.util = (function(u) {
u.trim = trim;
u.istrcmp = istrcmp;
u.contains = contains;
u.icontains = icontains;
u.fthis = fthis;
u.fcaller = fcaller;
return u;
})({});
o.dom = (function(d) {
d.after = insertAfter;
d.remove = removeE;
d.first = firstE;
d.e = newE;
return d;
})({});
o.urls = (function(u) {
u.root = global._SPRoot;
u.web = global._SPWebRoot;
u.assets = global._VosAssets;
u.js = jsFolder;
u.mods = modsFolder;
u.lvos = localVosFolder;
u.lcfg = localVosConfig;
u.libs = consts;
return u;
})({});
return o;
})(global.VOS = {});
global.$V = {};
var setShortMember = function($V, name, member) { $V[name] = member; };
for(var builtin in global.VOS) {
if(isSObj(VOS[builtin])) {
for(var child in VOS[builtin]) {
setShortMember(global.$V, builtin + child.charAt(0).toUpperCase() + child.substring(1), global.VOS[builtin][child]);
}
} else { setShortMember(global.$V, builtin, global.VOS[builtin]); }
}
// required: shim for FF <= 3.5 not having document.readyState
if(doc.readyState == null && doc.addEventListener) {
doc.readyState = "loading";
doc.addEventListener("DOMContentLoaded", handler = function() {
doc.removeEventListener("DOMContentLoaded", handler, false);
doc.readyState = "complete";
}, false);
}
bootstrap();
})(window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment