c.getName()===partsi) {
node = childrenc;
nodePath.push(node);
break;
}
}
if(c===children.length) {
return null; //No path match
}
}
return nodePath;
};
}
var NextActionId=0;
var Actions = ;
function Action(config) {
var self = this;
var fn = OpenForum.evaluate("("+config.fn+")");
var icon = config.icon;
var toolTip = config.toolTip;
var id = "ActionId"+NextActionId;
NextActionId++;
Actionsid=this;
icon = "/OpenForum/Images/icons/png/" + icon + ".png";
self.call = function(node) {
fn(node);
};
self.render = function(target)
{
data=" "+
"";
return data;
};
}
function TreeNode(name,attributes,newParent,jsonModifier) {
var self = this;
var id = "TreeNode"+NextTreeNodeIndex;
NextTreeNodeIndex++;
TreeNodesid = self;
var children = ;
var expanded = false;
var SPACE = " ";
var localDepth = 0;
var lazyLoad = null;
var parent = newParent;
var paint = function() {
document.getElementById(id).innerHTML = self.render(localDepth);
};
self.paint = paint;
self.getId = function() {
return id;
};
self.setLazyLoad = function(lazyLoadFn) {
lazyLoad = lazyLoadFn;
return this;
};
self.getParent = function() {
return parent;
};
self.setParent = function(newParent) {
parent = newParent;
};
self.addChild = function(name,attributes) {
var newChild = new TreeNode(name,attributes,self,jsonModifier);
childrenchildren.length = newChild;
newChild.parent = self;
return newChild;
};
self.addJSON = function(node) {
if(jsonModifier!==null) jsonModifier(node);
var child = self.addChild( node.name,node.attributes );
if(node.leaves) {
for(var i in node.leaves) {
child.addJSON( node.leavesi );
}
}
return child;
};
self.importJSON = function(url,action,parameters) {
JSON.get(url,action,parameters).onSuccess(
function(response) {
for(var i in response.leaves) {
self.addJSON( response.leavesi );
}
paint();
}
).go();
};
self.toJSON = function() {
var json = {
name: name,
attributes: {},
leaves:
};
for(var a in attributes) {
if( typeof a == "string") {
json.attributesa = attributesa;
}
}
for(var c in children) {
json.leaves.push( childrenc.toJSON() );
}
return json;
};
self.deleteChild = function(node) {
for(var index in children) {
if(childrenindex.getId()===node.getId()) {
children.splice(index,1);
return this;
}
}
return this;
};
self.isExpanded = function() {
return expanded;
};
self.expand = function() {
if(lazyLoad!==null) {
lazyLoad(self);
lazyLoad = null;
return this;
}
if(parent && parent.isExpanded()===false) {
parent.expand();
}
expanded=true;
paint();
return this;
};
self.collapse = function() {
expanded=false;
paint();
return this;
};
self.toggle = function() {
expanded=!expand;
paint();
return this;
};
self.render = function(depth) {
if(!depth) {
depth=0;
}
localDepth = depth;
var data = "";
data+="";
for(var count=0;count0) {
if(expanded===false) {
data+=""+
"";
} else {
data+=""+
"";
}
} else {
data+=" ";
}
if(attributes && attributes.link) {
if(attributes.toolTip) {
data += """ + attributes.link + "
" title=
""+ attributes.toolTip +"
" target=
"_pageView
">";
} else {
data += """ + attributes.link + "
" target=
"_pageView
">";
}
if(attributes.icon) {
data += "";
}
data += name;
data += "";
} else {
if(attributes && attributes.icon) {
data += "";
}
data += name;
}
if(attributes && attributes.actions) {
for(var actionIndex in attributes.actions) {
var actionConfig = attributes.actionsactionIndex;
var action = new Action(actionConfig);
data+=action.render("TreeNodes""target="editor" style="color: red" title="The page /OpenForum/Editor?pageName=/OpenForum/Javascript/Core/
""+id+"
" does not exist. Click to create it.">
""+id+"
"");
}
}
data+="
";
if(expanded===true) {
for(var childIndex in children) {
data+=childrenchildIndex.render(depth+1);
}
}
data+="";
return data;
};
self.getName = function() {
return name;
};
self.setName = function(newName) {
name = newName;
};
self.getAttribute = function(name) {
return attributesname;
};
self.setAttribute = function(name,value) {
attributesname = value;
};
self.applyToChildren = function( fn ) {
children.forEach( function(child) { fn(child); } );
};
self.getChildren = function() {
return children;
};
}
OpenForum.createFileTree = function(id,root,fileExtension,modifier) {
var tree = new Tree(id,"Loading...","",modifier);
if( isUndefined(fileExtension) ) {
JSON.get("/OpenForum/Javascript/Tree","getPageTree","pageName="+root).onSuccess(
function(result) {
tree.setJSON(result);
tree.render();
tree.getRoot().expand();
tree.init();
}
).go();
} else {
JSON.get("/OpenForum/Javascript/Tree","getPageTree","pageName="+root+"&match=.*
."+fileExtension).onSuccess(
function(result) {
tree.setJSON(result);
tree.render();
tree.getRoot().expand();
tree.init();
}
).go();
}
return tree;
};
//==============================================================================================================//
//==============================================================================================================//
//==============================================================================================================//
//Global extra methods
function typeOf( thing ) {
return Object.prototype.toString.call( thing ).slice(8, -1).toLowerCase();
}
function isArray( thing ) {
return typeOf( thing ) == "array";
}
function isObject( thing ) {
return typeOf( thing ) == "object";
}
function isFunction( thing ) {
return typeOf( thing ) == "function";
}
function isUndefined( thing ) {
return typeOf( thing ) == "undefined";
}
function isString( thing ) {
return typeOf( thing ) == "string";
}
function isNumber( thing ) {
return typeOf( thing ) == "number";
}
function isFloat( thing ) {
return thing === +thing && thing !== (thing|0);
}
function isInteger( thing ) {
return thing === +thing && thing === (thing|0);
}
function isNullOrBlank( thing ) {
return (
isUndefined(thing) ||
thing == null ||
( isString( thing ) && thing.trim().length == 0)
);
}
//
Math extra methods
Math.degToRad = function( deg ) {
return (deg * Math.PI)/180;
};
Math.radToDeg = function( rad ) {
return (rad * 180)/Math.PI;
};
//
String extra methods
String.prototype.contains = function(start) {
return (this.indexOf(start)!==-1);
};
String.prototype.startsWith = function(start) {
return (this.indexOf(start)===0);
};
String.prototype.endsWith = function(end) {
if(!this.contains(end)) return false;
return (this.lastIndexOf(end)===this.length-end.length);
};
String.prototype.between = function(start,end) {
if(!this.contains(start) || !this.contains(end)) return;
return this.substring(this.indexOf(start)+start.length,this.indexOf(end));
};
String.prototype.before = function (end) {
if(!this.contains(end)) return;
return this.substring(0,this.indexOf(end));
};
String.prototype.beforeLast = function (end) {
if(!this.contains(end)) return;
return this.substring(0,this.lastIndexOf(end));
};
String.prototype.after = function (start) {
if(!this.contains(start)) return;
return this.substring(this.indexOf(start)+start.length);
};
String.prototype.afterLast = function (start) {
if(!this.contains(start)) return;
return this.substring(this.lastIndexOf(start)+start.length);
};
String.prototype.replaceAll = function(find,replace) {
return this.replace( new RegExp(find,"g"), replace);
};
String.prototype.padBefore = function(padding,targetLength) {
var result = this;
while(result.length Date extra methods
Date.prototype.getDisplayString = function() {
return (""+this).substring(0,24);
};
Date.prototype.SECOND_IN_MILLIS = 1000;
Date.prototype.MINUTE_IN_MILLIS = Date.prototype.SECOND_IN_MILLIS*60;
Date.prototype.HOUR_IN_MILLIS = Date.prototype.MINUTE_IN_MILLIS*60;
Date.prototype.DAY_IN_MILLIS = Date.prototype.HOUR_IN_MILLIS*24;
Date.prototype.clone = function() {
return new Date( this.getTime() );
};
Date.prototype.toISODateString = function() {
return this.toISOString().substring(0,10);
};
Date.prototype.plusSeconds = function(seconds) {
this.setTime( this.getTime()+(this.SECOND_IN_MILLIS*seconds) );
return this;
};
Date.prototype.plusMinutes = function(minutes) {
this.setTime( this.getTime()+(this.HOUR_IN_MILLIS*minutes) );
return this;
};
Date.prototype.plusHours = function(hours) {
this.setTime( this.getTime()+(this.HOUR_IN_MILLIS*hours) );
return this;
};
Date.prototype.plusDays = function(days) {
this.setTime( this.getTime()+(this.DAY_IN_MILLIS*days) );
return this;
};
Date.prototype.plusMonths = function(months) {
this.setMonth( this.getMonth()+months );
return this;
};
Date.prototype.plusYears = function(years) {
this.setYear( this.getYears()+years );
return this;
};
Date.prototype.isOnOrAfter = function(date) {
return (Math.floor(this.getTime()/this.DAY_IN_MILLIS)>=Math.floor(date.getTime()/this.DAY_IN_MILLIS));
};
Date.prototype.isAfter = function(date) {
return (this.getTime()>date.getTime());
};
Date.prototype.isBefore = function(date) {
return (this.getTime() New type, time
var Time = function(hours,minutes,seconds) {
var self = this;
if(!hours) hours = 0;
var parts = hours.split(":");
if(parts.length>1) {
hours = parts0;
}
if(parts1) {
minutes = parts1;
}
if(parts2) {
seconds = parts1;
}
if(!minutes) minutes = 0;
if(!seconds) seconds = 0;
hours = parseInt(hours);
minutes = parseInt(minutes);
seconds = parseInt(seconds);
self.getTime = function() {
return hours * 3600) + (minutes * 60) + seconds)*1000;
};
self.plusSeconds = function( newSeconds ) {
seconds += parseInt(newSeconds);
minutes += Math.floor(seconds/60);
seconds = seconds % 60;
hours += Math.floor(minutes/60);
minutes = minutes % 60;
};
self.getHours = function() { return hours; };
self.getMinutes = function() { return minutes; };
self.getSeconds = function() { return seconds; };
self.setHours = function(newHours) { hours=newHours; };
self.setMinutes = function(newMinutes) { minutes=newMinutes; };
self.setSeconds = function(newSeconds) { seconds=newSeconds; };
self.plusMinutes = function( newMinutes ) {
minutes += parseInt(newMinutes);
hours += Math.floor(minutes/60);
minutes = minutes % 60;
};
self.plusHours = function( newHours ) {
hours += parseInt(newHours);
};
self.isAtOrAfter = function(time) {
if( self.getTime() >= time.getTime() )
return true;
else
return false;
};
self.isAfter = function(time) {
if( self.getTime() > time.getTime() )
return true;
else
return false;
};
self.isAtOrBefore = function(time) {
if( self.getTime() <= time.getTime() )
return true;
else
return false;
};
self.isBefore = function(time) {
if( self.getTime() < time.getTime() )
return true;
else
return false;
};
self.toString = function() {
return ("" + hours).padBefore("0",2) + ":" + ("" + minutes).padBefore("0",2) + ":" + ("" + seconds).padBefore("0",2);
};
self.toShortString = function() {
return ("" + hours).padBefore("0",2) + ":" + ("" + minutes).padBefore("0",2);
};
};
//
Async processing helper
function Process() {
var callFn;
var waitTest;
var thenFn;
var self = this;
self.call = function(newCallFn) {
callFn = newCallFn;
return self;
};
self.waitFor = function(newWaitTest) {
waitTest = newWaitTest;
return self;
};
self.then = function(newThenFn) {
thenFn = newThenFn;
return self;
};
var wait = function() {
if(waitTest()===false) {
setTimeout(wait,100);
} else {
if(thenFn) thenFn();
}
};
self.run = function(data) {
if(callFn) callFn(data);
wait();
};
}
//==============================================================================================================//
//==============================================================================================================//
//==============================================================================================================//
//
OpenForumObject
function OpenForumObject(objectId) {
var self = this;
var id = objectId;
var value = null;
var targets=;
var listeners=;
var quiet = false;
OpenForum.debug("INFO","Object " + id + " created");
var notifyListeners = function() {
if(quiet) {
OpenForum.debug("INFO","Object " + id + " has changed but is quiet");
return;
}
for(var listenerIndex in listeners) {
var listener = listenerslistenerIndex;
listener( self );
if(listener.getId) {
OpenForum.debug("INFO","Object " + id + " has notified " + listener.getId() + "of change");
}
}
};
self.getId = function() {
return id;
};
self.add = function(target) {
targets.push(target);
if(value != null) { // If you want to join, you have to take on the value
var hold = value;
value = null; // Force the value to be set in all targets as will be seen as a change
self.setValueQuietly(hold); // Not a real change of value, so quietly does it
}
if(target.getId) {
OpenForum.debug("INFO","Object " + id + " has added new target " + target.getId(;
} else {
OpenForum.debug("INFO","Object " + id + " has added new target " + target);
}
};
self.reset = function() {
value = null;
};
self.setValueQuietly = function (newValue,exclude,clone) {
quiet = true;
self.setValue(newValue,exclude,clone);
quiet = false;
};
self.setValue = function(newValue,exclude,clone) {
if(OpenForum.isEqual(newValue,value)) {
return;
}
OpenForum.debug("INFO","Object " + id + " value set to " + newValue);
if(clone && typeof newValue == "object") {
value = OpenForum.clone(newValue);
} else {
value = newValue;
}
for(var targetIndex in targets) {
var target = targetstargetIndex;
if(target===null) {
continue;
}
if(exclude && exclude===target) {
continue;
}
if(typeof(target.type)!="undefined" && target.type=="checkbox") {
target.checked = value;
} else if(typeof(target.type)!="undefined" && target.type=="select-multiple") {
for(var i in target.options) {
target.optionsi.selected=false;
for(var j in value) {
if(target.optionsi.value==valuej) {
target.optionsi.selected=true;
}
}
}
OpenForum.setGlobal(id,value);
} else if(typeof(target.value)!="undefined") {
target.value = value;
} else if(target.innerHTML) {
if(value==="") {
target.innerHTML = " ";
} else {
target.innerHTML = ""+value;
}
}
}
};
self.getValue = function() {
return value;
};
self.scan = function() {
for(var targetIndex=0; targetIndextargetIndex;
if(target===null) {
continue;
}
if(typeof(target.type)!="undefined" && target.type=="checkbox") {
if(target.checked!==value) {
//If UI has been checked
self.setValue(target.checked,target,true);
OpenForum.setGlobal(id,target.checked);
OpenForum.debug("INFO","Object (checkbox) " + id + " value set to " + value);
notifyListeners();
return;
}
} else if(target.type=="select-multiple") {
var selected = ;
for(var i in target.options) {
if(target.optionsi.selected) selected.push(target.optionsi.value);
}
//If UI selection changes
if(OpenForum.isEqual(value,selected)==false) {
self.setValue(selected,target,true);
OpenForum.setGlobal(id,selected);
OpenForum.debug("INFO","Object (select-multiple) " + id + " value set to " + selected);
notifyListeners();
return;
}
} else if(typeof(target.value)!="undefined") {
//If UI value changes
if(target.value!=value) {
self.setValue(target.value,target,true);
OpenForum.setGlobal(id,value);
OpenForum.debug("INFO","Object " + id + " value set to " + value);
notifyListeners();
return;
}
}
} catch(e) {
OpenForum.debug("ERROR","Object " + id + " error in setting value (case 1).", e);
}
}
try{
var testId = id;
if( OpenForum.globalExists(testId) ) {
//If bound js variable changes
if( OpenForum.isEqual(value,OpenForum.getGlobal(testId))===false) {
self.setValue(OpenForum.getGlobal(testId),null,true);
notifyListeners();
}
} else {
OpenForum.setGlobal(testId,value,true);
OpenForum.debug("INFO","Global object created " + testId + " and value set to " + value);
}
} catch(e) {
OpenForum.debug("ERROR","Object " + id + " error in setting value (case 2).", e);
}
};
self.addListener = function(listener) {
listeners.push(listener);
if(listener.getId) {
OpenForum.debug("INFO","Object " + id + " has added new listener " + listener.getId());
} else {
OpenForum.debug("INFO","Object " + id + " has added new listener " + listener);
}
};
self.removeListener = function(listener) {
for(var listenerIndex in listeners) {
if(listenerslistenerIndex.getId && listener.getId && listenerslistenerIndex.getId() == listener.getId() ) {
listeners.splice(listenerIndex,1);
break;
} else if (listenerslistenerIndex == listener) {
listeners.splice(listenerIndex,1);
break;
}
}
if(listener.getId) {
OpenForum.debug("INFO","Object " + id + " has added removed a listener " + listener.getId());
} else {
OpenForum.debug("INFO","Object " + id + " has added removed a listener " + listener);
}
};
self.getId = function() {
return id;
};
self.getTargets = function() {
return targets;
};
}
//==============================================================================================================//
//==============================================================================================================//
//==============================================================================================================//
//
OpenForumTable
function OpenForumTable(node) {
var self = this;
var rowNode = node;
var tableNode = node.parentNode;
var value;
var id;
if(tableNode.attributes && tableNode.attributes'of-id') {
id=tableNode.attributes'of-id'.value;
} else if(tableNode.id) {
id=tableNode.id;
} else {
id="OFTable"+OpenForum.getNextId();
}
node.parentNode.removeChild(node);
var temp = document.createElement("table");
temp.appendChild(node);
var rowHTML = temp.innerHTML;
var repeatFor = node.attributes'of-repeatFor'.value;
var target = repeatFor.substring(repeatFor.indexOf(" in ")+4);
var element = repeatFor.substring(0,repeatFor.indexOf(" in "));
var targetObject = OpenForum.getObject(target);
var targetObjectSignature = OpenForum.createObjectSignature( targetObject.getValue() );
if(id.indexOf("OFTable")===0) id += "_" + repeatFor.replaceAll(" ","_");
OpenForum.debug("INFO","Added OpenForum table " + repeatFor + " as " + id);
var tableTop = tableNode.innerHTML;
tableNode.id = id;
self.setTableNode = function(newTableNode) {
tableNode = newTableNode;
};
self.reset = function() {
targetObjectSignature = null;
value = null;
};
self.updateQuietly = function() {
targetObjectSignature = OpenForum.createObjectSignature( targetObject.getValue() );
};
self.refresh = function() {
try {
if(tableNode.attributes && tableNode.attributes'of-id' && typeof tableNode.value != "undefined" ) {
//Not sure what the empty string was there for, but it stops select working
//if( this.tableNode.value!=this.value && this.value!="") {
if( tableNode.value!=value) {
value = tableNode.value;
OpenForum.setGlobal(tableNode.id,value);
OpenForum.debug("INFO","Table " + id + " value changed to " + value);
} else {
var newValue = OpenForum.getGlobal(tableNode.id);
if( typeof tableNode.value !== "undefined" && tableNode.value!=newValue && typeof newValue !== "undefined" && newValue !== null ) {
tableNode.value=newValue;
value = newValue;
if(tableNode.value === newValue) {
OpenForum.debug("INFO","Table " + id + " value changed to " + value);
}
}
}
}
} catch(e) {
OpenForum.debug("ERROR","Table " + id + " set value failed.", e);
}
//check if changed
var objectSignature = OpenForum.createObjectSignature( targetObject.getValue() );
if(objectSignature==targetObjectSignature) {
return;
}
var errors = false;
var tableData = tableTop;
var collection = targetObject.getValue();
for( var elementIndex in collection ) {
try {
var item = {};
itemelement= collectionelementIndex;
itemelement.index = elementIndex;
var data = ""+rowHTML;
while(data.indexOf(OpenForum.FIELD_DELIMETER_START)!=-1) {
var name = data.substring(data.indexOf(OpenForum.FIELD_DELIMETER_START)+2,data.indexOf(OpenForum.FIELD_DELIMETER_END));
var rowValue;
if(name.indexOf(".")===-1) {
if(name==element) {
rowValue = itemelement;
} else {
rowValue = OpenForum.getGlobal(name);
}
} else {
var parts = name.split(".");
rowValue = item;
for(var part in parts) {
if(partspart.indexOf("(")!==-1) {
var fn = partspart.substring(0,partspart.indexOf("("));
var call = partspart.substring(partspart.indexOf("("),partspart.indexOf(")")).split(",");
rowValue = rowValuefn.apply( this,call );
} else if(partspart.indexOf("=")!==-1) {
var pName = partspart.substring(0,partspart.indexOf("="));
var value = partspart.substring(partspart.indexOf("=")+1).split("?");
if( rowValuepName == value0 ) {
rowValue = value1;
} else {
rowValue = "";
}
}else {
rowValue = rowValuepart" alt="partspart" title="partspart"/>];
}
}
}
var dataStart = data.substring(0,data.indexOf(OpenForum.FIELD_DELIMETER_START));
var dataEnd = data.substring(data.indexOf(OpenForum.FIELD_DELIMETER_END)+2);
if(dataStart.indexOf("of-if=
"")==dataStart.length-7) {
data = dataStart.substring(0,dataStart.indexOf("of-if=
""))+
rowValue+
dataEnd.substring(1);
} else {
data = dataStart + rowValue + dataEnd;
}
if( tableNode.type=="select-one") {
if(OpenForum.getGlobal(id) === rowValue ) {
data = data.replace("selected=
"
"","selected");
OpenForum.debug("INFO","Table " + id + " selected = " + rowValue);
} else {
data = data.replace("selected=
"
"","");
}
}
}
tableData += data;
} catch(e) {
OpenForum.debug("ERROR","Table " + id + " refresh failed.", e);
//Fail quietly
errors = true;
}
}
OpenForum.debug("INFO","Table " + id + " updated.");
tableNode.innerHTML=tableData;
OpenForum.preparePage(tableNode);
//Only update the signature once the data is in the view without errors
if(errors==false) {
targetObjectSignature=objectSignature;
}
};
self.getId = function() {
return id;
};
}
//==============================================================================================================//
//==============================================================================================================//
//==============================================================================================================//
if(!OpenForum) {
OpenForum = {};
}
OpenForum.Browser={};
OpenForum.Browser.download = function(fileName,data){
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:attachment/text,' + encodeURIComponent(data);
hiddenElement.target = '_blank';
hiddenElement.style.display = "none";
hiddenElement.download = fileName;
document.body.appendChild(hiddenElement);
hiddenElement.click();
};
OpenForum.Browser.upload = function(callback,onError) {
var hiddenElement = document.createElement('input');
hiddenElement.type = "file";
hiddenElement.style.display = "none";
hiddenElement.onchange = function(event) {
var reader = new FileReader();
reader.onload = function(event) {
if(event.target.readyState != 2) return;
if(event.target.error) {
if(onError) {
onError('Error while reading file');
} else {
alert('Error while reading file');
}
return;
}
callback( event.target.result );
};
reader.readAsText(event.target.files0);
};
document.body.appendChild(hiddenElement);
hiddenElement.click();
};
OpenForum.Browser.uploadDataUrl = function(callback,onError) {
var hiddenElement = document.createElement('input');
hiddenElement.type = "file";
hiddenElement.style.display = "none";
hiddenElement.onchange = function(event) {
var reader = new FileReader();
reader.onload = function(event) {
if(event.target.readyState != 2) return;
if(event.target.error) {
if(onError) {
onError('Error while reading file');
} else {
alert('Error while reading file');
}
return;
}
callback( event.target.result );
};
reader.readAsDataURL(event.target.files0);
};
document.body.appendChild(hiddenElement);
hiddenElement.click();
};
OpenForum.Browser.overrideSave = function(fn) {
$(document).bind('keydown', function(e) {
if(e.ctrlKey && (e.which == 83)) {
e.preventDefault();
fn();
return false;
}
});
};
OpenForum.Browser.isBrowserStorageEnabled = function() {
return ( typeof OpenForum.findBrowserFileTreeNode != "undefined" );
};
OpenForum.Browser.enableBrowserStorage = function() {
if( OpenForum.Browser.isBrowserStorageEnabled() ) {
console.log("Browser Storage already enabled");
return;
}
OpenForum.findBrowserFileTreeNode = function( pageName ) {
pageName = pageName.replace("browser:/","");
var list = OpenForum.Storage.find("browserFS "+pageName+"*.");
var data = ;
var found = {};
for(var a in list) {
var fileName = lista.key.substring( pageName.length + 10);
if(fileName.startsWith("/")) fileName = fileName.substring(1);
if(fileName.indexOf("/")!=-1) {
var page = fileName.substring(0,fileName.indexOf("/"));
if( page.length==0 ) continue;
if( typeof foundpage == "undefined" ) {
data.push( {fileName: page, type: "page"} );
foundpage = true;
}
} else {
if( fileName.length==0 ) continue;
if( typeof foundfileName == "undefined" ) {
var extension = fileName.substring( fileName.indexOf(".")+1 );
data.push( {fileName: fileName, type: "file", extension: ""} );
foundfileName = true;
}
}
}
return data;
};
OpenForum.remoteSave = OpenForum.saveFile;
OpenForum.saveFile = function(fileName,data,callBack) {
if(fileName.startsWith("browser://")) {
fileName = fileName.replace("browser:/","browserFS ");
OpenForum.Storage.set(fileName,data);
if( isUndefined(OpenForum.inq) == false ) OpenForum.inq.send( { type: "browserFS", event: "fileChanged", fileName: fileName } );
var simpleFileName = fileName.substring( fileName.lastIndexOf("/")+1 );
var extension = simpleFileName.substring( simpleFileName.lastIndexOf(".")+1 );
OpenForum.findBrowserFileTreeNode( fileName, { type: "file", size: data.length, created: new Date().getTime(), updated: new Date().getTime(), fileName: simpleFileName, extension: extension } );
var response = {"result":"ok","message":"Saved " + fileName,"saved":true};
if(callBack) {
callBack( response );
} else {
return response;
}
} else {
return OpenForum.remoteSave(fileName,data,callBack);
}
};
OpenForum.remoteDelete = OpenForum.deleteFile;
OpenForum.deleteFile = function(pageName,fileName,callBack) {
if(fileName.startsWith("browser://")) {
fileName = fileName.replace("browser:/","browserFS ");
OpenForum.findBrowserFileTreeNode( fileName, { deleted: true } );
if( isUndefined(OpenForum.inq) == false ) OpenForum.inq.send( { type: "browserFS", event: "fileDeleted", fileName: fileName } );
var response = {"result":"ok","message":"Deleted " + fileName,"deleted":true};
if(callBack) {
callBack( response );
} else {
return response;
}
} else {
return OpenForum.remoteDelete(pageName,fileName,callBack);
}
};
OpenForum.remoteLoad = OpenForum.loadFile;
OpenForum.loadFile = function(fileName,callBack,noCache) {
if(fileName.startsWith("browser://")) {
fileName = fileName.replace("browser:/","browserFS ");
var data = OpenForum.Storage.get(fileName);
if(callBack) {
callBack( data );
}
return data;
} else {
return OpenForum.remoteLoad(fileName,callBack,noCache);
}
};
OpenForum.remoteAppend = OpenForum.appendFile;
OpenForum.appendFile = function(fileName,data,callBack) {
if(fileName.startsWith("browser://")) {
fileName = fileName.replace("browser:/","browserFS ");
var currentData = OpenForum.Storage.get(fileName);
if( currentData == null ) {
return OpenForum.saveFile(fileName,data,callBack);
}
data = currentData + data;
OpenForum.Storage.set(fileName,data);
if( isUndefined(OpenForum.inq) == false ) OpenForum.inq.send( { type: "browserFS", event: "fileChanged", fileName: fileName } );
OpenForum.findBrowserFileTreeNode( fileName, { modified: new Date().getTime(), size: data.length } );
var response = {"result":"ok","message":"Appended " + fileName,"appended":true};
if(callBack) {
callBack( response );
} else {
return response;
}
} else {
return OpenForum.remoteAppend(fileName,data,callBack);
}
};
OpenForum.remoteCopy = OpenForum.copyFile;
OpenForum.copyFile = function(fileName,toFileName,callBack) {
if(fileName.startsWith("browser://")) {
fileName = fileName.replace("browser:/","browserFS ");
var data = OpenForum.Storage.get(fileName);
OpenForum.saveFile(toFileName,data);
var response = {"result":"ok","message":"Copied " + fileName,"copied":true};
if(callBack) {
callBack( response );
} else {
return response;
}
} else {
return OpenForum.remoteCopy(fileName,toFileName,callBack);
}
};
OpenForum.remoteMove = OpenForum.moveFile;
OpenForum.moveFile = function(fileName,toFileName,callBack) {
if(fileName.startsWith("browser://")) {
fileName = fileName.replace("browser:/","browserFS ");
var data = OpenForum.Storage.get(fileName);
OpenForum.saveFile(toFileName,data);
OpenForum.deleteFile(fileName);
var response = {"result":"ok","message":"Moved " + fileName,"moved":true};
if(callBack) {
callBack( response );
} else {
return response;
}
} else {
return OpenForum.remoteMove(fileName,toFileName,callBack);
}
};
OpenForum.remoteFileExists = OpenForum.fileExists;
OpenForum.fileExists = function(fileName) {
if(fileName.startsWith("browser://")) {
fileName = fileName.replace("browser:/","browserFS ");
return OpenForum.Storage.get(fileName) != null;
} else {
return OpenForum.remoteFileExists(fileName);
}
};
OpenForum.remoteGetAttachments = OpenForum.getAttachments;
OpenForum.getAttachments = function(pageName,callBack,matching,withMetaData) {
if(pageName.startsWith("browser://")) {
pageName = pageName.replace("browser:/","browserFS ");
var list = OpenForum.Storage.find(pageName+"*.");
var json = {
attachments: ,
length: 0,
pageName: pageName
};
if(withMetaData) {
json.size = 0;
}
for(var a in list) {
var fileName = lista.key.substring( pageName.length+1 );
if(fileName.indexOf("/")!=-1) continue;
var attachment = {
pageName: pageName,
fileName: fileName
};
if(withMetaData) {
attachment.size = lista.value.length;
attachment.lastModified = 0;
json.size += attachment.size;
}
json.length ++;
json.attachments.push( attachment );
}
if(callBack) {
callBack( json.attachments);
} else {
return json.attachments;
}
} else {
return OpenForum.remoteGetAttachments(pageName,callBack,matching,withMetaData);
}
};
OpenForum.remoteGetSubPages = OpenForum.getSubPages;
OpenForum.getSubPages = function(pageName, callBack) {
if(pageName.startsWith("browser://")) {
pageName = pageName.replace("browser:/","browserFS ");
var list = OpenForum.Storage.find(pageName+"*.");
var json = ;
var found = {};
for(var a in list) {
var fileName = lista.key.substring( pageName.length );
if(fileName.indexOf("/")!=-1) {
dataPageName = fileName.substring( 0, fileName.indexOf("/") );
if(typeof founddataPageName == "undefined") {
json.push(dataPageName);
founddataPageName = true;
}
}
}
if(callBack) {
callBack( json );
} else {
return json;
}
} else {
return OpenForum.remoteGetSubPages(pageName,callBack);
}
};
OpenForum.remoteCreateFileTree = OpenForum.createFileTree;
OpenForum.createFileTree = function(id,root,fileExtension,modifier) {
if(root.startsWith("browser://")) {
var tree = new Tree(id,"Loading...","",modifier);
var fsJson = OpenForum.findBrowserFileTreeNode( root.replace("browser:/","") );
//Copy
//https://open-forum.onestonesoup.org/OpenForum/Javascript/Tree?action=getPageTree&pageName=/TheLab/Experiments/BrowserFileStorage
var toFileTree = function( depth, name, json, path ) {
if( isUndefined( path ) ) {
path = "";
}
var newNode = {};
newNode.name = name;
newNode.attributes = {
type: "page",
pageName: path,
link: path,
icon: "book",
toolTip: "Open page"
};
newNode.leaves = ;
for(var i in json) {
var node = jsoni;
if(node.type && node.type == "file") {
if( ( typeof fileExtension != "undefined" ) && node.extension.match( ".*
." + fileExtension ) ) {
continue;
}
var jsonNode = {};
jsonNode.name = node.fileName;
jsonNode.leaves = ;
jsonNode.attributes = {
type: "file",
pageName: path,
fileName: node.fileName,
link: path + "/" +node.fileName,
icon: "attach",
actions:
{
fn: "function(node){ window.open('/OpenForum/Editor?pageName=' + node.getAttribute('pageName') + '&fileName=' + node.getAttribute('fileName')); }",
icon: "pencil",
toolTip: "Edit file"
}
};
newNode.leaves.push( jsonNode );
} else if(node.type && node.type == "page") {
var fullPage = path;
if( fullPage.endsWith("/") == false ) fullPage += "/";
fullPage += node.fileName;
var jsonNode = {};
jsonNode.name = node.fileName;
jsonNode.leaves = ;
jsonNode.attributes = {
type: "page",
pageName: node.fileName,
link: fullPage,
icon: "page",
toolTip: "Open page",
depth: depth
};
var fsJson = OpenForum.findBrowserFileTreeNode( fullPage );
newNode.leaves.push( toFileTree( depth+1, node.fileName, fsJson, fullPage ) );
}
}
return newNode;
};
var jsonTree = toFileTree( 0,root.substring( root.lastIndexOf("/")+1 ) ,fsJson, root );
tree.setJSON(jsonTree);
tree.render();
tree.getRoot().expand();
tree.init();
return tree;
} else {
return OpenForum.remoteCreateFileTree(id,root,fileExtension,modifier);
}
};
};
OpenForum.addInitialiser( function() {
//browserFS enabled by default. Add ?browserFS=false to stop
if( OpenForum.getParameter("browserFS")=="false" == false ) {
OpenForum.Browser.enableBrowserStorage();
}
});
//==============================================================================================================//
//==============================================================================================================//
//==============================================================================================================//
OpenForum.action = {};
OpenForum.action.copyPage = function(pageName,newPageName) {
window.open("/OpenForum/Actions/Copy?newPageName="+newPageName+"&pageName="+pageName);
};
OpenForum.action.movePage = function(pageName,newPageName) {
window.location = "/OpenForum/Actions/Move?newPageName="+newPageName+"&pageName="+pageName;
};
OpenForum.action.zipPage = function(pageName) {
window.location = "/OpenForum/Actions/Zip?action=zip&pageName="+pageName;
};
OpenForum.action.deletePage = function(pageName) {
window.location = "/OpenForum/Actions/Delete?pageName="+pageName;
};
//==============================================================================================================//
//==============================================================================================================//
//==============================================================================================================//
if(!OpenForum) {
OpenForum = {};
}
OpenForum.BLANK = ""; //Used in Extensions where "" cannot be used
OpenForum.createObjectSignature = function(object) {
var cache = ;
var signature = JSON.stringify(object, function(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
cache = null;
return signature;
};
OpenForum.copyElement = function(id) {
document.getElementById(id).select();
document.execCommand('copy');
};
OpenForum.copyData = function(data) {
var hiddenElement = document.createElement('textarea');
hiddenElement.value = data;
document.body.appendChild( hiddenElement );
hiddenElement.select();
document.execCommand('copy');
document.body.removeChild( hiddenElement );
};
OpenForum.setElement = function(id,content) {
document.getElementById(id).innerHTML = content;
OpenForum.crawl( document.getElementById(id) );
};
OpenForum.appendToElement = function(id,content) {
document.getElementById(id).innerHTML += content;
OpenForum.crawl( document.getElementById(id) );
};
OpenForum.showElement = function(id, show) {
if( typeof show != "undefined" && show == false ) {
OpenForum.hideElement( id );
} else {
document.getElementById(id).style.display = "block";
}
};
OpenForum.hideElement = function(id) {
document.getElementById(id).style.display = "none";
};
OpenForum.toggleElement = function(id) {
if(document.getElementById(id).style.display==="block") {
document.getElementById(id).style.display = "none";
} else {
document.getElementById(id).style.display = "block";
}
};
OpenForum.setTitle = function(title) {
document.title = title;
};
OpenForum.setCursor = function(pointer) {
if(pointer == "wait") {
document.body.style.cursor = 'wait';
return;
} else if(pointer == "zoom-in") {
document.body.style.cursor = 'zoom-in';
return;
} else if(pointer == "pointer") {
document.body.style.cursor = 'pointer';
return;
} else if(pointer == "crosshair") {
document.body.style.cursor = 'crosshair';
return;
} else if(pointer == "default") {
document.body.style.cursor = 'default';
return;
}
if(pointer.indexOf(".")==-1) {
pointer = "/OpenForum/Images/icons/png/" +pointer+ ".png";
}
document.getElementsByTagName("body")0.style.cursor = "url('"+pointer+"'), auto";
};
OpenForum.setTabIcon = function(icon) {
if(icon.indexOf(".")==-1) {
icon = "/OpenForum/Images/icons/png/" +icon+ ".png";
}
var link = document.querySelector("linkrel~='icon'");
if (!link) {
link = document.createElement('link');
link.rel = 'icon';
document.head.appendChild(link);
}
link.href = icon;
};
OpenForum.getParameter = function( name ) {
name = name.replace(/" alt="
" title="
"/>/g,"
" alt="").replace(/
" title="").replace(/
"/>]/g,"
]");
var regexS = "
?&"+name+"=(^*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results === null )
return "";
else
return results1;
};
OpenForum.getCookie = function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++)
{
var c = cai;
while (c.charAt(0)==' ')
{
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) === 0)
{
return c.substring(nameEQ.length,c.length);
}
}
return null;
};
//Keep all the evil in one place
OpenForum.evaluate = function(script) {
try{
return eval(script);
} catch (e) {
OpenForum.debug( "ERROR", "Exception evaluating '" + script + "'",e );
throw e;
}
};
OpenForum.globalExists = function( name ) {
name = name.replace(/
"target="editor" style="color: red" title="The page /OpenForum/Editor?pageName=/g,".").replace(/
does not exist. Click to create it.">/g,".").replace(/
/g,"").replace(/'/g,"").replace(/
(.*
)/g,"");
var parts = name.split(".");
var obj = window;
for(var part in parts) {
if( typeof objpart" alt="partspart" title="partspart"/>] === "undefined" ) return false;
obj = objpart" alt="partspart" title="partspart"/>];
}
return true;
};
OpenForum.getGlobal = function( name ) {
name = name.replace(/
"target="editor" style="color: red" title="The page /OpenForum/Editor?pageName=/g,".").replace(/
does not exist. Click to create it.">/g,".").replace(/
/g,"").replace(/'/g,"").replace(/
(.*
)/g,"");
var parts = name.split(".");
var obj = window;
for(var part in parts) obj = objpart" alt="partspart" title="partspart"/>];
if(typeof obj === "function") return obj();
else return obj;
};
OpenForum.setGlobal = function( name,value,create ) {
name = name.replace(/
"target="editor" style="color: red" title="The page /OpenForum/Editor?pageName=/g,".").replace(/
does not exist. Click to create it.">/g,".").replace(/
/g,"").replace(/'/g,"");
var parts = name.split(".");
var obj = window;
var i=0;
for(i=0; ii" alt="partsi" title="partsi"/>] === "undefined" && create===true ) obji" alt="partsi" title="partsi"/>] = {};
obj = obji" alt="partsi" title="partsi"/>];
}
obji" alt="partsi" title="partsi"/>] = value;
};
OpenForum.isEqual = function(a,b,depth,maxDepth) {
if(typeof b === undefined || typeof a === undefined) return false;
if(b === null && a === null) return true;
if(b === null || a === null) return false;
if(typeof a !== typeof b) return false;
if(!depth) {
depth=0;
}
if(depth>maxDepth) {
OpenForum.debug( "Maximum depth exceeded in isEqual." );
return true;
}
if(!maxDepth) {
maxDepth = 10;
}
if( typeof a === "object" ) {
if(Array.isArray(a)) {
if(!Array.isArray(b) || a.length!==b.length) return false;
}
if(Array.isArray(b)) {
if(!Array.isArray(a) || a.length!==b.length) return false;
}
for(var i in a) {
if(typeof bi === "undefined") return false;
if( OpenForum.isEqual(ai,bi,depth+1,maxDepth)===false) return false;
}
return true;
} else {
return (a===b);
}
};
OpenForum.copyDifferencesFromTo = function(a,b,depth,minDepth,maxDepth,doDelete) {
if(!minDepth) {
minDepth=1;
}
if(!maxDepth) {
maxDepth = 10;
}
if(!depth) {
depth=1;
}
if(depth>maxDepth) {
OpenForum.debug( "Maximum depth exceeded in isEqual." );
return null;
}
if(doDelete == false && Array.isArray(a) && Array.isArray(b)) {
for(var i in a) {
b.push( ai );
}
return b;
}
if( typeof a === "object" ) {
for(var i in a) {
if( typeof ai == "function" ) { // Do not clone objects with functions
return null;
}
}
for(var i in a) {
if(!bi) {
//If it doesn't exist, create it
if(typeof ai === "object") {
var value;
if(ai==null) value = null;
else if(Array.isArray(ai)) value = OpenForum.copyDifferencesFromTo(ai,,depth+1,minDepth,maxDepth,doDelete);
else value = OpenForum.copyDifferencesFromTo(ai,{},depth+1,minDepth,maxDepth,doDelete);
if(value==null) {
if(depth<=maxDepth) {
bi = ai;
} else {
return null;
}
} else {
bi = value;
}
} else {
bi = ai;
}
} else if( OpenForum.isEqual(ai,bi)===false) {
//If it exists but is not equal, copy differences
var value = OpenForum.copyDifferencesFromTo(ai,bi,depth+1,minDepth,maxDepth,doDelete);
if(value!=null) {
if(depth<=maxDepth) {
bi = value;
} else {
return null;
}
}
}
}
for(var i in b) {
if(typeof ai == "undefined" && typeof bi != "undefined" ) {
if(doDelete) {
delete bi;
} else {
ai = bi;
}
}
}
} else {
return a;
}
return b;
};
OpenForum.clone = function(a) {
var b = {};
if(a.length) b = ;
OpenForum.copyDifferencesFromTo(a,b);
return b;
};
OpenForum.clean = function(a) {
if( typeof a === "object" ) {
for(var i in a) {
if(typeof ai === "object") {
ai = OpenForum.clean(ai);
} else if(typeof ai === "number") {
ai = 0;
} else if(typeof ai === "boolean") {
ai = true;
} else {
ai = "";
}
}
}
return a;
};
OpenForum.addFunctionPrefix = function( fn1, fn2 ) {
var secondFn = ""+fn1;
var firstFunction = "" + fn2;
firstFunction = firstFunction.substring(firstFunction.indexOf("{")+1, firstFunction.lastIndexOf("}")-1 );
secondFn = "f = " + secondFn.substring(0,secondFn.indexOf("{")+1) + " " + firstFunction + " " + secondFn.substring( secondFn.indexOf("{")+1 );
return OpenForum.evaluate( secondFn );
};
OpenForum.addFunctionSuffix = function( fn1, fn2 ) {
var secondFn = ""+fn2;
var firstFunction = "" + fn1;
firstFunction = firstFunction.substring(firstFunction.indexOf("{")+1, firstFunction.lastIndexOf("}")-1 );
secondFn = "f = " + secondFn.substring(0,secondFn.indexOf("{")+1) + " " + firstFunction + " " + secondFn.substring( secondFn.indexOf("{")+1 );
return OpenForum.evaluate( secondFn );
};
OpenForum.setInterval = function(fn,timePeriod,immediate,blocking,doesCallback) {
if(blocking) {
var blocked = false;
if(immediate) {
blocked = true;
try{
if(doesCallback) {
fn( function() {blocked = false;} );
} else {
fn();
blocked = false;
}
} catch (e) {
blocked = false;
}
}
return setInterval( function() {
if(blocked) return;
blocked = true;
try{
if(doesCallback) {
fn( function() {blocked = false;} );
} else {
fn();
blocked = false;
}
} catch (e) {
blocked = false;
}
}, timePeriod );
} else {
if(immediate) {
fn();
return setInterval(fn,timePeriod);
}
}
};
OpenForum.waitFor = function(test,callback,pause,timeout) {
if(!pause) pause=200;
if(!timeout) timeout = new Date().getTime()+30000;
else if( new Date().getTime()>timeout ) throw "Timeout waiting for " + test;
if(test()===true) {
callback();
} else {
setTimeout(
function(test,callback,pause,timeout){
return function() {
OpenForum.waitFor(test,callback,pause,timeout);
};
}(
test,
callback,
pause
),
pause
);
}
};
OpenForum.runAsync = function(fn) {
setTimeout( function() { fn(); },1 );
};
OpenForum.queue = function(process,supplyState) {
var test = OpenForum.queue.ready;
if(!test) test = function() { return true; };
OpenForum.queue.ready = function() { return (!OpenForum.processing); };
var state = {complete: false};
if(supplyState===true) {
OpenForum.queue.ready = function() {
if(state.complete===true) delete OpenForum.processing;
return (state.complete);
};
}
OpenForum.waitFor(
test,
function() {
OpenForum.processing = process;
process(state);
if(!supplyState) {
delete OpenForum.processing;
}
}
);
};
OpenForum.Table = {};
OpenForum.Table.setCell = function(table,row,column,value) {
if(typeof value != "undefined") {
tablerowcolumn = value;
} else {
//Is simple array so value is column
tablerow = column;
}
};
OpenForum.Table.editRow = function(table,index) {
for(var i in table) {
tablei.view = "display: block;";
tablei.edit = "display: none;";
}
tableindex.edit = "display: block;";
tableindex.view = "display: none;";
};
OpenForum.jsonToCsv = function(json,delimiter) {
if(!delimiter) delimiter = "
t";
var csv = "";
if(Array.isArray(json)) {
for(var i in json) {
var row = jsoni;
//add column name row
if(csv.length===0) {
for (var c in row) {
if(csv.length>0) {
csv+=delimiter;
}
csv += c;
}
csv += "
n";
}
//add row
var csvRow = "";
for (var r in row) {
if(csvRow.length>0) {
csvRow+=delimiter;
}
csvRow += rowr;
}
csv += csvRow +"
n";
}
} else if(typeof json === "object") {
for(var name in json) {
csv += name + delimiter + jsonname + "
n";
}
}
return csv;
};
OpenForum.Table.closeTable = function(table) {
for(var i in table) {
tablei.view = "display: block;";
tablei.edit = "display: none;";
}
};
OpenForum.Table.addRow = function(table,templateRow,clean) {
if(!templateRow) {
templateRow = tabletable.length-1;
}
if(!templateRow.view) {
templateRow.view = "display: block;";
templateRow.edit = "display: none;";
}
var newRow = OpenForum.clone( templateRow );
if(clean) {
OpenForum.clean( newRow );
}
table.push( newRow );
OpenForum.Table.editRow(table,table.length-1);
};
OpenForum.Table.removeRow = function(table,index) {
return table.splice(index,1)0;
};
OpenForum.Table.moveRowUp = function(table,index) {
if(index<=0) return;
var row = table.splice(index,1)0;
table.splice(index-1,0,row);
};
OpenForum.Table.moveRowDown = function(table,index) {
if(index>=table.length-1) return;
var row = table.splice(index,1)0;
table.splice(index+1,0,row);
};
OpenForum.Table.applyRowFilter = function(tableName,tableData,fieldName,fieldFilter) {
var table = document.getElementById(tableName);
var filters = ;
var allBlank = true;
if(typeof fieldFilter == "undefined" && fieldName.length) {
//Assume array of filters
filters = fieldName;
for(var i in filters) {
if(filtersi.fieldFilter!="") allBlank = false;
filtersi.query = ".*"+filtersi.fieldFilter+".*";
}
} else {
if(fieldFilter!="") allBlank = false;
filters.push( {fieldName: fieldName, fieldFilter: fieldFilter, query: ".*"+fieldFilter+".*"} );
}
var index = 1;
for(var i in tableData) {
var rowData = tableDatai;
if(allBlank) {
OpenForum.Table.showRow(table,index);
} else {
OpenForum.Table.showRow(table,index);
for(var j in filters) {
if( (filtersj.query != ".*.*") && (""+rowDataj" alt="filtersj" title="filtersj"/>.fieldName]).match(filtersj.query) == null) {
OpenForum.Table.hideRow(table,index);
}
}
}
index++;
}
};
OpenForum.Table.sort = function(tableData,fieldName,ascending) {
tableData.sort(
function(a,b) {
if(ascending) {
if(afieldNamefieldName) return 1;
else return -1;
} else {
if(afieldName>bfieldName) return 1;
else return -1;
}
}
);
};
OpenForum.Table.hideRow = function(table,row) {
var nodes = table.querySelectorAll('tbody tr:nth-child(' + row + ')');
nodes.item(0).style.display = "none";
};
OpenForum.Table.showRow = function(table,row) {
var nodes = table.querySelectorAll('tbody tr:nth-child(' + row + ')');
nodes.item(0).style.display = "";
};
OpenForum.Table.renderTable = function(tableName,tableData) {
var html = "";
html += "";
for(var n in tableData0) {
html += "" + n.replaceAll("_"," ") + " | ";
}
html += "
";
html += "";
for(var r in tableData) {
var row = tableDatar;
html += "";
for(var n in row) {
var cell = rown;
iftypeof n == "string" && n.indexOf("url")!=-1) || (typeof cell == "string" && cell.indexOf("http")!=-1
{
cell = ""+cell+"";
}
html += "" + cell + " | ";
}
html += "
";
}
html+= "";
html+="
";
return html;
};
//==============================================================================================================//
//==============================================================================================================//
//==============================================================================================================//
if(!OpenForum) {
OpenForum = {};
}
OpenForum.Storage = {};
OpenForum.Storage.requestAccess = function() {
document.requestStorageAccess();
};
OpenForum.Storage.get = function(key) {
try{
return localStorage.getItem(key);
} catch(e) {
console.log(e);
}
};
OpenForum.Storage.set = function(key,value) {
try{
localStorage.setItem(key,value);
} catch(e) {
console.log(e);
}
};
OpenForum.Storage.find = function(regex) {
try{
var found = ;
for(var i in localStorage) {
if( i.match(regex)) {
found.push( {key: i, value: localStoragei} );
}
}
return found;
} catch(e) {
console.log(e);
}
};
//==============================================================================================================//
//==============================================================================================================//
//==============================================================================================================//
var OFX = {
fromJson: function( json ) {
if(json.method == "get" ) {
return OFX.get( json.url ).withAction( json.action ).withData( json.data );
} else if(json.method == "post" ) {
return OFX.post( json.url ).withAction( json.action ).withData( json.data );
}
},
clearOfflineCache: function() {
OpenForum.Storage.set("OFX.cache","");
console.log("OFX cache cleared.");
},
sendOfflineCache: function( callback, callbackError ) {
if(navigator.onLine===false) {
return;
}
var cache = OFX.getOfflineCache();
if(cache.length==0) {
return;
}
var request = cache.shift();
OpenForum.Storage.set("OFX.cache",JSON.stringify(cache));
OFX.fromJson( request ).onSuccess( callback ).onError( callbackError ).go(true);
if(cache.length!=0) {
setTimeout( function() { OFX.sendOfflineCache(callback,callbackError); }, 1000 );
}
},
getOfflineCache: function() {
var cache = OpenForum.Storage.get("OFX.cache");
if(cache==null) {
cache = ;
} else {
try{
cache = JSON.parse(cache);
} catch(e) {
console.log("OFX cache error "+e+". Replacing cache.");
cache = ;
}
}
return cache;
},
appendToOfflineCache: function(request) {
var cache = OFX.getOfflineCache();
cache.push( request.toJson() );
OpenForum.Storage.set("OFX.cache",JSON.stringify(cache));
},
get: function(url) {
var GET = function(url) {
var self = this;
var action;
var data;
var callBack;
var callOnError;
self.withAction = function(newAction) {
action = newAction;
return self;
};
self.withData = function(newData) {
data = newData;
return self;
};
self.onSuccess = function(newCallBack) {
callBack = newCallBack;
return self;
};
self.onError = function(newCallOnError) {
callOnError = newCallOnError;
return self;
};
self.toJson = function() {
return {
url: url,
method: "get",
action: action,
data: data,
requestedTime: new Date().getTime()
};
};
self.go = function( withOfflineCache ) {
if(navigator.onLine===false && withOfflineCache) {
OFX.appendToOfflineCache( self );
return true;
}
if(action) {
if(data) {
if(typeof data == "object") {
var dataString = "";
for(var name in data) {
if(dataString.length>0) dataString += "&";
if(typeof dataname == "object") {
dataString += name + "="+ JSON.stringify( dataname );
} else {
dataString += name + "="+ dataname;
}
}
data = dataString;
}
}
var get = JSON.get(url,action,data);
if(callBack) {
get = get.onSuccess( callBack );
}
if(callOnError) {
get = get.onError(callOnError);
}
get.go();
} else {
OpenForum.loadFile(url,callBack);
}
};
};
return new GET(url);
},
post: function(url) {
var POST = function(url) {
var self = this;
var action;
var data;
var callBack;
var callOnError;
self.withAction = function(newAction) {
action = newAction;
return self;
};
self.withData = function(newData) {
data = newData;
return self;
};
self.onSuccess = function(newCallBack) {
callBack = newCallBack;
return self;
};
self.onError = function(newCallOnError) {
callOnError = newCallOnError;
return self;
};
self.toJson = function() {
return {
url: url,
method: "post",
action: action,
data: data,
requestedTime: new Date().getTime()
};
};
self.go = function( withOfflineCache ) {
if(navigator.onLine===false && withOfflineCache) {
OFX.appendToOfflineCache( self );
return true;
}
if(action) {
if(data) {
if(typeof data == "object") {
var dataString = "";
for(var name in data) {
if(dataString.length>0) dataString += "&";
if(typeof dataname == "object") {
dataString += name + "="+ JSON.stringify( dataname );
} else {
dataString += name + "="+ dataname;
}
}
data = dataString;
}
}
var post = JSON.post(url,action,data);
if(callBack) {
post = post.onSuccess( callBack );
}
if(callOnError) {
post = post.onError(callOnError);
}
post.go();
} else {
OpenForum.saveFile(url,data);
}
};
};
return new POST(url);
}
};
//==============================================================================================================//
//==============================================================================================================//
//==============================================================================================================//
if(typeof OpenForum == "undefined") {
OpenForum = {};
}
OpenForum.IntraQ = function( queueName, types ) {
var self = this;
var tabId = "Tab:" + new Date().getTime() + ":" + Math.random();
var lastChecked = 0;
var listeners = ;
if( typeof types == "undefined" ) {
types = ;
}
self.registerAsType = function( type ) {
types.push( type );
};
self.addListener = function(listener) {
listeners.push( listener );
};
var checkForMessages = function() {
var queue = JSON.parse( OpenForum.Storage.get("IntraQ."+queueName) );
var now = new Date().getTime();
var newQ = ;
for(var i in queue) {
var packet = queuei;
if(packet.ts>lastChecked && packet.id != tabId) {
var typeMatch = false;
if(packet.data.types) {
for(var t in types) {
packet.data.types.includes( typest );
typeMatch = true;
break;
}
} else {
typeMatch = true;
}
if( typeMatch == true ) {
for(var l in listeners) {
listenersl(packet.data);
}
}
}
if(now-packet.ts<5000) { //Messages that are older than 5 seconds are not included
newQ.push(packet);
}
}
lastChecked = now;
var owner = JSON.parse( OpenForum.Storage.get("IntraQ."+queueName+".owner") );
if(owner==null) {
owner = {id: tabId, ts: now};
}
if(owner.id == tabId) {
owner.ts = now;
OpenForum.Storage.set("IntraQ."+queueName+".owner", JSON.stringify(owner) );
OpenForum.Storage.set("IntraQ."+queueName, JSON.stringify(newQ) ); //Retire messages that are not new
} else if(now-owner.ts>5000) {
owner.id = tabId; // Take ownership if queue owner has gone
owner.ts = now;
OpenForum.Storage.set("IntraQ."+queueName+".owner", JSON.stringify(owner) );
}
setTimeout( checkForMessages, 500 );
};
self.getTabId = function() {
return tabId;
};
self.send = function( data ) {
var queue = JSON.parse( OpenForum.Storage.get("IntraQ."+queueName) );
if(queue==null) queue = ;
queue.push( {data: data, ts: new Date().getTime(), id: tabId} );
OpenForum.Storage.set("IntraQ."+queueName, JSON.stringify(queue));
};
self.send( { action: "joined", tabId: tabId, types: types } );
checkForMessages();
};
OpenForum.InQ = function() {
var self = this;
var inq = new OpenForum.IntraQ( "inq" );
//TODO Needs to handle lots of different objects and values
//Only ignore those that have just been set to stop a loop back condition
var ignore = null;
var listeners = ;
inq.addListener( function( data) {
if(data.action && data.action=="run") {
OpenForum.evaluate( data.script );
} else if(data.action && data.action=="set") {
ignore = data.name;
OpenForum.evaluate( data.name + " = " + JSON.stringify( data.value ) );
} else if(data.action && data.action=="message") {
inq.notifyListeners( data.message );
}
});
inq.notifyListeners = function(message) {
for( var l in listeners ) {
var listener = listenersl;
if( listener.type == "*" || listener.type == message.type ) {
listener.fn( message );
}
}
};
self.addMessageListener = function( listener, type ) {
listeners.push( {fn: listener, type: type} );
};
self.send = function(message) {
inq.send( { action: "message",tabId: inq.getTabId(),"message": message } );
};
self.run = function( script ) {
inq.send( { action: "run",tabId: inq.getTabId(),"script": script } );
};
self.share = function( name) {
OpenForum.getObject( name ).addListener(
function( obj ) {
if( ignore != obj.getId() ) {
inq.send( { action: "set",tabId: inq.getTabId(),"name": obj.getId(), "value": obj.getValue() } );
} else {
ignore = null;
}
}
);
};
};
OpenForum.addInitialiser( function() {
//inq default. Add ?inq=false to stop
if( OpenForum.getParameter("inq")=="false" == false ) {
OpenForum.inq = new OpenForum.InQ();
}
});
//==============================================================================================================//
//==============================================================================================================//
//==============================================================================================================//
OpenForum.loadGoogleFont = function(fontFamily,weight) {
if(!weight) weight = 400;
OpenForum.loadCSS( "https://fonts.googleapis.com/css2?family="+fontFamily+":wght@"+weight );
};
//==============================================================================================================//
//==============================================================================================================//
//==============================================================================================================//
OpenForum.debugON = false;
OpenForum.setDebugToConsole = function(state) {
if( state === true ) {
OpenForum.debug = function(type,message,exception) {
if(!message) {
message = type;
type = "INFO";
}
console.log( new Date().toLocaleTimeString() + " " + type + " " + message );
if(exception) {
if(exception.stack) {
console.log("Stack trace: " + exception.stack);
} else {
console.log("Exception: " + exception);
}
}
};
OpenForum.stop = function() { debugger; };
OpenForum.debug("INFO","OpenForum Console Debugging now on.");
} else {
OpenForum.debug("INFO","OpenForum Console Debugging now off.");
OpenForum.debug = function(type,message,exception) {};
OpenForum.stop = function(){};
}
OpenForum.debugON = state;
};
OpenForum.stop = function(){};
OpenForum.debug = function(type,message,exception) {};
if( OpenForum.getParameter("debug")=="true" ) {
OpenForum.setDebugToConsole(true);
}
//==============================================================================================================//
//==============================================================================================================//
//==============================================================================================================//
OpenForum.getUserReference = function() {
var userReference = OpenForum.Storage.get("user.reference");
if(userReference==null) {
userReference = "User:"+(""+Math.random()).replace(".","")+":"+new Date().getTime();
OpenForum.Storage.set("user.reference",userReference);
}
return userReference;
};
//==============================================================================================================//
//==============================================================================================================//
//==============================================================================================================//
OpenForum.bind = function( a, b) {
if(typeof b == "function") {
b( OpenForum.getObject( a ).getValue() );
OpenForum.getObject( a ).addListener( function(value) {
b( value.getValue() );
} );
} else {
OpenForum.getObject( b ).setValue( OpenForum.getObject( a ).getValue() );
OpenForum.getObject( a ).addListener( function(value) {
OpenForum.getObject( b ).setValue( value.getValue() );
} );
}
};
//==============================================================================================================//
//==============================================================================================================//
//==============================================================================================================//
if(typeof OpenForum == "undefined") {
OpenForum = { testing: {} };
} else if(typeof OpenForum.testing == "undefined") {
OpenForum.testing = {};
}
OpenForum.testing.showComments = function() {
var filterNone = function() {
return NodeFilter.FILTER_ACCEPT;
};
var iterator = document.createNodeIterator(document.body, NodeFilter.SHOW_COMMENT, filterNone);
var currentNode;
while ( currentNode = iterator.nextNode() ) {
try{
var e = document.createElement("div");
//if(currentNode.nextElementSibling.offsetParent!=null) {
var x = currentNode.nextElementSibling.offsetTop;
var y = currentNode.nextElementSibling.offsetLeft;
e.style.position = "absolute";
e.style.top = x;
e.style.left = y;
e.style.color = "black";
e.style.backgroundColor = "white";
e.style.border = "solid 1px black";
e.style.borderRadius = "8px";
e.style.padding = "2px";
e.style.zIndex = "9999";
//}
e.innerHTML = "comment";
e.title = currentNode.nodeValue;
currentNode.nextElementSibling.insertAdjacentElement('beforeBegin',e);
console.log("Displaying comment " + currentNode.nodeValue);
} catch (ex) {
console.log("Error displaying comment " + ex);
}
}
};
OpenForum.testing.showIds = function() {
var filterNone = function() {
return NodeFilter.FILTER_ACCEPT;
};
var iterator = document.createNodeIterator(document.body, NodeFilter.SHOW_ALL, filterNone);
var currentNode;
while ( currentNode = iterator.nextNode() ) {
try{
if(typeof currentNode.id == "undefined" || currentNode.id == "") continue;
var e = document.createElement("div");
//if(currentNode.nextElementSibling.offsetParent!=null) {
var x = currentNode.offsetTop;
var y = currentNode.offsetLeft;
e.style.position = "absolute";
e.style.top = x;
e.style.left = y;
e.style.color = "black";
e.style.backgroundColor = "cyan";
e.style.border = "solid 1px black";
e.style.borderRadius = "2px";
e.style.padding = "2px";
e.style.zIndex = "9999";
//}
e.innerHTML = "id";
e.title = currentNode.id;
currentNode.insertAdjacentElement('beforeBegin',e);
console.log("Displaying id " + currentNode.id);
} catch (ex) {
console.log("Error displaying id " + ex + " for " +currentNode.id);
}
}
};
OpenForum.testing.showNames = function() {
var filterNone = function() {
return NodeFilter.FILTER_ACCEPT;
};
var iterator = document.createNodeIterator(document.body, NodeFilter.SHOW_ALL, filterNone);
var currentNode;
while ( currentNode = iterator.nextNode() ) {
try{
if(typeof currentNode.name == "undefined" || currentNode.name == "") continue;
var e = document.createElement("div");
//if(currentNode.nextElementSibling.offsetParent!=null) {
var x = currentNode.offsetTop;
var y = currentNode.offsetLeft;
e.style.position = "absolute";
e.style.top = x;
e.style.left = y;
e.style.color = "white";
e.style.backgroundColor = "black";
e.style.border = "solid 1px white";
e.style.borderRadius = "2px";
e.style.padding = "2px";
e.style.zIndex = "9999";
//}
e.innerHTML = "name";
e.title = currentNode.name;
currentNode.insertAdjacentElement('beforeBegin',e);
console.log("Displaying id " + currentNode.id);
} catch (ex) {
console.log("Error displaying id " + ex + " for " +currentNode.id);
}
}
};
OpenForum.testing.readForm = function() {
var data = {};
var is = document.getElementsByTagName("input");
for( var i in is ) {
if( isi.id ) {
if(isi.type == "radio") {
datai" alt=" isi" title=" isi"/>.id ] = isi.checked;
} else {
datai" alt=" isi" title=" isi"/>.id ] = isi.value;
}
} else if( isi.name ) {
if(isi.type == "radio") {
datai" alt=" isi" title=" isi"/>.name ] = isi.checked;
} else {
datai" alt=" isi" title=" isi"/>.name ] = isi.value;
}
}
}
is = document.getElementsByTagName("select");
for( var i in is ) {
if( isi.id ) {
datai" alt=" isi" title=" isi"/>.id ] = isi.value;
} else if( isi.name ) {
datai" alt=" isi" title=" isi"/>.name ] = isi.value;
}
}
return data;
};
OpenForum.testing.writeToForm = function(data) {
for(var i in data) {
try{
var el = document.getElementById(i);
if(typeof el == "undefined") {
el = document.getElementsByName(i)0;
}
if(el.type=="radio") {
if(datai==true) {
el.checked=true;
console.log( i + ".checked = true" );
} else {
el.checked=false;
console.log( i + ".checked = false" );
}
} else {
el.value = datai;
console.log( i + ".value set to " + el.value );
}
} catch(e) {
console.log("In "+i);
console.log("Ex:" + e);
}
}
};
//==============================================================================================================//
//==============================================================================================================//
//==============================================================================================================//
if(!OpenForum) {
OpenForum = {};
}
OpenForum.Input={};
OpenForum.Input.getText = function(elementId) {
var input = document.getElementById( elementId );
return input.value;
};
OpenForum.Input.getSelectedText = function(elementId) {
var input = document.getElementById( elementId );
return input.value.substring(input.selectionStart,input.selectionEnd);
};
OpenForum.Input.hasSelection = function(elementId) {
var input = document.getElementById( elementId );
return input.selectionStart != input.selectionEnd;
};
OpenForum.Input.wrapSelectedText = function ( elementId, startText, endText ) {
var input = document.getElementById( elementId );
var text = input.value.substring(input.selectionStart,input.selectionEnd);
var start = input.value.substring(0,input.selectionStart);
var end = input.value.substring(input.selectionEnd);
input.value = start + startText + text + endText + end;
};
OpenForum.Input.wrapAllText = function ( elementId, startText, endText ) {
var input = document.getElementById( elementId );
var text = input.value;
input.value = startText + text + endText;
};
OpenForum.Input.replaceSelectedText = function ( elementId, replaceWith ) {
var input = document.getElementById( elementId );
var start = input.value.substring(0,input.selectionStart);
var end = input.value.substring(input.selectionEnd);
input.value = start + replaceWith + end;
};
OpenForum.Input.appendAtCursor = function ( elementId, text ) {
var input = document.getElementById( elementId );
var start = input.value.substring(0,input.selectionEnd);
var end = input.value.substring(input.selectionEnd);
input.value = start + text + end;
};
OpenForum.Input.toDateField = function ( date ) {
var value = date.getFullYear()+"-"+(""+(date.getMonth()+1)).padBefore("0",2)+"-"+(""+date.getDate()).padBefore("0",2);
return value;
};
OpenForum.Input.toDateTimeField = function ( date ) {
var value = date.getFullYear()+"-"+(""+(date.getMonth()+1)).padBefore("0",2)+"-"+(""+date.getDate()).padBefore("0",2);
value += "T" + (""+date.getHours() ).padBefore("0",2) + ":" + (""+date.getMinutes() ).padBefore("0",2);
return value;
};
OpenForum.Input.fromDateField = function ( value ) {
var parts = value.split("-");
var newDate = new Date(parts0, parseInt(parts1,10)-1, parts2, 0, 0, 0, 0);
return newDate;
};
OpenForum.Input.fromDateTimeField = function ( value ) {
var parts = value.before("T").split("-");
var newDate = new Date(parts0, parseInt(parts1,10)-1, parts2, 0, 0, 0, 0);
parts = value.after("T").split(":");
newDate.setHours( parseInt( parts0 ) );
newDate.setMinutes( parseInt( parts1 ) );
return newDate;
};
//==============================================================================================================//