Detecting Java version (runnable in browser) with JavaScript? - javascript

I was checking this code provided by Sun that can retrieve a list of the Java Runtime Environments installed on the machine. Here's the code formatted and with some functions removed so it's easier to read:
var deployJava = {
debug: null,
firefoxJavaVersion: null,
returnPage: null,
locale: null,
oldMimeType: 'application/npruntime-scriptable-plugin;DeploymentToolkit',
mimeType: 'application/java-deployment-toolkit',
browserName: null,
browserName2: null,
getJREs: function () {
var list = new Array();
if (deployJava.isPluginInstalled()) {
var plugin = deployJava.getPlugin();
var VMs = plugin.jvms;
for (var i = 0; i < VMs.getLength(); i++) {
list[i] = VMs.get(i).version;
}
} else {
var browser = deployJava.getBrowser();
if (browser == 'MSIE') {
if (deployJava.testUsingActiveX('1.7.0')) {
list[0] = '1.7.0';
} else if (deployJava.testUsingActiveX('1.6.0')) {
list[0] = '1.6.0';
} else if (deployJava.testUsingActiveX('1.5.0')) {
list[0] = '1.5.0';
} else if (deployJava.testUsingActiveX('1.4.2')) {
list[0] = '1.4.2';
} else if (deployJava.testForMSVM()) {
list[0] = '1.1';
}
} else if (browser == 'Netscape Family') {
deployJava.getJPIVersionUsingMimeType();
if (deployJava.firefoxJavaVersion != null) {
list[0] = deployJava.firefoxJavaVersion;
} else if (deployJava.testUsingMimeTypes('1.7')) {
list[0] = '1.7.0';
} else if (deployJava.testUsingMimeTypes('1.6')) {
list[0] = '1.6.0';
} else if (deployJava.testUsingMimeTypes('1.5')) {
list[0] = '1.5.0';
} else if (deployJava.testUsingMimeTypes('1.4.2')) {
list[0] = '1.4.2';
} else if (deployJava.browserName2 == 'Safari') {
if (deployJava.testUsingPluginsArray('1.7.0')) {
list[0] = '1.7.0';
} else if (deployJava.testUsingPluginsArray('1.6')) {
list[0] = '1.6.0';
} else if (deployJava.testUsingPluginsArray('1.5')) {
list[0] = '1.5.0';
} else if (deployJava.testUsingPluginsArray('1.4.2')) {
list[0] = '1.4.2';
}
}
}
}
if (deployJava.debug) {
for (var i = 0; i < list.length; ++i) {
alert('We claim to have detected Java SE ' + list[i]);
}
}
return list;
},
runApplet: function (attributes, parameters, minimumVersion) {
if (minimumVersion == 'undefined' || minimumVersion == null) {
minimumVersion = '1.1';
}
var regex = "^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?$";
var matchData = minimumVersion.match(regex);
if (deployJava.returnPage == null) {
deployJava.returnPage = document.location;
}
if (matchData != null) {
var browser = deployJava.getBrowser();
if ((browser != '?') && ('Safari' != deployJava.browserName2)) {
if (deployJava.versionCheck(minimumVersion + '+')) {
deployJava.writeAppletTag(attributes, parameters);
}
} else {
deployJava.writeAppletTag(attributes, parameters);
}
} else {
if (deployJava.debug) {
alert('Invalid minimumVersion argument to runApplet():' + minimumVersion);
}
}
},
writeAppletTag: function (attributes, parameters) {
var startApplet = '<' + 'applet ';
var params = '';
var endApplet = '<' + '/' + 'applet' + '>';
var addCodeAttribute = true;
for (var attribute in attributes) {
startApplet += (' ' + attribute + '="' + attributes[attribute] + '"');
if (attribute == 'code' || attribute == 'java_code') {
addCodeAttribute = false;
}
}
if (parameters != 'undefined' && parameters != null) {
var codebaseParam = false;
for (var parameter in parameters) {
if (parameter == 'codebase_lookup') {
codebaseParam = true;
}
if (parameter == 'object' || parameter == 'java_object') {
addCodeAttribute = false;
}
params += '<param name="' + parameter + '" value="' + parameters[parameter] + '"/>';
}
if (!codebaseParam) {
params += '<param name="codebase_lookup" value="false"/>';
}
}
if (addCodeAttribute) {
startApplet += (' code="dummy"');
}
startApplet += '>';
document.write(startApplet + '\n' + params + '\n' + endApplet);
},
versionCheck: function (versionPattern) {
var index = 0;
var regex = "^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?(\\*|\\+)?$";
var matchData = versionPattern.match(regex);
if (matchData != null) {
var familyMatch = true;
var patternArray = new Array();
for (var i = 1; i < matchData.length; ++i) {
if ((typeof matchData[i] == 'string') && (matchData[i] != '')) {
patternArray[index] = matchData[i];
index++;
}
}
if (patternArray[patternArray.length - 1] == '+') {
familyMatch = false;
patternArray.length--;
} else {
if (patternArray[patternArray.length - 1] == '*') {
patternArray.length--;
}
}
var list = deployJava.getJREs();
for (var i = 0; i < list.length; ++i) {
if (deployJava.compareVersionToPattern(list[i], patternArray, familyMatch)) {
return true;
}
}
return false;
} else {
alert('Invalid versionPattern passed to versionCheck: ' + versionPattern);
return false;
}
},
isWebStartInstalled: function (minimumVersion) {
var browser = deployJava.getBrowser();
if ((browser == '?') || ('Safari' == deployJava.browserName2)) {
return true;
}
if (minimumVersion == 'undefined' || minimumVersion == null) {
minimumVersion = '1.4.2';
}
var retval = false;
var regex = "^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?$";
var matchData = minimumVersion.match(regex);
if (matchData != null) {
retval = deployJava.versionCheck(minimumVersion + '+');
} else {
if (deployJava.debug) {
alert('Invalid minimumVersion argument to isWebStartInstalled(): ' + minimumVersion);
}
retval = deployJava.versionCheck('1.4.2+');
}
return retval;
},
getJPIVersionUsingMimeType: function () {
for (var i = 0; i < navigator.mimeTypes.length; ++i) {
var s = navigator.mimeTypes[i].type;
var m = s.match(/^application\/x-java-applet;jpi-version=(.*)$/);
if (m != null) {
deployJava.firefoxJavaVersion = m[1];
if ('Opera' != deployJava.browserName2) {
break;
}
}
}
},
isPluginInstalled: function () {
var plugin = deployJava.getPlugin();
if (plugin && plugin.jvms) {
return true;
} else {
return false;
}
},
isPlugin2: function () {
if (deployJava.isPluginInstalled()) {
if (deployJava.versionCheck('1.6.0_10+')) {
try {
return deployJava.getPlugin().isPlugin2();
} catch (err) {}
}
}
return false;
},
allowPlugin: function () {
deployJava.getBrowser();
var ret = ('Safari' != deployJava.browserName2 && 'Opera' != deployJava.browserName2);
return ret;
},
getPlugin: function () {
deployJava.refresh();
var ret = null;
if (deployJava.allowPlugin()) {
ret = document.getElementById('deployJavaPlugin');
}
return ret;
},
compareVersionToPattern: function (version, patternArray, familyMatch) {
var regex = "^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?$";
var matchData = version.match(regex);
if (matchData != null) {
var index = 0;
var result = new Array();
for (var i = 1; i < matchData.length; ++i) {
if ((typeof matchData[i] == 'string') && (matchData[i] != '')) {
result[index] = matchData[i];
index++;
}
}
var l = Math.min(result.length, patternArray.length);
if (familyMatch) {
for (var i = 0; i < l; ++i) {
if (result[i] != patternArray[i]) return false;
}
return true;
} else {
for (var i = 0; i < l; ++i) {
if (result[i] < patternArray[i]) {
return false;
} else if (result[i] > patternArray[i]) {
return true;
}
}
return true;
}
} else {
return false;
}
},
getBrowser: function () {
if (deployJava.browserName == null) {
var browser = navigator.userAgent.toLowerCase();
if (deployJava.debug) {
alert('userAgent -> ' + browser);
}
if (browser.indexOf('msie') != -1) {
deployJava.browserName = 'MSIE';
deployJava.browserName2 = 'MSIE';
} else if (browser.indexOf('iphone') != -1) {
deployJava.browserName = 'Netscape Family';
deployJava.browserName2 = 'iPhone';
} else if (browser.indexOf('firefox') != -1) {
deployJava.browserName = 'Netscape Family';
deployJava.browserName2 = 'Firefox';
} else if (browser.indexOf('chrome') != -1) {
deployJava.browserName = 'Netscape Family';
deployJava.browserName2 = 'Chrome';
} else if (browser.indexOf('safari') != -1) {
deployJava.browserName = 'Netscape Family';
deployJava.browserName2 = 'Safari';
} else if (browser.indexOf('mozilla') != -1) {
deployJava.browserName = 'Netscape Family';
deployJava.browserName2 = 'Other';
} else if (browser.indexOf('opera') != -1) {
deployJava.browserName = 'Netscape Family';
deployJava.browserName2 = 'Opera';
} else {
deployJava.browserName = '?';
deployJava.browserName2 = 'unknown';
}
if (deployJava.debug) {
alert('Detected browser name:' + deployJava.browserName + ', ' + deployJava.browserName2);
}
}
return deployJava.browserName;
},
testUsingActiveX: function (version) {
var objectName = 'JavaWebStart.isInstalled.' + version + '.0';
if (!ActiveXObject) {
if (deployJava.debug) {
alert('Browser claims to be IE, but no ActiveXObject object?');
}
return false;
}
try {
return (new ActiveXObject(objectName) != null);
} catch (exception) {
return false;
}
},
testForMSVM: function () {
var clsid = '{08B0E5C0-4FCB-11CF-AAA5-00401C608500}';
if (typeof oClientCaps != 'undefined') {
var v = oClientCaps.getComponentVersion(clsid, "ComponentID");
if ((v == '') || (v == '5,0,5000,0')) {
return false;
} else {
return true;
}
} else {
return false;
}
},
testUsingMimeTypes: function (version) {
if (!navigator.mimeTypes) {
if (deployJava.debug) {
alert('Browser claims to be Netscape family, but no mimeTypes[] array?');
}
return false;
}
for (var i = 0; i < navigator.mimeTypes.length; ++i) {
s = navigator.mimeTypes[i].type;
var m = s.match(/^application\/x-java-applet\x3Bversion=(1\.8|1\.7|1\.6|1\.5|1\.4\.2)$/);
if (m != null) {
if (deployJava.compareVersions(m[1], version)) {
return true;
}
}
}
return false;
},
testUsingPluginsArray: function (version) {
if ((!navigator.plugins) || (!navigator.plugins.length)) {
return false;
}
var platform = navigator.platform.toLowerCase();
for (var i = 0; i < navigator.plugins.length; ++i) {
s = navigator.plugins[i].description;
if (s.search(/^Java Switchable Plug-in (Cocoa)/) != -1) {
if (deployJava.compareVersions("1.5.0", version)) {
return true;
}
} else if (s.search(/^Java/) != -1) {
if (platform.indexOf('win') != -1) {
if (deployJava.compareVersions("1.5.0", version) || deployJava.compareVersions("1.6.0", version)) {
return true;
}
}
}
}
if (deployJava.compareVersions("1.5.0", version)) {
return true;
}
return false;
},
compareVersions: function (installed, required) {
var a = installed.split('.');
var b = required.split('.');
for (var i = 0; i < a.length; ++i) {
a[i] = Number(a[i]);
}
for (var i = 0; i < b.length; ++i) {
b[i] = Number(b[i]);
}
if (a.length == 2) {
a[2] = 0;
}
if (a[0] > b[0]) return true;
if (a[0] < b[0]) return false;
if (a[1] > b[1]) return true;
if (a[1] < b[1]) return false;
if (a[2] > b[2]) return true;
if (a[2] < b[2]) return false;
return true;
},
enableAlerts: function () {
deployJava.browserName = null;
deployJava.debug = true;
},
writePluginTag: function () {
var browser = deployJava.getBrowser();
if (browser == 'MSIE') {
document.write('<' + 'object classid="clsid:CAFEEFAC-DEC7-0000-0000-ABCDEFFEDCBA" ' + 'id="deployJavaPlugin" width="0" height="0">' + '<' + '/' + 'object' + '>');
} else if (browser == 'Netscape Family' && deployJava.allowPlugin()) {
deployJava.writeEmbedTag();
}
},
refresh: function () {
navigator.plugins.refresh(false);
var browser = deployJava.getBrowser();
if (browser == 'Netscape Family' && deployJava.allowPlugin()) {
var plugin = document.getElementById('deployJavaPlugin');
if (plugin == null) {
deployJava.writeEmbedTag();
}
}
},
writeEmbedTag: function () {
var written = false;
if (navigator.mimeTypes != null) {
for (var i = 0; i < navigator.mimeTypes.length; i++) {
if (navigator.mimeTypes[i].type == deployJava.mimeType) {
if (navigator.mimeTypes[i].enabledPlugin) {
document.write('<' + 'embed id="deployJavaPlugin" type="' + deployJava.mimeType + '" hidden="true" />');
written = true;
}
}
}
if (!written) for (var i = 0; i < navigator.mimeTypes.length; i++) {
if (navigator.mimeTypes[i].type == deployJava.oldMimeType) {
if (navigator.mimeTypes[i].enabledPlugin) {
document.write('<' + 'embed id="deployJavaPlugin" type="' + deployJava.oldMimeType + '" hidden="true" />');
}
}
}
}
},
do_initialize: function () {
deployJava.writePluginTag();
if (deployJava.locale == null) {
var loc = null;
if (loc == null) try {
loc = navigator.userLanguage;
} catch (err) {}
if (loc == null) try {
loc = navigator.systemLanguage;
} catch (err) {}
if (loc == null) try {
loc = navigator.language;
} catch (err) {}
if (loc != null) {
loc.replace("-", "_")
deployJava.locale = loc;
}
}
}
};
deployJava.do_initialize();
But I've read regarding this code:
...if you have both a Sun JRE and
MSJVM installed, the toolkit will
report the Sun JRE version even if
it's disabled and the browser will
actually run MSJVM...
The second problem with that code is that it retrieves a list of the installed JREs, and I only care about the one that will open the Applet I need to deploy inside the browser.
Does someone knows a pure js method to get the version of Java that would run in the browser if I try load an Applet?

Related

How to take the actual written value in html js

I am using the following library to implement multilingualism in my test website. However, there are some shortcomings that are difficult to deal with with my little experience.
The script works in such a way that we have a default language, it is written directly to html and dictionaries are made for other languages(they are at the very end of the js code). Everything works fine except for the title. When we want to switch to the default language, the title does not change, only after reloading the page it changes.
Most likely, the matter is in the following piece of code(184-186 line):
if (langDict["Title"] != null) {
document.title = langDict["Title"];
}
I suppose we need to add else and somehow set for it a value that is written in the html itself, but not which js changed in the translation.
var languative;
(function (languative) {
var phraseIdAttr = "data-phrase-id";
languative.ignoreTags = {
img: "<img />",
br: "<br />",
hr: "<hr />"
};
languative.dictonaries = {
html: {
_id: "html",
_name: "HTML"
},
en: {
_id: "en",
_name: "English"
},
ru: {
_id: "ru",
_name: "Русский - Russian"
},
de: {
_id: "de",
_name: "Deutsche - German"
}
};
languative.selectedDictionary = null;
function getDictionary(langKey) {
langKey = langKey.toLowerCase();
if (langKey in languative.dictonaries)
return languative.dictonaries[langKey];
var sep = langKey.indexOf("-");
if (sep > 0)
langKey = langKey.substring(0, sep);
return languative.dictonaries[langKey];
}
languative.getDictionary = getDictionary;
function getPhrase(phraseId) {
var res = findPhrase(phraseId);
if (res)
return res; else
return phraseId;
}
languative.getPhrase = getPhrase;
function findPhrase(phraseId) {
if ((phraseId == null) || (phraseId == ""))
return null;
if ((languative.selectedDictionary != null) && (phraseId in languative.selectedDictionary))
return languative.selectedDictionary[phraseId];
if (phraseId in languative.dictonaries.html)
return languative.dictonaries.html[phraseId];
return null;
}
languative.findPhrase = findPhrase;
function getYesNo(value) {
if (value === undefined)
return getPhrase("undefined"); else if (value)
return getPhrase("yes"); else
return getPhrase("no");
}
languative.getYesNo = getYesNo;
function getAttr(node, attr) {
var result = (node.getAttribute && node.getAttribute(attr)) || null;
if (!result && node.attributes) {
for (var i = 0; i < node.attributes.length; i++) {
var attrNode = node.attributes[i];
if (attrNode.nodeName === attr)
return attrNode.nodeValue;
}
}
return result;
}
function getDictionaryFromHtml() {
function getNodeValue(node) {
var res = null;
if ("innerHTML" in node) {
res = node["innerHTML"];
} else {
res = node.nodeValue;
}
if (res != null) {
res = res.replace(/\s{2,}/g, ' ');
res = res.replace(/^\s+|\s+$/g, '');
}
return res;
}
function getTagPhrase(tag) {
if (tag.childNodes.length > 1) {
var resPhrase = new Array();
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var chName = chNode.nodeName.toLowerCase();
var chValue = null;
if (chName in languative.ignoreTags)
chValue = languative.ignoreTags[chName]; else
chValue = getNodeValue(chNode);
resPhrase.push(chValue);
}
return resPhrase;
} else {
return getNodeValue(tag);
}
}
var tags = getHtmlTags();
var resDict = new Object();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = getTagPhrase(tag);
if ((phraseId in resDict) && (resDict[phraseId] != phraseValue)) {
console.warn("Different phrases with the same data-phrase-id='" + phraseId + "'\n" + " 1: " + JSON.stringify(resDict[phraseId], null, " ") + "\n 2: " + JSON.stringify(phraseValue, null, " "));
} else {
resDict[phraseId] = phraseValue;
}
}
}
return resDict;
}
languative.getDictionaryFromHtml = getDictionaryFromHtml;
function changeLanguage(langKey) {
function setTagPhrase(tag, phrase) {
if (tag.childNodes.length > 1) {
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var nName = chNode.nodeName.toLowerCase();
if (!(nName in languative.ignoreTags)) {
if ("innerHTML" in chNode) {
chNode["innerHTML"] = " " + phrase[ci] + " ";
} else {
chNode.nodeValue = " " + phrase[ci] + " ";
}
}
}
} else {
tag.innerHTML = " " + phrase + " ";
}
}
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
console.warn("Cannot identify dictionary by key '" + langKey + "'. Default dictionary (" + languative.dictonaries.html._id + ": " + languative.dictonaries.html._name + ") used instead.");
langDict = languative.dictonaries.html;
}
languative.selectedDictionary = langDict;
var tags = getHtmlTags();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = languative.getPhrase(phraseId);
if (phraseValue) {
setTagPhrase(tag, phraseValue);
} else {
console.warn("Phrase not definied in dictionary: data-phrase-id='" + phraseId + "'");
}
}
}
if (langDict["Title"] != null) {
document.title = langDict["Title"];
}
}
languative.changeLanguage = changeLanguage;
function getHtmlTags() {
var res = new Array();
var docTags = document.body.getElementsByTagName("*");
for (var i = 0; i < docTags.length; i++) {
var docTag = docTags[i];
var phraseId = getAttr(docTag, phraseIdAttr);
if (phraseId)
res.push(docTag);
}
return res;
}
var initialized = false;
function init() {
if (!initialized) {
initialized = true;
var htmlDict = languative.getDictionaryFromHtml();
for (var dictKey in htmlDict) {
if (!(dictKey in languative.dictonaries.html)) {
languative.dictonaries.html[dictKey] = htmlDict[dictKey];
}
}
var nav = window.navigator;
languative.changeLanguage(nav.userLanguage || nav.language);
}
}
languative.init = init;
function modifyDictionary(langKey, dictModifications) {
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
languative.dictonaries[langKey.toLowerCase()] = dictModifications;
} else {
for (var dictKey in dictModifications) {
langDict[dictKey] = dictModifications[dictKey];
}
}
}
languative.modifyDictionary = modifyDictionary;
})(languative || (languative = {}));
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', languative.init);
if (window.addEventListener) {
window.addEventListener('load', languative.init, false);
} else {
window.attachEvent('onload', languative.init);
}
languative.modifyDictionary("ru", {
Title: "Заголовок",
firstmessage: "ЭТО ЯЗЫК ПО УМОЛЧАНИЮ",
secondmessage: "КАКОЙ ТО ДРУГОЙ ТЕКСТ",
thirdmessage: "ЧТО ТО ЕЩЕ"
});
languative.modifyDictionary("de", {
Title: "Überschrift",
firstmessage: "Dies ist die Standardsprache",
secondmessage: "JEDER ANDERE TEXT",
thirdmessage: "ETWAS ANDERES"
});
<ul>
<li>English</li>
<li>Russian</li>
<li>German</li>
</ul>
<h1 data-phrase-id="firstmessage">THIS IS THE DEFAULT LANGUAGE</h1>
<span data-phrase-id="secondmessage">ANY OTHER TEXT</span>
<p data-phrase-id="thirdmessage">SOMETHING ELSE</p>
Also on my website there is a feedback form. I would like it to be possible to translate the placeholder values. How to do it?
I got it like this, but is this a good way?
if ((localStorage.getItem("lang") == "de") || (window.navigator.userLanguage == "de") || (window.navigator.language) == "de") {
document.querySelector("input[name=name]").placeholder = "Name";
document.querySelector("input[name=subject]").placeholder = "Thema";
document.querySelector("input[name=message]").placeholder = "Brief";
} else if ((localStorage.getItem("lang") == "ru") || (window.navigator.userLanguage == "ru") || (window.navigator.language) == "ru") {
document.querySelector("input[name=name]").placeholder = "Имя";
document.querySelector("input[name=subject]").placeholder = "Тема";
document.querySelector("input[name=message]").placeholder = "Сообщение";
} else {
document.querySelector("input[name=name]").placeholder = "Name";
document.querySelector("input[name=subject]").placeholder = "Subject";
document.querySelector("input[name=message]").placeholder = "Message";
};
document.querySelector('.lang').onclick = function() {
if ((localStorage.getItem("lang") == "de") || (window.navigator.userLanguage == "de") || (window.navigator.language) == "de") {
document.querySelector("input[name=name]").placeholder = "Name";
document.querySelector("input[name=subject]").placeholder = "Thema";
document.querySelector("input[name=message]").placeholder = "Brief";
} else if ((localStorage.getItem("lang") == "ru") || (window.navigator.userLanguage == "ru") || (window.navigator.language) == "ru") {
document.querySelector("input[name=name]").placeholder = "Имя";
document.querySelector("input[name=subject]").placeholder = "Тема";
document.querySelector("input[name=message]").placeholder = "Сообщение";
} else {
document.querySelector("input[name=name]").placeholder = "Name";
document.querySelector("input[name=subject]").placeholder = "Subject";
document.querySelector("input[name=message]").placeholder = "Message";
};
};
var languative;
(function (languative) {
var phraseIdAttr = "data-phrase-id";
languative.ignoreTags = {
img: "<img />",
br: "<br />",
hr: "<hr />"
};
languative.dictonaries = {
html: {
_id: "html",
_name: "HTML"
},
en: {
_id: "en",
_name: "English"
},
ru: {
_id: "ru",
_name: "Русский - Russian"
},
de: {
_id: "de",
_name: "Deutsche - German"
}
};
languative.selectedDictionary = null;
function getDictionary(langKey) {
langKey = langKey.toLowerCase();
if (langKey in languative.dictonaries)
return languative.dictonaries[langKey];
var sep = langKey.indexOf("-");
if (sep > 0)
langKey = langKey.substring(0, sep);
return languative.dictonaries[langKey];
}
languative.getDictionary = getDictionary;
function getPhrase(phraseId) {
var res = findPhrase(phraseId);
if (res)
return res; else
return phraseId;
}
languative.getPhrase = getPhrase;
function findPhrase(phraseId) {
if ((phraseId == null) || (phraseId == ""))
return null;
if ((languative.selectedDictionary != null) && (phraseId in languative.selectedDictionary))
return languative.selectedDictionary[phraseId];
if (phraseId in languative.dictonaries.html)
return languative.dictonaries.html[phraseId];
return null;
}
languative.findPhrase = findPhrase;
function getYesNo(value) {
if (value === undefined)
return getPhrase("undefined"); else if (value)
return getPhrase("yes"); else
return getPhrase("no");
}
languative.getYesNo = getYesNo;
function getAttr(node, attr) {
var result = (node.getAttribute && node.getAttribute(attr)) || null;
if (!result && node.attributes) {
for (var i = 0; i < node.attributes.length; i++) {
var attrNode = node.attributes[i];
if (attrNode.nodeName === attr)
return attrNode.nodeValue;
}
}
return result;
}
function getDictionaryFromHtml() {
function getNodeValue(node) {
var res = null;
if ("innerHTML" in node) {
res = node["innerHTML"];
} else {
res = node.nodeValue;
}
if (res != null) {
res = res.replace(/\s{2,}/g, ' ');
res = res.replace(/^\s+|\s+$/g, '');
}
return res;
}
function getTagPhrase(tag) {
if (tag.childNodes.length > 1) {
var resPhrase = new Array();
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var chName = chNode.nodeName.toLowerCase();
var chValue = null;
if (chName in languative.ignoreTags)
chValue = languative.ignoreTags[chName]; else
chValue = getNodeValue(chNode);
resPhrase.push(chValue);
}
return resPhrase;
} else {
return getNodeValue(tag);
}
}
var tags = getHtmlTags();
var resDict = new Object();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = getTagPhrase(tag);
if ((phraseId in resDict) && (resDict[phraseId] != phraseValue)) {
console.warn("Different phrases with the same data-phrase-id='" + phraseId + "'\n" + " 1: " + JSON.stringify(resDict[phraseId], null, " ") + "\n 2: " + JSON.stringify(phraseValue, null, " "));
} else {
resDict[phraseId] = phraseValue;
}
}
}
return resDict;
}
languative.getDictionaryFromHtml = getDictionaryFromHtml;
function changeLanguage(langKey) {
function setTagPhrase(tag, phrase) {
if (tag.childNodes.length > 1) {
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var nName = chNode.nodeName.toLowerCase();
if (!(nName in languative.ignoreTags)) {
if ("innerHTML" in chNode) {
chNode["innerHTML"] = " " + phrase[ci] + " ";
} else {
chNode.nodeValue = " " + phrase[ci] + " ";
}
}
}
} else {
tag.innerHTML = " " + phrase + " ";
}
}
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
console.warn("Cannot identify dictionary by key '" + langKey + "'. Default dictionary (" + languative.dictonaries.html._id + ": " + languative.dictonaries.html._name + ") used instead.");
langDict = languative.dictonaries.html;
}
languative.selectedDictionary = langDict;
var tags = getHtmlTags();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = languative.getPhrase(phraseId);
if (phraseValue) {
setTagPhrase(tag, phraseValue);
} else {
console.warn("Phrase not definied in dictionary: data-phrase-id='" + phraseId + "'");
}
}
}
if (langDict["Title"] != null) {
document.title = langDict["Title"];
}
}
languative.changeLanguage = changeLanguage;
function getHtmlTags() {
var res = new Array();
var docTags = document.body.getElementsByTagName("*");
for (var i = 0; i < docTags.length; i++) {
var docTag = docTags[i];
var phraseId = getAttr(docTag, phraseIdAttr);
if (phraseId)
res.push(docTag);
}
return res;
}
var initialized = false;
function init() {
if (!initialized) {
initialized = true;
var htmlDict = languative.getDictionaryFromHtml();
for (var dictKey in htmlDict) {
if (!(dictKey in languative.dictonaries.html)) {
languative.dictonaries.html[dictKey] = htmlDict[dictKey];
}
}
var nav = window.navigator;
languative.changeLanguage(nav.userLanguage || nav.language);
}
}
languative.init = init;
function modifyDictionary(langKey, dictModifications) {
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
languative.dictonaries[langKey.toLowerCase()] = dictModifications;
} else {
for (var dictKey in dictModifications) {
langDict[dictKey] = dictModifications[dictKey];
}
}
}
languative.modifyDictionary = modifyDictionary;
})(languative || (languative = {}));
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', languative.init);
if (window.addEventListener) {
window.addEventListener('load', languative.init, false);
} else {
window.attachEvent('onload', languative.init);
}
languative.modifyDictionary("ru", {
name: "Ваше имя",
email: "Ваш email",
send: "Отправить сообщение"
});
languative.modifyDictionary("de", {
name: "Ihr Name",
email: "Deine E-Mail",
send: "Nachricht senden"
});
ul li{
list-style: none;
}
<ul>
<li>English</li>
<li>Russian</li>
<li>German</li>
</ul>
<form>
<input type="text" name="name" data-phrase-id="name" placeholder="Your name">
<input type="text" name="email" data-phrase-id="email" placeholder="Your email">
<input type="submit" data-phrase-id="send" value="Send message">
</form>
For the first snippet you should just add a dictionary for en containing the Title and it will work, like so:
languative.modifyDictionary("en", {
Title: "Caption",
});
For the second one, there is more work because your script change innerHTML, which is not suitable for your feedback form since it contains only input elements which doesn't have innerHTML, so the script should be modified accordingly, like so:
var languative;
(function (languative) {
var phraseIdAttr = "data-phrase-id";
languative.ignoreTags = {
img: "<img />",
br: "<br />",
hr: "<hr />"
};
languative.dictonaries = {
html: {
_id: "html",
_name: "HTML"
},
en: {
_id: "en",
_name: "English"
},
ru: {
_id: "ru",
_name: "Русский - Russian"
},
de: {
_id: "de",
_name: "Deutsche - German"
}
};
languative.selectedDictionary = null;
function getDictionary(langKey) {
langKey = langKey.toLowerCase();
if (langKey in languative.dictonaries)
return languative.dictonaries[langKey];
var sep = langKey.indexOf("-");
if (sep > 0)
langKey = langKey.substring(0, sep);
return languative.dictonaries[langKey];
}
languative.getDictionary = getDictionary;
function getPhrase(phraseId) {
var res = findPhrase(phraseId);
if (res)
return res; else
return phraseId;
}
languative.getPhrase = getPhrase;
function findPhrase(phraseId) {
if ((phraseId == null) || (phraseId == ""))
return null;
if ((languative.selectedDictionary != null) && (phraseId in languative.selectedDictionary))
return languative.selectedDictionary[phraseId];
if (phraseId in languative.dictonaries.html)
return languative.dictonaries.html[phraseId];
return null;
}
languative.findPhrase = findPhrase;
function getYesNo(value) {
if (value === undefined)
return getPhrase("undefined"); else if (value)
return getPhrase("yes"); else
return getPhrase("no");
}
languative.getYesNo = getYesNo;
function getAttr(node, attr) {
var result = (node.getAttribute && node.getAttribute(attr)) || null;
if (!result && node.attributes) {
for (var i = 0; i < node.attributes.length; i++) {
var attrNode = node.attributes[i];
if (attrNode.nodeName === attr)
return attrNode.nodeValue;
}
}
return result;
}
function getDictionaryFromHtml() {
function getNodeValue(node) {
var res = null;
if (node.tagName !== 'INPUT') {
if ("innerHTML" in node) {
res = node["innerHTML"];
} else {
res = node.nodeValue;
}
} else {
res = node.getAttribute("placeholder") || node.value;
}
if (res != null) {
res = res.replace(/\s{2,}/g, ' ');
res = res.replace(/^\s+|\s+$/g, '');
}
return res;
}
function getTagPhrase(tag) {
if (tag.childNodes.length > 1) {
var resPhrase = new Array();
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var chName = chNode.nodeName.toLowerCase();
var chValue = null;
if (chName in languative.ignoreTags)
chValue = languative.ignoreTags[chName]; else
chValue = getNodeValue(chNode);
resPhrase.push(chValue);
}
return resPhrase;
} else {
return getNodeValue(tag);
}
}
var tags = getHtmlTags();
var resDict = new Object();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = getTagPhrase(tag);
if ((phraseId in resDict) && (resDict[phraseId] != phraseValue)) {
console.warn("Different phrases with the same data-phrase-id='" + phraseId + "'\n" + " 1: " + JSON.stringify(resDict[phraseId], null, " ") + "\n 2: " + JSON.stringify(phraseValue, null, " "));
} else {
resDict[phraseId] = phraseValue;
}
}
}
return resDict;
}
languative.getDictionaryFromHtml = getDictionaryFromHtml;
function changeLanguage(langKey) {
function setTagPhrase(tag, phrase) {
if (tag.childNodes.length > 1) {
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var nName = chNode.nodeName.toLowerCase();
if (!(nName in languative.ignoreTags)) {
console.log(chNode.tagName)
if (chNode.tagType !== 'INPUT') {
if ("innerHTML" in chNode) {
chNode["innerHTML"] = " " + phrase[ci] + " ";
} else {
chNode.nodeValue = " " + phrase[ci] + " ";
}
} else {
chNode.hasAttribute("placeholder")
? chNode.setAttribute("placeholder", phrase[ci])
: chNode.value = phrase[ci];
}
}
}
} else {
if (tag.tagName !== 'INPUT') {
tag.innerHTML = " " + phrase + " ";
} else {
tag.hasAttribute("placeholder")
? tag.setAttribute("placeholder", phrase)
: tag.value = phrase;
}
}
}
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
console.warn("Cannot identify dictionary by key '" + langKey + "'. Default dictionary (" + languative.dictonaries.html._id + ": " + languative.dictonaries.html._name + ") used instead.");
langDict = languative.dictonaries.html;
}
languative.selectedDictionary = langDict;
var tags = getHtmlTags();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = languative.getPhrase(phraseId);
if (phraseValue) {
setTagPhrase(tag, phraseValue);
} else {
console.warn("Phrase not definied in dictionary: data-phrase-id='" + phraseId + "'");
}
}
}
if (langDict["Title"] != null) {
document.title = langDict["Title"];
}
}
languative.changeLanguage = changeLanguage;
function getHtmlTags() {
var res = new Array();
var docTags = document.body.getElementsByTagName("*");
for (var i = 0; i < docTags.length; i++) {
var docTag = docTags[i];
var phraseId = getAttr(docTag, phraseIdAttr);
if (phraseId)
res.push(docTag);
}
return res;
}
var initialized = false;
function init() {
if (!initialized) {
initialized = true;
var htmlDict = languative.getDictionaryFromHtml();
for (var dictKey in htmlDict) {
if (!(dictKey in languative.dictonaries.html)) {
languative.dictonaries.html[dictKey] = htmlDict[dictKey];
}
}
var nav = window.navigator;
languative.changeLanguage(nav.userLanguage || nav.language);
}
}
languative.init = init;
function modifyDictionary(langKey, dictModifications) {
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
languative.dictonaries[langKey.toLowerCase()] = dictModifications;
} else {
for (var dictKey in dictModifications) {
langDict[dictKey] = dictModifications[dictKey];
}
}
}
languative.modifyDictionary = modifyDictionary;
})(languative || (languative = {}));
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', languative.init);
if (window.addEventListener) {
window.addEventListener('load', languative.init, false);
} else {
window.attachEvent('onload', languative.init);
}
languative.modifyDictionary("ru", {
name: "Ваше имя",
email: "Ваш email",
send: "Отправить сообщение"
});
languative.modifyDictionary("de", {
name: "Ihr Name",
email: "Deine E-Mail",
send: "Nachricht senden"
});
ul li{
list-style: none;
}
<ul>
<li>English</li>
<li>Russian</li>
<li>German</li>
</ul>
<form>
<input type="text" name="name" data-phrase-id="name" placeholder="Your name">
<input type="text" name="email" data-phrase-id="email" placeholder="Your email">
<input type="submit" data-phrase-id="send" value="Send message">
</form>

xml2json - "X2JS is not defined"

I'm using xml2json for the first time to get an review feed to populate on a website and I keep getting errors such as;
Uncaught ReferenceError: X2JS is not defined
and
Uncaught TypeError: Cannot set property 'X2JS' of undefined
I can't seem to find a solution, this is the code;
jQuery(document).ready(function() {
//below here
//API Feed for Testimonials
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define([], factory);
} else if (typeof exports === "object") {
module.exports = factory();
} else {
root.X2JS = factory();
}
}(this, function () {
return function (config) {
'use strict';
var VERSION = "1.2.0";
config = config || {};
initConfigDefaults();
initRequiredPolyfills();
function initConfigDefaults() {
if(config.escapeMode === undefined) {
config.escapeMode = true;
}
config.attributePrefix = config.attributePrefix || "_";
config.arrayAccessForm = config.arrayAccessForm || "none";
config.emptyNodeForm = config.emptyNodeForm || "text";
if(config.enableToStringFunc === undefined) {
config.enableToStringFunc = true;
}
config.arrayAccessFormPaths = config.arrayAccessFormPaths || [];
if(config.skipEmptyTextNodesForObj === undefined) {
config.skipEmptyTextNodesForObj = true;
}
if(config.stripWhitespaces === undefined) {
config.stripWhitespaces = true;
}
config.datetimeAccessFormPaths = config.datetimeAccessFormPaths || [];
if(config.useDoubleQuotes === undefined) {
config.useDoubleQuotes = false;
}
config.xmlElementsFilter = config.xmlElementsFilter || [];
config.jsonPropertiesFilter = config.jsonPropertiesFilter || [];
if(config.keepCData === undefined) {
config.keepCData = false;
}
}
var DOMNodeTypes = {
ELEMENT_NODE : 1,
TEXT_NODE : 3,
CDATA_SECTION_NODE : 4,
COMMENT_NODE : 8,
DOCUMENT_NODE : 9
};
function initRequiredPolyfills() {
}
function getNodeLocalName( node ) {
var nodeLocalName = node.localName;
if(nodeLocalName == null) // Yeah, this is IE!!
nodeLocalName = node.baseName;
if(nodeLocalName == null || nodeLocalName=="") // =="" is IE too
nodeLocalName = node.nodeName;
return nodeLocalName;
}
function getNodePrefix(node) {
return node.prefix;
}
function escapeXmlChars(str) {
if(typeof(str) == "string")
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, '&apos;');
else
return str;
}
function unescapeXmlChars(str) {
return str.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/&apos;/g, "'").replace(/&/g, '&');
}
function checkInStdFiltersArrayForm(stdFiltersArrayForm, obj, name, path) {
var idx = 0;
for(; idx < stdFiltersArrayForm.length; idx++) {
var filterPath = stdFiltersArrayForm[idx];
if( typeof filterPath === "string" ) {
if(filterPath == path)
break;
}
else
if( filterPath instanceof RegExp) {
if(filterPath.test(path))
break;
}
else
if( typeof filterPath === "function") {
if(filterPath(obj, name, path))
break;
}
}
return idx!=stdFiltersArrayForm.length;
}
function toArrayAccessForm(obj, childName, path) {
switch(config.arrayAccessForm) {
case "property":
if(!(obj[childName] instanceof Array))
obj[childName+"_asArray"] = [obj[childName]];
else
obj[childName+"_asArray"] = obj[childName];
break;
/*case "none":
break;*/
}
if(!(obj[childName] instanceof Array) && config.arrayAccessFormPaths.length > 0) {
if(checkInStdFiltersArrayForm(config.arrayAccessFormPaths, obj, childName, path)) {
obj[childName] = [obj[childName]];
}
}
}
function fromXmlDateTime(prop) {
// Implementation based up on http://stackoverflow.com/questions/8178598/xml-datetime-to-javascript-date-object
// Improved to support full spec and optional parts
var bits = prop.split(/[-T:+Z]/g);
var d = new Date(bits[0], bits[1]-1, bits[2]);
var secondBits = bits[5].split("\.");
d.setHours(bits[3], bits[4], secondBits[0]);
if(secondBits.length>1)
d.setMilliseconds(secondBits[1]);
// Get supplied time zone offset in minutes
if(bits[6] && bits[7]) {
var offsetMinutes = bits[6] * 60 + Number(bits[7]);
var sign = /\d\d-\d\d:\d\d$/.test(prop)? '-' : '+';
// Apply the sign
offsetMinutes = 0 + (sign == '-'? -1 * offsetMinutes : offsetMinutes);
// Apply offset and local timezone
d.setMinutes(d.getMinutes() - offsetMinutes - d.getTimezoneOffset())
}
else
if(prop.indexOf("Z", prop.length - 1) !== -1) {
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()));
}
// d is now a local time equivalent to the supplied time
return d;
}
function checkFromXmlDateTimePaths(value, childName, fullPath) {
if(config.datetimeAccessFormPaths.length > 0) {
var path = fullPath.split("\.#")[0];
if(checkInStdFiltersArrayForm(config.datetimeAccessFormPaths, value, childName, path)) {
return fromXmlDateTime(value);
}
else
return value;
}
else
return value;
}
function checkXmlElementsFilter(obj, childType, childName, childPath) {
if( childType == DOMNodeTypes.ELEMENT_NODE && config.xmlElementsFilter.length > 0) {
return checkInStdFiltersArrayForm(config.xmlElementsFilter, obj, childName, childPath);
}
else
return true;
}
function parseDOMChildren( node, path ) {
if(node.nodeType == DOMNodeTypes.DOCUMENT_NODE) {
var result = new Object;
var nodeChildren = node.childNodes;
// Alternative for firstElementChild which is not supported in some environments
for(var cidx=0; cidx <nodeChildren.length; cidx++) {
var child = nodeChildren.item(cidx);
if(child.nodeType == DOMNodeTypes.ELEMENT_NODE) {
var childName = getNodeLocalName(child);
result[childName] = parseDOMChildren(child, childName);
}
}
return result;
}
else
if(node.nodeType == DOMNodeTypes.ELEMENT_NODE) {
var result = new Object;
result.__cnt=0;
var nodeChildren = node.childNodes;
// Children nodes
for(var cidx=0; cidx <nodeChildren.length; cidx++) {
var child = nodeChildren.item(cidx); // nodeChildren[cidx];
var childName = getNodeLocalName(child);
if(child.nodeType!= DOMNodeTypes.COMMENT_NODE) {
var childPath = path+"."+childName;
if (checkXmlElementsFilter(result,child.nodeType,childName,childPath)) {
result.__cnt++;
if(result[childName] == null) {
result[childName] = parseDOMChildren(child, childPath);
toArrayAccessForm(result, childName, childPath);
}
else {
if(result[childName] != null) {
if( !(result[childName] instanceof Array)) {
result[childName] = [result[childName]];
toArrayAccessForm(result, childName, childPath);
}
}
(result[childName])[result[childName].length] = parseDOMChildren(child, childPath);
}
}
}
}
// Attributes
for(var aidx=0; aidx <node.attributes.length; aidx++) {
var attr = node.attributes.item(aidx); // [aidx];
result.__cnt++;
result[config.attributePrefix+attr.name]=attr.value;
}
// Node namespace prefix
var nodePrefix = getNodePrefix(node);
if(nodePrefix!=null && nodePrefix!="") {
result.__cnt++;
result.__prefix=nodePrefix;
}
if(result["#text"]!=null) {
result.__text = result["#text"];
if(result.__text instanceof Array) {
result.__text = result.__text.join("\n");
}
//if(config.escapeMode)
// result.__text = unescapeXmlChars(result.__text);
if(config.stripWhitespaces)
result.__text = result.__text.trim();
delete result["#text"];
if(config.arrayAccessForm=="property")
delete result["#text_asArray"];
result.__text = checkFromXmlDateTimePaths(result.__text, childName, path+"."+childName);
}
if(result["#cdata-section"]!=null) {
result.__cdata = result["#cdata-section"];
delete result["#cdata-section"];
if(config.arrayAccessForm=="property")
delete result["#cdata-section_asArray"];
}
if( result.__cnt == 0 && config.emptyNodeForm=="text" ) {
result = '';
}
else
if( result.__cnt == 1 && result.__text!=null ) {
result = result.__text;
}
else
if( result.__cnt == 1 && result.__cdata!=null && !config.keepCData ) {
result = result.__cdata;
}
else
if ( result.__cnt > 1 && result.__text!=null && config.skipEmptyTextNodesForObj) {
if( (config.stripWhitespaces && result.__text=="") || (result.__text.trim()=="")) {
delete result.__text;
}
}
delete result.__cnt;
if( config.enableToStringFunc && (result.__text!=null || result.__cdata!=null )) {
result.toString = function() {
return (this.__text!=null? this.__text:'')+( this.__cdata!=null ? this.__cdata:'');
};
}
return result;
}
else
if(node.nodeType == DOMNodeTypes.TEXT_NODE || node.nodeType == DOMNodeTypes.CDATA_SECTION_NODE) {
return node.nodeValue;
}
}
function startTag(jsonObj, element, attrList, closed) {
var resultStr = "<"+ ( (jsonObj!=null && jsonObj.__prefix!=null)? (jsonObj.__prefix+":"):"") + element;
if(attrList!=null) {
for(var aidx = 0; aidx < attrList.length; aidx++) {
var attrName = attrList[aidx];
var attrVal = jsonObj[attrName];
if(config.escapeMode)
attrVal=escapeXmlChars(attrVal);
resultStr+=" "+attrName.substr(config.attributePrefix.length)+"=";
if(config.useDoubleQuotes)
resultStr+='"'+attrVal+'"';
else
resultStr+="'"+attrVal+"'";
}
}
if(!closed)
resultStr+=">";
else
resultStr+="/>";
return resultStr;
}
function endTag(jsonObj,elementName) {
return "</"+ (jsonObj.__prefix!=null? (jsonObj.__prefix+":"):"")+elementName+">";
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function jsonXmlSpecialElem ( jsonObj, jsonObjField ) {
if((config.arrayAccessForm=="property" && endsWith(jsonObjField.toString(),("_asArray")))
|| jsonObjField.toString().indexOf(config.attributePrefix)==0
|| jsonObjField.toString().indexOf("__")==0
|| (jsonObj[jsonObjField] instanceof Function) )
return true;
else
return false;
}
function jsonXmlElemCount ( jsonObj ) {
var elementsCnt = 0;
if(jsonObj instanceof Object ) {
for( var it in jsonObj ) {
if(jsonXmlSpecialElem ( jsonObj, it) )
continue;
elementsCnt++;
}
}
return elementsCnt;
}
function checkJsonObjPropertiesFilter(jsonObj, propertyName, jsonObjPath) {
return config.jsonPropertiesFilter.length == 0
|| jsonObjPath==""
|| checkInStdFiltersArrayForm(config.jsonPropertiesFilter, jsonObj, propertyName, jsonObjPath);
}
function parseJSONAttributes ( jsonObj ) {
var attrList = [];
if(jsonObj instanceof Object ) {
for( var ait in jsonObj ) {
if(ait.toString().indexOf("__")== -1 && ait.toString().indexOf(config.attributePrefix)==0) {
attrList.push(ait);
}
}
}
return attrList;
}
function parseJSONTextAttrs ( jsonTxtObj ) {
var result ="";
if(jsonTxtObj.__cdata!=null) {
result+="<![CDATA["+jsonTxtObj.__cdata+"]]>";
}
if(jsonTxtObj.__text!=null) {
if(config.escapeMode)
result+=escapeXmlChars(jsonTxtObj.__text);
else
result+=jsonTxtObj.__text;
}
return result;
}
function parseJSONTextObject ( jsonTxtObj ) {
var result ="";
if( jsonTxtObj instanceof Object ) {
result+=parseJSONTextAttrs ( jsonTxtObj );
}
else
if(jsonTxtObj!=null) {
if(config.escapeMode)
result+=escapeXmlChars(jsonTxtObj);
else
result+=jsonTxtObj;
}
return result;
}
function getJsonPropertyPath(jsonObjPath, jsonPropName) {
if (jsonObjPath==="") {
return jsonPropName;
}
else
return jsonObjPath+"."+jsonPropName;
}
function parseJSONArray ( jsonArrRoot, jsonArrObj, attrList, jsonObjPath ) {
var result = "";
if(jsonArrRoot.length == 0) {
result+=startTag(jsonArrRoot, jsonArrObj, attrList, true);
}
else {
for(var arIdx = 0; arIdx < jsonArrRoot.length; arIdx++) {
result+=startTag(jsonArrRoot[arIdx], jsonArrObj, parseJSONAttributes(jsonArrRoot[arIdx]), false);
result+=parseJSONObject(jsonArrRoot[arIdx], getJsonPropertyPath(jsonObjPath,jsonArrObj));
result+=endTag(jsonArrRoot[arIdx],jsonArrObj);
}
}
return result;
}
function parseJSONObject ( jsonObj, jsonObjPath ) {
var result = "";
var elementsCnt = jsonXmlElemCount ( jsonObj );
if(elementsCnt > 0) {
for( var it in jsonObj ) {
if(jsonXmlSpecialElem ( jsonObj, it) || (jsonObjPath!="" && !checkJsonObjPropertiesFilter(jsonObj, it, getJsonPropertyPath(jsonObjPath,it))) )
continue;
var subObj = jsonObj[it];
var attrList = parseJSONAttributes( subObj )
if(subObj == null || subObj == undefined) {
result+=startTag(subObj, it, attrList, true);
}
else
if(subObj instanceof Object) {
if(subObj instanceof Array) {
result+=parseJSONArray( subObj, it, attrList, jsonObjPath );
}
else if(subObj instanceof Date) {
result+=startTag(subObj, it, attrList, false);
result+=subObj.toISOString();
result+=endTag(subObj,it);
}
else {
var subObjElementsCnt = jsonXmlElemCount ( subObj );
if(subObjElementsCnt > 0 || subObj.__text!=null || subObj.__cdata!=null) {
result+=startTag(subObj, it, attrList, false);
result+=parseJSONObject(subObj, getJsonPropertyPath(jsonObjPath,it));
result+=endTag(subObj,it);
}
else {
result+=startTag(subObj, it, attrList, true);
}
}
}
else {
result+=startTag(subObj, it, attrList, false);
result+=parseJSONTextObject(subObj);
result+=endTag(subObj,it);
}
}
}
result+=parseJSONTextObject(jsonObj);
return result;
}
this.parseXmlString = function(xmlDocStr) {
var isIEParser = window.ActiveXObject || "ActiveXObject" in window;
if (xmlDocStr === undefined) {
return null;
}
var xmlDoc;
if (window.DOMParser) {
var parser=new window.DOMParser();
var parsererrorNS = null;
// IE9+ now is here
if(!isIEParser) {
try {
parsererrorNS = parser.parseFromString("INVALID", "text/xml").getElementsByTagName("parsererror")[0].namespaceURI;
}
catch(err) {
parsererrorNS = null;
}
}
try {
xmlDoc = parser.parseFromString( xmlDocStr, "text/xml" );
if( parsererrorNS!= null && xmlDoc.getElementsByTagNameNS(parsererrorNS, "parsererror").length > 0) {
//throw new Error('Error parsing XML: '+xmlDocStr);
xmlDoc = null;
}
}
catch(err) {
xmlDoc = null;
}
}
else {
// IE :(
if(xmlDocStr.indexOf("<?")==0) {
xmlDocStr = xmlDocStr.substr( xmlDocStr.indexOf("?>") + 2 );
}
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(xmlDocStr);
}
return xmlDoc;
};
this.asArray = function(prop) {
if (prop === undefined || prop == null)
return [];
else
if(prop instanceof Array)
return prop;
else
return [prop];
};
this.toXmlDateTime = function(dt) {
if(dt instanceof Date)
return dt.toISOString();
else
if(typeof(dt) === 'number' )
return new Date(dt).toISOString();
else
return null;
};
this.asDateTime = function(prop) {
if(typeof(prop) == "string") {
return fromXmlDateTime(prop);
}
else
return prop;
};
this.xml2json = function (xmlDoc) {
return parseDOMChildren ( xmlDoc );
};
this.xml_str2json = function (xmlDocStr) {
var xmlDoc = this.parseXmlString(xmlDocStr);
if(xmlDoc!=null)
return this.xml2json(xmlDoc);
else
return null;
};
this.json2xml_str = function (jsonObj) {
return parseJSONObject ( jsonObj, "" );
};
this.json2xml = function (jsonObj) {
var xmlDocStr = this.json2xml_str (jsonObj);
return this.parseXmlString(xmlDocStr);
};
this.getVersion = function () {
return VERSION;
};
}
}))
// Create x2js instance with default config
var x2js = new X2JS();
var xmlText = "";
jQuery.getJSON( "https://service1.homepro.com/smart.asmx/GetFAP_ProfileReviewsJSON?bid=141772&sort=1&page=1", function( data ) {
var xmlText = data,
x2js = new X2JS(),
jsonObj = x2js.xml_str2json( xmlText ),
html = '<div class="flex-wrapper">';
// console.log(jsonObj.SMART);
jQuery.each( jsonObj.SMART.XMLJSON, function( key, answer ) {
html += '<div class="flex-shell testimonial">';
html += '<div class="flex-item">';
html += '<div>';
html += '<span class="review-number"><i>' + answer.Quality + '</i> Quality of work</span>' ;
html += '<span class="review-number"><i>' + answer.Time + '</i> Timeliness</span>' ;
html += '<span class="review-number"><i>' + answer.Budget + '</i> Value for Money</span>' ;
html += '<span class="review-number"><i>' + answer.Courtesy + '</i> Courtesy</span>' ;
html += '<span class="review">' + answer.Testimonial + '</span>' ;
html += '<span class="name">' + answer.RefName + ' - ' + answer.refDate + '</span>';
html += '</div>';
html += '</div>';
html += '</div>';
});
jQuery('.start').html(html);
});
//above here
});
Apologies if I've gone about this in the wrong way. I've done;
npm install xml2json
Which didn't flag up any errors but I still can't seem to get the data to load correctly.
Solution that after you import <script> from package x2js, you should use window.X2JS to get constructor of X2JS. Almost packages implementing for both NPM and browser, the browser version usually use via object window, because it is shared and free connected in almost browsers.
This is my demo for the solution: https://jsfiddle.net/huynhsamha/2evdgt7r/
In my demo, I've include package x2js from NPM here https://unpkg.com/x2js#3.2.3/x2js.js
var X2JS = window.X2JS;
var x2js = new X2JS();
const data = {
a: {
b: 1
},
c: [1, 2]
}
console.log(x2js.js2xml(data))
// <a><b>1</b></a><c>1</c><c>2</c>

Refresh Code when Infinite Scroll Is Called

How to I call a JavaScript function when Tumblr's infinite scroll loads more posts?
I figure it would have to be some sort of listener function for when tumblrAutoPager.init us called. I found the infinite scroll code online and don't really understand it.
var tumblrAutoPager = {
url: "http://proto.jp/",
ver: "0.1.7",
rF: true,
gP: {},
pp: null,
ppId: "",
LN: location.hostname,
init: function () {
if ($("autopagerize_icon") || navigator.userAgent.indexOf('iPhone') != -1) return;
var tAP = tumblrAutoPager;
var p = 1;
var lh = location.href;
var lhp = lh.lastIndexOf("/page/");
var lht = lh.lastIndexOf("/tagged/");
if (lhp != -1) {
p = parseInt(lh.slice(lhp + 6));
tAP.LN = lh.slice(7, lhp);
} else if (lht != -1) {
tAP.LN = lh.slice(7);
if (tAP.LN.slice(tAP.LN.length - 1) == "/") tAP.LN = tAP.LN.slice(0, tAP.LN.length - 1);
} else if ("http://" + tAP.LN + "/" != lh) {
return;
};
var gPFncs = [];
gPFncs[0] = function (aE) {
var r = [];
for (var i = 0, l = aE.length; i < l; i++) {
if (aE[i].className == "autopagerize_page_element") {
r = gCE(aE[i]);
break;
}
}
return r;
};
gPFncs[1] = function (aE) {
var r = [];
for (var i = 0, l = aE.length; i < l; i++) {
var arr = aE[i].className ? aE[i].className.split(" ") : null;
if (arr) {
for (var j = 0; j < arr.length; j++) {
arr[j] == "post" ? r.push(aE[i]) : null;
}
}
}
return r;
};
gPFncs[2] = function (aE) {
var r = [];
var tmpId = tAP.ppId ? [tAP.ppId] : ["posts", "main", "container", "content", "apDiv2", "wrapper", "projects"];
for (var i = 0, l = aE.length; i < l; i++) {
for (var j = 0; j < tmpId.length; j++) {
if (aE[i].id == tmpId[j]) {
r = gCE(aE[i]);
tAP.ppId = aE[i].id;
break;
}
}
}
return r;
};
for (var i = 0; i < gPFncs.length; i++) {
var getElems = gPFncs[i](document.body.getElementsByTagName('*'));
if (getElems.length) {
tAP.gP = gPFncs[i];
tAP.pp = getElems[0].parentNode;
break;
}
}
function gCE(pElem) {
var r = [];
for (var i = 0, l = pElem.childNodes.length; i < l; i++) {
r.push(pElem.childNodes.item(i))
}
return r;
}
if (!tAP.pp) {
return;
}
sendRequest.README = {
license: 'Public Domain',
url: 'http://jsgt.org/lib/ajax/ref.htm',
version: 0.516,
author: 'Toshiro Takahashi'
};
function chkAjaBrowser() {
var A, B = navigator.userAgent;
this.bw = {
safari: ((A = B.split('AppleWebKit/')[1]) ? A.split('(')[0].split('.')[0] : 0) >= 124,
konqueror: ((A = B.split('Konqueror/')[1]) ? A.split(';')[0] : 0) >= 3.3,
mozes: ((A = B.split('Gecko/')[1]) ? A.split(' ')[0] : 0) >= 20011128,
opera: ( !! window.opera) && ((typeof XMLHttpRequest) == 'function'),
msie: ( !! window.ActiveXObject) ? ( !! createHttpRequest()) : false
};
return (this.bw.safari || this.bw.konqueror || this.bw.mozes || this.bw.opera || this.bw.msie)
}
function createHttpRequest() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest()
} else {
if (window.ActiveXObject) {
try {
return new ActiveXObject('Msxml2.XMLHTTP')
} catch (B) {
try {
return new ActiveXObject('Microsoft.XMLHTTP')
} catch (A) {
return null
}
}
} else {
return null
}
}
};
function sendRequest(E, R, C, D, F, G, S, A) {
var Q = C.toUpperCase() == 'GET',
H = createHttpRequest();
if (H == null) {
return null
}
if ((G) ? G : false) {
D += ((D.indexOf('?') == -1) ? '?' : '&') + 't=' + (new Date()).getTime()
}
var P = new chkAjaBrowser(),
L = P.bw.opera,
I = P.bw.safari,
N = P.bw.konqueror,
M = P.bw.mozes;
if (typeof E == 'object') {
var J = E.onload;
var O = E.onbeforsetheader
} else {
var J = E;
var O = null
}
if (L || I || M) {
H.onload = function () {
J(H);
H.abort()
}
} else {
H.onreadystatechange = function () {
if (H.readyState == 4) {
J(H);
H.abort()
}
}
}
R = K(R, D);
if (Q) {
D += ((D.indexOf('?') == -1) ? '?' : (R == '') ? '' : '&') + R
}
H.open(C, D, F, S, A);
if ( !! O) {
O(H)
}
B(H);
H.send(R);
function B(T) {
if (!L || typeof T.setRequestHeader == 'function') {
T.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
}
return T
}
function K(X, V) {
var Z = [];
if (typeof X == 'object') {
for (var W in X) {
Y(W, X[W])
}
} else {
if (typeof X == 'string') {
if (X == '') {
return ''
}
if (X.charAt(0) == '&') {
X = X.substring(1, X.length)
}
var T = X.split('&');
for (var W = 0; W < T.length; W++) {
var U = T[W].split('=');
Y(U[0], U[1])
}
}
}
function Y(b, a) {
Z.push(encodeURIComponent(b) + '=' + encodeURIComponent(a))
}
return Z.join('&')
}
return H
}
function addNextPage(oj) {
if (oj.status == 404) {
tAP.remainFlg = false;
return;
}
var d = document.createElement("div");
d.innerHTML = oj.responseText;
var posts = tAP.gP(d.getElementsByTagName("*"));
if (posts.length < 2) {
tAP.rF = false;
return;
}
d = document.createElement("div");
d.className = "tumblrAutoPager_page_info";
tAP.pp.appendChild(d);
for (var i = 0; i < posts.length; i++) {
tAP.pp.appendChild(posts[i]);
}
var footer = $("footer");
footer ? footer.parentNode.appendChild(footer) : null;
tAP.rF = true;
}
watch_scroll();
function watch_scroll() {
var d = document.compatMode == "BackCompat" ? document.body : document.documentElement;
var r = d.scrollHeight - d.clientHeight - (d.scrollTop || document.body.scrollTop);
if (r < d.clientHeight * 2 && tAP.rF) {
tAP.rF = false;
p++;
sendRequest(addNextPage, "", "GET", "http://" + tAP.LN + "/page/" + p, true);
}
setTimeout(arguments.callee, 200);
};
function $(id) {
return document.getElementById(id)
};
},
switchAutoPage: function () {
this.rF = !this.rF;
var aE = document.getElementsByTagName('*');
for (var i = 0, l = aE.length; i < l; i++) {
if (aE[i].className == "tAP_switch") {
aE[i].firstChild.nodeValue = this.rF ? "AutoPage[OFF]" : "AutoPage[ON]";
}
}
}
};
window.addEventListener ? window.addEventListener('load', tumblrAutoPager.init, false) : window.attachEvent ? window.attachEvent("onload", tumblrAutoPager.init) : window.onload = tumblrAutoPager.init;

How can i set customize Form in add event of wdCalender?

i want to set my own customize form in wdCalendar add event like first name last name instead of "what". where in jquery.calendar.js i find quickadd function which one is used when user click on calendar to add event then form appear help of quickadd function but i dont know how to set custom field in this function so please help me
below one is quickadd function of jquery.calender.js
function quickadd(start, end, isallday, pos) {
if ((!option.quickAddHandler && option.quickAddUrl == "") || option.readonly) {
return;
}
var buddle = $("#bbit-cal-buddle");
if (buddle.length == 0) {
var temparr = [];
temparr.push('<div id="bbit-cal-buddle" style="z-index: 180; width: 400px;visibility:hidden;" class="bubble">');
temparr.push('<table class="bubble-table" cellSpacing="0" cellPadding="0"><tbody><tr><td class="bubble-cell-side"><div id="tl1" class="bubble-corner"><div class="bubble-sprite bubble-tl"></div></div>');
temparr.push('<td class="bubble-cell-main"><div class="bubble-top"></div><td class="bubble-cell-side"><div id="tr1" class="bubble-corner"><div class="bubble-sprite bubble-tr"></div></div> <tr><td class="bubble-mid" colSpan="3"><div style="overflow: hidden" id="bubbleContent1"><div><div></div><div class="cb-root">');
temparr.push('<table class="cb-table" cellSpacing="0" cellPadding="0"><tbody><tr><th class="cb-key">');
temparr.push(i18n.xgcalendar.time, ':</th><td class=cb-value><div id="bbit-cal-buddle-timeshow"></div></td></tr><tr><th class="cb-key">');
temparr.push(i18n.xgcalendar.content, ':</th><td class="cb-value"><div class="textbox-fill-wrapper"><div class="textbox-fill-mid"><input id="bbit-cal-what" class="textbox-fill-input"/></div></div><div class="cb-example">');
temparr.push(i18n.xgcalendar.example, '</div></td></tr></tbody></table><input id="bbit-cal-start" type="hidden"/><input id="bbit-cal-end" type="hidden"/><input id="bbit-cal-allday" type="hidden"/><input id="bbit-cal-quickAddBTN" value="');
temparr.push(i18n.xgcalendar.create_event, '" type="button"/> <SPAN id="bbit-cal-editLink" class="lk">');
temparr.push(i18n.xgcalendar.update_detail, ' <StrONG>>></StrONG></SPAN></div></div></div><tr><td><div id="bl1" class="bubble-corner"><div class="bubble-sprite bubble-bl"></div></div><td><div class="bubble-bottom"></div><td><div id="br1" class="bubble-corner"><div class="bubble-sprite bubble-br"></div></div></tr></tbody></table><div id="bubbleClose1" class="bubble-closebutton"></div><div id="prong2" class="prong"><div class=bubble-sprite></div></div></div>');
var tempquickAddHanler = temparr.join("");
temparr = null;
$(document.body).append(tempquickAddHanler);
buddle = $("#bbit-cal-buddle");
var calbutton = $("#bbit-cal-quickAddBTN");
var lbtn = $("#bbit-cal-editLink");
var closebtn = $("#bubbleClose1").click(function() {
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
});
calbutton.click(function(e) {
if (option.isloading) {
return false;
}
option.isloading = true;
var what = $("#bbit-cal-what").val();
var datestart = $("#bbit-cal-start").val();
var dateend = $("#bbit-cal-end").val();
var allday = $("#bbit-cal-allday").val();
var f = /^[^\$\<\>]+$/.test(what);
if (!f) {
alert(i18n.xgcalendar.invalid_title);
$("#bbit-cal-what").focus();
option.isloading = false;
return false;
}
var zone = new Date().getTimezoneOffset() / 60 * -1;
var param = [{ "name": "CalendarTitle", value: what },
{ "name": "CalendarStartTime", value: datestart },
{ "name": "CalendarEndTime", value: dateend },
{ "name": "IsAllDayEvent", value: allday },
{ "name": "timezone", value: zone}];
if (option.extParam) {
for (var pi = 0; pi < option.extParam.length; pi++) {
param[param.length] = option.extParam[pi];
}
}
if (option.quickAddHandler && $.isFunction(option.quickAddHandler)) {
option.quickAddHandler.call(this, param);
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
}
else {
$("#bbit-cal-buddle").css("visibility", "hidden");
var newdata = [];
var tId = -1;
option.onBeforeRequestData && option.onBeforeRequestData(2);
$.post(option.quickAddUrl, param, function(data) {
if (data) {
if (data.IsSuccess == true) {
option.isloading = false;
option.eventItems[tId][0] = data.Data;
option.eventItems[tId][8] = 1;
render();
option.onAfterRequestData && option.onAfterRequestData(2);
}
else {
option.onRequestDataError && option.onRequestDataError(2, data);
option.isloading = false;
option.onAfterRequestData && option.onAfterRequestData(2);
}
}
}, "json");
newdata.push(-1, what);
var sd = strtodate(datestart);
var ed = strtodate(dateend);
var diff = DateDiff("d", sd, ed);
newdata.push(sd, ed, allday == "1" ? 1 : 0, diff > 0 ? 1 : 0, 0);
newdata.push(-1, 0, "", "");
tId = Ind(newdata);
realsedragevent();
render();
}
});
lbtn.click(function(e) {
if (!option.EditCmdhandler) {
alert("EditCmdhandler" + i18n.xgcalendar.i_undefined);
}
else {
if (option.EditCmdhandler && $.isFunction(option.EditCmdhandler)) {
option.EditCmdhandler.call(this, ['0', $("#bbit-cal-what").val(), $("#bbit-cal-start").val(), $("#bbit-cal-end").val(), $("#bbit-cal-allday").val()]);
}
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
}
return false;
});
buddle.mousedown(function(e) { return false });
}
var dateshow = CalDateShow(start, end, !isallday, true);
var off = getbuddlepos(pos.left, pos.top);
if (off.hide) {
$("#prong2").hide()
}
else {
$("#prong2").show()
}
$("#bbit-cal-buddle-timeshow").html(dateshow);
var calwhat = $("#bbit-cal-what").val("");
$("#bbit-cal-allday").val(isallday ? "1" : "0");
$("#bbit-cal-start").val(dateFormat.call(start, i18n.xgcalendar.dateformat.fulldayvalue + " HH:mm"));
$("#bbit-cal-end").val(dateFormat.call(end, i18n.xgcalendar.dateformat.fulldayvalue + " HH:mm"));
buddle.css({ "visibility": "visible", left: off.left, top: off.top });
calwhat.blur().focus(); //add 2010-01-26 blur() fixed chrome
$(document).one("mousedown", function() {
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
});
return false;
}
could i add ajax link on add event and display custom form and add data to database ?
is there any solution of this type to direct open popup as in add event as like open in edit event ?
And Here we go..
just copy paste this code in your jquery.form.js
it will provide you and extra field to input text.
jquery.form.js
<script>
(function($) {
$.fn.ajaxSubmit = function(options) {
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
if (typeof options == 'function')
options = { success: options };
options = $.extend({
url: this.attr('action') || window.location.toString(),
type: this.attr('method') || 'GET'
}, options || {});
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var a = this.formToArray(options.semantic);
if (options.data) {
options.extraData = options.data;
for (var n in options.data) {
if(options.data[n] instanceof Array) {
for (var k in options.data[n])
a.push( { name: n, value: options.data[n][k] } )
}
else
a.push( { name: n, value: options.data[n] } );
}
}
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a);
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null;
}
else
options.data = q;
var $form = this, callbacks = [];
if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
if (options.clearForm) callbacks.push(function() { $form.clearForm(); });
if (!options.dataType && options.target) {
var oldSuccess = options.success || function(){};
callbacks.push(function(data) {
$(options.target).html(data).each(oldSuccess, arguments);
});
}
else if (options.success)
callbacks.push(options.success);
options.success = function(data, status) {
for (var i=0, max=callbacks.length; i < max; i++)
callbacks[i].apply(options, [data, status, $form]);
};
var files = $('input:file', this).fieldValue();
var found = false;
for (var j=0; j < files.length; j++)
if (files[j])
found = true;
if (options.iframe || found) {
if ($.browser.safari && options.closeKeepAlive)
$.get(options.closeKeepAlive, fileUpload);
else
fileUpload();
}
else
$.ajax(options);
this.trigger('form-submit-notify', [this, options]);
return this;
function fileUpload() {
var form = $form[0];
if ($(':input[#name=submit]', form).length) {
alert('Error: Form elements must not be named "submit".');
return;
}
var opts = $.extend({}, $.ajaxSettings, options);
var s = jQuery.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);
var id = 'jqFormIO' + (new Date().getTime());
var $io = $('<iframe id="' + id + '" name="' + id + '" />');
var io = $io[0];
if ($.browser.msie || $.browser.opera)
io.src = 'javascript:false;document.write("");';
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
var xhr = {
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {},
abort: function() {
this.aborted = 1;
$io.attr('src','about:blank');
}
};
var g = opts.global;
if (g && ! $.active++) $.event.trigger("ajaxStart");
if (g) $.event.trigger("ajaxSend", [xhr, opts]);
if (s.beforeSend && s.beforeSend(xhr, s) === false) {
s.global && jQuery.active--;
return;
}
if (xhr.aborted)
return;
var cbInvoked = 0;
var timedOut = 0;
var sub = form.clk;
if (sub) {
var n = sub.name;
if (n && !sub.disabled) {
options.extraData = options.extraData || {};
options.extraData[n] = sub.value;
if (sub.type == "image") {
options.extraData[name+'.x'] = form.clk_x;
options.extraData[name+'.y'] = form.clk_y;
}
}
}
setTimeout(function() {
var t = $form.attr('target'), a = $form.attr('action');
$form.attr({
target: id,
method: 'POST',
action: opts.url
});
if (! options.skipEncodingOverride) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
if (opts.timeout)
setTimeout(function() { timedOut = true; cb(); }, opts.timeout);
var extraInputs = [];
try {
if (options.extraData)
for (var n in options.extraData)
extraInputs.push(
$('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
.appendTo(form)[0]);
$io.appendTo('body');
io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
form.submit();
}
finally {
$form.attr('action', a);
t ? $form.attr('target', t) : $form.removeAttr('target');
$(extraInputs).remove();
}
}, 10);
function cb() {
if (cbInvoked++) return;
io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
var operaHack = 0;
var ok = true;
try {
if (timedOut) throw 'timeout';
var data, doc;
doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
if (doc.body == null && !operaHack && $.browser.opera) {
operaHack = 1;
cbInvoked--;
setTimeout(cb, 100);
return;
}
xhr.responseText = doc.body ? doc.body.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
xhr.getResponseHeader = function(header){
var headers = {'content-type': opts.dataType};
return headers[header];
};
if (opts.dataType == 'json' || opts.dataType == 'script') {
var ta = doc.getElementsByTagName('textarea')[0];
xhr.responseText = ta ? ta.value : xhr.responseText;
}
else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
xhr.responseXML = toXml(xhr.responseText);
}
data = $.httpData(xhr, opts.dataType);
}
catch(e){
ok = false;
$.handleError(opts, xhr, 'error', e);
}
if (ok) {
opts.success(data, 'success');
if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
}
if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
if (g && ! --$.active) $.event.trigger("ajaxStop");
if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');
// clean up
setTimeout(function() {
$io.remove();
xhr.responseXML = null;
}, 100);
};
function toXml(s, doc) {
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else
doc = (new DOMParser()).parseFromString(s, 'text/xml');
return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
};
};
};
$.fn.ajaxForm = function(options) {
return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
$(this).ajaxSubmit(options);
return false;
}).each(function() {
$(":submit,input:image", this).bind('click.form-plugin',function(e) {
var form = this.form;
form.clk = this;
if (this.type == 'image') {
if (e.offsetX != undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
var offset = $(this).offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - this.offsetLeft;
form.clk_y = e.pageY - this.offsetTop;
}
}
// clear form vars
setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 10);
});
});
};
$.fn.ajaxFormUnbind = function() {
this.unbind('submit.form-plugin');
return this.each(function() {
$(":submit,input:image", this).unbind('click.form-plugin');
});
};
$.fn.formToArray = function(semantic) {
var a = [];
if (this.length == 0) return a;
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) return a;
for(var i=0, max=els.length; i < max; i++) {
var el = els[i];
var n = el.name;
if (!n) continue;
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(!el.disabled && form.clk == el)
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
continue;
}
var v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
for(var j=0, jmax=v.length; j < jmax; j++)
a.push({name: n, value: v[j]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: n, value: v});
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle them here
var inputs = form.getElementsByTagName("input");
for(var i=0, max=inputs.length; i < max; i++) {
var input = inputs[i];
var n = input.name;
if(n && !input.disabled && input.type == "image" && form.clk == input)
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
}
return a;
};
$.fn.formSerialize = function(semantic) {
return $.param(this.formToArray(semantic));
};
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) return;
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i=0,max=v.length; i < max; i++)
a.push({name: n, value: v[i]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: this.name, value: v});
});
return $.param(a);
};
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
continue;
v.constructor == Array ? $.merge(val, v) : val.push(v);
}
return val;
};
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (typeof successful == 'undefined') successful = true;
if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1))
return null;
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) return null;
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index+1 : ops.length);
for(var i=(one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
if (one) return v;
a.push(v);
}
}
return a;
}
return el.value;
};
$.fn.clearForm = function() {
return this.each(function() {
$('input,select,textarea', this).clearFields();
});
};
$.fn.clearFields = $.fn.clearInputs = function() {
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (t == 'text' || t == 'password' || tag == 'textarea')
this.value = '';
else if (t == 'checkbox' || t == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
$.fn.resetForm = function() {
return this.each(function() {
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
this.reset();
});
};
$.fn.enable = function(b) {
if (b == undefined) b = true;
return this.each(function() {
this.disabled = !b
});
};
$.fn.selected = function(select) {
if (select == undefined) select = true;
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio')
this.checked = select;
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
});
};
function log() {
if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};
})(jQuery);
</script>

JavaScript TypeError: top.frames.plrf is undefined and Error: Permission denied to access property 'PM'

I have 2 files:
Ruins.js,
RuinsMap.loc.js
The code is pretty big, so I put a link on both files.
The script that runs both files is:
var RuinsPl = function() {
this.help = "#";
this.name = "Руины";
this.id = "Ruins";
this.master = null;
this.menuitem = null;
this.created = false;
this.enabled = true;
this.enabled = true;
this.options = {map: 0, loc: 0, profile: ""};
this.RuinsFrame = 0;
this.contentHTML = "";
this.Start = function(win) {
var This = this;
if (win.document.URL.indexOf("/ruines.php") != -1) {
win.document.getElementById('ione').style.display = "none";
}
if ((win.document.URL.indexOf("/ruines.php") != -1 || (win.document.URL.indexOf("/fbattle.php") != -1 && this.options.map > 0)) && !this.RuinsFrame) {
if (win.document.URL.indexOf("/ruines.php") != -1) {
var regex = /(\d{6,10})" target="_blank">Лог турнира/;
var res = win.document.body.innerHTML.match(regex);
if (res && res.length > 1) {
this.options.map = res[1];
}
this.master.SaveOptions();
}
this.RuinsFrame = 1;
top.document.getElementsByName("main")[0].outerHTML = '<frameset name="ruins" framespacing="0" border="0" frameborder="0" cols="*,400">' +
' <frame name="main" src="main.php?top=' + Math.random() + '">' +
' <frame name="rmap" src="refreshed.html">' +
'</frameset>';
} else if (win.document.URL.indexOf("/ruines_start.php") != -1 && this.RuinsFrame) {
this.RuinsFrame = 0;
top.document.getElementsByName("ruins")[0].outerHTML = '<frame name="main" src="main.php?top=' + Math.random() + '">';
}
if (win.document.URL.indexOf("/ruines_start.php") != -1 && this.options.map > 0) {
this.options.map = 0;
this.master.SaveOptions();
}
if (this.options.map > 0 && this.RuinsFrame) {
var html_doc = win.document.getElementsByTagName("head");
if (html_doc.length > 0)
html_doc = html_doc[0];
else
html_doc = win.document.body;
var js_plugin = win.document.createElement("script");
js_plugin.setAttribute("type", "text/javascript");
js_plugin.setAttribute("src", "http://old-proxy.info/dark/Ruins.js?" + Math.random());
js_plugin.setAttribute("charset", "utf-8");
html_doc.appendChild(js_plugin);
js_plugin = null;
}
}
this.ApplyOptions = function() {
var This = this;
if (this.master != null) {
$(this.master.global_options).each(function() {
if (this.id == This.id) {
if (this.enabled)
This.Enable();
else
This.Disable();
if (!$.isEmptyObject(this.value))
This.options = this.value;
else
This.options = {map:0};
}
})
}
}
this.Enable = function() {
this.enabled = true;
var mi = this.MenuItem();
if (mi != null) {
mi.removeClass("input_pl_off");
}
}
this.Disable = function() {
this.enabled = false;
var mi = this.MenuItem();
if (mi != null) {
mi.addClass("input_pl_off");
}
}
this.MenuItem = function() {
if (this.master != null && this.menuitem == null) {
var This = this;
This.mid = this.master.menu_id;
This.cid = this.master.content_id;
var menu_item = $('<input type="button" value="Руины"/>');
menu_item.bind('click', function() {
if (This.master.Current != This) {
This.master.Current.Dispose();
}
This.master.Current = This;
$(this).css("background-color", "#f0f0f0");
This.ToggleContent();
})
this.menuitem = $(menu_item);
return this.menuitem;
} else
return this.menuitem;
}
this.ToggleContent = function() {
var This = this;
if (!this.created) {
$(this.cid).html(this.contentHTML);
this.created = true;
} else {
$("#ruins_options").toggle();
}
this.master.ResizeFrame();
}
this.Dispose = function() {
this.created = false;
this.MenuItem().css("background-color","");
}
}
http://www.old-proxy.info/dark/RuinsMap.loc.js
and /dark/Ruins.js
(it's a plugin for a game)
I get the next errors: http://clip2net.com/s/6PL9Wc
TypeError: top.frames.plrf is undefined
top.frames.plrf.RefreshMap(loc);
and this one:
Error: Permission denied to access property 'plugin'
if(typeof(top.frames['plugin'])=='undefined')
in LoadEvent.js insert document.domain = "oldbk.com";

Categories