Use node rework css in browser - javascript

I would like to be able to use reworkcss/css in the browser. I downloaded version 2.0.0 from github and installed the needed packages with nmp install. I have tried requireJS (which claims to be able to process the CommonJS Module Format), requiring index.js, but an error occurs regarding "exports" being undefined. I also attempted to condense it using browserify, but this is evidently not what it was intended for. Does anyone know what I should do? I can't use node.js for the project, but need the CSS module's abilities in the browser.

I ended up condensing it by hand. Here's the result, if anyone's interested. It seems to work pretty well. If there are any mistakes, please mention them in a comment so they can be fixed.
/**
* npm modules: reworkcss
* author: TJ Holowaychuk <tj#vision-media.ca>
* license: MIT
* url: https://github.com/reworkcss/css.git
*
* Package condensed for client-side use by Aaron Fjerstad, July 2014.
*/
//Compressed object
var Compressed = function (opts) {
this.options = opts || {};
//Emit 'str'
this.emit = function(str) {
return str;
};
//Visit 'node'
this.visit = function(node){
return this[node.type](node);
};
//Map visit over array of 'nodes', optionally using a 'delim'
this.mapVisit = function(nodes, delim){
var buf = '';
delim = delim || '';
for (var i = 0, length = nodes.length; i < length; i++) {
buf += this.visit(nodes[i]);
if (delim && i < length - 1) buf += this.emit(delim);
}
return buf;
};
//Compile 'node'
this.compile = function(node){
return node.stylesheet
.rules.map(this.visit, this)
.join('');
};
//Visit comment node.
this.comment = function(node){
return this.emit('', node.position);
};
//Visit import node.
this.import = function(node){
return this.emit('#import ' + node.import + ';', node.position);
};
//Visit media node.
this.media = function(node){
return this.emit('#media ' + node.media, node.position)
+ this.emit('{')
+ this.mapVisit(node.rules)
+ this.emit('}');
};
//Visit document node.
this.document = function(node){
var doc = '#' + (node.vendor || '') + 'document ' + node.document;
return this.emit(doc, node.position)
+ this.emit('{')
+ this.mapVisit(node.rules)
+ this.emit('}');
};
//Visit charset node.
this.charset = function(node){
return this.emit('#charset ' + node.charset + ';', node.position);
};
//Visit namespace node.
this.namespace = function(node){
return this.emit('#namespace ' + node.namespace + ';', node.position);
};
//Visit supports node.
this.supports = function(node){
return this.emit('#supports ' + node.supports, node.position)
+ this.emit('{')
+ this.mapVisit(node.rules)
+ this.emit('}');
};
//Visit keyframes node.
this.keyframes = function(node){
return this.emit('#'
+ (node.vendor || '')
+ 'keyframes '
+ node.name, node.position)
+ this.emit('{')
+ this.mapVisit(node.keyframes)
+ this.emit('}');
};
//Visit keyframe node.
this.keyframe = function(node){
var decls = node.declarations;
return this.emit(node.values.join(','), node.position)
+ this.emit('{')
+ this.mapVisit(decls)
+ this.emit('}');
};
//Visit page node.
this.page = function(node){
var sel = node.selectors.length
? node.selectors.join(', ')
: '';
return this.emit('#page ' + sel, node.position)
+ this.emit('{')
+ this.mapVisit(node.declarations)
+ this.emit('}');
};
//Visit font-face node.
this['font-face'] = function(node){
return this.emit('#font-face', node.position)
+ this.emit('{')
+ this.mapVisit(node.declarations)
+ this.emit('}');
};
//Visit host node.
this.host = function(node){
return this.emit('#host', node.position)
+ this.emit('{')
+ this.mapVisit(node.rules)
+ this.emit('}');
};
//Visit custom-media node.
this['custom-media'] = function(node){
return this.emit('#custom-media ' + node.name + ' ' + node.media + ';', node.position);
};
//Visit rule node.
this.rule = function(node){
var decls = node.declarations;
if (!decls.length) return '';
return this.emit(node.selectors.join(','), node.position)
+ this.emit('{')
+ this.mapVisit(decls)
+ this.emit('}');
};
//Visit declaration node.
this.declaration = function(node){
return this.emit(node.property + ':' + node.value, node.position) + this.emit(';');
};
};
//Identity object
var Identity = function (opts) {
this.options = opts || {};
//Emit 'str'
this.emit = function(str) {
return str;
};
//Visit 'node'
this.visit = function(node){
return this[node.type](node);
};
//Map visit over array of 'nodes', optionally using a 'delim'
this.mapVisit = function(nodes, delim){
var buf = '';
delim = delim || '';
for (var i = 0, length = nodes.length; i < length; i++) {
buf += this.visit(nodes[i]);
if (delim && i < length - 1) buf += this.emit(delim);
}
return buf;
};
//Compile 'node'.
this.compile = function(node){
return this.stylesheet(node);
};
//Visit stylesheet node.
this.stylesheet = function(node){
return this.mapVisit(node.stylesheet.rules, '\n\n');
};
//Visit comment node.
this.comment = function(node){
return this.emit(this.indent() + '/*' + node.comment + '*/', node.position);
};
//Visit import node.
this.import = function(node){
return this.emit('#import ' + node.import + ';', node.position);
};
//Visit media node.
this.media = function(node){
return this.emit('#media ' + node.media, node.position)
+ this.emit(
' {\n'
+ this.indent(1))
+ this.mapVisit(node.rules, '\n\n')
+ this.emit(
this.indent(-1)
+ '\n}');
};
//Visit document node.
this.document = function(node){
var doc = '#' + (node.vendor || '') + 'document ' + node.document;
return this.emit(doc, node.position)
+ this.emit(
' '
+ ' {\n'
+ this.indent(1))
+ this.mapVisit(node.rules, '\n\n')
+ this.emit(
this.indent(-1)
+ '\n}');
};
//Visit charset node.
this.charset = function(node){
return this.emit('#charset ' + node.charset + ';', node.position);
};
//Visit namespace node.
this.namespace = function(node){
return this.emit('#namespace ' + node.namespace + ';', node.position);
};
//Visit supports node.
this.supports = function(node){
return this.emit('#supports ' + node.supports, node.position)
+ this.emit(
' {\n'
+ this.indent(1))
+ this.mapVisit(node.rules, '\n\n')
+ this.emit(
this.indent(-1)
+ '\n}');
};
//Visit keyframes node.
this.keyframes = function(node){
return this.emit('#' + (node.vendor || '') + 'keyframes ' + node.name, node.position)
+ this.emit(
' {\n'
+ this.indent(1))
+ this.mapVisit(node.keyframes, '\n')
+ this.emit(
this.indent(-1)
+ '}');
};
//Visit keyframe node.
this.keyframe = function(node){
var decls = node.declarations;
return this.emit(this.indent())
+ this.emit(node.values.join(', '), node.position)
+ this.emit(
' {\n'
+ this.indent(1))
+ this.mapVisit(decls, '\n')
+ this.emit(
this.indent(-1)
+ '\n'
+ this.indent() + '}\n');
};
//Visit page node.
this.page = function(node){
var sel = node.selectors.length
? node.selectors.join(', ') + ' '
: '';
return this.emit('#page ' + sel, node.position)
+ this.emit('{\n')
+ this.emit(this.indent(1))
+ this.mapVisit(node.declarations, '\n')
+ this.emit(this.indent(-1))
+ this.emit('\n}');
};
//Visit font-face node.
this['font-face'] = function(node){
return this.emit('#font-face ', node.position)
+ this.emit('{\n')
+ this.emit(this.indent(1))
+ this.mapVisit(node.declarations, '\n')
+ this.emit(this.indent(-1))
+ this.emit('\n}');
};
//Visit host node.
this.host = function(node){
return this.emit('#host', node.position)
+ this.emit(
' {\n'
+ this.indent(1))
+ this.mapVisit(node.rules, '\n\n')
+ this.emit(
this.indent(-1)
+ '\n}');
};
//Visit custom-media node.
this['custom-media'] = function(node){
return this.emit('#custom-media ' + node.name + ' ' + node.media + ';', node.position);
};
//Visit rule node.
this.rule = function(node){
var indent = this.indent();
var decls = node.declarations;
if (!decls.length) return '';
return this.emit(node.selectors.map(function(s){ return indent + s }).join(',\n'), node.position)
+ this.emit(' {\n')
+ this.emit(this.indent(1))
+ this.mapVisit(decls, '\n')
+ this.emit(this.indent(-1))
+ this.emit('\n' + this.indent() + '}');
};
//Visit declaration node.
this.declaration = function(node){
return this.emit(this.indent())
+ this.emit(node.property + ': ' + node.value, node.position)
+ this.emit(';');
};
//Increase, decrease or return current indentation.
this.indent = function(level) {
this.level = this.level || 1;
if (null != level) {
this.level += level;
return '';
}
return Array(this.level).join(this.indentation || ' ');
};
};
//CSS object
var CSS = function () {
var commentre = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//g
/**
* Trim `str`.
*/
var trim = function (str) {
return str ? str.replace(/^\s+|\s+$/g, '') : '';
}
//Adds non-enumerable parent node reference to each node.
var addParent = function (obj, parent) {
var isNode = obj && typeof obj.type === 'string';
var childParent = isNode ? obj : parent;
for (var k in obj) {
var value = obj[k];
if (Array.isArray(value)) {
value.forEach(function(v) { addParent(v, childParent); });
} else if (value && typeof value === 'object') {
addParent(value, childParent);
}
}
if (isNode) {
Object.defineProperty(obj, 'parent', {
configurable: true,
writable: true,
enumerable: false,
value: parent || null
});
}
return obj;
}
//CSS.parse()
this.parse = function(css, options){
options = options || {};
//Positional.
var lineno = 1;
var column = 1;
//Update lineno and column based on 'str'.
function updatePosition(str) {
var lines = str.match(/\n/g);
if (lines) lineno += lines.length;
var i = str.lastIndexOf('\n');
column = ~i ? str.length - i : column + str.length;
}
//Mark position and patch 'node.position'.
function position() {
var start = { line: lineno, column: column };
return function(node){
node.position = new Position(start);
whitespace();
return node;
};
}
//Store position information for a node
function Position(start) {
this.start = start;
this.end = { line: lineno, column: column };
this.source = options.source;
}
//Non-enumerable source string
Position.prototype.content = css;
//Error 'msg'.
function error(msg) {
if (options.silent === true) {
return false;
}
var err = new Error(msg + ' near line ' + lineno + ':' + column);
err.filename = options.source;
err.line = lineno;
err.column = column;
err.source = css;
throw err;
}
//Parse stylesheet.
function stylesheet() {
return {
type: 'stylesheet',
stylesheet: {
rules: rules()
}
};
}
//Opening brace.
function open() {
return match(/^{\s*/);
}
//Closing brace.
function close() {
return match(/^}/);
}
//Parse ruleset.
function rules() {
var node;
var rules = [];
whitespace();
comments(rules);
while (css.length && css.charAt(0) != '}' && (node = atrule() || rule())) {
if (node !== false) {
rules.push(node);
comments(rules);
}
}
return rules;
}
//Match 're' and return captures.
function match(re) {
var m = re.exec(css);
if (!m) return;
var str = m[0];
updatePosition(str);
css = css.slice(str.length);
return m;
}
//Parse whitespace.
function whitespace() {
match(/^\s*/);
}
//Parse comments.
function comments(rules) {
var c;
rules = rules || [];
while (c = comment()) {
if (c !== false) {
rules.push(c);
}
}
return rules;
}
//Parse comment.
function comment() {
var pos = position();
if ('/' != css.charAt(0) || '*' != css.charAt(1)) return;
var i = 2;
while ("" != css.charAt(i) && ('*' != css.charAt(i) || '/' != css.charAt(i + 1))) ++i;
i += 2;
if ("" === css.charAt(i-1)) {
return error('End of comment missing');
}
var str = css.slice(2, i - 2);
column += 2;
updatePosition(str);
css = css.slice(i);
column += 2;
return pos({
type: 'comment',
comment: str
});
}
//Parse selector.
function selector() {
var m = match(/^([^{]+)/);
if (!m) return;
/* #fix Remove all comments from selectors
* http://ostermiller.org/findcomment.html */
return trim(m[0])
.replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, '')
.replace(/(?:"[^"]*"|'[^']*')/g, function(m) {
return m.replace(/,/g, '\u200C');
})
.split(/\s*(?![^(]*\)),\s*/)
.map(function(s) {
return s.replace(/\u200C/g, ',');
});
}
//Parse declaration.
function declaration() {
var pos = position();
// prop
var prop = match(/^(\*?[-#\/\*\\\w]+(\[[0-9a-z_-]+\])?)\s*/);
if (!prop) return;
prop = trim(prop[0]);
// :
if (!match(/^:\s*/)) return error("property missing ':'");
// val
var val = match(/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^\)]*?\)|[^};])+)/);
var ret = pos({
type: 'declaration',
property: prop.replace(commentre, ''),
value: val ? trim(val[0]).replace(commentre, '') : ''
});
// ;
match(/^[;\s]*/);
return ret;
}
//Parse declarations.
function declarations() {
var decls = [];
if (!open()) return error("missing '{'");
comments(decls);
// declarations
var decl;
while (decl = declaration()) {
if (decl !== false) {
decls.push(decl);
comments(decls);
}
}
if (!close()) return error("missing '}'");
return decls;
}
//Parse keyframe.
function keyframe() {
var m;
var vals = [];
var pos = position();
while (m = match(/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/)) {
vals.push(m[1]);
match(/^,\s*/);
}
if (!vals.length) return;
return pos({
type: 'keyframe',
values: vals,
declarations: declarations()
});
}
//Parse keyframes.
function atkeyframes() {
var pos = position();
var m = match(/^#([-\w]+)?keyframes */);
if (!m) return;
var vendor = m[1];
// identifier
var m = match(/^([-\w]+)\s*/);
if (!m) return error("#keyframes missing name");
var name = m[1];
if (!open()) return error("#keyframes missing '{'");
var frame;
var frames = comments();
while (frame = keyframe()) {
frames.push(frame);
frames = frames.concat(comments());
}
if (!close()) return error("#keyframes missing '}'");
return pos({
type: 'keyframes',
name: name,
vendor: vendor,
keyframes: frames
});
}
//Parse supports.
function atsupports() {
var pos = position();
var m = match(/^#supports *([^{]+)/);
if (!m) return;
var supports = trim(m[1]);
if (!open()) return error("#supports missing '{'");
var style = comments().concat(rules());
if (!close()) return error("#supports missing '}'");
return pos({
type: 'supports',
supports: supports,
rules: style
});
}
//Parse host.
function athost() {
var pos = position();
var m = match(/^#host */);
if (!m) return;
if (!open()) return error("#host missing '{'");
var style = comments().concat(rules());
if (!close()) return error("#host missing '}'");
return pos({
type: 'host',
rules: style
});
}
//Parse media.
function atmedia() {
var pos = position();
var m = match(/^#media *([^{]+)/);
if (!m) return;
var media = trim(m[1]);
if (!open()) return error("#media missing '{'");
var style = comments().concat(rules());
if (!close()) return error("#media missing '}'");
return pos({
type: 'media',
media: media,
rules: style
});
}
//Parse custom-media.
function atcustommedia() {
var pos = position();
var m = match(/^#custom-media (--[^\s]+) *([^{;]+);/);
if (!m) return;
return pos({
type: 'custom-media',
name: trim(m[1]),
media: trim(m[2])
});
}
//Parse paged media.
function atpage() {
var pos = position();
var m = match(/^#page */);
if (!m) return;
var sel = selector() || [];
if (!open()) return error("#page missing '{'");
var decls = comments();
// declarations
var decl;
while (decl = declaration()) {
decls.push(decl);
decls = decls.concat(comments());
}
if (!close()) return error("#page missing '}'");
return pos({
type: 'page',
selectors: sel,
declarations: decls
});
}
//Parse document.
function atdocument() {
var pos = position();
var m = match(/^#([-\w]+)?document *([^{]+)/);
if (!m) return;
var vendor = trim(m[1]);
var doc = trim(m[2]);
if (!open()) return error("#document missing '{'");
var style = comments().concat(rules());
if (!close()) return error("#document missing '}'");
return pos({
type: 'document',
document: doc,
vendor: vendor,
rules: style
});
}
//Parse font-face.
function atfontface() {
var pos = position();
var m = match(/^#font-face */);
if (!m) return;
if (!open()) return error("#font-face missing '{'");
var decls = comments();
// declarations
var decl;
while (decl = declaration()) {
decls.push(decl);
decls = decls.concat(comments());
}
if (!close()) return error("#font-face missing '}'");
return pos({
type: 'font-face',
declarations: decls
});
}
//Parse import
var atimport = _compileAtrule('import');
//Parse charset
var atcharset = _compileAtrule('charset');
//Parse namespace
var atnamespace = _compileAtrule('namespace');
//Parse non-block at-rules
function _compileAtrule(name) {
var re = new RegExp('^#' + name + ' *([^;\\n]+);');
return function() {
var pos = position();
var m = match(re);
if (!m) return;
var ret = { type: name };
ret[name] = m[1].trim();
return pos(ret);
}
}
//Parse at rule.
function atrule() {
if (css[0] != '#') return;
return atkeyframes()
|| atmedia()
|| atcustommedia()
|| atsupports()
|| atimport()
|| atcharset()
|| atnamespace()
|| atdocument()
|| atpage()
|| athost()
|| atfontface();
}
//Parse rule.
function rule() {
var pos = position();
var sel = selector();
if (!sel) return error('selector missing');
comments();
return pos({
type: 'rule',
selectors: sel,
declarations: declarations()
});
}
return addParent(stylesheet());
};
//CSS.stringify()
this.stringify = function(node, options){
options = options || {};
var compiler = options.compress
? new Compressed(options)
: new Identity(options);
// source maps
if (options.sourcemap) {
var sourcemaps = require('./source-map-support');
sourcemaps(compiler);
var code = compiler.compile(node);
compiler.applySourceMaps();
return { code: code, map: compiler.map.toJSON() };
}
var code = compiler.compile(node);
return code;
};
};

Related

If evaluation not working properly

I have an if statement that when I print the result in the console, I can see sometimes its true, and sometimes its false.
However, whats inside the IF, its never executed and the resulting array is always empty.
var createQuery = function(viewFields,clientCode) {
return '<View Scope="RecursiveAll">' + viewFields +
'<Query>' +
'<Where>' +
'<And>' +
'<Eq>' +
'<FieldRef Name="ClientCode" />' +
'<Value Type="Text">'+ clientCode + '</Value>' +
'</Eq>' +
'<Neq>' +
'<FieldRef Name="ContentType" />' +
'<Value Type="Computed">Bill Cycle</Value>' +
'</Neq>' +
'</And>' +
'</Where>' +
'</Query>' +
'</View>';
};
var createListItemValues = function(filter) {
return function(listItems,selectProperties) {
var listItemsWithValues = [];
if (listItems) {
var enumerator = listItems.getEnumerator();
while (enumerator.moveNext()) {
var listItem = enumerator.get_current();
var listItemValues = [];
selectProperties
.forEach(function (propertyName) {
var value = listItem.get_item(propertyName);
if (propertyName === "JobCodesMulti") {
jobvalue = "";
value.forEach(function (jobvalues) {
jobvalue += jobvalues.get_lookupValue() + ";";
})
listItemValues[propertyName] = jobvalue;
} else {
listItemValues[propertyName] = value;
}
});
if(filter(listItemValues)){//only push if filter returns true
listItemsWithValues.push(listItemValues);
}
}
}
return listItemsWithValues;
};
};
var processListItemWithValue = function(listItemsWithValues) {
return function(listItem) {
var fileDirRef = listItem["FileRef"];
var id = listItem["ID"];
var title = listItem["Title"];
var serverUrl = _spPageContextInfo.webAbsoluteUrl.replace(_spPageContextInfo.webServerRelativeUrl, "");
var dispFormUrl = serverUrl + "/sites/billing/_layouts/15/DocSetHome.aspx?id=" + fileDirRef;
var parentLink = listItem["FileRef"];
//!!!PLEASE NOTE: made arrayofstrings a local variable
var arrayofstrings = parentLink.split("/");
var billCycleFolderName = arrayofstrings[arrayofstrings.length - 2];
arrayofstrings.pop();
var hyperLink = '' + billCycleFolderName + '';
listItem["Bill Cycle"] = hyperLink;
listItemsWithValues["Document Type"] = getContentTypeOfCurrentItem(listItem.ID.toString());
}
};
function GetRelatedBillingDocumentsFromList(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
$log.info("Retrieving related billing documents for bill cycle with name [" + currentBillCyclePath + "]");
//pass filter function to createListItemValues to get a new function that
// creates filtered list item values
var createFilteredListItemsWithValues = createListItemValues(
function(listItemValues) {
var x1=listItemValues && typeof listItemValues.FileRef === "string" && listItemValues.FileRef.split("/")[4];
var x2= currentBillCyclePath.split("/")[8]
console.log(x1===x2);
return !(//pass filter function to createListItemValues
listItemValues &&
typeof listItemValues.FileRef === "string" &&
listItemValues.FileRef.split("/")[4]
) === currentBillCyclePath.split("/")[8];
}
);
var webUrl = _spPageContextInfo.webAbsoluteUrl;
selectProperties = selectProperties.concat("ContentTypeId");
var viewFields = spService.ConvertSelectPropertiesToViewFields(selectProperties);
// query must return the documents for the same client but in other bill cycles not the current one
var camlQuery = createQuery(viewFields,clientCode);
var billCyclesListId = "{c23bbae4-34f7-494c-8f67-acece3ba60da}";
//return a promise like here so the caller knows if something went wrong
return spService.GetListItems(billCyclesListId, camlQuery, selectProperties)
.then(
function(listItems){
console.log("currentBillCyclePath:",currentBillCyclePath);
var listItemsValues = createFilteredListItemsWithValues
(listItems,selectProperties);
return $q.all(listItemsValues.map(addContentType))
.then(function(){ return listItemsValues; })//finished asynchronously mutating array of listItems
}
).then(
function(listItemsWithValues) {
listItemsWithValues.forEach(processListItemWithValue(listItemsWithValues));
return $q.all(
spService.SpSearchQuery.EnhanceSearchResults(listItemsWithValues, enhanceFunctions)
)
}
)
}
the important lines are: var createFilteredListItemsWithValues and if(filter(listItemValues))
You filter function will always return false because you're checking if a String value equals a boolean value.
!(
listItemValues &&
typeof listItemValues.FileRef === "string" &&
listItemValues.FileRef.split("/")[4]
)
Is a boolean, while
currentBillCyclePath.split("/")[8];
is a string.

Highlight.js and Showdown.js not work together

I am trying to be able to use highlight.js when my preview is enabled
Unable to get the highlightjs to work with my preview using showdown.js
Question: How to get the highlight.js to work with showdown.js
Codepen Demo Note all the .js files and css files are loaded in the codepen settings
I have tried using
$(document).ready(function() {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
});
$("#message").on('keyup paste cut', function() {
var text = document.getElementById('message').value,
target = document.getElementById('showdown'),
converter = new showdown.Converter({
parseImgDimensions: true
}),
html = converter.makeHtml(text);
target.innerHTML = html;
});
Full Script
$(document).ready(function() {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
})
$('#button-link').on('click', function() {
$('#myLink').modal('show');
});
$('#button-image').on('click', function() {
$('#myImage').modal('show');
});
$('#button-smile').on('click', function() {
$('#mySmile').modal('show');
});
$('#myLink').on('shown.bs.modal', function() {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
$('#link_title').val(selectedText);
$('#link_url').val('http://');
});
$('#myImage').on('shown.bs.modal', function() {
$("#image_url").attr("placeholder", "http://www.example.com/image.png");
});
$("#save-image").on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
var counter = findAvailableNumber(textarea);
var replace_word = '![enter image description here]' + '[' + counter + ']';
if (counter == 1) {
if ($('input#image_width').val().length > 0) {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#image_url').val() + ' =' + $('input#image_width').val() + 'x' + $('input#image_height').val();
} else {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#image_url').val();
}
} else {
var add_link = '\n' + ' [' + counter + ']: ' + $('#image_url').val();
}
textarea.value = textarea.value.substring(0, start) + replace_word + textarea.value.substring(end, len) + add_link;
$("#message").trigger('change');
});
$("#save-link").on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
var counter = findAvailableNumber(textarea);
if ($('#link_title').val().length > 0) {
var replace_word = '[' + $('#link_title').val() + ']' + '[' + counter + ']';
} else {
var replace_word = '[enter link description here]' + '[' + counter + ']';
}
if (counter == 1) {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#link_url').val();
} else {
var add_link = '\n' + ' [' + counter + ']: ' + $('#link_url').val();
}
textarea.value = textarea.value.substring(0, start) + replace_word + textarea.value.substring(end, len) + add_link;
$("#message").trigger('change');
});
// Editor Buttons
$('#bold').on('click', function(e) {
text_wrap("message", "**", "**", 'strong text');
});
$('#italic').on('click', function(e) {
text_wrap("message", "*", "*", 'emphasized text');
});
$('#quote').on('click', function(e) {
text_wrap("message", "> ", "", 'Blockquote');
});
$('#code').on('click', function(e) {
code_wrap("message", "", "", 'enter code here');
});
function text_wrap(elementID, openTag, closeTag, message) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
if (selectedText.length > 0) {
replacement = openTag + selectedText + closeTag;
} else {
replacement = openTag + message + closeTag;
}
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
function code_wrap(elementID, openTag, closeTag, message) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
var multiLineReplace = '\n' + openTag;
if (selectedText.length > 0) {
//using regex to replace all instances of `\n` with `\n` + your indent spaces.
replacement = ' ' + openTag + selectedText.replace(/\n/g, multiLineReplace) + closeTag;
} else {
replacement = ' ' + openTag + message + closeTag;
}
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
function findAvailableNumber(textarea) {
var number = 1;
var a = textarea.value;
if (a.indexOf('[1]') > -1) {
//Find lines with links
var matches = a.match(/(^|\n)\s*\[\d+\]:/g);
//Find corresponding numbers
var usedNumbers = matches.map(function(match) {
return parseInt(match.match(/\d+/)[0]);
});
//Find first unused number
var number = 1;
while (true) {
if (usedNumbers.indexOf(number) === -1) {
//Found unused number
return number;
}
number++;
}
}
return number;
}
$("#message").on('keyup paste cut', function() {
var text = document.getElementById('message').value,
target = document.getElementById('showdown'),
converter = new showdown.Converter({
parseImgDimensions: true
}),
html = converter.makeHtml(text);
target.innerHTML = html;
});
$(function() {
$('[data-toggle="tooltip"]').tooltip()
});

Stuck with migrating to youtube api v3

so im trying to make a script for youtube in my psp and when i try to play it crashes.
var YouTube = new Object();
YouTube.rev = 4;
YouTube.SearchDesc = "YouTube by NT and JCRV";
YouTube.Name = "YouTube";
YouTube.Search = function(keyword, page) {
var result = new Object();
result.bypage = 20;
result.start = (page - 1) * result.bypage + 1;
var sortBy = "relevance";
var catSpecified = false;
if (keyword.charAt(0) == '$')
{
var keywordBu = keyword;
var kpos = keyword.indexOf(" ");
var category = keyword.substring(1, kpos);
keyword = keyword.substring(kpos + 1);
catSpecified = true;
}
if (keyword.charAt(0) == '#')
{
sortBy = "published";
}
if (catSpecified == false)
{
c = GetContents('https://www.googleapis.com/youtube/v3/search?q=' + escape(keyword) + '&maxResults=' + result.bypage + '&order=' + sortBy + '&part=snippet&key=AIzaSyD6Bdt4uJP0ewhNtgagGbSszfrYqcx6ydU');
}
else
{
c = GetContents('https://www.googleapis.com/youtube/v3/search?q=' + escape(keyword) + '&maxResults=' + result.bypage + '&order=' + sortBy + '&part=snippet&key=AIzaSyD6Bdt4uJP0ewhNtgagGbSszfrYqcx6ydU');
}
result.total = ext("<openSearch:totalResults>");
result.VideoInfo = new Array();
v = {attr: 2};
v.id = 0;
v.Title = "YouTube Search Help";
v.Description = "#query = search by upload date\n$category query = search in a category";
v.URL = '';
p = 0;
result.VideoInfo.push(v);
while (p = c.indexOf("<entry", p) + 1) {
v = {attr: 2};//neither IDA|npp find this string ...0=RD 1= 2=SRD 3=S
v.id = ext("https://www.googleapis.com/youtube/v3/videos?id=", "&key=AIzaSyD6Bdt4uJP0ewhNtgagGbSszfrYqcx6ydU&part=snippet,contentDetails,statistics,status&forMine=true&type=video");
v.Title = ext("<title type='text'>");
v.Description = ext("content type='text'>") + '\nUploader:' + ext("<name>");
v.CommentCount = ext("statistics.commentCount='") * 1;
v.Tags = ext("keywords>").replace(/,/g, "");
v.LengthSeconds = ext("contentDetails.duration='") * 1;
v.RatingAvg = ext("contentDetails.contentRating='") * 1;
v.RatingCount = ext("statistics.likeCount='") * 1;
v.MylistCount = ext("statistics.favoriteCount='") * 1;
v.ViewCount = ext("statistics.viewCount='") * 1;
v.ThumbnailURL = 'http://i.ytimg.com/vi/' + v.id + '/default.jpg';
v.SaveFilename = v.id + ".flv";
v.URL = 'YouTube.play("' + v.id + '")';
result.VideoInfo.push(v);
}
result.end = result.start - 1 + result.VideoInfo.length;
return result;
}
YouTube.play = function(id) {
var pos;
c = GetContents("http://www.youtube.com/get_video_info?html5=1&video_id=" + id);
//PSPTube.log("\n" + c + "\n");
pos = c.indexOf("url_encoded_fmt_stream_map");
if (pos == -1) {
alert("Can not be played");
return "";
}
c = ext('url_encoded_fmt_stream_map', "&");
p = 0;
c = unescape(c);
var url = c.match(/url=(.+?itag%3D5.*?)[&,]/);
//PSPTube.log("\n" + url + "\n");
url = url[1];
//PSPTube.log("\n" + url + "\n");
pos = url.lastIndexOf("http");
url = url.substr(pos);
url = unescape(url);
//PSPTube.log("\n" + url + "\n");
return url;
}
SiteList.push(YouTube);

cookie is always not set

I am using the following code to set cookie, however, when I use document.cookie in console, it doesn't print the key-value pair I passed via setItem(). Anybody know what is the matter?
var docCookies = {
getItem: function (sKey) {
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sProperties) {
var cookieString = "";
var sExpires = "";
for (var sKey in sProperties){
console.log("inside for");
if (sProperties.hasOwnProperty(sKey)) {
// alert("Key is " + k + ", value is" + target[k]);
console.log("inside if");
cookieString += encodeURIComponent(sKey) + "=" + encodeURIComponent(sProperties[sKey])+"; ";
}
}
console.log("outside for");
document.cookie = cookieString.substring(0,cookieString.length-2);
return true;
},
hasItem: function (sKey) {
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
}
};
var expireDate = (new Date((new Date()).getTime() + (60*24*60*60*1000))).toUTCString();
var sProperties = [];
sProperties['_country'] = _country ;
sProperties['_language'] = _language ;
sProperties['_pageName'] = _pageName ;
sProperties['_products'] = _products ;
sProperties['_events'] = _events ;
sProperties['_server'] = _server ;
sProperties['_href'] = _href ;
sProperties['expires'] = expireDate ;
docCookies.setItem(sProperties);
the cookie you want to save should be an Object
var sProperties = {};

Significance of '&' Symbol in JavaScript

I am currently working on a form that posts data to SAP. I am using JavaScript to invoke a Web Service to do this. I am running into an issue where one of the fields in the form has the value of 'GT&N' and I only get an error when the '&' symbol is present. I have looked on Google but have found nothing in relation the the & Symbol and JavaScript.
Error Message I'm receiving from the Web Page:
Unexpected end of file. Following elements are not closed: Characteristic_Value, RunParameter, Run, Body, Envelope. Line 1, position 2520
**The 'Characteristic_Value' is my field within the form.
Error I see when I debug:
Whenever I do not use the '&' Symbol, everything works great. I also tried using other special charecters and it posts just fine.
There is quite a bit of code to this so I am not going to post all of it unless requested as this is just a general question in regards to the '&' Symbol and JavaScript.
The JavaScript Code
//Create
var WebServer = "http://webserver";
var WebServiceName = "CreateIngredient";
var ScriptType = "Transaction";
var RepeatingTableXMLPath = "/my:myFields/my:CreateIngredient/my:CreateIngredient_Repeat";
// To Call Web service from infopath
function CreateIngredient(theXmlNode) {
//Add parameter into the request
var addBatchRequest = new SOAPClientParameters();
var Addresses = new Array();
var AddressXmlNodes = theXmlNode.selectNodes(RepeatingTableXMLPath);
// Loop for Input Field from Repeating Table
for (var i = 0; i < AddressXmlNodes.length; i++) {
var xPath = AddressXmlNodes[i].getXPath();
// Input field, It can be n number of fields
addBatchRequest.add("Material_description", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Material_description").getValue());
addBatchRequest.add("Base_Unit_of_Measure", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Base_Unit_of_Measure").getValue());
addBatchRequest.add("Material_group", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Material_group").getValue());
addBatchRequest.add("External_Material_Group", AddressXmlNodes[i].selectSingleNode(xPath + "/my:External_Material_Group").getValue());
addBatchRequest.add("Division", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Division").getValue());
addBatchRequest.add("Authorization_Group", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Authorization_Group").getValue());
addBatchRequest.add("Gross_weight", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Gross_weight").getValue());
addBatchRequest.add("Weight_Unit", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Weight_Unit").getValue());
addBatchRequest.add("Net_weight", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Net_weight").getValue());
addBatchRequest.add("Dangerous_Goods_Indicator_Profile", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Dangerous_Goods_Indicator_Profile").getValue());
addBatchRequest.add("Class_number", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Class_number").getValue());
addBatchRequest.add("Characteristic_Value", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Characteristic_Value").getValue().toString());
addBatchRequest.add("Class_number1", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Class_number1").getValue());
addBatchRequest.add("Plant", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Plant").getValue());
addBatchRequest.add("Checking_Group_for_Availability_Check", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Checking_Group_for_Availability_Check").getValue());
addBatchRequest.add("Batch_management_requirement_indicator", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Batch_management_requirement_indicator").getValue());
addBatchRequest.add("Transportation_group", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Transportation_group").getValue());
addBatchRequest.add("Loading_group", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Loading_group").getValue());
addBatchRequest.add("Profit_Center", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Profit_Center").getValue());
addBatchRequest.add("Purchasing_group", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Purchasing_group").getValue());
addBatchRequest.add("Plant-Specific_Material_Status", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Plant-Specific_Material_Status").getValue());
addBatchRequest.add("Tax_indicator_for_material__Purchasing_", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Tax_indicator_for_material__Purchasing_").getValue());
addBatchRequest.add("Indicator___automatic_purchase_order_allowed_", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Indicator___automatic_purchase_order_allowed_").getValue());
addBatchRequest.add("Purchasing_Value_Key", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Purchasing_Value_Key").getValue());
addBatchRequest.add("Storage_location", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Storage_location").getValue());
addBatchRequest.add("Temperature_conditions_indicator", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Temperature_conditions_indicator").getValue());
addBatchRequest.add("Label_type", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Label_type").getValue());
addBatchRequest.add("Label_form", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Label_form").getValue());
addBatchRequest.add("Minimum_remaining_shelf_life", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Minimum_remaining_shelf_life").getValue());
addBatchRequest.add("Total_shelf_life", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Total_shelf_life").getValue());
addBatchRequest.add("Storage_percentage", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Storage_percentage").getValue());
addBatchRequest.add("Documentation_required_indicator", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Documentation_required_indicator").getValue());
addBatchRequest.add("QM_in_Procurement_is_Active", AddressXmlNodes[i].selectSingleNode(xPath + "/my:QM_in_Procurement_is_Active").getValue());
addBatchRequest.add("Control_Key_for_Quality_Management_in_Procurement", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Control_Key_for_Quality_Management_in_Procurement").getValue());
addBatchRequest.add("Valuation_Class", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Valuation_Class").getValue());
addBatchRequest.add("Price_control_indicator", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Price_control_indicator").getValue());
addBatchRequest.add("Price_unit", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Price_unit").getValue());
addBatchRequest.add("Standard_price", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Standard_price").getValue());
addBatchRequest.add("Price_unit_for_valuation_prices_based_on_tax_commercial_law", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Price_unit_for_valuation_prices_based_on_tax_commercial_law").getValue());
addBatchRequest.add("Material-related_origin", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Material-related_origin").getValue());
addBatchRequest.add("Variance_Key", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Variance_Key").getValue());
addBatchRequest.add("Lot_Size_for_Product_Costing", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Lot_Size_for_Product_Costing").getValue());
// Output field has been field with text Retrieving... in Gray color for presentation purpose only
var LogFieldNode = AddressXmlNodes[i].selectSingleNode(xPath + "/my:LogField");
var txtLog = document.getElementById("SV_" + LogFieldNode.getAttribute("SVFormElementId"));
txtLog.value = "Retrieving...";
txtLog.style.color = 'Gray';
// Final web service call parameter
var pl = new SOAPClientParameters();
pl.add("RunParameter", addBatchRequest.toXml());
pl.toXml();
SOAPClient.invoke(WebServer + "/formsservice.svc/basic", "Run", pl, true, CreateIngredient_callBack, i);
}
}
// To display the retrieved result in the proper output fields
function CreateIngredient_callBack(u, xmlresponse, RowNumber) {
var theXmlNode1 = SVFormInternalGetProperXmlNode(SVForms[0]);
var AddressXmlNodes1 = theXmlNode1.selectNodes(RepeatingTableXMLPath);
var xPath = AddressXmlNodes1[RowNumber].getXPath();
var LogFieldNode = AddressXmlNodes1[RowNumber].selectSingleNode(xPath + "/my:LogField");
var txtLog = document.getElementById("SV_" + LogFieldNode.getAttribute("SVFormElementId"));
txtLog.style.color = "";
txtLog.value = "";
if (u == null)
alert("No data retrieved for Row Number " + (RowNumber + 1) + ".");
else {
//Display result in repeating table
if (u.LogField) {
LogFieldNode.setValue(u.LogField);
document.getElementById("SV_" + LogFieldNode.getAttribute("SVFormElementId")).value = u.LogField;
}
}
}
///////////////////// Do not modify below this line ///////////////////////////////
var WsdlResult = null;
//Helping method: To build xml
function SOAPClientParameters() {
var _pl = new Array();
this.add = function (name, value) {
_pl[name] = value;
return _pl;
}
this.toXml = function () {
var xml = "";
for (var p in _pl) {
if (typeof (_pl[p]) != "function")
xml += "<" + p + ">" + _pl[p].toString() + "</" + p + ">";
}
return xml;
}
}
function SOAPClientRepeatingParametersXml(name, values) {
var xml = "";
for (var i = 0; i < values.length; i++) {
xml += "<" + name + ">" + values[i].toString() + "</" + name + ">";
}
return xml;
}
function SOAPClient() { }
SOAPClient.invoke = function (url, method, parameters, async, callback, RowNumber) {
if (async)
SOAPClient._loadWsdl(url, method, parameters, async, callback, RowNumber);
else
return SOAPClient._loadWsdl(url, method, parameters, async, callback, RowNumber);
}
// private: wsdl cache
SOAPClient_cacheWsdl = new Array();
// private: invoke async
SOAPClient._loadWsdl = function (url, method, parameters, async, callback, RowNumber) {
// load from cache?
var wsdl = SOAPClient_cacheWsdl[url];
if (wsdl + "" != "" && wsdl + "" != "undefined")
return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl, RowNumber);
// get wsdl
var xmlHttp = SOAPClient._getXmlHttp();
xmlHttp.open("GET", url + "?wsdl", async);
if (async) {
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4)
SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp, RowNumber);
}
}
xmlHttp.send(null);
if (!async)
return SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp, RowNumber);
}
SOAPClient._onLoadWsdl = function (url, method, parameters, async, callback, req, RowNumber) {
var wsdl = req.responseXML;
SOAPClient_cacheWsdl[url] = wsdl; // save a copy in cache
return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl, RowNumber);
}
SOAPClient._sendSoapRequest = function (url, method, parameters, async, callback, wsdl, RowNumber) {
// get namespace
try {
var ns = "http://servername.com/server/";
// build SOAP request
var sr =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
'xmlns:api="http://IPAddress/Integrics/Enswitch/API" ' +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<" + method + " xmlns=\"" + ns + "\">" +
parameters.toXml() +
"</" + method + "></soap:Body></soap:Envelope>";
// send request
var xmlHttp = SOAPClient._getXmlHttp();
xmlHttp.open("POST", url, async);
var soapaction = ((ns.lastIndexOf("/") != ns.length - 1) ? ns + "/" : ns) + method;
xmlHttp.setRequestHeader("SOAPAction", "http://servername.com/server/I" + ScriptType + "Service/Process(" + WebServiceName + ")");
xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
if (async) {
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4)
SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp, RowNumber);
}
}
xmlHttp.send(sr);
}
catch (ex) { }
if (!async)
return SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp, RowNumber);
}
SOAPClient._onSendSoapRequest = function (method, async, callback, wsdl, req, RowNumber) {
var o = null;
var nd = SOAPClient._getElementsByTagName(req.responseXML, method + "Result");
if (nd.length == 0) {
if (req.responseXML.getElementsByTagName("faultcode").length > 0);
alert(req.responseXML.getElementsByTagName("faultstring") [0].childNodes[0].nodeValue);
}
else
o = SOAPClient._soapresult2object(nd[0], wsdl);
if (callback)
callback(o, req.responseXML, RowNumber);
if (!async)
return o;
}
// private: utils
SOAPClient._getElementsByTagName = function (document, tagName) {
try {
// trying to get node omitting any namespaces (latest versions of MSXML.XMLDocument)
return document.selectNodes(".//*[local-name()=\"" + tagName + "\"]");
}
catch (ex) { }
// old XML parser support
return document.getElementsByTagName(tagName);
}
SOAPClient._soapresult2object = function (node, wsdl) {
return SOAPClient._node2object(node, wsdl);
}
SOAPClient._node2object = function (node, wsdl) {
// null node
if (node == null)
return null;
// text node
if (node.nodeType == 3 || node.nodeType == 4)
return SOAPClient._extractValue(node, wsdl);
// leaf node
if (node.childNodes.length == 1 && (node.childNodes[0].nodeType == 3 || node.childNodes[0].nodeType == 4))
return SOAPClient._node2object(node.childNodes[0], wsdl);
var isarray = SOAPClient._getTypeFromWsdl(node.nodeName, wsdl).toLowerCase().indexOf("arrayof") != -1;
// object node
if (!isarray) {
var obj = null;
if (node.hasChildNodes())
obj = new Object();
for (var i = 0; i < node.childNodes.length; i++) {
var p = SOAPClient._node2object(node.childNodes[i], wsdl);
obj[node.childNodes[i].nodeName] = p;
}
return obj;
}
// list node
else {
// create node ref
var l = new Array();
for (var i = 0; i < node.childNodes.length; i++)
l[l.length] = SOAPClient._node2object(node.childNodes[i], wsdl);
return l;
}
return null;
}
SOAPClient._extractValue = function (node, wsdl) {
var value = node.nodeValue;
switch (SOAPClient._getTypeFromWsdl(node.parentNode.nodeName, wsdl).toLowerCase()) {
default:
case "s:string":
return (value != null) ? value + "" : "";
case "s:boolean":
return value + "" == "true";
case "s:int":
case "s:long":
return (value != null) ? parseInt(value + "", 10) : 0;
case "s:double":
return (value != null) ? parseFloat(value + "") : 0;
case "s:datetime":
if (value == null)
return null;
else {
value = value + "";
value = value.substring(0, value.lastIndexOf("."));
value = value.replace(/T/gi, " ");
value = value.replace(/-/gi, "/");
var d = new Date();
d.setTime(Date.parse(value));
return d;
}
}
}
SOAPClient._getTypeFromWsdl = function (elementname, wsdl) {
var ell = wsdl.getElementsByTagName("s:element"); // IE
if (ell.length == 0)
ell = wsdl.getElementsByTagName("element"); // MOZ
for (var i = 0; i < ell.length; i++) {
if (ell[i].attributes["name"] + "" == "undefined") // IE
{
if (ell[i].attributes.getNamedItem("name") != null && ell[i].attributes.getNamedItem("name").nodeValue == elementname && ell[i].attributes.getNamedItem("type") != null)
return ell[i].attributes.getNamedItem("type").nodeValue;
}
else // MOZ
{
if (ell[i].attributes["name"] != null && ell[i].attributes["name"].value == elementname && ell[i].attributes["type"] != null)
return ell[i].attributes["type"].value;
}
}
return "";
}
// private: xmlhttp factory
SOAPClient._getXmlHttp = function () {
try {
if (window.XDomainRequest) {
var req = new window.XDomainRequest();
if (req.readyState == null) {
req.readyState = 1;
req.addEventListener("load",
function () {
req.readyState = 4;
if (typeof req.onreadystatechange == "function")
req.onreadystatechange();
},
false);
}
return req;
}
}
catch (ex) {
try {
if (window.XMLHttpRequest) {
var req = new XMLHttpRequest();
// some versions of Moz do not support the readyState property and the onreadystate event so we patch it!
if (req.readyState == null) {
req.readyState = 1;
req.addEventListener("load",
function () {
req.readyState = 4;
if (typeof req.onreadystatechange == "function")
req.onreadystatechange();
},
false);
}
return req;
}
}
catch (ex) {
try {
// Internet Explorer
if (window.ActiveXObject)
return new ActiveXObject("Msxml2.XMLHTTP"); //ActiveXObject(SOAPClient._getXmlHttpProgID());
} catch (e) {
// Firefox, Opera 8.0+, Safari
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
}
}
SOAPClient._getXmlHttpProgID = function () {
if (SOAPClient._getXmlHttpProgID.progid)
return SOAPClient._getXmlHttpProgID.progid;
var progids = ["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
var o;
for (var i = 0; i < progids.length; i++) {
try {
o = new ActiveXObject(progids[i]);
return SOAPClient._getXmlHttpProgID.progid = progids[i];
}
catch (ex) { };
}
throw new Error("Could not find an installed XML parser");
}
Thanks in advance for any helpful input.
Cheers
Try &#38 instead of & sign.

Categories

Resources