code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
tinyMCEPopup.requireLangPack();
var AnchorDialog = {
init : function(ed) {
var action, elm, f = document.forms[0];
this.editor = ed;
elm = ed.dom.getParent(ed.selection.getNode(), 'A');
v = ed.dom.getAttrib(elm, 'name');
if (v) {
this.action = 'update';
f.anchorName.value = v;
}
f.insert.value = ed.getLang(elm ? 'update' : 'insert');
},
update : function() {
var ed = this.editor, elm, name = document.forms[0].anchorName.value;
if (!name || !/^[a-z][a-z0-9\-\_:\.]*$/i.test(name)) {
tinyMCEPopup.alert('advanced_dlg.anchor_invalid');
return;
}
tinyMCEPopup.restoreSelection();
if (this.action != 'update')
ed.selection.collapse(1);
elm = ed.dom.getParent(ed.selection.getNode(), 'A');
if (elm)
elm.name = name;
else
ed.execCommand('mceInsertContent', 0, ed.dom.createHTML('a', {name : name, 'class' : 'mceItemAnchor'}, ''));
tinyMCEPopup.close();
}
};
tinyMCEPopup.onInit.add(AnchorDialog.init, AnchorDialog);
| JavaScript |
var ImageDialog = {
preInit : function() {
var url;
tinyMCEPopup.requireLangPack();
if (url = tinyMCEPopup.getParam("external_image_list_url"))
document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>');
},
init : function() {
var f = document.forms[0], ed = tinyMCEPopup.editor;
// Setup browse button
document.getElementById('srcbrowsercontainer').innerHTML = getBrowserHTML('srcbrowser','src','image','theme_advanced_image');
if (isVisible('srcbrowser'))
document.getElementById('src').style.width = '180px';
e = ed.selection.getNode();
this.fillFileList('image_list', tinyMCEPopup.getParam('external_image_list', 'tinyMCEImageList'));
if (e.nodeName == 'IMG') {
f.src.value = ed.dom.getAttrib(e, 'src');
f.alt.value = ed.dom.getAttrib(e, 'alt');
f.border.value = this.getAttrib(e, 'border');
f.vspace.value = this.getAttrib(e, 'vspace');
f.hspace.value = this.getAttrib(e, 'hspace');
f.width.value = ed.dom.getAttrib(e, 'width');
f.height.value = ed.dom.getAttrib(e, 'height');
f.insert.value = ed.getLang('update');
this.styleVal = ed.dom.getAttrib(e, 'style');
selectByValue(f, 'image_list', f.src.value);
selectByValue(f, 'align', this.getAttrib(e, 'align'));
this.updateStyle();
}
},
fillFileList : function(id, l) {
var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl;
l = typeof(l) === 'function' ? l() : window[l];
if (l && l.length > 0) {
lst.options[lst.options.length] = new Option('', '');
tinymce.each(l, function(o) {
lst.options[lst.options.length] = new Option(o[0], o[1]);
});
} else
dom.remove(dom.getParent(id, 'tr'));
},
update : function() {
var f = document.forms[0], nl = f.elements, ed = tinyMCEPopup.editor, args = {}, el;
tinyMCEPopup.restoreSelection();
if (f.src.value === '') {
if (ed.selection.getNode().nodeName == 'IMG') {
ed.dom.remove(ed.selection.getNode());
ed.execCommand('mceRepaint');
}
tinyMCEPopup.close();
return;
}
if (!ed.settings.inline_styles) {
args = tinymce.extend(args, {
vspace : nl.vspace.value,
hspace : nl.hspace.value,
border : nl.border.value,
align : getSelectValue(f, 'align')
});
} else
args.style = this.styleVal;
tinymce.extend(args, {
src : f.src.value.replace(/ /g, '%20'),
alt : f.alt.value,
width : f.width.value,
height : f.height.value
});
el = ed.selection.getNode();
if (el && el.nodeName == 'IMG') {
ed.dom.setAttribs(el, args);
tinyMCEPopup.editor.execCommand('mceRepaint');
tinyMCEPopup.editor.focus();
} else {
tinymce.each(args, function(value, name) {
if (value === "") {
delete args[name];
}
});
ed.execCommand('mceInsertContent', false, tinyMCEPopup.editor.dom.createHTML('img', args), {skip_undo : 1});
ed.undoManager.add();
}
tinyMCEPopup.close();
},
updateStyle : function() {
var dom = tinyMCEPopup.dom, st, v, f = document.forms[0];
if (tinyMCEPopup.editor.settings.inline_styles) {
st = tinyMCEPopup.dom.parseStyle(this.styleVal);
// Handle align
v = getSelectValue(f, 'align');
if (v) {
if (v == 'left' || v == 'right') {
st['float'] = v;
delete st['vertical-align'];
} else {
st['vertical-align'] = v;
delete st['float'];
}
} else {
delete st['float'];
delete st['vertical-align'];
}
// Handle border
v = f.border.value;
if (v || v == '0') {
if (v == '0')
st['border'] = '0';
else
st['border'] = v + 'px solid black';
} else
delete st['border'];
// Handle hspace
v = f.hspace.value;
if (v) {
delete st['margin'];
st['margin-left'] = v + 'px';
st['margin-right'] = v + 'px';
} else {
delete st['margin-left'];
delete st['margin-right'];
}
// Handle vspace
v = f.vspace.value;
if (v) {
delete st['margin'];
st['margin-top'] = v + 'px';
st['margin-bottom'] = v + 'px';
} else {
delete st['margin-top'];
delete st['margin-bottom'];
}
// Merge
st = tinyMCEPopup.dom.parseStyle(dom.serializeStyle(st), 'img');
this.styleVal = dom.serializeStyle(st, 'img');
}
},
getAttrib : function(e, at) {
var ed = tinyMCEPopup.editor, dom = ed.dom, v, v2;
if (ed.settings.inline_styles) {
switch (at) {
case 'align':
if (v = dom.getStyle(e, 'float'))
return v;
if (v = dom.getStyle(e, 'vertical-align'))
return v;
break;
case 'hspace':
v = dom.getStyle(e, 'margin-left')
v2 = dom.getStyle(e, 'margin-right');
if (v && v == v2)
return parseInt(v.replace(/[^0-9]/g, ''));
break;
case 'vspace':
v = dom.getStyle(e, 'margin-top')
v2 = dom.getStyle(e, 'margin-bottom');
if (v && v == v2)
return parseInt(v.replace(/[^0-9]/g, ''));
break;
case 'border':
v = 0;
tinymce.each(['top', 'right', 'bottom', 'left'], function(sv) {
sv = dom.getStyle(e, 'border-' + sv + '-width');
// False or not the same as prev
if (!sv || (sv != v && v !== 0)) {
v = 0;
return false;
}
if (sv)
v = sv;
});
if (v)
return parseInt(v.replace(/[^0-9]/g, ''));
break;
}
}
if (v = dom.getAttrib(e, at))
return v;
return '';
},
resetImageData : function() {
var f = document.forms[0];
f.width.value = f.height.value = "";
},
updateImageData : function() {
var f = document.forms[0], t = ImageDialog;
if (f.width.value == "")
f.width.value = t.preloadImg.width;
if (f.height.value == "")
f.height.value = t.preloadImg.height;
},
getImageData : function() {
var f = document.forms[0];
this.preloadImg = new Image();
this.preloadImg.onload = this.updateImageData;
this.preloadImg.onerror = this.resetImageData;
this.preloadImg.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.src.value);
}
};
ImageDialog.preInit();
tinyMCEPopup.onInit.add(ImageDialog.init, ImageDialog);
| JavaScript |
tinyMCEPopup.requireLangPack();
var LinkDialog = {
preInit : function() {
var url;
if (url = tinyMCEPopup.getParam("external_link_list_url"))
document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>');
},
init : function() {
var f = document.forms[0], ed = tinyMCEPopup.editor;
// Setup browse button
document.getElementById('hrefbrowsercontainer').innerHTML = getBrowserHTML('hrefbrowser', 'href', 'file', 'theme_advanced_link');
if (isVisible('hrefbrowser'))
document.getElementById('href').style.width = '180px';
this.fillClassList('class_list');
this.fillFileList('link_list', 'tinyMCELinkList');
this.fillTargetList('target_list');
if (e = ed.dom.getParent(ed.selection.getNode(), 'A')) {
f.href.value = ed.dom.getAttrib(e, 'href');
f.linktitle.value = ed.dom.getAttrib(e, 'title');
f.insert.value = ed.getLang('update');
selectByValue(f, 'link_list', f.href.value);
selectByValue(f, 'target_list', ed.dom.getAttrib(e, 'target'));
selectByValue(f, 'class_list', ed.dom.getAttrib(e, 'class'));
}
},
update : function() {
var f = document.forms[0], ed = tinyMCEPopup.editor, e, b, href = f.href.value.replace(/ /g, '%20');
tinyMCEPopup.restoreSelection();
e = ed.dom.getParent(ed.selection.getNode(), 'A');
// Remove element if there is no href
if (!f.href.value) {
if (e) {
b = ed.selection.getBookmark();
ed.dom.remove(e, 1);
ed.selection.moveToBookmark(b);
tinyMCEPopup.execCommand("mceEndUndoLevel");
tinyMCEPopup.close();
return;
}
}
// Create new anchor elements
if (e == null) {
ed.getDoc().execCommand("unlink", false, null);
tinyMCEPopup.execCommand("mceInsertLink", false, "#mce_temp_url#", {skip_undo : 1});
tinymce.each(ed.dom.select("a"), function(n) {
if (ed.dom.getAttrib(n, 'href') == '#mce_temp_url#') {
e = n;
ed.dom.setAttribs(e, {
href : href,
title : f.linktitle.value,
target : f.target_list ? getSelectValue(f, "target_list") : null,
'class' : f.class_list ? getSelectValue(f, "class_list") : null
});
}
});
} else {
ed.dom.setAttribs(e, {
href : href,
title : f.linktitle.value,
target : f.target_list ? getSelectValue(f, "target_list") : null,
'class' : f.class_list ? getSelectValue(f, "class_list") : null
});
}
// Don't move caret if selection was image
if (e.childNodes.length != 1 || e.firstChild.nodeName != 'IMG') {
ed.focus();
ed.selection.select(e);
ed.selection.collapse(0);
tinyMCEPopup.storeSelection();
}
tinyMCEPopup.execCommand("mceEndUndoLevel");
tinyMCEPopup.close();
},
checkPrefix : function(n) {
if (n.value && Validator.isEmail(n) && !/^\s*mailto:/i.test(n.value) && confirm(tinyMCEPopup.getLang('advanced_dlg.link_is_email')))
n.value = 'mailto:' + n.value;
if (/^\s*www\./i.test(n.value) && confirm(tinyMCEPopup.getLang('advanced_dlg.link_is_external')))
n.value = 'http://' + n.value;
},
fillFileList : function(id, l) {
var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl;
l = window[l];
if (l && l.length > 0) {
lst.options[lst.options.length] = new Option('', '');
tinymce.each(l, function(o) {
lst.options[lst.options.length] = new Option(o[0], o[1]);
});
} else
dom.remove(dom.getParent(id, 'tr'));
},
fillClassList : function(id) {
var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl;
if (v = tinyMCEPopup.getParam('theme_advanced_styles')) {
cl = [];
tinymce.each(v.split(';'), function(v) {
var p = v.split('=');
cl.push({'title' : p[0], 'class' : p[1]});
});
} else
cl = tinyMCEPopup.editor.dom.getClasses();
if (cl.length > 0) {
lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), '');
tinymce.each(cl, function(o) {
lst.options[lst.options.length] = new Option(o.title || o['class'], o['class']);
});
} else
dom.remove(dom.getParent(id, 'tr'));
},
fillTargetList : function(id) {
var dom = tinyMCEPopup.dom, lst = dom.get(id), v;
lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), '');
lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('advanced_dlg.link_target_same'), '_self');
lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('advanced_dlg.link_target_blank'), '_blank');
if (v = tinyMCEPopup.getParam('theme_advanced_link_targets')) {
tinymce.each(v.split(','), function(v) {
v = v.split('=');
lst.options[lst.options.length] = new Option(v[0], v[1]);
});
}
}
};
LinkDialog.preInit();
tinyMCEPopup.onInit.add(LinkDialog.init, LinkDialog);
| JavaScript |
tinyMCEPopup.requireLangPack();
function init() {
var ed, tcont;
tinyMCEPopup.resizeToInnerSize();
ed = tinyMCEPopup.editor;
// Give FF some time
window.setTimeout(insertHelpIFrame, 10);
tcont = document.getElementById('plugintablecontainer');
document.getElementById('plugins_tab').style.display = 'none';
var html = "";
html += '<table id="plugintable">';
html += '<thead>';
html += '<tr>';
html += '<td>' + ed.getLang('advanced_dlg.about_plugin') + '</td>';
html += '<td>' + ed.getLang('advanced_dlg.about_author') + '</td>';
html += '<td>' + ed.getLang('advanced_dlg.about_version') + '</td>';
html += '</tr>';
html += '</thead>';
html += '<tbody>';
tinymce.each(ed.plugins, function(p, n) {
var info;
if (!p.getInfo)
return;
html += '<tr>';
info = p.getInfo();
if (info.infourl != null && info.infourl != '')
html += '<td width="50%" title="' + n + '"><a href="' + info.infourl + '" target="_blank">' + info.longname + '</a></td>';
else
html += '<td width="50%" title="' + n + '">' + info.longname + '</td>';
if (info.authorurl != null && info.authorurl != '')
html += '<td width="35%"><a href="' + info.authorurl + '" target="_blank">' + info.author + '</a></td>';
else
html += '<td width="35%">' + info.author + '</td>';
html += '<td width="15%">' + info.version + '</td>';
html += '</tr>';
document.getElementById('plugins_tab').style.display = '';
});
html += '</tbody>';
html += '</table>';
tcont.innerHTML = html;
tinyMCEPopup.dom.get('version').innerHTML = tinymce.majorVersion + "." + tinymce.minorVersion;
tinyMCEPopup.dom.get('date').innerHTML = tinymce.releaseDate;
}
function insertHelpIFrame() {
var html;
if (tinyMCEPopup.getParam('docs_url')) {
html = '<iframe width="100%" height="300" src="' + tinyMCEPopup.editor.baseURI.toAbsolute(tinyMCEPopup.getParam('docs_url')) + '"></iframe>';
document.getElementById('iframecontainer').innerHTML = html;
document.getElementById('help_tab').style.display = 'block';
document.getElementById('help_tab').setAttribute("aria-hidden", "false");
}
}
tinyMCEPopup.onInit.add(init);
| JavaScript |
tinyMCEPopup.requireLangPack();
var detail = 50, strhex = "0123456789ABCDEF", i, isMouseDown = false, isMouseOver = false;
var colors = [
"#000000","#000033","#000066","#000099","#0000cc","#0000ff","#330000","#330033",
"#330066","#330099","#3300cc","#3300ff","#660000","#660033","#660066","#660099",
"#6600cc","#6600ff","#990000","#990033","#990066","#990099","#9900cc","#9900ff",
"#cc0000","#cc0033","#cc0066","#cc0099","#cc00cc","#cc00ff","#ff0000","#ff0033",
"#ff0066","#ff0099","#ff00cc","#ff00ff","#003300","#003333","#003366","#003399",
"#0033cc","#0033ff","#333300","#333333","#333366","#333399","#3333cc","#3333ff",
"#663300","#663333","#663366","#663399","#6633cc","#6633ff","#993300","#993333",
"#993366","#993399","#9933cc","#9933ff","#cc3300","#cc3333","#cc3366","#cc3399",
"#cc33cc","#cc33ff","#ff3300","#ff3333","#ff3366","#ff3399","#ff33cc","#ff33ff",
"#006600","#006633","#006666","#006699","#0066cc","#0066ff","#336600","#336633",
"#336666","#336699","#3366cc","#3366ff","#666600","#666633","#666666","#666699",
"#6666cc","#6666ff","#996600","#996633","#996666","#996699","#9966cc","#9966ff",
"#cc6600","#cc6633","#cc6666","#cc6699","#cc66cc","#cc66ff","#ff6600","#ff6633",
"#ff6666","#ff6699","#ff66cc","#ff66ff","#009900","#009933","#009966","#009999",
"#0099cc","#0099ff","#339900","#339933","#339966","#339999","#3399cc","#3399ff",
"#669900","#669933","#669966","#669999","#6699cc","#6699ff","#999900","#999933",
"#999966","#999999","#9999cc","#9999ff","#cc9900","#cc9933","#cc9966","#cc9999",
"#cc99cc","#cc99ff","#ff9900","#ff9933","#ff9966","#ff9999","#ff99cc","#ff99ff",
"#00cc00","#00cc33","#00cc66","#00cc99","#00cccc","#00ccff","#33cc00","#33cc33",
"#33cc66","#33cc99","#33cccc","#33ccff","#66cc00","#66cc33","#66cc66","#66cc99",
"#66cccc","#66ccff","#99cc00","#99cc33","#99cc66","#99cc99","#99cccc","#99ccff",
"#cccc00","#cccc33","#cccc66","#cccc99","#cccccc","#ccccff","#ffcc00","#ffcc33",
"#ffcc66","#ffcc99","#ffcccc","#ffccff","#00ff00","#00ff33","#00ff66","#00ff99",
"#00ffcc","#00ffff","#33ff00","#33ff33","#33ff66","#33ff99","#33ffcc","#33ffff",
"#66ff00","#66ff33","#66ff66","#66ff99","#66ffcc","#66ffff","#99ff00","#99ff33",
"#99ff66","#99ff99","#99ffcc","#99ffff","#ccff00","#ccff33","#ccff66","#ccff99",
"#ccffcc","#ccffff","#ffff00","#ffff33","#ffff66","#ffff99","#ffffcc","#ffffff"
];
var named = {
'#F0F8FF':'Alice Blue','#FAEBD7':'Antique White','#00FFFF':'Aqua','#7FFFD4':'Aquamarine','#F0FFFF':'Azure','#F5F5DC':'Beige',
'#FFE4C4':'Bisque','#000000':'Black','#FFEBCD':'Blanched Almond','#0000FF':'Blue','#8A2BE2':'Blue Violet','#A52A2A':'Brown',
'#DEB887':'Burly Wood','#5F9EA0':'Cadet Blue','#7FFF00':'Chartreuse','#D2691E':'Chocolate','#FF7F50':'Coral','#6495ED':'Cornflower Blue',
'#FFF8DC':'Cornsilk','#DC143C':'Crimson','#00FFFF':'Cyan','#00008B':'Dark Blue','#008B8B':'Dark Cyan','#B8860B':'Dark Golden Rod',
'#A9A9A9':'Dark Gray','#A9A9A9':'Dark Grey','#006400':'Dark Green','#BDB76B':'Dark Khaki','#8B008B':'Dark Magenta','#556B2F':'Dark Olive Green',
'#FF8C00':'Darkorange','#9932CC':'Dark Orchid','#8B0000':'Dark Red','#E9967A':'Dark Salmon','#8FBC8F':'Dark Sea Green','#483D8B':'Dark Slate Blue',
'#2F4F4F':'Dark Slate Gray','#2F4F4F':'Dark Slate Grey','#00CED1':'Dark Turquoise','#9400D3':'Dark Violet','#FF1493':'Deep Pink','#00BFFF':'Deep Sky Blue',
'#696969':'Dim Gray','#696969':'Dim Grey','#1E90FF':'Dodger Blue','#B22222':'Fire Brick','#FFFAF0':'Floral White','#228B22':'Forest Green',
'#FF00FF':'Fuchsia','#DCDCDC':'Gainsboro','#F8F8FF':'Ghost White','#FFD700':'Gold','#DAA520':'Golden Rod','#808080':'Gray','#808080':'Grey',
'#008000':'Green','#ADFF2F':'Green Yellow','#F0FFF0':'Honey Dew','#FF69B4':'Hot Pink','#CD5C5C':'Indian Red','#4B0082':'Indigo','#FFFFF0':'Ivory',
'#F0E68C':'Khaki','#E6E6FA':'Lavender','#FFF0F5':'Lavender Blush','#7CFC00':'Lawn Green','#FFFACD':'Lemon Chiffon','#ADD8E6':'Light Blue',
'#F08080':'Light Coral','#E0FFFF':'Light Cyan','#FAFAD2':'Light Golden Rod Yellow','#D3D3D3':'Light Gray','#D3D3D3':'Light Grey','#90EE90':'Light Green',
'#FFB6C1':'Light Pink','#FFA07A':'Light Salmon','#20B2AA':'Light Sea Green','#87CEFA':'Light Sky Blue','#778899':'Light Slate Gray','#778899':'Light Slate Grey',
'#B0C4DE':'Light Steel Blue','#FFFFE0':'Light Yellow','#00FF00':'Lime','#32CD32':'Lime Green','#FAF0E6':'Linen','#FF00FF':'Magenta','#800000':'Maroon',
'#66CDAA':'Medium Aqua Marine','#0000CD':'Medium Blue','#BA55D3':'Medium Orchid','#9370D8':'Medium Purple','#3CB371':'Medium Sea Green','#7B68EE':'Medium Slate Blue',
'#00FA9A':'Medium Spring Green','#48D1CC':'Medium Turquoise','#C71585':'Medium Violet Red','#191970':'Midnight Blue','#F5FFFA':'Mint Cream','#FFE4E1':'Misty Rose','#FFE4B5':'Moccasin',
'#FFDEAD':'Navajo White','#000080':'Navy','#FDF5E6':'Old Lace','#808000':'Olive','#6B8E23':'Olive Drab','#FFA500':'Orange','#FF4500':'Orange Red','#DA70D6':'Orchid',
'#EEE8AA':'Pale Golden Rod','#98FB98':'Pale Green','#AFEEEE':'Pale Turquoise','#D87093':'Pale Violet Red','#FFEFD5':'Papaya Whip','#FFDAB9':'Peach Puff',
'#CD853F':'Peru','#FFC0CB':'Pink','#DDA0DD':'Plum','#B0E0E6':'Powder Blue','#800080':'Purple','#FF0000':'Red','#BC8F8F':'Rosy Brown','#4169E1':'Royal Blue',
'#8B4513':'Saddle Brown','#FA8072':'Salmon','#F4A460':'Sandy Brown','#2E8B57':'Sea Green','#FFF5EE':'Sea Shell','#A0522D':'Sienna','#C0C0C0':'Silver',
'#87CEEB':'Sky Blue','#6A5ACD':'Slate Blue','#708090':'Slate Gray','#708090':'Slate Grey','#FFFAFA':'Snow','#00FF7F':'Spring Green',
'#4682B4':'Steel Blue','#D2B48C':'Tan','#008080':'Teal','#D8BFD8':'Thistle','#FF6347':'Tomato','#40E0D0':'Turquoise','#EE82EE':'Violet',
'#F5DEB3':'Wheat','#FFFFFF':'White','#F5F5F5':'White Smoke','#FFFF00':'Yellow','#9ACD32':'Yellow Green'
};
var namedLookup = {};
function init() {
var inputColor = convertRGBToHex(tinyMCEPopup.getWindowArg('input_color')), key, value;
tinyMCEPopup.resizeToInnerSize();
generatePicker();
generateWebColors();
generateNamedColors();
if (inputColor) {
changeFinalColor(inputColor);
col = convertHexToRGB(inputColor);
if (col)
updateLight(col.r, col.g, col.b);
}
for (key in named) {
value = named[key];
namedLookup[value.replace(/\s+/, '').toLowerCase()] = key.replace(/#/, '').toLowerCase();
}
}
function toHexColor(color) {
var matches, red, green, blue, toInt = parseInt;
function hex(value) {
value = parseInt(value).toString(16);
return value.length > 1 ? value : '0' + value; // Padd with leading zero
};
color = color.replace(/[\s#]+/g, '').toLowerCase();
color = namedLookup[color] || color;
matches = /^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)|([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})|([a-f0-9])([a-f0-9])([a-f0-9])$/.exec(color);
if (matches) {
if (matches[1]) {
red = toInt(matches[1]);
green = toInt(matches[2]);
blue = toInt(matches[3]);
} else if (matches[4]) {
red = toInt(matches[4], 16);
green = toInt(matches[5], 16);
blue = toInt(matches[6], 16);
} else if (matches[7]) {
red = toInt(matches[7] + matches[7], 16);
green = toInt(matches[8] + matches[8], 16);
blue = toInt(matches[9] + matches[9], 16);
}
return '#' + hex(red) + hex(green) + hex(blue);
}
return '';
}
function insertAction() {
var color = document.getElementById("color").value, f = tinyMCEPopup.getWindowArg('func');
tinyMCEPopup.restoreSelection();
if (f)
f(toHexColor(color));
tinyMCEPopup.close();
}
function showColor(color, name) {
if (name)
document.getElementById("colorname").innerHTML = name;
document.getElementById("preview").style.backgroundColor = color;
document.getElementById("color").value = color.toUpperCase();
}
function convertRGBToHex(col) {
var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi");
if (!col)
return col;
var rgb = col.replace(re, "$1,$2,$3").split(',');
if (rgb.length == 3) {
r = parseInt(rgb[0]).toString(16);
g = parseInt(rgb[1]).toString(16);
b = parseInt(rgb[2]).toString(16);
r = r.length == 1 ? '0' + r : r;
g = g.length == 1 ? '0' + g : g;
b = b.length == 1 ? '0' + b : b;
return "#" + r + g + b;
}
return col;
}
function convertHexToRGB(col) {
if (col.indexOf('#') != -1) {
col = col.replace(new RegExp('[^0-9A-F]', 'gi'), '');
r = parseInt(col.substring(0, 2), 16);
g = parseInt(col.substring(2, 4), 16);
b = parseInt(col.substring(4, 6), 16);
return {r : r, g : g, b : b};
}
return null;
}
function generatePicker() {
var el = document.getElementById('light'), h = '', i;
for (i = 0; i < detail; i++){
h += '<div id="gs'+i+'" style="background-color:#000000; width:15px; height:3px; border-style:none; border-width:0px;"'
+ ' onclick="changeFinalColor(this.style.backgroundColor)"'
+ ' onmousedown="isMouseDown = true; return false;"'
+ ' onmouseup="isMouseDown = false;"'
+ ' onmousemove="if (isMouseDown && isMouseOver) changeFinalColor(this.style.backgroundColor); return false;"'
+ ' onmouseover="isMouseOver = true;"'
+ ' onmouseout="isMouseOver = false;"'
+ '></div>';
}
el.innerHTML = h;
}
function generateWebColors() {
var el = document.getElementById('webcolors'), h = '', i;
if (el.className == 'generated')
return;
// TODO: VoiceOver doesn't seem to support legend as a label referenced by labelledby.
h += '<div role="listbox" aria-labelledby="webcolors_title" tabindex="0"><table role="presentation" border="0" cellspacing="1" cellpadding="0">'
+ '<tr>';
for (i=0; i<colors.length; i++) {
h += '<td bgcolor="' + colors[i] + '" width="10" height="10">'
+ '<a href="javascript:insertAction();" role="option" tabindex="-1" aria-labelledby="web_colors_' + i + '" onfocus="showColor(\'' + colors[i] + '\');" onmouseover="showColor(\'' + colors[i] + '\');" style="display:block;width:10px;height:10px;overflow:hidden;">';
if (tinyMCEPopup.editor.forcedHighContrastMode) {
h += '<canvas class="mceColorSwatch" height="10" width="10" data-color="' + colors[i] + '"></canvas>';
}
h += '<span class="mceVoiceLabel" style="display:none;" id="web_colors_' + i + '">' + colors[i].toUpperCase() + '</span>';
h += '</a></td>';
if ((i+1) % 18 == 0)
h += '</tr><tr>';
}
h += '</table></div>';
el.innerHTML = h;
el.className = 'generated';
paintCanvas(el);
enableKeyboardNavigation(el.firstChild);
}
function paintCanvas(el) {
tinyMCEPopup.getWin().tinymce.each(tinyMCEPopup.dom.select('canvas.mceColorSwatch', el), function(canvas) {
var context;
if (canvas.getContext && (context = canvas.getContext("2d"))) {
context.fillStyle = canvas.getAttribute('data-color');
context.fillRect(0, 0, 10, 10);
}
});
}
function generateNamedColors() {
var el = document.getElementById('namedcolors'), h = '', n, v, i = 0;
if (el.className == 'generated')
return;
for (n in named) {
v = named[n];
h += '<a href="javascript:insertAction();" role="option" tabindex="-1" aria-labelledby="named_colors_' + i + '" onfocus="showColor(\'' + n + '\',\'' + v + '\');" onmouseover="showColor(\'' + n + '\',\'' + v + '\');" style="background-color: ' + n + '">';
if (tinyMCEPopup.editor.forcedHighContrastMode) {
h += '<canvas class="mceColorSwatch" height="10" width="10" data-color="' + colors[i] + '"></canvas>';
}
h += '<span class="mceVoiceLabel" style="display:none;" id="named_colors_' + i + '">' + v + '</span>';
h += '</a>';
i++;
}
el.innerHTML = h;
el.className = 'generated';
paintCanvas(el);
enableKeyboardNavigation(el);
}
function enableKeyboardNavigation(el) {
tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', {
root: el,
items: tinyMCEPopup.dom.select('a', el)
}, tinyMCEPopup.dom);
}
function dechex(n) {
return strhex.charAt(Math.floor(n / 16)) + strhex.charAt(n % 16);
}
function computeColor(e) {
var x, y, partWidth, partDetail, imHeight, r, g, b, coef, i, finalCoef, finalR, finalG, finalB;
x = e.offsetX ? e.offsetX : (e.target ? e.clientX - e.target.x : 0);
y = e.offsetY ? e.offsetY : (e.target ? e.clientY - e.target.y : 0);
partWidth = document.getElementById('colors').width / 6;
partDetail = detail / 2;
imHeight = document.getElementById('colors').height;
r = (x >= 0)*(x < partWidth)*255 + (x >= partWidth)*(x < 2*partWidth)*(2*255 - x * 255 / partWidth) + (x >= 4*partWidth)*(x < 5*partWidth)*(-4*255 + x * 255 / partWidth) + (x >= 5*partWidth)*(x < 6*partWidth)*255;
g = (x >= 0)*(x < partWidth)*(x * 255 / partWidth) + (x >= partWidth)*(x < 3*partWidth)*255 + (x >= 3*partWidth)*(x < 4*partWidth)*(4*255 - x * 255 / partWidth);
b = (x >= 2*partWidth)*(x < 3*partWidth)*(-2*255 + x * 255 / partWidth) + (x >= 3*partWidth)*(x < 5*partWidth)*255 + (x >= 5*partWidth)*(x < 6*partWidth)*(6*255 - x * 255 / partWidth);
coef = (imHeight - y) / imHeight;
r = 128 + (r - 128) * coef;
g = 128 + (g - 128) * coef;
b = 128 + (b - 128) * coef;
changeFinalColor('#' + dechex(r) + dechex(g) + dechex(b));
updateLight(r, g, b);
}
function updateLight(r, g, b) {
var i, partDetail = detail / 2, finalCoef, finalR, finalG, finalB, color;
for (i=0; i<detail; i++) {
if ((i>=0) && (i<partDetail)) {
finalCoef = i / partDetail;
finalR = dechex(255 - (255 - r) * finalCoef);
finalG = dechex(255 - (255 - g) * finalCoef);
finalB = dechex(255 - (255 - b) * finalCoef);
} else {
finalCoef = 2 - i / partDetail;
finalR = dechex(r * finalCoef);
finalG = dechex(g * finalCoef);
finalB = dechex(b * finalCoef);
}
color = finalR + finalG + finalB;
setCol('gs' + i, '#'+color);
}
}
function changeFinalColor(color) {
if (color.indexOf('#') == -1)
color = convertRGBToHex(color);
setCol('preview', color);
document.getElementById('color').value = color;
}
function setCol(e, c) {
try {
document.getElementById(e).style.backgroundColor = c;
} catch (ex) {
// Ignore IE warning
}
}
tinyMCEPopup.onInit.add(init);
| JavaScript |
/**
* validate.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
/**
// String validation:
if (!Validator.isEmail('myemail'))
alert('Invalid email.');
// Form validation:
var f = document.forms['myform'];
if (!Validator.isEmail(f.myemail))
alert('Invalid email.');
*/
var Validator = {
isEmail : function(s) {
return this.test(s, '^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$');
},
isAbsUrl : function(s) {
return this.test(s, '^(news|telnet|nttp|file|http|ftp|https)://[-A-Za-z0-9\\.]+\\/?.*$');
},
isSize : function(s) {
return this.test(s, '^[0-9.]+(%|in|cm|mm|em|ex|pt|pc|px)?$');
},
isId : function(s) {
return this.test(s, '^[A-Za-z_]([A-Za-z0-9_])*$');
},
isEmpty : function(s) {
var nl, i;
if (s.nodeName == 'SELECT' && s.selectedIndex < 1)
return true;
if (s.type == 'checkbox' && !s.checked)
return true;
if (s.type == 'radio') {
for (i=0, nl = s.form.elements; i<nl.length; i++) {
if (nl[i].type == "radio" && nl[i].name == s.name && nl[i].checked)
return false;
}
return true;
}
return new RegExp('^\\s*$').test(s.nodeType == 1 ? s.value : s);
},
isNumber : function(s, d) {
return !isNaN(s.nodeType == 1 ? s.value : s) && (!d || !this.test(s, '^-?[0-9]*\\.[0-9]*$'));
},
test : function(s, p) {
s = s.nodeType == 1 ? s.value : s;
return s == '' || new RegExp(p).test(s);
}
};
var AutoValidator = {
settings : {
id_cls : 'id',
int_cls : 'int',
url_cls : 'url',
number_cls : 'number',
email_cls : 'email',
size_cls : 'size',
required_cls : 'required',
invalid_cls : 'invalid',
min_cls : 'min',
max_cls : 'max'
},
init : function(s) {
var n;
for (n in s)
this.settings[n] = s[n];
},
validate : function(f) {
var i, nl, s = this.settings, c = 0;
nl = this.tags(f, 'label');
for (i=0; i<nl.length; i++) {
this.removeClass(nl[i], s.invalid_cls);
nl[i].setAttribute('aria-invalid', false);
}
c += this.validateElms(f, 'input');
c += this.validateElms(f, 'select');
c += this.validateElms(f, 'textarea');
return c == 3;
},
invalidate : function(n) {
this.mark(n.form, n);
},
getErrorMessages : function(f) {
var nl, i, s = this.settings, field, msg, values, messages = [], ed = tinyMCEPopup.editor;
nl = this.tags(f, "label");
for (i=0; i<nl.length; i++) {
if (this.hasClass(nl[i], s.invalid_cls)) {
field = document.getElementById(nl[i].getAttribute("for"));
values = { field: nl[i].textContent };
if (this.hasClass(field, s.min_cls, true)) {
message = ed.getLang('invalid_data_min');
values.min = this.getNum(field, s.min_cls);
} else if (this.hasClass(field, s.number_cls)) {
message = ed.getLang('invalid_data_number');
} else if (this.hasClass(field, s.size_cls)) {
message = ed.getLang('invalid_data_size');
} else {
message = ed.getLang('invalid_data');
}
message = message.replace(/{\#([^}]+)\}/g, function(a, b) {
return values[b] || '{#' + b + '}';
});
messages.push(message);
}
}
return messages;
},
reset : function(e) {
var t = ['label', 'input', 'select', 'textarea'];
var i, j, nl, s = this.settings;
if (e == null)
return;
for (i=0; i<t.length; i++) {
nl = this.tags(e.form ? e.form : e, t[i]);
for (j=0; j<nl.length; j++) {
this.removeClass(nl[j], s.invalid_cls);
nl[j].setAttribute('aria-invalid', false);
}
}
},
validateElms : function(f, e) {
var nl, i, n, s = this.settings, st = true, va = Validator, v;
nl = this.tags(f, e);
for (i=0; i<nl.length; i++) {
n = nl[i];
this.removeClass(n, s.invalid_cls);
if (this.hasClass(n, s.required_cls) && va.isEmpty(n))
st = this.mark(f, n);
if (this.hasClass(n, s.number_cls) && !va.isNumber(n))
st = this.mark(f, n);
if (this.hasClass(n, s.int_cls) && !va.isNumber(n, true))
st = this.mark(f, n);
if (this.hasClass(n, s.url_cls) && !va.isAbsUrl(n))
st = this.mark(f, n);
if (this.hasClass(n, s.email_cls) && !va.isEmail(n))
st = this.mark(f, n);
if (this.hasClass(n, s.size_cls) && !va.isSize(n))
st = this.mark(f, n);
if (this.hasClass(n, s.id_cls) && !va.isId(n))
st = this.mark(f, n);
if (this.hasClass(n, s.min_cls, true)) {
v = this.getNum(n, s.min_cls);
if (isNaN(v) || parseInt(n.value) < parseInt(v))
st = this.mark(f, n);
}
if (this.hasClass(n, s.max_cls, true)) {
v = this.getNum(n, s.max_cls);
if (isNaN(v) || parseInt(n.value) > parseInt(v))
st = this.mark(f, n);
}
}
return st;
},
hasClass : function(n, c, d) {
return new RegExp('\\b' + c + (d ? '[0-9]+' : '') + '\\b', 'g').test(n.className);
},
getNum : function(n, c) {
c = n.className.match(new RegExp('\\b' + c + '([0-9]+)\\b', 'g'))[0];
c = c.replace(/[^0-9]/g, '');
return c;
},
addClass : function(n, c, b) {
var o = this.removeClass(n, c);
n.className = b ? c + (o != '' ? (' ' + o) : '') : (o != '' ? (o + ' ') : '') + c;
},
removeClass : function(n, c) {
c = n.className.replace(new RegExp("(^|\\s+)" + c + "(\\s+|$)"), ' ');
return n.className = c != ' ' ? c : '';
},
tags : function(f, s) {
return f.getElementsByTagName(s);
},
mark : function(f, n) {
var s = this.settings;
this.addClass(n, s.invalid_cls);
n.setAttribute('aria-invalid', 'true');
this.markLabels(f, n, s.invalid_cls);
return false;
},
markLabels : function(f, n, ic) {
var nl, i;
nl = this.tags(f, "label");
for (i=0; i<nl.length; i++) {
if (nl[i].getAttribute("for") == n.id || nl[i].htmlFor == n.id)
this.addClass(nl[i], ic);
}
return null;
}
};
| JavaScript |
/**
* mctabs.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
function MCTabs() {
this.settings = [];
this.onChange = tinyMCEPopup.editor.windowManager.createInstance('tinymce.util.Dispatcher');
};
MCTabs.prototype.init = function(settings) {
this.settings = settings;
};
MCTabs.prototype.getParam = function(name, default_value) {
var value = null;
value = (typeof(this.settings[name]) == "undefined") ? default_value : this.settings[name];
// Fix bool values
if (value == "true" || value == "false")
return (value == "true");
return value;
};
MCTabs.prototype.showTab =function(tab){
tab.className = 'current';
tab.setAttribute("aria-selected", true);
tab.setAttribute("aria-expanded", true);
tab.tabIndex = 0;
};
MCTabs.prototype.hideTab =function(tab){
var t=this;
tab.className = '';
tab.setAttribute("aria-selected", false);
tab.setAttribute("aria-expanded", false);
tab.tabIndex = -1;
};
MCTabs.prototype.showPanel = function(panel) {
panel.className = 'current';
panel.setAttribute("aria-hidden", false);
};
MCTabs.prototype.hidePanel = function(panel) {
panel.className = 'panel';
panel.setAttribute("aria-hidden", true);
};
MCTabs.prototype.getPanelForTab = function(tabElm) {
return tinyMCEPopup.dom.getAttrib(tabElm, "aria-controls");
};
MCTabs.prototype.displayTab = function(tab_id, panel_id, avoid_focus) {
var panelElm, panelContainerElm, tabElm, tabContainerElm, selectionClass, nodes, i, t = this;
tabElm = document.getElementById(tab_id);
if (panel_id === undefined) {
panel_id = t.getPanelForTab(tabElm);
}
panelElm= document.getElementById(panel_id);
panelContainerElm = panelElm ? panelElm.parentNode : null;
tabContainerElm = tabElm ? tabElm.parentNode : null;
selectionClass = t.getParam('selection_class', 'current');
if (tabElm && tabContainerElm) {
nodes = tabContainerElm.childNodes;
// Hide all other tabs
for (i = 0; i < nodes.length; i++) {
if (nodes[i].nodeName == "LI") {
t.hideTab(nodes[i]);
}
}
// Show selected tab
t.showTab(tabElm);
}
if (panelElm && panelContainerElm) {
nodes = panelContainerElm.childNodes;
// Hide all other panels
for (i = 0; i < nodes.length; i++) {
if (nodes[i].nodeName == "DIV")
t.hidePanel(nodes[i]);
}
if (!avoid_focus) {
tabElm.focus();
}
// Show selected panel
t.showPanel(panelElm);
}
};
MCTabs.prototype.getAnchor = function() {
var pos, url = document.location.href;
if ((pos = url.lastIndexOf('#')) != -1)
return url.substring(pos + 1);
return "";
};
//Global instance
var mcTabs = new MCTabs();
tinyMCEPopup.onInit.add(function() {
var tinymce = tinyMCEPopup.getWin().tinymce, dom = tinyMCEPopup.dom, each = tinymce.each;
each(dom.select('div.tabs'), function(tabContainerElm) {
var keyNav;
dom.setAttrib(tabContainerElm, "role", "tablist");
var items = tinyMCEPopup.dom.select('li', tabContainerElm);
var action = function(id) {
mcTabs.displayTab(id, mcTabs.getPanelForTab(id));
mcTabs.onChange.dispatch(id);
};
each(items, function(item) {
dom.setAttrib(item, 'role', 'tab');
dom.bind(item, 'click', function(evt) {
action(item.id);
});
});
dom.bind(dom.getRoot(), 'keydown', function(evt) {
if (evt.keyCode === 9 && evt.ctrlKey && !evt.altKey) { // Tab
keyNav.moveFocus(evt.shiftKey ? -1 : 1);
tinymce.dom.Event.cancel(evt);
}
});
each(dom.select('a', tabContainerElm), function(a) {
dom.setAttrib(a, 'tabindex', '-1');
});
keyNav = tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', {
root: tabContainerElm,
items: items,
onAction: action,
actOnFocus: true,
enableLeftRight: true,
enableUpDown: true
}, tinyMCEPopup.dom);
});
}); | JavaScript |
/**
* editable_selects.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
var TinyMCE_EditableSelects = {
editSelectElm : null,
init : function() {
var nl = document.getElementsByTagName("select"), i, d = document, o;
for (i=0; i<nl.length; i++) {
if (nl[i].className.indexOf('mceEditableSelect') != -1) {
o = new Option(tinyMCEPopup.editor.translate('value'), '__mce_add_custom__');
o.className = 'mceAddSelectValue';
nl[i].options[nl[i].options.length] = o;
nl[i].onchange = TinyMCE_EditableSelects.onChangeEditableSelect;
}
}
},
onChangeEditableSelect : function(e) {
var d = document, ne, se = window.event ? window.event.srcElement : e.target;
if (se.options[se.selectedIndex].value == '__mce_add_custom__') {
ne = d.createElement("input");
ne.id = se.id + "_custom";
ne.name = se.name + "_custom";
ne.type = "text";
ne.style.width = se.offsetWidth + 'px';
se.parentNode.insertBefore(ne, se);
se.style.display = 'none';
ne.focus();
ne.onblur = TinyMCE_EditableSelects.onBlurEditableSelectInput;
ne.onkeydown = TinyMCE_EditableSelects.onKeyDown;
TinyMCE_EditableSelects.editSelectElm = se;
}
},
onBlurEditableSelectInput : function() {
var se = TinyMCE_EditableSelects.editSelectElm;
if (se) {
if (se.previousSibling.value != '') {
addSelectValue(document.forms[0], se.id, se.previousSibling.value, se.previousSibling.value);
selectByValue(document.forms[0], se.id, se.previousSibling.value);
} else
selectByValue(document.forms[0], se.id, '');
se.style.display = 'inline';
se.parentNode.removeChild(se.previousSibling);
TinyMCE_EditableSelects.editSelectElm = null;
}
},
onKeyDown : function(e) {
e = e || window.event;
if (e.keyCode == 13)
TinyMCE_EditableSelects.onBlurEditableSelectInput();
}
};
| JavaScript |
/**
* form_utils.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
var themeBaseURL = tinyMCEPopup.editor.baseURI.toAbsolute('themes/' + tinyMCEPopup.getParam("theme"));
function getColorPickerHTML(id, target_form_element) {
var h = "", dom = tinyMCEPopup.dom;
if (label = dom.select('label[for=' + target_form_element + ']')[0]) {
label.id = label.id || dom.uniqueId();
}
h += '<a role="button" aria-labelledby="' + id + '_label" id="' + id + '_link" href="javascript:;" onclick="tinyMCEPopup.pickColor(event,\'' + target_form_element +'\');" onmousedown="return false;" class="pickcolor">';
h += '<span id="' + id + '" title="' + tinyMCEPopup.getLang('browse') + '"> <span id="' + id + '_label" class="mceVoiceLabel mceIconOnly" style="display:none;">' + tinyMCEPopup.getLang('browse') + '</span></span></a>';
return h;
}
function updateColor(img_id, form_element_id) {
document.getElementById(img_id).style.backgroundColor = document.forms[0].elements[form_element_id].value;
}
function setBrowserDisabled(id, state) {
var img = document.getElementById(id);
var lnk = document.getElementById(id + "_link");
if (lnk) {
if (state) {
lnk.setAttribute("realhref", lnk.getAttribute("href"));
lnk.removeAttribute("href");
tinyMCEPopup.dom.addClass(img, 'disabled');
} else {
if (lnk.getAttribute("realhref"))
lnk.setAttribute("href", lnk.getAttribute("realhref"));
tinyMCEPopup.dom.removeClass(img, 'disabled');
}
}
}
function getBrowserHTML(id, target_form_element, type, prefix) {
var option = prefix + "_" + type + "_browser_callback", cb, html;
cb = tinyMCEPopup.getParam(option, tinyMCEPopup.getParam("file_browser_callback"));
if (!cb)
return "";
html = "";
html += '<a id="' + id + '_link" href="javascript:openBrowser(\'' + id + '\',\'' + target_form_element + '\', \'' + type + '\',\'' + option + '\');" onmousedown="return false;" class="browse">';
html += '<span id="' + id + '" title="' + tinyMCEPopup.getLang('browse') + '"> </span></a>';
return html;
}
function openBrowser(img_id, target_form_element, type, option) {
var img = document.getElementById(img_id);
if (img.className != "mceButtonDisabled")
tinyMCEPopup.openBrowser(target_form_element, type, option);
}
function selectByValue(form_obj, field_name, value, add_custom, ignore_case) {
if (!form_obj || !form_obj.elements[field_name])
return;
if (!value)
value = "";
var sel = form_obj.elements[field_name];
var found = false;
for (var i=0; i<sel.options.length; i++) {
var option = sel.options[i];
if (option.value == value || (ignore_case && option.value.toLowerCase() == value.toLowerCase())) {
option.selected = true;
found = true;
} else
option.selected = false;
}
if (!found && add_custom && value != '') {
var option = new Option(value, value);
option.selected = true;
sel.options[sel.options.length] = option;
sel.selectedIndex = sel.options.length - 1;
}
return found;
}
function getSelectValue(form_obj, field_name) {
var elm = form_obj.elements[field_name];
if (elm == null || elm.options == null || elm.selectedIndex === -1)
return "";
return elm.options[elm.selectedIndex].value;
}
function addSelectValue(form_obj, field_name, name, value) {
var s = form_obj.elements[field_name];
var o = new Option(name, value);
s.options[s.options.length] = o;
}
function addClassesToList(list_id, specific_option) {
// Setup class droplist
var styleSelectElm = document.getElementById(list_id);
var styles = tinyMCEPopup.getParam('theme_advanced_styles', false);
styles = tinyMCEPopup.getParam(specific_option, styles);
if (styles) {
var stylesAr = styles.split(';');
for (var i=0; i<stylesAr.length; i++) {
if (stylesAr != "") {
var key, value;
key = stylesAr[i].split('=')[0];
value = stylesAr[i].split('=')[1];
styleSelectElm.options[styleSelectElm.length] = new Option(key, value);
}
}
} else {
tinymce.each(tinyMCEPopup.editor.dom.getClasses(), function(o) {
styleSelectElm.options[styleSelectElm.length] = new Option(o.title || o['class'], o['class']);
});
}
}
function isVisible(element_id) {
var elm = document.getElementById(element_id);
return elm && elm.style.display != "none";
}
function convertRGBToHex(col) {
var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi");
var rgb = col.replace(re, "$1,$2,$3").split(',');
if (rgb.length == 3) {
r = parseInt(rgb[0]).toString(16);
g = parseInt(rgb[1]).toString(16);
b = parseInt(rgb[2]).toString(16);
r = r.length == 1 ? '0' + r : r;
g = g.length == 1 ? '0' + g : g;
b = b.length == 1 ? '0' + b : b;
return "#" + r + g + b;
}
return col;
}
function convertHexToRGB(col) {
if (col.indexOf('#') != -1) {
col = col.replace(new RegExp('[^0-9A-F]', 'gi'), '');
r = parseInt(col.substring(0, 2), 16);
g = parseInt(col.substring(2, 4), 16);
b = parseInt(col.substring(4, 6), 16);
return "rgb(" + r + "," + g + "," + b + ")";
}
return col;
}
function trimSize(size) {
return size.replace(/([0-9\.]+)(px|%|in|cm|mm|em|ex|pt|pc)/i, '$1$2');
}
function getCSSSize(size) {
size = trimSize(size);
if (size == "")
return "";
// Add px
if (/^[0-9]+$/.test(size))
size += 'px';
// Sanity check, IE doesn't like broken values
else if (!(/^[0-9\.]+(px|%|in|cm|mm|em|ex|pt|pc)$/i.test(size)))
return "";
return size;
}
function getStyle(elm, attrib, style) {
var val = tinyMCEPopup.dom.getAttrib(elm, attrib);
if (val != '')
return '' + val;
if (typeof(style) == 'undefined')
style = attrib;
return tinyMCEPopup.dom.getStyle(elm, style);
}
| JavaScript |
// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download.
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================
/* SOURCE FILE: AnchorPosition.js */
/*
AnchorPosition.js
Author: Matt Kruse
Last modified: 10/11/02
DESCRIPTION: These functions find the position of an <A> tag in a document,
so other elements can be positioned relative to it.
COMPATABILITY: Netscape 4.x,6.x,Mozilla, IE 5.x,6.x on Windows. Some small
positioning errors - usually with Window positioning - occur on the
Macintosh platform.
FUNCTIONS:
getAnchorPosition(anchorname)
Returns an Object() having .x and .y properties of the pixel coordinates
of the upper-left corner of the anchor. Position is relative to the PAGE.
getAnchorWindowPosition(anchorname)
Returns an Object() having .x and .y properties of the pixel coordinates
of the upper-left corner of the anchor, relative to the WHOLE SCREEN.
NOTES:
1) For popping up separate browser windows, use getAnchorWindowPosition.
Otherwise, use getAnchorPosition
2) Your anchor tag MUST contain both NAME and ID attributes which are the
same. For example:
<A NAME="test" ID="test"> </A>
3) There must be at least a space between <A> </A> for IE5.5 to see the
anchor tag correctly. Do not do <A></A> with no space.
*/
// getAnchorPosition(anchorname)
// This function returns an object having .x and .y properties which are the coordinates
// of the named anchor, relative to the page.
function getAnchorPosition(anchorname) {
// This function will return an Object with x and y properties
var useWindow=false;
var coordinates=new Object();
var x=0,y=0;
// Browser capability sniffing
var use_gebi=false, use_css=false, use_layers=false;
if (document.getElementById) { use_gebi=true; }
else if (document.all) { use_css=true; }
else if (document.layers) { use_layers=true; }
// Logic to find position
if (use_gebi && document.all) {
x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
y=AnchorPosition_getPageOffsetTop(document.all[anchorname]);
}
else if (use_gebi) {
var o=document.getElementById(anchorname);
x=AnchorPosition_getPageOffsetLeft(o);
y=AnchorPosition_getPageOffsetTop(o);
}
else if (use_css) {
x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
y=AnchorPosition_getPageOffsetTop(document.all[anchorname]);
}
else if (use_layers) {
var found=0;
for (var i=0; i<document.anchors.length; i++) {
if (document.anchors[i].name==anchorname) { found=1; break; }
}
if (found==0) {
coordinates.x=0; coordinates.y=0; return coordinates;
}
x=document.anchors[i].x;
y=document.anchors[i].y;
}
else {
coordinates.x=0; coordinates.y=0; return coordinates;
}
coordinates.x=x;
coordinates.y=y;
return coordinates;
}
// getAnchorWindowPosition(anchorname)
// This function returns an object having .x and .y properties which are the coordinates
// of the named anchor, relative to the window
function getAnchorWindowPosition(anchorname) {
var coordinates=getAnchorPosition(anchorname);
var x=0;
var y=0;
if (document.getElementById) {
if (isNaN(window.screenX)) {
x=coordinates.x-document.body.scrollLeft+window.screenLeft;
y=coordinates.y-document.body.scrollTop+window.screenTop;
}
else {
x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;
y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;
}
}
else if (document.all) {
x=coordinates.x-document.body.scrollLeft+window.screenLeft;
y=coordinates.y-document.body.scrollTop+window.screenTop;
}
else if (document.layers) {
x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;
y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;
}
coordinates.x=x;
coordinates.y=y;
return coordinates;
}
// Functions for IE to get position of an object
function AnchorPosition_getPageOffsetLeft (el) {
var ol=el.offsetLeft;
while ((el=el.offsetParent) != null) { ol += el.offsetLeft; }
return ol;
}
function AnchorPosition_getWindowOffsetLeft (el) {
return AnchorPosition_getPageOffsetLeft(el)-document.body.scrollLeft;
}
function AnchorPosition_getPageOffsetTop (el) {
var ot=el.offsetTop;
while((el=el.offsetParent) != null) { ot += el.offsetTop; }
return ot;
}
function AnchorPosition_getWindowOffsetTop (el) {
return AnchorPosition_getPageOffsetTop(el)-document.body.scrollTop;
}
/* SOURCE FILE: PopupWindow.js */
/*
PopupWindow.js
Author: Matt Kruse
Last modified: 02/16/04
DESCRIPTION: This object allows you to easily and quickly popup a window
in a certain place. The window can either be a DIV or a separate browser
window.
COMPATABILITY: Works with Netscape 4.x, 6.x, IE 5.x on Windows. Some small
positioning errors - usually with Window positioning - occur on the
Macintosh platform. Due to bugs in Netscape 4.x, populating the popup
window with <STYLE> tags may cause errors.
USAGE:
// Create an object for a WINDOW popup
var win = new PopupWindow();
// Create an object for a DIV window using the DIV named 'mydiv'
var win = new PopupWindow('mydiv');
// Set the window to automatically hide itself when the user clicks
// anywhere else on the page except the popup
win.autoHide();
// Show the window relative to the anchor name passed in
win.showPopup(anchorname);
// Hide the popup
win.hidePopup();
// Set the size of the popup window (only applies to WINDOW popups
win.setSize(width,height);
// Populate the contents of the popup window that will be shown. If you
// change the contents while it is displayed, you will need to refresh()
win.populate(string);
// set the URL of the window, rather than populating its contents
// manually
win.setUrl("http://www.site.com/");
// Refresh the contents of the popup
win.refresh();
// Specify how many pixels to the right of the anchor the popup will appear
win.offsetX = 50;
// Specify how many pixels below the anchor the popup will appear
win.offsetY = 100;
NOTES:
1) Requires the functions in AnchorPosition.js
2) Your anchor tag MUST contain both NAME and ID attributes which are the
same. For example:
<A NAME="test" ID="test"> </A>
3) There must be at least a space between <A> </A> for IE5.5 to see the
anchor tag correctly. Do not do <A></A> with no space.
4) When a PopupWindow object is created, a handler for 'onmouseup' is
attached to any event handler you may have already defined. Do NOT define
an event handler for 'onmouseup' after you define a PopupWindow object or
the autoHide() will not work correctly.
*/
// Set the position of the popup window based on the anchor
function PopupWindow_getXYPosition(anchorname) {
var coordinates;
if (this.type == "WINDOW") {
coordinates = getAnchorWindowPosition(anchorname);
}
else {
coordinates = getAnchorPosition(anchorname);
}
this.x = coordinates.x;
this.y = coordinates.y;
}
// Set width/height of DIV/popup window
function PopupWindow_setSize(width,height) {
this.width = width;
this.height = height;
}
// Fill the window with contents
function PopupWindow_populate(contents) {
this.contents = contents;
this.populated = false;
}
// Set the URL to go to
function PopupWindow_setUrl(url) {
this.url = url;
}
// Set the window popup properties
function PopupWindow_setWindowProperties(props) {
this.windowProperties = props;
}
// Refresh the displayed contents of the popup
function PopupWindow_refresh() {
if (this.divName != null) {
// refresh the DIV object
if (this.use_gebi) {
document.getElementById(this.divName).innerHTML = this.contents;
}
else if (this.use_css) {
document.all[this.divName].innerHTML = this.contents;
}
else if (this.use_layers) {
var d = document.layers[this.divName];
d.document.open();
d.document.writeln(this.contents);
d.document.close();
}
}
else {
if (this.popupWindow != null && !this.popupWindow.closed) {
if (this.url!="") {
this.popupWindow.location.href=this.url;
}
else {
this.popupWindow.document.open();
this.popupWindow.document.writeln(this.contents);
this.popupWindow.document.close();
}
this.popupWindow.focus();
}
}
}
// Position and show the popup, relative to an anchor object
function PopupWindow_showPopup(anchorname) {
this.getXYPosition(anchorname);
this.x += this.offsetX;
this.y += this.offsetY;
if (!this.populated && (this.contents != "")) {
this.populated = true;
this.refresh();
}
if (this.divName != null) {
// Show the DIV object
if (this.use_gebi) {
document.getElementById(this.divName).style.left = this.x + "px";
document.getElementById(this.divName).style.top = this.y;
document.getElementById(this.divName).style.visibility = "visible";
}
else if (this.use_css) {
document.all[this.divName].style.left = this.x;
document.all[this.divName].style.top = this.y;
document.all[this.divName].style.visibility = "visible";
}
else if (this.use_layers) {
document.layers[this.divName].left = this.x;
document.layers[this.divName].top = this.y;
document.layers[this.divName].visibility = "visible";
}
}
else {
if (this.popupWindow == null || this.popupWindow.closed) {
// If the popup window will go off-screen, move it so it doesn't
if (this.x<0) { this.x=0; }
if (this.y<0) { this.y=0; }
if (screen && screen.availHeight) {
if ((this.y + this.height) > screen.availHeight) {
this.y = screen.availHeight - this.height;
}
}
if (screen && screen.availWidth) {
if ((this.x + this.width) > screen.availWidth) {
this.x = screen.availWidth - this.width;
}
}
var avoidAboutBlank = window.opera || ( document.layers && !navigator.mimeTypes['*'] ) || navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled );
this.popupWindow = window.open(avoidAboutBlank?"":"about:blank","window_"+anchorname,this.windowProperties+",width="+this.width+",height="+this.height+",screenX="+this.x+",left="+this.x+",screenY="+this.y+",top="+this.y+"");
}
this.refresh();
}
}
// Hide the popup
function PopupWindow_hidePopup() {
if (this.divName != null) {
if (this.use_gebi) {
document.getElementById(this.divName).style.visibility = "hidden";
}
else if (this.use_css) {
document.all[this.divName].style.visibility = "hidden";
}
else if (this.use_layers) {
document.layers[this.divName].visibility = "hidden";
}
}
else {
if (this.popupWindow && !this.popupWindow.closed) {
this.popupWindow.close();
this.popupWindow = null;
}
}
}
// Pass an event and return whether or not it was the popup DIV that was clicked
function PopupWindow_isClicked(e) {
if (this.divName != null) {
if (this.use_layers) {
var clickX = e.pageX;
var clickY = e.pageY;
var t = document.layers[this.divName];
if ((clickX > t.left) && (clickX < t.left+t.clip.width) && (clickY > t.top) && (clickY < t.top+t.clip.height)) {
return true;
}
else { return false; }
}
else if (document.all) { // Need to hard-code this to trap IE for error-handling
var t = window.event.srcElement;
while (t.parentElement != null) {
if (t.id==this.divName) {
return true;
}
t = t.parentElement;
}
return false;
}
else if (this.use_gebi && e) {
var t = e.originalTarget;
while (t.parentNode != null) {
if (t.id==this.divName) {
return true;
}
t = t.parentNode;
}
return false;
}
return false;
}
return false;
}
// Check an onMouseDown event to see if we should hide
function PopupWindow_hideIfNotClicked(e) {
if (this.autoHideEnabled && !this.isClicked(e)) {
this.hidePopup();
}
}
// Call this to make the DIV disable automatically when mouse is clicked outside it
function PopupWindow_autoHide() {
this.autoHideEnabled = true;
}
// This global function checks all PopupWindow objects onmouseup to see if they should be hidden
function PopupWindow_hidePopupWindows(e) {
for (var i=0; i<popupWindowObjects.length; i++) {
if (popupWindowObjects[i] != null) {
var p = popupWindowObjects[i];
p.hideIfNotClicked(e);
}
}
}
// Run this immediately to attach the event listener
function PopupWindow_attachListener() {
if (document.layers) {
document.captureEvents(Event.MOUSEUP);
}
window.popupWindowOldEventListener = document.onmouseup;
if (window.popupWindowOldEventListener != null) {
document.onmouseup = new Function("window.popupWindowOldEventListener(); PopupWindow_hidePopupWindows();");
}
else {
document.onmouseup = PopupWindow_hidePopupWindows;
}
}
// CONSTRUCTOR for the PopupWindow object
// Pass it a DIV name to use a DHTML popup, otherwise will default to window popup
function PopupWindow() {
if (!window.popupWindowIndex) { window.popupWindowIndex = 0; }
if (!window.popupWindowObjects) { window.popupWindowObjects = new Array(); }
if (!window.listenerAttached) {
window.listenerAttached = true;
PopupWindow_attachListener();
}
this.index = popupWindowIndex++;
popupWindowObjects[this.index] = this;
this.divName = null;
this.popupWindow = null;
this.width=0;
this.height=0;
this.populated = false;
this.visible = false;
this.autoHideEnabled = false;
this.contents = "";
this.url="";
this.windowProperties="toolbar=no,location=no,status=no,menubar=no,scrollbars=auto,resizable,alwaysRaised,dependent,titlebar=no";
if (arguments.length>0) {
this.type="DIV";
this.divName = arguments[0];
}
else {
this.type="WINDOW";
}
this.use_gebi = false;
this.use_css = false;
this.use_layers = false;
if (document.getElementById) { this.use_gebi = true; }
else if (document.all) { this.use_css = true; }
else if (document.layers) { this.use_layers = true; }
else { this.type = "WINDOW"; }
this.offsetX = 0;
this.offsetY = 0;
// Method mappings
this.getXYPosition = PopupWindow_getXYPosition;
this.populate = PopupWindow_populate;
this.setUrl = PopupWindow_setUrl;
this.setWindowProperties = PopupWindow_setWindowProperties;
this.refresh = PopupWindow_refresh;
this.showPopup = PopupWindow_showPopup;
this.hidePopup = PopupWindow_hidePopup;
this.setSize = PopupWindow_setSize;
this.isClicked = PopupWindow_isClicked;
this.autoHide = PopupWindow_autoHide;
this.hideIfNotClicked = PopupWindow_hideIfNotClicked;
}
/* SOURCE FILE: ColorPicker2.js */
/*
Last modified: 02/24/2003
DESCRIPTION: This widget is used to select a color, in hexadecimal #RRGGBB
form. It uses a color "swatch" to display the standard 216-color web-safe
palette. The user can then click on a color to select it.
COMPATABILITY: See notes in AnchorPosition.js and PopupWindow.js.
Only the latest DHTML-capable browsers will show the color and hex values
at the bottom as your mouse goes over them.
USAGE:
// Create a new ColorPicker object using DHTML popup
var cp = new ColorPicker();
// Create a new ColorPicker object using Window Popup
var cp = new ColorPicker('window');
// Add a link in your page to trigger the popup. For example:
<A HREF="#" onClick="cp.show('pick');return false;" NAME="pick" ID="pick">Pick</A>
// Or use the built-in "select" function to do the dirty work for you:
<A HREF="#" onClick="cp.select(document.forms[0].color,'pick');return false;" NAME="pick" ID="pick">Pick</A>
// If using DHTML popup, write out the required DIV tag near the bottom
// of your page.
<SCRIPT LANGUAGE="JavaScript">cp.writeDiv()</SCRIPT>
// Write the 'pickColor' function that will be called when the user clicks
// a color and do something with the value. This is only required if you
// want to do something other than simply populate a form field, which is
// what the 'select' function will give you.
function pickColor(color) {
field.value = color;
}
NOTES:
1) Requires the functions in AnchorPosition.js and PopupWindow.js
2) Your anchor tag MUST contain both NAME and ID attributes which are the
same. For example:
<A NAME="test" ID="test"> </A>
3) There must be at least a space between <A> </A> for IE5.5 to see the
anchor tag correctly. Do not do <A></A> with no space.
4) When a ColorPicker object is created, a handler for 'onmouseup' is
attached to any event handler you may have already defined. Do NOT define
an event handler for 'onmouseup' after you define a ColorPicker object or
the color picker will not hide itself correctly.
*/
ColorPicker_targetInput = null;
function ColorPicker_writeDiv() {
document.writeln("<DIV ID=\"colorPickerDiv\" STYLE=\"position:absolute;visibility:hidden;\"> </DIV>");
}
function ColorPicker_show(anchorname) {
this.showPopup(anchorname);
}
function ColorPicker_pickColor(color,obj) {
obj.hidePopup();
pickColor(color);
}
// A Default "pickColor" function to accept the color passed back from popup.
// User can over-ride this with their own function.
function pickColor(color) {
if (ColorPicker_targetInput==null) {
alert("Target Input is null, which means you either didn't use the 'select' function or you have no defined your own 'pickColor' function to handle the picked color!");
return;
}
ColorPicker_targetInput.value = color;
}
// This function is the easiest way to popup the window, select a color, and
// have the value populate a form field, which is what most people want to do.
function ColorPicker_select(inputobj,linkname) {
if (inputobj.type!="text" && inputobj.type!="hidden" && inputobj.type!="textarea") {
alert("colorpicker.select: Input object passed is not a valid form input object");
window.ColorPicker_targetInput=null;
return;
}
window.ColorPicker_targetInput = inputobj;
this.show(linkname);
}
// This function runs when you move your mouse over a color block, if you have a newer browser
function ColorPicker_highlightColor(c) {
var thedoc = (arguments.length>1)?arguments[1]:window.document;
var d = thedoc.getElementById("colorPickerSelectedColor");
d.style.backgroundColor = c;
d = thedoc.getElementById("colorPickerSelectedColorValue");
d.innerHTML = c;
}
function ColorPicker() {
var windowMode = false;
// Create a new PopupWindow object
if (arguments.length==0) {
var divname = "colorPickerDiv";
}
else if (arguments[0] == "window") {
var divname = '';
windowMode = true;
}
else {
var divname = arguments[0];
}
if (divname != "") {
var cp = new PopupWindow(divname);
}
else {
var cp = new PopupWindow();
cp.setSize(225,250);
}
// Object variables
cp.currentValue = "#FFFFFF";
// Method Mappings
cp.writeDiv = ColorPicker_writeDiv;
cp.highlightColor = ColorPicker_highlightColor;
cp.show = ColorPicker_show;
cp.select = ColorPicker_select;
// Code to populate color picker window
var colors = new Array( "#4180B6","#69AEE7","#000000","#000033","#000066","#000099","#0000CC","#0000FF","#330000","#330033","#330066","#330099",
"#3300CC","#3300FF","#660000","#660033","#660066","#660099","#6600CC","#6600FF","#990000","#990033","#990066","#990099",
"#9900CC","#9900FF","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#FF0000","#FF0033","#FF0066","#FF0099",
"#FF00CC","#FF00FF","#7FFFFF","#7FFFFF","#7FF7F7","#7FEFEF","#7FE7E7","#7FDFDF","#7FD7D7","#7FCFCF","#7FC7C7","#7FBFBF",
"#7FB7B7","#7FAFAF","#7FA7A7","#7F9F9F","#7F9797","#7F8F8F","#7F8787","#7F7F7F","#7F7777","#7F6F6F","#7F6767","#7F5F5F",
"#7F5757","#7F4F4F","#7F4747","#7F3F3F","#7F3737","#7F2F2F","#7F2727","#7F1F1F","#7F1717","#7F0F0F","#7F0707","#7F0000",
"#4180B6","#69AEE7","#003300","#003333","#003366","#003399","#0033CC","#0033FF","#333300","#333333","#333366","#333399",
"#3333CC","#3333FF","#663300","#663333","#663366","#663399","#6633CC","#6633FF","#993300","#993333","#993366","#993399",
"#9933CC","#9933FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#FF3300","#FF3333","#FF3366","#FF3399",
"#FF33CC","#FF33FF","#FF7FFF","#FF7FFF","#F77FF7","#EF7FEF","#E77FE7","#DF7FDF","#D77FD7","#CF7FCF","#C77FC7","#BF7FBF",
"#B77FB7","#AF7FAF","#A77FA7","#9F7F9F","#977F97","#8F7F8F","#877F87","#7F7F7F","#777F77","#6F7F6F","#677F67","#5F7F5F",
"#577F57","#4F7F4F","#477F47","#3F7F3F","#377F37","#2F7F2F","#277F27","#1F7F1F","#177F17","#0F7F0F","#077F07","#007F00",
"#4180B6","#69AEE7","#006600","#006633","#006666","#006699","#0066CC","#0066FF","#336600","#336633","#336666","#336699",
"#3366CC","#3366FF","#666600","#666633","#666666","#666699","#6666CC","#6666FF","#996600","#996633","#996666","#996699",
"#9966CC","#9966FF","#CC6600","#CC6633","#CC6666","#CC6699","#CC66CC","#CC66FF","#FF6600","#FF6633","#FF6666","#FF6699",
"#FF66CC","#FF66FF","#FFFF7F","#FFFF7F","#F7F77F","#EFEF7F","#E7E77F","#DFDF7F","#D7D77F","#CFCF7F","#C7C77F","#BFBF7F",
"#B7B77F","#AFAF7F","#A7A77F","#9F9F7F","#97977F","#8F8F7F","#87877F","#7F7F7F","#77777F","#6F6F7F","#67677F","#5F5F7F",
"#57577F","#4F4F7F","#47477F","#3F3F7F","#37377F","#2F2F7F","#27277F","#1F1F7F","#17177F","#0F0F7F","#07077F","#00007F",
"#4180B6","#69AEE7","#009900","#009933","#009966","#009999","#0099CC","#0099FF","#339900","#339933","#339966","#339999",
"#3399CC","#3399FF","#669900","#669933","#669966","#669999","#6699CC","#6699FF","#999900","#999933","#999966","#999999",
"#9999CC","#9999FF","#CC9900","#CC9933","#CC9966","#CC9999","#CC99CC","#CC99FF","#FF9900","#FF9933","#FF9966","#FF9999",
"#FF99CC","#FF99FF","#3FFFFF","#3FFFFF","#3FF7F7","#3FEFEF","#3FE7E7","#3FDFDF","#3FD7D7","#3FCFCF","#3FC7C7","#3FBFBF",
"#3FB7B7","#3FAFAF","#3FA7A7","#3F9F9F","#3F9797","#3F8F8F","#3F8787","#3F7F7F","#3F7777","#3F6F6F","#3F6767","#3F5F5F",
"#3F5757","#3F4F4F","#3F4747","#3F3F3F","#3F3737","#3F2F2F","#3F2727","#3F1F1F","#3F1717","#3F0F0F","#3F0707","#3F0000",
"#4180B6","#69AEE7","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#33CC00","#33CC33","#33CC66","#33CC99",
"#33CCCC","#33CCFF","#66CC00","#66CC33","#66CC66","#66CC99","#66CCCC","#66CCFF","#99CC00","#99CC33","#99CC66","#99CC99",
"#99CCCC","#99CCFF","#CCCC00","#CCCC33","#CCCC66","#CCCC99","#CCCCCC","#CCCCFF","#FFCC00","#FFCC33","#FFCC66","#FFCC99",
"#FFCCCC","#FFCCFF","#FF3FFF","#FF3FFF","#F73FF7","#EF3FEF","#E73FE7","#DF3FDF","#D73FD7","#CF3FCF","#C73FC7","#BF3FBF",
"#B73FB7","#AF3FAF","#A73FA7","#9F3F9F","#973F97","#8F3F8F","#873F87","#7F3F7F","#773F77","#6F3F6F","#673F67","#5F3F5F",
"#573F57","#4F3F4F","#473F47","#3F3F3F","#373F37","#2F3F2F","#273F27","#1F3F1F","#173F17","#0F3F0F","#073F07","#003F00",
"#4180B6","#69AEE7","#00FF00","#00FF33","#00FF66","#00FF99","#00FFCC","#00FFFF","#33FF00","#33FF33","#33FF66","#33FF99",
"#33FFCC","#33FFFF","#66FF00","#66FF33","#66FF66","#66FF99","#66FFCC","#66FFFF","#99FF00","#99FF33","#99FF66","#99FF99",
"#99FFCC","#99FFFF","#CCFF00","#CCFF33","#CCFF66","#CCFF99","#CCFFCC","#CCFFFF","#FFFF00","#FFFF33","#FFFF66","#FFFF99",
"#FFFFCC","#FFFFFF","#FFFF3F","#FFFF3F","#F7F73F","#EFEF3F","#E7E73F","#DFDF3F","#D7D73F","#CFCF3F","#C7C73F","#BFBF3F",
"#B7B73F","#AFAF3F","#A7A73F","#9F9F3F","#97973F","#8F8F3F","#87873F","#7F7F3F","#77773F","#6F6F3F","#67673F","#5F5F3F",
"#57573F","#4F4F3F","#47473F","#3F3F3F","#37373F","#2F2F3F","#27273F","#1F1F3F","#17173F","#0F0F3F","#07073F","#00003F",
"#4180B6","#69AEE7","#FFFFFF","#FFEEEE","#FFDDDD","#FFCCCC","#FFBBBB","#FFAAAA","#FF9999","#FF8888","#FF7777","#FF6666",
"#FF5555","#FF4444","#FF3333","#FF2222","#FF1111","#FF0000","#FF0000","#FF0000","#FF0000","#EE0000","#DD0000","#CC0000",
"#BB0000","#AA0000","#990000","#880000","#770000","#660000","#550000","#440000","#330000","#220000","#110000","#000000",
"#000000","#000000","#000000","#001111","#002222","#003333","#004444","#005555","#006666","#007777","#008888","#009999",
"#00AAAA","#00BBBB","#00CCCC","#00DDDD","#00EEEE","#00FFFF","#00FFFF","#00FFFF","#00FFFF","#11FFFF","#22FFFF","#33FFFF",
"#44FFFF","#55FFFF","#66FFFF","#77FFFF","#88FFFF","#99FFFF","#AAFFFF","#BBFFFF","#CCFFFF","#DDFFFF","#EEFFFF","#FFFFFF",
"#4180B6","#69AEE7","#FFFFFF","#EEFFEE","#DDFFDD","#CCFFCC","#BBFFBB","#AAFFAA","#99FF99","#88FF88","#77FF77","#66FF66",
"#55FF55","#44FF44","#33FF33","#22FF22","#11FF11","#00FF00","#00FF00","#00FF00","#00FF00","#00EE00","#00DD00","#00CC00",
"#00BB00","#00AA00","#009900","#008800","#007700","#006600","#005500","#004400","#003300","#002200","#001100","#000000",
"#000000","#000000","#000000","#110011","#220022","#330033","#440044","#550055","#660066","#770077","#880088","#990099",
"#AA00AA","#BB00BB","#CC00CC","#DD00DD","#EE00EE","#FF00FF","#FF00FF","#FF00FF","#FF00FF","#FF11FF","#FF22FF","#FF33FF",
"#FF44FF","#FF55FF","#FF66FF","#FF77FF","#FF88FF","#FF99FF","#FFAAFF","#FFBBFF","#FFCCFF","#FFDDFF","#FFEEFF","#FFFFFF",
"#4180B6","#69AEE7","#FFFFFF","#EEEEFF","#DDDDFF","#CCCCFF","#BBBBFF","#AAAAFF","#9999FF","#8888FF","#7777FF","#6666FF",
"#5555FF","#4444FF","#3333FF","#2222FF","#1111FF","#0000FF","#0000FF","#0000FF","#0000FF","#0000EE","#0000DD","#0000CC",
"#0000BB","#0000AA","#000099","#000088","#000077","#000066","#000055","#000044","#000033","#000022","#000011","#000000",
"#000000","#000000","#000000","#111100","#222200","#333300","#444400","#555500","#666600","#777700","#888800","#999900",
"#AAAA00","#BBBB00","#CCCC00","#DDDD00","#EEEE00","#FFFF00","#FFFF00","#FFFF00","#FFFF00","#FFFF11","#FFFF22","#FFFF33",
"#FFFF44","#FFFF55","#FFFF66","#FFFF77","#FFFF88","#FFFF99","#FFFFAA","#FFFFBB","#FFFFCC","#FFFFDD","#FFFFEE","#FFFFFF",
"#4180B6","#69AEE7","#FFFFFF","#FFFFFF","#FBFBFB","#F7F7F7","#F3F3F3","#EFEFEF","#EBEBEB","#E7E7E7","#E3E3E3","#DFDFDF",
"#DBDBDB","#D7D7D7","#D3D3D3","#CFCFCF","#CBCBCB","#C7C7C7","#C3C3C3","#BFBFBF","#BBBBBB","#B7B7B7","#B3B3B3","#AFAFAF",
"#ABABAB","#A7A7A7","#A3A3A3","#9F9F9F","#9B9B9B","#979797","#939393","#8F8F8F","#8B8B8B","#878787","#838383","#7F7F7F",
"#7B7B7B","#777777","#737373","#6F6F6F","#6B6B6B","#676767","#636363","#5F5F5F","#5B5B5B","#575757","#535353","#4F4F4F",
"#4B4B4B","#474747","#434343","#3F3F3F","#3B3B3B","#373737","#333333","#2F2F2F","#2B2B2B","#272727","#232323","#1F1F1F",
"#1B1B1B","#171717","#131313","#0F0F0F","#0B0B0B","#070707","#030303","#000000","#000000","#000000","#000000","#000000");
var total = colors.length;
var width = 72;
var cp_contents = "";
var windowRef = (windowMode)?"window.opener.":"";
if (windowMode) {
cp_contents += "<html><head><title>Select Color</title></head>";
cp_contents += "<body marginwidth=0 marginheight=0 leftmargin=0 topmargin=0><span style='text-align: center;'>";
}
cp_contents += "<table style='border: none;' cellspacing=0 cellpadding=0>";
var use_highlight = (document.getElementById || document.all)?true:false;
for (var i=0; i<total; i++) {
if ((i % width) == 0) { cp_contents += "<tr>"; }
if (use_highlight) { var mo = 'onMouseOver="'+windowRef+'ColorPicker_highlightColor(\''+colors[i]+'\',window.document)"'; }
else { mo = ""; }
cp_contents += '<td style="background-color: '+colors[i]+';"><a href="javascript:void()" onclick="'+windowRef+'ColorPicker_pickColor(\''+colors[i]+'\','+windowRef+'window.popupWindowObjects['+cp.index+']);return false;" '+mo+'> </a></td>';
if ( ((i+1)>=total) || (((i+1) % width) == 0)) {
cp_contents += "</tr>";
}
}
// If the browser supports dynamically changing TD cells, add the fancy stuff
if (document.getElementById) {
var width1 = Math.floor(width/2);
var width2 = width = width1;
cp_contents += "<tr><td colspan='"+width1+"' style='background-color: #FFF;' ID='colorPickerSelectedColor'> </td><td colspan='"+width2+"' style='text-align: center;' id='colorPickerSelectedColorValue'>#FFFFFF</td></tr>";
}
cp_contents += "</table>";
if (windowMode) {
cp_contents += "</span></body></html>";
}
// end populate code
// Write the contents to the popup object
cp.populate(cp_contents+"\n");
// Move the table down a bit so you can see it
cp.offsetY = 25;
cp.autoHide();
return cp;
}
| JavaScript |
/*
* Quicktags
*
* This is the HTML editor in WordPress. It can be attached to any textarea and will
* append a toolbar above it. This script is self-contained (does not require external libraries).
*
* Run quicktags(settings) to initialize it, where settings is an object containing up to 3 properties:
* settings = {
* id : 'my_id', the HTML ID of the textarea, required
* buttons: '' Comma separated list of the names of the default buttons to show. Optional.
* Current list of default button names: 'strong,em,link,block,del,ins,img,ul,ol,li,code,more,spell,close';
* }
*
* The settings can also be a string quicktags_id.
*
* quicktags_id string The ID of the textarea that will be the editor canvas
* buttons string Comma separated list of the default buttons names that will be shown in that instance.
*/
// new edit toolbar used with permission
// by Alex King
// http://www.alexking.org/
var QTags, edButtons = [], edCanvas,
/**
* Back-compat
*
* Define all former global functions so plugins that hack quicktags.js directly don't cause fatal errors.
*/
edAddTag = function(){},
edCheckOpenTags = function(){},
edCloseAllTags = function(){},
edInsertImage = function(){},
edInsertLink = function(){},
edInsertTag = function(){},
edLink = function(){},
edQuickLink = function(){},
edRemoveTag = function(){},
edShowButton = function(){},
edShowLinks = function(){},
edSpell = function(){},
edToolbar = function(){};
/**
* Initialize new instance of the Quicktags editor
*/
function quicktags(settings) {
return new QTags(settings);
}
/**
* Inserts content at the caret in the active editor (textarea)
*
* Added for back compatibility
* @see QTags.insertContent()
*/
function edInsertContent(bah, txt) {
return QTags.insertContent(txt);
}
/**
* Adds a button to all instances of the editor
*
* Added for back compatibility, use QTags.addButton() as it gives more flexibility like type of button, button placement, etc.
* @see QTags.addButton()
*/
function edButton(id, display, tagStart, tagEnd, access, open) {
return QTags.addButton( id, display, tagStart, tagEnd, access, '', -1 );
}
(function(){
// private stuff is prefixed with an underscore
var _domReady = function(func) {
var t, i, DOMContentLoaded;
if ( typeof jQuery != 'undefined' ) {
jQuery(document).ready(func);
} else {
t = _domReady;
t.funcs = [];
t.ready = function() {
if ( ! t.isReady ) {
t.isReady = true;
for ( i = 0; i < t.funcs.length; i++ ) {
t.funcs[i]();
}
}
};
if ( t.isReady ) {
func();
} else {
t.funcs.push(func);
}
if ( ! t.eventAttached ) {
if ( document.addEventListener ) {
DOMContentLoaded = function(){document.removeEventListener('DOMContentLoaded', DOMContentLoaded, false);t.ready();};
document.addEventListener('DOMContentLoaded', DOMContentLoaded, false);
window.addEventListener('load', t.ready, false);
} else if ( document.attachEvent ) {
DOMContentLoaded = function(){if (document.readyState === 'complete'){ document.detachEvent('onreadystatechange', DOMContentLoaded);t.ready();}};
document.attachEvent('onreadystatechange', DOMContentLoaded);
window.attachEvent('onload', t.ready);
(function(){
try {
document.documentElement.doScroll("left");
} catch(e) {
setTimeout(arguments.callee, 50);
return;
}
t.ready();
})();
}
t.eventAttached = true;
}
}
},
_datetime = (function() {
var now = new Date(), zeroise;
zeroise = function(number) {
var str = number.toString();
if ( str.length < 2 )
str = "0" + str;
return str;
}
return now.getUTCFullYear() + '-' +
zeroise( now.getUTCMonth() + 1 ) + '-' +
zeroise( now.getUTCDate() ) + 'T' +
zeroise( now.getUTCHours() ) + ':' +
zeroise( now.getUTCMinutes() ) + ':' +
zeroise( now.getUTCSeconds() ) +
'+00:00';
})(),
qt;
qt = QTags = function(settings) {
if ( typeof(settings) == 'string' )
settings = {id: settings};
else if ( typeof(settings) != 'object' )
return false;
var t = this,
id = settings.id,
canvas = document.getElementById(id),
name = 'qt_' + id,
tb, onclick, toolbar_id;
if ( !id || !canvas )
return false;
t.name = name;
t.id = id;
t.canvas = canvas;
t.settings = settings;
if ( id == 'content' && typeof(adminpage) == 'string' && ( adminpage == 'post-new-php' || adminpage == 'post-php' ) ) {
// back compat hack :-(
edCanvas = canvas;
toolbar_id = 'ed_toolbar';
} else {
toolbar_id = name + '_toolbar';
}
tb = document.createElement('div');
tb.id = toolbar_id;
tb.className = 'quicktags-toolbar';
canvas.parentNode.insertBefore(tb, canvas);
t.toolbar = tb;
// listen for click events
onclick = function(e) {
e = e || window.event;
var target = e.target || e.srcElement, i;
// as long as it has the class ed_button, execute the callback
if ( / ed_button /.test(' ' + target.className + ' ') ) {
// we have to reassign canvas here
t.canvas = canvas = document.getElementById(id);
i = target.id.replace(name + '_', '');
if ( t.theButtons[i] )
t.theButtons[i].callback.call(t.theButtons[i], target, canvas, t);
}
};
if ( tb.addEventListener ) {
tb.addEventListener('click', onclick, false);
} else if ( tb.attachEvent ) {
tb.attachEvent('onclick', onclick);
}
t.getButton = function(id) {
return t.theButtons[id];
};
t.getButtonElement = function(id) {
return document.getElementById(name + '_' + id);
};
qt.instances[id] = t;
if ( !qt.instances[0] ) {
qt.instances[0] = qt.instances[id];
_domReady( function(){ qt._buttonsInit(); } );
}
};
qt.instances = {};
qt.getInstance = function(id) {
return qt.instances[id];
};
qt._buttonsInit = function() {
var t = this, canvas, name, settings, theButtons, html, inst, ed, id, i, use,
defaults = ',strong,em,link,block,del,ins,img,ul,ol,li,code,more,spell,close,';
for ( inst in t.instances ) {
if ( inst == 0 )
continue;
ed = t.instances[inst];
canvas = ed.canvas;
name = ed.name;
settings = ed.settings;
html = '';
theButtons = {};
use = '';
// set buttons
if ( settings.buttons )
use = ','+settings.buttons+',';
for ( i in edButtons ) {
if ( !edButtons[i] )
continue;
id = edButtons[i].id;
if ( use && defaults.indexOf(','+id+',') != -1 && use.indexOf(','+id+',') == -1 )
continue;
if ( !edButtons[i].instance || edButtons[i].instance == inst ) {
theButtons[id] = edButtons[i];
if ( edButtons[i].html )
html += edButtons[i].html(name + '_');
}
}
if ( use && use.indexOf(',fullscreen,') != -1 ) {
theButtons['fullscreen'] = new qt.FullscreenButton();
html += theButtons['fullscreen'].html(name + '_');
}
ed.toolbar.innerHTML = html;
ed.theButtons = theButtons;
}
t.buttonsInitDone = true;
};
/**
* Main API function for adding a button to Quicktags
*
* Adds qt.Button or qt.TagButton depending on the args. The first three args are always required.
* To be able to add button(s) to Quicktags, your script should be enqueued as dependent
* on "quicktags" and outputted in the footer. If you are echoing JS directly from PHP,
* use add_action( 'admin_print_footer_scripts', 'output_my_js', 100 ) or add_action( 'wp_footer', 'output_my_js', 100 )
*
* Minimum required to add a button that calls an external function:
* QTags.addButton( 'my_id', 'my button', my_callback );
* function my_callback() { alert('yeah!'); }
*
* Minimum required to add a button that inserts a tag:
* QTags.addButton( 'my_id', 'my button', '<span>', '</span>' );
* QTags.addButton( 'my_id2', 'my button', '<br />' );
*
* @param id string required Button HTML ID
* @param display string required Button's value="..."
* @param arg1 string || function required Either a starting tag to be inserted like "<span>" or a callback that is executed when the button is clicked.
* @param arg2 string optional Ending tag like "</span>"
* @param access_key string optional Access key for the button.
* @param title string optional Button's title="..."
* @param priority int optional Number representing the desired position of the button in the toolbar. 1 - 9 = first, 11 - 19 = second, 21 - 29 = third, etc.
* @param instance string optional Limit the button to a specifric instance of Quicktags, add to all instances if not present.
* @return mixed null or the button object that is needed for back-compat.
*/
qt.addButton = function( id, display, arg1, arg2, access_key, title, priority, instance ) {
var btn;
if ( !id || !display )
return;
priority = priority || 0;
arg2 = arg2 || '';
if ( typeof(arg1) === 'function' ) {
btn = new qt.Button(id, display, access_key, title, instance);
btn.callback = arg1;
} else if ( typeof(arg1) === 'string' ) {
btn = new qt.TagButton(id, display, arg1, arg2, access_key, title, instance);
} else {
return;
}
if ( priority == -1 ) // back-compat
return btn;
if ( priority > 0 ) {
while ( typeof(edButtons[priority]) != 'undefined' ) {
priority++
}
edButtons[priority] = btn;
} else {
edButtons[edButtons.length] = btn;
}
if ( this.buttonsInitDone )
this._buttonsInit(); // add the button HTML to all instances toolbars if addButton() was called too late
};
qt.insertContent = function(content) {
var sel, startPos, endPos, scrollTop, text, canvas = document.getElementById(wpActiveEditor);
if ( !canvas )
return false;
if ( document.selection ) { //IE
canvas.focus();
sel = document.selection.createRange();
sel.text = content;
canvas.focus();
} else if ( canvas.selectionStart || canvas.selectionStart == '0' ) { // FF, WebKit, Opera
text = canvas.value;
startPos = canvas.selectionStart;
endPos = canvas.selectionEnd;
scrollTop = canvas.scrollTop;
canvas.value = text.substring(0, startPos) + content + text.substring(endPos, text.length);
canvas.focus();
canvas.selectionStart = startPos + content.length;
canvas.selectionEnd = startPos + content.length;
canvas.scrollTop = scrollTop;
} else {
canvas.value += content;
canvas.focus();
}
return true;
};
// a plain, dumb button
qt.Button = function(id, display, access, title, instance) {
var t = this;
t.id = id;
t.display = display;
t.access = access;
t.title = title || '';
t.instance = instance || '';
};
qt.Button.prototype.html = function(idPrefix) {
var access = this.access ? ' accesskey="' + this.access + '"' : '';
return '<input type="button" id="' + idPrefix + this.id + '"' + access + ' class="ed_button" title="' + this.title + '" value="' + this.display + '" />';
};
qt.Button.prototype.callback = function(){};
// a button that inserts HTML tag
qt.TagButton = function(id, display, tagStart, tagEnd, access, title, instance) {
var t = this;
qt.Button.call(t, id, display, access, title, instance);
t.tagStart = tagStart;
t.tagEnd = tagEnd;
};
qt.TagButton.prototype = new qt.Button();
qt.TagButton.prototype.openTag = function(e, ed) {
var t = this;
if ( ! ed.openTags ) {
ed.openTags = [];
}
if ( t.tagEnd ) {
ed.openTags.push(t.id);
e.value = '/' + e.value;
}
};
qt.TagButton.prototype.closeTag = function(e, ed) {
var t = this, i = t.isOpen(ed);
if ( i !== false ) {
ed.openTags.splice(i, 1);
}
e.value = t.display;
};
// whether a tag is open or not. Returns false if not open, or current open depth of the tag
qt.TagButton.prototype.isOpen = function (ed) {
var t = this, i = 0, ret = false;
if ( ed.openTags ) {
while ( ret === false && i < ed.openTags.length ) {
ret = ed.openTags[i] == t.id ? i : false;
i ++;
}
} else {
ret = false;
}
return ret;
};
qt.TagButton.prototype.callback = function(element, canvas, ed) {
var t = this, startPos, endPos, cursorPos, scrollTop, v = canvas.value, l, r, i, sel, endTag = v ? t.tagEnd : '';
if ( document.selection ) { // IE
canvas.focus();
sel = document.selection.createRange();
if ( sel.text.length > 0 ) {
if ( !t.tagEnd )
sel.text = sel.text + t.tagStart;
else
sel.text = t.tagStart + sel.text + endTag;
} else {
if ( !t.tagEnd ) {
sel.text = t.tagStart;
} else if ( t.isOpen(ed) === false ) {
sel.text = t.tagStart;
t.openTag(element, ed);
} else {
sel.text = endTag;
t.closeTag(element, ed);
}
}
canvas.focus();
} else if ( canvas.selectionStart || canvas.selectionStart == '0' ) { // FF, WebKit, Opera
startPos = canvas.selectionStart;
endPos = canvas.selectionEnd;
cursorPos = endPos;
scrollTop = canvas.scrollTop;
l = v.substring(0, startPos); // left of the selection
r = v.substring(endPos, v.length); // right of the selection
i = v.substring(startPos, endPos); // inside the selection
if ( startPos != endPos ) {
if ( !t.tagEnd ) {
canvas.value = l + i + t.tagStart + r; // insert self closing tags after the selection
cursorPos += t.tagStart.length;
} else {
canvas.value = l + t.tagStart + i + endTag + r;
cursorPos += t.tagStart.length + endTag.length;
}
} else {
if ( !t.tagEnd ) {
canvas.value = l + t.tagStart + r;
cursorPos = startPos + t.tagStart.length;
} else if ( t.isOpen(ed) === false ) {
canvas.value = l + t.tagStart + r;
t.openTag(element, ed);
cursorPos = startPos + t.tagStart.length;
} else {
canvas.value = l + endTag + r;
cursorPos = startPos + endTag.length;
t.closeTag(element, ed);
}
}
canvas.focus();
canvas.selectionStart = cursorPos;
canvas.selectionEnd = cursorPos;
canvas.scrollTop = scrollTop;
} else { // other browsers?
if ( !endTag ) {
canvas.value += t.tagStart;
} else if ( t.isOpen(ed) !== false ) {
canvas.value += t.tagStart;
t.openTag(element, ed);
} else {
canvas.value += endTag;
t.closeTag(element, ed);
}
canvas.focus();
}
};
// the spell button
qt.SpellButton = function() {
qt.Button.call(this, 'spell', quicktagsL10n.lookup, '', quicktagsL10n.dictionaryLookup);
};
qt.SpellButton.prototype = new qt.Button();
qt.SpellButton.prototype.callback = function(element, canvas, ed) {
var word = '', sel, startPos, endPos;
if ( document.selection ) {
canvas.focus();
sel = document.selection.createRange();
if ( sel.text.length > 0 ) {
word = sel.text;
}
} else if ( canvas.selectionStart || canvas.selectionStart == '0' ) {
startPos = canvas.selectionStart;
endPos = canvas.selectionEnd;
if ( startPos != endPos ) {
word = canvas.value.substring(startPos, endPos);
}
}
if ( word === '' ) {
word = prompt(quicktagsL10n.wordLookup, '');
}
if ( word !== null && /^\w[\w ]*$/.test(word)) {
window.open('http://www.answers.com/' + encodeURIComponent(word));
}
};
// the close tags button
qt.CloseButton = function() {
qt.Button.call(this, 'close', quicktagsL10n.closeTags, '', quicktagsL10n.closeAllOpenTags);
};
qt.CloseButton.prototype = new qt.Button();
qt._close = function(e, c, ed) {
var button, element, tbo = ed.openTags;
if ( tbo ) {
while ( tbo.length > 0 ) {
button = ed.getButton(tbo[tbo.length - 1]);
element = document.getElementById(ed.name + '_' + button.id);
if ( e )
button.callback.call(button, element, c, ed);
else
button.closeTag(element, ed);
}
}
};
qt.CloseButton.prototype.callback = qt._close;
qt.closeAllTags = function(editor_id) {
var ed = this.getInstance(editor_id);
qt._close('', ed.canvas, ed);
};
// the link button
qt.LinkButton = function() {
qt.TagButton.call(this, 'link', 'link', '', '</a>', 'a');
};
qt.LinkButton.prototype = new qt.TagButton();
qt.LinkButton.prototype.callback = function(e, c, ed, defaultValue) {
var URL, t = this;
if ( typeof(wpLink) != 'undefined' ) {
wpLink.open();
return;
}
if ( ! defaultValue )
defaultValue = 'http://';
if ( t.isOpen(ed) === false ) {
URL = prompt(quicktagsL10n.enterURL, defaultValue);
if ( URL ) {
t.tagStart = '<a href="' + URL + '">';
qt.TagButton.prototype.callback.call(t, e, c, ed);
}
} else {
qt.TagButton.prototype.callback.call(t, e, c, ed);
}
};
// the img button
qt.ImgButton = function() {
qt.TagButton.call(this, 'img', 'img', '', '', 'm');
};
qt.ImgButton.prototype = new qt.TagButton();
qt.ImgButton.prototype.callback = function(e, c, ed, defaultValue) {
if ( ! defaultValue ) {
defaultValue = 'http://';
}
var src = prompt(quicktagsL10n.enterImageURL, defaultValue), alt;
if ( src ) {
alt = prompt(quicktagsL10n.enterImageDescription, '');
this.tagStart = '<img src="' + src + '" alt="' + alt + '" />';
qt.TagButton.prototype.callback.call(this, e, c, ed);
}
};
qt.FullscreenButton = function() {
qt.Button.call(this, 'fullscreen', quicktagsL10n.fullscreen, 'f', quicktagsL10n.toggleFullscreen);
};
qt.FullscreenButton.prototype = new qt.Button();
qt.FullscreenButton.prototype.callback = function(e, c) {
if ( c.id != 'content' || typeof(fullscreen) == 'undefined' )
return;
fullscreen.on();
};
// ensure backward compatibility
edButtons[10] = new qt.TagButton('strong','b','<strong>','</strong>','b');
edButtons[20] = new qt.TagButton('em','i','<em>','</em>','i'),
edButtons[30] = new qt.LinkButton(), // special case
edButtons[40] = new qt.TagButton('block','b-quote','\n\n<blockquote>','</blockquote>\n\n','q'),
edButtons[50] = new qt.TagButton('del','del','<del datetime="' + _datetime + '">','</del>','d'),
edButtons[60] = new qt.TagButton('ins','ins','<ins datetime="' + _datetime + '">','</ins>','s'),
edButtons[70] = new qt.ImgButton(), // special case
edButtons[80] = new qt.TagButton('ul','ul','<ul>\n','</ul>\n\n','u'),
edButtons[90] = new qt.TagButton('ol','ol','<ol>\n','</ol>\n\n','o'),
edButtons[100] = new qt.TagButton('li','li','\t<li>','</li>\n','l'),
edButtons[110] = new qt.TagButton('code','code','<code>','</code>','c'),
edButtons[120] = new qt.TagButton('more','more','<!--more-->','','t'),
edButtons[130] = new qt.SpellButton(),
edButtons[140] = new qt.CloseButton()
})();
| JavaScript |
/**
* Pointer jQuery widget.
*/
(function($){
var identifier = 0,
zindex = 9999;
$.widget("wp.pointer", {
options: {
pointerClass: 'wp-pointer',
pointerWidth: 320,
content: function( respond, event, t ) {
return $(this).text();
},
buttons: function( event, t ) {
var close = ( wpPointerL10n ) ? wpPointerL10n.dismiss : 'Dismiss',
button = $('<a class="close" href="#">' + close + '</a>');
return button.bind( 'click.pointer', function(e) {
e.preventDefault();
t.element.pointer('close');
});
},
position: 'top',
show: function( event, t ) {
t.pointer.show();
t.opened();
},
hide: function( event, t ) {
t.pointer.hide();
t.closed();
},
document: document
},
_create: function() {
var positioning,
family;
this.content = $('<div class="wp-pointer-content"></div>');
this.arrow = $('<div class="wp-pointer-arrow"><div class="wp-pointer-arrow-inner"></div></div>');
family = this.element.parents().add( this.element );
positioning = 'absolute';
if ( family.filter(function(){ return 'fixed' === $(this).css('position'); }).length )
positioning = 'fixed';
this.pointer = $('<div />')
.append( this.content )
.append( this.arrow )
.attr('id', 'wp-pointer-' + identifier++)
.addClass( this.options.pointerClass )
.css({'position': positioning, 'width': this.options.pointerWidth+'px', 'display': 'none'})
.appendTo( this.options.document.body );
},
_setOption: function( key, value ) {
var o = this.options,
tip = this.pointer;
// Handle document transfer
if ( key === "document" && value !== o.document ) {
tip.detach().appendTo( value.body );
// Handle class change
} else if ( key === "pointerClass" ) {
tip.removeClass( o.pointerClass ).addClass( value );
}
// Call super method.
$.Widget.prototype._setOption.apply( this, arguments );
// Reposition automatically
if ( key === "position" ) {
this.reposition();
// Update content automatically if pointer is open
} else if ( key === "content" && this.active ) {
this.update();
}
},
destroy: function() {
this.pointer.remove();
$.Widget.prototype.destroy.call( this );
},
widget: function() {
return this.pointer;
},
update: function( event ) {
var self = this,
o = this.options,
dfd = $.Deferred(),
content;
if ( o.disabled )
return;
dfd.done( function( content ) {
self._update( event, content );
})
// Either o.content is a string...
if ( typeof o.content === 'string' ) {
content = o.content;
// ...or o.content is a callback.
} else {
content = o.content.call( this.element[0], dfd.resolve, event, this._handoff() );
}
// If content is set, then complete the update.
if ( content )
dfd.resolve( content );
return dfd.promise();
},
/**
* Update is separated into two functions to allow events to defer
* updating the pointer (e.g. fetch content with ajax, etc).
*/
_update: function( event, content ) {
var buttons,
o = this.options;
if ( ! content )
return;
this.pointer.stop(); // Kill any animations on the pointer.
this.content.html( content );
buttons = o.buttons.call( this.element[0], event, this._handoff() );
if ( buttons ) {
buttons.wrap('<div class="wp-pointer-buttons" />').parent().appendTo( this.content );
}
this.reposition();
},
reposition: function() {
var position;
if ( this.options.disabled )
return;
position = this._processPosition( this.options.position );
// Reposition pointer.
this.pointer.css({
top: 0,
left: 0,
zIndex: zindex++ // Increment the z-index so that it shows above other opened pointers.
}).show().position($.extend({
of: this.element
}, position )); // the object comes before this.options.position so the user can override position.of.
this.repoint();
},
repoint: function() {
var o = this.options,
edge;
if ( o.disabled )
return;
edge = ( typeof o.position == 'string' ) ? o.position : o.position.edge;
// Remove arrow classes.
this.pointer[0].className = this.pointer[0].className.replace( /wp-pointer-[^\s'"]*/, '' );
// Add arrow class.
this.pointer.addClass( 'wp-pointer-' + edge );
},
_processPosition: function( position ) {
var opposite = {
top: 'bottom',
bottom: 'top',
left: 'right',
right: 'left'
},
result;
// If the position object is a string, it is shorthand for position.edge.
if ( typeof position == 'string' ) {
result = {
edge: position + ''
};
} else {
result = $.extend( {}, position );
}
if ( ! result.edge )
return result;
if ( result.edge == 'top' || result.edge == 'bottom' ) {
result.align = result.align || 'left';
result.at = result.at || result.align + ' ' + opposite[ result.edge ];
result.my = result.my || result.align + ' ' + result.edge;
} else {
result.align = result.align || 'top';
result.at = result.at || opposite[ result.edge ] + ' ' + result.align;
result.my = result.my || result.edge + ' ' + result.align;
}
return result;
},
open: function( event ) {
var self = this,
o = this.options;
if ( this.active || o.disabled || this.element.is(':hidden') )
return;
this.update().done( function() {
self._open( event );
});
},
_open: function( event ) {
var self = this,
o = this.options;
if ( this.active || o.disabled || this.element.is(':hidden') )
return;
this.active = true;
this._trigger( "open", event, this._handoff() );
this._trigger( "show", event, this._handoff({
opened: function() {
self._trigger( "opened", event, self._handoff() );
}
}));
},
close: function( event ) {
if ( !this.active || this.options.disabled )
return;
var self = this;
this.active = false;
this._trigger( "close", event, this._handoff() );
this._trigger( "hide", event, this._handoff({
closed: function() {
self._trigger( "closed", event, self._handoff() );
}
}));
},
sendToTop: function( event ) {
if ( this.active )
this.pointer.css( 'z-index', zindex++ );
},
toggle: function( event ) {
if ( this.pointer.is(':hidden') )
this.open( event );
else
this.close( event );
},
_handoff: function( extend ) {
return $.extend({
pointer: this.pointer,
element: this.element
}, extend);
}
});
})(jQuery);
| JavaScript |
/*
* Thickbox 3.1 - One Box To Rule Them All.
* By Cody Lindley (http://www.codylindley.com)
* Copyright (c) 2007 cody lindley
* Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
if ( typeof tb_pathToImage != 'string' ) {
var tb_pathToImage = thickboxL10n.loadingAnimation;
}
if ( typeof tb_closeImage != 'string' ) {
var tb_closeImage = thickboxL10n.closeImage;
}
/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/
//on page load call tb_init
jQuery(document).ready(function(){
tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
imgLoader = new Image();// preload image
imgLoader.src = tb_pathToImage;
});
//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
jQuery(domChunk).live('click', tb_click);
}
function tb_click(){
var t = this.title || this.name || null;
var a = this.href || this.alt;
var g = this.rel || false;
tb_show(t,a,g);
this.blur();
return false;
}
function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link
try {
if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
jQuery("body","html").css({height: "100%", width: "100%"});
jQuery("html").css("overflow","hidden");
if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
jQuery("body").append("<iframe id='TB_HideSelect'>"+thickboxL10n.noiframes+"</iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
jQuery("#TB_overlay").click(tb_remove);
}
}else{//all others
if(document.getElementById("TB_overlay") === null){
jQuery("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
jQuery("#TB_overlay").click(tb_remove);
}
}
if(tb_detectMacXFF()){
jQuery("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
}else{
jQuery("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
}
if(caption===null){caption="";}
jQuery("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
jQuery('#TB_load').show();//show loader
var baseURL;
if(url.indexOf("?")!==-1){ //ff there is a query string involved
baseURL = url.substr(0, url.indexOf("?"));
}else{
baseURL = url;
}
var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
var urlType = baseURL.toLowerCase().match(urlString);
if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
TB_PrevCaption = "";
TB_PrevURL = "";
TB_PrevHTML = "";
TB_NextCaption = "";
TB_NextURL = "";
TB_NextHTML = "";
TB_imageCount = "";
TB_FoundURL = false;
if(imageGroup){
TB_TempArray = jQuery("a[rel="+imageGroup+"]").get();
for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
if (!(TB_TempArray[TB_Counter].href == url)) {
if (TB_FoundURL) {
TB_NextCaption = TB_TempArray[TB_Counter].title;
TB_NextURL = TB_TempArray[TB_Counter].href;
TB_NextHTML = "<span id='TB_next'> <a href='#'>"+thickboxL10n.next+"</a></span>";
} else {
TB_PrevCaption = TB_TempArray[TB_Counter].title;
TB_PrevURL = TB_TempArray[TB_Counter].href;
TB_PrevHTML = "<span id='TB_prev'> <a href='#'>"+thickboxL10n.prev+"</a></span>";
}
} else {
TB_FoundURL = true;
TB_imageCount = thickboxL10n.image + ' ' + (TB_Counter + 1) + ' ' + thickboxL10n.of + ' ' + (TB_TempArray.length);
}
}
}
imgPreloader = new Image();
imgPreloader.onload = function(){
imgPreloader.onload = null;
// Resizing large images - orginal by Christian Montoya edited by me.
var pagesize = tb_getPageSize();
var x = pagesize[0] - 150;
var y = pagesize[1] - 150;
var imageWidth = imgPreloader.width;
var imageHeight = imgPreloader.height;
if (imageWidth > x) {
imageHeight = imageHeight * (x / imageWidth);
imageWidth = x;
if (imageHeight > y) {
imageWidth = imageWidth * (y / imageHeight);
imageHeight = y;
}
} else if (imageHeight > y) {
imageWidth = imageWidth * (y / imageHeight);
imageHeight = y;
if (imageWidth > x) {
imageHeight = imageHeight * (x / imageWidth);
imageWidth = x;
}
}
// End Resizing
TB_WIDTH = imageWidth + 30;
TB_HEIGHT = imageHeight + 60;
jQuery("#TB_window").append("<a href='' id='TB_ImageOff' title='"+thickboxL10n.close+"'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='"+thickboxL10n.close+"'><img src='" + tb_closeImage + "' /></a></div>");
jQuery("#TB_closeWindowButton").click(tb_remove);
if (!(TB_PrevHTML === "")) {
function goPrev(){
if(jQuery(document).unbind("click",goPrev)){jQuery(document).unbind("click",goPrev);}
jQuery("#TB_window").remove();
jQuery("body").append("<div id='TB_window'></div>");
tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
return false;
}
jQuery("#TB_prev").click(goPrev);
}
if (!(TB_NextHTML === "")) {
function goNext(){
jQuery("#TB_window").remove();
jQuery("body").append("<div id='TB_window'></div>");
tb_show(TB_NextCaption, TB_NextURL, imageGroup);
return false;
}
jQuery("#TB_next").click(goNext);
}
jQuery(document).bind('keydown.thickbox', function(e){
e.stopImmediatePropagation();
if ( e.which == 27 ){ // close
if ( ! jQuery(document).triggerHandler( 'wp_CloseOnEscape', [{ event: e, what: 'thickbox', cb: tb_remove }] ) )
tb_remove();
} else if ( e.which == 190 ){ // display previous image
if(!(TB_NextHTML == "")){
jQuery(document).unbind('thickbox');
goNext();
}
} else if ( e.which == 188 ){ // display next image
if(!(TB_PrevHTML == "")){
jQuery(document).unbind('thickbox');
goPrev();
}
}
return false;
});
tb_position();
jQuery("#TB_load").remove();
jQuery("#TB_ImageOff").click(tb_remove);
jQuery("#TB_window").css({'visibility':'visible'}); //for safari using css instead of show
};
imgPreloader.src = url;
}else{//code to show html
var queryString = url.replace(/^[^\?]+\??/,'');
var params = tb_parseQuery( queryString );
TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
ajaxContentW = TB_WIDTH - 30;
ajaxContentH = TB_HEIGHT - 45;
if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window
urlNoQuery = url.split('TB_');
jQuery("#TB_iframeContent").remove();
if(params['modal'] != "true"){//iframe no modal
jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='"+thickboxL10n.close+"'><img src='" + tb_closeImage + "' /></a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' >"+thickboxL10n.noiframes+"</iframe>");
}else{//iframe modal
jQuery("#TB_overlay").unbind();
jQuery("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'>"+thickboxL10n.noiframes+"</iframe>");
}
}else{// not an iframe, ajax
if(jQuery("#TB_window").css("visibility") != "visible"){
if(params['modal'] != "true"){//ajax no modal
jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'><img src='" + tb_closeImage + "' /></a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
}else{//ajax modal
jQuery("#TB_overlay").unbind();
jQuery("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");
}
}else{//this means the window is already up, we are just loading new content via ajax
jQuery("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
jQuery("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
jQuery("#TB_ajaxContent")[0].scrollTop = 0;
jQuery("#TB_ajaxWindowTitle").html(caption);
}
}
jQuery("#TB_closeWindowButton").click(tb_remove);
if(url.indexOf('TB_inline') != -1){
jQuery("#TB_ajaxContent").append(jQuery('#' + params['inlineId']).children());
jQuery("#TB_window").bind('tb_unload', function () {
jQuery('#' + params['inlineId']).append( jQuery("#TB_ajaxContent").children() ); // move elements back when you're finished
});
tb_position();
jQuery("#TB_load").remove();
jQuery("#TB_window").css({'visibility':'visible'});
}else if(url.indexOf('TB_iframe') != -1){
tb_position();
if(jQuery.browser.safari){//safari needs help because it will not fire iframe onload
jQuery("#TB_load").remove();
jQuery("#TB_window").css({'visibility':'visible'});
}
}else{
jQuery("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
tb_position();
jQuery("#TB_load").remove();
tb_init("#TB_ajaxContent a.thickbox");
jQuery("#TB_window").css({'visibility':'visible'});
});
}
}
if(!params['modal']){
jQuery(document).bind('keyup.thickbox', function(e){
if ( e.which == 27 ){ // close
e.stopImmediatePropagation();
if ( ! jQuery(document).triggerHandler( 'wp_CloseOnEscape', [{ event: e, what: 'thickbox', cb: tb_remove }] ) )
tb_remove();
return false;
}
});
}
} catch(e) {
//nothing here
}
}
//helper functions below
function tb_showIframe(){
jQuery("#TB_load").remove();
jQuery("#TB_window").css({'visibility':'visible'});
}
function tb_remove() {
jQuery("#TB_imageOff").unbind("click");
jQuery("#TB_closeWindowButton").unbind("click");
jQuery("#TB_window").fadeOut("fast",function(){jQuery('#TB_window,#TB_overlay,#TB_HideSelect').trigger("tb_unload").unbind().remove();});
jQuery("#TB_load").remove();
if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
jQuery("body","html").css({height: "auto", width: "auto"});
jQuery("html").css("overflow","");
}
jQuery(document).unbind('.thickbox');
return false;
}
function tb_position() {
var isIE6 = typeof document.body.style.maxHeight === "undefined";
jQuery("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
if ( ! isIE6 ) { // take away IE6
jQuery("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
}
}
function tb_parseQuery ( query ) {
var Params = {};
if ( ! query ) {return Params;}// return empty object
var Pairs = query.split(/[;&]/);
for ( var i = 0; i < Pairs.length; i++ ) {
var KeyVal = Pairs[i].split('=');
if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
var key = unescape( KeyVal[0] );
var val = unescape( KeyVal[1] );
val = val.replace(/\+/g, ' ');
Params[key] = val;
}
return Params;
}
function tb_getPageSize(){
var de = document.documentElement;
var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
arrayPageSize = [w,h];
return arrayPageSize;
}
function tb_detectMacXFF() {
var userAgent = navigator.userAgent.toLowerCase();
if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
return true;
}
}
| JavaScript |
jQuery(document).ready(function() {
jQuery('#upload_image_button').click(function() {
formfield = jQuery('#upload_image').attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
window.send_to_editor = function(html) {
imgurl = jQuery('img',html).attr('src');
jQuery('#upload_image').val(imgurl);
tb_remove();
}
}); | JavaScript |
if ( typeof lightbox_path == "undefined" ) var lightbox_path = 'http://'+location.hostname+'/wp-content/plugins/lightbox-gallery/';
if ( typeof hs != "undefined" ) {
if ( typeof graphicsDir != "undefined" ) hs.graphicsDir = graphicsDir;
else hs.graphicsDir = 'http://'+location.hostname+'/wp-content/plugins/lightbox-gallery/graphics/';
}
if ( typeof hs == "undefined" ) {
jQuery(document).ready(function () {
// If you make images display slowly, use following two lines;
// var i = 0;
// showImg(i);
jQuery('a[rel*=lightbox]').lightBox();
jQuery('.gallery a').tooltip({track:true, delay:0, showURL: false});
jQuery('.gallery1 a').lightBox({captionPosition:'gallery'});
// Add these lines if you want to handle multiple galleries in one page.
// You need to add into a [gallery] shorttag. ex) [gallery class="gallery2"]
// jQuery('.gallery2 a').lightBox({captionPosition:'gallery'});
// jQuery('.gallery3 a').lightBox({captionPosition:'gallery'});
});
function showImg(i){
if(i == jQuery('img').length){
return;
}else{
jQuery(jQuery('img')[i]).animate({opacity:'show'},"normal",function(){i++;showImg(i)});
}
}
} | JavaScript |
/*
* jQuery Tooltip plugin 1.3
*
* http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
* http://docs.jquery.com/Plugins/Tooltip
*
* Copyright (c) 2006 - 2008 Jörn Zaefferer
*
* jQueryId: jquery.tooltip.js 5741 2008-06-21 15:22:16Z joern.zaefferer jQuery
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
;(function(jQuery) {
// the tooltip element
var helper = {},
// the current tooltipped element
current,
// the title of the current element, used for restoring
title,
// timeout id for delayed tooltips
tID,
// IE 5.5 or 6
IE = jQuery.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
// flag for mouse tracking
track = false;
jQuery.tooltip = {
blocked: false,
defaults: {
delay: 200,
fade: false,
showURL: true,
extraClass: "",
top: 15,
left: 15,
id: "tooltip"
},
block: function() {
jQuery.tooltip.blocked = !jQuery.tooltip.blocked;
}
};
jQuery.fn.extend({
tooltip: function(settings) {
settings = jQuery.extend({}, jQuery.tooltip.defaults, settings);
createHelper(settings);
return this.each(function() {
jQuery.data(this, "tooltip", settings);
this.tOpacity = helper.parent.css("opacity");
// copy tooltip into its own expando and remove the title
this.tooltipText = this.title;
jQuery(this).removeAttr("title");
// also remove alt attribute to prevent default tooltip in IE
this.alt = "";
})
.mouseover(save)
.mouseout(hide)
.click(hide);
},
fixPNG: IE ? function() {
return this.each(function () {
var image = jQuery(this).css('backgroundImage');
if (image.match(/^url\(["']?(.*\.png)["']?\)jQuery/i)) {
image = RegExp.jQuery1;
jQuery(this).css({
'backgroundImage': 'none',
'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
}).each(function () {
var position = jQuery(this).css('position');
if (position != 'absolute' && position != 'relative')
jQuery(this).css('position', 'relative');
});
}
});
} : function() { return this; },
unfixPNG: IE ? function() {
return this.each(function () {
jQuery(this).css({'filter': '', backgroundImage: ''});
});
} : function() { return this; },
hideWhenEmpty: function() {
return this.each(function() {
jQuery(this)[ jQuery(this).html() ? "show" : "hide" ]();
});
},
url: function() {
return this.attr('href') || this.attr('src');
}
});
function createHelper(settings) {
// there can be only one tooltip helper
if( helper.parent )
return;
// create the helper, h3 for title, div for url
helper.parent = jQuery('<div id="' + settings.id + '"><h3></h3><div class="body"></div><div class="url"></div></div>')
// add to document
.appendTo(document.body)
// hide it at first
.hide();
// apply bgiframe if available
if ( jQuery.fn.bgiframe )
helper.parent.bgiframe();
// save references to title and url elements
helper.title = jQuery('h3', helper.parent);
helper.body = jQuery('div.body', helper.parent);
helper.url = jQuery('div.url', helper.parent);
}
function settings(element) {
return jQuery.data(element, "tooltip");
}
// main event handler to start showing tooltips
function handle(event) {
// show helper, either with timeout or on instant
if( settings(this).delay )
tID = setTimeout(show, settings(this).delay);
else
show();
// if selected, update the helper position when the mouse moves
track = !!settings(this).track;
jQuery(document.body).bind('mousemove', update);
// update at least once
update(event);
}
// save elements title before the tooltip is displayed
function save() {
// if this is the current source, or it has no title (occurs with click event), stop
if ( jQuery.tooltip.blocked || this == current || (!this.tooltipText && !settings(this).bodyHandler) )
return;
// save current
current = this;
title = this.tooltipText;
if ( settings(this).bodyHandler ) {
helper.title.hide();
var bodyContent = settings(this).bodyHandler.call(this);
if (bodyContent.nodeType || bodyContent.jquery) {
helper.body.empty().append(bodyContent)
} else {
helper.body.html( bodyContent );
}
helper.body.show();
} else if ( settings(this).showBody ) {
var parts = title.split(settings(this).showBody);
helper.title.html(parts.shift()).show();
helper.body.empty();
for(var i = 0, part; (part = parts[i]); i++) {
if(i > 0)
helper.body.append("<br/>");
helper.body.append(part);
}
helper.body.hideWhenEmpty();
} else {
helper.title.html(title).show();
helper.body.hide();
}
// if element has href or src, add and show it, otherwise hide it
if( settings(this).showURL && jQuery(this).url() )
helper.url.html( jQuery(this).url().replace('http://', '') ).show();
else
helper.url.hide();
// add an optional class for this tip
helper.parent.addClass(settings(this).extraClass);
// fix PNG background for IE
if (settings(this).fixPNG )
helper.parent.fixPNG();
handle.apply(this, arguments);
}
// delete timeout and show helper
function show() {
tID = null;
if ((!IE || !jQuery.fn.bgiframe) && settings(current).fade) {
if (helper.parent.is(":animated"))
helper.parent.stop().show().fadeTo(settings(current).fade, current.tOpacity);
else
helper.parent.is(':visible') ? helper.parent.fadeTo(settings(current).fade, current.tOpacity) : helper.parent.fadeIn(settings(current).fade);
} else {
helper.parent.show();
}
update();
}
/**
* callback for mousemove
* updates the helper position
* removes itself when no current element
*/
function update(event) {
if(jQuery.tooltip.blocked)
return;
if (event && event.target.tagName == "OPTION") {
return;
}
// stop updating when tracking is disabled and the tooltip is visible
if ( !track && helper.parent.is(":visible")) {
jQuery(document.body).unbind('mousemove', update)
}
// if no current element is available, remove this listener
if( current == null ) {
jQuery(document.body).unbind('mousemove', update);
return;
}
// remove position helper classes
helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");
var left = helper.parent[0].offsetLeft;
var top = helper.parent[0].offsetTop;
if (event) {
// position the helper 15 pixel to bottom right, starting from mouse position
left = event.pageX + settings(current).left;
top = event.pageY + settings(current).top;
var right='auto';
if (settings(current).positionLeft) {
right = jQuery(window).width() - left;
left = 'auto';
}
helper.parent.css({
left: left,
right: right,
top: top
});
}
var v = viewport(),
h = helper.parent[0];
// check horizontal position
if (v.x + v.cx < h.offsetLeft + h.offsetWidth) {
left -= h.offsetWidth + 20 + settings(current).left;
helper.parent.css({left: left + 'px'}).addClass("viewport-right");
}
// check vertical position
if (v.y + v.cy < h.offsetTop + h.offsetHeight) {
top -= h.offsetHeight + 20 + settings(current).top;
helper.parent.css({top: top + 'px'}).addClass("viewport-bottom");
}
}
function viewport() {
return {
x: jQuery(window).scrollLeft(),
y: jQuery(window).scrollTop(),
cx: jQuery(window).width(),
cy: jQuery(window).height()
};
}
// hide helper and restore added classes and the title
function hide(event) {
if(jQuery.tooltip.blocked)
return;
// clear timeout if possible
if(tID)
clearTimeout(tID);
// no more current element
current = null;
var tsettings = settings(this);
function complete() {
helper.parent.removeClass( tsettings.extraClass ).hide().css("opacity", "");
}
if ((!IE || !jQuery.fn.bgiframe) && tsettings.fade) {
if (helper.parent.is(':animated'))
helper.parent.stop().fadeTo(tsettings.fade, 0, complete);
else
helper.parent.stop().fadeOut(tsettings.fade, complete);
} else
complete();
if( settings(this).fixPNG )
helper.parent.unfixPNG();
}
})(jQuery);
| JavaScript |
/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* $LastChangedDate: 2007-06-20 03:23:36 +0200 (Mi, 20 Jun 2007) $
* $Rev: 2110 $
*
* Version 2.1
*/
(function($){
/**
* The bgiframe is chainable and applies the iframe hack to get
* around zIndex issues in IE6. It will only apply itself in IE
* and adds a class to the iframe called 'bgiframe'. The iframe
* is appeneded as the first child of the matched element(s)
* with a tabIndex and zIndex of -1.
*
* By default the plugin will take borders, sized with pixel units,
* into account. If a different unit is used for the border's width,
* then you will need to use the top and left settings as explained below.
*
* NOTICE: This plugin has been reported to cause perfromance problems
* when used on elements that change properties (like width, height and
* opacity) a lot in IE6. Most of these problems have been caused by
* the expressions used to calculate the elements width, height and
* borders. Some have reported it is due to the opacity filter. All
* these settings can be changed if needed as explained below.
*
* @example $('div').bgiframe();
* @before <div><p>Paragraph</p></div>
* @result <div><iframe class="bgiframe".../><p>Paragraph</p></div>
*
* @param Map settings Optional settings to configure the iframe.
* @option String|Number top The iframe must be offset to the top
* by the width of the top border. This should be a negative
* number representing the border-top-width. If a number is
* is used here, pixels will be assumed. Otherwise, be sure
* to specify a unit. An expression could also be used.
* By default the value is "auto" which will use an expression
* to get the border-top-width if it is in pixels.
* @option String|Number left The iframe must be offset to the left
* by the width of the left border. This should be a negative
* number representing the border-left-width. If a number is
* is used here, pixels will be assumed. Otherwise, be sure
* to specify a unit. An expression could also be used.
* By default the value is "auto" which will use an expression
* to get the border-left-width if it is in pixels.
* @option String|Number width This is the width of the iframe. If
* a number is used here, pixels will be assume. Otherwise, be sure
* to specify a unit. An experssion could also be used.
* By default the value is "auto" which will use an experssion
* to get the offsetWidth.
* @option String|Number height This is the height of the iframe. If
* a number is used here, pixels will be assume. Otherwise, be sure
* to specify a unit. An experssion could also be used.
* By default the value is "auto" which will use an experssion
* to get the offsetHeight.
* @option Boolean opacity This is a boolean representing whether or not
* to use opacity. If set to true, the opacity of 0 is applied. If
* set to false, the opacity filter is not applied. Default: true.
* @option String src This setting is provided so that one could change
* the src of the iframe to whatever they need.
* Default: "javascript:false;"
*
* @name bgiframe
* @type jQuery
* @cat Plugins/bgiframe
* @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
*/
$.fn.bgIframe = $.fn.bgiframe = function(s) {
// This is only for IE6
if ( $.browser.msie && parseInt($.browser.version) <= 6 ) {
s = $.extend({
top : 'auto', // auto == .currentStyle.borderTopWidth
left : 'auto', // auto == .currentStyle.borderLeftWidth
width : 'auto', // auto == offsetWidth
height : 'auto', // auto == offsetHeight
opacity : true,
src : 'javascript:false;'
}, s || {});
var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
'style="display:block;position:absolute;z-index:-1;'+
(s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
'"/>';
return this.each(function() {
if ( $('> iframe.bgiframe', this).length == 0 )
this.insertBefore( document.createElement(html), this.firstChild );
});
}
return this;
};
// Add browser.version if it doesn't exist
if (!$.browser.version)
$.browser.version = navigator.userAgent.toLowerCase().match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)[1];
})(jQuery); | JavaScript |
/******************************************************************************
Name: Highslide JS
Version: 4.1.8 (October 27 2009)
Config: default
Author: Torstein Hønsi
Support: http://highslide.com/support
Licence:
Highslide JS is licensed under a Creative Commons Attribution-NonCommercial 2.5
License (http://creativecommons.org/licenses/by-nc/2.5/).
You are free:
* to copy, distribute, display, and perform the work
* to make derivative works
Under the following conditions:
* Attribution. You must attribute the work in the manner specified by the
author or licensor.
* Noncommercial. You may not use this work for commercial purposes.
* For any reuse or distribution, you must make clear to others the license
terms of this work.
* Any of these conditions can be waived if you get permission from the
copyright holder.
Your fair use and other rights are in no way affected by the above.
******************************************************************************/
if (!hs) { var hs = {
// Language strings
lang : {
cssDirection: 'ltr',
loadingText : 'Loading...',
loadingTitle : 'Click to cancel',
focusTitle : 'Click to bring to front',
fullExpandTitle : 'Expand to actual size (f)',
creditsText : 'Powered by <i>Highslide JS</i>',
creditsTitle : 'Go to the Highslide JS homepage',
restoreTitle : 'Click to close image, click and drag to move. Use arrow keys for next and previous.'
},
// See http://highslide.com/ref for examples of settings
graphicsDir : 'highslide/graphics/',
expandCursor : 'zoomin.cur', // null disables
restoreCursor : 'zoomout.cur', // null disables
expandDuration : 250, // milliseconds
restoreDuration : 250,
marginLeft : 15,
marginRight : 15,
marginTop : 15,
marginBottom : 15,
zIndexCounter : 1001, // adjust to other absolutely positioned elements
loadingOpacity : 0.75,
allowMultipleInstances: true,
numberOfImagesToPreload : 5,
outlineWhileAnimating : 2, // 0 = never, 1 = always, 2 = HTML only
outlineStartOffset : 3, // ends at 10
padToMinWidth : false, // pad the popup width to make room for wide caption
fullExpandPosition : 'bottom right',
fullExpandOpacity : 1,
showCredits : true, // you can set this to false if you want
creditsHref : 'http://highslide.com/',
creditsTarget : '_self',
enableKeyListener : true,
openerTagNames : ['a'], // Add more to allow slideshow indexing
dragByHeading: true,
minWidth: 200,
minHeight: 200,
allowSizeReduction: true, // allow the image to reduce to fit client size. If false, this overrides minWidth and minHeight
outlineType : 'drop-shadow', // set null to disable outlines
// END OF YOUR SETTINGS
// declare internal properties
preloadTheseImages : [],
continuePreloading: true,
expanders : [],
overrides : [
'allowSizeReduction',
'useBox',
'outlineType',
'outlineWhileAnimating',
'captionId',
'captionText',
'captionEval',
'captionOverlay',
'headingId',
'headingText',
'headingEval',
'headingOverlay',
'creditsPosition',
'dragByHeading',
'width',
'height',
'wrapperClassName',
'minWidth',
'minHeight',
'maxWidth',
'maxHeight',
'slideshowGroup',
'easing',
'easingClose',
'fadeInOut',
'src'
],
overlays : [],
idCounter : 0,
oPos : {
x: ['leftpanel', 'left', 'center', 'right', 'rightpanel'],
y: ['above', 'top', 'middle', 'bottom', 'below']
},
mouse: {},
headingOverlay: {},
captionOverlay: {},
timers : [],
pendingOutlines : {},
clones : {},
onReady: [],
uaVersion: /Trident\/4\.0/.test(navigator.userAgent) ? 8 :
parseFloat((navigator.userAgent.toLowerCase().match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1]),
ie : (document.all && !window.opera),
safari : /Safari/.test(navigator.userAgent),
geckoMac : /Macintosh.+rv:1\.[0-8].+Gecko/.test(navigator.userAgent),
$ : function (id) {
if (id) return document.getElementById(id);
},
push : function (arr, val) {
arr[arr.length] = val;
},
createElement : function (tag, attribs, styles, parent, nopad) {
var el = document.createElement(tag);
if (attribs) hs.extend(el, attribs);
if (nopad) hs.setStyles(el, {padding: 0, border: 'none', margin: 0});
if (styles) hs.setStyles(el, styles);
if (parent) parent.appendChild(el);
return el;
},
extend : function (el, attribs) {
for (var x in attribs) el[x] = attribs[x];
return el;
},
setStyles : function (el, styles) {
for (var x in styles) {
if (hs.ie && x == 'opacity') {
if (styles[x] > 0.99) el.style.removeAttribute('filter');
else el.style.filter = 'alpha(opacity='+ (styles[x] * 100) +')';
}
else el.style[x] = styles[x];
}
},
animate: function(el, prop, opt) {
var start,
end,
unit;
if (typeof opt != 'object' || opt === null) {
var args = arguments;
opt = {
duration: args[2],
easing: args[3],
complete: args[4]
};
}
if (typeof opt.duration != 'number') opt.duration = 250;
opt.easing = Math[opt.easing] || Math.easeInQuad;
opt.curAnim = hs.extend({}, prop);
for (var name in prop) {
var e = new hs.fx(el, opt , name );
start = parseFloat(hs.css(el, name)) || 0;
end = parseFloat(prop[name]);
unit = name != 'opacity' ? 'px' : '';
e.custom( start, end, unit );
}
},
css: function(el, prop) {
if (document.defaultView) {
return document.defaultView.getComputedStyle(el, null).getPropertyValue(prop);
} else {
if (prop == 'opacity') prop = 'filter';
var val = el.currentStyle[prop.replace(/\-(\w)/g, function (a, b){ return b.toUpperCase(); })];
if (prop == 'filter')
val = val.replace(/alpha\(opacity=([0-9]+)\)/,
function (a, b) { return b / 100 });
return val === '' ? 1 : val;
}
},
getPageSize : function () {
var d = document, w = window, iebody = d.compatMode && d.compatMode != 'BackCompat'
? d.documentElement : d.body;
var width = hs.ie ? iebody.clientWidth :
(d.documentElement.clientWidth || self.innerWidth),
height = hs.ie ? iebody.clientHeight : self.innerHeight;
hs.page = {
width: width,
height: height,
scrollLeft: hs.ie ? iebody.scrollLeft : pageXOffset,
scrollTop: hs.ie ? iebody.scrollTop : pageYOffset
}
},
getPosition : function(el) {
var p = { x: el.offsetLeft, y: el.offsetTop };
while (el.offsetParent) {
el = el.offsetParent;
p.x += el.offsetLeft;
p.y += el.offsetTop;
if (el != document.body && el != document.documentElement) {
p.x -= el.scrollLeft;
p.y -= el.scrollTop;
}
}
return p;
},
expand : function(a, params, custom, type) {
if (!a) a = hs.createElement('a', null, { display: 'none' }, hs.container);
if (typeof a.getParams == 'function') return params;
try {
new hs.Expander(a, params, custom);
return false;
} catch (e) { return true; }
},
focusTopmost : function() {
var topZ = 0,
topmostKey = -1,
expanders = hs.expanders,
exp,
zIndex;
for (var i = 0; i < expanders.length; i++) {
exp = expanders[i];
if (exp) {
zIndex = exp.wrapper.style.zIndex;
if (zIndex && zIndex > topZ) {
topZ = zIndex;
topmostKey = i;
}
}
}
if (topmostKey == -1) hs.focusKey = -1;
else expanders[topmostKey].focus();
},
getParam : function (a, param) {
a.getParams = a.onclick;
var p = a.getParams ? a.getParams() : null;
a.getParams = null;
return (p && typeof p[param] != 'undefined') ? p[param] :
(typeof hs[param] != 'undefined' ? hs[param] : null);
},
getSrc : function (a) {
var src = hs.getParam(a, 'src');
if (src) return src;
return a.href;
},
getNode : function (id) {
var node = hs.$(id), clone = hs.clones[id], a = {};
if (!node && !clone) return null;
if (!clone) {
clone = node.cloneNode(true);
clone.id = '';
hs.clones[id] = clone;
return node;
} else {
return clone.cloneNode(true);
}
},
discardElement : function(d) {
if (d) hs.garbageBin.appendChild(d);
hs.garbageBin.innerHTML = '';
},
transit : function (adj, exp) {
var last = exp = exp || hs.getExpander();
if (hs.upcoming) return false;
else hs.last = last;
try {
hs.upcoming = adj;
adj.onclick();
} catch (e){
hs.last = hs.upcoming = null;
}
try {
exp.close();
} catch (e) {}
return false;
},
previousOrNext : function (el, op) {
var exp = hs.getExpander(el);
if (exp) return hs.transit(exp.getAdjacentAnchor(op), exp);
else return false;
},
previous : function (el) {
return hs.previousOrNext(el, -1);
},
next : function (el) {
return hs.previousOrNext(el, 1);
},
keyHandler : function(e) {
if (!e) e = window.event;
if (!e.target) e.target = e.srcElement; // ie
if (typeof e.target.form != 'undefined') return true; // form element has focus
var exp = hs.getExpander();
var op = null;
switch (e.keyCode) {
case 70: // f
if (exp) exp.doFullExpand();
return true;
case 32: // Space
case 34: // Page Down
case 39: // Arrow right
case 40: // Arrow down
op = 1;
break;
case 8: // Backspace
case 33: // Page Up
case 37: // Arrow left
case 38: // Arrow up
op = -1;
break;
case 27: // Escape
case 13: // Enter
op = 0;
}
if (op !== null) {hs.removeEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler);
if (!hs.enableKeyListener) return true;
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
if (exp) {
if (op == 0) {
exp.close();
} else {
hs.previousOrNext(exp.key, op);
}
return false;
}
}
return true;
},
registerOverlay : function (overlay) {
hs.push(hs.overlays, hs.extend(overlay, { hsId: 'hsId'+ hs.idCounter++ } ));
},
getWrapperKey : function (element, expOnly) {
var el, re = /^highslide-wrapper-([0-9]+)$/;
// 1. look in open expanders
el = element;
while (el.parentNode) {
if (el.id && re.test(el.id)) return el.id.replace(re, "$1");
el = el.parentNode;
}
// 2. look in thumbnail
if (!expOnly) {
el = element;
while (el.parentNode) {
if (el.tagName && hs.isHsAnchor(el)) {
for (var key = 0; key < hs.expanders.length; key++) {
var exp = hs.expanders[key];
if (exp && exp.a == el) return key;
}
}
el = el.parentNode;
}
}
return null;
},
getExpander : function (el, expOnly) {
if (typeof el == 'undefined') return hs.expanders[hs.focusKey] || null;
if (typeof el == 'number') return hs.expanders[el] || null;
if (typeof el == 'string') el = hs.$(el);
return hs.expanders[hs.getWrapperKey(el, expOnly)] || null;
},
isHsAnchor : function (a) {
return (a.onclick && a.onclick.toString().replace(/\s/g, ' ').match(/hs.(htmlE|e)xpand/));
},
reOrder : function () {
for (var i = 0; i < hs.expanders.length; i++)
if (hs.expanders[i] && hs.expanders[i].isExpanded) hs.focusTopmost();
},
mouseClickHandler : function(e)
{
if (!e) e = window.event;
if (e.button > 1) return true;
if (!e.target) e.target = e.srcElement;
var el = e.target;
while (el.parentNode
&& !(/highslide-(image|move|html|resize)/.test(el.className)))
{
el = el.parentNode;
}
var exp = hs.getExpander(el);
if (exp && (exp.isClosing || !exp.isExpanded)) return true;
if (exp && e.type == 'mousedown') {
if (e.target.form) return true;
var match = el.className.match(/highslide-(image|move|resize)/);
if (match) {
hs.dragArgs = {
exp: exp ,
type: match[1],
left: exp.x.pos,
width: exp.x.size,
top: exp.y.pos,
height: exp.y.size,
clickX: e.clientX,
clickY: e.clientY
};
hs.addEventListener(document, 'mousemove', hs.dragHandler);
if (e.preventDefault) e.preventDefault(); // FF
if (/highslide-(image|html)-blur/.test(exp.content.className)) {
exp.focus();
hs.hasFocused = true;
}
return false;
}
} else if (e.type == 'mouseup') {
hs.removeEventListener(document, 'mousemove', hs.dragHandler);
if (hs.dragArgs) {
if (hs.styleRestoreCursor && hs.dragArgs.type == 'image')
hs.dragArgs.exp.content.style.cursor = hs.styleRestoreCursor;
var hasDragged = hs.dragArgs.hasDragged;
if (!hasDragged &&!hs.hasFocused && !/(move|resize)/.test(hs.dragArgs.type)) {
exp.close();
}
else if (hasDragged || (!hasDragged && hs.hasHtmlExpanders)) {
hs.dragArgs.exp.doShowHide('hidden');
}
hs.hasFocused = false;
hs.dragArgs = null;
} else if (/highslide-image-blur/.test(el.className)) {
el.style.cursor = hs.styleRestoreCursor;
}
}
return false;
},
dragHandler : function(e)
{
if (!hs.dragArgs) return true;
if (!e) e = window.event;
var a = hs.dragArgs, exp = a.exp;
a.dX = e.clientX - a.clickX;
a.dY = e.clientY - a.clickY;
var distance = Math.sqrt(Math.pow(a.dX, 2) + Math.pow(a.dY, 2));
if (!a.hasDragged) a.hasDragged = (a.type != 'image' && distance > 0)
|| (distance > (hs.dragSensitivity || 5));
if (a.hasDragged && e.clientX > 5 && e.clientY > 5) {
if (a.type == 'resize') exp.resize(a);
else {
exp.moveTo(a.left + a.dX, a.top + a.dY);
if (a.type == 'image') exp.content.style.cursor = 'move';
}
}
return false;
},
wrapperMouseHandler : function (e) {
try {
if (!e) e = window.event;
var over = /mouseover/i.test(e.type);
if (!e.target) e.target = e.srcElement; // ie
if (hs.ie) e.relatedTarget =
over ? e.fromElement : e.toElement; // ie
var exp = hs.getExpander(e.target);
if (!exp.isExpanded) return;
if (!exp || !e.relatedTarget || hs.getExpander(e.relatedTarget, true) == exp
|| hs.dragArgs) return;
for (var i = 0; i < exp.overlays.length; i++) (function() {
var o = hs.$('hsId'+ exp.overlays[i]);
if (o && o.hideOnMouseOut) {
if (over) hs.setStyles(o, { visibility: 'visible', display: '' });
hs.animate(o, { opacity: over ? o.opacity : 0 }, o.dur);
}
})();
} catch (e) {}
},
addEventListener : function (el, event, func) {
if (el == document && event == 'ready') hs.push(hs.onReady, func);
try {
el.addEventListener(event, func, false);
} catch (e) {
try {
el.detachEvent('on'+ event, func);
el.attachEvent('on'+ event, func);
} catch (e) {
el['on'+ event] = func;
}
}
},
removeEventListener : function (el, event, func) {
try {
el.removeEventListener(event, func, false);
} catch (e) {
try {
el.detachEvent('on'+ event, func);
} catch (e) {
el['on'+ event] = null;
}
}
},
preloadFullImage : function (i) {
if (hs.continuePreloading && hs.preloadTheseImages[i] && hs.preloadTheseImages[i] != 'undefined') {
var img = document.createElement('img');
img.onload = function() {
img = null;
hs.preloadFullImage(i + 1);
};
img.src = hs.preloadTheseImages[i];
}
},
preloadImages : function (number) {
if (number && typeof number != 'object') hs.numberOfImagesToPreload = number;
var arr = hs.getAnchors();
for (var i = 0; i < arr.images.length && i < hs.numberOfImagesToPreload; i++) {
hs.push(hs.preloadTheseImages, hs.getSrc(arr.images[i]));
}
// preload outlines
if (hs.outlineType) new hs.Outline(hs.outlineType, function () { hs.preloadFullImage(0)} );
else
hs.preloadFullImage(0);
// preload cursor
if (hs.restoreCursor) var cur = hs.createElement('img', { src: hs.graphicsDir + hs.restoreCursor });
},
init : function () {
if (!hs.container) {
hs.getPageSize();
hs.ieLt7 = hs.ie && hs.uaVersion < 7;
for (var x in hs.langDefaults) {
if (typeof hs[x] != 'undefined') hs.lang[x] = hs[x];
else if (typeof hs.lang[x] == 'undefined' && typeof hs.langDefaults[x] != 'undefined')
hs.lang[x] = hs.langDefaults[x];
}
hs.container = hs.createElement('div', {
className: 'highslide-container'
}, {
position: 'absolute',
left: 0,
top: 0,
width: '100%',
zIndex: hs.zIndexCounter,
direction: 'ltr'
},
document.body,
true
);
hs.loading = hs.createElement('a', {
className: 'highslide-loading',
title: hs.lang.loadingTitle,
innerHTML: hs.lang.loadingText,
href: 'javascript:;'
}, {
position: 'absolute',
top: '-9999px',
opacity: hs.loadingOpacity,
zIndex: 1
}, hs.container
);
hs.garbageBin = hs.createElement('div', null, { display: 'none' }, hs.container);
// http://www.robertpenner.com/easing/
Math.linearTween = function (t, b, c, d) {
return c*t/d + b;
};
Math.easeInQuad = function (t, b, c, d) {
return c*(t/=d)*t + b;
};
hs.hideSelects = hs.ieLt7;
hs.hideIframes = ((window.opera && hs.uaVersion < 9) || navigator.vendor == 'KDE'
|| (hs.ie && hs.uaVersion < 5.5));
}
},
ready : function() {
if (hs.isReady) return;
hs.isReady = true;
for (var i = 0; i < hs.onReady.length; i++) hs.onReady[i]();
},
updateAnchors : function() {
var el, els, all = [], images = [],groups = {}, re;
for (var i = 0; i < hs.openerTagNames.length; i++) {
els = document.getElementsByTagName(hs.openerTagNames[i]);
for (var j = 0; j < els.length; j++) {
el = els[j];
re = hs.isHsAnchor(el);
if (re) {
hs.push(all, el);
if (re[0] == 'hs.expand') hs.push(images, el);
var g = hs.getParam(el, 'slideshowGroup') || 'none';
if (!groups[g]) groups[g] = [];
hs.push(groups[g], el);
}
}
}
hs.anchors = { all: all, groups: groups, images: images };
return hs.anchors;
},
getAnchors : function() {
return hs.anchors || hs.updateAnchors();
},
close : function(el) {
var exp = hs.getExpander(el);
if (exp) exp.close();
return false;
}
}; // end hs object
hs.fx = function( elem, options, prop ){
this.options = options;
this.elem = elem;
this.prop = prop;
if (!options.orig) options.orig = {};
};
hs.fx.prototype = {
update: function(){
(hs.fx.step[this.prop] || hs.fx.step._default)(this);
if (this.options.step)
this.options.step.call(this.elem, this.now, this);
},
custom: function(from, to, unit){
this.startTime = (new Date()).getTime();
this.start = from;
this.end = to;
this.unit = unit;// || this.unit || "px";
this.now = this.start;
this.pos = this.state = 0;
var self = this;
function t(gotoEnd){
return self.step(gotoEnd);
}
t.elem = this.elem;
if ( t() && hs.timers.push(t) == 1 ) {
hs.timerId = setInterval(function(){
var timers = hs.timers;
for ( var i = 0; i < timers.length; i++ )
if ( !timers[i]() )
timers.splice(i--, 1);
if ( !timers.length ) {
clearInterval(hs.timerId);
}
}, 13);
}
},
step: function(gotoEnd){
var t = (new Date()).getTime();
if ( gotoEnd || t >= this.options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
this.options.curAnim[ this.prop ] = true;
var done = true;
for ( var i in this.options.curAnim )
if ( this.options.curAnim[i] !== true )
done = false;
if ( done ) {
if (this.options.complete) this.options.complete.call(this.elem);
}
return false;
} else {
var n = t - this.startTime;
this.state = n / this.options.duration;
this.pos = this.options.easing(n, 0, 1, this.options.duration);
this.now = this.start + ((this.end - this.start) * this.pos);
this.update();
}
return true;
}
};
hs.extend( hs.fx, {
step: {
opacity: function(fx){
hs.setStyles(fx.elem, { opacity: fx.now });
},
_default: function(fx){
try {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null )
fx.elem.style[ fx.prop ] = fx.now + fx.unit;
else
fx.elem[ fx.prop ] = fx.now;
} catch (e) {}
}
}
});
hs.Outline = function (outlineType, onLoad) {
this.onLoad = onLoad;
this.outlineType = outlineType;
var v = hs.uaVersion, tr;
this.hasAlphaImageLoader = hs.ie && v >= 5.5 && v < 7;
if (!outlineType) {
if (onLoad) onLoad();
return;
}
hs.init();
this.table = hs.createElement(
'table', {
cellSpacing: 0
}, {
visibility: 'hidden',
position: 'absolute',
borderCollapse: 'collapse',
width: 0
},
hs.container,
true
);
var tbody = hs.createElement('tbody', null, null, this.table, 1);
this.td = [];
for (var i = 0; i <= 8; i++) {
if (i % 3 == 0) tr = hs.createElement('tr', null, { height: 'auto' }, tbody, true);
this.td[i] = hs.createElement('td', null, null, tr, true);
var style = i != 4 ? { lineHeight: 0, fontSize: 0} : { position : 'relative' };
hs.setStyles(this.td[i], style);
}
this.td[4].className = outlineType +' highslide-outline';
this.preloadGraphic();
};
hs.Outline.prototype = {
preloadGraphic : function () {
var src = hs.graphicsDir + (hs.outlinesDir || "outlines/")+ this.outlineType +".png";
var appendTo = hs.safari ? hs.container : null;
this.graphic = hs.createElement('img', null, { position: 'absolute',
top: '-9999px' }, appendTo, true); // for onload trigger
var pThis = this;
this.graphic.onload = function() { pThis.onGraphicLoad(); };
this.graphic.src = src;
},
onGraphicLoad : function () {
var o = this.offset = this.graphic.width / 4,
pos = [[0,0],[0,-4],[-2,0],[0,-8],0,[-2,-8],[0,-2],[0,-6],[-2,-2]],
dim = { height: (2*o) +'px', width: (2*o) +'px' };
for (var i = 0; i <= 8; i++) {
if (pos[i]) {
if (this.hasAlphaImageLoader) {
var w = (i == 1 || i == 7) ? '100%' : this.graphic.width +'px';
var div = hs.createElement('div', null, { width: '100%', height: '100%', position: 'relative', overflow: 'hidden'}, this.td[i], true);
hs.createElement ('div', null, {
filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale, src='"+ this.graphic.src + "')",
position: 'absolute',
width: w,
height: this.graphic.height +'px',
left: (pos[i][0]*o)+'px',
top: (pos[i][1]*o)+'px'
},
div,
true);
} else {
hs.setStyles(this.td[i], { background: 'url('+ this.graphic.src +') '+ (pos[i][0]*o)+'px '+(pos[i][1]*o)+'px'});
}
if (window.opera && (i == 3 || i ==5))
hs.createElement('div', null, dim, this.td[i], true);
hs.setStyles (this.td[i], dim);
}
}
this.graphic = null;
if (hs.pendingOutlines[this.outlineType]) hs.pendingOutlines[this.outlineType].destroy();
hs.pendingOutlines[this.outlineType] = this;
if (this.onLoad) this.onLoad();
},
setPosition : function (pos, offset, vis, dur, easing) {
var exp = this.exp,
stl = exp.wrapper.style,
offset = offset || 0,
pos = pos || {
x: exp.x.pos + offset,
y: exp.y.pos + offset,
w: exp.x.get('wsize') - 2 * offset,
h: exp.y.get('wsize') - 2 * offset
};
if (vis) this.table.style.visibility = (pos.h >= 4 * this.offset)
? 'visible' : 'hidden';
hs.setStyles(this.table, {
left: (pos.x - this.offset) +'px',
top: (pos.y - this.offset) +'px',
width: (pos.w + 2 * this.offset) +'px'
});
pos.w -= 2 * this.offset;
pos.h -= 2 * this.offset;
hs.setStyles (this.td[4], {
width: pos.w >= 0 ? pos.w +'px' : 0,
height: pos.h >= 0 ? pos.h +'px' : 0
});
if (this.hasAlphaImageLoader) this.td[3].style.height
= this.td[5].style.height = this.td[4].style.height;
},
destroy : function(hide) {
if (hide) this.table.style.visibility = 'hidden';
else hs.discardElement(this.table);
}
};
hs.Dimension = function(exp, dim) {
this.exp = exp;
this.dim = dim;
this.ucwh = dim == 'x' ? 'Width' : 'Height';
this.wh = this.ucwh.toLowerCase();
this.uclt = dim == 'x' ? 'Left' : 'Top';
this.lt = this.uclt.toLowerCase();
this.ucrb = dim == 'x' ? 'Right' : 'Bottom';
this.rb = this.ucrb.toLowerCase();
this.p1 = this.p2 = 0;
};
hs.Dimension.prototype = {
get : function(key) {
switch (key) {
case 'loadingPos':
return this.tpos + this.tb + (this.t - hs.loading['offset'+ this.ucwh]) / 2;
case 'wsize':
return this.size + 2 * this.cb + this.p1 + this.p2;
case 'fitsize':
return this.clientSize - this.marginMin - this.marginMax;
case 'maxsize':
return this.get('fitsize') - 2 * this.cb - this.p1 - this.p2 ;
case 'opos':
return this.pos - (this.exp.outline ? this.exp.outline.offset : 0);
case 'osize':
return this.get('wsize') + (this.exp.outline ? 2*this.exp.outline.offset : 0);
case 'imgPad':
return this.imgSize ? Math.round((this.size - this.imgSize) / 2) : 0;
}
},
calcBorders: function() {
// correct for borders
this.cb = (this.exp.content['offset'+ this.ucwh] - this.t) / 2;
this.marginMax = hs['margin'+ this.ucrb];
},
calcThumb: function() {
this.t = this.exp.el[this.wh] ? parseInt(this.exp.el[this.wh]) :
this.exp.el['offset'+ this.ucwh];
this.tpos = this.exp.tpos[this.dim];
this.tb = (this.exp.el['offset'+ this.ucwh] - this.t) / 2;
if (this.tpos == 0 || this.tpos == -1) {
this.tpos = (hs.page[this.wh] / 2) + hs.page['scroll'+ this.uclt];
};
},
calcExpanded: function() {
var exp = this.exp;
this.justify = 'auto';
// size and position
this.pos = this.tpos - this.cb + this.tb;
if (this.maxHeight && this.dim == 'x')
exp.maxWidth = Math.min(exp.maxWidth || this.full, exp.maxHeight * this.full / exp.y.full);
this.size = Math.min(this.full, exp['max'+ this.ucwh] || this.full);
this.minSize = exp.allowSizeReduction ?
Math.min(exp['min'+ this.ucwh], this.full) :this.full;
if (exp.isImage && exp.useBox) {
this.size = exp[this.wh];
this.imgSize = this.full;
}
if (this.dim == 'x' && hs.padToMinWidth) this.minSize = exp.minWidth;
this.marginMin = hs['margin'+ this.uclt];
this.scroll = hs.page['scroll'+ this.uclt];
this.clientSize = hs.page[this.wh];
},
setSize: function(i) {
var exp = this.exp;
if (exp.isImage && (exp.useBox || hs.padToMinWidth)) {
this.imgSize = i;
this.size = Math.max(this.size, this.imgSize);
exp.content.style[this.lt] = this.get('imgPad')+'px';
} else
this.size = i;
exp.content.style[this.wh] = i +'px';
exp.wrapper.style[this.wh] = this.get('wsize') +'px';
if (exp.outline) exp.outline.setPosition();
if (this.dim == 'x' && exp.overlayBox) exp.sizeOverlayBox(true);
},
setPos: function(i) {
this.pos = i;
this.exp.wrapper.style[this.lt] = i +'px';
if (this.exp.outline) this.exp.outline.setPosition();
}
};
hs.Expander = function(a, params, custom, contentType) {
if (document.readyState && hs.ie && !hs.isReady) {
hs.addEventListener(document, 'ready', function() {
new hs.Expander(a, params, custom, contentType);
});
return;
}
this.a = a;
this.custom = custom;
this.contentType = contentType || 'image';
this.isImage = !this.isHtml;
hs.continuePreloading = false;
this.overlays = [];
hs.init();
var key = this.key = hs.expanders.length;
// override inline parameters
for (var i = 0; i < hs.overrides.length; i++) {
var name = hs.overrides[i];
this[name] = params && typeof params[name] != 'undefined' ?
params[name] : hs[name];
}
if (!this.src) this.src = a.href;
// get thumb
var el = (params && params.thumbnailId) ? hs.$(params.thumbnailId) : a;
el = this.thumb = el.getElementsByTagName('img')[0] || el;
this.thumbsUserSetId = el.id || a.id;
// check if already open
for (var i = 0; i < hs.expanders.length; i++) {
if (hs.expanders[i] && hs.expanders[i].a == a) {
hs.expanders[i].focus();
return false;
}
}
// cancel other
if (!hs.allowSimultaneousLoading) for (var i = 0; i < hs.expanders.length; i++) {
if (hs.expanders[i] && hs.expanders[i].thumb != el && !hs.expanders[i].onLoadStarted) {
hs.expanders[i].cancelLoading();
}
}
hs.expanders[key] = this;
if (!hs.allowMultipleInstances && !hs.upcoming) {
if (hs.expanders[key-1]) hs.expanders[key-1].close();
if (typeof hs.focusKey != 'undefined' && hs.expanders[hs.focusKey])
hs.expanders[hs.focusKey].close();
}
// initiate metrics
this.el = el;
this.tpos = hs.getPosition(el);
hs.getPageSize();
var x = this.x = new hs.Dimension(this, 'x');
x.calcThumb();
var y = this.y = new hs.Dimension(this, 'y');
y.calcThumb();
this.wrapper = hs.createElement(
'div', {
id: 'highslide-wrapper-'+ this.key,
className: 'highslide-wrapper '+ this.wrapperClassName
}, {
visibility: 'hidden',
position: 'absolute',
zIndex: hs.zIndexCounter += 2
}, null, true );
this.wrapper.onmouseover = this.wrapper.onmouseout = hs.wrapperMouseHandler;
if (this.contentType == 'image' && this.outlineWhileAnimating == 2)
this.outlineWhileAnimating = 0;
// get the outline
if (!this.outlineType) {
this[this.contentType +'Create']();
} else if (hs.pendingOutlines[this.outlineType]) {
this.connectOutline();
this[this.contentType +'Create']();
} else {
this.showLoading();
var exp = this;
new hs.Outline(this.outlineType,
function () {
exp.connectOutline();
exp[exp.contentType +'Create']();
}
);
}
return true;
};
hs.Expander.prototype = {
error : function(e) {
// alert ('Line '+ e.lineNumber +': '+ e.message);
window.location.href = this.src;
},
connectOutline : function() {
var outline = this.outline = hs.pendingOutlines[this.outlineType];
outline.exp = this;
outline.table.style.zIndex = this.wrapper.style.zIndex - 1;
hs.pendingOutlines[this.outlineType] = null;
},
showLoading : function() {
if (this.onLoadStarted || this.loading) return;
this.loading = hs.loading;
var exp = this;
this.loading.onclick = function() {
exp.cancelLoading();
};
var exp = this,
l = this.x.get('loadingPos') +'px',
t = this.y.get('loadingPos') +'px';
setTimeout(function () {
if (exp.loading) hs.setStyles(exp.loading, { left: l, top: t, zIndex: hs.zIndexCounter++ })}
, 100);
},
imageCreate : function() {
var exp = this;
var img = document.createElement('img');
this.content = img;
img.onload = function () {
if (hs.expanders[exp.key]) exp.contentLoaded();
};
if (hs.blockRightClick) img.oncontextmenu = function() { return false; };
img.className = 'highslide-image';
hs.setStyles(img, {
visibility: 'hidden',
display: 'block',
position: 'absolute',
maxWidth: '9999px',
zIndex: 3
});
img.title = hs.lang.restoreTitle;
if (hs.safari) hs.container.appendChild(img);
if (hs.ie && hs.flushImgSize) img.src = null;
img.src = this.src;
this.showLoading();
},
contentLoaded : function() {
try {
if (!this.content) return;
this.content.onload = null;
if (this.onLoadStarted) return;
else this.onLoadStarted = true;
var x = this.x, y = this.y;
if (this.loading) {
hs.setStyles(this.loading, { top: '-9999px' });
this.loading = null;
}
x.full = this.content.width;
y.full = this.content.height;
hs.setStyles(this.content, {
width: x.t +'px',
height: y.t +'px'
});
this.wrapper.appendChild(this.content);
hs.container.appendChild(this.wrapper);
x.calcBorders();
y.calcBorders();
hs.setStyles (this.wrapper, {
left: (x.tpos + x.tb - x.cb) +'px',
top: (y.tpos + x.tb - y.cb) +'px'
});
this.getOverlays();
var ratio = x.full / y.full;
x.calcExpanded();
this.justify(x);
y.calcExpanded();
this.justify(y);
if (this.overlayBox) this.sizeOverlayBox(0, 1);
if (this.allowSizeReduction) {
this.correctRatio(ratio);
if (this.isImage && this.x.full > (this.x.imgSize || this.x.size)) {
this.createFullExpand();
if (this.overlays.length == 1) this.sizeOverlayBox();
}
}
this.show();
} catch (e) {
this.error(e);
}
},
justify : function (p, moveOnly) {
var tgtArr, tgt = p.target, dim = p == this.x ? 'x' : 'y';
var hasMovedMin = false;
var allowReduce = p.exp.allowSizeReduction;
p.pos = Math.round(p.pos - ((p.get('wsize') - p.t) / 2));
if (p.pos < p.scroll + p.marginMin) {
p.pos = p.scroll + p.marginMin;
hasMovedMin = true;
}
if (!moveOnly && p.size < p.minSize) {
p.size = p.minSize;
allowReduce = false;
}
if (p.pos + p.get('wsize') > p.scroll + p.clientSize - p.marginMax) {
if (!moveOnly && hasMovedMin && allowReduce) {
p.size = Math.min(p.size, p.get(dim == 'y' ? 'fitsize' : 'maxsize'));
} else if (p.get('wsize') < p.get('fitsize')) {
p.pos = p.scroll + p.clientSize - p.marginMax - p.get('wsize');
} else { // image larger than viewport
p.pos = p.scroll + p.marginMin;
if (!moveOnly && allowReduce) p.size = p.get(dim == 'y' ? 'fitsize' : 'maxsize');
}
}
if (!moveOnly && p.size < p.minSize) {
p.size = p.minSize;
allowReduce = false;
}
if (p.pos < p.marginMin) {
var tmpMin = p.pos;
p.pos = p.marginMin;
if (allowReduce && !moveOnly) p.size = p.size - (p.pos - tmpMin);
}
},
correctRatio : function(ratio) {
var x = this.x,
y = this.y,
changed = false,
xSize = Math.min(x.full, x.size),
ySize = Math.min(y.full, y.size),
useBox = (this.useBox || hs.padToMinWidth);
if (xSize / ySize > ratio) { // width greater
xSize = ySize * ratio;
if (xSize < x.minSize) { // below minWidth
xSize = x.minSize;
ySize = xSize / ratio;
}
changed = true;
} else if (xSize / ySize < ratio) { // height greater
ySize = xSize / ratio;
changed = true;
}
if (hs.padToMinWidth && x.full < x.minSize) {
x.imgSize = x.full;
y.size = y.imgSize = y.full;
} else if (this.useBox) {
x.imgSize = xSize;
y.imgSize = ySize;
} else {
x.size = xSize;
y.size = ySize;
}
changed = this.fitOverlayBox(useBox ? null : ratio, changed);
if (useBox && y.size < y.imgSize) {
y.imgSize = y.size;
x.imgSize = y.size * ratio;
}
if (changed || useBox) {
x.pos = x.tpos - x.cb + x.tb;
x.minSize = x.size;
this.justify(x, true);
y.pos = y.tpos - y.cb + y.tb;
y.minSize = y.size;
this.justify(y, true);
if (this.overlayBox) this.sizeOverlayBox();
}
},
fitOverlayBox : function(ratio, changed) {
var x = this.x, y = this.y;
if (this.overlayBox) {
while (y.size > this.minHeight && x.size > this.minWidth
&& y.get('wsize') > y.get('fitsize')) {
y.size -= 10;
if (ratio) x.size = y.size * ratio;
this.sizeOverlayBox(0, 1);
changed = true;
}
}
return changed;
},
show : function () {
var x = this.x, y = this.y;
this.doShowHide('hidden');
// Apply size change
this.changeSize(
1, {
wrapper: {
width : x.get('wsize'),
height : y.get('wsize'),
left: x.pos,
top: y.pos
},
content: {
left: x.p1 + x.get('imgPad'),
top: y.p1 + y.get('imgPad'),
width:x.imgSize ||x.size,
height:y.imgSize ||y.size
}
},
hs.expandDuration
);
},
changeSize : function(up, to, dur) {
if (this.outline && !this.outlineWhileAnimating) {
if (up) this.outline.setPosition();
else this.outline.destroy();
}
if (!up) this.destroyOverlays();
var exp = this,
x = exp.x,
y = exp.y,
easing = this.easing;
if (!up) easing = this.easingClose || easing;
var after = up ?
function() {
if (exp.outline) exp.outline.table.style.visibility = "visible";
setTimeout(function() {
exp.afterExpand();
}, 50);
} :
function() {
exp.afterClose();
};
if (up) hs.setStyles( this.wrapper, {
width: x.t +'px',
height: y.t +'px'
});
if (this.fadeInOut) {
hs.setStyles(this.wrapper, { opacity: up ? 0 : 1 });
hs.extend(to.wrapper, { opacity: up });
}
hs.animate( this.wrapper, to.wrapper, {
duration: dur,
easing: easing,
step: function(val, args) {
if (exp.outline && exp.outlineWhileAnimating && args.prop == 'top') {
var fac = up ? args.pos : 1 - args.pos;
var pos = {
w: x.t + (x.get('wsize') - x.t) * fac,
h: y.t + (y.get('wsize') - y.t) * fac,
x: x.tpos + (x.pos - x.tpos) * fac,
y: y.tpos + (y.pos - y.tpos) * fac
};
exp.outline.setPosition(pos, 0, 1);
}
}
});
hs.animate( this.content, to.content, dur, easing, after);
if (up) {
this.wrapper.style.visibility = 'visible';
this.content.style.visibility = 'visible';
this.a.className += ' highslide-active-anchor';
}
},
afterExpand : function() {
this.isExpanded = true;
this.focus();
if (hs.upcoming && hs.upcoming == this.a) hs.upcoming = null;
this.prepareNextOutline();
var p = hs.page, mX = hs.mouse.x + p.scrollLeft, mY = hs.mouse.y + p.scrollTop;
this.mouseIsOver = this.x.pos < mX && mX < this.x.pos + this.x.get('wsize')
&& this.y.pos < mY && mY < this.y.pos + this.y.get('wsize');
if (this.overlayBox) this.showOverlays();
},
prepareNextOutline : function() {
var key = this.key;
var outlineType = this.outlineType;
new hs.Outline(outlineType,
function () { try { hs.expanders[key].preloadNext(); } catch (e) {} });
},
preloadNext : function() {
var next = this.getAdjacentAnchor(1);
if (next && next.onclick.toString().match(/hs\.expand/))
var img = hs.createElement('img', { src: hs.getSrc(next) });
},
getAdjacentAnchor : function(op) {
var current = this.getAnchorIndex(), as = hs.anchors.groups[this.slideshowGroup || 'none'];
/*< ? if ($cfg->slideshow) : ?>s*/
if (!as[current + op] && this.slideshow && this.slideshow.repeat) {
if (op == 1) return as[0];
else if (op == -1) return as[as.length-1];
}
/*< ? endif ?>s*/
return as[current + op] || null;
},
getAnchorIndex : function() {
var arr = hs.getAnchors().groups[this.slideshowGroup || 'none'];
if (arr) for (var i = 0; i < arr.length; i++) {
if (arr[i] == this.a) return i;
}
return null;
},
cancelLoading : function() {
hs.discardElement (this.wrapper);
hs.expanders[this.key] = null;
if (this.loading) hs.loading.style.left = '-9999px';
},
writeCredits : function () {
this.credits = hs.createElement('a', {
href: hs.creditsHref,
target: hs.creditsTarget,
className: 'highslide-credits',
innerHTML: hs.lang.creditsText,
title: hs.lang.creditsTitle
});
this.createOverlay({
overlayId: this.credits,
position: this.creditsPosition || 'top left'
});
},
getInline : function(types, addOverlay) {
for (var i = 0; i < types.length; i++) {
var type = types[i], s = null;
if (!this[type +'Id'] && this.thumbsUserSetId)
this[type +'Id'] = type +'-for-'+ this.thumbsUserSetId;
if (this[type +'Id']) this[type] = hs.getNode(this[type +'Id']);
if (!this[type] && !this[type +'Text'] && this[type +'Eval']) try {
s = eval(this[type +'Eval']);
} catch (e) {}
if (!this[type] && this[type +'Text']) {
s = this[type +'Text'];
}
if (!this[type] && !s) {
this[type] = hs.getNode(this.a['_'+ type + 'Id']);
if (!this[type]) {
var next = this.a.nextSibling;
while (next && !hs.isHsAnchor(next)) {
if ((new RegExp('highslide-'+ type)).test(next.className || null)) {
if (!next.id) this.a['_'+ type + 'Id'] = next.id = 'hsId'+ hs.idCounter++;
this[type] = hs.getNode(next.id);
break;
}
next = next.nextSibling;
}
}
}
if (!this[type] && s) this[type] = hs.createElement('div',
{ className: 'highslide-'+ type, innerHTML: s } );
if (addOverlay && this[type]) {
var o = { position: (type == 'heading') ? 'above' : 'below' };
for (var x in this[type+'Overlay']) o[x] = this[type+'Overlay'][x];
o.overlayId = this[type];
this.createOverlay(o);
}
}
},
// on end move and resize
doShowHide : function(visibility) {
if (hs.hideSelects) this.showHideElements('SELECT', visibility);
if (hs.hideIframes) this.showHideElements('IFRAME', visibility);
if (hs.geckoMac) this.showHideElements('*', visibility);
},
showHideElements : function (tagName, visibility) {
var els = document.getElementsByTagName(tagName);
var prop = tagName == '*' ? 'overflow' : 'visibility';
for (var i = 0; i < els.length; i++) {
if (prop == 'visibility' || (document.defaultView.getComputedStyle(
els[i], "").getPropertyValue('overflow') == 'auto'
|| els[i].getAttribute('hidden-by') != null)) {
var hiddenBy = els[i].getAttribute('hidden-by');
if (visibility == 'visible' && hiddenBy) {
hiddenBy = hiddenBy.replace('['+ this.key +']', '');
els[i].setAttribute('hidden-by', hiddenBy);
if (!hiddenBy) els[i].style[prop] = els[i].origProp;
} else if (visibility == 'hidden') { // hide if behind
var elPos = hs.getPosition(els[i]);
elPos.w = els[i].offsetWidth;
elPos.h = els[i].offsetHeight;
var clearsX = (elPos.x + elPos.w < this.x.get('opos')
|| elPos.x > this.x.get('opos') + this.x.get('osize'));
var clearsY = (elPos.y + elPos.h < this.y.get('opos')
|| elPos.y > this.y.get('opos') + this.y.get('osize'));
var wrapperKey = hs.getWrapperKey(els[i]);
if (!clearsX && !clearsY && wrapperKey != this.key) { // element falls behind image
if (!hiddenBy) {
els[i].setAttribute('hidden-by', '['+ this.key +']');
els[i].origProp = els[i].style[prop];
els[i].style[prop] = 'hidden';
} else if (hiddenBy.indexOf('['+ this.key +']') == -1) {
els[i].setAttribute('hidden-by', hiddenBy + '['+ this.key +']');
}
} else if ((hiddenBy == '['+ this.key +']' || hs.focusKey == wrapperKey)
&& wrapperKey != this.key) { // on move
els[i].setAttribute('hidden-by', '');
els[i].style[prop] = els[i].origProp || '';
} else if (hiddenBy && hiddenBy.indexOf('['+ this.key +']') > -1) {
els[i].setAttribute('hidden-by', hiddenBy.replace('['+ this.key +']', ''));
}
}
}
}
},
focus : function() {
this.wrapper.style.zIndex = hs.zIndexCounter += 2;
// blur others
for (var i = 0; i < hs.expanders.length; i++) {
if (hs.expanders[i] && i == hs.focusKey) {
var blurExp = hs.expanders[i];
blurExp.content.className += ' highslide-'+ blurExp.contentType +'-blur';
blurExp.content.style.cursor = hs.ie ? 'hand' : 'pointer';
blurExp.content.title = hs.lang.focusTitle;
}
}
// focus this
if (this.outline) this.outline.table.style.zIndex
= this.wrapper.style.zIndex - 1;
this.content.className = 'highslide-'+ this.contentType;
this.content.title = hs.lang.restoreTitle;
if (hs.restoreCursor) {
hs.styleRestoreCursor = window.opera ? 'pointer' : 'url('+ hs.graphicsDir + hs.restoreCursor +'), pointer';
if (hs.ie && hs.uaVersion < 6) hs.styleRestoreCursor = 'hand';
this.content.style.cursor = hs.styleRestoreCursor;
}
hs.focusKey = this.key;
hs.addEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler);
},
moveTo: function(x, y) {
this.x.setPos(x);
this.y.setPos(y);
},
resize : function (e) {
var w, h, r = e.width / e.height;
w = Math.max(e.width + e.dX, Math.min(this.minWidth, this.x.full));
if (this.isImage && Math.abs(w - this.x.full) < 12) w = this.x.full;
h = w / r;
if (h < Math.min(this.minHeight, this.y.full)) {
h = Math.min(this.minHeight, this.y.full);
if (this.isImage) w = h * r;
}
this.resizeTo(w, h);
},
resizeTo: function(w, h) {
this.y.setSize(h);
this.x.setSize(w);
this.wrapper.style.height = this.y.get('wsize') +'px';
},
close : function() {
if (this.isClosing || !this.isExpanded) return;
this.isClosing = true;
hs.removeEventListener(document, window.opera ? 'keypress' : 'keydown', hs.keyHandler);
try {
this.content.style.cursor = 'default';
this.changeSize(
0, {
wrapper: {
width : this.x.t,
height : this.y.t,
left: this.x.tpos - this.x.cb + this.x.tb,
top: this.y.tpos - this.y.cb + this.y.tb
},
content: {
left: 0,
top: 0,
width: this.x.t,
height: this.y.t
}
}, hs.restoreDuration
);
} catch (e) { this.afterClose(); }
},
createOverlay : function (o) {
var el = o.overlayId;
if (typeof el == 'string') el = hs.getNode(el);
if (o.html) el = hs.createElement('div', { innerHTML: o.html });
if (!el || typeof el == 'string') return;
el.style.display = 'block';
this.genOverlayBox();
var width = o.width && /^[0-9]+(px|%)$/.test(o.width) ? o.width : 'auto';
if (/^(left|right)panel$/.test(o.position) && !/^[0-9]+px$/.test(o.width)) width = '200px';
var overlay = hs.createElement(
'div', {
id: 'hsId'+ hs.idCounter++,
hsId: o.hsId
}, {
position: 'absolute',
visibility: 'hidden',
width: width,
direction: hs.lang.cssDirection || '',
opacity: 0
},this.overlayBox,
true
);
overlay.appendChild(el);
hs.extend(overlay, {
opacity: 1,
offsetX: 0,
offsetY: 0,
dur: (o.fade === 0 || o.fade === false || (o.fade == 2 && hs.ie)) ? 0 : 250
});
hs.extend(overlay, o);
if (this.gotOverlays) {
this.positionOverlay(overlay);
if (!overlay.hideOnMouseOut || this.mouseIsOver)
hs.animate(overlay, { opacity: overlay.opacity }, overlay.dur);
}
hs.push(this.overlays, hs.idCounter - 1);
},
positionOverlay : function(overlay) {
var p = overlay.position || 'middle center',
offX = overlay.offsetX,
offY = overlay.offsetY;
if (overlay.parentNode != this.overlayBox) this.overlayBox.appendChild(overlay);
if (/left$/.test(p)) overlay.style.left = offX +'px';
if (/center$/.test(p)) hs.setStyles (overlay, {
left: '50%',
marginLeft: (offX - Math.round(overlay.offsetWidth / 2)) +'px'
});
if (/right$/.test(p)) overlay.style.right = - offX +'px';
if (/^leftpanel$/.test(p)) {
hs.setStyles(overlay, {
right: '100%',
marginRight: this.x.cb +'px',
top: - this.y.cb +'px',
bottom: - this.y.cb +'px',
overflow: 'auto'
});
this.x.p1 = overlay.offsetWidth;
} else if (/^rightpanel$/.test(p)) {
hs.setStyles(overlay, {
left: '100%',
marginLeft: this.x.cb +'px',
top: - this.y.cb +'px',
bottom: - this.y.cb +'px',
overflow: 'auto'
});
this.x.p2 = overlay.offsetWidth;
}
if (/^top/.test(p)) overlay.style.top = offY +'px';
if (/^middle/.test(p)) hs.setStyles (overlay, {
top: '50%',
marginTop: (offY - Math.round(overlay.offsetHeight / 2)) +'px'
});
if (/^bottom/.test(p)) overlay.style.bottom = - offY +'px';
if (/^above$/.test(p)) {
hs.setStyles(overlay, {
left: (- this.x.p1 - this.x.cb) +'px',
right: (- this.x.p2 - this.x.cb) +'px',
bottom: '100%',
marginBottom: this.y.cb +'px',
width: 'auto'
});
this.y.p1 = overlay.offsetHeight;
} else if (/^below$/.test(p)) {
hs.setStyles(overlay, {
position: 'relative',
left: (- this.x.p1 - this.x.cb) +'px',
right: (- this.x.p2 - this.x.cb) +'px',
top: '100%',
marginTop: this.y.cb +'px',
width: 'auto'
});
this.y.p2 = overlay.offsetHeight;
overlay.style.position = 'absolute';
}
},
getOverlays : function() {
this.getInline(['heading', 'caption'], true);
if (this.heading && this.dragByHeading) this.heading.className += ' highslide-move';
if (hs.showCredits) this.writeCredits();
for (var i = 0; i < hs.overlays.length; i++) {
var o = hs.overlays[i], tId = o.thumbnailId, sg = o.slideshowGroup;
if ((!tId && !sg) || (tId && tId == this.thumbsUserSetId)
|| (sg && sg === this.slideshowGroup)) {
this.createOverlay(o);
}
}
var os = [];
for (var i = 0; i < this.overlays.length; i++) {
var o = hs.$('hsId'+ this.overlays[i]);
if (/panel$/.test(o.position)) this.positionOverlay(o);
else hs.push(os, o);
}
for (var i = 0; i < os.length; i++) this.positionOverlay(os[i]);
this.gotOverlays = true;
},
genOverlayBox : function() {
if (!this.overlayBox) this.overlayBox = hs.createElement (
'div', {
className: this.wrapperClassName
}, {
position : 'absolute',
width: (this.x.size || (this.useBox ? this.width : null)
|| this.x.full) +'px',
height: (this.y.size || this.y.full) +'px',
visibility : 'hidden',
overflow : 'hidden',
zIndex : hs.ie ? 4 : 'auto'
},
hs.container,
true
);
},
sizeOverlayBox : function(doWrapper, doPanels) {
var overlayBox = this.overlayBox,
x = this.x,
y = this.y;
hs.setStyles( overlayBox, {
width: x.size +'px',
height: y.size +'px'
});
if (doWrapper || doPanels) {
for (var i = 0; i < this.overlays.length; i++) {
var o = hs.$('hsId'+ this.overlays[i]);
var ie6 = (hs.ieLt7 || document.compatMode == 'BackCompat');
if (o && /^(above|below)$/.test(o.position)) {
if (ie6) {
o.style.width = (overlayBox.offsetWidth + 2 * x.cb
+ x.p1 + x.p2) +'px';
}
y[o.position == 'above' ? 'p1' : 'p2'] = o.offsetHeight;
}
if (o && ie6 && /^(left|right)panel$/.test(o.position)) {
o.style.height = (overlayBox.offsetHeight + 2* y.cb) +'px';
}
}
}
if (doWrapper) {
hs.setStyles(this.content, {
top: y.p1 +'px'
});
hs.setStyles(overlayBox, {
top: (y.p1 + y.cb) +'px'
});
}
},
showOverlays : function() {
var b = this.overlayBox;
b.className = '';
hs.setStyles(b, {
top: (this.y.p1 + this.y.cb) +'px',
left: (this.x.p1 + this.x.cb) +'px',
overflow : 'visible'
});
if (hs.safari) b.style.visibility = 'visible';
this.wrapper.appendChild (b);
for (var i = 0; i < this.overlays.length; i++) {
var o = hs.$('hsId'+ this.overlays[i]);
o.style.zIndex = 4;
if (!o.hideOnMouseOut || this.mouseIsOver) {
o.style.visibility = 'visible';
hs.setStyles(o, { visibility: 'visible', display: '' });
hs.animate(o, { opacity: o.opacity }, o.dur);
}
}
},
destroyOverlays : function() {
if (!this.overlays.length) return;
hs.discardElement(this.overlayBox);
},
createFullExpand : function () {
this.fullExpandLabel = hs.createElement(
'a', {
href: 'javascript:hs.expanders['+ this.key +'].doFullExpand();',
title: hs.lang.fullExpandTitle,
className: 'highslide-full-expand'
}
);
this.createOverlay({
overlayId: this.fullExpandLabel,
position: hs.fullExpandPosition,
hideOnMouseOut: true,
opacity: hs.fullExpandOpacity
});
},
doFullExpand : function () {
try {
if (this.fullExpandLabel) hs.discardElement(this.fullExpandLabel);
this.focus();
var xSize = this.x.size;
this.resizeTo(this.x.full, this.y.full);
var xpos = this.x.pos - (this.x.size - xSize) / 2;
if (xpos < hs.marginLeft) xpos = hs.marginLeft;
this.moveTo(xpos, this.y.pos);
this.doShowHide('hidden');
} catch (e) {
this.error(e);
}
},
afterClose : function () {
this.a.className = this.a.className.replace('highslide-active-anchor', '');
this.doShowHide('visible');
if (this.outline && this.outlineWhileAnimating) this.outline.destroy();
hs.discardElement(this.wrapper);
hs.expanders[this.key] = null;
hs.reOrder();
}
};
hs.langDefaults = hs.lang;
// history
var HsExpander = hs.Expander;
if (hs.ie) {
(function () {
try {
document.documentElement.doScroll('left');
} catch (e) {
setTimeout(arguments.callee, 50);
return;
}
hs.ready();
})();
}
hs.addEventListener(document, 'DOMContentLoaded', hs.ready);
hs.addEventListener(window, 'load', hs.ready);
// set handlers
hs.addEventListener(document, 'ready', function() {
if (hs.expandCursor) {
var style = hs.createElement('style', { type: 'text/css' }, null,
document.getElementsByTagName('HEAD')[0]);
function addRule(sel, dec) {
if (!hs.ie) {
style.appendChild(document.createTextNode(sel + " {" + dec + "}"));
} else {
var last = document.styleSheets[document.styleSheets.length - 1];
if (typeof(last.addRule) == "object") last.addRule(sel, dec);
}
}
function fix(prop) {
return 'expression( ( ( ignoreMe = document.documentElement.'+ prop +
' ? document.documentElement.'+ prop +' : document.body.'+ prop +' ) ) + \'px\' );';
}
if (hs.expandCursor) addRule ('.highslide img',
'cursor: url('+ hs.graphicsDir + hs.expandCursor +'), pointer !important;');
}
});
hs.addEventListener(window, 'resize', function() {
hs.getPageSize();
});
hs.addEventListener(document, 'mousemove', function(e) {
hs.mouse = { x: e.clientX, y: e.clientY };
});
hs.addEventListener(document, 'mousedown', hs.mouseClickHandler);
hs.addEventListener(document, 'mouseup', hs.mouseClickHandler);
hs.addEventListener(document, 'ready', hs.getAnchors);
hs.addEventListener(window, 'load', hs.preloadImages);
} | JavaScript |
jQuery(document).ready(function () {
jQuery('.akismet-status').each(function () {
var thisId = jQuery(this).attr('commentid');
jQuery(this).prependTo('#comment-' + thisId + ' .column-comment div:first-child');
});
jQuery('.akismet-user-comment-count').each(function () {
var thisId = jQuery(this).attr('commentid');
jQuery(this).insertAfter('#comment-' + thisId + ' .author strong:first').show();
});
});
| JavaScript |
/**
* Dockable.
**/
(function($){
$.widget("db.dockable", $.ui.mouse, {
options: {
handle: false,
axis: 'y',
resize: function() {},
resized: function() {}
},
_create: function() {
if ( this.options.axis == 'x' ) {
this.page = 'pageX';
this.dimension = 'width';
} else {
this.page = 'pageY';
this.dimension = 'height';
}
if ( ! this.options.handle )
return;
this.handle = $( this.options.handle );
this._mouseInit();
},
_handoff: function() {
return {
element: this.element,
handle: this.handle,
axis: this.options.axis
};
},
_mouseStart: function(event) {
this._trigger( "start", event, this._handoff() );
this.d0 = this.element[this.dimension]() + event[this.page];
},
_mouseDrag: function(event) {
var resize = this._trigger( "resize", event, this._handoff() );
// If the resize event returns false, we don't resize.
if ( resize === false )
return;
this.element[this.dimension]( this.d0 - event[this.page] );
this._trigger( "resized", event, this._handoff() );
},
_mouseCapture: function(event) {
return !this.options.disabled && event.target == this.handle[0];
},
_mouseStop: function(event) {
this._trigger( "stop", event, this._handoff() );
}
});
})(jQuery); | JavaScript |
(function() {
var count, list, rawCount = 0;
window.onerror = function( errorMsg, url, lineNumber ) {
var errorLine, place, button, tab;
rawCount++;
if ( !count )
count = document.getElementById( 'debug-bar-js-error-count' );
if ( !list )
list = document.getElementById( 'debug-bar-js-errors' );
if ( !count || !list )
return; // threw way too early... @todo cache these?
if ( 1 == rawCount ) {
button = document.getElementById( 'wp-admin-bar-debug-bar' );
if ( !button )
return; // how did this happen?
if ( button.className.indexOf( 'debug-bar-php-warning-summary' ) === -1 )
button.className = button.className + ' debug-bar-php-warning-summary';
tab = document.getElementById('debug-menu-link-Debug_Bar_JS');
if ( tab )
tab.style.display = 'block';
}
count.textContent = rawCount;
errorLine = document.createElement( 'li' );
errorLine.className = 'debug-bar-js-error';
errorLine.textContent = errorMsg;
place = document.createElement( 'span' );
place.textContent = url + ' line ' + lineNumber;
errorLine.appendChild( place );
list.appendChild( errorLine );
return false;
};
// suppress error handling
window.addEventListener( 'error', function( e ) {
e.preventDefault();
}, true );
})(); | JavaScript |
var wpDebugBar;
(function($) {
var api;
wpDebugBar = api = {
// The element that we will pad to prevent the debug bar
// from overlapping the bottom of the page.
body: undefined,
init: function() {
// If we're not in the admin, pad the body.
api.body = $(document.body);
api.toggle.init();
api.tabs();
api.actions.init();
},
toggle: {
init: function() {
$('#wp-admin-bar-debug-bar').click( function(e) {
e.preventDefault();
api.toggle.visibility();
});
},
visibility: function( show ) {
show = typeof show == 'undefined' ? ! api.body.hasClass( 'debug-bar-visible' ) : show;
// Show/hide the debug bar.
api.body.toggleClass( 'debug-bar-visible', show );
// Press/unpress the button.
$(this).toggleClass( 'active', show );
}
},
tabs: function() {
var debugMenuLinks = $('.debug-menu-link'),
debugMenuTargets = $('.debug-menu-target');
debugMenuLinks.click( function(e) {
var t = $(this);
e.preventDefault();
if ( t.hasClass('current') )
return;
// Deselect other tabs and hide other panels.
debugMenuTargets.hide().trigger('debug-bar-hide');
debugMenuLinks.removeClass('current');
// Select the current tab and show the current panel.
t.addClass('current');
// The hashed component of the href is the id that we want to display.
$('#' + this.href.substr( this.href.indexOf( '#' ) + 1 ) ).show().trigger('debug-bar-show');
});
},
actions: {
init: function() {
var actions = $('#debug-bar-actions');
$('.maximize', actions).click( api.actions.maximize );
$('.restore', actions).click( api.actions.restore );
$('.close', actions).click( api.actions.close );
},
maximize: function() {
api.body.removeClass('debug-bar-partial');
api.body.addClass('debug-bar-maximized');
},
restore: function() {
api.body.removeClass('debug-bar-maximized');
api.body.addClass('debug-bar-partial');
},
close: function() {
api.toggle.visibility( false );
console.log( 'boo');
}
}
};
wpDebugBar.Panel = function() {
};
$(document).ready( wpDebugBar.init );
})(jQuery); | JavaScript |
(function($) {
$(document).ready( function() {
$('.feature-slider a').click(function(e) {
$('.featured-posts section.featured-post').css({
opacity: 0,
visibility: 'hidden'
});
$(this.hash).css({
opacity: 1,
visibility: 'visible'
});
$('.feature-slider a').removeClass('active');
$(this).addClass('active');
e.preventDefault();
});
});
})(jQuery); | JavaScript |
var farbtastic;
(function($){
var pickColor = function(a) {
farbtastic.setColor(a);
$('#link-color').val(a);
$('#link-color-example').css('background-color', a);
};
$(document).ready( function() {
$('#default-color').wrapInner('<a href="#" />');
farbtastic = $.farbtastic('#colorPickerDiv', pickColor);
pickColor( $('#link-color').val() );
$('.pickcolor').click( function(e) {
$('#colorPickerDiv').show();
e.preventDefault();
});
$('#link-color').keyup( function() {
var a = $('#link-color').val(),
b = a;
a = a.replace(/[^a-fA-F0-9]/, '');
if ( '#' + a !== b )
$('#link-color').val(a);
if ( a.length === 3 || a.length === 6 )
pickColor( '#' + a );
});
$(document).mousedown( function() {
$('#colorPickerDiv').hide();
});
$('#default-color a').click( function(e) {
pickColor( '#' + this.innerHTML.replace(/[^a-fA-F0-9]/, '') );
e.preventDefault();
});
$('.image-radio-option.color-scheme input:radio').change( function() {
var currentDefault = $('#default-color a'),
newDefault = $(this).next().val();
if ( $('#link-color').val() == currentDefault.text() )
pickColor( newDefault );
currentDefault.text( newDefault );
});
});
})(jQuery); | JavaScript |
var showNotice, adminMenu, columns, validateForm, screenMeta, autofold_menu;
(function($){
// Removed in 3.3.
// (perhaps) needed for back-compat
adminMenu = {
init : function() {},
fold : function() {},
restoreMenuState : function() {},
toggle : function() {},
favorites : function() {}
};
// show/hide/save table columns
columns = {
init : function() {
var that = this;
$('.hide-column-tog', '#adv-settings').click( function() {
var $t = $(this), column = $t.val();
if ( $t.prop('checked') )
that.checked(column);
else
that.unchecked(column);
columns.saveManageColumnsState();
});
},
saveManageColumnsState : function() {
var hidden = this.hidden();
$.post(ajaxurl, {
action: 'hidden-columns',
hidden: hidden,
screenoptionnonce: $('#screenoptionnonce').val(),
page: pagenow
});
},
checked : function(column) {
$('.column-' + column).show();
this.colSpanChange(+1);
},
unchecked : function(column) {
$('.column-' + column).hide();
this.colSpanChange(-1);
},
hidden : function() {
return $('.manage-column').filter(':hidden').map(function() { return this.id; }).get().join(',');
},
useCheckboxesForHidden : function() {
this.hidden = function(){
return $('.hide-column-tog').not(':checked').map(function() {
var id = this.id;
return id.substring( id, id.length - 5 );
}).get().join(',');
};
},
colSpanChange : function(diff) {
var $t = $('table').find('.colspanchange'), n;
if ( !$t.length )
return;
n = parseInt( $t.attr('colspan'), 10 ) + diff;
$t.attr('colspan', n.toString());
}
}
$(document).ready(function(){columns.init();});
validateForm = function( form ) {
return !$( form ).find('.form-required').filter( function() { return $('input:visible', this).val() == ''; } ).addClass( 'form-invalid' ).find('input:visible').change( function() { $(this).closest('.form-invalid').removeClass( 'form-invalid' ); } ).size();
}
// stub for doing better warnings
showNotice = {
warn : function() {
var msg = commonL10n.warnDelete || '';
if ( confirm(msg) ) {
return true;
}
return false;
},
note : function(text) {
alert(text);
}
};
screenMeta = {
element: null, // #screen-meta
toggles: null, // .screen-meta-toggle
page: null, // #wpcontent
init: function() {
this.element = $('#screen-meta');
this.toggles = $('.screen-meta-toggle a');
this.page = $('#wpcontent');
this.toggles.click( this.toggleEvent );
},
toggleEvent: function( e ) {
var panel = $( this.href.replace(/.+#/, '#') );
e.preventDefault();
if ( !panel.length )
return;
if ( panel.is(':visible') )
screenMeta.close( panel, $(this) );
else
screenMeta.open( panel, $(this) );
},
open: function( panel, link ) {
$('.screen-meta-toggle').not( link.parent() ).css('visibility', 'hidden');
panel.parent().show();
panel.slideDown( 'fast', function() {
link.addClass('screen-meta-active');
});
},
close: function( panel, link ) {
panel.slideUp( 'fast', function() {
link.removeClass('screen-meta-active');
$('.screen-meta-toggle').css('visibility', '');
panel.parent().hide();
});
}
};
/**
* Help tabs.
*/
$('.contextual-help-tabs').delegate('a', 'click focus', function(e) {
var link = $(this),
panel;
e.preventDefault();
// Don't do anything if the click is for the tab already showing.
if ( link.is('.active a') )
return false;
// Links
$('.contextual-help-tabs .active').removeClass('active');
link.parent('li').addClass('active');
panel = $( link.attr('href') );
// Panels
$('.help-tab-content').not( panel ).removeClass('active').hide();
panel.addClass('active').show();
});
$(document).ready( function() {
var lastClicked = false, checks, first, last, checked, menu = $('#adminmenu'),
pageInput = $('input.current-page'), currentPage = pageInput.val(), folded, refresh;
// admin menu
refresh = function(i, el){ // force the browser to refresh the tabbing index
var node = $(el), tab = node.attr('tabindex');
if ( tab )
node.attr('tabindex', '0').attr('tabindex', tab);
};
$('#collapse-menu', menu).click(function(){
var body = $(document.body);
if ( body.hasClass('folded') ) {
body.removeClass('folded');
setUserSetting('mfold', 'o');
} else {
body.addClass('folded');
setUserSetting('mfold', 'f');
}
return false;
});
$('li.wp-has-submenu', menu).hoverIntent({
over: function(e){
var b, h, o, f, m = $(this).find('.wp-submenu'), menutop, wintop, maxtop;
if ( !$(document.body).hasClass('folded') && $(this).hasClass('wp-menu-open') )
return;
menutop = $(this).offset().top;
wintop = $(window).scrollTop();
maxtop = menutop - wintop - 30; // max = make the top of the sub almost touch admin bar
b = menutop + m.height() + 1; // Bottom offset of the menu
h = $('#wpwrap').height(); // Height of the entire page
o = 60 + b - h;
f = $(window).height() + wintop - 15; // The fold
if ( f < (b - o) )
o = b - f;
if ( o > maxtop )
o = maxtop;
if ( o > 1 )
m.css({'marginTop':'-'+o+'px'});
else if ( m.css('marginTop') )
m.css({'marginTop':''});
menu.find('.wp-submenu').removeClass('sub-open');
m.addClass('sub-open');
},
out: function(){
$(this).find('.wp-submenu').removeClass('sub-open');
},
timeout: 200,
sensitivity: 7,
interval: 90
});
// Tab to select, Enter to open sub, Esc to close sub and focus the top menu
$('li.wp-has-submenu > a.wp-not-current-submenu', menu).bind('keydown.adminmenu', function(e){
if ( e.which != 13 )
return;
var target = $(e.target);
e.stopPropagation();
e.preventDefault();
menu.find('.wp-submenu').removeClass('sub-open');
target.siblings('.wp-submenu').toggleClass('sub-open').find('a[role="menuitem"]').each(refresh);
}).each(refresh);
$('a[role="menuitem"]', menu).bind('keydown.adminmenu', function(e){
if ( e.which != 27 )
return;
var target = $(e.target);
e.stopPropagation();
e.preventDefault();
target.add( target.siblings() ).closest('.sub-open').removeClass('sub-open').siblings('a.wp-not-current-submenu').focus();
});
// Move .updated and .error alert boxes. Don't move boxes designed to be inline.
$('div.wrap h2:first').nextAll('div.updated, div.error').addClass('below-h2');
$('div.updated, div.error').not('.below-h2, .inline').insertAfter( $('div.wrap h2:first') );
// Init screen meta
screenMeta.init();
// check all checkboxes
$('tbody').children().children('.check-column').find(':checkbox').click( function(e) {
if ( 'undefined' == e.shiftKey ) { return true; }
if ( e.shiftKey ) {
if ( !lastClicked ) { return true; }
checks = $( lastClicked ).closest( 'form' ).find( ':checkbox' );
first = checks.index( lastClicked );
last = checks.index( this );
checked = $(this).prop('checked');
if ( 0 < first && 0 < last && first != last ) {
checks.slice( first, last ).prop( 'checked', function(){
if ( $(this).closest('tr').is(':visible') )
return checked;
return false;
});
}
}
lastClicked = this;
return true;
});
$('thead, tfoot').find('.check-column :checkbox').click( function(e) {
var c = $(this).prop('checked'),
kbtoggle = 'undefined' == typeof toggleWithKeyboard ? false : toggleWithKeyboard,
toggle = e.shiftKey || kbtoggle;
$(this).closest( 'table' ).children( 'tbody' ).filter(':visible')
.children().children('.check-column').find(':checkbox')
.prop('checked', function() {
if ( $(this).closest('tr').is(':hidden') )
return false;
if ( toggle )
return $(this).prop( 'checked' );
else if (c)
return true;
return false;
});
$(this).closest('table').children('thead, tfoot').filter(':visible')
.children().children('.check-column').find(':checkbox')
.prop('checked', function() {
if ( toggle )
return false;
else if (c)
return true;
return false;
});
});
$('#default-password-nag-no').click( function() {
setUserSetting('default_password_nag', 'hide');
$('div.default-password-nag').hide();
return false;
});
// tab in textareas
$('#newcontent').bind('keydown.wpevent_InsertTab', function(e) {
if ( e.keyCode != 9 )
return true;
var el = e.target, selStart = el.selectionStart, selEnd = el.selectionEnd, val = el.value, scroll, sel;
try {
this.lastKey = 9; // not a standard DOM property, lastKey is to help stop Opera tab event. See blur handler below.
} catch(err) {}
if ( document.selection ) {
el.focus();
sel = document.selection.createRange();
sel.text = '\t';
} else if ( selStart >= 0 ) {
scroll = this.scrollTop;
el.value = val.substring(0, selStart).concat('\t', val.substring(selEnd) );
el.selectionStart = el.selectionEnd = selStart + 1;
this.scrollTop = scroll;
}
if ( e.stopPropagation )
e.stopPropagation();
if ( e.preventDefault )
e.preventDefault();
});
$('#newcontent').bind('blur.wpevent_InsertTab', function(e) {
if ( this.lastKey && 9 == this.lastKey )
this.focus();
});
if ( pageInput.length ) {
pageInput.closest('form').submit( function(e){
// Reset paging var for new filters/searches but not for bulk actions. See #17685.
if ( $('select[name="action"]').val() == -1 && $('select[name="action2"]').val() == -1 && pageInput.val() == currentPage )
pageInput.val('1');
});
}
// auto-fold the menu when screen is under 800px
$(window).bind('resize.autofold', function(){
if ( getUserSetting('mfold') == 'f' )
return;
var width = $(window).width();
// fold admin menu
if ( width <= 800 ) {
if ( !folded ) {
$(document.body).addClass('folded');
folded = true;
}
} else {
if ( folded ) {
$(document.body).removeClass('folded');
folded = false;
}
}
}).triggerHandler('resize');
});
// internal use
$(document).bind( 'wp_CloseOnEscape', function( e, data ) {
if ( typeof(data.cb) != 'function' )
return;
if ( typeof(data.condition) != 'function' || data.condition() )
data.cb();
return true;
});
})(jQuery);
| JavaScript |
(function($){
function check_pass_strength() {
var pass1 = $('#pass1').val(), user = $('#user_login').val(), pass2 = $('#pass2').val(), strength;
$('#pass-strength-result').removeClass('short bad good strong');
if ( ! pass1 ) {
$('#pass-strength-result').html( pwsL10n.empty );
return;
}
strength = passwordStrength(pass1, user, pass2);
switch ( strength ) {
case 2:
$('#pass-strength-result').addClass('bad').html( pwsL10n['bad'] );
break;
case 3:
$('#pass-strength-result').addClass('good').html( pwsL10n['good'] );
break;
case 4:
$('#pass-strength-result').addClass('strong').html( pwsL10n['strong'] );
break;
case 5:
$('#pass-strength-result').addClass('short').html( pwsL10n['mismatch'] );
break;
default:
$('#pass-strength-result').addClass('short').html( pwsL10n['short'] );
}
}
$(document).ready(function() {
$('#pass1').val('').keyup( check_pass_strength );
$('#pass2').val('').keyup( check_pass_strength );
$('#pass-strength-result').show();
$('.color-palette').click(function(){$(this).siblings('input[name="admin_color"]').prop('checked', true)});
$('#first_name, #last_name, #nickname').blur(function(){
var select = $('#display_name'), current = select.find('option:selected').attr('id'), dub = [],
inputs = {
display_nickname : $('#nickname').val(),
display_username : $('#user_login').val(),
display_firstname : $('#first_name').val(),
display_lastname : $('#last_name').val()
};
if ( inputs.display_firstname && inputs.display_lastname ) {
inputs['display_firstlast'] = inputs.display_firstname + ' ' + inputs.display_lastname;
inputs['display_lastfirst'] = inputs.display_lastname + ' ' + inputs.display_firstname;
}
$('option', select).remove();
$.each(inputs, function( id, value ) {
var val = value.replace(/<\/?[a-z][^>]*>/gi, '');
if ( inputs[id].length && $.inArray( val, dub ) == -1 ) {
dub.push(val);
$('<option />', {
'id': id,
'text': val,
'selected': (id == current)
}).appendTo( select );
}
});
});
});
})(jQuery);
| JavaScript |
var tagBox, commentsBox, editPermalink, makeSlugeditClickable, WPSetThumbnailHTML, WPSetThumbnailID, WPRemoveThumbnail, wptitlehint;
// return an array with any duplicate, whitespace or values removed
function array_unique_noempty(a) {
var out = [];
jQuery.each( a, function(key, val) {
val = jQuery.trim(val);
if ( val && jQuery.inArray(val, out) == -1 )
out.push(val);
} );
return out;
}
(function($){
tagBox = {
clean : function(tags) {
return tags.replace(/\s*,\s*/g, ',').replace(/,+/g, ',').replace(/[,\s]+$/, '').replace(/^[,\s]+/, '');
},
parseTags : function(el) {
var id = el.id, num = id.split('-check-num-')[1], taxbox = $(el).closest('.tagsdiv'), thetags = taxbox.find('.the-tags'), current_tags = thetags.val().split(','), new_tags = [];
delete current_tags[num];
$.each( current_tags, function(key, val) {
val = $.trim(val);
if ( val ) {
new_tags.push(val);
}
});
thetags.val( this.clean( new_tags.join(',') ) );
this.quickClicks(taxbox);
return false;
},
quickClicks : function(el) {
var thetags = $('.the-tags', el),
tagchecklist = $('.tagchecklist', el),
id = $(el).attr('id'),
current_tags, disabled;
if ( !thetags.length )
return;
disabled = thetags.prop('disabled');
current_tags = thetags.val().split(',');
tagchecklist.empty();
$.each( current_tags, function( key, val ) {
var span, xbutton;
val = $.trim( val );
if ( ! val )
return;
// Create a new span, and ensure the text is properly escaped.
span = $('<span />').text( val );
// If tags editing isn't disabled, create the X button.
if ( ! disabled ) {
xbutton = $( '<a id="' + id + '-check-num-' + key + '" class="ntdelbutton">X</a>' );
xbutton.click( function(){ tagBox.parseTags(this); });
span.prepend(' ').prepend( xbutton );
}
// Append the span to the tag list.
tagchecklist.append( span );
});
},
flushTags : function(el, a, f) {
a = a || false;
var text, tags = $('.the-tags', el), newtag = $('input.newtag', el), newtags;
text = a ? $(a).text() : newtag.val();
tagsval = tags.val();
newtags = tagsval ? tagsval + ',' + text : text;
newtags = this.clean( newtags );
newtags = array_unique_noempty( newtags.split(',') ).join(',');
tags.val(newtags);
this.quickClicks(el);
if ( !a )
newtag.val('');
if ( 'undefined' == typeof(f) )
newtag.focus();
return false;
},
get : function(id) {
var tax = id.substr(id.indexOf('-')+1);
$.post(ajaxurl, {'action':'get-tagcloud','tax':tax}, function(r, stat) {
if ( 0 == r || 'success' != stat )
r = wpAjax.broken;
r = $('<p id="tagcloud-'+tax+'" class="the-tagcloud">'+r+'</p>');
$('a', r).click(function(){
tagBox.flushTags( $(this).closest('.inside').children('.tagsdiv'), this);
return false;
});
$('#'+id).after(r);
});
},
init : function() {
var t = this, ajaxtag = $('div.ajaxtag');
$('.tagsdiv').each( function() {
tagBox.quickClicks(this);
});
$('input.tagadd', ajaxtag).click(function(){
t.flushTags( $(this).closest('.tagsdiv') );
});
$('div.taghint', ajaxtag).click(function(){
$(this).css('visibility', 'hidden').parent().siblings('.newtag').focus();
});
$('input.newtag', ajaxtag).blur(function() {
if ( this.value == '' )
$(this).parent().siblings('.taghint').css('visibility', '');
}).focus(function(){
$(this).parent().siblings('.taghint').css('visibility', 'hidden');
}).keyup(function(e){
if ( 13 == e.which ) {
tagBox.flushTags( $(this).closest('.tagsdiv') );
return false;
}
}).keypress(function(e){
if ( 13 == e.which ) {
e.preventDefault();
return false;
}
}).each(function(){
var tax = $(this).closest('div.tagsdiv').attr('id');
$(this).suggest( ajaxurl + '?action=ajax-tag-search&tax=' + tax, { delay: 500, minchars: 2, multiple: true, multipleSep: "," } );
});
// save tags on post save/publish
$('#post').submit(function(){
$('div.tagsdiv').each( function() {
tagBox.flushTags(this, false, 1);
});
});
// tag cloud
$('a.tagcloud-link').click(function(){
tagBox.get( $(this).attr('id') );
$(this).unbind().click(function(){
$(this).siblings('.the-tagcloud').toggle();
return false;
});
return false;
});
}
};
commentsBox = {
st : 0,
get : function(total, num) {
var st = this.st, data;
if ( ! num )
num = 20;
this.st += num;
this.total = total;
$('#commentsdiv img.waiting').show();
data = {
'action' : 'get-comments',
'mode' : 'single',
'_ajax_nonce' : $('#add_comment_nonce').val(),
'p' : $('#post_ID').val(),
'start' : st,
'number' : num
};
$.post(ajaxurl, data,
function(r) {
r = wpAjax.parseAjaxResponse(r);
$('#commentsdiv .widefat').show();
$('#commentsdiv img.waiting').hide();
if ( 'object' == typeof r && r.responses[0] ) {
$('#the-comment-list').append( r.responses[0].data );
theList = theExtraList = null;
$("a[className*=':']").unbind();
if ( commentsBox.st > commentsBox.total )
$('#show-comments').hide();
else
$('#show-comments').html(postL10n.showcomm);
return;
} else if ( 1 == r ) {
$('#show-comments').parent().html(postL10n.endcomm);
return;
}
$('#the-comment-list').append('<tr><td colspan="2">'+wpAjax.broken+'</td></tr>');
}
);
return false;
}
};
WPSetThumbnailHTML = function(html){
$('.inside', '#postimagediv').html(html);
};
WPSetThumbnailID = function(id){
var field = $('input[value="_thumbnail_id"]', '#list-table');
if ( field.size() > 0 ) {
$('#meta\\[' + field.attr('id').match(/[0-9]+/) + '\\]\\[value\\]').text(id);
}
};
WPRemoveThumbnail = function(nonce){
$.post(ajaxurl, {
action:"set-post-thumbnail", post_id: $('#post_ID').val(), thumbnail_id: -1, _ajax_nonce: nonce, cookie: encodeURIComponent(document.cookie)
}, function(str){
if ( str == '0' ) {
alert( setPostThumbnailL10n.error );
} else {
WPSetThumbnailHTML(str);
}
}
);
};
})(jQuery);
jQuery(document).ready( function($) {
var stamp, visibility, sticky = '', last = 0, co = $('#content');
postboxes.add_postbox_toggles(pagenow);
// multi-taxonomies
if ( $('#tagsdiv-post_tag').length ) {
tagBox.init();
} else {
$('#side-sortables, #normal-sortables, #advanced-sortables').children('div.postbox').each(function(){
if ( this.id.indexOf('tagsdiv-') === 0 ) {
tagBox.init();
return false;
}
});
}
// categories
$('.categorydiv').each( function(){
var this_id = $(this).attr('id'), noSyncChecks = false, syncChecks, catAddAfter, taxonomyParts, taxonomy, settingName;
taxonomyParts = this_id.split('-');
taxonomyParts.shift();
taxonomy = taxonomyParts.join('-');
settingName = taxonomy + '_tab';
if ( taxonomy == 'category' )
settingName = 'cats';
// TODO: move to jQuery 1.3+, support for multiple hierarchical taxonomies, see wp-lists.dev.js
$('a', '#' + taxonomy + '-tabs').click( function(){
var t = $(this).attr('href');
$(this).parent().addClass('tabs').siblings('li').removeClass('tabs');
$('#' + taxonomy + '-tabs').siblings('.tabs-panel').hide();
$(t).show();
if ( '#' + taxonomy + '-all' == t )
deleteUserSetting(settingName);
else
setUserSetting(settingName, 'pop');
return false;
});
if ( getUserSetting(settingName) )
$('a[href="#' + taxonomy + '-pop"]', '#' + taxonomy + '-tabs').click();
// Ajax Cat
$('#new' + taxonomy).one( 'focus', function() { $(this).val( '' ).removeClass( 'form-input-tip' ) } );
$('#' + taxonomy + '-add-submit').click( function(){ $('#new' + taxonomy).focus(); });
syncChecks = function() {
if ( noSyncChecks )
return;
noSyncChecks = true;
var th = jQuery(this), c = th.is(':checked'), id = th.val().toString();
$('#in-' + taxonomy + '-' + id + ', #in-' + taxonomy + '-category-' + id).prop( 'checked', c );
noSyncChecks = false;
};
catAddBefore = function( s ) {
if ( !$('#new'+taxonomy).val() )
return false;
s.data += '&' + $( ':checked', '#'+taxonomy+'checklist' ).serialize();
return s;
};
catAddAfter = function( r, s ) {
var sup, drop = $('#new'+taxonomy+'_parent');
if ( 'undefined' != s.parsed.responses[0] && (sup = s.parsed.responses[0].supplemental.newcat_parent) ) {
drop.before(sup);
drop.remove();
}
};
$('#' + taxonomy + 'checklist').wpList({
alt: '',
response: taxonomy + '-ajax-response',
addBefore: catAddBefore,
addAfter: catAddAfter
});
$('#' + taxonomy + '-add-toggle').click( function() {
$('#' + taxonomy + '-adder').toggleClass( 'wp-hidden-children' );
$('a[href="#' + taxonomy + '-all"]', '#' + taxonomy + '-tabs').click();
$('#new'+taxonomy).focus();
return false;
});
$('#' + taxonomy + 'checklist li.popular-category :checkbox, #' + taxonomy + 'checklist-pop :checkbox').live( 'click', function(){
var t = $(this), c = t.is(':checked'), id = t.val();
if ( id && t.parents('#taxonomy-'+taxonomy).length )
$('#in-' + taxonomy + '-' + id + ', #in-popular-' + taxonomy + '-' + id).prop( 'checked', c );
});
}); // end cats
// Custom Fields
if ( $('#postcustom').length ) {
$('#the-list').wpList( { addAfter: function( xml, s ) {
$('table#list-table').show();
}, addBefore: function( s ) {
s.data += '&post_id=' + $('#post_ID').val();
return s;
}
});
}
// submitdiv
if ( $('#submitdiv').length ) {
stamp = $('#timestamp').html();
visibility = $('#post-visibility-display').html();
function updateVisibility() {
var pvSelect = $('#post-visibility-select');
if ( $('input:radio:checked', pvSelect).val() != 'public' ) {
$('#sticky').prop('checked', false);
$('#sticky-span').hide();
} else {
$('#sticky-span').show();
}
if ( $('input:radio:checked', pvSelect).val() != 'password' ) {
$('#password-span').hide();
} else {
$('#password-span').show();
}
}
function updateText() {
var attemptedDate, originalDate, currentDate, publishOn, postStatus = $('#post_status'),
optPublish = $('option[value="publish"]', postStatus), aa = $('#aa').val(),
mm = $('#mm').val(), jj = $('#jj').val(), hh = $('#hh').val(), mn = $('#mn').val();
attemptedDate = new Date( aa, mm - 1, jj, hh, mn );
originalDate = new Date( $('#hidden_aa').val(), $('#hidden_mm').val() -1, $('#hidden_jj').val(), $('#hidden_hh').val(), $('#hidden_mn').val() );
currentDate = new Date( $('#cur_aa').val(), $('#cur_mm').val() -1, $('#cur_jj').val(), $('#cur_hh').val(), $('#cur_mn').val() );
if ( attemptedDate.getFullYear() != aa || (1 + attemptedDate.getMonth()) != mm || attemptedDate.getDate() != jj || attemptedDate.getMinutes() != mn ) {
$('.timestamp-wrap', '#timestampdiv').addClass('form-invalid');
return false;
} else {
$('.timestamp-wrap', '#timestampdiv').removeClass('form-invalid');
}
if ( attemptedDate > currentDate && $('#original_post_status').val() != 'future' ) {
publishOn = postL10n.publishOnFuture;
$('#publish').val( postL10n.schedule );
} else if ( attemptedDate <= currentDate && $('#original_post_status').val() != 'publish' ) {
publishOn = postL10n.publishOn;
$('#publish').val( postL10n.publish );
} else {
publishOn = postL10n.publishOnPast;
$('#publish').val( postL10n.update );
}
if ( originalDate.toUTCString() == attemptedDate.toUTCString() ) { //hack
$('#timestamp').html(stamp);
} else {
$('#timestamp').html(
publishOn + ' <b>' +
$('option[value="' + $('#mm').val() + '"]', '#mm').text() + ' ' +
jj + ', ' +
aa + ' @ ' +
hh + ':' +
mn + '</b> '
);
}
if ( $('input:radio:checked', '#post-visibility-select').val() == 'private' ) {
$('#publish').val( postL10n.update );
if ( optPublish.length == 0 ) {
postStatus.append('<option value="publish">' + postL10n.privatelyPublished + '</option>');
} else {
optPublish.html( postL10n.privatelyPublished );
}
$('option[value="publish"]', postStatus).prop('selected', true);
$('.edit-post-status', '#misc-publishing-actions').hide();
} else {
if ( $('#original_post_status').val() == 'future' || $('#original_post_status').val() == 'draft' ) {
if ( optPublish.length ) {
optPublish.remove();
postStatus.val($('#hidden_post_status').val());
}
} else {
optPublish.html( postL10n.published );
}
if ( postStatus.is(':hidden') )
$('.edit-post-status', '#misc-publishing-actions').show();
}
$('#post-status-display').html($('option:selected', postStatus).text());
if ( $('option:selected', postStatus).val() == 'private' || $('option:selected', postStatus).val() == 'publish' ) {
$('#save-post').hide();
} else {
$('#save-post').show();
if ( $('option:selected', postStatus).val() == 'pending' ) {
$('#save-post').show().val( postL10n.savePending );
} else {
$('#save-post').show().val( postL10n.saveDraft );
}
}
return true;
}
$('.edit-visibility', '#visibility').click(function () {
if ($('#post-visibility-select').is(":hidden")) {
updateVisibility();
$('#post-visibility-select').slideDown('fast');
$(this).hide();
}
return false;
});
$('.cancel-post-visibility', '#post-visibility-select').click(function () {
$('#post-visibility-select').slideUp('fast');
$('#visibility-radio-' + $('#hidden-post-visibility').val()).prop('checked', true);
$('#post_password').val($('#hidden_post_password').val());
$('#sticky').prop('checked', $('#hidden-post-sticky').prop('checked'));
$('#post-visibility-display').html(visibility);
$('.edit-visibility', '#visibility').show();
updateText();
return false;
});
$('.save-post-visibility', '#post-visibility-select').click(function () { // crazyhorse - multiple ok cancels
var pvSelect = $('#post-visibility-select');
pvSelect.slideUp('fast');
$('.edit-visibility', '#visibility').show();
updateText();
if ( $('input:radio:checked', pvSelect).val() != 'public' ) {
$('#sticky').prop('checked', false);
} // WEAPON LOCKED
if ( true == $('#sticky').prop('checked') ) {
sticky = 'Sticky';
} else {
sticky = '';
}
$('#post-visibility-display').html( postL10n[$('input:radio:checked', pvSelect).val() + sticky] );
return false;
});
$('input:radio', '#post-visibility-select').change(function() {
updateVisibility();
});
$('#timestampdiv').siblings('a.edit-timestamp').click(function() {
if ($('#timestampdiv').is(":hidden")) {
$('#timestampdiv').slideDown('fast');
$(this).hide();
}
return false;
});
$('.cancel-timestamp', '#timestampdiv').click(function() {
$('#timestampdiv').slideUp('fast');
$('#mm').val($('#hidden_mm').val());
$('#jj').val($('#hidden_jj').val());
$('#aa').val($('#hidden_aa').val());
$('#hh').val($('#hidden_hh').val());
$('#mn').val($('#hidden_mn').val());
$('#timestampdiv').siblings('a.edit-timestamp').show();
updateText();
return false;
});
$('.save-timestamp', '#timestampdiv').click(function () { // crazyhorse - multiple ok cancels
if ( updateText() ) {
$('#timestampdiv').slideUp('fast');
$('#timestampdiv').siblings('a.edit-timestamp').show();
}
return false;
});
$('#post-status-select').siblings('a.edit-post-status').click(function() {
if ($('#post-status-select').is(":hidden")) {
$('#post-status-select').slideDown('fast');
$(this).hide();
}
return false;
});
$('.save-post-status', '#post-status-select').click(function() {
$('#post-status-select').slideUp('fast');
$('#post-status-select').siblings('a.edit-post-status').show();
updateText();
return false;
});
$('.cancel-post-status', '#post-status-select').click(function() {
$('#post-status-select').slideUp('fast');
$('#post_status').val($('#hidden_post_status').val());
$('#post-status-select').siblings('a.edit-post-status').show();
updateText();
return false;
});
} // end submitdiv
// permalink
if ( $('#edit-slug-box').length ) {
editPermalink = function(post_id) {
var i, c = 0, e = $('#editable-post-name'), revert_e = e.html(), real_slug = $('#post_name'), revert_slug = real_slug.val(), b = $('#edit-slug-buttons'), revert_b = b.html(), full = $('#editable-post-name-full').html();
$('#view-post-btn').hide();
b.html('<a href="#" class="save button">'+postL10n.ok+'</a> <a class="cancel" href="#">'+postL10n.cancel+'</a>');
b.children('.save').click(function() {
var new_slug = e.children('input').val();
if ( new_slug == $('#editable-post-name-full').text() ) {
return $('.cancel', '#edit-slug-buttons').click();
}
$.post(ajaxurl, {
action: 'sample-permalink',
post_id: post_id,
new_slug: new_slug,
new_title: $('#title').val(),
samplepermalinknonce: $('#samplepermalinknonce').val()
}, function(data) {
$('#edit-slug-box').html(data);
b.html(revert_b);
real_slug.val(new_slug);
makeSlugeditClickable();
$('#view-post-btn').show();
});
return false;
});
$('.cancel', '#edit-slug-buttons').click(function() {
$('#view-post-btn').show();
e.html(revert_e);
b.html(revert_b);
real_slug.val(revert_slug);
return false;
});
for ( i = 0; i < full.length; ++i ) {
if ( '%' == full.charAt(i) )
c++;
}
slug_value = ( c > full.length / 4 ) ? '' : full;
e.html('<input type="text" id="new-post-slug" value="'+slug_value+'" />').children('input').keypress(function(e){
var key = e.keyCode || 0;
// on enter, just save the new slug, don't save the post
if ( 13 == key ) {
b.children('.save').click();
return false;
}
if ( 27 == key ) {
b.children('.cancel').click();
return false;
}
real_slug.val(this.value);
}).focus();
}
makeSlugeditClickable = function() {
$('#editable-post-name').click(function() {
$('#edit-slug-buttons').children('.edit-slug').click();
});
}
makeSlugeditClickable();
}
// word count
if ( typeof(wpWordCount) != 'undefined' ) {
$(document).triggerHandler('wpcountwords', [ co.val() ]);
co.keyup( function(e) {
var k = e.keyCode || e.charCode;
if ( k == last )
return true;
if ( 13 == k || 8 == last || 46 == last )
$(document).triggerHandler('wpcountwords', [ co.val() ]);
last = k;
return true;
});
}
wptitlehint = function(id) {
id = id || 'title';
var title = $('#' + id), titleprompt = $('#' + id + '-prompt-text');
if ( title.val() == '' )
titleprompt.css('visibility', '');
titleprompt.click(function(){
$(this).css('visibility', 'hidden');
title.focus();
});
title.blur(function(){
if ( this.value == '' )
titleprompt.css('visibility', '');
}).focus(function(){
titleprompt.css('visibility', 'hidden');
}).keydown(function(e){
titleprompt.css('visibility', 'hidden');
$(this).unbind(e);
});
}
wptitlehint();
});
| JavaScript |
(function($) {
inlineEditTax = {
init : function() {
var t = this, row = $('#inline-edit');
t.type = $('#the-list').attr('class').substr(5);
t.what = '#'+t.type+'-';
$('.editinline').live('click', function(){
inlineEditTax.edit(this);
return false;
});
// prepare the edit row
row.keyup(function(e) { if(e.which == 27) return inlineEditTax.revert(); });
$('a.cancel', row).click(function() { return inlineEditTax.revert(); });
$('a.save', row).click(function() { return inlineEditTax.save(this); });
$('input, select', row).keydown(function(e) { if(e.which == 13) return inlineEditTax.save(this); });
$('#posts-filter input[type="submit"]').mousedown(function(e){
t.revert();
});
},
toggle : function(el) {
var t = this;
$(t.what+t.getId(el)).css('display') == 'none' ? t.revert() : t.edit(el);
},
edit : function(id) {
var t = this, editRow;
t.revert();
if ( typeof(id) == 'object' )
id = t.getId(id);
editRow = $('#inline-edit').clone(true), rowData = $('#inline_'+id);
$('td', editRow).attr('colspan', $('.widefat:first thead th:visible').length);
if ( $(t.what+id).hasClass('alternate') )
$(editRow).addClass('alternate');
$(t.what+id).hide().after(editRow);
$(':input[name="name"]', editRow).val( $('.name', rowData).text() );
$(':input[name="slug"]', editRow).val( $('.slug', rowData).text() );
$(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();
$('.ptitle', editRow).eq(0).focus();
return false;
},
save : function(id) {
var params, fields, tax = $('input[name="taxonomy"]').val() || '';
if( typeof(id) == 'object' )
id = this.getId(id);
$('table.widefat .inline-edit-save .waiting').show();
params = {
action: 'inline-save-tax',
tax_type: this.type,
tax_ID: id,
taxonomy: tax
};
fields = $('#edit-'+id+' :input').serialize();
params = fields + '&' + $.param(params);
// make ajax request
$.post('admin-ajax.php', params,
function(r) {
var row, new_id;
$('table.widefat .inline-edit-save .waiting').hide();
if (r) {
if ( -1 != r.indexOf('<tr') ) {
$(inlineEditTax.what+id).remove();
new_id = $(r).attr('id');
$('#edit-'+id).before(r).remove();
row = new_id ? $('#'+new_id) : $(inlineEditTax.what+id);
row.hide().fadeIn();
} else
$('#edit-'+id+' .inline-edit-save .error').html(r).show();
} else
$('#edit-'+id+' .inline-edit-save .error').html(inlineEditL10n.error).show();
}
);
return false;
},
revert : function() {
var id = $('table.widefat tr.inline-editor').attr('id');
if ( id ) {
$('table.widefat .inline-edit-save .waiting').hide();
$('#'+id).remove();
id = id.substr( id.lastIndexOf('-') + 1 );
$(this.what+id).show();
}
return false;
},
getId : function(o) {
var id = o.tagName == 'TR' ? o.id : $(o).parents('tr').attr('id'), parts = id.split('-');
return parts[parts.length - 1];
}
};
$(document).ready(function(){inlineEditTax.init();});
})(jQuery);
| JavaScript |
function WPSetAsThumbnail(id, nonce){
var $link = jQuery('a#wp-post-thumbnail-' + id);
$link.text( setPostThumbnailL10n.saving );
jQuery.post(ajaxurl, {
action:"set-post-thumbnail", post_id: post_id, thumbnail_id: id, _ajax_nonce: nonce, cookie: encodeURIComponent(document.cookie)
}, function(str){
var win = window.dialogArguments || opener || parent || top;
$link.text( setPostThumbnailL10n.setThumbnail );
if ( str == '0' ) {
alert( setPostThumbnailL10n.error );
} else {
jQuery('a.wp-post-thumbnail').show();
$link.text( setPostThumbnailL10n.done );
$link.fadeOut( 2000 );
win.WPSetThumbnailID(id);
win.WPSetThumbnailHTML(str);
}
}
);
}
| JavaScript |
jQuery(document).ready( function($) {
var stamp = $('#timestamp').html();
$('.edit-timestamp').click(function () {
if ($('#timestampdiv').is(":hidden")) {
$('#timestampdiv').slideDown("normal");
$('.edit-timestamp').hide();
}
return false;
});
$('.cancel-timestamp').click(function() {
$('#timestampdiv').slideUp("normal");
$('#mm').val($('#hidden_mm').val());
$('#jj').val($('#hidden_jj').val());
$('#aa').val($('#hidden_aa').val());
$('#hh').val($('#hidden_hh').val());
$('#mn').val($('#hidden_mn').val());
$('#timestamp').html(stamp);
$('.edit-timestamp').show();
return false;
});
$('.save-timestamp').click(function () { // crazyhorse - multiple ok cancels
var aa = $('#aa').val(), mm = $('#mm').val(), jj = $('#jj').val(), hh = $('#hh').val(), mn = $('#mn').val(),
newD = new Date( aa, mm - 1, jj, hh, mn );
if ( newD.getFullYear() != aa || (1 + newD.getMonth()) != mm || newD.getDate() != jj || newD.getMinutes() != mn ) {
$('.timestamp-wrap', '#timestampdiv').addClass('form-invalid');
return false;
} else {
$('.timestamp-wrap', '#timestampdiv').removeClass('form-invalid');
}
$('#timestampdiv').slideUp("normal");
$('.edit-timestamp').show();
$('#timestamp').html(
commentL10n.submittedOn + ' <b>' +
$( '#mm option[value="' + mm + '"]' ).text() + ' ' +
jj + ', ' +
aa + ' @ ' +
hh + ':' +
mn + '</b> '
);
return false;
});
});
| JavaScript |
jQuery(document).ready(function($) {
var gallerySortable, gallerySortableInit, w, desc = false;
gallerySortableInit = function() {
gallerySortable = $('#media-items').sortable( {
items: 'div.media-item',
placeholder: 'sorthelper',
axis: 'y',
distance: 2,
handle: 'div.filename',
stop: function(e, ui) {
// When an update has occurred, adjust the order for each item
var all = $('#media-items').sortable('toArray'), len = all.length;
$.each(all, function(i, id) {
var order = desc ? (len - i) : (1 + i);
$('#' + id + ' .menu_order input').val(order);
});
}
} );
}
sortIt = function() {
var all = $('.menu_order_input'), len = all.length;
all.each(function(i){
var order = desc ? (len - i) : (1 + i);
$(this).val(order);
});
}
clearAll = function(c) {
c = c || 0;
$('.menu_order_input').each(function(){
if ( this.value == '0' || c ) this.value = '';
});
}
$('#asc').click(function(){desc = false; sortIt(); return false;});
$('#desc').click(function(){desc = true; sortIt(); return false;});
$('#clear').click(function(){clearAll(1); return false;});
$('#showall').click(function(){
$('#sort-buttons span a').toggle();
$('a.describe-toggle-on').hide();
$('a.describe-toggle-off, table.slidetoggle').show();
$('img.pinkynail').toggle(false);
return false;
});
$('#hideall').click(function(){
$('#sort-buttons span a').toggle();
$('a.describe-toggle-on').show();
$('a.describe-toggle-off, table.slidetoggle').hide();
$('img.pinkynail').toggle(true);
return false;
});
// initialize sortable
gallerySortableInit();
clearAll();
if ( $('#media-items>*').length > 1 ) {
w = wpgallery.getWin();
$('#save-all, #gallery-settings').show();
if ( typeof w.tinyMCE != 'undefined' && w.tinyMCE.activeEditor && ! w.tinyMCE.activeEditor.isHidden() ) {
wpgallery.mcemode = true;
wpgallery.init();
} else {
$('#insert-gallery').show();
}
}
});
jQuery(window).unload( function () { tinymce = tinyMCE = wpgallery = null; } ); // Cleanup
/* gallery settings */
var tinymce = null, tinyMCE, wpgallery;
wpgallery = {
mcemode : false,
editor : {},
dom : {},
is_update : false,
el : {},
I : function(e) {
return document.getElementById(e);
},
init: function() {
var t = this, li, q, i, it, w = t.getWin();
if ( ! t.mcemode ) return;
li = ('' + document.location.search).replace(/^\?/, '').split('&');
q = {};
for (i=0; i<li.length; i++) {
it = li[i].split('=');
q[unescape(it[0])] = unescape(it[1]);
}
if (q.mce_rdomain)
document.domain = q.mce_rdomain;
// Find window & API
tinymce = w.tinymce;
tinyMCE = w.tinyMCE;
t.editor = tinymce.EditorManager.activeEditor;
t.setup();
},
getWin : function() {
return window.dialogArguments || opener || parent || top;
},
setup : function() {
var t = this, a, ed = t.editor, g, columns, link, order, orderby;
if ( ! t.mcemode ) return;
t.el = ed.selection.getNode();
if ( t.el.nodeName != 'IMG' || ! ed.dom.hasClass(t.el, 'wpGallery') ) {
if ( (g = ed.dom.select('img.wpGallery')) && g[0] ) {
t.el = g[0];
} else {
if ( getUserSetting('galfile') == '1' ) t.I('linkto-file').checked = "checked";
if ( getUserSetting('galdesc') == '1' ) t.I('order-desc').checked = "checked";
if ( getUserSetting('galcols') ) t.I('columns').value = getUserSetting('galcols');
if ( getUserSetting('galord') ) t.I('orderby').value = getUserSetting('galord');
jQuery('#insert-gallery').show();
return;
}
}
a = ed.dom.getAttrib(t.el, 'title');
a = ed.dom.decode(a);
if ( a ) {
jQuery('#update-gallery').show();
t.is_update = true;
columns = a.match(/columns=['"]([0-9]+)['"]/);
link = a.match(/link=['"]([^'"]+)['"]/i);
order = a.match(/order=['"]([^'"]+)['"]/i);
orderby = a.match(/orderby=['"]([^'"]+)['"]/i);
if ( link && link[1] ) t.I('linkto-file').checked = "checked";
if ( order && order[1] ) t.I('order-desc').checked = "checked";
if ( columns && columns[1] ) t.I('columns').value = ''+columns[1];
if ( orderby && orderby[1] ) t.I('orderby').value = orderby[1];
} else {
jQuery('#insert-gallery').show();
}
},
update : function() {
var t = this, ed = t.editor, all = '', s;
if ( ! t.mcemode || ! t.is_update ) {
s = '[gallery'+t.getSettings()+']';
t.getWin().send_to_editor(s);
return;
}
if (t.el.nodeName != 'IMG') return;
all = ed.dom.decode(ed.dom.getAttrib(t.el, 'title'));
all = all.replace(/\s*(order|link|columns|orderby)=['"]([^'"]+)['"]/gi, '');
all += t.getSettings();
ed.dom.setAttrib(t.el, 'title', all);
t.getWin().tb_remove();
},
getSettings : function() {
var I = this.I, s = '';
if ( I('linkto-file').checked ) {
s += ' link="file"';
setUserSetting('galfile', '1');
}
if ( I('order-desc').checked ) {
s += ' order="DESC"';
setUserSetting('galdesc', '1');
}
if ( I('columns').value != 3 ) {
s += ' columns="'+I('columns').value+'"';
setUserSetting('galcols', I('columns').value);
}
if ( I('orderby').value != 'menu_order' ) {
s += ' orderby="'+I('orderby').value+'"';
setUserSetting('galord', I('orderby').value);
}
return s;
}
};
| JavaScript |
/*!
* Farbtastic: jQuery color picker plug-in v1.3u
*
* Licensed under the GPL license:
* http://www.gnu.org/licenses/gpl.html
*/
(function($) {
$.fn.farbtastic = function (options) {
$.farbtastic(this, options);
return this;
};
$.farbtastic = function (container, callback) {
var container = $(container).get(0);
return container.farbtastic || (container.farbtastic = new $._farbtastic(container, callback));
};
$._farbtastic = function (container, callback) {
// Store farbtastic object
var fb = this;
// Insert markup
$(container).html('<div class="farbtastic"><div class="color"></div><div class="wheel"></div><div class="overlay"></div><div class="h-marker marker"></div><div class="sl-marker marker"></div></div>');
var e = $('.farbtastic', container);
fb.wheel = $('.wheel', container).get(0);
// Dimensions
fb.radius = 84;
fb.square = 100;
fb.width = 194;
// Fix background PNGs in IE6
if (navigator.appVersion.match(/MSIE [0-6]\./)) {
$('*', e).each(function () {
if (this.currentStyle.backgroundImage != 'none') {
var image = this.currentStyle.backgroundImage;
image = this.currentStyle.backgroundImage.substring(5, image.length - 2);
$(this).css({
'backgroundImage': 'none',
'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
});
}
});
}
/**
* Link to the given element(s) or callback.
*/
fb.linkTo = function (callback) {
// Unbind previous nodes
if (typeof fb.callback == 'object') {
$(fb.callback).unbind('keyup', fb.updateValue);
}
// Reset color
fb.color = null;
// Bind callback or elements
if (typeof callback == 'function') {
fb.callback = callback;
}
else if (typeof callback == 'object' || typeof callback == 'string') {
fb.callback = $(callback);
fb.callback.bind('keyup', fb.updateValue);
if (fb.callback.get(0).value) {
fb.setColor(fb.callback.get(0).value);
}
}
return this;
};
fb.updateValue = function (event) {
if (this.value && this.value != fb.color) {
fb.setColor(this.value);
}
};
/**
* Change color with HTML syntax #123456
*/
fb.setColor = function (color) {
var unpack = fb.unpack(color);
if (fb.color != color && unpack) {
fb.color = color;
fb.rgb = unpack;
fb.hsl = fb.RGBToHSL(fb.rgb);
fb.updateDisplay();
}
return this;
};
/**
* Change color with HSL triplet [0..1, 0..1, 0..1]
*/
fb.setHSL = function (hsl) {
fb.hsl = hsl;
fb.rgb = fb.HSLToRGB(hsl);
fb.color = fb.pack(fb.rgb);
fb.updateDisplay();
return this;
};
/////////////////////////////////////////////////////
/**
* Retrieve the coordinates of the given event relative to the center
* of the widget.
*/
fb.widgetCoords = function (event) {
var offset = $(fb.wheel).offset();
return { x: (event.pageX - offset.left) - fb.width / 2, y: (event.pageY - offset.top) - fb.width / 2 };
};
/**
* Mousedown handler
*/
fb.mousedown = function (event) {
// Capture mouse
if (!document.dragging) {
$(document).bind('mousemove', fb.mousemove).bind('mouseup', fb.mouseup);
document.dragging = true;
}
// Check which area is being dragged
var pos = fb.widgetCoords(event);
fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > fb.square;
// Process
fb.mousemove(event);
return false;
};
/**
* Mousemove handler
*/
fb.mousemove = function (event) {
// Get coordinates relative to color picker center
var pos = fb.widgetCoords(event);
// Set new HSL parameters
if (fb.circleDrag) {
var hue = Math.atan2(pos.x, -pos.y) / 6.28;
if (hue < 0) hue += 1;
fb.setHSL([hue, fb.hsl[1], fb.hsl[2]]);
}
else {
var sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + .5));
var lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + .5));
fb.setHSL([fb.hsl[0], sat, lum]);
}
return false;
};
/**
* Mouseup handler
*/
fb.mouseup = function () {
// Uncapture mouse
$(document).unbind('mousemove', fb.mousemove);
$(document).unbind('mouseup', fb.mouseup);
document.dragging = false;
};
/**
* Update the markers and styles
*/
fb.updateDisplay = function () {
// Markers
var angle = fb.hsl[0] * 6.28;
$('.h-marker', e).css({
left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + 'px',
top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + 'px'
});
$('.sl-marker', e).css({
left: Math.round(fb.square * (.5 - fb.hsl[1]) + fb.width / 2) + 'px',
top: Math.round(fb.square * (.5 - fb.hsl[2]) + fb.width / 2) + 'px'
});
// Saturation/Luminance gradient
$('.color', e).css('backgroundColor', fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5])));
// Linked elements or callback
if (typeof fb.callback == 'object') {
// Set background/foreground color
$(fb.callback).css({
backgroundColor: fb.color,
color: fb.hsl[2] > 0.5 ? '#000' : '#fff'
});
// Change linked value
$(fb.callback).each(function() {
if (this.value && this.value != fb.color) {
this.value = fb.color;
}
});
}
else if (typeof fb.callback == 'function') {
fb.callback.call(fb, fb.color);
}
};
/* Various color utility functions */
fb.pack = function (rgb) {
var r = Math.round(rgb[0] * 255);
var g = Math.round(rgb[1] * 255);
var b = Math.round(rgb[2] * 255);
return '#' + (r < 16 ? '0' : '') + r.toString(16) +
(g < 16 ? '0' : '') + g.toString(16) +
(b < 16 ? '0' : '') + b.toString(16);
};
fb.unpack = function (color) {
if (color.length == 7) {
return [parseInt('0x' + color.substring(1, 3)) / 255,
parseInt('0x' + color.substring(3, 5)) / 255,
parseInt('0x' + color.substring(5, 7)) / 255];
}
else if (color.length == 4) {
return [parseInt('0x' + color.substring(1, 2)) / 15,
parseInt('0x' + color.substring(2, 3)) / 15,
parseInt('0x' + color.substring(3, 4)) / 15];
}
};
fb.HSLToRGB = function (hsl) {
var m1, m2, r, g, b;
var h = hsl[0], s = hsl[1], l = hsl[2];
m2 = (l <= 0.5) ? l * (s + 1) : l + s - l*s;
m1 = l * 2 - m2;
return [this.hueToRGB(m1, m2, h+0.33333),
this.hueToRGB(m1, m2, h),
this.hueToRGB(m1, m2, h-0.33333)];
};
fb.hueToRGB = function (m1, m2, h) {
h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h);
if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
if (h * 2 < 1) return m2;
if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6;
return m1;
};
fb.RGBToHSL = function (rgb) {
var min, max, delta, h, s, l;
var r = rgb[0], g = rgb[1], b = rgb[2];
min = Math.min(r, Math.min(g, b));
max = Math.max(r, Math.max(g, b));
delta = max - min;
l = (min + max) / 2;
s = 0;
if (l > 0 && l < 1) {
s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l));
}
h = 0;
if (delta > 0) {
if (max == r && max != g) h += (g - b) / delta;
if (max == g && max != b) h += (2 + (b - r) / delta);
if (max == b && max != r) h += (4 + (r - g) / delta);
h /= 6;
}
return [h, s, l];
};
// Install mousedown handler (the others are set on the document on-demand)
$('*', e).mousedown(fb.mousedown);
// Init color
fb.setColor('#000000');
// Set linked elements/callback
if (callback) {
fb.linkTo(callback);
}
};
})(jQuery); | JavaScript |
var farbtastic;
function pickColor(color) {
farbtastic.setColor(color);
jQuery('#background-color').val(color);
jQuery('#custom-background-image').css('background-color', color);
if ( color && color !== '#' )
jQuery('#clearcolor').show();
else
jQuery('#clearcolor').hide();
}
jQuery(document).ready(function() {
jQuery('#pickcolor').click(function() {
jQuery('#colorPickerDiv').show();
return false;
});
jQuery('#clearcolor a').click( function(e) {
pickColor('');
e.preventDefault();
});
jQuery('#background-color').keyup(function() {
var _hex = jQuery('#background-color').val(), hex = _hex;
if ( hex.charAt(0) != '#' )
hex = '#' + hex;
hex = hex.replace(/[^#a-fA-F0-9]+/, '');
if ( hex != _hex )
jQuery('#background-color').val(hex);
if ( hex.length == 4 || hex.length == 7 )
pickColor( hex );
});
jQuery('input[name="background-position-x"]').change(function() {
jQuery('#custom-background-image').css('background-position', jQuery(this).val() + ' top');
});
jQuery('input[name="background-repeat"]').change(function() {
jQuery('#custom-background-image').css('background-repeat', jQuery(this).val());
});
farbtastic = jQuery.farbtastic('#colorPickerDiv', function(color) {
pickColor(color);
});
pickColor(jQuery('#background-color').val());
jQuery(document).mousedown(function(){
jQuery('#colorPickerDiv').each(function(){
var display = jQuery(this).css('display');
if ( display == 'block' )
jQuery(this).fadeOut(2);
});
});
});
| JavaScript |
// send html to the post editor
var wpActiveEditor;
function send_to_editor(h) {
var ed, mce = typeof(tinymce) != 'undefined', qt = typeof(QTags) != 'undefined';
if ( !wpActiveEditor ) {
if ( mce && tinymce.activeEditor ) {
ed = tinymce.activeEditor;
wpActiveEditor = ed.id;
} else if ( !qt ) {
return false;
}
} else if ( mce ) {
if ( tinymce.activeEditor && (tinymce.activeEditor.id == 'mce_fullscreen' || tinymce.activeEditor.id == 'wp_mce_fullscreen') )
ed = tinymce.activeEditor;
else
ed = tinymce.get(wpActiveEditor);
}
if ( ed && !ed.isHidden() ) {
// restore caret position on IE
if ( tinymce.isIE && ed.windowManager.insertimagebookmark )
ed.selection.moveToBookmark(ed.windowManager.insertimagebookmark);
if ( h.indexOf('[caption') === 0 ) {
if ( ed.plugins.wpeditimage )
h = ed.plugins.wpeditimage._do_shcode(h);
} else if ( h.indexOf('[gallery') === 0 ) {
if ( ed.plugins.wpgallery )
h = ed.plugins.wpgallery._do_gallery(h);
} else if ( h.indexOf('[embed') === 0 ) {
if ( ed.plugins.wordpress )
h = ed.plugins.wordpress._setEmbed(h);
}
ed.execCommand('mceInsertContent', false, h);
} else if ( qt ) {
QTags.insertContent(h);
} else {
document.getElementById(wpActiveEditor).value += h;
}
try{tb_remove();}catch(e){};
}
// thickbox settings
var tb_position;
(function($) {
tb_position = function() {
var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 720 < width ) ? 720 : width, adminbar_height = 0;
if ( $('body.admin-bar').length )
adminbar_height = 28;
if ( tbWindow.size() ) {
tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
$('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
tbWindow.css({'margin-left': '-' + parseInt((( W - 50 ) / 2),10) + 'px'});
if ( typeof document.body.style.maxWidth != 'undefined' )
tbWindow.css({'top': 20 + adminbar_height + 'px','margin-top':'0'});
};
return $('a.thickbox').each( function() {
var href = $(this).attr('href');
if ( ! href ) return;
href = href.replace(/&width=[0-9]+/g, '');
href = href.replace(/&height=[0-9]+/g, '');
$(this).attr( 'href', href + '&width=' + ( W - 80 ) + '&height=' + ( H - 85 - adminbar_height ) );
});
};
$(window).resize(function(){ tb_position(); });
// store caret position in IE
$(document).ready(function($){
$('a.thickbox').click(function(){
var ed;
if ( typeof(tinymce) != 'undefined' && tinymce.isIE && ( ed = tinymce.get(wpActiveEditor) ) && !ed.isHidden() ) {
ed.focus();
ed.windowManager.insertimagebookmark = ed.selection.getBookmark();
}
});
});
})(jQuery);
| JavaScript |
var findPosts;
(function($){
findPosts = {
open : function(af_name, af_val) {
var st = document.documentElement.scrollTop || $(document).scrollTop();
if ( af_name && af_val ) {
$('#affected').attr('name', af_name).val(af_val);
}
$('#find-posts').show().draggable({
handle: '#find-posts-head'
}).css({'top':st + 50 + 'px','left':'50%','marginLeft':'-250px'});
$('#find-posts-input').focus().keyup(function(e){
if (e.which == 27) { findPosts.close(); } // close on Escape
});
return false;
},
close : function() {
$('#find-posts-response').html('');
$('#find-posts').draggable('destroy').hide();
},
send : function() {
var post = {
ps: $('#find-posts-input').val(),
action: 'find_posts',
_ajax_nonce: $('#_ajax_nonce').val()
};
var selectedItem;
$("input[@name='itemSelect[]']:checked").each(function() { selectedItem = $(this).val() });
post['post_type'] = selectedItem;
$.ajax({
type : 'POST',
url : ajaxurl,
data : post,
success : function(x) { findPosts.show(x); },
error : function(r) { findPosts.error(r); }
});
},
show : function(x) {
if ( typeof(x) == 'string' ) {
this.error({'responseText': x});
return;
}
var r = wpAjax.parseAjaxResponse(x);
if ( r.errors ) {
this.error({'responseText': wpAjax.broken});
}
r = r.responses[0];
$('#find-posts-response').html(r.data);
},
error : function(r) {
var er = r.statusText;
if ( r.responseText ) {
er = r.responseText.replace( /<.[^<>]*?>/g, '' );
}
if ( er ) {
$('#find-posts-response').html(er);
}
}
};
$(document).ready(function() {
$('#find-posts-submit').click(function(e) {
if ( '' == $('#find-posts-response').html() )
e.preventDefault();
});
$( '#find-posts .find-box-search :input' ).keypress( function( event ) {
if ( 13 == event.which ) {
findPosts.send();
return false;
}
} );
$( '#find-posts-search' ).click( findPosts.send );
$( '#find-posts-close' ).click( findPosts.close );
$('#doaction, #doaction2').click(function(e){
$('select[name^="action"]').each(function(){
if ( $(this).val() == 'attach' ) {
e.preventDefault();
findPosts.open();
}
});
});
});
})(jQuery);
| JavaScript |
/**
* PubSub
*
* A lightweight publish/subscribe implementation.
* Private use only!
*/
var PubSub, fullscreen, wptitlehint;
PubSub = function() {
this.topics = {};
};
PubSub.prototype.subscribe = function( topic, callback ) {
if ( ! this.topics[ topic ] )
this.topics[ topic ] = [];
this.topics[ topic ].push( callback );
return callback;
};
PubSub.prototype.unsubscribe = function( topic, callback ) {
var i, l,
topics = this.topics[ topic ];
if ( ! topics )
return callback || [];
// Clear matching callbacks
if ( callback ) {
for ( i = 0, l = topics.length; i < l; i++ ) {
if ( callback == topics[i] )
topics.splice( i, 1 );
}
return callback;
// Clear all callbacks
} else {
this.topics[ topic ] = [];
return topics;
}
};
PubSub.prototype.publish = function( topic, args ) {
var i, l, broken,
topics = this.topics[ topic ];
if ( ! topics )
return;
args = args || [];
for ( i = 0, l = topics.length; i < l; i++ ) {
broken = ( topics[i].apply( null, args ) === false || broken );
}
return ! broken;
};
/**
* Distraction Free Writing
* (wp-fullscreen)
*
* Access the API globally using the fullscreen variable.
*/
(function($){
var api, ps, bounder, s;
// Initialize the fullscreen/api object
fullscreen = api = {};
// Create the PubSub (publish/subscribe) interface.
ps = api.pubsub = new PubSub();
timer = 0;
block = false;
s = api.settings = { // Settings
visible : false,
mode : 'tinymce',
editor_id : 'content',
title_id : '',
timer : 0,
toolbar_shown : false
}
/**
* Bounder
*
* Creates a function that publishes start/stop topics.
* Used to throttle events.
*/
bounder = api.bounder = function( start, stop, delay, e ) {
var y, top;
delay = delay || 1250;
if ( e ) {
y = e.pageY || e.clientY || e.offsetY;
top = $(document).scrollTop();
if ( !e.isDefaultPrevented ) // test if e ic jQuery normalized
y = 135 + y;
if ( y - top > 120 )
return;
}
if ( block )
return;
block = true;
setTimeout( function() {
block = false;
}, 400 );
if ( s.timer )
clearTimeout( s.timer );
else
ps.publish( start );
function timed() {
ps.publish( stop );
s.timer = 0;
}
s.timer = setTimeout( timed, delay );
};
/**
* on()
*
* Turns fullscreen on.
*
* @param string mode Optional. Switch to the given mode before opening.
*/
api.on = function() {
if ( s.visible )
return;
// Settings can be added or changed by defining "wp_fullscreen_settings" JS object.
// This can be done by defining it as PHP associative array, json encoding it and passing it to JS with:
// wp_add_script_before( 'wp-fullscreen', 'wp_fullscreen_settings = ' . $json_encoded_array . ';' );
if ( typeof(wp_fullscreen_settings) == 'object' )
$.extend( s, wp_fullscreen_settings );
s.editor_id = wpActiveEditor || 'content';
if ( !s.title_id ) {
if ( $('input#title').length && s.editor_id == 'content' )
s.title_id = 'title';
else if ( $('input#' + s.editor_id + '-title').length ) // the title input field should have [editor_id]-title HTML ID to be auto detected
s.title_id = s.editor_id + '-title';
else
$('#wp-fullscreen-title, #wp-fullscreen-title-prompt-text').hide();
}
s.mode = $('#' + s.editor_id).is(':hidden') ? 'tinymce' : 'html';
s.qt_canvas = $('#' + s.editor_id).get(0);
if ( ! s.element )
api.ui.init();
s.is_mce_on = s.has_tinymce && typeof( tinyMCE.get(s.editor_id) ) != 'undefined';
api.ui.fade( 'show', 'showing', 'shown' );
};
/**
* off()
*
* Turns fullscreen off.
*/
api.off = function() {
if ( ! s.visible )
return;
api.ui.fade( 'hide', 'hiding', 'hidden' );
};
/**
* switchmode()
*
* @return string - The current mode.
*
* @param string to - The fullscreen mode to switch to.
* @event switchMode
* @eventparam string to - The new mode.
* @eventparam string from - The old mode.
*/
api.switchmode = function( to ) {
var from = s.mode;
if ( ! to || ! s.visible || ! s.has_tinymce )
return from;
// Don't switch if the mode is the same.
if ( from == to )
return from;
ps.publish( 'switchMode', [ from, to ] );
s.mode = to;
ps.publish( 'switchedMode', [ from, to ] );
return to;
};
/**
* General
*/
api.save = function() {
var hidden = $('#hiddenaction'), old = hidden.val(), spinner = $('#wp-fullscreen-save img'),
message = $('#wp-fullscreen-save span');
spinner.show();
api.savecontent();
hidden.val('wp-fullscreen-save-post');
$.post( ajaxurl, $('form#post').serialize(), function(r){
spinner.hide();
message.show();
setTimeout( function(){
message.fadeOut(1000);
}, 3000 );
if ( r.last_edited )
$('#wp-fullscreen-save input').attr( 'title', r.last_edited );
}, 'json');
hidden.val(old);
}
api.savecontent = function() {
var ed, content;
if ( s.title_id )
$('#' + s.title_id).val( $('#wp-fullscreen-title').val() );
if ( s.mode === 'tinymce' && (ed = tinyMCE.get('wp_mce_fullscreen')) ) {
content = ed.save();
} else {
content = $('#wp_mce_fullscreen').val();
}
$('#' + s.editor_id).val( content );
$(document).triggerHandler('wpcountwords', [ content ]);
}
set_title_hint = function( title ) {
if ( ! title.val().length )
title.siblings('label').css( 'visibility', '' );
else
title.siblings('label').css( 'visibility', 'hidden' );
}
api.dfw_width = function(n) {
var el = $('#wp-fullscreen-wrap'), w = el.width();
if ( !n ) { // reset to theme width
el.width( $('#wp-fullscreen-central-toolbar').width() );
deleteUserSetting('dfw_width');
return;
}
w = n + w;
if ( w < 200 || w > 1200 ) // sanity check
return;
el.width( w );
setUserSetting('dfw_width', w);
}
ps.subscribe( 'showToolbar', function() {
s.toolbars.removeClass('fade-1000').addClass('fade-300');
api.fade.In( s.toolbars, 300, function(){ ps.publish('toolbarShown'); }, true );
$('#wp-fullscreen-body').addClass('wp-fullscreen-focus');
s.toolbar_shown = true;
});
ps.subscribe( 'hideToolbar', function() {
s.toolbars.removeClass('fade-300').addClass('fade-1000');
api.fade.Out( s.toolbars, 1000, function(){ ps.publish('toolbarHidden'); }, true );
$('#wp-fullscreen-body').removeClass('wp-fullscreen-focus');
});
ps.subscribe( 'toolbarShown', function() {
s.toolbars.removeClass('fade-300');
});
ps.subscribe( 'toolbarHidden', function() {
s.toolbars.removeClass('fade-1000');
s.toolbar_shown = false;
});
ps.subscribe( 'show', function() { // This event occurs before the overlay blocks the UI.
var title;
if ( s.title_id ) {
title = $('#wp-fullscreen-title').val( $('#' + s.title_id).val() );
set_title_hint( title );
}
$('#wp-fullscreen-save input').attr( 'title', $('#last-edit').text() );
s.textarea_obj.value = s.qt_canvas.value;
if ( s.has_tinymce && s.mode === 'tinymce' )
tinyMCE.execCommand('wpFullScreenInit');
s.orig_y = $(window).scrollTop();
});
ps.subscribe( 'showing', function() { // This event occurs while the DFW overlay blocks the UI.
$( document.body ).addClass( 'fullscreen-active' );
api.refresh_buttons();
$( document ).bind( 'mousemove.fullscreen', function(e) { bounder( 'showToolbar', 'hideToolbar', 2000, e ); } );
bounder( 'showToolbar', 'hideToolbar', 2000 );
api.bind_resize();
setTimeout( api.resize_textarea, 200 );
// scroll to top so the user is not disoriented
scrollTo(0, 0);
// needed it for IE7 and compat mode
$('#wpadminbar').hide();
});
ps.subscribe( 'shown', function() { // This event occurs after the DFW overlay is shown
var interim_init;
s.visible = true;
// init the standard TinyMCE instance if missing
if ( s.has_tinymce && ! s.is_mce_on ) {
interim_init = function(mce, ed) {
var el = ed.getElement(), old_val = el.value, settings = tinyMCEPreInit.mceInit[s.editor_id];
if ( settings && settings.wpautop && typeof(switchEditors) != 'undefined' )
el.value = switchEditors.wpautop( el.value );
ed.onInit.add(function(ed) {
ed.hide();
ed.getElement().value = old_val;
tinymce.onAddEditor.remove(interim_init);
});
};
tinymce.onAddEditor.add(interim_init);
tinyMCE.init(tinyMCEPreInit.mceInit[s.editor_id]);
s.is_mce_on = true;
}
wpActiveEditor = 'wp_mce_fullscreen';
});
ps.subscribe( 'hide', function() { // This event occurs before the overlay blocks DFW.
var htmled_is_hidden = $('#' + s.editor_id).is(':hidden');
// Make sure the correct editor is displaying.
if ( s.has_tinymce && s.mode === 'tinymce' && !htmled_is_hidden ) {
switchEditors.go(s.editor_id, 'tmce');
} else if ( s.mode === 'html' && htmled_is_hidden ) {
switchEditors.go(s.editor_id, 'html');
}
// Save content must be after switchEditors or content will be overwritten. See #17229.
api.savecontent();
$( document ).unbind( '.fullscreen' );
$(s.textarea_obj).unbind('.grow');
if ( s.has_tinymce && s.mode === 'tinymce' )
tinyMCE.execCommand('wpFullScreenSave');
if ( s.title_id )
set_title_hint( $('#' + s.title_id) );
s.qt_canvas.value = s.textarea_obj.value;
});
ps.subscribe( 'hiding', function() { // This event occurs while the overlay blocks the DFW UI.
$( document.body ).removeClass( 'fullscreen-active' );
scrollTo(0, s.orig_y);
$('#wpadminbar').show();
});
ps.subscribe( 'hidden', function() { // This event occurs after DFW is removed.
s.visible = false;
$('#wp_mce_fullscreen, #wp-fullscreen-title').removeAttr('style');
if ( s.has_tinymce && s.is_mce_on )
tinyMCE.execCommand('wpFullScreenClose');
s.textarea_obj.value = '';
api.oldheight = 0;
wpActiveEditor = s.editor_id;
});
ps.subscribe( 'switchMode', function( from, to ) {
var ed;
if ( !s.has_tinymce || !s.is_mce_on )
return;
ed = tinyMCE.get('wp_mce_fullscreen');
if ( from === 'html' && to === 'tinymce' ) {
if ( tinyMCE.get(s.editor_id).getParam('wpautop') && typeof(switchEditors) != 'undefined' )
s.textarea_obj.value = switchEditors.wpautop( s.textarea_obj.value );
if ( 'undefined' == typeof(ed) )
tinyMCE.execCommand('wpFullScreenInit');
else
ed.show();
} else if ( from === 'tinymce' && to === 'html' ) {
if ( ed )
ed.hide();
}
});
ps.subscribe( 'switchedMode', function( from, to ) {
api.refresh_buttons(true);
if ( to === 'html' )
setTimeout( api.resize_textarea, 200 );
});
/**
* Buttons
*/
api.b = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('Bold');
}
api.i = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('Italic');
}
api.ul = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('InsertUnorderedList');
}
api.ol = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('InsertOrderedList');
}
api.link = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('WP_Link');
else
wpLink.open();
}
api.unlink = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('unlink');
}
api.atd = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('mceWritingImprovementTool');
}
api.help = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('WP_Help');
}
api.blockquote = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('mceBlockQuote');
}
api.medialib = function() {
if ( s.has_tinymce && 'tinymce' === s.mode ) {
tinyMCE.execCommand('WP_Medialib');
} else {
var href = $('#wp-' + s.editor_id + '-media-buttons a.thickbox').attr('href') || '';
if ( href )
tb_show('', href);
}
}
api.refresh_buttons = function( fade ) {
fade = fade || false;
if ( s.mode === 'html' ) {
$('#wp-fullscreen-mode-bar').removeClass('wp-tmce-mode').addClass('wp-html-mode');
if ( fade )
$('#wp-fullscreen-button-bar').fadeOut( 150, function(){
$(this).addClass('wp-html-mode').fadeIn( 150 );
});
else
$('#wp-fullscreen-button-bar').addClass('wp-html-mode');
} else if ( s.mode === 'tinymce' ) {
$('#wp-fullscreen-mode-bar').removeClass('wp-html-mode').addClass('wp-tmce-mode');
if ( fade )
$('#wp-fullscreen-button-bar').fadeOut( 150, function(){
$(this).removeClass('wp-html-mode').fadeIn( 150 );
});
else
$('#wp-fullscreen-button-bar').removeClass('wp-html-mode');
}
}
/**
* UI Elements
*
* Used for transitioning between states.
*/
api.ui = {
init: function() {
var topbar = $('#fullscreen-topbar'), txtarea = $('#wp_mce_fullscreen'), last = 0;
s.toolbars = topbar.add( $('#wp-fullscreen-status') );
s.element = $('#fullscreen-fader');
s.textarea_obj = txtarea[0];
s.has_tinymce = typeof(tinymce) != 'undefined';
if ( !s.has_tinymce )
$('#wp-fullscreen-mode-bar').hide();
if ( wptitlehint && $('#wp-fullscreen-title').length )
wptitlehint('wp-fullscreen-title');
$(document).keyup(function(e){
var c = e.keyCode || e.charCode, a, data;
if ( !fullscreen.settings.visible )
return true;
if ( navigator.platform && navigator.platform.indexOf('Mac') != -1 )
a = e.ctrlKey; // Ctrl key for Mac
else
a = e.altKey; // Alt key for Win & Linux
if ( 27 == c ) { // Esc
data = {
event: e,
what: 'dfw',
cb: fullscreen.off,
condition: function(){
if ( $('#TB_window').is(':visible') || $('.wp-dialog').is(':visible') )
return false;
return true;
}
};
if ( ! jQuery(document).triggerHandler( 'wp_CloseOnEscape', [data] ) )
fullscreen.off();
}
if ( a && (61 == c || 107 == c || 187 == c) ) // +
api.dfw_width(25);
if ( a && (45 == c || 109 == c || 189 == c) ) // -
api.dfw_width(-25);
if ( a && 48 == c ) // 0
api.dfw_width(0);
return false;
});
// word count in HTML mode
if ( typeof(wpWordCount) != 'undefined' ) {
txtarea.keyup( function(e) {
var k = e.keyCode || e.charCode;
if ( k == last )
return true;
if ( 13 == k || 8 == last || 46 == last )
$(document).triggerHandler('wpcountwords', [ txtarea.val() ]);
last = k;
return true;
});
}
topbar.mouseenter(function(e){
s.toolbars.addClass('fullscreen-make-sticky');
$( document ).unbind( '.fullscreen' );
clearTimeout( s.timer );
s.timer = 0;
}).mouseleave(function(e){
s.toolbars.removeClass('fullscreen-make-sticky');
if ( s.visible )
$( document ).bind( 'mousemove.fullscreen', function(e) { bounder( 'showToolbar', 'hideToolbar', 2000, e ); } );
});
},
fade: function( before, during, after ) {
if ( ! s.element )
api.ui.init();
// If any callback bound to before returns false, bail.
if ( before && ! ps.publish( before ) )
return;
api.fade.In( s.element, 600, function() {
if ( during )
ps.publish( during );
api.fade.Out( s.element, 600, function() {
if ( after )
ps.publish( after );
})
});
}
};
api.fade = {
transitionend: 'transitionend webkitTransitionEnd oTransitionEnd',
// Sensitivity to allow browsers to render the blank element before animating.
sensitivity: 100,
In: function( element, speed, callback, stop ) {
callback = callback || $.noop;
speed = speed || 400;
stop = stop || false;
if ( api.fade.transitions ) {
if ( element.is(':visible') ) {
element.addClass( 'fade-trigger' );
return element;
}
element.show();
element.first().one( this.transitionend, function() {
callback();
});
setTimeout( function() { element.addClass( 'fade-trigger' ); }, this.sensitivity );
} else {
if ( stop )
element.stop();
element.css( 'opacity', 1 );
element.first().fadeIn( speed, callback );
if ( element.length > 1 )
element.not(':first').fadeIn( speed );
}
return element;
},
Out: function( element, speed, callback, stop ) {
callback = callback || $.noop;
speed = speed || 400;
stop = stop || false;
if ( ! element.is(':visible') )
return element;
if ( api.fade.transitions ) {
element.first().one( api.fade.transitionend, function() {
if ( element.hasClass('fade-trigger') )
return;
element.hide();
callback();
});
setTimeout( function() { element.removeClass( 'fade-trigger' ); }, this.sensitivity );
} else {
if ( stop )
element.stop();
element.first().fadeOut( speed, callback );
if ( element.length > 1 )
element.not(':first').fadeOut( speed );
}
return element;
},
transitions: (function() { // Check if the browser supports CSS 3.0 transitions
var s = document.documentElement.style;
return ( typeof ( s.WebkitTransition ) == 'string' ||
typeof ( s.MozTransition ) == 'string' ||
typeof ( s.OTransition ) == 'string' ||
typeof ( s.transition ) == 'string' );
})()
};
/**
* Resize API
*
* Automatically updates textarea height.
*/
api.bind_resize = function() {
$(s.textarea_obj).bind('keypress.grow click.grow paste.grow', function(){
setTimeout( api.resize_textarea, 200 );
});
}
api.oldheight = 0;
api.resize_textarea = function() {
var txt = s.textarea_obj, newheight;
newheight = txt.scrollHeight > 300 ? txt.scrollHeight : 300;
if ( newheight != api.oldheight ) {
txt.style.height = newheight + 'px';
api.oldheight = newheight;
}
};
})(jQuery);
| JavaScript |
(function($) {
wpWordCount = {
settings : {
strip : /<[a-zA-Z\/][^<>]*>/g, // strip HTML tags
clean : /[0-9.(),;:!?%#$¿'"_+=\\/-]+/g, // regexp to remove punctuation, etc.
count : /\S\s+/g // counting regexp
},
block : 0,
wc : function(tx) {
var t = this, w = $('.word-count'), tc = 0;
if ( t.block )
return;
t.block = 1;
setTimeout( function() {
if ( tx ) {
tx = tx.replace( t.settings.strip, ' ' ).replace( / | /gi, ' ' );
tx = tx.replace( t.settings.clean, '' );
tx.replace( t.settings.count, function(){tc++;} );
}
w.html(tc.toString());
setTimeout( function() { t.block = 0; }, 2000 );
}, 1 );
}
}
$(document).bind( 'wpcountwords', function(e, txt) {
wpWordCount.wc(txt);
});
}(jQuery));
| JavaScript |
// utility functions
var wpCookies = {
// The following functions are from Cookie.js class in TinyMCE, Moxiecode, used under LGPL.
each : function(o, cb, s) {
var n, l;
if (!o)
return 0;
s = s || o;
if (typeof(o.length) != 'undefined') {
for (n=0, l = o.length; n<l; n++) {
if (cb.call(s, o[n], n, o) === false)
return 0;
}
} else {
for (n in o) {
if (o.hasOwnProperty(n)) {
if (cb.call(s, o[n], n, o) === false) {
return 0;
}
}
}
}
return 1;
},
getHash : function(n) {
var v = this.get(n), h;
if (v) {
this.each(v.split('&'), function(v) {
v = v.split('=');
h = h || {};
h[v[0]] = v[1];
});
}
return h;
},
setHash : function(n, v, e, p, d, s) {
var o = '';
this.each(v, function(v, k) {
o += (!o ? '' : '&') + k + '=' + v;
});
this.set(n, o, e, p, d, s);
},
get : function(n) {
var c = document.cookie, e, p = n + "=", b;
if (!c)
return;
b = c.indexOf("; " + p);
if (b == -1) {
b = c.indexOf(p);
if (b != 0)
return null;
} else {
b += 2;
}
e = c.indexOf(";", b);
if (e == -1)
e = c.length;
return decodeURIComponent(c.substring(b + p.length, e));
},
set : function(n, v, e, p, d, s) {
document.cookie = n + "=" + encodeURIComponent(v) +
((e) ? "; expires=" + e.toGMTString() : "") +
((p) ? "; path=" + p : "") +
((d) ? "; domain=" + d : "") +
((s) ? "; secure" : "");
},
remove : function(n, p) {
var d = new Date();
d.setTime(d.getTime() - 1000);
this.set(n, '', d, p, d);
}
};
// Returns the value as string. Second arg or empty string is returned when value is not set.
function getUserSetting( name, def ) {
var o = getAllUserSettings();
if ( o.hasOwnProperty(name) )
return o[name];
if ( typeof def != 'undefined' )
return def;
return '';
}
// Both name and value must be only ASCII letters, numbers or underscore
// and the shorter, the better (cookies can store maximum 4KB). Not suitable to store text.
function setUserSetting( name, value, del ) {
if ( 'object' !== typeof userSettings )
return false;
var c = 'wp-settings-' + userSettings.uid, o = wpCookies.getHash(c) || {}, d = new Date(), p,
n = name.toString().replace(/[^A-Za-z0-9_]/, ''), v = value.toString().replace(/[^A-Za-z0-9_]/, '');
if ( del ) {
delete o[n];
} else {
o[n] = v;
}
d.setTime( d.getTime() + 31536000000 );
p = userSettings.url;
wpCookies.setHash(c, o, d, p);
wpCookies.set('wp-settings-time-'+userSettings.uid, userSettings.time, d, p);
return name;
}
function deleteUserSetting( name ) {
return setUserSetting( name, '', 1 );
}
// Returns all settings as js object.
function getAllUserSettings() {
if ( 'object' !== typeof userSettings )
return {};
return wpCookies.getHash('wp-settings-' + userSettings.uid) || {};
}
| JavaScript |
var postboxes, is_iPad = navigator.userAgent.match(/iPad/);
(function($) {
postboxes = {
add_postbox_toggles : function(page, args) {
this.init(page, args);
$('.postbox h3, .postbox .handlediv').bind('click.postboxes', function() {
var p = $(this).parent('.postbox'), id = p.attr('id');
if ( 'dashboard_browser_nag' == id )
return;
p.toggleClass('closed');
postboxes.save_state(page);
if ( id ) {
if ( !p.hasClass('closed') && $.isFunction(postboxes.pbshow) )
postboxes.pbshow(id);
else if ( p.hasClass('closed') && $.isFunction(postboxes.pbhide) )
postboxes.pbhide(id);
}
});
$('.postbox h3 a').click( function(e) {
e.stopPropagation();
});
$('.postbox a.dismiss').bind('click.postboxes', function(e) {
var hide_id = $(this).parents('.postbox').attr('id') + '-hide';
$( '#' + hide_id ).prop('checked', false).triggerHandler('click');
return false;
});
$('.hide-postbox-tog').bind('click.postboxes', function() {
var box = $(this).val();
if ( $(this).prop('checked') ) {
$('#' + box).show();
if ( $.isFunction( postboxes.pbshow ) )
postboxes.pbshow( box );
} else {
$('#' + box).hide();
if ( $.isFunction( postboxes.pbhide ) )
postboxes.pbhide( box );
}
postboxes.save_state(page);
postboxes._mark_area();
});
$('.columns-prefs input[type="radio"]').bind('click.postboxes', function(){
var n = parseInt($(this).val(), 10), pb = postboxes;
if ( n ) {
pb._pb_edit(n);
pb.save_order(page);
}
});
},
init : function(page, args) {
$.extend( this, args || {} );
$('#wpbody-content').css('overflow','hidden');
$('.meta-box-sortables').sortable({
placeholder: 'sortable-placeholder',
connectWith: '.meta-box-sortables',
items: '.postbox',
handle: '.hndle',
cursor: 'move',
distance: 2,
tolerance: 'pointer',
forcePlaceholderSize: true,
helper: 'clone',
opacity: 0.65,
stop: function(e,ui) {
if ( $(this).find('#dashboard_browser_nag').is(':visible') && 'dashboard_browser_nag' != this.firstChild.id ) {
$(this).sortable('cancel');
return;
}
postboxes.save_order(page);
},
receive: function(e,ui) {
if ( 'dashboard_browser_nag' == ui.item[0].id )
$(ui.sender).sortable('cancel');
postboxes._mark_area();
}
});
if ( navigator.userAgent.match(/iPad/) ) {
$(document.body).bind('orientationchange', function(){ postboxes._pb_change(); });
this._pb_change();
}
this._mark_area();
},
save_state : function(page) {
var closed = $('.postbox').filter('.closed').map(function() { return this.id; }).get().join(','),
hidden = $('.postbox').filter(':hidden').map(function() { return this.id; }).get().join(',');
$.post(ajaxurl, {
action: 'closed-postboxes',
closed: closed,
hidden: hidden,
closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(),
page: page
});
},
save_order : function(page) {
var postVars, page_columns = $('.columns-prefs input:checked').val() || 0;
postVars = {
action: 'meta-box-order',
_ajax_nonce: $('#meta-box-order-nonce').val(),
page_columns: page_columns,
page: page
}
$('.meta-box-sortables').each( function() {
postVars["order[" + this.id.split('-')[0] + "]"] = $(this).sortable( 'toArray' ).join(',');
} );
$.post( ajaxurl, postVars );
},
_colname : function(n) {
switch (n) {
case 1:
return 'normal';
break
case 2:
return 'side';
break
case 3:
return 'column3';
break
case 4:
return 'column4';
break
default:
return '';
}
},
_mark_area : function() {
$('#side-info-column .meta-box-sortables:visible, #dashboard-widgets .meta-box-sortables:visible').each(function(n, el){
var t = $(this);
if ( !t.children('.postbox:visible').length )
t.addClass('empty-container');
else
t.removeClass('empty-container');
});
},
_pb_edit : function(n) {
var ps = $('#poststuff'), i, el, done, pb = postboxes, visible = $('.postbox-container:visible').length;
if ( n == visible )
return;
if ( ps.length ) {
if ( n == 2 ) {
$('.wrap').removeClass('columns-1').addClass('columns-2');
ps.addClass('has-right-sidebar');
if ( !$('#side-info-column #side-sortables').length )
$('#side-info-column').append( $('#side-sortables') );
} else if ( n == 1 ) {
$('.wrap').removeClass('columns-2').addClass('columns-1');
ps.removeClass('has-right-sidebar');
if ( !$('#post-body-content #side-sortables').length )
$('#normal-sortables').before( $('#side-sortables') );
}
} else {
for ( i = 4; ( i > n && i > 1 ); i-- ) {
el = $('#' + postboxes._colname(i) + '-sortables');
$('#' + postboxes._colname(i-1) + '-sortables').append(el.children('.postbox'));
el.parent().hide();
}
for ( i = n; i > 0; i-- ) {
el = $('#' + postboxes._colname(i) + '-sortables');
done = false;
if ( el.parent().is(':hidden') ) {
switch ( i ) {
case 4:
done = pb._move_one( el, $('.postbox:visible', $('#column3-sortables')) );
case 3:
if ( !done )
done = pb._move_one( el, $('.postbox:visible', $('#side-sortables')) );
case 2:
if ( !done )
done = pb._move_one( el, $('.postbox:visible', $('#normal-sortables')) );
default:
if ( !done )
el.addClass('empty-container')
}
el.parent().show();
}
}
$('.postbox-container:visible').css('width', 100/n + '%');
}
},
_pb_change : function() {
switch ( window.orientation ) {
case 90:
case -90:
this._pb_edit(2);
break;
case 0:
case 180:
if ( $('#poststuff').length )
this._pb_edit(1);
else
this._pb_edit(2);
break;
}
},
_move_one : function(el, move) {
if ( move.length > 1 ) {
el.append( move.last() );
return true;
}
return false;
},
/* Callbacks */
pbshow : false,
pbhide : false
};
}(jQuery));
| JavaScript |
/**
* WordPress Administration Navigation Menu
* Interface JS functions
*
* @version 2.0.0
*
* @package WordPress
* @subpackage Administration
*/
var wpNavMenu;
(function($) {
var api = wpNavMenu = {
options : {
menuItemDepthPerLevel : 30, // Do not use directly. Use depthToPx and pxToDepth instead.
globalMaxDepth : 11
},
menuList : undefined, // Set in init.
targetList : undefined, // Set in init.
menusChanged : false,
isRTL: !! ( 'undefined' != typeof isRtl && isRtl ),
negateIfRTL: ( 'undefined' != typeof isRtl && isRtl ) ? -1 : 1,
// Functions that run on init.
init : function() {
api.menuList = $('#menu-to-edit');
api.targetList = api.menuList;
this.jQueryExtensions();
this.attachMenuEditListeners();
this.setupInputWithDefaultTitle();
this.attachQuickSearchListeners();
this.attachThemeLocationsListeners();
this.attachTabsPanelListeners();
this.attachUnsavedChangesListener();
if( api.menuList.length ) // If no menu, we're in the + tab.
this.initSortables();
this.initToggles();
this.initTabManager();
},
jQueryExtensions : function() {
// jQuery extensions
$.fn.extend({
menuItemDepth : function() {
var margin = api.isRTL ? this.eq(0).css('margin-right') : this.eq(0).css('margin-left');
return api.pxToDepth( margin && -1 != margin.indexOf('px') ? margin.slice(0, -2) : 0 );
},
updateDepthClass : function(current, prev) {
return this.each(function(){
var t = $(this);
prev = prev || t.menuItemDepth();
$(this).removeClass('menu-item-depth-'+ prev )
.addClass('menu-item-depth-'+ current );
});
},
shiftDepthClass : function(change) {
return this.each(function(){
var t = $(this),
depth = t.menuItemDepth();
$(this).removeClass('menu-item-depth-'+ depth )
.addClass('menu-item-depth-'+ (depth + change) );
});
},
childMenuItems : function() {
var result = $();
this.each(function(){
var t = $(this), depth = t.menuItemDepth(), next = t.next();
while( next.length && next.menuItemDepth() > depth ) {
result = result.add( next );
next = next.next();
}
});
return result;
},
updateParentMenuItemDBId : function() {
return this.each(function(){
var item = $(this),
input = item.find('.menu-item-data-parent-id'),
depth = item.menuItemDepth(),
parent = item.prev();
if( depth == 0 ) { // Item is on the top level, has no parent
input.val(0);
} else { // Find the parent item, and retrieve its object id.
while( ! parent[0] || ! parent[0].className || -1 == parent[0].className.indexOf('menu-item') || ( parent.menuItemDepth() != depth - 1 ) )
parent = parent.prev();
input.val( parent.find('.menu-item-data-db-id').val() );
}
});
},
hideAdvancedMenuItemFields : function() {
return this.each(function(){
var that = $(this);
$('.hide-column-tog').not(':checked').each(function(){
that.find('.field-' + $(this).val() ).addClass('hidden-field');
});
});
},
/**
* Adds selected menu items to the menu.
*
* @param jQuery metabox The metabox jQuery object.
*/
addSelectedToMenu : function(processMethod) {
if ( 0 == $('#menu-to-edit').length ) {
return false;
}
return this.each(function() {
var t = $(this), menuItems = {},
checkboxes = t.find('.tabs-panel-active .categorychecklist li input:checked'),
re = new RegExp('menu-item\\[(\[^\\]\]*)');
processMethod = processMethod || api.addMenuItemToBottom;
// If no items are checked, bail.
if ( !checkboxes.length )
return false;
// Show the ajax spinner
t.find('img.waiting').show();
// Retrieve menu item data
$(checkboxes).each(function(){
var t = $(this),
listItemDBIDMatch = re.exec( t.attr('name') ),
listItemDBID = 'undefined' == typeof listItemDBIDMatch[1] ? 0 : parseInt(listItemDBIDMatch[1], 10);
if ( this.className && -1 != this.className.indexOf('add-to-top') )
processMethod = api.addMenuItemToTop;
menuItems[listItemDBID] = t.closest('li').getItemData( 'add-menu-item', listItemDBID );
});
// Add the items
api.addItemToMenu(menuItems, processMethod, function(){
// Deselect the items and hide the ajax spinner
checkboxes.removeAttr('checked');
t.find('img.waiting').hide();
});
});
},
getItemData : function( itemType, id ) {
itemType = itemType || 'menu-item';
var itemData = {}, i,
fields = [
'menu-item-db-id',
'menu-item-object-id',
'menu-item-object',
'menu-item-parent-id',
'menu-item-position',
'menu-item-type',
'menu-item-title',
'menu-item-url',
'menu-item-description',
'menu-item-attr-title',
'menu-item-target',
'menu-item-classes',
'menu-item-xfn'
];
if( !id && itemType == 'menu-item' ) {
id = this.find('.menu-item-data-db-id').val();
}
if( !id ) return itemData;
this.find('input').each(function() {
var field;
i = fields.length;
while ( i-- ) {
if( itemType == 'menu-item' )
field = fields[i] + '[' + id + ']';
else if( itemType == 'add-menu-item' )
field = 'menu-item[' + id + '][' + fields[i] + ']';
if (
this.name &&
field == this.name
) {
itemData[fields[i]] = this.value;
}
}
});
return itemData;
},
setItemData : function( itemData, itemType, id ) { // Can take a type, such as 'menu-item', or an id.
itemType = itemType || 'menu-item';
if( !id && itemType == 'menu-item' ) {
id = $('.menu-item-data-db-id', this).val();
}
if( !id ) return this;
this.find('input').each(function() {
var t = $(this), field;
$.each( itemData, function( attr, val ) {
if( itemType == 'menu-item' )
field = attr + '[' + id + ']';
else if( itemType == 'add-menu-item' )
field = 'menu-item[' + id + '][' + attr + ']';
if ( field == t.attr('name') ) {
t.val( val );
}
});
});
return this;
}
});
},
initToggles : function() {
// init postboxes
postboxes.add_postbox_toggles('nav-menus');
// adjust columns functions for menus UI
columns.useCheckboxesForHidden();
columns.checked = function(field) {
$('.field-' + field).removeClass('hidden-field');
}
columns.unchecked = function(field) {
$('.field-' + field).addClass('hidden-field');
}
// hide fields
api.menuList.hideAdvancedMenuItemFields();
},
initSortables : function() {
var currentDepth = 0, originalDepth, minDepth, maxDepth,
prev, next, prevBottom, nextThreshold, helperHeight, transport,
menuEdge = api.menuList.offset().left,
body = $('body'), maxChildDepth,
menuMaxDepth = initialMenuMaxDepth();
// Use the right edge if RTL.
menuEdge += api.isRTL ? api.menuList.width() : 0;
api.menuList.sortable({
handle: '.menu-item-handle',
placeholder: 'sortable-placeholder',
start: function(e, ui) {
var height, width, parent, children, tempHolder;
// handle placement for rtl orientation
if ( api.isRTL )
ui.item[0].style.right = 'auto';
transport = ui.item.children('.menu-item-transport');
// Set depths. currentDepth must be set before children are located.
originalDepth = ui.item.menuItemDepth();
updateCurrentDepth(ui, originalDepth);
// Attach child elements to parent
// Skip the placeholder
parent = ( ui.item.next()[0] == ui.placeholder[0] ) ? ui.item.next() : ui.item;
children = parent.childMenuItems();
transport.append( children );
// Update the height of the placeholder to match the moving item.
height = transport.outerHeight();
// If there are children, account for distance between top of children and parent
height += ( height > 0 ) ? (ui.placeholder.css('margin-top').slice(0, -2) * 1) : 0;
height += ui.helper.outerHeight();
helperHeight = height;
height -= 2; // Subtract 2 for borders
ui.placeholder.height(height);
// Update the width of the placeholder to match the moving item.
maxChildDepth = originalDepth;
children.each(function(){
var depth = $(this).menuItemDepth();
maxChildDepth = (depth > maxChildDepth) ? depth : maxChildDepth;
});
width = ui.helper.find('.menu-item-handle').outerWidth(); // Get original width
width += api.depthToPx(maxChildDepth - originalDepth); // Account for children
width -= 2; // Subtract 2 for borders
ui.placeholder.width(width);
// Update the list of menu items.
tempHolder = ui.placeholder.next();
tempHolder.css( 'margin-top', helperHeight + 'px' ); // Set the margin to absorb the placeholder
ui.placeholder.detach(); // detach or jQuery UI will think the placeholder is a menu item
$(this).sortable( "refresh" ); // The children aren't sortable. We should let jQ UI know.
ui.item.after( ui.placeholder ); // reattach the placeholder.
tempHolder.css('margin-top', 0); // reset the margin
// Now that the element is complete, we can update...
updateSharedVars(ui);
},
stop: function(e, ui) {
var children, depthChange = currentDepth - originalDepth;
// Return child elements to the list
children = transport.children().insertAfter(ui.item);
// Update depth classes
if( depthChange != 0 ) {
ui.item.updateDepthClass( currentDepth );
children.shiftDepthClass( depthChange );
updateMenuMaxDepth( depthChange );
}
// Register a change
api.registerChange();
// Update the item data.
ui.item.updateParentMenuItemDBId();
// address sortable's incorrectly-calculated top in opera
ui.item[0].style.top = 0;
// handle drop placement for rtl orientation
if ( api.isRTL ) {
ui.item[0].style.left = 'auto';
ui.item[0].style.right = 0;
}
// The width of the tab bar might have changed. Just in case.
api.refreshMenuTabs( true );
},
change: function(e, ui) {
// Make sure the placeholder is inside the menu.
// Otherwise fix it, or we're in trouble.
if( ! ui.placeholder.parent().hasClass('menu') )
(prev.length) ? prev.after( ui.placeholder ) : api.menuList.prepend( ui.placeholder );
updateSharedVars(ui);
},
sort: function(e, ui) {
var offset = ui.helper.offset(),
edge = api.isRTL ? offset.left + ui.helper.width() : offset.left,
depth = api.negateIfRTL * api.pxToDepth( edge - menuEdge );
// Check and correct if depth is not within range.
// Also, if the dragged element is dragged upwards over
// an item, shift the placeholder to a child position.
if ( depth > maxDepth || offset.top < prevBottom ) depth = maxDepth;
else if ( depth < minDepth ) depth = minDepth;
if( depth != currentDepth )
updateCurrentDepth(ui, depth);
// If we overlap the next element, manually shift downwards
if( nextThreshold && offset.top + helperHeight > nextThreshold ) {
next.after( ui.placeholder );
updateSharedVars( ui );
$(this).sortable( "refreshPositions" );
}
}
});
function updateSharedVars(ui) {
var depth;
prev = ui.placeholder.prev();
next = ui.placeholder.next();
// Make sure we don't select the moving item.
if( prev[0] == ui.item[0] ) prev = prev.prev();
if( next[0] == ui.item[0] ) next = next.next();
prevBottom = (prev.length) ? prev.offset().top + prev.height() : 0;
nextThreshold = (next.length) ? next.offset().top + next.height() / 3 : 0;
minDepth = (next.length) ? next.menuItemDepth() : 0;
if( prev.length )
maxDepth = ( (depth = prev.menuItemDepth() + 1) > api.options.globalMaxDepth ) ? api.options.globalMaxDepth : depth;
else
maxDepth = 0;
}
function updateCurrentDepth(ui, depth) {
ui.placeholder.updateDepthClass( depth, currentDepth );
currentDepth = depth;
}
function initialMenuMaxDepth() {
if( ! body[0].className ) return 0;
var match = body[0].className.match(/menu-max-depth-(\d+)/);
return match && match[1] ? parseInt(match[1]) : 0;
}
function updateMenuMaxDepth( depthChange ) {
var depth, newDepth = menuMaxDepth;
if ( depthChange === 0 ) {
return;
} else if ( depthChange > 0 ) {
depth = maxChildDepth + depthChange;
if( depth > menuMaxDepth )
newDepth = depth;
} else if ( depthChange < 0 && maxChildDepth == menuMaxDepth ) {
while( ! $('.menu-item-depth-' + newDepth, api.menuList).length && newDepth > 0 )
newDepth--;
}
// Update the depth class.
body.removeClass( 'menu-max-depth-' + menuMaxDepth ).addClass( 'menu-max-depth-' + newDepth );
menuMaxDepth = newDepth;
}
},
attachMenuEditListeners : function() {
var that = this;
$('#update-nav-menu').bind('click', function(e) {
if ( e.target && e.target.className ) {
if ( -1 != e.target.className.indexOf('item-edit') ) {
return that.eventOnClickEditLink(e.target);
} else if ( -1 != e.target.className.indexOf('menu-save') ) {
return that.eventOnClickMenuSave(e.target);
} else if ( -1 != e.target.className.indexOf('menu-delete') ) {
return that.eventOnClickMenuDelete(e.target);
} else if ( -1 != e.target.className.indexOf('item-delete') ) {
return that.eventOnClickMenuItemDelete(e.target);
} else if ( -1 != e.target.className.indexOf('item-cancel') ) {
return that.eventOnClickCancelLink(e.target);
}
}
});
$('#add-custom-links input[type="text"]').keypress(function(e){
if ( e.keyCode === 13 ) {
e.preventDefault();
$("#submit-customlinkdiv").click();
}
});
},
/**
* An interface for managing default values for input elements
* that is both JS and accessibility-friendly.
*
* Input elements that add the class 'input-with-default-title'
* will have their values set to the provided HTML title when empty.
*/
setupInputWithDefaultTitle : function() {
var name = 'input-with-default-title';
$('.' + name).each( function(){
var $t = $(this), title = $t.attr('title'), val = $t.val();
$t.data( name, title );
if( '' == val ) $t.val( title );
else if ( title == val ) return;
else $t.removeClass( name );
}).focus( function(){
var $t = $(this);
if( $t.val() == $t.data(name) )
$t.val('').removeClass( name );
}).blur( function(){
var $t = $(this);
if( '' == $t.val() )
$t.addClass( name ).val( $t.data(name) );
});
},
attachThemeLocationsListeners : function() {
var loc = $('#nav-menu-theme-locations'), params = {};
params['action'] = 'menu-locations-save';
params['menu-settings-column-nonce'] = $('#menu-settings-column-nonce').val();
loc.find('input[type="submit"]').click(function() {
loc.find('select').each(function() {
params[this.name] = $(this).val();
});
loc.find('.waiting').show();
$.post( ajaxurl, params, function(r) {
loc.find('.waiting').hide();
});
return false;
});
},
attachQuickSearchListeners : function() {
var searchTimer;
$('.quick-search').keypress(function(e){
var t = $(this);
if( 13 == e.which ) {
api.updateQuickSearchResults( t );
return false;
}
if( searchTimer ) clearTimeout(searchTimer);
searchTimer = setTimeout(function(){
api.updateQuickSearchResults( t );
}, 400);
}).attr('autocomplete','off');
},
updateQuickSearchResults : function(input) {
var panel, params,
minSearchLength = 2,
q = input.val();
if( q.length < minSearchLength ) return;
panel = input.parents('.tabs-panel');
params = {
'action': 'menu-quick-search',
'response-format': 'markup',
'menu': $('#menu').val(),
'menu-settings-column-nonce': $('#menu-settings-column-nonce').val(),
'q': q,
'type': input.attr('name')
};
$('img.waiting', panel).show();
$.post( ajaxurl, params, function(menuMarkup) {
api.processQuickSearchQueryResponse(menuMarkup, params, panel);
});
},
addCustomLink : function( processMethod ) {
var url = $('#custom-menu-item-url').val(),
label = $('#custom-menu-item-name').val();
processMethod = processMethod || api.addMenuItemToBottom;
if ( '' == url || 'http://' == url )
return false;
// Show the ajax spinner
$('.customlinkdiv img.waiting').show();
this.addLinkToMenu( url, label, processMethod, function() {
// Remove the ajax spinner
$('.customlinkdiv img.waiting').hide();
// Set custom link form back to defaults
$('#custom-menu-item-name').val('').blur();
$('#custom-menu-item-url').val('http://');
});
},
addLinkToMenu : function(url, label, processMethod, callback) {
processMethod = processMethod || api.addMenuItemToBottom;
callback = callback || function(){};
api.addItemToMenu({
'-1': {
'menu-item-type': 'custom',
'menu-item-url': url,
'menu-item-title': label
}
}, processMethod, callback);
},
addItemToMenu : function(menuItem, processMethod, callback) {
var menu = $('#menu').val(),
nonce = $('#menu-settings-column-nonce').val();
processMethod = processMethod || function(){};
callback = callback || function(){};
params = {
'action': 'add-menu-item',
'menu': menu,
'menu-settings-column-nonce': nonce,
'menu-item': menuItem
};
$.post( ajaxurl, params, function(menuMarkup) {
var ins = $('#menu-instructions');
processMethod(menuMarkup, params);
if( ! ins.hasClass('menu-instructions-inactive') && ins.siblings().length )
ins.addClass('menu-instructions-inactive');
callback();
});
},
/**
* Process the add menu item request response into menu list item.
*
* @param string menuMarkup The text server response of menu item markup.
* @param object req The request arguments.
*/
addMenuItemToBottom : function( menuMarkup, req ) {
$(menuMarkup).hideAdvancedMenuItemFields().appendTo( api.targetList );
},
addMenuItemToTop : function( menuMarkup, req ) {
$(menuMarkup).hideAdvancedMenuItemFields().prependTo( api.targetList );
},
attachUnsavedChangesListener : function() {
$('#menu-management input, #menu-management select, #menu-management, #menu-management textarea').change(function(){
api.registerChange();
});
if ( 0 != $('#menu-to-edit').length ) {
window.onbeforeunload = function(){
if ( api.menusChanged )
return navMenuL10n.saveAlert;
};
} else {
// Make the post boxes read-only, as they can't be used yet
$('#menu-settings-column').find('input,select').prop('disabled', true).end().find('a').attr('href', '#').unbind('click');
}
},
registerChange : function() {
api.menusChanged = true;
},
attachTabsPanelListeners : function() {
$('#menu-settings-column').bind('click', function(e) {
var selectAreaMatch, panelId, wrapper, items,
target = $(e.target);
if ( target.hasClass('nav-tab-link') ) {
panelId = /#(.*)$/.exec(e.target.href);
if ( panelId && panelId[1] )
panelId = panelId[1]
else
return false;
wrapper = target.parents('.inside').first();
// upon changing tabs, we want to uncheck all checkboxes
$('input', wrapper).removeAttr('checked');
$('.tabs-panel-active', wrapper).removeClass('tabs-panel-active').addClass('tabs-panel-inactive');
$('#' + panelId, wrapper).removeClass('tabs-panel-inactive').addClass('tabs-panel-active');
$('.tabs', wrapper).removeClass('tabs');
target.parent().addClass('tabs');
// select the search bar
$('.quick-search', wrapper).focus();
return false;
} else if ( target.hasClass('select-all') ) {
selectAreaMatch = /#(.*)$/.exec(e.target.href);
if ( selectAreaMatch && selectAreaMatch[1] ) {
items = $('#' + selectAreaMatch[1] + ' .tabs-panel-active .menu-item-title input');
if( items.length === items.filter(':checked').length )
items.removeAttr('checked');
else
items.prop('checked', true);
return false;
}
} else if ( target.hasClass('submit-add-to-menu') ) {
api.registerChange();
if ( e.target.id && 'submit-customlinkdiv' == e.target.id )
api.addCustomLink( api.addMenuItemToBottom );
else if ( e.target.id && -1 != e.target.id.indexOf('submit-') )
$('#' + e.target.id.replace(/submit-/, '')).addSelectedToMenu( api.addMenuItemToBottom );
return false;
} else if ( target.hasClass('page-numbers') ) {
$.post( ajaxurl, e.target.href.replace(/.*\?/, '').replace(/action=([^&]*)/, '') + '&action=menu-get-metabox',
function( resp ) {
if ( -1 == resp.indexOf('replace-id') )
return;
var metaBoxData = $.parseJSON(resp),
toReplace = document.getElementById(metaBoxData['replace-id']),
placeholder = document.createElement('div'),
wrap = document.createElement('div');
if ( ! metaBoxData['markup'] || ! toReplace )
return;
wrap.innerHTML = metaBoxData['markup'] ? metaBoxData['markup'] : '';
toReplace.parentNode.insertBefore( placeholder, toReplace );
placeholder.parentNode.removeChild( toReplace );
placeholder.parentNode.insertBefore( wrap, placeholder );
placeholder.parentNode.removeChild( placeholder );
}
);
return false;
}
});
},
initTabManager : function() {
var fixed = $('.nav-tabs-wrapper'),
fluid = fixed.children('.nav-tabs'),
active = fluid.children('.nav-tab-active'),
tabs = fluid.children('.nav-tab'),
tabsWidth = 0,
fixedRight, fixedLeft,
arrowLeft, arrowRight, resizeTimer, css = {},
marginFluid = api.isRTL ? 'margin-right' : 'margin-left',
marginFixed = api.isRTL ? 'margin-left' : 'margin-right',
msPerPx = 2;
/**
* Refreshes the menu tabs.
* Will show and hide arrows where necessary.
* Scrolls to the active tab by default.
*
* @param savePosition {boolean} Optional. Prevents scrolling so
* that the current position is maintained. Default false.
**/
api.refreshMenuTabs = function( savePosition ) {
var fixedWidth = fixed.width(),
margin = 0, css = {};
fixedLeft = fixed.offset().left;
fixedRight = fixedLeft + fixedWidth;
if( !savePosition )
active.makeTabVisible();
// Prevent space from building up next to the last tab if there's more to show
if( tabs.last().isTabVisible() ) {
margin = fixed.width() - tabsWidth;
margin = margin > 0 ? 0 : margin;
css[marginFluid] = margin + 'px';
fluid.animate( css, 100, "linear" );
}
// Show the arrows only when necessary
if( fixedWidth > tabsWidth )
arrowLeft.add( arrowRight ).hide();
else
arrowLeft.add( arrowRight ).show();
}
$.fn.extend({
makeTabVisible : function() {
var t = this.eq(0), left, right, css = {}, shift = 0;
if( ! t.length ) return this;
left = t.offset().left;
right = left + t.outerWidth();
if( right > fixedRight )
shift = fixedRight - right;
else if ( left < fixedLeft )
shift = fixedLeft - left;
if( ! shift ) return this;
css[marginFluid] = "+=" + api.negateIfRTL * shift + 'px';
fluid.animate( css, Math.abs( shift ) * msPerPx, "linear" );
return this;
},
isTabVisible : function() {
var t = this.eq(0),
left = t.offset().left,
right = left + t.outerWidth();
return ( right <= fixedRight && left >= fixedLeft ) ? true : false;
}
});
// Find the width of all tabs
tabs.each(function(){
tabsWidth += $(this).outerWidth(true);
});
// Set up fixed margin for overflow, unset padding
css['padding'] = 0;
css[marginFixed] = (-1 * tabsWidth) + 'px';
fluid.css( css );
// Build tab navigation
arrowLeft = $('<div class="nav-tabs-arrow nav-tabs-arrow-left"><a>«</a></div>');
arrowRight = $('<div class="nav-tabs-arrow nav-tabs-arrow-right"><a>»</a></div>');
// Attach to the document
fixed.wrap('<div class="nav-tabs-nav"/>').parent().prepend( arrowLeft ).append( arrowRight );
// Set the menu tabs
api.refreshMenuTabs();
// Make sure the tabs reset on resize
$(window).resize(function() {
if( resizeTimer ) clearTimeout(resizeTimer);
resizeTimer = setTimeout( api.refreshMenuTabs, 200);
});
// Build arrow functions
$.each([{
arrow : arrowLeft,
next : "next",
last : "first",
operator : "+="
},{
arrow : arrowRight,
next : "prev",
last : "last",
operator : "-="
}], function(){
var that = this;
this.arrow.mousedown(function(){
var marginFluidVal = Math.abs( parseInt( fluid.css(marginFluid) ) ),
shift = marginFluidVal,
css = {};
if( "-=" == that.operator )
shift = Math.abs( tabsWidth - fixed.width() ) - marginFluidVal;
if( ! shift ) return;
css[marginFluid] = that.operator + shift + 'px';
fluid.animate( css, shift * msPerPx, "linear" );
}).mouseup(function(){
var tab, next;
fluid.stop(true);
tab = tabs[that.last]();
while( (next = tab[that.next]()) && next.length && ! next.isTabVisible() ) {
tab = next;
}
tab.makeTabVisible();
});
});
},
eventOnClickEditLink : function(clickedEl) {
var settings, item,
matchedSection = /#(.*)$/.exec(clickedEl.href);
if ( matchedSection && matchedSection[1] ) {
settings = $('#'+matchedSection[1]);
item = settings.parent();
if( 0 != item.length ) {
if( item.hasClass('menu-item-edit-inactive') ) {
if( ! settings.data('menu-item-data') ) {
settings.data( 'menu-item-data', settings.getItemData() );
}
settings.slideDown('fast');
item.removeClass('menu-item-edit-inactive')
.addClass('menu-item-edit-active');
} else {
settings.slideUp('fast');
item.removeClass('menu-item-edit-active')
.addClass('menu-item-edit-inactive');
}
return false;
}
}
},
eventOnClickCancelLink : function(clickedEl) {
var settings = $(clickedEl).closest('.menu-item-settings');
settings.setItemData( settings.data('menu-item-data') );
return false;
},
eventOnClickMenuSave : function(clickedEl) {
var locs = '',
menuName = $('#menu-name'),
menuNameVal = menuName.val();
// Cancel and warn if invalid menu name
if( !menuNameVal || menuNameVal == menuName.attr('title') || !menuNameVal.replace(/\s+/, '') ) {
menuName.parent().addClass('form-invalid');
return false;
}
// Copy menu theme locations
$('#nav-menu-theme-locations select').each(function() {
locs += '<input type="hidden" name="' + this.name + '" value="' + $(this).val() + '" />';
});
$('#update-nav-menu').append( locs );
// Update menu item position data
api.menuList.find('.menu-item-data-position').val( function(index) { return index + 1; } );
window.onbeforeunload = null;
return true;
},
eventOnClickMenuDelete : function(clickedEl) {
// Delete warning AYS
if ( confirm( navMenuL10n.warnDeleteMenu ) ) {
window.onbeforeunload = null;
return true;
}
return false;
},
eventOnClickMenuItemDelete : function(clickedEl) {
var itemID = parseInt(clickedEl.id.replace('delete-', ''), 10);
api.removeMenuItem( $('#menu-item-' + itemID) );
api.registerChange();
return false;
},
/**
* Process the quick search response into a search result
*
* @param string resp The server response to the query.
* @param object req The request arguments.
* @param jQuery panel The tabs panel we're searching in.
*/
processQuickSearchQueryResponse : function(resp, req, panel) {
var matched, newID,
takenIDs = {},
form = document.getElementById('nav-menu-meta'),
pattern = new RegExp('menu-item\\[(\[^\\]\]*)', 'g'),
$items = $('<div>').html(resp).find('li'),
$item;
if( ! $items.length ) {
$('.categorychecklist', panel).html( '<li><p>' + navMenuL10n.noResultsFound + '</p></li>' );
$('img.waiting', panel).hide();
return;
}
$items.each(function(){
$item = $(this);
// make a unique DB ID number
matched = pattern.exec($item.html());
if ( matched && matched[1] ) {
newID = matched[1];
while( form.elements['menu-item[' + newID + '][menu-item-type]'] || takenIDs[ newID ] ) {
newID--;
}
takenIDs[newID] = true;
if ( newID != matched[1] ) {
$item.html( $item.html().replace(new RegExp(
'menu-item\\[' + matched[1] + '\\]', 'g'),
'menu-item[' + newID + ']'
) );
}
}
});
$('.categorychecklist', panel).html( $items );
$('img.waiting', panel).hide();
},
removeMenuItem : function(el) {
var children = el.childMenuItems();
el.addClass('deleting').animate({
opacity : 0,
height: 0
}, 350, function() {
var ins = $('#menu-instructions');
el.remove();
children.shiftDepthClass(-1).updateParentMenuItemDBId();
if( ! ins.siblings().length )
ins.removeClass('menu-instructions-inactive');
});
},
depthToPx : function(depth) {
return depth * api.options.menuItemDepthPerLevel;
},
pxToDepth : function(px) {
return Math.floor(px / api.options.menuItemDepthPerLevel);
}
};
$(document).ready(function(){ wpNavMenu.init(); });
})(jQuery);
| JavaScript |
var ajaxWidgets, ajaxPopulateWidgets, quickPressLoad;
jQuery(document).ready( function($) {
/* Dashboard Welcome Panel */
var welcomePanel = $('#welcome-panel'),
welcomePanelHide = $('#wp_welcome_panel-hide'),
updateWelcomePanel = function( visible ) {
$.post( ajaxurl, {
action: 'update-welcome-panel',
visible: visible,
welcomepanelnonce: $('#welcomepanelnonce').val()
});
};
if ( welcomePanel.hasClass('hidden') && welcomePanelHide.prop('checked') )
welcomePanel.removeClass('hidden');
$('.welcome-panel-close, .welcome-panel-dismiss a', welcomePanel).click( function(e) {
e.preventDefault();
welcomePanel.addClass('hidden');
updateWelcomePanel( 0 );
$('#wp_welcome_panel-hide').prop('checked', false);
});
welcomePanelHide.click( function() {
welcomePanel.toggleClass('hidden', ! this.checked );
updateWelcomePanel( this.checked ? 1 : 0 );
});
// These widgets are sometimes populated via ajax
ajaxWidgets = [
'dashboard_incoming_links',
'dashboard_primary',
'dashboard_secondary',
'dashboard_plugins'
];
ajaxPopulateWidgets = function(el) {
function show(i, id) {
var p, e = $('#' + id + ' div.inside:visible').find('.widget-loading');
if ( e.length ) {
p = e.parent();
setTimeout( function(){
p.load( ajaxurl.replace( '/admin-ajax.php', '' ) + '/index-extra.php?jax=' + id, '', function() {
p.hide().slideDown('normal', function(){
$(this).css('display', '');
});
});
}, i * 500 );
}
}
if ( el ) {
el = el.toString();
if ( $.inArray(el, ajaxWidgets) != -1 )
show(0, el);
} else {
$.each( ajaxWidgets, show );
}
};
ajaxPopulateWidgets();
postboxes.add_postbox_toggles(pagenow, { pbshow: ajaxPopulateWidgets } );
/* QuickPress */
quickPressLoad = function() {
var act = $('#quickpost-action'), t;
t = $('#quick-press').submit( function() {
$('#dashboard_quick_press #publishing-action img.waiting').css('visibility', 'visible');
$('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').prop('disabled', true);
if ( 'post' == act.val() ) {
act.val( 'post-quickpress-publish' );
}
$('#dashboard_quick_press div.inside').load( t.attr( 'action' ), t.serializeArray(), function() {
$('#dashboard_quick_press #publishing-action img.waiting').css('visibility', 'hidden');
$('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').prop('disabled', false);
$('#dashboard_quick_press ul').next('p').remove();
$('#dashboard_quick_press ul').find('li').each( function() {
$('#dashboard_recent_drafts ul').prepend( this );
} ).end().remove();
quickPressLoad();
} );
return false;
} );
$('#publish').click( function() { act.val( 'post-quickpress-publish' ); } );
};
quickPressLoad();
} );
| JavaScript |
var theList, theExtraList, toggleWithKeyboard = false, getCount, updateCount, updatePending, dashboardTotals;
(function($) {
setCommentsList = function() {
var totalInput, perPageInput, pageInput, lastConfidentTime = 0, dimAfter, delBefore, updateTotalCount, delAfter, refillTheExtraList;
totalInput = $('input[name="_total"]', '#comments-form');
perPageInput = $('input[name="_per_page"]', '#comments-form');
pageInput = $('input[name="_page"]', '#comments-form');
dimAfter = function( r, settings ) {
var c = $('#' + settings.element), editRow, replyID, replyButton;
editRow = $('#replyrow');
replyID = $('#comment_ID', editRow).val();
replyButton = $('#replybtn', editRow);
if ( c.is('.unapproved') ) {
if ( settings.data.id == replyID )
replyButton.text(adminCommentsL10n.replyApprove);
c.find('div.comment_status').html('0');
} else {
if ( settings.data.id == replyID )
replyButton.text(adminCommentsL10n.reply);
c.find('div.comment_status').html('1');
}
$('span.pending-count').each( function() {
var a = $(this), n, dif;
n = a.html().replace(/[^0-9]+/g, '');
n = parseInt(n, 10);
if ( isNaN(n) )
return;
dif = $('#' + settings.element).is('.' + settings.dimClass) ? 1 : -1;
n = n + dif;
if ( n < 0 )
n = 0;
a.closest('.awaiting-mod')[ 0 == n ? 'addClass' : 'removeClass' ]('count-0');
updateCount(a, n);
dashboardTotals();
});
};
// Send current total, page, per_page and url
delBefore = function( settings, list ) {
var cl = $(settings.target).attr('class'), id, el, n, h, a, author, action = false;
settings.data._total = totalInput.val() || 0;
settings.data._per_page = perPageInput.val() || 0;
settings.data._page = pageInput.val() || 0;
settings.data._url = document.location.href;
settings.data.comment_status = $('input[name="comment_status"]', '#comments-form').val();
if ( cl.indexOf(':trash=1') != -1 )
action = 'trash';
else if ( cl.indexOf(':spam=1') != -1 )
action = 'spam';
if ( action ) {
id = cl.replace(/.*?comment-([0-9]+).*/, '$1');
el = $('#comment-' + id);
note = $('#' + action + '-undo-holder').html();
el.find('.check-column :checkbox').prop('checked', false); // Uncheck the row so as not to be affected by Bulk Edits.
if ( el.siblings('#replyrow').length && commentReply.cid == id )
commentReply.close();
if ( el.is('tr') ) {
n = el.children(':visible').length;
author = $('.author strong', el).text();
h = $('<tr id="undo-' + id + '" class="undo un' + action + '" style="display:none;"><td colspan="' + n + '">' + note + '</td></tr>');
} else {
author = $('.comment-author', el).text();
h = $('<div id="undo-' + id + '" style="display:none;" class="undo un' + action + '">' + note + '</div>');
}
el.before(h);
$('strong', '#undo-' + id).text(author + ' ');
a = $('.undo a', '#undo-' + id);
a.attr('href', 'comment.php?action=un' + action + 'comment&c=' + id + '&_wpnonce=' + settings.data._ajax_nonce);
a.attr('class', 'delete:the-comment-list:comment-' + id + '::un' + action + '=1 vim-z vim-destructive');
$('.avatar', el).clone().prependTo('#undo-' + id + ' .' + action + '-undo-inside');
a.click(function(){
list.wpList.del(this);
$('#undo-' + id).css( {backgroundColor:'#ceb'} ).fadeOut(350, function(){
$(this).remove();
$('#comment-' + id).css('backgroundColor', '').fadeIn(300, function(){ $(this).show() });
});
return false;
});
}
return settings;
};
// Updates the current total (stored in the _total input)
updateTotalCount = function( total, time, setConfidentTime ) {
if ( time < lastConfidentTime )
return;
if ( setConfidentTime )
lastConfidentTime = time;
totalInput.val( total.toString() );
};
dashboardTotals = function(n) {
var dash = $('#dashboard_right_now'), total, appr, totalN, apprN;
n = n || 0;
if ( isNaN(n) || !dash.length )
return;
total = $('span.total-count', dash);
appr = $('span.approved-count', dash);
totalN = getCount(total);
totalN = totalN + n;
apprN = totalN - getCount( $('span.pending-count', dash) ) - getCount( $('span.spam-count', dash) );
updateCount(total, totalN);
updateCount(appr, apprN);
};
getCount = function(el) {
var n = parseInt( el.html().replace(/[^0-9]+/g, ''), 10 );
if ( isNaN(n) )
return 0;
return n;
};
updateCount = function(el, n) {
var n1 = '';
if ( isNaN(n) )
return;
n = n < 1 ? '0' : n.toString();
if ( n.length > 3 ) {
while ( n.length > 3 ) {
n1 = thousandsSeparator + n.substr(n.length - 3) + n1;
n = n.substr(0, n.length - 3);
}
n = n + n1;
}
el.html(n);
};
updatePending = function(n) {
$('span.pending-count').each( function() {
var a = $(this);
if ( n < 0 )
n = 0;
a.closest('.awaiting-mod')[ 0 == n ? 'addClass' : 'removeClass' ]('count-0');
updateCount(a, n);
dashboardTotals();
});
};
// In admin-ajax.php, we send back the unix time stamp instead of 1 on success
delAfter = function( r, settings ) {
var total, N, spam, trash, pending,
untrash = $(settings.target).parent().is('span.untrash'),
unspam = $(settings.target).parent().is('span.unspam'),
unapproved = $('#' + settings.element).is('.unapproved');
function getUpdate(s) {
if ( $(settings.target).parent().is('span.' + s) )
return 1;
else if ( $('#' + settings.element).is('.' + s) )
return -1;
return 0;
}
if ( untrash )
trash = -1;
else
trash = getUpdate('trash');
if ( unspam )
spam = -1;
else
spam = getUpdate('spam');
pending = getCount( $('span.pending-count').eq(0) );
if ( $(settings.target).parent().is('span.unapprove') || ( ( untrash || unspam ) && unapproved ) ) { // we "deleted" an approved comment from the approved list by clicking "Unapprove"
pending = pending + 1;
} else if ( unapproved ) { // we deleted a formerly unapproved comment
pending = pending - 1;
}
updatePending(pending);
$('span.spam-count').each( function() {
var a = $(this), n = getCount(a) + spam;
updateCount(a, n);
});
$('span.trash-count').each( function() {
var a = $(this), n = getCount(a) + trash;
updateCount(a, n);
});
if ( $('#dashboard_right_now').length ) {
N = trash ? -1 * trash : 0;
dashboardTotals(N);
} else {
total = totalInput.val() ? parseInt( totalInput.val(), 10 ) : 0;
if ( $(settings.target).parent().is('span.undo') )
total++;
else
total--;
if ( total < 0 )
total = 0;
if ( ( 'object' == typeof r ) && lastConfidentTime < settings.parsed.responses[0].supplemental.time ) {
total_items_i18n = settings.parsed.responses[0].supplemental.total_items_i18n || '';
if ( total_items_i18n ) {
$('.displaying-num').text( total_items_i18n );
$('.total-pages').text( settings.parsed.responses[0].supplemental.total_pages_i18n );
$('.tablenav-pages').find('.next-page, .last-page').toggleClass('disabled', settings.parsed.responses[0].supplemental.total_pages == $('.current-page').val());
}
updateTotalCount( total, settings.parsed.responses[0].supplemental.time, true );
} else {
updateTotalCount( total, r, false );
}
}
if ( ! theExtraList || theExtraList.size() == 0 || theExtraList.children().size() == 0 || untrash || unspam ) {
return;
}
theList.get(0).wpList.add( theExtraList.children(':eq(0)').remove().clone() );
refillTheExtraList();
};
refillTheExtraList = function(ev) {
var args = $.query.get(), total_pages = $('.total-pages').text(), per_page = $('input[name="_per_page"]', '#comments-form').val();
if (! args.paged)
args.paged = 1;
if (args.paged > total_pages) {
return;
}
if (ev) {
theExtraList.empty();
args.number = Math.min(8, per_page); // see WP_Comments_List_Table::prepare_items() @ class-wp-comments-list-table.php
} else {
args.number = 1;
args.offset = Math.min(8, per_page) - 1; // fetch only the next item on the extra list
}
args.no_placeholder = true;
args.paged ++;
// $.query.get() needs some correction to be sent into an ajax request
if ( true === args.comment_type )
args.comment_type = '';
args = $.extend(args, {
'action': 'fetch-list',
'list_args': list_args,
'_ajax_fetch_list_nonce': $('#_ajax_fetch_list_nonce').val()
});
$.ajax({
url: ajaxurl,
global: false,
dataType: 'json',
data: args,
success: function(response) {
theExtraList.get(0).wpList.add( response.rows );
}
});
};
theExtraList = $('#the-extra-comment-list').wpList( { alt: '', delColor: 'none', addColor: 'none' } );
theList = $('#the-comment-list').wpList( { alt: '', delBefore: delBefore, dimAfter: dimAfter, delAfter: delAfter, addColor: 'none' } )
.bind('wpListDelEnd', function(e, s){
var id = s.element.replace(/[^0-9]+/g, '');
if ( s.target.className.indexOf(':trash=1') != -1 || s.target.className.indexOf(':spam=1') != -1 )
$('#undo-' + id).fadeIn(300, function(){ $(this).show() });
});
};
commentReply = {
cid : '',
act : '',
init : function() {
var row = $('#replyrow');
$('a.cancel', row).click(function() { return commentReply.revert(); });
$('a.save', row).click(function() { return commentReply.send(); });
$('input#author, input#author-email, input#author-url', row).keypress(function(e){
if ( e.which == 13 ) {
commentReply.send();
e.preventDefault();
return false;
}
});
// add events
$('#the-comment-list .column-comment > p').dblclick(function(){
commentReply.toggle($(this).parent());
});
$('#doaction, #doaction2, #post-query-submit').click(function(e){
if ( $('#the-comment-list #replyrow').length > 0 )
commentReply.close();
});
this.comments_listing = $('#comments-form > input[name="comment_status"]').val() || '';
/* $(listTable).bind('beforeChangePage', function(){
commentReply.close();
}); */
},
addEvents : function(r) {
r.each(function() {
$(this).find('.column-comment > p').dblclick(function(){
commentReply.toggle($(this).parent());
});
});
},
toggle : function(el) {
if ( $(el).css('display') != 'none' )
$(el).find('a.vim-q').click();
},
revert : function() {
if ( $('#the-comment-list #replyrow').length < 1 )
return false;
$('#replyrow').fadeOut('fast', function(){
commentReply.close();
});
return false;
},
close : function() {
var c;
if ( this.cid ) {
c = $('#comment-' + this.cid);
if ( typeof QTags != 'undefined' )
QTags.closeAllTags('replycontent');
if ( this.act == 'edit-comment' )
c.fadeIn(300, function(){ c.show() }).css('backgroundColor', '');
$('#replyrow').hide();
$('#com-reply').append( $('#replyrow') );
$('#replycontent').val('');
$('input', '#edithead').val('');
$('.error', '#replysubmit').html('').hide();
$('.waiting', '#replysubmit').hide();
$('#replycontent').css('height', '');
this.cid = '';
}
},
open : function(id, p, a) {
var t = this, editRow, rowData, act, c = $('#comment-' + id), h = c.height(), replyButton;
t.close();
t.cid = id;
editRow = $('#replyrow');
rowData = $('#inline-'+id);
act = t.act = (a == 'edit') ? 'edit-comment' : 'replyto-comment';
$('#action', editRow).val(act);
$('#comment_post_ID', editRow).val(p);
$('#comment_ID', editRow).val(id);
if ( h > 120 )
$('#replycontent', editRow).css('height', (35+h) + 'px');
if ( a == 'edit' ) {
$('#author', editRow).val( $('div.author', rowData).text() );
$('#author-email', editRow).val( $('div.author-email', rowData).text() );
$('#author-url', editRow).val( $('div.author-url', rowData).text() );
$('#status', editRow).val( $('div.comment_status', rowData).text() );
$('#replycontent', editRow).val( $('textarea.comment', rowData).val() );
$('#edithead, #savebtn', editRow).show();
$('#replyhead, #replybtn', editRow).hide();
c.after( editRow ).fadeOut('fast', function(){
$('#replyrow').fadeIn(300, function(){ $(this).show() });
});
} else {
replyButton = $('#replybtn', editRow);
$('#edithead, #savebtn', editRow).hide();
$('#replyhead, #replybtn', editRow).show();
c.after(editRow);
if ( c.hasClass('unapproved') ) {
replyButton.text(adminCommentsL10n.replyApprove);
} else {
replyButton.text(adminCommentsL10n.reply);
}
$('#replyrow').fadeIn(300, function(){ $(this).show() });
}
setTimeout(function() {
var rtop, rbottom, scrollTop, vp, scrollBottom;
rtop = $('#replyrow').offset().top;
rbottom = rtop + $('#replyrow').height();
scrollTop = window.pageYOffset || document.documentElement.scrollTop;
vp = document.documentElement.clientHeight || self.innerHeight || 0;
scrollBottom = scrollTop + vp;
if ( scrollBottom - 20 < rbottom )
window.scroll(0, rbottom - vp + 35);
else if ( rtop - 20 < scrollTop )
window.scroll(0, rtop - 35);
$('#replycontent').focus().keyup(function(e){
if ( e.which == 27 )
commentReply.revert(); // close on Escape
});
}, 600);
return false;
},
send : function() {
var post = {};
$('#replysubmit .error').hide();
$('#replysubmit .waiting').show();
$('#replyrow input').not(':button').each(function() {
post[ $(this).attr('name') ] = $(this).val();
});
post.content = $('#replycontent').val();
post.id = post.comment_post_ID;
post.comments_listing = this.comments_listing;
post.p = $('[name="p"]').val();
if ( $('#comment-' + $('#comment_ID').val()).hasClass('unapproved') )
post.approve_parent = 1;
$.ajax({
type : 'POST',
url : ajaxurl,
data : post,
success : function(x) { commentReply.show(x); },
error : function(r) { commentReply.error(r); }
});
return false;
},
show : function(xml) {
var t = this, r, c, id, bg, pid;
if ( typeof(xml) == 'string' ) {
t.error({'responseText': xml});
return false;
}
r = wpAjax.parseAjaxResponse(xml);
if ( r.errors ) {
t.error({'responseText': wpAjax.broken});
return false;
}
t.revert();
r = r.responses[0];
c = r.data;
id = '#comment-' + r.id;
if ( 'edit-comment' == t.act )
$(id).remove();
if ( r.supplemental.parent_approved ) {
pid = $('#comment-' + r.supplemental.parent_approved);
updatePending( getCount( $('span.pending-count').eq(0) ) - 1 );
if ( this.comments_listing == 'moderated' ) {
pid.animate( { 'backgroundColor':'#CCEEBB' }, 400, function(){
pid.fadeOut();
});
return;
}
}
$(c).hide()
$('#replyrow').after(c);
id = $(id);
t.addEvents(id);
bg = id.hasClass('unapproved') ? '#FFFFE0' : id.closest('.widefat, .postbox').css('backgroundColor');
id.animate( { 'backgroundColor':'#CCEEBB' }, 300 )
.animate( { 'backgroundColor': bg }, 300, function() {
if ( pid && pid.length ) {
pid.animate( { 'backgroundColor':'#CCEEBB' }, 300 )
.animate( { 'backgroundColor': bg }, 300 )
.removeClass('unapproved').addClass('approved')
.find('div.comment_status').html('1');
}
});
},
error : function(r) {
var er = r.statusText;
$('#replysubmit .waiting').hide();
if ( r.responseText )
er = r.responseText.replace( /<.[^<>]*?>/g, '' );
if ( er )
$('#replysubmit .error').html(er).show();
}
};
$(document).ready(function(){
var make_hotkeys_redirect, edit_comment, toggle_all, make_bulk;
setCommentsList();
commentReply.init();
$(document).delegate('span.delete a.delete', 'click', function(){return false;});
if ( typeof $.table_hotkeys != 'undefined' ) {
make_hotkeys_redirect = function(which) {
return function() {
var first_last, l;
first_last = 'next' == which? 'first' : 'last';
l = $('.tablenav-pages .'+which+'-page:not(.disabled)');
if (l.length)
window.location = l[0].href.replace(/\&hotkeys_highlight_(first|last)=1/g, '')+'&hotkeys_highlight_'+first_last+'=1';
}
};
edit_comment = function(event, current_row) {
window.location = $('span.edit a', current_row).attr('href');
};
toggle_all = function() {
toggleWithKeyboard = true;
$('input:checkbox', '#cb').click().prop('checked', false);
toggleWithKeyboard = false;
};
make_bulk = function(value) {
return function() {
var scope = $('select[name="action"]');
$('option[value="' + value + '"]', scope).prop('selected', true);
$('#doaction').click();
}
};
$.table_hotkeys(
$('table.widefat'),
['a', 'u', 's', 'd', 'r', 'q', 'z', ['e', edit_comment], ['shift+x', toggle_all],
['shift+a', make_bulk('approve')], ['shift+s', make_bulk('spam')],
['shift+d', make_bulk('delete')], ['shift+t', make_bulk('trash')],
['shift+z', make_bulk('untrash')], ['shift+u', make_bulk('unapprove')]],
{ highlight_first: adminCommentsL10n.hotkeys_highlight_first, highlight_last: adminCommentsL10n.hotkeys_highlight_last,
prev_page_link_cb: make_hotkeys_redirect('prev'), next_page_link_cb: make_hotkeys_redirect('next') }
);
}
});
})(jQuery);
| JavaScript |
/* Plugin Browser Thickbox related JS*/
var tb_position;
jQuery(document).ready(function($) {
tb_position = function() {
var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 720 < width ) ? 720 : width, adminbar_height = 0;
if ( $('body.admin-bar').length )
adminbar_height = 28;
if ( tbWindow.size() ) {
tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
$('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
tbWindow.css({'margin-left': '-' + parseInt((( W - 50 ) / 2),10) + 'px'});
if ( typeof document.body.style.maxWidth != 'undefined' )
tbWindow.css({'top': 20 + adminbar_height + 'px','margin-top':'0'});
};
return $('a.thickbox').each( function() {
var href = $(this).attr('href');
if ( ! href )
return;
href = href.replace(/&width=[0-9]+/g, '');
href = href.replace(/&height=[0-9]+/g, '');
$(this).attr( 'href', href + '&width=' + ( W - 80 ) + '&height=' + ( H - 85 - adminbar_height ) );
});
};
$(window).resize(function(){ tb_position(); });
$('#dashboard_plugins a.thickbox, .plugins a.thickbox').click( function() {
tb_click.call(this);
$('#TB_title').css({'background-color':'#222','color':'#cfcfcf'});
$('#TB_ajaxWindowTitle').html('<strong>' + plugininstallL10n.plugin_information + '</strong> ' + $(this).attr('title') );
return false;
});
/* Plugin install related JS*/
$('#plugin-information #sidemenu a').click( function() {
var tab = $(this).attr('name');
//Flip the tab
$('#plugin-information-header a.current').removeClass('current');
$(this).addClass('current');
//Flip the content.
$('#section-holder div.section').hide(); //Hide 'em all
$('#section-' + tab).show();
return false;
});
$('a.install-now').click( function() {
return confirm( plugininstallL10n.ays );
});
});
| JavaScript |
var wpWidgets;
(function($) {
wpWidgets = {
init : function() {
var rem, sidebars = $('div.widgets-sortables'), isRTL = !! ( 'undefined' != typeof isRtl && isRtl ),
margin = ( isRtl ? 'marginRight' : 'marginLeft' ), the_id;
$('#widgets-right').children('.widgets-holder-wrap').children('.sidebar-name').click(function(){
var c = $(this).siblings('.widgets-sortables'), p = $(this).parent();
if ( !p.hasClass('closed') ) {
c.sortable('disable');
p.addClass('closed');
} else {
p.removeClass('closed');
c.sortable('enable').sortable('refresh');
}
});
$('#widgets-left').children('.widgets-holder-wrap').children('.sidebar-name').click(function() {
$(this).parent().toggleClass('closed');
});
sidebars.each(function(){
if ( $(this).parent().hasClass('inactive') )
return true;
var h = 50, H = $(this).children('.widget').length;
h = h + parseInt(H * 48, 10);
$(this).css( 'minHeight', h + 'px' );
});
$('a.widget-action').live('click', function(){
var css = {}, widget = $(this).closest('div.widget'), inside = widget.children('.widget-inside'), w = parseInt( widget.find('input.widget-width').val(), 10 );
if ( inside.is(':hidden') ) {
if ( w > 250 && inside.closest('div.widgets-sortables').length ) {
css['width'] = w + 30 + 'px';
if ( inside.closest('div.widget-liquid-right').length )
css[margin] = 235 - w + 'px';
widget.css(css);
}
wpWidgets.fixLabels(widget);
inside.slideDown('fast');
} else {
inside.slideUp('fast', function() {
widget.css({'width':'', margin:''});
});
}
return false;
});
$('input.widget-control-save').live('click', function(){
wpWidgets.save( $(this).closest('div.widget'), 0, 1, 0 );
return false;
});
$('a.widget-control-remove').live('click', function(){
wpWidgets.save( $(this).closest('div.widget'), 1, 1, 0 );
return false;
});
$('a.widget-control-close').live('click', function(){
wpWidgets.close( $(this).closest('div.widget') );
return false;
});
sidebars.children('.widget').each(function() {
wpWidgets.appendTitle(this);
if ( $('p.widget-error', this).length )
$('a.widget-action', this).click();
});
$('#widget-list').children('.widget').draggable({
connectToSortable: 'div.widgets-sortables',
handle: '> .widget-top > .widget-title',
distance: 2,
helper: 'clone',
zIndex: 5,
containment: 'document',
start: function(e,ui) {
ui.helper.find('div.widget-description').hide();
the_id = this.id;
},
stop: function(e,ui) {
if ( rem )
$(rem).hide();
rem = '';
}
});
sidebars.sortable({
placeholder: 'widget-placeholder',
items: '> .widget',
handle: '> .widget-top > .widget-title',
cursor: 'move',
distance: 2,
containment: 'document',
start: function(e,ui) {
ui.item.children('.widget-inside').hide();
ui.item.css({margin:'', 'width':''});
},
stop: function(e,ui) {
if ( ui.item.hasClass('ui-draggable') && ui.item.data('draggable') )
ui.item.draggable('destroy');
if ( ui.item.hasClass('deleting') ) {
wpWidgets.save( ui.item, 1, 0, 1 ); // delete widget
ui.item.remove();
return;
}
var add = ui.item.find('input.add_new').val(),
n = ui.item.find('input.multi_number').val(),
id = the_id,
sb = $(this).attr('id');
ui.item.css({margin:'', 'width':''});
the_id = '';
if ( add ) {
if ( 'multi' == add ) {
ui.item.html( ui.item.html().replace(/<[^<>]+>/g, function(m){ return m.replace(/__i__|%i%/g, n); }) );
ui.item.attr( 'id', id.replace('__i__', n) );
n++;
$('div#' + id).find('input.multi_number').val(n);
} else if ( 'single' == add ) {
ui.item.attr( 'id', 'new-' + id );
rem = 'div#' + id;
}
wpWidgets.save( ui.item, 0, 0, 1 );
ui.item.find('input.add_new').val('');
ui.item.find('a.widget-action').click();
return;
}
wpWidgets.saveOrder(sb);
},
receive: function(e, ui) {
var sender = $(ui.sender);
if ( !$(this).is(':visible') || this.id.indexOf('orphaned_widgets') != -1 )
sender.sortable('cancel');
if ( sender.attr('id').indexOf('orphaned_widgets') != -1 && !sender.children('.widget').length ) {
sender.parents('.orphan-sidebar').slideUp(400, function(){ $(this).remove(); });
}
}
}).sortable('option', 'connectWith', 'div.widgets-sortables').parent().filter('.closed').children('.widgets-sortables').sortable('disable');
$('#available-widgets').droppable({
tolerance: 'pointer',
accept: function(o){
return $(o).parent().attr('id') != 'widget-list';
},
drop: function(e,ui) {
ui.draggable.addClass('deleting');
$('#removing-widget').hide().children('span').html('');
},
over: function(e,ui) {
ui.draggable.addClass('deleting');
$('div.widget-placeholder').hide();
if ( ui.draggable.hasClass('ui-sortable-helper') )
$('#removing-widget').show().children('span')
.html( ui.draggable.find('div.widget-title').children('h4').html() );
},
out: function(e,ui) {
ui.draggable.removeClass('deleting');
$('div.widget-placeholder').show();
$('#removing-widget').hide().children('span').html('');
}
});
},
saveOrder : function(sb) {
if ( sb )
$('#' + sb).closest('div.widgets-holder-wrap').find('img.ajax-feedback').css('visibility', 'visible');
var a = {
action: 'widgets-order',
savewidgets: $('#_wpnonce_widgets').val(),
sidebars: []
};
$('div.widgets-sortables').each( function() {
if ( $(this).sortable )
a['sidebars[' + $(this).attr('id') + ']'] = $(this).sortable('toArray').join(',');
});
$.post( ajaxurl, a, function() {
$('img.ajax-feedback').css('visibility', 'hidden');
});
this.resize();
},
save : function(widget, del, animate, order) {
var sb = widget.closest('div.widgets-sortables').attr('id'), data = widget.find('form').serialize(), a;
widget = $(widget);
$('.ajax-feedback', widget).css('visibility', 'visible');
a = {
action: 'save-widget',
savewidgets: $('#_wpnonce_widgets').val(),
sidebar: sb
};
if ( del )
a['delete_widget'] = 1;
data += '&' + $.param(a);
$.post( ajaxurl, data, function(r){
var id;
if ( del ) {
if ( !$('input.widget_number', widget).val() ) {
id = $('input.widget-id', widget).val();
$('#available-widgets').find('input.widget-id').each(function(){
if ( $(this).val() == id )
$(this).closest('div.widget').show();
});
}
if ( animate ) {
order = 0;
widget.slideUp('fast', function(){
$(this).remove();
wpWidgets.saveOrder();
});
} else {
widget.remove();
wpWidgets.resize();
}
} else {
$('.ajax-feedback').css('visibility', 'hidden');
if ( r && r.length > 2 ) {
$('div.widget-content', widget).html(r);
wpWidgets.appendTitle(widget);
wpWidgets.fixLabels(widget);
}
}
if ( order )
wpWidgets.saveOrder();
});
},
appendTitle : function(widget) {
var title = $('input[id*="-title"]', widget);
if ( title = title.val() ) {
title = title.replace(/<[^<>]+>/g, '').replace(/</g, '<').replace(/>/g, '>');
$(widget).children('.widget-top').children('.widget-title').children()
.children('.in-widget-title').html(': ' + title);
}
},
resize : function() {
$('div.widgets-sortables').each(function(){
if ( $(this).parent().hasClass('inactive') )
return true;
var h = 50, H = $(this).children('.widget').length;
h = h + parseInt(H * 48, 10);
$(this).css( 'minHeight', h + 'px' );
});
},
fixLabels : function(widget) {
widget.children('.widget-inside').find('label').each(function(){
var f = $(this).attr('for');
if ( f && f == $('input', this).attr('id') )
$(this).removeAttr('for');
});
},
close : function(widget) {
widget.children('.widget-inside').slideUp('fast', function(){
widget.css({'width':'', margin:''});
});
}
};
$(document).ready(function($){ wpWidgets.init(); });
})(jQuery);
| JavaScript |
var switchEditors = {
switchto: function(el) {
var aid = el.id, l = aid.length, id = aid.substr(0, l - 5), mode = aid.substr(l - 4);
this.go(id, mode);
},
go: function(id, mode) { // mode can be 'html', 'tmce', or 'toggle'
id = id || 'content';
mode = mode || 'toggle';
var t = this, ed = tinyMCE.get(id), wrap_id, txtarea_el, dom = tinymce.DOM;
wrap_id = 'wp-'+id+'-wrap';
txtarea_el = dom.get(id);
if ( 'toggle' == mode ) {
if ( ed && !ed.isHidden() )
mode = 'html';
else
mode = 'tmce';
}
if ( 'tmce' == mode || 'tinymce' == mode ) {
if ( ed && ! ed.isHidden() )
return false;
if ( typeof(QTags) != 'undefined' )
QTags.closeAllTags(id);
if ( tinyMCEPreInit.mceInit[id] && tinyMCEPreInit.mceInit[id].wpautop )
txtarea_el.value = t.wpautop( txtarea_el.value );
if ( ed ) {
ed.show();
} else {
ed = new tinymce.Editor(id, tinyMCEPreInit.mceInit[id]);
ed.render();
}
dom.removeClass(wrap_id, 'html-active');
dom.addClass(wrap_id, 'tmce-active');
setUserSetting('editor', 'tinymce');
} else if ( 'html' == mode ) {
if ( ed && ed.isHidden() )
return false;
if ( ed ) {
txtarea_el.style.height = ed.getContentAreaContainer().offsetHeight + 20 + 'px';
ed.hide();
}
dom.removeClass(wrap_id, 'tmce-active');
dom.addClass(wrap_id, 'html-active');
setUserSetting('editor', 'html');
}
return false;
},
_wp_Nop : function(content) {
var blocklist1, blocklist2;
// Protect pre|script tags
if ( content.indexOf('<pre') != -1 || content.indexOf('<script') != -1 ) {
content = content.replace(/<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function(a) {
a = a.replace(/<br ?\/?>(\r\n|\n)?/g, '<wp_temp>');
return a.replace(/<\/?p( [^>]*)?>(\r\n|\n)?/g, '<wp_temp>');
});
}
// Pretty it up for the source editor
blocklist1 = 'blockquote|ul|ol|li|table|thead|tbody|tfoot|tr|th|td|div|h[1-6]|p|fieldset';
content = content.replace(new RegExp('\\s*</('+blocklist1+')>\\s*', 'g'), '</$1>\n');
content = content.replace(new RegExp('\\s*<((?:'+blocklist1+')(?: [^>]*)?)>', 'g'), '\n<$1>');
// Mark </p> if it has any attributes.
content = content.replace(/(<p [^>]+>.*?)<\/p>/g, '$1</p#>');
// Sepatate <div> containing <p>
content = content.replace(/<div( [^>]*)?>\s*<p>/gi, '<div$1>\n\n');
// Remove <p> and <br />
content = content.replace(/\s*<p>/gi, '');
content = content.replace(/\s*<\/p>\s*/gi, '\n\n');
content = content.replace(/\n[\s\u00a0]+\n/g, '\n\n');
content = content.replace(/\s*<br ?\/?>\s*/gi, '\n');
// Fix some block element newline issues
content = content.replace(/\s*<div/g, '\n<div');
content = content.replace(/<\/div>\s*/g, '</div>\n');
content = content.replace(/\s*\[caption([^\[]+)\[\/caption\]\s*/gi, '\n\n[caption$1[/caption]\n\n');
content = content.replace(/caption\]\n\n+\[caption/g, 'caption]\n\n[caption');
blocklist2 = 'blockquote|ul|ol|li|table|thead|tbody|tfoot|tr|th|td|h[1-6]|pre|fieldset';
content = content.replace(new RegExp('\\s*<((?:'+blocklist2+')(?: [^>]*)?)\\s*>', 'g'), '\n<$1>');
content = content.replace(new RegExp('\\s*</('+blocklist2+')>\\s*', 'g'), '</$1>\n');
content = content.replace(/<li([^>]*)>/g, '\t<li$1>');
if ( content.indexOf('<hr') != -1 ) {
content = content.replace(/\s*<hr( [^>]*)?>\s*/g, '\n\n<hr$1>\n\n');
}
if ( content.indexOf('<object') != -1 ) {
content = content.replace(/<object[\s\S]+?<\/object>/g, function(a){
return a.replace(/[\r\n]+/g, '');
});
}
// Unmark special paragraph closing tags
content = content.replace(/<\/p#>/g, '</p>\n');
content = content.replace(/\s*(<p [^>]+>[\s\S]*?<\/p>)/g, '\n$1');
// Trim whitespace
content = content.replace(/^\s+/, '');
content = content.replace(/[\s\u00a0]+$/, '');
// put back the line breaks in pre|script
content = content.replace(/<wp_temp>/g, '\n');
return content;
},
_wp_Autop : function(pee) {
var blocklist = 'table|thead|tfoot|tbody|tr|td|th|caption|col|colgroup|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|address|math|p|h[1-6]|fieldset|legend|hr|noscript|menu|samp|header|footer|article|section|hgroup|nav|aside|details|summary';
if ( pee.indexOf('<object') != -1 ) {
pee = pee.replace(/<object[\s\S]+?<\/object>/g, function(a){
return a.replace(/[\r\n]+/g, '');
});
}
pee = pee.replace(/<[^<>]+>/g, function(a){
return a.replace(/[\r\n]+/g, ' ');
});
// Protect pre|script tags
if ( pee.indexOf('<pre') != -1 || pee.indexOf('<script') != -1 ) {
pee = pee.replace(/<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function(a) {
return a.replace(/(\r\n|\n)/g, '<wp_temp_br>');
});
}
pee = pee + '\n\n';
pee = pee.replace(/<br \/>\s*<br \/>/gi, '\n\n');
pee = pee.replace(new RegExp('(<(?:'+blocklist+')(?: [^>]*)?>)', 'gi'), '\n$1');
pee = pee.replace(new RegExp('(</(?:'+blocklist+')>)', 'gi'), '$1\n\n');
pee = pee.replace(/<hr( [^>]*)?>/gi, '<hr$1>\n\n'); // hr is self closing block element
pee = pee.replace(/\r\n|\r/g, '\n');
pee = pee.replace(/\n\s*\n+/g, '\n\n');
pee = pee.replace(/([\s\S]+?)\n\n/g, '<p>$1</p>\n');
pee = pee.replace(/<p>\s*?<\/p>/gi, '');
pee = pee.replace(new RegExp('<p>\\s*(</?(?:'+blocklist+')(?: [^>]*)?>)\\s*</p>', 'gi'), "$1");
pee = pee.replace(/<p>(<li.+?)<\/p>/gi, '$1');
pee = pee.replace(/<p>\s*<blockquote([^>]*)>/gi, '<blockquote$1><p>');
pee = pee.replace(/<\/blockquote>\s*<\/p>/gi, '</p></blockquote>');
pee = pee.replace(new RegExp('<p>\\s*(</?(?:'+blocklist+')(?: [^>]*)?>)', 'gi'), "$1");
pee = pee.replace(new RegExp('(</?(?:'+blocklist+')(?: [^>]*)?>)\\s*</p>', 'gi'), "$1");
pee = pee.replace(/\s*\n/gi, '<br />\n');
pee = pee.replace(new RegExp('(</?(?:'+blocklist+')[^>]*>)\\s*<br />', 'gi'), "$1");
pee = pee.replace(/<br \/>(\s*<\/?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)>)/gi, '$1');
pee = pee.replace(/(?:<p>|<br ?\/?>)*\s*\[caption([^\[]+)\[\/caption\]\s*(?:<\/p>|<br ?\/?>)*/gi, '[caption$1[/caption]');
pee = pee.replace(/(<(?:div|th|td|form|fieldset|dd)[^>]*>)(.*?)<\/p>/g, function(a, b, c) {
if ( c.match(/<p( [^>]*)?>/) )
return a;
return b + '<p>' + c + '</p>';
});
// put back the line breaks in pre|script
pee = pee.replace(/<wp_temp_br>/g, '\n');
return pee;
},
pre_wpautop : function(content) {
var t = this, o = { o: t, data: content, unfiltered: content },
q = typeof(jQuery) != 'undefined';
if ( q )
jQuery('body').trigger('beforePreWpautop', [o]);
o.data = t._wp_Nop(o.data);
if ( q )
jQuery('body').trigger('afterPreWpautop', [o]);
return o.data;
},
wpautop : function(pee) {
var t = this, o = { o: t, data: pee, unfiltered: pee },
q = typeof(jQuery) != 'undefined';
if ( q )
jQuery('body').trigger('beforeWpautop', [o]);
o.data = t._wp_Autop(o.data);
if ( q )
jQuery('body').trigger('afterWpautop', [o]);
return o.data;
}
}
| JavaScript |
jQuery(document).ready( function($) {
var newCat, noSyncChecks = false, syncChecks, catAddAfter;
$('#link_name').focus();
// postboxes
postboxes.add_postbox_toggles('link');
// category tabs
$('#category-tabs a').click(function(){
var t = $(this).attr('href');
$(this).parent().addClass('tabs').siblings('li').removeClass('tabs');
$('.tabs-panel').hide();
$(t).show();
if ( '#categories-all' == t )
deleteUserSetting('cats');
else
setUserSetting('cats','pop');
return false;
});
if ( getUserSetting('cats') )
$('#category-tabs a[href="#categories-pop"]').click();
// Ajax Cat
newCat = $('#newcat').one( 'focus', function() { $(this).val( '' ).removeClass( 'form-input-tip' ) } );
$('#category-add-submit').click( function() { newCat.focus(); } );
syncChecks = function() {
if ( noSyncChecks )
return;
noSyncChecks = true;
var th = $(this), c = th.is(':checked'), id = th.val().toString();
$('#in-link-category-' + id + ', #in-popular-category-' + id).prop( 'checked', c );
noSyncChecks = false;
};
catAddAfter = function( r, s ) {
$(s.what + ' response_data', r).each( function() {
var t = $($(this).text());
t.find( 'label' ).each( function() {
var th = $(this), val = th.find('input').val(), id = th.find('input')[0].id, name = $.trim( th.text() ), o;
$('#' + id).change( syncChecks );
o = $( '<option value="' + parseInt( val, 10 ) + '"></option>' ).text( name );
} );
} );
};
$('#categorychecklist').wpList( {
alt: '',
what: 'link-category',
response: 'category-ajax-response',
addAfter: catAddAfter
} );
$('a[href="#categories-all"]').click(function(){deleteUserSetting('cats');});
$('a[href="#categories-pop"]').click(function(){setUserSetting('cats','pop');});
if ( 'pop' == getUserSetting('cats') )
$('a[href="#categories-pop"]').click();
$('#category-add-toggle').click( function() {
$(this).parents('div:first').toggleClass( 'wp-hidden-children' );
$('#category-tabs a[href="#categories-all"]').click();
$('#newcategory').focus();
return false;
} );
$('.categorychecklist :checkbox').change( syncChecks ).filter( ':checked' ).change();
});
| JavaScript |
var thickDims, tbWidth, tbHeight;
jQuery(document).ready(function($) {
thickDims = function() {
var tbWindow = $('#TB_window'), H = $(window).height(), W = $(window).width(), w, h;
w = (tbWidth && tbWidth < W - 90) ? tbWidth : W - 90;
h = (tbHeight && tbHeight < H - 60) ? tbHeight : H - 60;
if ( tbWindow.size() ) {
tbWindow.width(w).height(h);
$('#TB_iframeContent').width(w).height(h - 27);
tbWindow.css({'margin-left': '-' + parseInt((w / 2),10) + 'px'});
if ( typeof document.body.style.maxWidth != 'undefined' )
tbWindow.css({'top':'30px','margin-top':'0'});
}
};
thickDims();
$(window).resize( function() { thickDims() } );
$('a.thickbox-preview').click( function() {
tb_click.call(this);
var alink = $(this).parents('.available-theme').find('.activatelink'), link = '', href = $(this).attr('href'), url, text;
if ( tbWidth = href.match(/&tbWidth=[0-9]+/) )
tbWidth = parseInt(tbWidth[0].replace(/[^0-9]+/g, ''), 10);
else
tbWidth = $(window).width() - 90;
if ( tbHeight = href.match(/&tbHeight=[0-9]+/) )
tbHeight = parseInt(tbHeight[0].replace(/[^0-9]+/g, ''), 10);
else
tbHeight = $(window).height() - 60;
if ( alink.length ) {
url = alink.attr('href') || '';
text = alink.attr('title') || '';
link = ' <a href="' + url + '" target="_top" class="tb-theme-preview-link">' + text + '</a>';
} else {
text = $(this).attr('title') || '';
link = ' <span class="tb-theme-preview-link">' + text + '</span>';
}
$('#TB_title').css({'background-color':'#222','color':'#dfdfdf'});
$('#TB_closeAjaxWindow').css({'float':'left'});
$('#TB_ajaxWindowTitle').css({'float':'right'}).html(link);
$('#TB_iframeContent').width('100%');
thickDims();
return false;
} );
// Theme details
$('.theme-detail').click(function () {
$(this).siblings('.themedetaildiv').toggle();
return false;
});
});
| JavaScript |
jQuery(document).ready( function($) {
var before, addBefore, addAfter, delBefore;
before = function() {
var nonce = $('#newmeta [name="_ajax_nonce"]').val(), postId = $('#post_ID').val();
if ( !nonce || !postId ) { return false; }
return [nonce,postId];
}
addBefore = function( s ) {
var b = before();
if ( !b ) { return false; }
s.data = s.data.replace(/_ajax_nonce=[a-f0-9]+/, '_ajax_nonce=' + b[0]) + '&post_id=' + b[1];
return s;
};
addAfter = function( r, s ) {
var postId = $('postid', r).text(), h;
if ( !postId ) { return; }
$('#post_ID').attr( 'name', 'post_ID' ).val( postId );
h = $('#hiddenaction');
if ( 'post' == h.val() ) { h.val( 'postajaxpost' ); }
};
delBefore = function( s ) {
var b = before(); if ( !b ) return false;
s.data._ajax_nonce = b[0]; s.data.post_id = b[1];
return s;
}
$('#the-list')
.wpList( { addBefore: addBefore, addAfter: addAfter, delBefore: delBefore } )
.find('.updatemeta, .deletemeta').attr( 'type', 'button' );
} );
| JavaScript |
// Password strength meter
function passwordStrength(password1, username, password2) {
var shortPass = 1, badPass = 2, goodPass = 3, strongPass = 4, mismatch = 5, symbolSize = 0, natLog, score;
// password 1 != password 2
if ( (password1 != password2) && password2.length > 0)
return mismatch
//password < 4
if ( password1.length < 4 )
return shortPass
//password1 == username
if ( password1.toLowerCase() == username.toLowerCase() )
return badPass;
if ( password1.match(/[0-9]/) )
symbolSize +=10;
if ( password1.match(/[a-z]/) )
symbolSize +=26;
if ( password1.match(/[A-Z]/) )
symbolSize +=26;
if ( password1.match(/[^a-zA-Z0-9]/) )
symbolSize +=31;
natLog = Math.log( Math.pow(symbolSize, password1.length) );
score = natLog / Math.LN2;
if (score < 40 )
return badPass
if (score < 56 )
return goodPass
return strongPass;
}
| JavaScript |
jQuery(document).ready( function($) {
$('#link_rel').prop('readonly', true);
$('#linkxfndiv input').bind('click keyup', function() {
var isMe = $('#me').is(':checked'), inputs = '';
$('input.valinp').each( function() {
if (isMe) {
$(this).prop('disabled', true).parent().addClass('disabled');
} else {
$(this).removeAttr('disabled').parent().removeClass('disabled');
if ( $(this).is(':checked') && $(this).val() != '')
inputs += $(this).val() + ' ';
}
});
$('#link_rel').val( (isMe) ? 'me' : inputs.substr(0,inputs.length - 1) );
});
});
| JavaScript |
jQuery(document).ready(function($) {
var options = false, addAfter, delBefore, delAfter;
if ( document.forms['addcat'].category_parent )
options = document.forms['addcat'].category_parent.options;
addAfter = function( r, settings ) {
var name, id;
name = $("<span>" + $('name', r).text() + "</span>").text();
id = $('cat', r).attr('id');
options[options.length] = new Option(name, id);
}
delAfter = function( r, settings ) {
var id = $('cat', r).attr('id'), o;
for ( o = 0; o < options.length; o++ )
if ( id == options[o].value )
options[o] = null;
}
delBefore = function(s) {
if ( 'undefined' != showNotice )
return showNotice.warn() ? s : false;
return s;
}
if ( options )
$('#the-list').wpList( { addAfter: addAfter, delBefore: delBefore, delAfter: delAfter } );
else
$('#the-list').wpList({ delBefore: delBefore });
$('.delete a[class^="delete"]').live('click', function(){return false;});
});
| JavaScript |
var ThemeViewer;
(function($){
ThemeViewer = function( args ) {
function init() {
$( '#filter-click, #mini-filter-click' ).unbind( 'click' ).click( function() {
$( '#filter-click' ).toggleClass( 'current' );
$( '#filter-box' ).slideToggle();
$( '#current-theme' ).slideToggle( 300 );
return false;
});
$( '#filter-box :checkbox' ).unbind( 'click' ).click( function() {
var count = $( '#filter-box :checked' ).length,
text = $( '#filter-click' ).text();
if ( text.indexOf( '(' ) != -1 )
text = text.substr( 0, text.indexOf( '(' ) );
if ( count == 0 )
$( '#filter-click' ).text( text );
else
$( '#filter-click' ).text( text + ' (' + count + ')' );
});
/* $('#filter-box :submit').unbind( 'click' ).click(function() {
var features = [];
$('#filter-box :checked').each(function() {
features.push($(this).val());
});
listTable.update_rows({'features': features}, true, function() {
$( '#filter-click' ).toggleClass( 'current' );
$( '#filter-box' ).slideToggle();
$( '#current-theme' ).slideToggle( 300 );
});
return false;
}); */
}
// These are the functions we expose
var api = {
init: init
};
return api;
}
})(jQuery);
jQuery( document ).ready( function($) {
theme_viewer = new ThemeViewer();
theme_viewer.init();
});
| JavaScript |
var imageEdit;
(function($) {
imageEdit = {
iasapi : {},
hold : {},
postid : '',
intval : function(f) {
return f | 0;
},
setDisabled : function(el, s) {
if ( s ) {
el.removeClass('disabled');
$('input', el).removeAttr('disabled');
} else {
el.addClass('disabled');
$('input', el).prop('disabled', true);
}
},
init : function(postid, nonce) {
var t = this, old = $('#image-editor-' + t.postid),
x = t.intval( $('#imgedit-x-' + postid).val() ),
y = t.intval( $('#imgedit-y-' + postid).val() );
if ( t.postid != postid && old.length )
t.close(t.postid);
t.hold['w'] = t.hold['ow'] = x;
t.hold['h'] = t.hold['oh'] = y;
t.hold['xy_ratio'] = x / y;
t.hold['sizer'] = parseFloat( $('#imgedit-sizer-' + postid).val() );
t.postid = postid;
$('#imgedit-response-' + postid).empty();
$('input[type="text"]', '#imgedit-panel-' + postid).keypress(function(e) {
var k = e.keyCode;
if ( 36 < k && k < 41 )
$(this).blur()
if ( 13 == k ) {
e.preventDefault();
e.stopPropagation();
return false;
}
});
},
toggleEditor : function(postid, toggle) {
var wait = $('#imgedit-wait-' + postid);
if ( toggle )
wait.height( $('#imgedit-panel-' + postid).height() ).fadeIn('fast');
else
wait.fadeOut('fast');
},
toggleHelp : function(el) {
$(el).siblings('.imgedit-help').slideToggle('fast');
return false;
},
getTarget : function(postid) {
return $('input[name="imgedit-target-' + postid + '"]:checked', '#imgedit-save-target-' + postid).val() || 'full';
},
scaleChanged : function(postid, x) {
var w = $('#imgedit-scale-width-' + postid), h = $('#imgedit-scale-height-' + postid),
warn = $('#imgedit-scale-warn-' + postid), w1 = '', h1 = '';
if ( x ) {
h1 = (w.val() != '') ? this.intval( w.val() / this.hold['xy_ratio'] ) : '';
h.val( h1 );
} else {
w1 = (h.val() != '') ? this.intval( h.val() * this.hold['xy_ratio'] ) : '';
w.val( w1 );
}
if ( ( h1 && h1 > this.hold['oh'] ) || ( w1 && w1 > this.hold['ow'] ) )
warn.css('visibility', 'visible');
else
warn.css('visibility', 'hidden');
},
getSelRatio : function(postid) {
var x = this.hold['w'], y = this.hold['h'],
X = this.intval( $('#imgedit-crop-width-' + postid).val() ),
Y = this.intval( $('#imgedit-crop-height-' + postid).val() );
if ( X && Y )
return X + ':' + Y;
if ( x && y )
return x + ':' + y;
return '1:1';
},
filterHistory : function(postid, setSize) {
// apply undo state to history
var history = $('#imgedit-history-' + postid).val(), pop, n, o, i, op = [];
if ( history != '' ) {
history = JSON.parse(history);
pop = this.intval( $('#imgedit-undone-' + postid).val() );
if ( pop > 0 ) {
while ( pop > 0 ) {
history.pop();
pop--;
}
}
if ( setSize ) {
if ( !history.length ) {
this.hold['w'] = this.hold['ow'];
this.hold['h'] = this.hold['oh'];
return '';
}
// restore
o = history[history.length - 1];
o = o.c || o.r || o.f || false;
if ( o ) {
this.hold['w'] = o.fw;
this.hold['h'] = o.fh;
}
}
// filter the values
for ( n in history ) {
i = history[n];
if ( i.hasOwnProperty('c') ) {
op[n] = { 'c': { 'x': i.c.x, 'y': i.c.y, 'w': i.c.w, 'h': i.c.h } };
} else if ( i.hasOwnProperty('r') ) {
op[n] = { 'r': i.r.r };
} else if ( i.hasOwnProperty('f') ) {
op[n] = { 'f': i.f.f };
}
}
return JSON.stringify(op);
}
return '';
},
refreshEditor : function(postid, nonce, callback) {
var t = this, data, img;
t.toggleEditor(postid, 1);
data = {
'action': 'imgedit-preview',
'_ajax_nonce': nonce,
'postid': postid,
'history': t.filterHistory(postid, 1),
'rand': t.intval(Math.random() * 1000000)
};
img = $('<img id="image-preview-' + postid + '" />');
img.load( function() {
var max1, max2, parent = $('#imgedit-crop-' + postid), t = imageEdit;
parent.empty().append(img);
// w, h are the new full size dims
max1 = Math.max( t.hold.w, t.hold.h );
max2 = Math.max( $(img).width(), $(img).height() );
t.hold['sizer'] = max1 > max2 ? max2 / max1 : 1;
t.initCrop(postid, img, parent);
t.setCropSelection(postid, 0);
if ( (typeof callback != "unknown") && callback != null )
callback();
if ( $('#imgedit-history-' + postid).val() && $('#imgedit-undone-' + postid).val() == 0 )
$('input.imgedit-submit-btn', '#imgedit-panel-' + postid).removeAttr('disabled');
else
$('input.imgedit-submit-btn', '#imgedit-panel-' + postid).prop('disabled', true);
t.toggleEditor(postid, 0);
}).error(function(){
$('#imgedit-crop-' + postid).empty().append('<div class="error"><p>' + imageEditL10n.error + '</p></div>');
t.toggleEditor(postid, 0);
}).attr('src', ajaxurl + '?' + $.param(data));
},
action : function(postid, nonce, action) {
var t = this, data, w, h, fw, fh;
if ( t.notsaved(postid) )
return false;
data = {
'action': 'image-editor',
'_ajax_nonce': nonce,
'postid': postid
};
if ( 'scale' == action ) {
w = $('#imgedit-scale-width-' + postid),
h = $('#imgedit-scale-height-' + postid),
fw = t.intval(w.val()),
fh = t.intval(h.val());
if ( fw < 1 ) {
w.focus();
return false;
} else if ( fh < 1 ) {
h.focus();
return false;
}
if ( fw == t.hold.ow || fh == t.hold.oh )
return false;
data['do'] = 'scale';
data['fwidth'] = fw;
data['fheight'] = fh;
} else if ( 'restore' == action ) {
data['do'] = 'restore';
} else {
return false;
}
t.toggleEditor(postid, 1);
$.post(ajaxurl, data, function(r) {
$('#image-editor-' + postid).empty().append(r);
t.toggleEditor(postid, 0);
});
},
save : function(postid, nonce) {
var data, target = this.getTarget(postid), history = this.filterHistory(postid, 0);
if ( '' == history )
return false;
this.toggleEditor(postid, 1);
data = {
'action': 'image-editor',
'_ajax_nonce': nonce,
'postid': postid,
'history': history,
'target': target,
'do': 'save'
};
$.post(ajaxurl, data, function(r) {
var ret = JSON.parse(r);
if ( ret.error ) {
$('#imgedit-response-' + postid).html('<div class="error"><p>' + ret.error + '</p><div>');
imageEdit.close(postid);
return;
}
if ( ret.fw && ret.fh )
$('#media-dims-' + postid).html( ret.fw + ' × ' + ret.fh );
if ( ret.thumbnail )
$('.thumbnail', '#thumbnail-head-' + postid).attr('src', ''+ret.thumbnail);
if ( ret.msg )
$('#imgedit-response-' + postid).html('<div class="updated"><p>' + ret.msg + '</p></div>');
imageEdit.close(postid);
});
},
open : function(postid, nonce) {
var data, elem = $('#image-editor-' + postid), head = $('#media-head-' + postid),
btn = $('#imgedit-open-btn-' + postid), spin = btn.siblings('img');
btn.prop('disabled', true);
spin.css('visibility', 'visible');
data = {
'action': 'image-editor',
'_ajax_nonce': nonce,
'postid': postid,
'do': 'open'
};
elem.load(ajaxurl, data, function() {
elem.fadeIn('fast');
head.fadeOut('fast', function(){
btn.removeAttr('disabled');
spin.css('visibility', 'hidden');
});
});
},
imgLoaded : function(postid) {
var img = $('#image-preview-' + postid), parent = $('#imgedit-crop-' + postid);
this.initCrop(postid, img, parent);
this.setCropSelection(postid, 0);
this.toggleEditor(postid, 0);
},
initCrop : function(postid, image, parent) {
var t = this, selW = $('#imgedit-sel-width-' + postid),
selH = $('#imgedit-sel-height-' + postid);
t.iasapi = $(image).imgAreaSelect({
parent: parent,
instance: true,
handles: true,
keys: true,
minWidth: 3,
minHeight: 3,
onInit: function(img, c) {
parent.children().mousedown(function(e){
var ratio = false, sel, defRatio;
if ( e.shiftKey ) {
sel = t.iasapi.getSelection();
defRatio = t.getSelRatio(postid);
ratio = ( sel && sel.width && sel.height ) ? sel.width + ':' + sel.height : defRatio;
}
t.iasapi.setOptions({
aspectRatio: ratio
});
});
},
onSelectStart: function(img, c) {
imageEdit.setDisabled($('#imgedit-crop-sel-' + postid), 1);
},
onSelectEnd: function(img, c) {
imageEdit.setCropSelection(postid, c);
},
onSelectChange: function(img, c) {
var sizer = imageEdit.hold.sizer;
selW.val( imageEdit.round(c.width / sizer) );
selH.val( imageEdit.round(c.height / sizer) );
}
});
},
setCropSelection : function(postid, c) {
var sel, min = $('#imgedit-minthumb-' + postid).val() || '128:128',
sizer = this.hold['sizer'];
min = min.split(':');
c = c || 0;
if ( !c || ( c.width < 3 && c.height < 3 ) ) {
this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 0);
this.setDisabled($('#imgedit-crop-sel-' + postid), 0);
$('#imgedit-sel-width-' + postid).val('');
$('#imgedit-sel-height-' + postid).val('');
$('#imgedit-selection-' + postid).val('');
return false;
}
if ( c.width < (min[0] * sizer) && c.height < (min[1] * sizer) ) {
this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 0);
$('#imgedit-selection-' + postid).val('');
return false;
}
sel = { 'x': c.x1, 'y': c.y1, 'w': c.width, 'h': c.height };
this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 1);
$('#imgedit-selection-' + postid).val( JSON.stringify(sel) );
},
close : function(postid, warn) {
warn = warn || false;
if ( warn && this.notsaved(postid) )
return false;
this.iasapi = {};
this.hold = {};
$('#image-editor-' + postid).fadeOut('fast', function() {
$('#media-head-' + postid).fadeIn('fast');
$(this).empty();
});
},
notsaved : function(postid) {
var h = $('#imgedit-history-' + postid).val(),
history = (h != '') ? JSON.parse(h) : new Array(),
pop = this.intval( $('#imgedit-undone-' + postid).val() );
if ( pop < history.length ) {
if ( confirm( $('#imgedit-leaving-' + postid).html() ) )
return false;
return true;
}
return false;
},
addStep : function(op, postid, nonce) {
var t = this, elem = $('#imgedit-history-' + postid),
history = (elem.val() != '') ? JSON.parse(elem.val()) : new Array(),
undone = $('#imgedit-undone-' + postid),
pop = t.intval(undone.val());
while ( pop > 0 ) {
history.pop();
pop--;
}
undone.val(0); // reset
history.push(op);
elem.val( JSON.stringify(history) );
t.refreshEditor(postid, nonce, function() {
t.setDisabled($('#image-undo-' + postid), true);
t.setDisabled($('#image-redo-' + postid), false);
});
},
rotate : function(angle, postid, nonce, t) {
if ( $(t).hasClass('disabled') )
return false;
this.addStep({ 'r': { 'r': angle, 'fw': this.hold['h'], 'fh': this.hold['w'] }}, postid, nonce);
},
flip : function (axis, postid, nonce, t) {
if ( $(t).hasClass('disabled') )
return false;
this.addStep({ 'f': { 'f': axis, 'fw': this.hold['w'], 'fh': this.hold['h'] }}, postid, nonce);
},
crop : function (postid, nonce, t) {
var sel = $('#imgedit-selection-' + postid).val(),
w = this.intval( $('#imgedit-sel-width-' + postid).val() ),
h = this.intval( $('#imgedit-sel-height-' + postid).val() );
if ( $(t).hasClass('disabled') || sel == '' )
return false;
sel = JSON.parse(sel);
if ( sel.w > 0 && sel.h > 0 && w > 0 && h > 0 ) {
sel['fw'] = w;
sel['fh'] = h;
this.addStep({ 'c': sel }, postid, nonce);
}
},
undo : function (postid, nonce) {
var t = this, button = $('#image-undo-' + postid), elem = $('#imgedit-undone-' + postid),
pop = t.intval( elem.val() ) + 1;
if ( button.hasClass('disabled') )
return;
elem.val(pop);
t.refreshEditor(postid, nonce, function() {
var elem = $('#imgedit-history-' + postid),
history = (elem.val() != '') ? JSON.parse(elem.val()) : new Array();
t.setDisabled($('#image-redo-' + postid), true);
t.setDisabled(button, pop < history.length);
});
},
redo : function(postid, nonce) {
var t = this, button = $('#image-redo-' + postid), elem = $('#imgedit-undone-' + postid),
pop = t.intval( elem.val() ) - 1;
if ( button.hasClass('disabled') )
return;
elem.val(pop);
t.refreshEditor(postid, nonce, function() {
t.setDisabled($('#image-undo-' + postid), true);
t.setDisabled(button, pop > 0);
});
},
setNumSelection : function(postid) {
var sel, elX = $('#imgedit-sel-width-' + postid), elY = $('#imgedit-sel-height-' + postid),
x = this.intval( elX.val() ), y = this.intval( elY.val() ),
img = $('#image-preview-' + postid), imgh = img.height(), imgw = img.width(),
sizer = this.hold['sizer'], x1, y1, x2, y2, ias = this.iasapi;
if ( x < 1 ) {
elX.val('');
return false;
}
if ( y < 1 ) {
elY.val('');
return false;
}
if ( x && y && ( sel = ias.getSelection() ) ) {
x2 = sel.x1 + Math.round( x * sizer );
y2 = sel.y1 + Math.round( y * sizer );
x1 = sel.x1;
y1 = sel.y1;
if ( x2 > imgw ) {
x1 = 0;
x2 = imgw;
elX.val( Math.round( x2 / sizer ) );
}
if ( y2 > imgh ) {
y1 = 0;
y2 = imgh;
elY.val( Math.round( y2 / sizer ) );
}
ias.setSelection( x1, y1, x2, y2 );
ias.update();
this.setCropSelection(postid, ias.getSelection());
}
},
round : function(num) {
var s;
num = Math.round(num);
if ( this.hold.sizer > 0.6 )
return num;
s = num.toString().slice(-1);
if ( '1' == s )
return num - 1;
else if ( '9' == s )
return num + 1;
return num;
},
setRatioSelection : function(postid, n, el) {
var sel, r, x = this.intval( $('#imgedit-crop-width-' + postid).val() ),
y = this.intval( $('#imgedit-crop-height-' + postid).val() ),
h = $('#image-preview-' + postid).height();
if ( !this.intval( $(el).val() ) ) {
$(el).val('');
return;
}
if ( x && y ) {
this.iasapi.setOptions({
aspectRatio: x + ':' + y
});
if ( sel = this.iasapi.getSelection(true) ) {
r = Math.ceil( sel.y1 + ((sel.x2 - sel.x1) / (x / y)) );
if ( r > h ) {
r = h;
if ( n )
$('#imgedit-crop-height-' + postid).val('');
else
$('#imgedit-crop-width-' + postid).val('');
}
this.iasapi.setSelection( sel.x1, sel.y1, sel.x2, r );
this.iasapi.update();
}
}
}
}
})(jQuery);
| JavaScript |
jQuery(document).ready(function($) {
$('.delete-tag').live('click', function(e){
var t = $(this), tr = t.parents('tr'), r = true, data;
if ( 'undefined' != showNotice )
r = showNotice.warn();
if ( r ) {
data = t.attr('href').replace(/[^?]*\?/, '').replace(/action=delete/, 'action=delete-tag');
$.post(ajaxurl, data, function(r){
if ( '1' == r ) {
$('#ajax-response').empty();
tr.fadeOut('normal', function(){ tr.remove(); });
// Remove the term from the parent box and tag cloud
$('select#parent option[value="' + data.match(/tag_ID=(\d+)/)[1] + '"]').remove();
$('a.tag-link-' + data.match(/tag_ID=(\d+)/)[1]).remove();
} else if ( '-1' == r ) {
$('#ajax-response').empty().append('<div class="error"><p>' + tagsl10n.noPerm + '</p></div>');
tr.children().css('backgroundColor', '');
} else {
$('#ajax-response').empty().append('<div class="error"><p>' + tagsl10n.broken + '</p></div>');
tr.children().css('backgroundColor', '');
}
});
tr.children().css('backgroundColor', '#f33');
}
return false;
});
$('#submit').click(function(){
var form = $(this).parents('form');
if ( !validateForm( form ) )
return false;
$.post(ajaxurl, $('#addtag').serialize(), function(r){
$('#ajax-response').empty();
var res = wpAjax.parseAjaxResponse(r, 'ajax-response');
if ( ! res )
return;
var parent = form.find('select#parent').val();
if ( parent > 0 && $('#tag-' + parent ).length > 0 ) // If the parent exists on this page, insert it below. Else insert it at the top of the list.
$('.tags #tag-' + parent).after( res.responses[0].supplemental['noparents'] ); // As the parent exists, Insert the version with - - - prefixed
else
$('.tags').prepend( res.responses[0].supplemental['parents'] ); // As the parent is not visible, Insert the version with Parent - Child - ThisTerm
$('.tags .no-items').remove();
if ( form.find('select#parent') ) {
// Parents field exists, Add new term to the list.
var term = res.responses[1].supplemental;
// Create an indent for the Parent field
var indent = '';
for ( var i = 0; i < res.responses[1].position; i++ )
indent += ' ';
form.find('select#parent option:selected').after('<option value="' + term['term_id'] + '">' + indent + term['name'] + '</option>');
}
$('input[type="text"]:visible, textarea:visible', form).val('');
});
return false;
});
});
| JavaScript |
(function($) {
inlineEditPost = {
init : function(){
var t = this, qeRow = $('#inline-edit'), bulkRow = $('#bulk-edit');
t.type = $('table.widefat').hasClass('pages') ? 'page' : 'post';
t.what = '#post-';
// prepare the edit rows
qeRow.keyup(function(e){
if (e.which == 27)
return inlineEditPost.revert();
});
bulkRow.keyup(function(e){
if (e.which == 27)
return inlineEditPost.revert();
});
$('a.cancel', qeRow).click(function(){
return inlineEditPost.revert();
});
$('a.save', qeRow).click(function(){
return inlineEditPost.save(this);
});
$('td', qeRow).keydown(function(e){
if ( e.which == 13 )
return inlineEditPost.save(this);
});
$('a.cancel', bulkRow).click(function(){
return inlineEditPost.revert();
});
$('#inline-edit .inline-edit-private input[value="private"]').click( function(){
var pw = $('input.inline-edit-password-input');
if ( $(this).prop('checked') ) {
pw.val('').prop('disabled', true);
} else {
pw.prop('disabled', false);
}
});
// add events
$('a.editinline').live('click', function(){
inlineEditPost.edit(this);
return false;
});
$('#bulk-title-div').parents('fieldset').after(
$('#inline-edit fieldset.inline-edit-categories').clone()
).siblings( 'fieldset:last' ).prepend(
$('#inline-edit label.inline-edit-tags').clone()
);
// hiearchical taxonomies expandable?
$('span.catshow').click(function(){
$(this).hide().next().show().parent().next().addClass("cat-hover");
});
$('span.cathide').click(function(){
$(this).hide().prev().show().parent().next().removeClass("cat-hover");
});
$('select[name="_status"] option[value="future"]', bulkRow).remove();
$('#doaction, #doaction2').click(function(e){
var n = $(this).attr('id').substr(2);
if ( $('select[name="'+n+'"]').val() == 'edit' ) {
e.preventDefault();
t.setBulk();
} else if ( $('form#posts-filter tr.inline-editor').length > 0 ) {
t.revert();
}
});
$('#post-query-submit').mousedown(function(e){
t.revert();
$('select[name^="action"]').val('-1');
});
},
toggle : function(el){
var t = this;
$(t.what+t.getId(el)).css('display') == 'none' ? t.revert() : t.edit(el);
},
setBulk : function(){
var te = '', type = this.type, tax, c = true;
this.revert();
$('#bulk-edit td').attr('colspan', $('.widefat:first thead th:visible').length);
$('table.widefat tbody').prepend( $('#bulk-edit') );
$('#bulk-edit').addClass('inline-editor').show();
$('tbody th.check-column input[type="checkbox"]').each(function(i){
if ( $(this).prop('checked') ) {
c = false;
var id = $(this).val(), theTitle;
theTitle = $('#inline_'+id+' .post_title').text() || inlineEditL10n.notitle;
te += '<div id="ttle'+id+'"><a id="_'+id+'" class="ntdelbutton" title="'+inlineEditL10n.ntdeltitle+'">X</a>'+theTitle+'</div>';
}
});
if ( c )
return this.revert();
$('#bulk-titles').html(te);
$('#bulk-titles a').click(function(){
var id = $(this).attr('id').substr(1);
$('table.widefat input[value="' + id + '"]').prop('checked', false);
$('#ttle'+id).remove();
});
// enable autocomplete for tags
if ( 'post' == type ) {
// support multi taxonomies?
tax = 'post_tag';
$('tr.inline-editor textarea[name="tax_input['+tax+']"]').suggest( 'admin-ajax.php?action=ajax-tag-search&tax='+tax, { delay: 500, minchars: 2, multiple: true, multipleSep: ", " } );
}
$('html, body').animate( { scrollTop: 0 }, 'fast' );
},
edit : function(id) {
var t = this, fields, editRow, rowData, status, pageOpt, pageLevel, nextPage, pageLoop = true, nextLevel, cur_format, f;
t.revert();
if ( typeof(id) == 'object' )
id = t.getId(id);
fields = ['post_title', 'post_name', 'post_author', '_status', 'jj', 'mm', 'aa', 'hh', 'mn', 'ss', 'post_password', 'post_format'];
if ( t.type == 'page' )
fields.push('post_parent', 'menu_order', 'page_template');
// add the new blank row
editRow = $('#inline-edit').clone(true);
$('td', editRow).attr('colspan', $('.widefat:first thead th:visible').length);
if ( $(t.what+id).hasClass('alternate') )
$(editRow).addClass('alternate');
$(t.what+id).hide().after(editRow);
// populate the data
rowData = $('#inline_'+id);
if ( !$(':input[name="post_author"] option[value="' + $('.post_author', rowData).text() + '"]', editRow).val() ) {
// author no longer has edit caps, so we need to add them to the list of authors
$(':input[name="post_author"]', editRow).prepend('<option value="' + $('.post_author', rowData).text() + '">' + $('#' + t.type + '-' + id + ' .author').text() + '</option>');
}
if ( $(':input[name="post_author"] option', editRow).length == 1 ) {
$('label.inline-edit-author', editRow).hide();
}
// hide unsupported formats, but leave the current format alone
cur_format = $('.post_format', rowData).text();
$('option.unsupported', editRow).each(function() {
var $this = $(this);
if ( $this.val() != cur_format )
$this.remove();
});
for ( f = 0; f < fields.length; f++ ) {
$(':input[name="' + fields[f] + '"]', editRow).val( $('.'+fields[f], rowData).text() );
}
if ( $('.comment_status', rowData).text() == 'open' )
$('input[name="comment_status"]', editRow).prop("checked", true);
if ( $('.ping_status', rowData).text() == 'open' )
$('input[name="ping_status"]', editRow).prop("checked", true);
if ( $('.sticky', rowData).text() == 'sticky' )
$('input[name="sticky"]', editRow).prop("checked", true);
// hierarchical taxonomies
$('.post_category', rowData).each(function(){
var term_ids = $(this).text();
if ( term_ids ) {
taxname = $(this).attr('id').replace('_'+id, '');
$('ul.'+taxname+'-checklist :checkbox', editRow).val(term_ids.split(','));
}
});
//flat taxonomies
$('.tags_input', rowData).each(function(){
var terms = $(this).text(),
taxname = $(this).attr('id').replace('_' + id, ''),
textarea = $('textarea.tax_input_' + taxname, editRow);
if ( terms )
textarea.val(terms);
textarea.suggest( 'admin-ajax.php?action=ajax-tag-search&tax='+taxname, { delay: 500, minchars: 2, multiple: true, multipleSep: ", " } );
});
// handle the post status
status = $('._status', rowData).text();
if ( 'future' != status )
$('select[name="_status"] option[value="future"]', editRow).remove();
if ( 'private' == status ) {
$('input[name="keep_private"]', editRow).prop("checked", true);
$('input.inline-edit-password-input').val('').prop('disabled', true);
}
// remove the current page and children from the parent dropdown
pageOpt = $('select[name="post_parent"] option[value="' + id + '"]', editRow);
if ( pageOpt.length > 0 ) {
pageLevel = pageOpt[0].className.split('-')[1];
nextPage = pageOpt;
while ( pageLoop ) {
nextPage = nextPage.next('option');
if (nextPage.length == 0) break;
nextLevel = nextPage[0].className.split('-')[1];
if ( nextLevel <= pageLevel ) {
pageLoop = false;
} else {
nextPage.remove();
nextPage = pageOpt;
}
}
pageOpt.remove();
}
$(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();
$('.ptitle', editRow).focus();
return false;
},
save : function(id) {
var params, fields, page = $('.post_status_page').val() || '';
if ( typeof(id) == 'object' )
id = this.getId(id);
$('table.widefat .inline-edit-save .waiting').show();
params = {
action: 'inline-save',
post_type: typenow,
post_ID: id,
edit_date: 'true',
post_status: page
};
fields = $('#edit-'+id+' :input').serialize();
params = fields + '&' + $.param(params);
// make ajax request
$.post('admin-ajax.php', params,
function(r) {
$('table.widefat .inline-edit-save .waiting').hide();
if (r) {
if ( -1 != r.indexOf('<tr') ) {
$(inlineEditPost.what+id).remove();
$('#edit-'+id).before(r).remove();
$(inlineEditPost.what+id).hide().fadeIn();
} else {
r = r.replace( /<.[^<>]*?>/g, '' );
$('#edit-'+id+' .inline-edit-save .error').html(r).show();
}
} else {
$('#edit-'+id+' .inline-edit-save .error').html(inlineEditL10n.error).show();
}
}
, 'html');
return false;
},
revert : function(){
var id = $('table.widefat tr.inline-editor').attr('id');
if ( id ) {
$('table.widefat .inline-edit-save .waiting').hide();
if ( 'bulk-edit' == id ) {
$('table.widefat #bulk-edit').removeClass('inline-editor').hide();
$('#bulk-titles').html('');
$('#inlineedit').append( $('#bulk-edit') );
} else {
$('#'+id).remove();
id = id.substr( id.lastIndexOf('-') + 1 );
$(this.what+id).show();
}
}
return false;
},
getId : function(o) {
var id = $(o).closest('tr').attr('id'),
parts = id.split('-');
return parts[parts.length - 1];
}
};
$(document).ready(function(){inlineEditPost.init();});
})(jQuery);
| JavaScript |
/*
**************************************************************************
_____ _____ _ _
| ____| | _ \ | | / /
| |__ | | | | | |/ /
| __| | | | | | |\ \
| |___ | |_| | | | \ \
|_____| |_____/ |_| \_\
Version: 0.1.1
Author: Frank Cheung
QQ: 799887651
Email: frank@ajaxjs.com
Web: www.ajaxjs.com
Licenses: Berkeley Software Distribution,BSD
本代码可以免费使用、修改,希望我的程序能为您的工作带来方便,同时请保留以上请息。
BEGIN LICENSE BLOCK
Copyright 版权所有 (c) 2011 Frank Cheung
任何获得本软件副本及相关文档文件(下面简称为“软件”)的个人都可以免费获得不受限制处置本软件的权限,
包括不受限制地使用、复制、修改、合并、出版、分发、重新许可或者销售本软件的副本,
并且在满足下述条件时,允许本软件的受让人获得下述权限:
在本软件的所有或者重要部分中包含上述版权公告信息和本权限公告信息。
本软件不提供保证,不包含任何类型的保证(无论是明指的还是暗喻的),
包含但不限于关于本软件的适销性、特定用途的适用性和无侵权保证。
在任何情况下,无论是否签订了合约、存在侵权行为还是在其他情况下,
本软件作者或版权持有人不对由本软件直接或间接产生的
或由使用本软件或处置本软件所产生的任何索赔、损坏或者其他责任。
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
END LICENSE BLOCK
***************************************************************************/
//*************************************************************************
// Edk.js它具备very core的特性。
// 此外,它既可以在客户端运行,也可以满足服务端DSL的要求,一物两用。
//*************************************************************************
/* $$表示Edk,何解?没什么,只是因为Edk不如敲打“$$”来得轻松:) */
if(!this['$$']) $$ = {}; // init Namespace
/**
* Douglas Crockford 基于原型的基础方法。
* Ref. http://javascript.crockford.com/prototypal.html
* newObject = Object.create(oldObject);
* 2008-04-07
* @param {Object} ource 原型对象
*/
Object.create = function(source){
var dummy = source.constructor != Object ? source.constructor : function (){};
dummy.prototype = source;
return new dummy(arguments[1], arguments[2], arguments[3], arguments[4]);
}
/**
* 继承。
* @param {Object} target 子类
* @param {Object} source 父类
*/
Object.inherit = function(target, source){
// 定义继承阶段不要执行构造函数,所以不好使用Object.create()
function dummy(){}
dummy.prototype = source;
var clone = new dummy;
for(var i in target){
clone[i] = target[i];
}
if(target.constructor != Object){
clone.constructor = target.constructor; // patch for JSCript
}
return clone;
}
/**
* 多继承。
*/
Object.mix = function(){
var
baseObj = arguments[0]
,target
,targets = Array.prototype.slice.call(arguments, 1)
,superObj;
/**
* 继承。
* @param {Object} target 子类
* @param {Object} source 父类
*/
function inheritWITHOUTconstructor(target, source){
// 定义继承阶段不要执行构造函数,所以不好使用Object.create()
function dummy(){}
dummy.prototype = source;
var clone = new dummy;
for(var i in target){
clone[i] = target[i];
}
return clone;
}
for(var i = 0, j = targets.length, superObj = baseObj; i < j; i++){
target = targets[i];
if(!target)throw '不存在某个类!';
superObj = inheritWITHOUTconstructor(target, superObj);
}
return superObj;
}
/**
* 将一个数组插入另外一个数组的指定位置
* @param {Array} target
* @param {Number} insertIndex
* @param {Array} arr
* @return {Array}
*/
Array.insert = function(target, insertIndex, arr){
return target.splice.apply(target, Array.concat.call(insertIndex, 0, arr));
}
Array.indexOf = function(arr, el){
for(var i = 0, j = arr.length; i < j; i++){
if(arr[i] == el){
return i;
}
}
return -1;
}
Array.remove = function(arr, el){
var index = Array.indexOf(arr, el);
arr.splice(index, 1);
return el;
}
/**
* 格式化字符串。字符串格式型如:“foo{0}bar{1}……”。
* @param {String []} 可变长度的字符串参数。
* @this {String}
* @return {String}
*/
String.prototype.format = (function(){
var
getSlot = /{(\d+)}/g
,replace = String.prototype.replace
,replaceEl = function(m, i){
return this[i]; // this为arguments
};
return function(){
replaceEl.scope = arguments;// 委托作用域
return replace.call(this, getSlot, replaceEl.delegate());
}
})();
String.trim = function(str){
return str.replace(String.trimReg, '');
};
String.trimReg = /^[\s\t\r\n]+|[\s\t\r\n]+$/g;
/**
* 日期格式化。
* 详见我博客文章:http://blog.csdn.net/zhangxin09/archive/2011/01/01/6111294.aspx
* e.g: new Date().format("yyyy-MM-dd hh:mm:ss")
* @param {String} format
* @return {String}
*/
Date.prototype.format = function(format){
var
$1
,o = {
"M+": this.getMonth() + 1 // 月份,从0开始算
,"d+": this.getDate() // 日期
,"h+": this.getHours() // 小时
,"m+": this.getMinutes() // 分钟
,"s+": this.getSeconds() // 秒钟
// 季度quarter
,"q+": Math.floor((this.getMonth() + 3) / 3)
,"S" : this.getMilliseconds() // 千秒
}
,key
,value;
if (/(y+)/.test(format)) {
$1 = RegExp.$1
,format = format.replace($1, String(this.getFullYear()).substr(4 - $1));
}
// 如果没有指定该参数,则子字符串将延续到 stringvar 的最后。
for (key in o){
if(new RegExp("(" + key + ")").test(format)){
$1 = RegExp.$1
,value = String(o[key])
,value = $1.length == 1 ? value : ("00" + value).substr(value.length)
,format = format.replace($1, value);
}
}
return format;
}
//// 日期功能 by Liu Shuan
//Core.lib.date = function() {
// // 格式化日期
// this.formatDate = function(date, style) {
// style = style || "yyyy-MM-ddThh:mm:ss";
// return style.replace(/y+|M+|d+|h+|m+|s+|w+|q+|S/g, function($0) {
// var temp = 0;
// switch ($0.charAt(0)) {
// case "y" :
// return String(date.getFullYear()).substr(4 - $0.length);
// case "w" :
// return "日一二三四五六".charAt(date.getDay());
// case "q" :
// return Math.floor((date.getMonth() + 3) / 3);
// case "S" :
// return date.getMilliseconds();
//
// case "M" :
// temp = date.getMonth() + 1;
// break;
// case "d" :
// temp = date.getDate();
// break;
// case "h" :
// temp = date.getHours();
// break;
// case "m" :
// temp = date.getMinutes();
// break;
// case "s" :
// temp = date.getSeconds();
// break;
// }
//
// return (temp < 10 && $0.length == 2) ? "0" + temp : temp;
// });
// }
//
// var cache1 = {};
// var cache2 = {};
//
// // 解析出日期
// this.parseDate = function(text, style) {
//
// style = style || "y-M-d";
//
// // 匹配的模板 || 兼缓存
// var pattern = cache1[style] || (cache1[style] = RegExp().compile(style.replace(/([Mdyhms])/g, "(\\d+)")));
//
// // 匹配的顺序 || 兼缓存
// var order = cache2[style]|| (cache2[style] = ("^" + style.replace(/[^Mdyhms]/g, '')).split(''));
//
// // 匹配的项目 || 不可缓存
// var match = pattern.exec(text);
//
// // 匹配的结果 (顺序对应项目)
// var result = {}
// for (var i = 1; i < order.length; i++) {
// result[order[i]] = match[i];
// }
//
// // 按照构造参数进行构造
// var args = "M/d/y h:m:s".replace(/[Mdyhms]/g, function($0) {return result[$0] || 0;});
//
// return new Date(args);
// }
//}
/**
* 继承。
* @param {this} superClass
* @param {Object} subInstance
* @return {Any}
*/
Function.prototype.extend = function(subInstance){
var
superClass = this
,supClassPro = superClass.prototype
,subClassPro = subInstance.constructor.prototype
,result;
// call super
result = superClass.apply(
subClassPro
,Array.prototype.slice.call(arguments, 1)
);
// 遍历父对象的prototype成员拷贝到当前对象的prototype。
for(var i in supClassPro){
subClassPro[i] = supClassPro[i];
}
return result;
}
/**
*
* forece Args! so there's no args, it server as Args!
* 预设函数的作用域。考查下面两个方法:
Function.prototype.delegateScope = function (scope){
var self = this;
return function(){
return self.apply(scope, arguments);
}
}
Function.prototype.delegateArgs = function(){
var
self = this
,args = arguments;
return function(){
return self.apply(this, args);
};
}
* @return {Function}
*/
Function.prototype.delegate = function(){
var
self = this
,scope = this.scope
,args = arguments
,aLength = arguments.length;
return function(){
var
bLength = arguments.length
,Length = (aLength > bLength) ? aLength : bLength;
for(var i = 0; i < Length; i++){
if(arguments[i]){
args[i] = arguments[i];
}
}
// 在 MS jscript下面,rguments作为数字来使用还是有问题,就是length不能自动更新。修正如下:
args.length = Length;
return self.apply(scope || this, args);
};
}
/**
* 修改function的参数。
* @param {Number} argIndex 指定哪一个参数?
* @param {Function} filterFn 修改的函数
* @param {Boolean} isArray 还要指定第几个的参数?
* @return {Function}
*/
Function.prototype.delegateArg = function(argIndex, filterFn, isArray){
var
self = this
,toArray = Array.prototype.slice;
return function(){
var args = toArray.call(arguments, 0); // 变为真正数组。
if(isArray){
args[argIndex] = filterFn.apply(this, arguments);
}else{
args[argIndex] = filterFn.call (this, arguments[argIndex]);
}
return self.apply(this, args);
};
}
/**
* 设置一个后置函数。
* @param {Function} composeFn
* @return {Function}
*/
Function.prototype.after = function(composeFn){
var self = this;
return function(){
var result = self.apply(this, arguments);
return result && (typeof result.pop != 'undefined') && (typeof result.pop != 'unknown')
? composeFn.apply(this, result)
: composeFn.call (this, result);
};
}
/**
* 设置一个前置函数。
* @param {Function} sequenceFn
* @return {Function}
*/
Function.prototype.before = function(sequenceFn){
var self = this;
return function(){
var result = sequenceFn.apply(this, arguments);
return result && (typeof result.pop != 'undefined') && (typeof result.pop != 'unknown')
? self.apply(this, result)
: self.call (this, result);
};
}
/**
* @param {Array} arr
* @return {Function}
*/
Function.prototype.map = function(arr){
var
self = this
,fixArgs = Array.prototype.slice;
return function(){
var
args = fixArgs.call(arguments, 1)
,result;
for(var i = 0, j = arr.length, result = new Array(j); i < j; i++){
result[i] = self.apply(this, args.concat(arr[i]));
}
return result;
}
}
/**
* fn与参数的关系。
* @param {Array} arr
* @param {Object} init
* @param {Any}
*/
Function.prototype.reduce = function(arr, init){
for(var i = 0, j = arr.length; i < j; i++){
init = this.call(init || this, arr[i]);
}
return init;
}
/*
* *----------------*
* Require
* *----------------*
*/
$$.require = function(_package){
if(!_package){
throw "必须输入args对象!";
}else if(arguments.length > 1){
arguments.callee.reduce(arguments);
}else if(_package._tokenString || typeof _package == "string" ){
var filePath = _package._tokenString // get token by Static member
|| _package; // 传入字符串就是资源的路径。
filePath += ".js";
arguments.callee.eval_JS_File(filePath);
}else if(
(typeof _package == "function")
||
(_package.constructor && typeof _package.constructor == "function" && !_package._tokenString)
||
(_package._loaded == true)// _package.prototype.loaded is token to know if loaded
||
(_package.prototype && _package.prototype._loaded == true)
){
return _package; // 已经加载了,不重复加载
}else{
debugger;
}
return true; // done.
}
// prototype
$$.require.eval_JS_File = function(file){
}
;(function(){
function eval_JS_File_MS_ASP_JScript(filePath){
// for MS ASP Boost file
Response.Charset = "utf-8";
Session.CodePage = 65001;
Session.Timeout = 200;
Server.ScriptTimeout = 100;
if(arguments.length > 1){
argsList(arguments, arguments.callee);
}else{
with (new ActiveXObject("Adodb.Stream")){
type = 2;
mode = 3;
charset = "utf-8";
open();
if(typeof($$.console) != 'undefined' && $$.console.log){
$$.console.log(filePath);
$$.console.log(Server.Mappath(filePath));
}
loadFromFile(Server.Mappath(filePath));
var source = readText();
eval(source);
close();
}
}
}
function eval_JS_File_Browser(src){
if(arguments.length > 1){
argsList(arguments, arguments.callee);
}else{
var scriptTag = '<scr' + 'ipt src="{0}"></sc' + 'ript>';
if($$.env.isHTA){ // HTA环境下不支持“/”路径,只支持相对路径。
scriptTag = '<scr' + 'ipt src="http://localhost/{0}"></sc' + 'ript>';
}
document.write(scriptTag.format(src));
}
}
// @todo
function eval_JS_File_NodeJS(file){
}
if(typeof Server != 'undefined'){
$$.require.eval_JS_File = eval_JS_File_MS_ASP_JScript;
}else if(document){
$$.require.eval_JS_File = eval_JS_File_Browser;
}
})();
/* *----------------*
* Require
* *----------------*
*/
/*
* *----------------*
* Debug
* *----------------*
*/
$$.l = function(a){
if(typeof $$.console != 'undefined' && $$.console.log){
$$.console.log(a);
return;
}
if(typeof(Response) != 'undefined' ){
Response.write(a);
}else{
if(typeof $$.console != 'undefined' && $$console.log){
$$.console.log(a);
}else{
$$.l.count++;
if($$.l.count > $$.l.showLimit ){
return;
}else{
if($$.l.count == $$.l.showLimit ){
alert('Too much errors! Not Boring?');
return;
}
alert(a);
}
}
}
}
$$.l.count = 0;
$$.l.showLimit = 5;
l=$$.l;
/*
* *----------------*
* Debug
* *----------------*
*/
| JavaScript |
$$.XML = (function(){
// 不完全JSON,某些XMLDoc的成员一幅其中。
function parseXMLNode(node) {
var obj = {};
var element = node.firstChild;
while (element) {
if (element.nodeType === 1) {
var name = element.nodeName;
var sub = parseXMLNode(element)
sub.nodeValue = "";
sub.xml = element.xml;
sub.toString = function() {
return this.nodeValue;
};
sub.toXMLString = function() {
return this.xml;
}
// get attributes
if (element.attributes) {
for (var i = 0; i < element.attributes.length; i++) {
var attribute = element.attributes[i];
sub[attribute.nodeName] = attribute.nodeValue;
}
}
// get nodeValue
if (element.firstChild) {
var nodeType = element.firstChild.nodeType;
if (nodeType === 3 || nodeType === 4) {
sub.nodeValue = element.firstChild.nodeValue;
}
}
// node already exists?
if (obj[name]) {
// need to create array?
if (!obj[name].length) {
var temp = obj[name];
obj[name] = [];
obj[name].push(temp);
}
// append object to array
obj[name].push(sub);
} else {
// create object
obj[name] = sub;
}
}
element = element.nextSibling;
}
return obj;
}
var Xml = {
prolog: function(version, encoding, standalone) {
var version = version || "1.0";
var encoding = encoding || "utf-8";
return "<?xml version=\"" + version + "\" encoding=\"" + encoding + "\"" + (standalone ? " standalone=\"yes\"" : "") + " ?>";
},
text: function(text) {
return (text != null) ? text.toString().replace(/\&/g, "&").replace(/\</g, "<").replace(/\>/g, ">") : "";
},
attr: function(name, value) {
return (name && value != null) ? (" " + name + "=\"" + this.text(value).replace(/\x22/g, """) + "\"") : "";
},
cdata: function(text) {
return (text) ? "<![CDATA[" + text.toString().replace("]>>", "]>>") + "]>>" : "";
},
comment: function(text) {
return (text) ? "<!--" + text.toString().replace("--", "\x2D\x2D") + "-->" : "";
},
toXMLString: function(obj) {
var xml = [];
function serialize(obj) {
var xml = [];
var type = typeof obj;
switch (type) {
case "object" : {
if (obj === null) {
xml.push("<"+i+" />\n");
} else if (typeof obj.getTime === "function") {
xml.push("<"+i+Xml.attr("type", "date")+(obj !== "" ? ">"+obj.toUTCString()+"</"+i : " /")+">\n");
} else if (typeof obj.join === "function") {
for (var j=0; j<obj.length; j++) {
xml.push(serialize(obj[j]));
}
} else {
var sub = Xml.toXMLString(obj);
xml.push("<"+i+Xml.attr("type", type)+(sub !== "" ? ">\n"+sub+"</"+i : " /")+">\n");
}
break;
}
case "string" :
xml.push("<"+i+Xml.attr("type", type)+(obj !== "" ? ">"+Xml.text(obj)+"</"+i : " /")+">\n");
break;
case "date" :
case "boolean" :
case "number" : {
xml.push("<"+i+Xml.attr("type", type)+">"+obj+"</"+i+">\n");
break;
}
}
return xml.join("");
}
for (var i in obj) {
xml.push(serialize(obj[i]));
}
return xml.join("");
}
};
return {
/**
* 把XML格式转换为JSON输出。
* @param {IXMLDOMNode} n
* @return {Object} JSON
*/
parse: parseXMLNode
,json2xml: function(json){
return Xml.toXMLString(json);
}
/**
* 保存XML对象为XML文本文件。
* 注意:Server Side Only
* @param {XMLDocument} xmlDoc XML文档对象本身。
* @param {String} xmlFilePath 可选的。XML文档的真实磁盘路径。
* @return {Boolean} 是否操作成功。
*/
,saveXML: function(xmlDoc, xmlFilePath){
xmlFilePath = xmlFilePath || xmlDoc.url.replace(/file:\/\/\//,'');
// make a clone
var saver = new ActiveXObject('Msxml2.DOMDocument.6.0');
saver.loadXML(xmlDoc.xml);
if( saver.readyState == 4 && saver.parsed){
saver.save(xmlFilePath);
}
return true;
}
,CData:Xml.cdata
/**
* 依据数据值是什么(在data里查找匹配的),决定选中哪一个Option控件。
* @param {IXMLDOMNode} n XML节点对象。
* @param {Object} data 数据对象。
* @return {IXMLDOMNode} XML节点对象。
*/
,setSelectByNode: function(n, data){
var i, k;
var selectEl;
for(i in data){
k = ".//select[@name='{0}']".format(i);
selectEl = n.selectSingleNode(k);
if(selectEl){
// 选中value一样的节点
for(var z = 0; z < 2; z++){
if( selectEl.childNodes(z).attributes(0).value == data[i]){
selectEl.childNodes(z).setAttribute('selected', 'true'); // 设置为选中!
}
}
}
}
return n;
}
/**
* 依据数据值是什么(在data里查找匹配的),决定选中哪一个Radio控件。
* @param {IXMLDOMNode} n XML节点对象。
* @param {Object} data 数据对象。
* @return {IXMLDOMNode} XML节点对象。
*/
,setRadioByNode: function(n, data){
var
k
,selectEl;
for(var i in data){
k = ".//input[@name='{0}']".format(i);
selectEl = n.selectNodes(k);
if(selectEl && selectEl.length > 0){
// 选中value一样的节点
for(var z = 0; z < selectEl.length; z++){
// 默认attributes(3)是name属性
if( selectEl(z).attributes(1).value == data[i]){
selectEl(z).setAttribute('checked', 'true'); // 设置为选中!
}
}
}
}
return n;
}
/**
* 从XML文档中选择指定的模板文件,将其数据绑定data输出。
* 有取消CData作转意之功能。
* @param {String} xmlFile XML片段或者是XML文件,需要完全的文件路径地址,一般需要Server.Mappath获取真实地址后才输入到这里。
* @param {String} xPath XPath路径。
* @param {Object} data (可选的)数据实体,通常是JSON实体或者是配置文件$$.cfg。
* @return {String} 携带数据的HTML。
*/
,from_XML_Tpl : function(xmlFile, xPath, data){
var
xml = new ActiveXObject('Msxml2.DOMDocument.6.0')
,node
,tpl
,html;
// 自动判别是否可使用服务端的方法
if(typeof Server != 'undefiend'){
if(xml.load(Server.Mappath(xmlFile)) != true){
throw '加载' + xmlFile + '模板文件失败';
};
}else{
if(xml.loadXML(xmlFile) != true){
throw '加载' + xmlFile + '片段失败';
};
}
node = xml.selectSingleNode(xPath);
if(!node){
throw '没有模板节点';
}
// Option的Selected属性等的居然没用完整XML陈述形式!!
if(data){
$$.XML.setSelectByNode(node, data);
$$.XML.setRadioByNode(node, data);
}
tpl = node.xml
,tpl = tpl.replace('&', '&') // 规避XML标准的转义
,xml = null
,html = data ? new Edk.Template(tpl).applyTemplate(data) : tpl;
// 由于有些地步不合XML WellForm标准,故用CData豁免之,先还原。
if(html.indexOf('<![CDATA[')){
html = html.replace('<![CDATA[', '').replace(']]>', '');
}
return html;
}
,from_XML_CData: function(xmlFile, xPath){
var xml
,node
,CData;
xml = new ActiveXObject('Msxml2.DOMDocument.6.0');
// 自动判别是否可使用服务端的方法
if(typeof Server != 'undefiend'){
if(xml.load(Server.Mappath(xmlFile)) != true){
throw '加载' + xmlFile + '模板文件失败';
};
}else{
if(xml.loadXML(xmlFile) != true){
throw '加载' + xmlFile + '片段失败';
};
}
node = xml.selectSingleNode(xPath);
if(!node){
throw '没有模板节点';
}
return node.text;
}
,saveCDATA : function (){
var post = $$.form.post();
var filePath = Server.Mappath($$.cfg.edk_root + '/app/form/staticPage.xml');
var xml = new ActiveXObject('Msxml2.DOMDocument.6.0');
if(!xml.load(filePath)){
throw "打开模板文件错误";
}
var parentNode = xml.selectSingleNode('//' + page.split('.').pop());
var CDataNode = xml.createCDATASection(post['Content']);
parentNode.replaceChild(CDataNode, parentNode.childNodes(0));
$$.XML.saveXML(xml, filePath);
Response.Write('写入CData数据成功!');
return true;
}
};
})(); | JavaScript |
;(function(){
// fso不存在 rename(),只有通过 move() 来完成。
function renName(){}
/**
* @class $$.fs.File
*/
$$.fs.File = function(){
/**
* 根据文件的MIME(content-type)类型,返回文件的扩展名。
* @param {String} contentType
* @return {String} null表示为不能识别该Content-Type。
*/
this.setMIME = function(contentType){
switch(contentType){
case "application/msword" :
return ".doc";break;
case "application/pdf" :
return ".pdf";break;
case "application/vnd.ms-excel" :
return ".xls";break;
case "application/vnd.ms-powerpoint" :
return ".ppt";break;
case "application/x-javascript" :
return ".js";break;
case "application/x-shockwave-flash" :
return ".swf";break;
case "application/xhtml+xml" :
return ".xhtml";break;
case "application/zip" :
return ".zip";break;
case "application/msaccess" :
return ".mdb";break;
case "audio/midi" :
return ".mid";break;
case "audio/mpeg" :
return ".mp3";break;
case "audio/x-aiff" :
return ".aif";break;
case "audio/x-mpegurl" :
return ".m3u";break;
case "application/vnd.rn-realmedia" :
case "audio/x-pn-realaudio" :
return ".rm";break;
case "audio/x-pn-realaudio-plugin" :
return ".rpm";break;
case "audio/x-realaudio" :
return ".ra";break;
case "audio/wav" :
return ".wav";break;
case "image/bmp" :
return ".bmp";break;
case "image/gif" :
return ".gif";break;
case "image/jpg" :
case "image/jpeg" :
case "image/pjpeg" :
return ".jpg";break;
case "image/x-png":
case "image/png" :
return ".png";break;
case "image/tiff" :
return ".tiff";break;
case "image/vnd.wap.wbmp" :
return ".wbmp";break;
case "text/css" :
return ".css";break;
case "text/html" :
return ".html";break;
case "text/plain" :
return ".txt";break;
case "text/richtext" :
return ".rtx";break;
case "text/rtf" :
return ".rtf";break;
case "text/xml" :
return ".xml";break;
case "video/mpeg" :
return ".mpeg";break;
case "audio/x-ms-wma" :
return ".wma";break;
case "video/quicktime" :
return ".mov";break;
case "video/vnd.mpegurl" :
return ".mxu";break;
case "video/x-msvideo" :
return ".avi";break;
case "video/x-sgi-movie" :
return ".movie";break;
case "application/octet-stream" :
default :
return null; // 分不清什么类型,返回null。
}
}
}
})();
/**
* 打开文件,读取其内容,返回文本的格式。
* @static
* @param {String} path 文件路径
* @param {Boolean} isMapPath 是否送入相对路径。True的话把虚拟路径还原为真实的磁盘路径。
* @return {String} 文本内容
*/
$$.fs.File.read = function(path){
with(new ActiveXObject("Adodb.Stream")){
type = 2;
mode = 3;
charset = "utf-8";
try {
open();
loadFromFile(path);
return readText();
}catch (e){
throw e;
}finally{
close();
}
}
}
/**
* 将数据保存到磁盘上。可支持文本数据和二进制数据。
* @static
* @param {String} data 要写入的数据,可以是二进制对象。
* @param {String} path 文件路径。
* @param {Boolean} isBinary 是否为二进制数据。
* @param {Boolean} isMapPath 是否送入相对路径。True的话把虚拟路径还原为真实的磁盘路径。
* @return {Boolean} True 表示操作成功。
*/
$$.fs.File.write = function(data, path, isBinary, chartset){
with(new ActiveXObject("Adodb.Stream")){
type = isBinary ? 1 : 2;
if (!chartset && !isBinary)
charset = "utf-8";
if (chartset)
charset = "GB2312";
try {
open();
if(!isBinary){
writeText(data);
}else{
write(data);
}
saveToFile(path, 2);
return true;
}catch(e){
throw e;
} finally {
close();
}
}
return true;
}
var noType = /(?:\|?exe\|?)|(?:\|?dll\|?)|(?:\|?jpe?g\|?)|(?:\|?gif\|?)/i;
// 使用setTimeout的好处是可随时中止。
var EasySR = {
/**
* @param {String} sPath 对哪个目录进行搜索,即“目录路径”。
* @param {RegExp} sExt 扩展名
* @param {String} sReg 搜索的内容。
* @param {String} sRep 替换的内容(可选的)。
* @param {String} sIG 正则的第二个参数。
* @param {Boolean} sReplace 是否也替换呢?
* @param {Boolean} sCopy 替换后应该是直接覆盖或则备份。
* @param {Boolean} sSub 是否包括子目录。
*/
matchFile : function(sPath, sExt, sReg, sRep, sIG, sReplace, sCopy, sSub){
if (!sPath || !sExt)return;
if (noType.test(sExt)){
alert('Only accept the text of the types of files!');
return;
}
btnStart.style.display = 'none'
,btnStop.style.display = 'inline-block'
,cmd.innerHTML = '正在搜索中……'
,list.innerHTML = '<select size="10"><option>搜索文件中……</option></select>';
var
fso = new ActiveXObject("Scripting.FileSystemObject")
,aP = [sPath]
,aF = [] // 命中的文件列表
,aM = []
,aC = [] // chartset
,ext = new RegExp('\.(?:' + sExt + ')$', 'i') // 扩展名的正则
,rt = new RegExp(sReg, 'i')
,r = new RegExp(sReg, sIG)
,iL = 0
,ipp = 0
,iTimerSF = 0
,iTimerMF = 0;
// stop
btnStop.onclick = function(){
if (iTimerSF)
window.clearTimeout(iTimerSF);
if (iTimerMF)
window.clearTimeout(iTimerMF);
btnStart.style.display = 'inline-block';
btnStop.style.display = 'none';
};
// search files
// 先根据输入的条件,搜索符合文件名要求的文件,
// 再匹配内容。
var innerSF = function(){
if (aP.length == 0){
// 搜索结束
iL = aF.length
,fcount.innerHTML = iL + ' files waiting for match'
,cmd.innerHTML = '匹配的结果有:'
,list.innerHTML = '<select size="10"><option>' + aF.join('</option><option>') + '</option></select>';
if(iTimerSF){
window.clearTimeout(iTimerSF);
}
// 搜索文件而已
if(!sReg){
btnStart.style.display = 'inline-block'
,btnStop.style.display = 'none'
,cmd.innerHTML = 'Mission completed! '
,msg.innerHTML = 'Search files: ' + aF.length
,aF = null;
}else{
iTimerMF = window.setTimeout(innerMF);
}
return;
}
var sPath = aP.shift();
if (!fso.FolderExists(sPath)){
iTimerSF = window.setTimeout(arguments.callee);
return;
}
msg.innerHTML = sPath;
var
f = fso.GetFolder(sPath)
,fs = new Enumerator(f.files) // 遍历文件
,sf = new Enumerator(f.SubFolders) // 遍历目录
,fileObj; // 文件对象
while(!fs.atEnd()){
fileObj = fs.item();
if (ext.test(fileObj.path)){
aF.push(fileObj);
}
ext.lastIndex = 0;
fs.moveNext();
}
// aFT = null; ??
if (sSub == 'fs'){
var aTmp = [];
for (; !sf.atEnd(); sf.moveNext()) {
aTmp.push(sf.item());
}
aP = aTmp.slice(0).concat(aP);
aTmp = null;
}
iTimerSF = window.setTimeout(arguments.callee);
}
// match files
var innerMF = function(){
if (ipp == iL) {
btnStart.style.display = 'inline-block'
,btnStop.style.display = 'none';
if (iTimerMF)
window.clearTimeout(iTimerMF);
aF = aM = null;
return;
}
var
sF = aF[ipp]
,ifsize
,oFile;
ipp++;
if(!fso.FileExists(sF)){
iTimerMF = window.setTimeout(arguments.callee);
return;
}
ifsize = parseInt(fso.GetFile(sF).size, 10) / 1024 / 1024;
if(ifsize <= 5){// set file size less than 5m
msg.innerHTML = sF
,oFile = $$.fs.File.read(sF)
,sFile = oFile[0]
,sCharset = oFile[1];
if(rt.test(sFile)){
if (sReplace == 'replace'){
if (sCopy == 'copy'){
EasySR.saveFile(sF + '.EasySR', sFile, sCharset);
}
EasySR.saveFile(sF, sFile.replace(r, sRep), sCharset);
}
rt.lastIndex = 0;
aM.push(sF);
aC.push(sCharset);
}
}
iTimerMF = window.setTimeout(arguments.callee);
}
// start
iTimerSF = window.setTimeout(innerSF);
}
}
/**
* @private
* @param {String} str
* @return {Shell.Application}
*/
function showFolderPickuper(str){
var objFolder = new ActiveXObject("Shell.Application").BrowseForFolder(
0
,str || "请选择一个目录。"
,0
,0x11
);
return objFolder ? objFolder.Self.Path : '';
}
$$.disk = {
//function folderHelper(path, onfile_Fn, onfolder_Fn) {
// var fso = new ActiveXObject("Scripting.FileSystemObject");
//
// if (fso.FolderExists(path)){
// search(fso.GetFolder(path));
// }
// // __Search()
// function search(folder){
// for (var e = new Enumerator(folder.SubFolders); !e.atEnd(); e.moveNext()) {
// var item = e.item();
// if (typeof onfolder_Fn === "function")
// onfolder_Fn(item, fso);
// if (recursive){
// arguments.callee(item);
// }
// }
// for (var e = new Enumerator(folder.Files); !e.atEnd(); e.moveNext()) {
// if (typeof onfile_Fn === "function"){
// onfile_Fn(e.item(), fso);
// }
// }
// }
//}
/**
* @param {String} folder
* @param {Function} fn
*/
getFlatFlies : function(folder, isRecursive, fn, scope){
var
fso = new ActiveXObject("Scripting.FileSystemObject")
,target = fso.getFolder(folder);
if(!fn || typeof(fn) != 'function'){
throw "该函数期待一个合法函数的参数!";
}
function getFiles(folderObj){
var fileObj, i = 0;
with(new Enumerator(folderObj.Files /* 列出所有文件 */)){
while (!atEnd()){
fileObj = item();
// if(fileObj.Name.split('.').pop().indexOf('js') != -1){
// arr.push(fileObj.Path);
// }
fn.call(scope, fileObj, folderObj, i++);
fileObj = null;
moveNext();
}
}
}
// 本目录下的文件
getFiles(target);
// 子目录下所有的文件
if(isRecursive){
;(function(items){
var folderObj;
with(new Enumerator(items)){
while (!atEnd()){
folderObj = item();
getFiles(folderObj);
if(folderObj.subFolders.Count > 0){
arguments.callee(folderObj.subFolders); // 递归
}
folderObj = null;
moveNext();
}
}
})(target.SubFolders);
}
return true;
}
,base64EncodeText: function (TextStr) {
var xml_dom = new ActiveXObject("MSXML2.DOMDocument");
var ado_stream = new ActiveXObject("ADODB.Stream");
var tmpNode = xml_dom.createElement("tmpNode");
tmpNode.dataType = "bin.base64";
ado_stream.Charset = "gb2312";
ado_stream.Type = 2;// 1=adTypeBinary 2=adTypeText
if (ado_stream.state == 0) {// 0=adStateClosed 1=adStateOpen
ado_stream.Open();
}
ado_stream.WriteText(TextStr);
ado_stream.Position = 0;
ado_stream.Type = 1;// 1=adTypeBinary 2=adTypeText
tmpNode.nodeTypedValue = ado_stream.Read(-1);// -1=adReadAll
ado_stream.Close();
return tmpNode.text;
}
};
/**
* 自动适应编码类型http://www.codeproject.com/KB/scripting/Exsead7.aspx
* @param {String} filename
* @return {String}
*/
$$.disk.toString = function(filename, sCharset) {
var fileContent, stream = new ActiveXObject('adodb.stream');
with(stream){
type = 2;// 1-二进制,2-文本
mode = 3;// 1-读,2-写,3-读写
open();
if (!sCharset) {
try{
stream.charset = "437"; // why try, cause some bug now
}catch(e){}
loadFromFile(filename);
// get the BOM(byte order mark) or escape(ReadText(2)) is fine?
switch (escape(readText(2).replace(/\s/g, ''))) {
case "%3Ca" :
case "%3Cd" :
case "%3C%3F" :
case "%u2229%u2557" : // 0xEF,0xBB => UTF-8
sCharset = "UTF-8";
break;
case "%A0%u25A0" : // 0xFF,0xFE => Unicode
case "%u25A0%A0" : // 0xFE,0xFF => Unicode big endian
sCharset = "Unicode";
break;
default :
// 判断不出来就使用GBK,这样可以在大多数情况下正确处理中文
sCharset = "GBK";
// close();
// 用使用“系统默认编码”
// { Read: 1, Write: 2, Append: 8 }
// with(new ActiveXObject("Scripting.FileSystemObject").openTextFile(filename, 1)){
// fileContent = readAll();
// close();
// }
// fileContent = new String(fileContent);
// fileContent.charset = 'SystemDefault';
// return fileContent;
break;
}
close();
open();
}
charset = sCharset;
loadFromFile(filename);
fileContent = new String(readText());
fileContent.charset = sCharset;
close();
}
return fileContent;
}
| JavaScript |
$$.file.FileDownload = {
/**
* 送入一个文件磁盘地址,使用ADODB.Stream组件下载。
* 文件大小有限制?
* 隐藏下载地址及防盗代码。
* @param {String} filePath
* @return {Boolean} 是否传送成功。
*/
fsoDown : function(filePath){
var
fileObj
,fileSize;
with(new ActiveXObject("Scripting.FileSystemObject")){
fileObj = getFile(filePath);
if(!fileObj){
throw '目标文件不存在!';
}
fileSize = fileObj.size;
}
// 防盗链
var
From_Url = Request.ServerVarIables("HTTP_REFERER")()
,Serv_Url = Request.ServerVarIables("SERVER_NAME")();
if (MId(From_Url,8,len(Serv_Url)) != Serv_Url){
Response.WrIte("该文件数据不完整或许已损坏.");
Response.End();
}
with(new ActiveXObject("ADODB.Stream")){
Open();
Type = 1;
LoadFromFile(filePath);
Response.AddHeader("Content-DIsposItIon", "attachment; FIlename=" + F.Name);
Response.AddHeader("Content-Length", IntFilelength);
Response.Buffer = True
Response.CharSet = "UTF-8";
Response.ContentType = "application/x-download";
Response.Clear();
Response.BinaryWrite(Read());
Response.Flush();
Close();
}
return true;
}
,nodeDown : function(){
}
} | JavaScript |
;(function(){
$$.data.Synchronizer = function(){
/**
* 生成上一条记录,下一条记录功能
* @param {String} tableName 表名。
* @param {Number} opt opt有两个值,0或1.
* @return {String}
*/
this.between = function(tableName, opt) {
var
html = '<a href="?ID={0}">{1}</a>'
,ID = Number(Request.QueryString('ID')())
,sql = opt
? "SELECT ID, title FROM {0} WHERE ID < {1} ORDER BY ID DESC"
: "SELECT ID, title FROM {0} WHERE ID > {1} ORDER BY ID"
,sql = sql.format(tableName, ID);
with (this.constructor(sql).rsObj) {
html = EOF ? (opt ? "下面没有记录。" : "此为第一条记录。") : html.format(
fields("ID").value, fields("title").value);
Close();
}
return html;
}
// 计数器
this.readHits = function(table){
var
sql = "UPDATE {0} SET ReadHits = ReadHits + 1 WHERE ID = {1}".format(table, Request('ID')())
,sql = this.constructor(sql)
,sql = "SELECT ReadHits FROM {0} WHERE ID = {1}".format(table, Request('ID')())
,sql = this.constructor(sql).rsObj
,readHits = sql('readHits').value;
sql.close();
return readHits;
}
}
})(); | JavaScript |
/**
* @class $$.sql.writer.Writer
*/
$$.sql.writer.Writer = (function(){
var
sqlTpl_Insert = 'INSERT INTO {0} ({1}) VALUES ({2})'
,sqlTpl_Update = 'UPDATE {0} SET {1} WHERE id = {2}'
,sqlTpl_Delete = 'DELETE FROM {0} WHERE id = {1}';
/**
* @param {Object} entityObj
* @param {Action} action
* @return {String} SQL语句。
*/
function write(entityObj, action){
var sql;
switch(action){
case $$.data.INITIALIZE: // 新建表格。
var insertData = entityObj.eachFields(entity2insert, [ [], [] ]);
sql = sqlTpl_Insert.format(
entityObj.getTableName()
,insertData[0].join(',')
,json2sql(insertData[1].join(','))
);
break;
case $$.data.CREATE: // 执行SQL INSERT指令。
var insertData = entityObj.eachFields(entity2insert, [ [], [] ]);
sql = sqlTpl_Insert.format(
entityObj.getTableName()
,insertData[0].join(',')
,json2sql(insertData[1].join(','))
);
break;
case $$.data.UPDATE: // 执行SQL UPDATE指令。
var
updateData = entityObj.eachFields(entity2update, [])
,updateData = updateData.join(',');
sql = sqlTpl_Update.format(entityObj.getTableName(), updateData, entityObj.id);
break;
case $$.data.DELETE: // 输入记录的id参数,删除记录。
sql = sqlTpl_Delete.format(entityObj.getTableName(), entityObj.id);
break;
default:
// warn
break;
}
return sql;
}
/**
* @this {Array}
*/
function entity2insert(field){
this[0].push(field.key);
this[1].push(field.getSqlValue());
}
/**
* @this {Array}
*/
function entity2update(field){
this.push(field.key + ' = ' + field.getSqlValue());
}
/**
* 送入一个JSON值,根据其类型返回符合SQL存储的字符串。
* @private
* @param {Any} v 值
* @return {String} 符合sQL存储的字符串。
*/
function json2sql(v){
switch(typeof(v)){
case 'boolean':
break;
case 'string':
v = v.replace(/\'/g, "''").replace(/\r/g,"").replace(/(wh)(ere)/ig, "$1'+'$2");
v = "'"+ v +"'";
break;
case 'number':
/*
* Access 双精度数字需要转换
* @dep
if(false){
v = " Format(" + v + ",'#0.0000') ";
}*/
break;
case 'object':
if(v.toString() === new Date(v).toString()){ // 日期类型
v = (
$$.cfg.edk_dbType == 'mysql'
? "'" + $$.Date.dateFormat(v, "yyyy-mm-dd HH:MM:ss") + "'"
: "#" + $$.Date.dateFormat(v, "yyyy-mm-dd HH:MM:ss") + "#"
);
break;
}
default :
throw "unknow type!";
}
return v;
}
/**
* 这里一定要转换,因为COM日期类型到JS中很奇怪。
* 原理ADO Types -->JS Types
* 以字符出现date字眼为判断!
* @param {String} key
* @param {COM/COM+} v
* @return {Date}
*/
function getPrimitiveDate(key, v){
if(/date/i.test(key)){
v = new Date(v);
}
return v;
}
return {
add : write.delegate(this, $$.data.CREATE)
,update : write.delegate(this, $$.data.UPDATE)
,delte : write.delegate(this, $$.data.DELETE)
/**
* 新建表格。
* @param {Object} entityObj
* @param {Boolean} isDropTable 创建表格之前是否删除表格。
* @return {Boolean} True表示创建成功。
*/
,createTable : function(entityObj, isDropTable){
var
sql = 'CREATE TABLE ' + tableName
,meta = $$.Model.meta
,fieldName
,SQLType
,arr = [];
for(fieldName in model){
SQLType = meta.getMeta.call(model[fieldName], meta.SQLType);
switch(SQLType){
case 'BOOLEAN':
SQLType = ($$.cfg.edk_dbType == 'access') ? 'BIT' : SQLType;
break;
case 'CHAR':
SQLType = 'CHAR({0})'.format(meta.getMeta.call(model[fieldName], meta.Length))
break;
}
arr.push(fieldName + ' ' + SQLType + (fieldName == "ID" ? " NOT NULL PRIMARY KEY" : ""));
}
sql += '('+ arr.join('\n,') + ")";
if(isDropTable){
// Access不支持 IF EXIST……
$$.sql.execute('DROP TABLE {0}'.format(tableName));
}
//进行数据库操作
return sql;
}
};
})(); | JavaScript |
/**
* @class $$.sql.reader.Querist
*/
/*
bar = {
select : [news.id, news.title, newsclass.title, newsclass.id, user.id, user.title]
}
*/
$$.sql.reader.Querist = {
constructor: function(){
var data = this.data;
if(!data) {
data = this.data = {};
}
data.mainTable = '';
data.top = {};
data.top.value = 0;
data.top.sql = '';
data.field = {};
data.field.value = [];
data.field.sql = '';
data.subQuery = {};
data.subQuery.value = [];
data.subQuery.sql = '';
data.join = {};
data.join.value = [];
data.join.sql = '';
data.filter = {};
data.filter.value = [];
data.filter.sql = '';
data.orderBy = {};
data.orderBy.value = [];
data.orderBy.sql = '';
data.noConflict = {};
data.noConflict.sql = '';
}
// for First
,setTop : function(num){
this.data.top.value = num
this.data.top.sql = "TOP " + num;
return this;
}
,setField : function(field){
this.data.field.value.push(field);
this.data.field.sql += ' '+ field + ' ';
return this;
}
// for fields
,setSubQuery : function(queristInstance, token){
this.data.subQuery.value.push(queristInstance);
this.data.subQuery.sql += ',(' + queristInstance.read() + ') AS ' + token;
return this;
}
,setFrom : function(mainTable){
this.data.mainTable = mainTable;
return this;
}
/**
* for tables
* 生成下面的语句:
* USER] INNER JOIN (news INNER JOIN newsClass ON news.ClassID = newsClass.ID) ON USER.ID = news.SubmitterID;
* 有两个关系:
* student(s#,sname,d#),即学生这个关系有三个属性:学号,姓名,所在系别
* dep(d#,dname),即院系有两个属性:系号、系名则s#、d#是主键,也是各自所在关系的唯一候选键,d#是student的外键。
*/
,setJoin : (function(){
var tpl = "({1} INNER JOIN {0} ON {3}.{4} = {1}.{2})";
/**
* @param {String} mainTable
* @param {Array} tables
* @return {String}
*/
function makeJoin(mainTable, tables){
var
join
,table
,inner // 内面一层的join
,out = []; // Is this useful? @todo
for(var i = 0, j = tables.length; i < j; i++){
table = tables[i]
,inner = (i == 0) ? mainTable : out[i - 1]
,join = tpl.format(
inner
,table.tableName
,table.primaryKey
,mainTable
,table.foreignKey
);
out.push(join);
// SELECT fields, noConflict
if(table.noConflict){
var noConflict = new String(' ');
for(var q = 0, p = table.noConflict.length; q < p; q++){
noConflict += ',' + table.noConflict[q] + ' ';
}
this.data.noConflict.sql = this.data.noConflict.sql + noConflict;
}
}
return join;
}
return function(mainTable, tables){
var thisJoin = this.data.join;
// 保存value,就是保存參數
thisJoin.value.push([ mainTable, tables]);
// 不用join,沒有tables
if(!tables){
thisJoin.sql = mainTable;
return thisJoin.sql;
}
// 如果有sql值存在,表示這是第二次調用join(),則mainTable為fn.sql
if(thisJoin.sql && thisJoin.sql != ''){
mainTable = thisJoin.sql;
}
thisJoin.sql = makeJoin.call(this, mainTable, tables); // 每次join操作都会破坏旧字符串
return thisJoin.sql;
}
})()
,addJoin : function(join){
var tmpJoin = this.data.tmpJoin;
if(!tmpJoin){
tmpJoin = this.data.tmpJoin = [];
}
tmpJoin.push(join);
return this;
}
// for where
,setFilter : function(filter){
this.data.filter.value.push(filter);
this.data.filter.sql += ' '+ filter + ' ';
return this;
}
// for order
,orderBy : function(){
return emptyStr;
return this;
}
// for page
,limit : function(){
return emptyStr;
return this;
}
,read : function(){
var
dummyStr = ''
,data = this.data
,top // first
,fields // 字段
,tables // 关联表
,filter // 查询条件
,order; // 排序
top = data.top .sql || dummyStr
,fields = (data.field.sql + data.noConflict.sql)
,fields = (
(data.field .sql || dummyStr)
+(data.noConflict .sql || dummyStr)
+(data.subQuery .sql || dummyStr)
) || ' * '
,tables = this.setJoin(data.mainTable, data.tmpJoin)
,filter = data.filter.sql
,filter = filter ? ' WHERE ' + filter : dummyStr
,order = data.orderBy .sql || dummyStr;
fields += data.noConflict.sql; // a bug?
return "SELECT " + top + fields + ' FROM ' + tables + filter + order;
}
}; | JavaScript |
/**
* @class $$.sql.reader.Pagination
* 使用start/limited的方式的分页类。
*/
$$.sql.reader.Pagination = {
constructor : function(){
this.pageSize = Number(Request.QueryString('limit')()) || this.pageSize;
this.startNum = Number(Request.QueryString('start')()) || this.startNum;
}
/**
* 每页显示记录笔数,或者说读取多少笔的记录。如不指定则为pageSize。
* @type {Number} pageSize
*/
,pageSize : 8
/**
* 如不指定则为零,表示从第一笔记录开始。
* @type {Number} startNum
*/
,startNum : 0
/**
* 符合当前查询条件的记录数。
* @type {Number} totalCount。
*/
,totalCount : 0
/**
* 符合当前查询条件的总页数 = totalCount / pageSize
* @type {Number}
*/
,pages : 0
/**
* 页码
* @type {Number} page
*/
,pageNo : null
/**
* Why?
* 结论1:Select * 语句对速度影响很大。
* select * from Adab 用时:35940 (共57个字段)
* select xhjm,xm,xjztdm,bdm,nj,dwdm from Adab 用时 4186
* select xhjm,xm from Adab 用时1626
* select xm from Adab 用时830
* 可以看得出每增加一个字段,时间会增加几乎是一倍。
* 另外,返回的数据的长度也会影响时间:如 select sfzh from Adab 用时1580 几乎与select xhjm,xm from Adab相同。
* 因此,返回的数据量是影响速度最关键的因素。网络上的数据传送成了执行SQL最大的性能问题。
* 执行一个selec dwdm,count(xhjm) from Adab的语句,用时106 要汇总计算,但传送数据少,因此速度很快。
* @ASP Only
* @param {String} id_fieldName 排序的字段
* @return {Object} pagination
*/
,renderPage : (function(){
var
removeFields = /(?:SELECT)\s+(.*)\s+(?:FROM)\s+(.+)\s?/i
,hasSort = /(\s+ORDER\s+BY\s+[\w\.]+)\s?(ASC|DESC)?/i
,hasWhere = /\s+WHERE\s+/i;
/**
* @static
* @private
* @ASP Only
* @return {String}
* 优化一下,先不要id选好记录,选好后,跳到那一页,根据id读取。
*/
function getQuickSql(querySql){
if(!querySql){
throw '没有查询的SQL!';
}
/**
* 欲查询的SQL,即分页前的SQL。
* @type {String}
*/
this.querySql = querySql; // 先保存一下。
var arr = querySql.match(removeFields);
return querySql.replace(arr[1], 'news.ID'); // id only
}
/**
* @private
* @ASP Only
* @param {ado.rs} rs
* @param {String} querySql
* @return {String}
*/
function getCurrentSql(rs, querySql){
var
IDs = []
,i = 0
,pageSize = rs.pageSize;
do {
IDs.push(rs('id').value);
// Response.Write("<p>每条记录信息:" + rs("id") + "</p>");
i++;
rs.movenext();
}while (!rs.Eof && ( i < pageSize));
IDs = (hasWhere.test(querySql) ? " WHERE " : " WHERE ") + " news.ID = " + IDs.join(' OR news.ID = ')
if(!hasSort.test(querySql)){
return querySql + IDs;
}else{
IDs += " $1 ASC "; // 必须相反,与原来的ORDER BY!
return querySql.replace(hasSort, IDs);
}
}
/**
* 分页的核心函数,返回 pagination 对象。转换 start/limit 分页方式 为 ado 的 absolutepage/pagesize 分页。
* @param {Number} start
* @param {Number} pageSize
* @param {Number} totalCount
* @return {Object}
* @private
* @static
*/
function page(start, pageSize, totalCount){
var
// 计算分页总数。
pages = totalCount % pageSize ? Math.floor(totalCount / pageSize) + 1 : totalCount / pageSize
// 获取当前的页码。通过 start 计算得在第几页。
,pageNo = start / pageSize + 1
/*
// pageNo的另一种解法
var
pageNo = (this.startNum / pageSize) + 1
,pageNo = pageNo || 1
,pageNo = (pageNo - totalCount) > 0 ? totalCount : pageNo
*/
,lastOffset = (pageNo - 2) * pageSize
,isBOF = lastOffset < 0
,isEOF = (pageNo * pageSize) > totalCount
,nextOffset = isEOF
? (pageNo - 1) * pageSize
: (pageNo * pageSize);
return {
totalCount : totalCount // 符合条件的记录总数。
,start : start // 从第几笔记录开始偏移(offset)。
,pageSize : pageSize // 每页多少笔记录?也可以认为是 偏移数
,pageNo : pageNo // 当前页码,即第几页。
,pages : pages // 总页数。
,lastOffset : lastOffset // 跳到前一页(offset的方式)
,nextOffset : nextOffset // 跳到后一页(offset的方式)
,isBOF : isBOF // 是否在最头一页(boolean)
,isEOF : isEOF // 是否在最尾一页(boolean)
};
}
/**
* @param {String} querySql
*/
return function(querySql, id_fieldName){
var
// 为求记录总数而优化的SQL,即分页后的SQL。当前页数据的SQL
rs = new ActiveXObject("ADODB.Recordset")
,quickSql = getQuickSql.call(this, querySql);
rs.Open(quickSql, this.getConnObj(), 1 ,1);
if(rs.EOF && rs.BOF){
Response.write('没有记录');
throw '没有记录';
}else{
var
pagination = page(this.startNum, this.pageSize, rs.recordcount)
,uiBar = Object.create($$.sql.reader.Pagination.barController)
,currentPageSql;
rs.pagesize = pagination.pageSize
,rs.absolutepage = pagination.pageNo
,currentPageSql = getCurrentSql(rs, this.querySql); // 求当前页数据的SQL。
rs.close();
for(var i in pagination)uiBar[i] = pagination[i];
}
return {
sql : currentPageSql
,count : pagination.totalCount
, html : uiBar.render()
};
}
})()
};
/**
* This is a controller.
* @class $$.sql.reader.Pagination.barController
*/
$$.sql.reader.Pagination.barController = {
/**
* 返回true表示存在除了start以外还有其他的参数。
* @return {Boolean}
*/
hasQueryStr : function (){
var req = Request.QueryString;
if(req.Count > 0){
if(req.Count == 1 && req('start').Count){
return false; // 只有 start 的参数
}
return true;
}else{
return false;
}
}
/**
* 返回QueryString
* @todo
* @return {String}
*/
,getQueryString : function (){
var arr = [], QueryObj = {};
var key, v;
for(var e = new Enumerator(Request.QueryString); !e.atEnd(); e.moveNext()){
key = e.item().toString();
v = Request.QueryString(key)(); // MS ASP这里好奇怪,不加()不能返回字符串
/*
v = unescape(decodeURI(v));
if( v == 'true' ) v = true;
if( v == 'false' ) v = false;
*/
//if(isNum.test(v)) v = Number(v);
QueryObj[key] = v;
}
if( QueryObj.start || QueryObj.start === 0 ){
delete QueryObj.start;
}
for(var i in QueryObj){
arr.push(i + '=' + QueryObj[i]);
}
return arr.join('&');
}
/**
* @private
* @type {String}
*/
,el : '<li><a href="{0}" title="{1}">{2}</a></li>'
// 上一页
,renderBOF : function(){
var urlP = "?start={0}";
if(this.hasQueryStr()){
urlP += "&" + this.getQueryString();
}
if(this.isBOF){
return this.el.format(urlP.format(0), "首页" , "首页");
}else{
return this.el.format(urlP.format(this.lastOffset), "下一页", "前页");
}
}
// 下一页
,renderEOF : function(){
var urlP = "?start={0}";
if(this.hasQueryStr()){
urlP += "&" + this.getQueryString();
}
if(this.isEOF){
return this.el.format(urlP.format(this.nextOffset), "末页" , "末页");
}else{
return this.el.format(urlP.format(this.nextOffset), "后一页", "后页");
}
}
,renderBar : function(){
var link = {
href : "?start={0}"
,title : ""
,text : ""
};
if(this.hasQueryStr()){
link.href += "&" + this.getQueryString();
}
var e, html, links = [];
var page;
for(var i = 0, j = this.pages; i < j; i++){
page = i + 1;
e = {};
for(var i in link){
e[i]= link[i];
}
e.href = e.href.format( i * this.pageSize); // 倍数关系
e.text = page;
e.title = "-->" + page;
html = this.el.format(e.href, e.title, e.text);
if(page == this.pageNo){
html = html.replace("<li", "<li class=\"highlight\"");
}
links.push(html);
}
return links.join('\n');
}
/**
* @return {String}
*/
,render : function(){
this.el = this.renderBOF() + this.renderBar() + this.renderEOF();
return $$.tpl.fillData($$.cfg.edk.edk_tpl.selectSingleNode('//pagingBar/div').xml, this);
}
}; | JavaScript |
/**
* @class SQL搜索器。
*/
DeepCMS.search = {
/**
* 简易分词生成器
* @cfg {Array} targetField 选择要搜索的字段(最多两个)
* @cfg {Boolean} isPreSearch 可选的 默认false 返回找到的记录集SQL语句
* @cfg {String} tablename 选择的表名
* @return {String} SQL字符串
*/
searchParser: function (config){
var keyword = config.keyword;
if (!keyword)
throw new Error(3003, '查找的内容不能为空!');
var len = keyword.length;
var subkey = '';
var s1 = [], s2 = [];
var lensubkey = 2;
var targetField_1 = config.targetField[0];
var targetField_2 = config.targetField[1];
switch (len) {
case 0 :
throw '查找的内容不能为空!';
break;
case 1 :
// 若长度为1,则不设任何值
break;
default :
// 若长度大于1,则从字符串首字符开始,循环取长度为2的子字符串作为查询条件
for (var i = 0, j = len - (lensubkey - 1); i < j; i++) {
s1.push(' or ' + targetField_1 + ' like \'%'
+ keyword.substr(i, lensubkey) + '%\'');
s2.push(' or ' + targetField_2 + ' like \'%'
+ keyword.substr(i, lensubkey) + '%\'');
}
break;
}
return config.isPreSearch
? "SELECT count(*) AS TotalCount FROM " + config.tablename
+ "" + " where " + targetField_1 + " like '%" + keyword
+ "%' " + " or " + targetField_2 + " like '%" + keyword
+ "%'" + s1.join('') + s2.join('')
: "SELECT * FROM " + config.tablename + "" + " where "
+ targetField_1 + " like '%" + keyword + "%' " + " or "
+ targetField_2 + " like '%" + keyword + "%'"
+ s1.join('') + s2.join('');
}
,highlight : function(str, arrKeywords) {
// Generate Keyword RegExp String - We need to duplicate the original
// keyword array here
var reStr = arrKeywords.join("$,$");
reStr = reStr.split("$,$");
for (var i = 0; i < reStr.length; i++) {
if (func.lengthW(reStr[i]) < 3) {
reStr.splice(i, 1);
i--;
} else {
reStr[i] = this.stringToRegExp(reStr[i]);
}
}
reStr = new RegExp("(" + reStr + ")", "ig");
var arrMatch;
var re = new RegExp("(\>|^)(.*?)(\<|$)", "igm");
while ((arrMatch = re.exec(str)) != null) {
var newStr = arrMatch[1]
+ arrMatch[2].replace(reStr, '<span class="highlight">'
+ "$1" + '</span>') + arrMatch[3];
str = str.replace(arrMatch[0], newStr);
re.lastIndex += newStr.length - arrMatch[0].length;
}
return str;
}
};
DeepCMS.search.actions = {};
DeepCMS.search.actions.get = function(){
var folder = "e:\\edk";
var isInvert = false;
var openFileFn = $$.disk.toString;
var
wildcard = 'partial' || "*"
,wildcard = new RegExp(
// "^" +
(
wildcard
.replace(/([\\\^\$+[\]{}.=!:(|)])/g, "\\$1") // 转义为字符串表达方式RegExp
.replace(/\*/g, ".*") // 通配符转RegExp
.replace(/\?/g, ".") // 通配符转RegExp
)
// + "$"
,'ig'
);
var fn = function(fileObj, folderObj){
var fileContent = openFileFn(fileObj.path);
if(fileContent){
if(wildcard.test(fileContent) && !isInvert){
l(fileObj+'<br>');
}else if(isInvert && !wildcard.test(fileContent)){
// isInvert goes here……
}
}else{
// 文件内容为空
}
};
var isRecursive = true;
var f = $$.disk.getFlatFlies(folder, isRecursive, fn);
} | JavaScript |
$$.require($$.sql.writer.Writer);
$$.require($$.sql.reader.Reader);
$$.require($$.sql.reader.Pagination);
/**
* @class Edk.sql.DAO
* @mix $$.sql.writer.Writer
* @mix $$.sql.reader.Reader
* @mix $$.sql.reader.Pagination
* DAO = Data Access Object 数据访问对象,既可读又可写的。
*/
$$.sql.DAO = (function(){
var connectObj; // 数据库连接对象,只设置一次,无须重复创建。多次创建则浪费。
function connectDB(cfg){
var
dbType // 链接数据库的类型,是Access呢?MySQL呢?还是SQLServer?
,dbPath // 数据库文件的路径,如果通过磁盘访问的话。
,connectStr // 链接数据库的字符串。
// 数据库对象,同前面的 var connectObj; 的对象
,connectObj = new ActiveXObject("ADODB.CONNECTION");
if(cfg){
dbType = cfg.dbType;
}else if(!cfg && $$.cfg){
dbType = $$.cfg.edk_dbType.toLowerCase();
}else{
dbType = 'access'; // 默认为MS Access数据库
}
switch(dbType){
case 'access' :
if(cfg && cfg.dbPath){
dbPath = cfg.dbPath;
}else if(!cfg && $$.cfg){
dbPath = $$.cfg.edk_isDebugging
? $$.cfg.edk_dbFilePath_Test
: Server.mappath($$.cfg.edk_dbFilePath);
}
connectStr = "DBQ={0};DefaultDir=;DRIVER={Microsoft Access Driver (*.mdb)};".format(dbPath);
break;
case 'sqlservver' :
throw '尚未实现';
case 'mysql' :
// 使用driver模式不用有空格在连接字符串中
connectStr = "DRIVER={mysql odbc 5.1 driver};SERVER={0};PORT={1};UID={2};PASSWORD={3};DATABASE={4};OPTION=3";
connectStr = connectStr.format('localhost', 3306, 'root' ,'123', 'test');
break;
case 'sqlite' :
dbPath = 'd:\\test.db';
connectStr = "DRIVER={SQLite3 ODBC Driver};Database=" + dbPath;
break;
default:
throw '非法数据库连接类型!';
};
connectObj.open(connectStr);
return connectObj;
}
/**
* 首先通过调用的父类方法检测SQL语句是否安全的。
* 其次,该方法执行以下的步骤:
* 一、连接数据库;二、执行 SQL 操作。三、返回数据集合。
* 其中连接了的数据库应该对象不应立刻销毁,应予保留,
* 使得在当前线程的上下文(整个Edk Context)内,对象connectObj可供以后程序多次反复地使用。
* 注意谨记:在程序最后阶段关闭数据库连接,即 $$.sql.close();
* @private
* @param {String} sql 要执行的 SQL 语句(可选的)。
* @param {Objcec} cfg 配置对象,可以包含连接数据库的字符串(可选的)
* @return {ADODB.Recordset} 数据库记录集合。
*/
function execute(sql, cfg, isRS){
if(!connectObj){
connectObj = execute.connectObj = connectDB(cfg); // call only once.
}
if(sql){
if(isRS){
return connectObj.execute(sql);
}else{
return row2json(connectObj.execute(sql));
}
}else{
return connectObj
}
}
/**
* 转换值的 ADO 类型为 JavaScript 类型。
* 更多常量信息请查阅文件: adovbs.inc ,该文件在系统中默认的路径为:
* C:\Program Files\Common Files\System\ado\adovbs.inc
* 其他系统请自行搜索。
* @private
* @param {Number} adoField
* @param {Any} value
* @return {Any}
*/
function sql2json(value, dataType){
switch(dataType){
case "string":
case 129: // 'char':
case 130: // 'nchar':
case 200: // 'varchar':
case 201: // 'text':
case 202: // 'nvarchar':
case 203: // 'ntext':
return String(value);
case "number":
case 20: // 'bigint':
case 2: // 'smallint':
case 16: // 'tinyint':
case 14: // 'decimal':
case 5: // 'double':
case 3:
return Number(value);
case 11: // "boolean":
case 'bol':
return Boolean(value);
case "date":
case "object":
case 135: // 'datetime':
case 64: // 'fileTime':
case 134:
case 137:
return new Date(value).format("yyyy-mm-dd");
default:
return eval(value);
}
}
/**
* 针对已查询出来的记录集,转换为 JavaScript 的 JSON 结构。
* @param {RecroedSet} rs ADO 对象集合。
* @return {Array} 输出的 JSON 数组。
*/
function row2json(rs){
var
output = [] // Array 输出的 JSON 数组
,rawArr = rs.getRows().toArray() // Array getRows() 返回的数组
,fields = rs.Fields // comObj rs.Fields 字段对象,每一列都不同。
,fLen = fields.Count // int 字段总数
,len = rawArr.length / fLen // int 记录数
,sp // int 位数
,row; // object 构成 JSON 的行对象
// 自动关闭 RecordSet 集合,可以尽快释放 RecordSet 对象占用的资源。
rs.Close();
for (var i = 0; i < len; i++){
sp = i * fLen
,row = {};
for (var j = 0; j < fLen; j++){
row[fields(j).name] = sql2json(rawArr[sp + j], fields(j).Type);
}
output.push(row);
}
return output;
}
return {
constructor : function(){
var _reader = $$.sql.reader;
_reader.Pagination.constructor.call(this.DAO);
_reader.Querist.constructor.call(this.DAO);
// 设置表名。
this.DAO.data.mainTable = this.getTableName();
}
,DAO : {
data : null
,execute : execute
,getConnObj : execute
/**
* 关闭数据库连接,释放占用的资源。
*/
,close : function(){
this.getConnObj().close();
}
}
/**
* 输入一个id,返回其实体。
* @param {Number} id
* @return {Object}
*/
,findById : function(id){
var
dao = this.DAO // Object
,sql // String
,json; // JSON
dao.setField(this.getTableName() + this.getFields())
,dao.setFilter('news.id=' + Request.QueryString('id')());
sql = dao.read();
json = dao.execute(sql);
json = json[0];
return this.setValueByJson(json);
}
/**
* 返回分页的数据部分,另外页面部分由模板提供。
* @param {Number} id
* @return {Array}
*/
,findPage : function(){
var
dao = this.DAO // Object
,sql // String
,page; // Object
dao.setField(this.getTableName() + this.getFields());
sql = dao.read();
page = dao.renderPage(sql);
return [dao.execute(page.sql), page];
}
/**
* 分段查找
*/
,findAll : function(){
}
,findByLike : function(){
}
,findBy : function(fn){}
};
})();
$$.sql.DAO.DAO = Object.mix($$.sql.DAO.DAO, $$.sql.writer.Writer, $$.sql.reader.Querist, $$.sql.reader.Pagination); | JavaScript |
$$.Server.IO = (function(){
/**
* @overrided
*/
function findById(tagLibs, authority, id){
var
data = this.findById(id)
,content = tagLibs.renderContentPanel(data)
,header = tagLibs.renderHead({
isEditMode: authority.isEditMode()
})
,body = tagLibs.renderBody(content);
this.content = $$.tags.Html.format(header, body);
}
/**
* @overrided
*/
function findPage(tagLibs, authority){
var
start = Number(Request.QueryString('start')()) // Number
,findPage = this.findPage(start) // Array
,data = findPage[0] // JSON
,page = findPage[1] // Object
,header = tagLibs.renderHead({
isEditMode: authority.isEditMode()
}) // String
// String
,body = tagLibs.renderBody(tagLibs.renderRecordSet(data, null, '新闻') + page.html);
this.content = $$.tags.Html.format(header, body);
}
return {
HTTPInterface : function(tagLibs, authority){
var
id = Request('id')()
,action = Request('action')()
// printout contentPanel
if(id && !action){
findById.call(this, tagLibs, authority, id);
}if(id && action){
switch(action.toUpperCase()){
case $$.data.CREATE:
break;
case $$.data.UPDATE:
var entity = this.findById(id);
entity.state = $$.data.Entity.updateState;
this.content = $$.JSON.encode(entity);
break;
case $$.data.DELETE:
break;
}
// 列记录
}if(!id && !action){
findPage.apply(this, arguments);
}
this.DAO.close();
}
/**
* 输出到客户端的HTML内容。
* @property {String}
*/
,content: null
};
})(); | JavaScript |
/// 获取客户端IP
/// @return {String} IP
function getIp() {
var proxy = $("HTTP_X_FORWARDED_FOR", "serv"),
ip = proxy && proxy.indexOf("unknown") != -1 ? proxy.split(/,;/g)[0] : $("REMOTE_ADDR", "serv");
ip = ip.trim().substring(0, 15);
return "::1" === ip ? "127.0.0.1" : ip;
};
/**
* Raw POST的解析器。Raw Post也是标准HTTP POST方式的一种,但不像key1=value2&key2=value2的形式提交数据,
* 而是一堆二进制的数据。
* 浏览器提交的POST数据视作原始的实际,须经过Adodb.Stream二进制解码后才可以使用。
* 注意:一旦使用过该方法。Request.Form('key')就无法使用,但QueryString仍可用。
* @return {Object}
*/
function rawPost(){
with(new ActiveXObject('Adodb.Stream')){
try{
Open();
Type = 2;// 2 = adTypeText
WriteText(Request.BinaryRead(Request.TotalBytes));
Position = 0;
Charset = "us-ascii";// gb2312?
Position = 2;
// 使用 eval()函数时,必须要一个变量来承载!
eval('this.requestObj = ' + ReadText());
return this.requestObj;
}catch(e){
throw e;
}finally{
Close();
}
}
}
// Request
;(function(){
var
getQuery
,getForm
// // 不进行字符串转换的方法
,binaryRead;
if($$.Server.isNodeJS){
log = console.log;
}else if($$.Server.isASP){
var every = function(emu, isAutoType){
var
key
,e
,v
,queryObj = {}
,i = 0;
if(!emu && emu.count <= 0)return queryObj;
for(e = new Enumerator(emu); !e.atEnd(); e.moveNext()){
key = e.item().toString();
v = emu(key)(); // MS ASP这里好奇怪,不加()不能返回字符串
// v = decodeURI(v);
// v = unescape(v);
queryObj[key] = isAutoType ? $$.getPerm(v) : v;
i++;
}
queryObj._count = i; // 字段总数
return queryObj;
};
/**
* 获取来自表单的各个字段的数据。HTTP FORM所提交的数据乃是key/value配对的结构。
* 本函数是把这些key/value集合转化成为JavaScript对象。这是post包最核心的函数。
* 对各个字段有decodeURI()、unescape()、$$.getPerm()自动类型转化的功能。
* @param {Boolean/String} isAllRequest true表示为返回QueryString和Form的Request对象集合。
* 如果指定form则返回表单的hash值,如果指定QueryString则返回URL上面的参数hash。
* @param {Boolean} isAutoType 是否进行自动类型转换。
* @return {Object} 客户端提交的数据或查询参数。
*/
getQuery = function(isAllRequest, isAutoType){
if(typeof isAllRequest == 'string') isAllRequest = isAllRequest.toLowerCase();
switch(isAllRequest){
case true:
var
_queryObj = every(Request.QueryString, isAutoType)
,_formObj = every(Request.Form, isAutoType)
,_count = _queryObj._count + _formObj._count
,_allObj;
for(var i in _formObj){
_queryObj[i] =_formObj[i];// 如果越到相同的key,则保留form的。
}
_allObj = _queryObj;
_allObj._count = _count;
return _allObj;
break;
case 'form':
return every(Request.Form, isAutoType);
break;
case 'querystring':
default:
return every(Request.QueryString, isAutoType);
}
}
}
/**
* @class $$.Request
*/
$$.Request = function (){
}
$$.Request.prototype = {
/**
* 是否POST提交数据。
* @return {Boolean}
*/
isPOST : function(){
return Request.ServerVariables('HTTP_METHOD')() == "POST";
}
/**
* 返回是否Raw 的POST。这个方法在某种场合必须使用,例如Ext.Direct。
* 约定:凡application/json的提交均视作Raw POST。
* @return {Boolean}
*/
,isRawPOST : function(){
return this.isPOST() && (Request.ServerVariables('Content_Type')().indexOf('application/json')) != -1
}
,getQuery: getQuery
,getForm : getForm
/**
* 返回页面的路径。
* @return {String} url
*/
,getPath : function(){
return Request.ServerVariables('URL')();
}
,hash : function(key){
return this.getQuery(true)[key];
}
,method : function(){
return Request.ServerVariables('HTTP_METHOD')();
}
/**
* Raw POST的解析器。Raw Post也是标准HTTP POST方式的一种,但不像key1=value2&key2=value2的形式提交数据,
* 而是一堆二进制的数据。
* 浏览器提交的POST数据视作原始的实际,须经过Adodb.Stream二进制解码后才可以使用。
* 注意:一旦使用过该方法。Request.Form('key')就无法使用,但QueryString仍可用。
* @return {Object}
*/
,getRawPost: function (){
with(new ActiveXObject('Adodb.Stream')){
open();
type = 2;// 2 = adTypeText
writeText(Request.binaryRead(Request.totalBytes));
position = 0;
charset = "us-ascii";// gb2312?
position = 2;
// 使用 eval()函数时,必须要一个变量来承载!
eval('this.requestObj = ' + readText());
close();
return this.requestObj;
}
}
};
})();
| JavaScript |
;(function(){
var
// 输出到浏览器的方法。
write
// 添加一个HTML的首部到响应。
,addHeader
// 输出二进制数据,不进行任何字符的转换。
,binaryWrite;
if($$.Server.isNodeJS){
write = $$.emptyFn;
// @todo
addHeader = function(){
}
}else if($$.Server.isASP){
write = function(){
Response.write(arguments[0]);
}
addHeader = function(key, value){
Response.addHeader(key, value);
}
binaryWrite = function(key, value){
Response.binaryWrite(arguments[0]);
}
}
function _Response(){
this.addEvent(
'write'
,'beforeWrite'
);
}
_Response.prototype = {
write : write
,addHeader : addHeader
,binaryWrite: binaryWrite
/**
* @type {String} HTTP内容类型。默认值是text/HTML
*/
,contentType: 'text/html'
/**
* @type {Number} HTTP状态代码。
*/
,statusCode : 0
,setFormat : function(contentType){
this.contentType = contentType;
}
,setText : function(data){
return (data);
}
,setJSON : function(data){
this.contentType = 'text/json';
return $$.JSON.encode(data);
}
,setXML : function(data, wrapTag, isCDATA){
this.contentType = 'text/xml';
if(typeof data == 'string'){
if(wrapTag && !isCDATA){
data = '<{0}>{1}</{0}>'.format(wrapTag, data);
}else if(wrapTag && isCDATA){
data = '<{0}>' + ("<![CD" + "ATA[") + "{1}" + ("]>" + ">") + '</{0}>'.format(wrapTag, data.replace(("]>" +">"), "]>>"));
}
return data;
}else{
data = $$.XML.json2xml(data);
}
return datal
}
,setHTML : function(data){
if(typeof data == 'string'){
return data;
}else{
}
}
};
})(); | JavaScript |
;(function(){
var
isNodeJS = (typeof process != 'undefined') && !!(process && process.version)
,isASP = !!this.ASP;
if($$.Server.isNodeJS){
$$.Server.mappath = function(){};
$$.log = console.log;
// @todo set a file for Application
}if($$.Server.isASP){
$$.Server.mappath = function(){
return Application.mappath(arguments[0]);
}
}
/**
* 获取来自表单的各个字段的数据。HTTP FORM所提交的数据乃是key/value配对的结构。
* 本函数是把这些key/value集合转化成为JavaScript对象。这是post包最核心的函数。
* 对各个字段有decodeURI()、unescape()、getPerm()自动类型转化的功能。
* @param {Boolean/String} isAllRequest true表示为返回QueryString和Form的Request对象集合。
* 如果指定form则返回表单的hash值,如果指定QueryString则返回URL上面的参数hash。
* @param {Boolean} isAutoType 是否进行自动类型转换。
* @return {Object} 客户端提交的数据或查询参数。
*/
function emuRequest(isAutoType, emuableObj){
var
key
,e
,v
,queryObj = {
_count : 0
}
,i = 0;
/**
* 输入参数,还原它的primitive值。
* @param {Any} v
* @return {Any}
*/
function getPerm(v){
if(v){
if(v == 'true' ) return true;
if(v == 'false') return false;
if(v.toString() == (new Date(v)).toString()) return new Date(v);
if(v == Number(v)) return Number(v);
}
return v;
}
if(!emuableObj)return queryObj;
if(emuableObj && emuableObj.count <= 0)return queryObj;
for(e = new Enumerator(emuableObj); !e.atEnd(); e.moveNext()){
key = e.item().toString();
v = emuableObj(key)(); // MS ASP这里好奇怪,不加()不能返回字符串
// v = decodeURI(v);
// v = unescape(v);
queryObj[key] = isAutoType ? getPerm(v) : v;
i++;
}
queryObj._count = i; // 字段总数
return queryObj;
}
$$.server.Server = {
getRequest_QueryString : emuRequest.delegate(null, Request.QueryString)
,getRequest_Form : emuRequest.delegate(null, Request.Form)
,getAll_Request : emuRequest.map([Request.QueryString, Request.Form, Request.Cookie]).C(function(){
var allRequest = {
_count: 0
};
var _args = [];
for(var i = 0, j = arguments.length; i < j; i++){
_args[i] = arguments[i]; // 修正arguments关键字不是数组的补丁函数。
}
var obj;
for(var i = 0, j = _args.length; i < j; i++){
obj = _args[i];
if(obj._count > 0){
var count = allRequest._count + obj._count;
for(var i in obj){
allRequest[i] = obj[i];
}
allRequest._count = count;
}
}
return allRequest;
})
};
// make them as list.
var _server = $$.server.Server;
_server.getRequest_Form_toList = _server.getRequest_Form.C($$.toArray);
_server.getRequest_QueryString_toList = _server.getRequest_QueryString.C($$.toArray);
_server.getAll_Request_toList = _server.getAll_Request.C($$.toArray);
})(); | JavaScript |
var i =0; | JavaScript |
/**
* @class Edk.Event
* Event类,就是一个提供事件服务的类,写得简简单单,不求多元、繁复(明显没有比Ext都考虑得多,那是一种方向)。
* 好像但凡研究JS到一定阶段的人,都要搞清楚事件吧,嗯~必修课。
* 事件的立论基础大家可以从观察者模式得到许多灵感,当然就是必须有第三方的“中立”观察者,
* 一边提供订阅事件的接口,一边让组件触发事件的fireEvent()。
* 前言:
不得不承认,有时候从新写一个库是一件很辛苦的事情。但是,相比较之下,直接使用别人写好的软件来修改,难道这样痛苦的程度就会减少吗?
基于事件模式的设计
JS的一大好处就是对Function天然的良性支持。这一点纵观眼下多少语言都未必能够赋予这种地位,有的即使赋予了,但率直来讲,也没有JS的那样的流通性的地位。试问一下,现今有多少主流语言是对Function这一类型主打的?若没有JS带来的影响,可能这一观念认识知道的人,不计发烧玩家、专家级人马,少之又少,或是又是其他具有“忽悠”价值的概念来代替这一朴质的概念……
事件本身与Function形影不离。好多GUI系统都以Function为编程的中心,因为制定GUI的过程往往就是制定Function的过程。事件类型一旦明确用哪一个好之后,开发人员所关心的便是这个事件到底应该执行些什么过程。若过程可以以一个变量或对象来表示,再给他起个名字,我们从某个角度上理解,也可以说该过程被抽象化了。抽象有什么好处?就是把一些必要的过程先写好,以后在复用。直截了当的说,我定义函数为一变量,可以全局变量,也可以私有变量,看您怎么用它——还可以当作参数传来传去。
也是一下子这样说有点跨越性太大,不易接受。如果是真的,操作起来究竟有什么好处呢?首先我们得从了解函数其意义的本质上去入手理解。什么?函数是什么??这不是初中层次的内容?……哎呀,插一句,不是怕大家见笑哦,我就是看了什么好东西,一味东拿来一点西拿来一点拼装一起,还自诩高级,其实没有扎实的基础知识联系,准吃亏!哎~回头来还比不过老老实实的说明一下基础内容。——各位已深明大义的看官请掠过。
*/
$$.event = function(){
this.events = {};
this.addEvents = function(){
var eventName;
for(var i = 0; i < arguments.length; i++){
eventName = String(arguments[i]).toLowerCase();
this.events[eventName] = [];
}
}
/**
*
* @param {String} name
* @param {Array} args
* @return {Boolean}
*/
this.fireEvent = function(name) {
var listeners = this.events[name.toLowerCase()];
if (listeners && listeners.length) {
var
arg1 = arguments[1]
,arg2 = arguments[2]
,arg3 = arguments[3]
,arg4 = arguments[4];
for (var i = 0, ln = listeners.length; i < ln; i++) {
if((listeners[i])(arg1, arg2, arg3, arg4) === false){
return false;
}
}
}
return true;
}
/**
*
* @param {String} name
* @param {Function} fn
* @return {this}
*/
this.addListener = function(name, fn, scope) {
var eventObj = this.events[String(name).toLowerCase()];
if(!eventObj){
throw '没有该事件!请使用addEvent()增加事件';
}
if(scope){
fn = fn.createDelegate(scope);
}
eventObj.push(fn);
return this;
}
this.on = this.addListener;
/**
*
* @param {String} name
* @param {Function} fn
* @return {this}
*/
this.removeListener = function(name, fn) {
if (this.events[name]) {
Array.remove(this.events[name], fn);
}
return this;
}
}
/**
* @class $$.Observable
* 简单的事件类。
*/
$$.Observable = function(ObservableList){
if(ObservableList){
this.addObservable(ObservableList);
}
}
$$.Observable.prototype = {
toString: function(){
return 'Observable';
}
,addObservable : function(){
// 创建事件结构
this.Observables = this.Observables || {};
for(var i = 0 ;i < arguments.length; i++){
this.Observables[String(arguments[i]).toLowerCase()] = [];
}
}
,addListener: function(ObservableName, ObservableHandler, scope, option){
var thatObservable = this.Observables[ObservableName.toLowerCase()];
if(!thatObservable){
throw "No such Observable";
}if(!ObservableHandler){
throw 'No passing Function!';
}else{
// ObservableObj
thatObservable.push({
fn : ObservableHandler
,scope : scope || $$.emptyObj
,cfg : option
});
}
}
,hasObservable : function(ObservableName){
return !!(this.Observables[ObservableName.toLowerCase()]);
}
,fireObservable : function(ObservableName){
var thatObservable = this.Observables[ObservableName.toLowerCase()]
if(!thatObservable){
throw "No such Observable";
}else{
var ObservableObj, args = Array.prototype.slice.call(arguments, 1);
for(var i = 0 ;i < thatObservable.length; i++){
ObservableObj = thatObservable[i];
ObservableObj.fn.apply(ObservableObj.scope, args);
}
return true;
}
}
};
// shorthands
$$.Observable.prototype.on = $$.Observable.prototype.addListener; | JavaScript |
/**
* @class $$.data.Tree
*/
$$.data.Tree = (function(){
/**
* iterator
* @param {Array} arr
* @param {Object} scope
* @param {Number} i
* @param {Number} j A ghost value, 穿梭于
*/
function array_Iterator(arr, scope, i, j){
// init...
if(typeof scope == 'undefined'){
scope = this;
}
if(typeof i == 'undefined'){
i = 0;
}
if(typeof j == 'undefined'){
j = 0;
}
// init end.
var elmemnt = arr[i];
if(typeof elmemnt == 'undefined'){
return;
}else{
// do something...
if(array_Iterator.Fn){
if(array_Iterator.Fn.call(scope, elmemnt, arr, i, j) == false){
return;
}
};
// do something-End
if(elmemnt.children && elmemnt.children.length){
// var x = j + 1; // 每一次循环children都会对j产生变化。
// -->y
array_Iterator(elmemnt.children, elmemnt/*已经变了这个Scope*/, 0, j + 1);
};
// -->x
array_Iterator(arr, scope, ++i, j /* Do not give a "j" here, cause it's needed to have j reset!*/);
}
}
return {
array_Iterator : function(fn, output){
var list = [];
array_Iterator.Fn = fn;
array_Iterator(this.aspArray(), list);
}
/**
* @return {Array}
*/
,toList : function(){
var list = [];
array_Iterator.Fn = function(e, arr, i, j){
list.push(e);
}
array_Iterator(this.tree, list);
return list;
}
/**
* @return {Object}
*/
,level : function(level){
var result = [];
array_Iterator.Fn = function(e, arr, i, j){
if(j == level){
// assert every node has a key name called "id"
if(!this.fullPath)this.fullPath = ''; // 执行此步的时候为根目录
e.fullPath = this.fullPath + '/' + e.id;
result.push(e);
}
}
array_Iterator(this.tree, result);
return result;
}
/**
* @return {Object}
*/
,_toHash : function(){
var hash = {};
array_Iterator.Fn = function(e, arr, i, j){
if(!this.fullPath)this.fullPath = ''; // 执行此步的时候为根目录
// // 包含父路径的全称路径
e.fullPath = this.fullPath + '/' + e.id;
// // 缩进
e.sj = j;
/*
* @todo
* 服务器的错!!!!!!!!!!!!!!!!!!!!不能读取Array!???
*/
var obj;
obj = {
text : e.text
,id : e.id
,fullPath : e.fullPath
,sj : e.sj
};
if(e.children){
for(var arr = [], i = 0, j = e.children.length; i < j; i++){
arr[i] = e.children[i];
}
// arr = [].concat(e.children); 快速克隆数组无效!?
obj.children = arr;
}
/*
* 服务器的错!!!!!!!!!!!!!!!!!!!!不能读取Array!???
*/
this[e.id] = obj || e;
}
array_Iterator(this.tree, hash);
return hash;
}
,xx : function(data){
var hash = {};
array_Iterator.Fn = function(e, arr, i, j){
if(!this.fullPath)this.fullPath = ''; // 执行此步的时候为根目录
// // 包含父路径的全称路径
e.fullPath = this.fullPath + '/' + e.id;
// // 缩进
e.sj = j;
this[e.id] = e;
}
array_Iterator(data, hash);
return hash;
}
/**
* getHashValueByFullKey
* @param {Boolean} isAllMatch
* @param {String|Array}
* @return {Object}
*/
,hashSearch : function(isAllMatch, list){
var
result = []
,i = 0;
if(!list && arguments.length > 1){ // 可变参数的条件
list = Array.prototype.slice.call(arguments, 1);
}else if(list && typeof list == 'string'){ // 送入字符串的条件
list = list.split('/');
list.shift();
}else if(list && list.pop){ // 送入数组的条件
// do nothing...
}
// debugger;
// if(!this.hash){
// this.hash = this._toHash();
// }
/**
* @param {String} key
*/
(function(key){
var _shift = this[key];
if(!_shift){
return;
}else{
result.push(_shift);
i++;
var nextKey = list[i];
arguments.callee.call(_shift, nextKey);
}
}).call(this.xx(this.aspArray()), list[i]);
return isAllMatch ? result : result.pop();
}
/**
* 可编织任意的数据,如:
var h = {};
var foo = this.webStructure.buildIndex(null, null, function(e, arr, i, j){
if(j == 1){
h[e.id] = e;
}
});
* @param {Array} arr
* @param {String} keyName 注意不是什么类型的数据都可以作为key!
* @param {Function} handler
* @return {Object}
*/
,buildIndex : function(arr, keyName, handler){
var hash;
hash = {}
arr = arr || this.tree
keyName = keyName || 'id'; // assert every node has a key name called "id"
array_Iterator.Fn = handler;
array_Iterator(arr, hash);
return hash;
}
};
})(); | JavaScript |
/**
* 网页模板是把动态的数据和静态的表现组装到一起的工具,使得内容与表现方式可以分离,是Web开发中的重要技术手段。
* 早期的Web开发很简单,没有“模板 ”的概念。
* 只需把数据提取出来,放在HTML里面显示就达到程序的目的。
* HTML代码混合于逻辑代码之中,HTML就是直接显示的内容,内嵌在HMTL 中<% ... %>表示为后台(服务端)执行代码,
* 但很多情况<% ... %>中又有HTML的片段,至于怎么拼凑出HTML片段的方式方法各式各样、与多种的后台语言掺杂一起(ASP、PHP、JSP)各显神通。
*/
$$.tpl = (function(){
var divBlock = '<{0}\\s*[^>]*>((?:(?=([^<]+))\\2|<(?!{0}\\s*[^>]*>))*?)<\/({0})>';
var matchValue = (function(){
var
regexp = /{([^}\n]*)}/ig
,execJS = /^\[([^\]]*)\]$/
,getParent = /^parent\.\b(\w*)\b$/i
,getRoot = /^root\.\b(\w*)\b$/i;
/**
* @private
* @param {mixed} v
* @return {Boolean} 是否hash(是否对象)。
*/
function isObject(v){
return !!v && isObject.toString.call(v) == isObject.token;
}
isObject.toString = Object.prototype.toString
isObject.token = '[object Object]';
function replace(m1, m2){
var
jsCode
,parent = arguments.callee.parent
,root = arguments.callee.root;
if(execJS.test(m2)){
jsCode = execJS.exec(m2);
jsCode = jsCode[1];
try{ // 写try之目的为容错性的设计。
with(this){
jsCode = eval(jsCode);
}
return jsCode;
}catch(e){
return '空值';
}
}else if(isObject(parent) && getParent.test(m2)){ /* 父级寻址 */
m2 = m2.match(getParent);
m2 = m2[1];
return parent[m2] || m1;// 替换置,如果未发现匹配的值,就返回原模版的格式({xxx}),即m1
}else if(isObject(root) && getRoot.test(m2)){ /* 全称寻址 */
m2 = m2.match(getRoot);
m2 = m2[1];
return root[m2] || m1;
}else{
return this[m2] || m1;
}
}
/**
* Lazy function
* @param {String} tpl
* @param {Object} dataObj
* @param {Object} parentObj
* @return {String}
*/
return function(tpl, dataObj, parentObj){
if(!replace.root){
replace.root = $$.tpl.root;
}
replace.parent = parentObj || 'itself'; // 无else部分,即表示全部就是trueBlock
replace.scope = dataObj;
return tpl.replace(regexp, replace.delegate());// set scope object!
}
})();
var matchIf = (function(){
var
elseReg = /<else\s*\/?>/i
,evalReg = /<if\s*(?:eval="([\w\d=<>\.!'\|\(\)]*)")[^>]*>/i
,tabReg = /\t{2}/g
,ifReg = new RegExp(divBlock.format('if'), 'ig');
/**
* 运算<if eval="exp">内容。
* @param {Object} data
* @param {Object} parent
* @param {String} ifTag
* @return {Boolean}
*/
function evalExp(data, parent, ifTag){
var exp;
if(!evalReg.test(ifTag)){
$$.console.error('输入的标签{0}不是一个标准的if tag'.format(ifTag));
throw '不是一个标准的if tag';
}
exp = evalReg.exec(ifTag);
exp = exp[1];
exp = '(' + exp +')'; // make it as the Expression 表达式
// 通过with(data){}给定对象可见的范围。如果没有matchedObj,则为this。这也是有可能的。
with(data || parent || this){
if(eval('typeof '+exp.toString()+' =="undefined";')){
exp = false; // undefined,means false.
}else{
exp = eval(exp);
}
exp = !!exp;
}
return exp;
}
/**
* @this {OBject} 值对象
*/
function replace(m1, m2){
var
evalResult // 运算表达式后的结果
,trueBlock // true块
,falseBlock = null // false块,默认没有
if(elseReg.test(m2)){// 有else部分
var arr = m2.split(elseReg);
if(!arr || arr.length < 2){
$$.console.error('if-else不完整');
throw "if-else不完整";
};
trueBlock = arr[0];
falseBlock = arr[1];
}else{
trueBlock = m2; // 无else部分,即表示全部就是trueBlock
}
trueBlock = String.trim(trueBlock);
trueBlock = trueBlock.replace(tabReg, '\t');// 消除多余tab符。
// 求 if 的表达式
evalResult = evalExp(this, arguments.callee.parent, m1);
if(evalResult){
return trueBlock;
}else if(!evalResult && falseBlock == null){
return '';
}else if(!evalResult && falseBlock){
return falseBlock;
}else{
// 不应该会走到这里的。若真的走到便抛出一个异常。
$$.console.error('求if-else块时发生致命错误!');
throw '求if-else块时发生致命错误!';
}
}
return function(tpl, data, parentData){
ifReg.lastIndex = 0;// 有global时需要注意 lastIndex的问题。
if(ifReg.test(tpl)){
replace.parent = parentData;
replace.scope = data;
return tpl.replace(ifReg, replace.delegate());
}else{
return tpl;
}
}
})();
function replace(m1, m2, m3, m4){
var
parentData = this
,values = parentData[m4]
,callee = $$.tpl.fillData
,str = ''
,arrTpl;
if(values && values.pop){ /* 有时候会因为大小写问题,无法匹配。请检查key即(m4)是否一致 */
m2 = callee(m2, values); // 递归 for sub
for(var i = 0, j = values.length; i < j; i++){
value = values[i];
m2 = matchIf(m2, value, parentData);
arrTpl = callee(m2, value);
str += matchValue(arrTpl, value, parentData);
}
return str;
}else if(values == false /* 特定为false的情况 */ ){
return str;
}else{
$$.console.warn('怎么数据源没提供数据? 宜debug之');
return 'nothing';// 怎么数据源没提供数据? 宜debug之
}
}
return {
/**
* @param {String} tpl
* @param {Object} data
* @return {String}
*/
fillData : function (tpl, data){
if(!$$.tpl.root){
$$.tpl.root = data;
}
if(data && !data.pop){
replace.scope = data;
var _replace = replace.delegate();
for(var i in data){
tpl = tpl.replace(new RegExp(divBlock.format(i), 'i'), _replace);
}
tpl = matchIf(tpl, data, data);
return matchValue(tpl, data);
}else if(data && data.pop){
return tpl;
}
return '';
}
,root : null
/**
* 为能在HTML显示的字符转义&、<、>以及'。
* @return {String} 编码后的文本
*/
,htmlEncode : function(isAndOff){
var str = this.replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
return isAndOff ? str.replace(/&/g, "&") : str;
}
/**
* 将&、<、>以及'字符从HTML显示的格式还原。
* @return {String} 编码后的文本
* @credit Ext
*/
,htmlDecode : function(v){
return v.replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"');
}
};
})(); | JavaScript |
$$.JSON = (function() {
function NumberAs(num) {
return num.toString();
}
// function StringAs(string) {
// return '"' + object.replace(/(\\|\")/g, "\\$1").replace(/\n|\r|\t/g,
// function() {
// var a = arguments[0];
// return (a == '\n') ? '\\n' : (a == '\r')
// ? '\\r'
// : (a == '\t') ? '\\t' : ""
// }) + '"';
// }
function StringAs(string) {
var reg = StringAs.reg;
return '"' + string.replace(reg, "\\$1") + '"';
}
StringAs.reg = /(\\|\"|\n|\r|\t)/g
function ObjectAs(object) {
var
value
,results = []
,callee = $$.JSON.encode;
for (var i in object) {
value = callee(object[i]);
if (value !== undefined) {
results.push(callee(i) + ':' + value);
}
}
return '{' + results.join(',') + '}';
}
function ArrayAs(array) {
var
value
,results = []
,callee = $$.JSON.encode;
for (var i = 0, j = array.length; i < j; i++) {
value = callee(array[i]);
if (value !== undefined) {
results.push(value);
};
}
return '[' + results.join(',') + ']';
}
/**
* "new Date(" + obj.valueOf() + ")";
*/
function DateAs(date){
return "new Date(" + date.valueOf() + ")";
var makeTwoDigits = DateAs.makeTwoDigits;
return date.getUTCFullYear() + '-'
+ makeTwoDigits(date.getUTCMonth() + 1) + '-'
+ makeTwoDigits(date.getUTCDate()) + 'T'
+ makeTwoDigits(date.getUTCHours()) + ':'
+ makeTwoDigits(date.getUTCMinutes()) + ':'
+ makeTwoDigits(date.getUTCSeconds()) + 'Z';
}
/**
* Format integers to have at least two digits.
*/
DateAs.makeTwoDigits = function(n) {
return n < 10 ? '0' + n : n;
}
/**
* decode日期函数,日期格式是ISO,以下就是这个转换函数,蛮有意思的是with(){} statement的用法:)
*/
function decodeDate(str){
var getDate = decodeDate.reg;
if(!getDate.test(str)){
return null;
}else{
with(getDate.exec(str)){
return new Date([1], [2], [3], [4], [5], [6]);
}
}
}
decodeDate.reg = /(\d{4})-(\d{1,2})-(\d{1,2})T(\d{1,2}):(\d{1,2}):(\d{1,2})/;
return {
decode : function() {
return eval("(" + arguments[0] + ')');
},
// uneval
encode : function(object) {
if (object === null) {
return 'null';
}else if(typeof object == 'undefined'){
return;
}
if(object instanceof Boolean){
return NumberAs(object);
}else if(object instanceof Number){
return NumberAs(object);
}else if(object instanceof String){
return StringAs(object);
}else if(object instanceof Array){
return ArrayAs(object);
}else if(object instanceof Date){
return DateAs(object);
}else if(object instanceof RegExp){
return;
}
switch (object.constructor) {
case Boolean :
return NumberAs(object);
break;
case Number :
return NumberAs(object);
break;
case String :
return StringAs(object);
break;
case Array :
return ArrayAs(object);
break;
case Date :
return DateAs(object);
break;
case RegExp :
return;
break;
}
switch (typeof object){
case 'undefined' :
case 'unknown' :
case 'function' :
case 'regexp' :
return;
break;
case 'boolean' :
case 'number' :
return NumberAs(object);
break;
case 'date' :
return DateAs(object);
break;
case 'string' :
return StringAs(object);
case 'object' :
return ObjectAs(object);
break;
case 'array' :
return ArrayAs(object);
}
}
};
})(); | JavaScript |
/**
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
用法:
<%@language=jscript codepage=65001%>
<script src="/edk/common/edk.js" language="JavaScript" runat="server"></script>
<script src="/edk/common/utils/json.js" language="JavaScript" runat="server"></script>
<script src="/edk_ServerScript/server/console.js" language="JavaScript" runat="server"></script>
<script language="JavaScript" runat="server">
$$.console.log("Hello world!");
$$.console.info("And", "so", "on");
$$.console.debug(98);
$$.console.warn(99);
$$.console.error('Error')
</script>
不支持下列的用法:
* $$.console.assert()
* $$.console.count()
* $$.console.dir()
* $$.console.dirxml()
* $$.console.profile()
* $$.console.profileEnd()
* $$.console.trace()
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
*/
/**
* @fileOverview A server-side implementation of the Firebug Console API
* @author Nathan L Smith
* @date November 21, 2008
* @version 0.0.4
*/
/*global console, Jaxer, Request, Response */
/**
* @namespace console
*
* This is a partial implementation of the Firebug Console API using
* the Wildfire/FirePHP protocol.
*
* @see http://nlsmith.com/projects/console/
* @see http://getfirebug.com/console.html
* @see http://www.firephp.org/HQ/Use.htm
*/
$$.console = (function () {
/**
* Is the console enabled? Set this with
* console.enable()/console.disable()
*/
var enabled = true;
/**
* The possible console levels
*/
var levels = {
log : "LOG",
info : "INFO",
warn : "WARN",
error : "ERROR",
trace : "TRACE",
table : "TABLE",
dump : "DUMP",
group : "GROUP_START",
groupEnd : "GROUP_END",
time : "TIME",
timeEnd : "TIME_END"
};
/**
* Timers for console.time()
*/
var timers = {};
/**
* The platforms object defines objects for the server-side JavaScript
* platform on which the console object is used
*/
var platforms = (function platforms() {
var p = {}; // Platforms object to return
try {
p.jaxer = {
addHeader : function addHeader(header, value) {
Jaxer.response.headers[header] = value;
},
userAgent : Jaxer.request.headers["User-Agent"],
toJSON : function toJSON(o) {
return Jaxer.Serialization.toJSONString(o, { as : "JSON" });
}
};
} catch (eJaxer) {}
try {
p.asp = {
addHeader : function addHeader(header, value) {
Response.addHeader(header, value);
},
userAgent : String(Request.ServerVariables("HTTP_USER_AGENT")),
toJSON : $$.JSON.encode // This is from Prototype.js
};
} catch (eAsp) {}
try {
p.appjet = {
addHeader : function addHeader(header, value) {
response.setHeader(header, value);
},
userAgent : request.headers["User-Agent"],
toJSON : JSON.stringify
};
} catch (eAppjet) {}
p.unknown = {
addHeader : function addHeader() {
throw new Error("Unknown platform");
},
userAgent : "",
toJSON : function toJSON() { return ""; }
};
return p;
})();
/**
* Detect the current platform here and assign it to the platform
* variable
*/
var platform = (function platform() {
if (typeof Jaxer === "object" && Jaxer.isOnServer) {
return "jaxer";
} else if (typeof Request === "object" &&
typeof Response === "object" &&
typeof Request.ServerVariables === "object") {
if($$.JSON.encode){
Object.toJSON = $$.JSON.encode;
}
// Require Prototype for ASP
if (typeof Object.toJSON !== "function") {
throw new Error("Prototype ASP (or another implementation of Object.toJSON())is required. Get it from http://nlsmith.com/projects/prototype-asp");
}
return "asp";
} else if (typeof appjet === "object") {
return "appjet";
} else if (false) {
// TODO: other platforms
} else { return "unknown"; }
})();
/**
* Add a header
*/
var addHeader = platforms[platform].addHeader;
/**
* The User agent string from the agent
*/
var userAgent = platforms[platform].userAgent;
/**
* Convert an object to its JSON representation
*/
var toJSON = platforms[platform].toJSON;
/**
* Does the user agent have FirePHP installed?
*
* The official FirePHP library checks the version, etc., but this just
* checks if "FirePHP" is in the user agent string
*/
var hasFirePHP = userAgent.match("FirePHP") !== null;
/**
* The index of headers to be added. Starts at 1
*/
var index = 1;
/**
* The maximium length of any given message
*/
var maxLength = 5000;
/**
* This is an implementation of the sprintf function based on the one
* found at http://webtoolkit.info. Takes an array instead of
* multiple arguments
*
* @see http://www.webtoolkit.info/javascript-sprintf.html
*/
function sprintf(args) {
if (typeof args == "undefined") { return null; }
if (args.length < 1) { return null; }
if (typeof args[0] != "string") { return null; }
if (typeof RegExp == "undefined") { return null; }
function convert(match, nosign){
if (nosign) {
match.sign = '';
} else {
match.sign = match.negative ? '-' : match.sign;
}
var l = match.min - match.argument.length + 1 - match.sign.length;
var pad = new Array(l < 0 ? 0 : l).join(match.pad);
if (!match.left) {
if (match.pad == "0" || nosign) {
return match.sign + pad + match.argument;
} else {
return pad + match.sign + match.argument;
}
} else {
if (match.pad == "0" || nosign) {
return match.sign + match.argument + pad.replace(/0/g, ' ');
} else {
return match.sign + match.argument + pad;
}
}
}
var string = args[0];
var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdifosxX])))/g);
var matches = new Array();
var strings = new Array();
var convCount = 0;
var stringPosStart = 0;
var stringPosEnd = 0;
var matchPosEnd = 0;
var newString = '';
var match = null;
while (match = exp.exec(string)) {
if (match[9]) { convCount += 1; }
stringPosStart = matchPosEnd;
stringPosEnd = exp.lastIndex - match[0].length;
strings[strings.length] = string.substring(stringPosStart, stringPosEnd);
matchPosEnd = exp.lastIndex;
matches[matches.length] = {
match: match[0],
left: match[3] ? true : false,
sign: match[4] || '',
pad: match[5] || ' ',
min: match[6] || 0,
precision: match[8],
code: match[9] || '%',
negative: parseInt(args[convCount]) < 0 ? true : false,
argument: String(args[convCount])
};
}
strings[strings.length] = string.substring(matchPosEnd);
if (matches.length == 0) { return string; }
if ((args.length - 1) < convCount) { return null; }
var code = null;
var match = null;
var i = null;
for (i=0; i<matches.length; i++) {
if (matches[i].code == '%') { substitution = '%' }
else if (matches[i].code == 'b') {
matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
substitution = convert(matches[i], true);
}
else if (matches[i].code == 'c') {
matches[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
substitution = convert(matches[i], true);
}
else if (matches[i].code == 'd' || matches[i].code == 'i') {
matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
substitution = convert(matches[i]);
}
else if (matches[i].code == 'f') {
matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
substitution = convert(matches[i]);
}
else if (matches[i].code == 'o') {
matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
substitution = convert(matches[i]);
}
else if (matches[i].code == 's') {
matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length)
substitution = convert(matches[i], true);
}
else if (matches[i].code == 'x') {
matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
substitution = convert(matches[i]);
}
else if (matches[i].code == 'X') {
matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
substitution = convert(matches[i]).toUpperCase();
}
else {
substitution = matches[i].match;
}
newString += strings[i];
newString += substitution;
}
newString += strings[i];
return newString;
}
/**
* Combine the arguments to the function and run them through
* sprintf if necessary
*/
function handleArgs(args) {
args = args || [];
var argc = args.length;
var s = []; // String to return
// Number of items to substitute in first argument
var substitutions = 0;
if (argc > 0) {
if (typeof args[0] === "string") {
substitutions = (args[0].match(/\%\w/g) || []).length + 1;
// Run string through sprintf is needed
if (substitutions > 1) {
s.push(sprintf(args.slice(0, substitutions)));
args = args.slice(substitutions, argc);
argc = args.length;
}
}
for (var i = 0; i < argc; i += 1) {
s.push(String(args[i]));
}
}
return s.join(" ");
}
/**
* The function that does the work of setting the headers and formatting
*/
function f(level, args) {
if (!platform || !hasFirePHP || !enabled) { return; }
level = level || levels.log;
args = Array.prototype.slice.call(args);
var s = ""; // The string to send to the console
var msg = ""; // The complete header message
var meta = { // Metadata for object
Type : level
};
var time; // Value for timer
if (args.length > 0) { // Proceed if there are arguments
// If the first argument is an object, only it gets processed
if (typeof args[0] === "object") {
// Error objects can be handled with more detail if they
// were thrown with the "new Error(...)" constructor
if (level === levels.error && args[0] instanceof Error) {
if (args[0].lineNumber) {
meta.Line = args[0].lineNumber;
}
if (args[0].fileName) {
meta.File = args[0].fileName;
}
}
s = args[0];
// If the first argument is not an object, we assume it's a
// string or number and process it accordingly
} else {
if (level === levels.group) { // Handle groups
meta.Label = args[0];
} else if (level === levels.time) { // Handle time
timers[args[0]] = { start : (new Date()).getTime() };
return;
} else if (level === levels.timeEnd) { // Handle time end
meta.Type = levels.info;
if (args[0] in timers) {
timers[args[0]].end = (new Date()).getTime();
// Calculate elapsed time
time = timers[args[0]].end - timers[args[0]].start;
if (isFinite(time)) {
args[0] = args[0] + ": " + time + "ms";
} else { args[0] = "Invalid timer"; }
}
}
s = handleArgs(args);
}
} else { return; } // Do nothing if no arguments
// If the starting headers haven't been added, add them
if (index <= 1) {
addHeader("X-Wf-Protocol-1", "http://meta.wildfirehq.org/Protocol/JsonStream/0.2");
addHeader("X-Wf-1-Plugin-1", " http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.2.0");
addHeader("X-Wf-1-Structure-1", "http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1");
}
s = toJSON(s); // JSONify string
meta = toJSON(meta); // And meta
msg = '[' + meta + ',' + s + ']'; // Start message
if (msg.length < maxLength) {
addHeader('X-Wf-1-1-1-' + index, msg.length + '|' + msg + '|');
} else { // Split the message up if it's greater than maxLength
(function splitMessage() {
var keyPrefix = 'X-Wf-1-1-1-';
var key = keyPrefix + index;
var value = "";
var totalLength = msg.length;
var messages = [];
var chars = msg.split("");
var part = "";
// Split the messages up
for (var i = 0; i < chars.length; i += maxLength) {
part = chars.slice(i, i + maxLength).join("");
messages.push(part);
}
// Add a header for each part
for(i = 0; i < messages.length; i += 1) {
key = keyPrefix + index;
value = '|' + messages[i] + '|';
if (i === 0) { value = totalLength + value; }
if (i !== messages.length - 1) { value += "\\"; }
addHeader(key, value);
index += 1;
}
})();
}
index += 1;
}
return {
log : function log() {
f(levels.log, arguments);
},
debug : function debug() {
// log & debug do the same thing
f(levels.log, arguments);
},
info : function info() {
f(levels.info, arguments);
},
warn : function warn() {
f(levels.warn, arguments);
},
error : function error() {
f(levels.error, arguments);
},
assert : function assert() {
f(levels.warn, ["console.assert() is not implemented"]);
},
/**
* dir is Firebug specific and probably will not be implemented
*/
dir : function dir() {
f(levels.warn, ["console.dir() is not implemented"]);
},
/**
* dirxml is Firebug specific and probably will not be implemented
*/
dirxml : function dirxml() {
f(levels.warn, ["console.dirxml() is not implemented"]);
},
trace : function trace() {
f(levels.warn, ["console.trace() is not implemented"]);
},
group : function group() {
f(levels.group, [arguments[0] || ""]);
},
groupEnd : function groupEnd() {
f(levels.groupEnd, [""]);
},
time : function time() {
f(levels.time, [arguments[0] || ""]);
},
timeEnd : function timeEnd() {
f(levels.timeEnd, [arguments[0] || ""]);
},
/**
* profile is Firebug specific and probably will not be implemented
*/
profile : function profile() {
f(levels.warn, ["console.profile() is not implemented"]);
},
/**
* profileEnd is Firebug specific and probably will not be
* implemented
*/
profileEnd : function profileEnd() {
f(levels.warn, ["console.profileEnd() is not implemented"]);
},
count : function count() {
f(levels.warn, ["console.count() is not implemented"]);
},
/**
* table shows the logged object in a tablular format. This is NOT
* part of the Firebug console API and is specific to Wildfire
*/
table : function table() {
f(levels.warn, ["console.table() is not implemented"]);
},
/**
* dump is FirePHP specific and shows an object in the Response
* pane of the Firebug Net tab.I don't forsee implementing it at
* any time.
*/
dump : function dump() {
f(levels.warn, ["console.dump() is not implemented"]);
},
/**
* Enable the console
*/
enable : function enable() {
enabled = true;
f(levels.info, ["console is enabled"]);
},
/**
* Disable the console
*/
disable : function disable() {
f(levels.info, ["console is disabled"]);
enabled = false;
}
};
})();
//var traceTime;
//trace = function(){
// var traceTime = new Date();
// var fso
//}
//debug = (function(){
// var traceTime
// ,fso;
// var filename = 'd:/te.txt';
// var stream;
// return {
// trace: function (name, text, raw, url) {
// if (!traceTime) {
// traceTime = new Date();
// }
// if (!fso) {
// fso = new ActiveXObject("Scripting.FileSystemObject");
// }
//
// var script = Request.ServerVariables("SCRIPT_NAME");
//
// if (!stream) {
// stream = fso.OpenTextFile(filename, 8, true); // ForAppending=8
// if (!raw) stream.WriteLine("--------------------------------------------------------------------------------");
// }
// if (!raw) {
// var timestamp = new Date().valueOf() - traceTime.valueOf();
// var caller = arguments.callee.caller;
// var fn = caller+"";
// var i = fn.indexOf("function")+9;
// var j = fn.indexOf("(");
// var k = fn.indexOf(")");
// var __name = (i<j) ? fn.substring(i,j) : name;
// var __args = (k>j+1) ? fn.substring(j+1, k).split(",") : [];
// var temp = [];
// for (var i=0; i<__args.length; i++) {
// var v = caller.arguments[i];
// var s = (v + "");
// if (s.length>160) s = s.substring(0,160) + "...";
// s = s.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
// switch (typeof v) {
// case "undefined" : s = "<>"; break;
// case "string" : s = "\"" + s + "\""; break;
// case "number" :
// case "boolean" :
// case "date" :
// case "object" :
// default :
// }
// temp.push(__args[i] + "=" + s);
// }
// stream.WriteLine("[" + traceTime.toUTCString() + "] " + script + ": " + (__name+"()" + (temp.length ? " " + temp : "") + "") + (text ? " {" + text + "}" : "") + " (" + timestamp + "ms)");
// } else {
// stream.WriteLine(text);
// }
//
// }
// ,closeTrace: function(){
// if(stream && stream.close)stream.close();
// stream = null;
// fso = null;
// }
// }
//})();
//// asp的session可以放置对象!这样wsc容器内都可以使用!
//Session.Contents('$$_console') = $$.console;
//Session.Contents('trace') = debug.trace;
log = $$.console.log; | JavaScript |
/**
* @classs Edk.logger 记录日志。
/**
* LOG一些SQL操作。读的操作就不LOG。
* @param rs {ADODB.Recordset} 记录集合
* @return {ADODB.Recordset}
*/
function logSQL(rs){
// var writeSQL = /(.*?((insert)|(delete)|(update)|(drop)|(truncate)).*?){2,}/i;
var writeSQL = /((insert)|(delete)|(update)|(drop)|(truncate))/i;
var hasSource = (typeof rs.Source != 'undefined') && (typeof rs.Source != 'unknown');
if( hasSource && writeSQL.test(rs.Source)){
// new $$.logger({sql : rs.Source});
}
return rs;
}
*/
$$.logger = function(a){
if(a.sql){
// todo
this.add({
type: "sqlLog"
,sql : a.sql
,createDate: new Date
});
}else if(a.text){
this.text = a.text;
}
}
$$.logger.prototype = {
/**
*
* @param {Object} log
*/
add: function(log){
var XML = $$.XML;
var json, tmp;
if(log.sql){
tmp = log.sql;
delete log.sql;
}
json = XML.json2xml(log);
var logItem = new ActiveXObject('Msxml2.DOMDocument.6.0');
if(!logItem.loadXML('<item>' + json + '</item>')){
throw "生成日志XML文档时错误";
}
var value = logItem.createElement("value");
var cd = logItem.createCDATASection(tmp);
value.appendChild(cd);
logItem.firstChild.appendChild(value);
// 插入新的XML节点
var xml = new ActiveXObject('Msxml2.DOMDocument.6.0');
if(!xml.load(Server.Mappath('/app/public/log.xml'))){
throw "保存日志XML文档时错误";
}
xml.lastChild.appendChild(logItem.firstChild);
XML.saveXML(xml);
logItem = xml = value = cd = null;
return true;
}
/**
* 获取客户端的IP地址。
* @return {}
*/
,getIP : function(isParseInt){
var ip = Request.ServerVariables("HTTP_X_FORWARDED_FOR")();
// for 0.0.0.0
if (!ip || (ip && ip.length < 7)){
ip = Request.ServerVariables("REMOTE_ADDR")();
}
// what does this line be used to?
// if (strIP.indexOf(",") > 7) strIP = strIP.substr(0, strIP.indexOf(","));
if(isParseInt){
ip = ip.split('.');
ip = Number(ip[0]) * 256 * 256 * 256 +
Number(ip[1]) * 256 * 256 +
Number(ip[2]) * 256 +
Number(ip[3]);
}
return ip;
}()
}; | JavaScript |
/* =================================================================================================
* TransMenu
* March, 2003
* Customizable multi-level animated DHTML menus with transparency.
*
* Copyright Aaron Boodman (www.youngpup.net)
* =================================================================================================
* updates:
* 04.19.04 fixed cascade problem with menus nested greater than two levels.
* 12.23.03 added hideCurrent for menu actuators with no menus. renamed to TransMenu.
* 04.18.03 fixed render bug in IE 5.0 Mac by removing that browser from compatibility table ;)
* also made gecko check a little more strict by specifying build no.
* ============================================================================================== */
//==================================================================================================
// Configuration properties
//==================================================================================================
TransMenu.spacerGif = "x.gif"; // path to a transparent spacer gif
TransMenu.dingbatOn = "submenu-on.gif"; // path to the active sub menu dingbat
TransMenu.dingbatOff = "submenu-off.gif"; // path to the inactive sub menu dingbat
TransMenu.dingbatSize = 14; // size of the dingbat (square shape assumed)
TransMenu.menuPadding = 5; // padding between menu border and items grid
TransMenu.itemPadding = 3; // additional padding around each item
TransMenu.shadowSize = 2; // size of shadow under menu
TransMenu.shadowOffset = 3; // distance shadow should be offset from leading edge
TransMenu.shadowColor = "#888"; // color of shadow (transparency is set in CSS)
TransMenu.shadowPng = "grey-40.png"; // a PNG graphic to serve as the shadow for mac IE5
TransMenu.backgroundColor = "white"; // color of the background (transparency set in CSS)
TransMenu.backgroundPng = "white-90.png"; // a PNG graphic to server as the background for mac IE5
TransMenu.hideDelay = 1000; // number of milliseconds to wait before hiding a menu
TransMenu.slideTime = 400; // number of milliseconds it takes to open and close a menu
//==================================================================================================
// Internal use properties
//==================================================================================================
TransMenu.reference = {topLeft:1,topRight:2,bottomLeft:3,bottomRight:4};
TransMenu.direction = {down:1,right:2};
TransMenu.registry = [];
TransMenu._maxZ = 100;
//==================================================================================================
// Static methods
//==================================================================================================
// supporting win ie5+, mac ie5.1+ and gecko >= mozilla 1.0
TransMenu.isSupported = function() {
var ua = navigator.userAgent.toLowerCase();
var pf = navigator.platform.toLowerCase();
var an = navigator.appName;
var r = false;
if (ua.indexOf("gecko") > -1 && navigator.productSub >= 20020605) r = true; // gecko >= moz 1.0
else if (an == "Microsoft Internet Explorer") {
if (document.getElementById) { // ie5.1+ mac,win
if (pf.indexOf("mac") == 0) {
r = /msie (\d(.\d*)?)/.test(ua) && Number(RegExp.$1) >= 5.1;
}
else r = true;
}
}
return r;
}
// call this in onload once menus have been created
TransMenu.initialize = function() {
for (var i = 0, menu = null; menu = this.registry[i]; i++) {
menu.initialize();
}
}
// call this in document body to write out menu html
TransMenu.renderAll = function() {
var aMenuHtml = [];
for (var i = 0, menu = null; menu = this.registry[i]; i++) {
aMenuHtml[i] = menu.toString();
}
var div = document.createElement("div");
div.innerHTML = aMenuHtml.join("");
document.getElementsByTagName('body')[0].appendChild(div);
}
//==================================================================================================
// TransMenu constructor (only called internally)
//==================================================================================================
// oActuator : The thing that causes the menu to be shown when it is mousedover. Either a
// reference to an HTML element, or a TransMenuItem from an existing menu.
// iDirection : The direction to slide out. One of TransMenu.direction.
// iLeft : Left pixel offset of menu from actuator
// iTop : Top pixel offset of menu from actuator
// iReferencePoint : Corner of actuator to measure from. One of TransMenu.referencePoint.
// parentMenuSet : Menuset this menu will be added to.
//==================================================================================================
function TransMenu(oActuator, iDirection, iLeft, iTop, iReferencePoint, parentMenuSet) {
// public methods
this.addItem = addItem;
this.addMenu = addMenu;
this.toString = toString;
this.initialize = initialize;
this.isOpen = false;
this.show = show;
this.hide = hide;
this.items = [];
// events
this.onactivate = new Function(); // when the menu starts to slide open
this.ondeactivate = new Function(); // when the menu finishes sliding closed
this.onmouseover = new Function(); // when the menu has been moused over
this.onqueue = new Function(); // hack .. when the menu sets a timer to be closed a little while in the future
this.ondequeue = new Function();
// initialization
this.index = TransMenu.registry.length;
TransMenu.registry[this.index] = this;
var id = "TransMenu" + this.index;
var contentHeight = null;
var contentWidth = null;
var childMenuSet = null;
var animating = false;
var childMenus = [];
var slideAccel = -1;
var elmCache = null;
var ready = false;
var _this = this;
var a = null;
var pos = iDirection == TransMenu.direction.down ? "top" : "left";
var dim = null;
// private and public method implimentations
function addItem(sText, sUrl) {
var item = new TransMenuItem(sText, sUrl, this);
item._index = this.items.length;
this.items[item._index] = item;
}
function addMenu(oMenuItem) {
if (!oMenuItem.parentMenu == this) throw new Error("Cannot add a menu here");
if (childMenuSet == null) childMenuSet = new TransMenuSet(TransMenu.direction.right, -5, 2, TransMenu.reference.topRight);
var m = childMenuSet.addMenu(oMenuItem);
childMenus[oMenuItem._index] = m;
m.onmouseover = child_mouseover;
m.ondeactivate = child_deactivate;
m.onqueue = child_queue;
m.ondequeue = child_dequeue;
return m;
}
function initialize() {
initCache();
initEvents();
initSize();
ready = true;
}
function show() {
//dbg_dump("show");
if (ready) {
_this.isOpen = true;
animating = true;
setContainerPos();
elmCache["clip"].style.visibility = "visible";
elmCache["clip"].style.zIndex = TransMenu._maxZ++;
//dbg_dump("maxZ: " + TransMenu._maxZ);
slideStart();
_this.onactivate();
}
}
function hide() {
if (ready) {
_this.isOpen = false;
animating = true;
for (var i = 0, item = null; item = elmCache.item[i]; i++)
dehighlight(item);
if (childMenuSet) childMenuSet.hide();
slideStart();
_this.ondeactivate();
}
}
function setContainerPos() {
var sub = oActuator.constructor == TransMenuItem;
var act = sub ? oActuator.parentMenu.elmCache["item"][oActuator._index] : oActuator;
var el = act;
var x = 0;
var y = 0;
var minX = 0;
var maxX = (window.innerWidth ? window.innerWidth : document.body.clientWidth) - parseInt(elmCache["clip"].style.width);
var minY = 0;
var maxY = (window.innerHeight ? window.innerHeight : document.body.clientHeight) - parseInt(elmCache["clip"].style.height);
// add up all offsets... subtract any scroll offset
while (sub ? el.parentNode.className.indexOf("transMenu") == -1 : el.offsetParent) {
x += el.offsetLeft;
y += el.offsetTop;
if (el.scrollLeft) x -= el.scrollLeft;
if (el.scrollTop) y -= el.scrollTop;
el = el.offsetParent;
}
if (oActuator.constructor == TransMenuItem) {
x += parseInt(el.parentNode.style.left);
y += parseInt(el.parentNode.style.top);
}
switch (iReferencePoint) {
case TransMenu.reference.topLeft:
break;
case TransMenu.reference.topRight:
x += act.offsetWidth;
break;
case TransMenu.reference.bottomLeft:
y += act.offsetHeight;
break;
case TransMenu.reference.bottomRight:
x += act.offsetWidth;
y += act.offsetHeight;
break;
}
x += iLeft;
y += iTop;
x = Math.max(Math.min(x, maxX), minX);
y = Math.max(Math.min(y, maxY), minY);
elmCache["clip"].style.left = x + "px";
elmCache["clip"].style.top = y + "px";
}
function slideStart() {
var x0 = parseInt(elmCache["content"].style[pos]);
var x1 = _this.isOpen ? 0 : -dim;
if (a != null) a.stop();
a = new Accelimation(x0, x1, TransMenu.slideTime, slideAccel);
a.onframe = slideFrame;
a.onend = slideEnd;
a.start();
}
function slideFrame(x) {
elmCache["content"].style[pos] = x + "px";
}
function slideEnd() {
if (!_this.isOpen) elmCache["clip"].style.visibility = "hidden";
animating = false;
}
function initSize() {
// everything is based off the size of the items table...
var ow = elmCache["items"].offsetWidth;
var oh = elmCache["items"].offsetHeight;
var ua = navigator.userAgent.toLowerCase();
// clipping container should be ow/oh + the size of the shadow
elmCache["clip"].style.width = ow + TransMenu.shadowSize + 2 + "px";
elmCache["clip"].style.height = oh + TransMenu.shadowSize + 2 + "px";
// same with content...
elmCache["content"].style.width = ow + TransMenu.shadowSize + "px";
elmCache["content"].style.height = oh + TransMenu.shadowSize + "px";
contentHeight = oh + TransMenu.shadowSize;
contentWidth = ow + TransMenu.shadowSize;
dim = iDirection == TransMenu.direction.down ? contentHeight : contentWidth;
// set initially closed
elmCache["content"].style[pos] = -dim - TransMenu.shadowSize + "px";
elmCache["clip"].style.visibility = "hidden";
// if *not* mac/ie 5
if (ua.indexOf("mac") == -1 || ua.indexOf("gecko") > -1) {
// set background div to offset size
elmCache["background"].style.width = ow + "px";
elmCache["background"].style.height = oh + "px";
elmCache["background"].style.backgroundColor = TransMenu.backgroundColor;
// shadow left starts at offset left and is offsetHeight pixels high
elmCache["shadowRight"].style.left = ow + "px";
elmCache["shadowRight"].style.height = oh - (TransMenu.shadowOffset - TransMenu.shadowSize) + "px";
elmCache["shadowRight"].style.backgroundColor = TransMenu.shadowColor;
// shadow bottom starts at offset height and is offsetWidth - shadowOffset
// pixels wide (we don't want the bottom and right shadows to overlap or we
// get an extra bright bottom-right corner)
elmCache["shadowBottom"].style.top = oh + "px";
elmCache["shadowBottom"].style.width = ow - TransMenu.shadowOffset + "px";
elmCache["shadowBottom"].style.backgroundColor = TransMenu.shadowColor;
}
// mac ie is a little different because we use a PNG for the transparency
else {
// set background div to offset size
elmCache["background"].firstChild.src = TransMenu.backgroundPng;
elmCache["background"].firstChild.width = ow;
elmCache["background"].firstChild.height = oh;
// shadow left starts at offset left and is offsetHeight pixels high
elmCache["shadowRight"].firstChild.src = TransMenu.shadowPng;
elmCache["shadowRight"].style.left = ow + "px";
elmCache["shadowRight"].firstChild.width = TransMenu.shadowSize;
elmCache["shadowRight"].firstChild.height = oh - (TransMenu.shadowOffset - TransMenu.shadowSize);
// shadow bottom starts at offset height and is offsetWidth - shadowOffset
// pixels wide (we don't want the bottom and right shadows to overlap or we
// get an extra bright bottom-right corner)
elmCache["shadowBottom"].firstChild.src = TransMenu.shadowPng;
elmCache["shadowBottom"].style.top = oh + "px";
elmCache["shadowBottom"].firstChild.height = TransMenu.shadowSize;
elmCache["shadowBottom"].firstChild.width = ow - TransMenu.shadowOffset;
}
}
function initCache() {
var menu = document.getElementById(id);
var all = menu.all ? menu.all : menu.getElementsByTagName("*"); // IE/win doesn't support * syntax, but does have the document.all thing
elmCache = {};
elmCache["clip"] = menu;
elmCache["item"] = [];
for (var i = 0, elm = null; elm = all[i]; i++) {
switch (elm.className) {
case "items":
case "content":
case "background":
case "shadowRight":
case "shadowBottom":
elmCache[elm.className] = elm;
break;
case "item":
elm._index = elmCache["item"].length;
elmCache["item"][elm._index] = elm;
break;
}
}
// hack!
_this.elmCache = elmCache;
}
function initEvents() {
// hook item mouseover
for (var i = 0, item = null; item = elmCache.item[i]; i++) {
item.onmouseover = item_mouseover;
item.onmouseout = item_mouseout;
item.onclick = item_click;
}
// hook actuation
if (typeof oActuator.tagName != "undefined") {
oActuator.onmouseover = actuator_mouseover;
oActuator.onmouseout = actuator_mouseout;
}
// hook menu mouseover
elmCache["content"].onmouseover = content_mouseover;
elmCache["content"].onmouseout = content_mouseout;
}
function highlight(oRow) {
oRow.className = "item hover";
if (childMenus[oRow._index])
oRow.lastChild.firstChild.src = TransMenu.dingbatOn;
}
function dehighlight(oRow) {
oRow.className = "item";
if (childMenus[oRow._index])
oRow.lastChild.firstChild.src = TransMenu.dingbatOff;
}
function item_mouseover() {
if (!animating) {
highlight(this);
if (childMenus[this._index])
childMenuSet.showMenu(childMenus[this._index]);
else if (childMenuSet) childMenuSet.hide();
}
}
function item_mouseout() {
if (!animating) {
if (childMenus[this._index])
childMenuSet.hideMenu(childMenus[this._index]);
else // otherwise child_deactivate will do this
dehighlight(this);
}
}
function item_click() {
if (!animating) {
if (_this.items[this._index].url)
location.href = _this.items[this._index].url;
}
}
function actuator_mouseover() {
parentMenuSet.showMenu(_this);
}
function actuator_mouseout() {
parentMenuSet.hideMenu(_this);
}
function content_mouseover() {
if (!animating) {
parentMenuSet.showMenu(_this);
_this.onmouseover();
}
}
function content_mouseout() {
if (!animating) {
parentMenuSet.hideMenu(_this);
}
}
function child_mouseover() {
if (!animating) {
parentMenuSet.showMenu(_this);
}
}
function child_deactivate() {
for (var i = 0; i < childMenus.length; i++) {
if (childMenus[i] == this) {
dehighlight(elmCache["item"][i]);
break;
}
}
}
function child_queue() {
parentMenuSet.hideMenu(_this);
}
function child_dequeue() {
parentMenuSet.showMenu(_this);
}
function toString() {
var aHtml = [];
var sClassName = "transMenu" + (oActuator.constructor != TransMenuItem ? " top" : "");
for (var i = 0, item = null; item = this.items[i]; i++) {
aHtml[i] = item.toString(childMenus[i]);
}
return '<div id="' + id + '" class="' + sClassName + '">' +
'<div class="content"><table class="items" cellpadding="0" cellspacing="0" border="0">' +
'<tr><td colspan="2"><img src="' + TransMenu.spacerGif + '" width="1" height="' + TransMenu.menuPadding + '"></td></tr>' +
aHtml.join('') +
'<tr><td colspan="2"><img src="' + TransMenu.spacerGif + '" width="1" height="' + TransMenu.menuPadding + '"></td></tr></table>' +
'<div class="shadowBottom"><img src="' + TransMenu.spacerGif + '" width="1" height="1"></div>' +
'<div class="shadowRight"><img src="' + TransMenu.spacerGif + '" width="1" height="1"></div>' +
'<div class="background"><img src="' + TransMenu.spacerGif + '" width="1" height="1"></div>' +
'</div></div>';
}
}
//==================================================================================================
// TransMenuSet
//==================================================================================================
// iDirection : The direction to slide out. One of TransMenu.direction.
// iLeft : Left pixel offset of menus from actuator
// iTop : Top pixel offset of menus from actuator
// iReferencePoint : Corner of actuator to measure from. One of TransMenu.referencePoint.
//==================================================================================================
TransMenuSet.registry = [];
function TransMenuSet(iDirection, iLeft, iTop, iReferencePoint) {
// public methods
this.addMenu = addMenu;
this.showMenu = showMenu;
this.hideMenu = hideMenu;
this.hide = hide;
this.hideCurrent = hideCurrent;
// initialization
var menus = [];
var _this = this;
var current = null;
this.index = TransMenuSet.registry.length;
TransMenuSet.registry[this.index] = this;
// method implimentations...
function addMenu(oActuator) {
var m = new TransMenu(oActuator, iDirection, iLeft, iTop, iReferencePoint, this);
menus[menus.length] = m;
return m;
}
function showMenu(oMenu) {
if (oMenu != current) {
// close currently open menu
if (current != null) hide(current);
// set current menu to this one
current = oMenu;
// if this menu is closed, open it
oMenu.show();
}
else {
// hide pending calls to close this menu
cancelHide(oMenu);
}
}
function hideMenu(oMenu) {
//dbg_dump("hideMenu a " + oMenu.index);
if (current == oMenu && oMenu.isOpen) {
//dbg_dump("hideMenu b " + oMenu.index);
if (!oMenu.hideTimer) scheduleHide(oMenu);
}
}
function scheduleHide(oMenu) {
//dbg_dump("scheduleHide " + oMenu.index);
oMenu.onqueue();
oMenu.hideTimer = window.setTimeout("TransMenuSet.registry[" + _this.index + "].hide(TransMenu.registry[" + oMenu.index + "])", TransMenu.hideDelay);
}
function cancelHide(oMenu) {
//dbg_dump("cancelHide " + oMenu.index);
if (oMenu.hideTimer) {
oMenu.ondequeue();
window.clearTimeout(oMenu.hideTimer);
oMenu.hideTimer = null;
}
}
function hide(oMenu) {
if (!oMenu && current) oMenu = current;
if (oMenu && current == oMenu && oMenu.isOpen) {
hideCurrent();
}
}
function hideCurrent() {
if (null != current) {
cancelHide(current);
current.hideTimer = null;
current.hide();
current = null;
}
}
}
//==================================================================================================
// TransMenuItem (internal)
// represents an item in a dropdown
//==================================================================================================
// sText : The item display text
// sUrl : URL to load when the item is clicked
// oParent : Menu this item is a part of
//==================================================================================================
function TransMenuItem(sText, sUrl, oParent) {
this.toString = toString;
this.text = sText;
this.url = sUrl;
this.parentMenu = oParent;
function toString(bDingbat) {
var sDingbat = bDingbat ? TransMenu.dingbatOff : TransMenu.spacerGif;
var iEdgePadding = TransMenu.itemPadding + TransMenu.menuPadding;
var sPaddingLeft = "padding:" + TransMenu.itemPadding + "px; padding-left:" + iEdgePadding + "px;"
var sPaddingRight = "padding:" + TransMenu.itemPadding + "px; padding-right:" + iEdgePadding + "px;"
return '<tr class="item"><td nowrap style="' + sPaddingLeft + '">' +
sText + '</td><td width="14" style="' + sPaddingRight + '">' +
'<img src="' + sDingbat + '" width="14" height="14"></td></tr>';
}
}
//=====================================================================
// Accel[erated] [an]imation object
// change a property of an object over time in an accelerated fashion
//=====================================================================
// obj : reference to the object whose property you'd like to animate
// prop : property you would like to change eg: "left"
// to : final value of prop
// time : time the animation should take to run
// zip : optional. specify the zippiness of the acceleration. pick a
// number between -1 and 1 where -1 is full decelerated, 1 is
// full accelerated, and 0 is linear (no acceleration). default
// is 0.
// unit : optional. specify the units for use with prop. default is
// "px".
//=====================================================================
// bezier functions lifted from the lib_animation.js file in the
// 13th Parallel API. www.13thparallel.org
//=====================================================================
function Accelimation(from, to, time, zip) {
if (typeof zip == "undefined") zip = 0;
if (typeof unit == "undefined") unit = "px";
this.x0 = from;
this.x1 = to;
this.dt = time;
this.zip = -zip;
this.unit = unit;
this.timer = null;
this.onend = new Function();
this.onframe = new Function();
}
//=====================================================================
// public methods
//=====================================================================
// after you create an accelimation, you call this to start it-a runnin'
Accelimation.prototype.start = function() {
this.t0 = new Date().getTime();
this.t1 = this.t0 + this.dt;
var dx = this.x1 - this.x0;
this.c1 = this.x0 + ((1 + this.zip) * dx / 3);
this.c2 = this.x0 + ((2 + this.zip) * dx / 3);
Accelimation._add(this);
}
// and if you need to stop it early for some reason...
Accelimation.prototype.stop = function() {
Accelimation._remove(this);
}
//=====================================================================
// private methods
//=====================================================================
// paints one frame. gets called by Accelimation._paintAll.
Accelimation.prototype._paint = function(time) {
if (time < this.t1) {
var elapsed = time - this.t0;
this.onframe(Accelimation._getBezier(elapsed/this.dt,this.x0,this.x1,this.c1,this.c2));
}
else this._end();
}
// ends the animation
Accelimation.prototype._end = function() {
Accelimation._remove(this);
this.onframe(this.x1);
this.onend();
}
//=====================================================================
// static methods (all private)
//=====================================================================
// add a function to the list of ones to call periodically
Accelimation._add = function(o) {
var index = this.instances.length;
this.instances[index] = o;
// if this is the first one, start the engine
if (this.instances.length == 1) {
this.timerID = window.setInterval("Accelimation._paintAll()", this.targetRes);
}
}
// remove a function from the list
Accelimation._remove = function(o) {
for (var i = 0; i < this.instances.length; i++) {
if (o == this.instances[i]) {
this.instances = this.instances.slice(0,i).concat( this.instances.slice(i+1) );
break;
}
}
// if that was the last one, stop the engine
if (this.instances.length == 0) {
window.clearInterval(this.timerID);
this.timerID = null;
}
}
// "engine" - call each function in the list every so often
Accelimation._paintAll = function() {
var now = new Date().getTime();
for (var i = 0; i < this.instances.length; i++) {
this.instances[i]._paint(now);
}
}
// Bezier functions:
Accelimation._B1 = function(t) { return t*t*t }
Accelimation._B2 = function(t) { return 3*t*t*(1-t) }
Accelimation._B3 = function(t) { return 3*t*(1-t)*(1-t) }
Accelimation._B4 = function(t) { return (1-t)*(1-t)*(1-t) }
//Finds the coordinates of a point at a certain stage through a bezier curve
Accelimation._getBezier = function(percent,startPos,endPos,control1,control2) {
return endPos * this._B1(percent) + control2 * this._B2(percent) + control1 * this._B3(percent) + startPos * this._B4(percent);
}
//=====================================================================
// static properties
//=====================================================================
Accelimation.instances = [];
Accelimation.targetRes = 10;
Accelimation.timerID = null;
//=====================================================================
// IE win memory cleanup
//=====================================================================
if (window.attachEvent) {
var cearElementProps = [
'data',
'onmouseover',
'onmouseout',
'onmousedown',
'onmouseup',
'ondblclick',
'onclick',
'onselectstart',
'oncontextmenu'
];
window.attachEvent("onunload", function() {
var el;
for(var d = document.all.length;d--;){
el = document.all[d];
for(var c = cearElementProps.length;c--;){
el[cearElementProps[c]] = null;
}
}
});
} | JavaScript |
/**
*
* @author Alexander Khaylo <alex.khaylo@gmail.com>
* @copyright Copyright (c) 2012 NIX Solutions (http://www.nixsolutions.com)
*/
$(function() {
$('.grid-buttons').delegate('a#up-button', 'click', function(e) {
e.stopPropagation();
var url = this.href, res = [];
$('#grid').find("input:checked").each(function() {
res.push(this.value);
});
if(!res.length) {
alert('No row selected');
} else if(res.length == 1) {
$.post(url, { id: res[0] }, function() {
$('#grid').data('plugin_grid').refresh();
});
} else {
alert('Many row selected');
}
return false;
});
$('.grid-buttons').delegate('a#down-button', 'click', function(e) {
e.stopPropagation();
var url = this.href, res = [];
$('#grid').find("input:checked").each(function() {
res.push(this.value);
});
if(!res.length) {
alert('No row selected');
} else if(res.length == 1) {
$.post(url, { id: res[0] }, function() {
$('#grid').data('plugin_grid').refresh();
});
} else {
alert('Many row selected');
}
return false;
});
});
| JavaScript |
/**
* Notices
*/
var Messages = (function($, undefined) {
var M = {
_uid:"messages",
_el:null,
_to:null,
_callback:null,
_settings:{
'fadeIn':500,
'fadeOut':500,
'showTime':3000
},
getContainer:function(){
if (!M._el) {
if ($('#'+M._uid).length == 0) {
M._el = $('<div id="'+M._uid+'">'+'</div>');
M._el.prependTo('body');
M._el.css({display:'none'});
} else if ($('#'+M._uid).length > 0) {
M._el = $('#'+M._uid);
}
M._el.click(function(){
$(this).hide();
});
}
return M._el;
},
showMessage:function(type, text) {
var el = M.getContainer();
if (type != undefined && text != undefined) {
// add new message to container
var p = $('<p class="'+type+'">'+text+'</p>');
el.append(p);
} else {
text = el.text();
}
// additonal 12ms for char
var delay = M._settings.showTime + text.length * 12;
el.stop(true, true);
el.data('fx', null);
// hack for bootstrap.js with float header menu
var top = 0;
if ($('.navbar-fixed-top').length) {
top += 40;
}
if ($('.subnav-fixed').length) {
top += 37;
}
el.css('top', top);
el.animate({opacity:"show"}, M._settings.fadeIn)
.delay(delay)
.animate({opacity: "hide"}, M._settings.fadeOut, M.callback);
},
addMessages:function(messages) {
for (var type in messages) {
$(messages[type]).each(function(i, el){
M.showMessage(type, el);
})
}
},
addError:function(message) {
M.showMessage('error', message);
},
addNotice:function(message) {
M.showMessage('info', message);
},
addSuccess:function(message) {
M.showMessage('success', message);
},
setCallback:function(callback) {
M._callback = callback;
},
/**
* callback realization
* call after hided message bar
*/
callback:function() {
// clear messages
M.clear();
// if exists callback run it and clean
if (M._callback) {
M._callback();
M._callback = null;
}
},
clear:function() {
M.getContainer().html('');
},
ready:function() {
if ($('#'+M._uid).length > 0) {
M.showMessage();
}
}
};
return M;
})(jQuery);
// DOM ready event
jQuery(Messages.ready);
| JavaScript |
/**
* Ready event
*
* @author Anton Shevchuk
*/
(function($, undefined) {
$(function(){
// jQUery UI widgets
// Datepickers
if (!$.browser.opera && $.isFunction($.datepicker)) {
$('input[type=date]').datepicker({"dateFormat":'yy-mm-dd'});
}
// Tabs
if ($.isFunction($.tabs)) {
$(".tabs").tabs();
}
// Ajax global events
$("#loading").bind("ajaxSend", function(){
$(this).show();
}).bind("ajaxComplete", function(){
$(this).hide();
});
// Ajax callback
var ajaxCallback = function(data) {
// redirect and reload page
var callback = null;
if (data.reload != undefined) {
callback = function() {
// reload current page
window.location.reload();
}
} else if (data.redirect != undefined) {
callback = function() {
// redirect to another page
window.location = data.redirect;
}
}
// show messages and run callback after
if (data._messages != undefined) {
Messages.setCallback(callback);
Messages.addMessages(data._messages);
} else {
callback();
}
if (data.callback != undefined && $.isFunction(window[data.callback])) {
window[data.callback](data);
}
};
// get only plain data
var processData = function(el) {
var data = el.data();
var plain = {};
$.each(data, function(key, value){
if (
typeof value == 'function' ||
typeof value == 'object') {
return false;
} else {
plain[key] = value;
}
});
return plain;
};
// Ajax links
$(document).on('click', 'a.ajax', function(){
var $this = $(this);
if ($this.hasClass('noactive')) {
// request in progress
return false;
}
$.ajax({
url:$this.attr('href'),
data: processData($this),
dataType:'json',
beforeSend:function() {
$this.addClass('noactive');
},
success:ajaxCallback,
error:function() {
Messages.addWarning('Connection is fail');
},
complete:function() {
$this.removeClass('noactive');
}
});
return false;
});
// Ajax modal
$(document).on('click', 'a.dialog', function(){
var $this = $(this);
if ($this.hasClass('noactive')) {
// request in progress
return false;
}
$.ajax({
url:$this.attr('href'),
data: processData($this),
dataType:'html',
beforeSend:function() {
$this.addClass('noactive');
},
success:function(data) {
var $div = $('<div>', {'class': 'modal hide fade'});
$div.html(data);
$div.modal({
keyboard:true,
backdrop:true
}).on('shown', function() {
var onShown = window[$this.attr('shown')];
if (typeof onShown === 'function') {
onShown.call($div);
}
}).on('hidden', function() {
var onHidden = window[$this.attr('hidden')];
if (typeof onHidden === 'function') {
onHidden.call($div);
}
$(this).remove();
});
$div.modal('show');
},
error:function() {
Messages.addWarning('Connection is fail');
},
complete:function() {
$this.removeClass('noactive');
}
});
return false;
});
// Ajax form
$(document).on('submit', 'form.ajax', function(){
var $this = $(this);
if ($this.hasClass('noactive')) {
// request in progress
return false;
}
$.ajax({
url:$this.attr('action'),
type: 'post',
data: $this.serializeArray(),
dataType:'json',
beforeSend:function() {
$this.addClass('noactive');
},
success:ajaxCallback,
error:function() {
Messages.addWarning('Connection is fail');
},
complete:function() {
$this.removeClass('noactive');
}
});
return false;
});
});
})(jQuery);
| JavaScript |
;(function($) {
var pluginName = 'grid'
, defaults = {};
function Plugin(element, options) {
this.element = $(element);
this.options = $.extend({}, defaults, this.element.data(), options || {}) ;
this.data = {};
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function() {
var that = this;
if (!this.options.url) {
$.error('Url is not set');
}
/** listen changing page */
this.element.delegate('.pagination a', 'click', function() {
var page = $(this).data('page');
if (!!page) {
that.page(page);
}
return false;
});
/** listen changing ordering */
this.element.delegate('th.orderable', 'click', function() {
var data = $(this).data();
if (!!data.column) {
data.direction = data.direction.toUpperCase() == 'ASC' ? 'DESC' : 'ASC';
that.order(data.column, data.direction);
}
});
/** draw grid */
this.refresh();
//this.element.disableSelection();
},
page: function(page) {
this.data.page = page;
this.refresh();
},
order: function(column, direction) {
this.data.orderColumn = column;
this.data.orderDirection = direction || 'ASC';
this.refresh();
},
filter: function(column, filter) {
this.data.filterColumn = column;
this.data.filterValue = filter;
this.refresh();
},
reset: function() {
this.data = {};
this.refresh();
},
overlay: function() {
var styles = {
"position": "absolute",
"top": "0",
"left": "0",
"background-color": "#fff",
"z-index": "1000",
"width": "100%",
"height": "100%",
"filter": "progid:DXImageTransform.Microsoft.Alpha(opacity=60)",
"-moz-opacity": "0.6",
"-khtml-opacity": "0.6",
"opacity": "0.6"
};
this.element
.css({ position: "relative" })
.append($('<div>').css(styles));
},
refresh: function() {
var that = this;
this.overlay();
$.post(this.options.url, this.data, function(res) {
that.element.html(res);
});
}
};
$.fn[pluginName] = function(options) {
return this.each(function() {
var element = $(this);
if (!element.data('plugin_' + pluginName)) {
element.data('plugin_' + pluginName, new Plugin(this, options));
}
});
};
})(jQuery); | JavaScript |
/*
Redactor v7.7.2
Updated: July 19, 2012
http://redactorjs.com/
Copyright (c) 2009-2012, Imperavi Ltd.
License: http://redactorjs.com/license/
Usage: $('#content').redactor();
*/
if (typeof RELANG === 'undefined')
{
var RELANG = {};
}
var RLANG = {
html: 'HTML',
video: 'Insert Video...',
image: 'Insert Image...',
table: 'Table',
link: 'Link',
link_insert: 'Insert Link ...',
unlink: 'Unlink',
formatting: 'Formatting',
paragraph: 'Paragraph',
quote: 'Quote',
code: 'Code',
header1: 'Header 1',
header2: 'Header 2',
header3: 'Header 3',
header4: 'Header 4',
bold: 'Bold',
italic: 'Italic',
fontcolor: 'Font Color',
backcolor: 'Back Color',
unorderedlist: 'Unordered List',
orderedlist: 'Ordered List',
outdent: 'Outdent',
indent: 'Indent',
cancel: 'Cancel',
insert: 'Insert',
save: 'Save',
_delete: 'Delete',
insert_table: 'Insert Table...',
insert_row_above: 'Add Row Above',
insert_row_below: 'Add Row Below',
insert_column_left: 'Add Column Left',
insert_column_right: 'Add Column Right',
delete_column: 'Delete Column',
delete_row: 'Delete Row',
delete_table: 'Delete Table',
rows: 'Rows',
columns: 'Columns',
add_head: 'Add Head',
delete_head: 'Delete Head',
title: 'Title',
image_position: 'Position',
none: 'None',
left: 'Left',
right: 'Right',
image_web_link: 'Image Web Link',
text: 'Text',
mailto: 'Email',
web: 'URL',
video_html_code: 'Video Embed Code',
file: 'Insert File...',
upload: 'Upload',
download: 'Download',
choose: 'Choose',
or_choose: 'Or choose',
drop_file_here: 'Drop file here',
align_left: 'Align Left',
align_center: 'Align Center',
align_right: 'Align Right',
align_justify: 'Justify',
horizontalrule: 'Insert Horizontal Rule',
fullscreen: 'Fullscreen',
deleted: 'Deleted',
anchor: 'Anchor'
};
(function($){
"use strict";
// Plugin
jQuery.fn.redactor = function(option)
{
return this.each(function()
{
var $obj = $(this);
var data = $obj.data('redactor');
if (!data)
{
$obj.data('redactor', (data = new Redactor(this, option)));
}
});
};
// Initialization
var Redactor = function(element, options)
{
// Element
this.$el = $(element);
// Lang
if (typeof options !== 'undefined' && typeof options.lang !== 'undefined' && options.lang !== 'en' && typeof RELANG[options.lang] !== 'undefined')
{
RLANG = RELANG[options.lang];
}
// Options
this.opts = $.extend({
lang: 'en',
direction: 'ltr', // ltr or rtl
callback: false, // function
keyupCallback: false, // function
keydownCallback: false, // function
execCommandCallback: false, // function
path: false,
css: 'style.css',
focus: false,
resize: true,
autoresize: false,
fixed: false,
autoformat: true,
cleanUp: true,
removeStyles: false,
removeClasses: false,
convertDivs: true,
convertLinks: true,
xhtml: false,
handler: false, // false or url
autosave: false, // false or url
interval: 60, // seconds
imageGetJson: false, // url (ex. /folder/images.json ) or false
imageUpload: false, // url
imageUploadCallback: false, // function
fileUpload: false, // url
fileUploadCallback: false, // function
observeImages: true,
visual: true,
fullscreen: false,
overlay: true, // modal overlay
buttonsCustom: {},
buttonsAdd: [],
buttons: ['html', '|', 'formatting', '|', 'bold', 'italic', 'deleted', '|', 'unorderedlist', 'orderedlist', 'outdent', 'indent', '|',
'image', 'video', 'file', 'table', 'link', '|',
'fontcolor', 'backcolor', '|', 'alignleft', 'aligncenter', 'alignright', 'justify', '|',
'horizontalrule', 'fullscreen'],
colors: [
'#ffffff', '#000000', '#eeece1', '#1f497d', '#4f81bd', '#c0504d', '#9bbb59', '#8064a2', '#4bacc6', '#f79646', '#ffff00',
'#f2f2f2', '#7f7f7f', '#ddd9c3', '#c6d9f0', '#dbe5f1', '#f2dcdb', '#ebf1dd', '#e5e0ec', '#dbeef3', '#fdeada', '#fff2ca',
'#d8d8d8', '#595959', '#c4bd97', '#8db3e2', '#b8cce4', '#e5b9b7', '#d7e3bc', '#ccc1d9', '#b7dde8', '#fbd5b5', '#ffe694',
'#bfbfbf', '#3f3f3f', '#938953', '#548dd4', '#95b3d7', '#d99694', '#c3d69b', '#b2a2c7', '#b7dde8', '#fac08f', '#f2c314',
'#a5a5a5', '#262626', '#494429', '#17365d', '#366092', '#953734', '#76923c', '#5f497a', '#92cddc', '#e36c09', '#c09100',
'#7f7f7f', '#0c0c0c', '#1d1b10', '#0f243e', '#244061', '#632423', '#4f6128', '#3f3151', '#31859b', '#974806', '#7f6000'],
// private
allEmptyHtml: '<p><br /></p>',
mozillaEmptyHtml: '<p> </p>',
// modal windows container
modal_file: String() +
'<form id="redactorUploadFileForm" method="post" action="" enctype="multipart/form-data">' +
'<label>Name (optional)</label>' +
'<input type="text" id="redactor_filename" class="redactor_input" />' +
'<div style="margin-top: 7px;">' +
'<input type="file" id="redactor_file" name="file" />' +
'</div>' +
'</form>',
modal_image_edit: String() +
'<label>' + RLANG.title + '</label>' +
'<input id="redactor_file_alt" class="redactor_input" />' +
'<label>' + RLANG.link + '</label>' +
'<input id="redactor_file_link" class="redactor_input" />' +
'<label>' + RLANG.image_position + '</label>' +
'<select id="redactor_form_image_align">' +
'<option value="none">' + RLANG.none + '</option>' +
'<option value="left">' + RLANG.left + '</option>' +
'<option value="right">' + RLANG.right + '</option>' +
'</select>' +
'<div id="redactor_modal_footer">' +
'<a href="javascript:void(null);" id="redactor_image_delete_btn" style="color: #000;">' + RLANG._delete + '</a>' +
'<span class="redactor_btns_box">' +
'<input type="button" name="save" id="redactorSaveBtn" value="' + RLANG.save + '" />' +
'<a href="javascript:void(null);" id="redactor_btn_modal_close">' + RLANG.cancel + '</a>' +
'</span>' +
'</div>',
modal_image: String() +
'<div id="redactor_tabs">' +
'<a href="javascript:void(null);" class="redactor_tabs_act">' + RLANG.upload + '</a>' +
'<a href="javascript:void(null);">' + RLANG.choose + '</a>' +
'<a href="javascript:void(null);">' + RLANG.link + '</a>' +
'</div>' +
'<form id="redactorInsertImageForm" method="post" action="" enctype="multipart/form-data">' +
'<div id="redactor_tab1" class="redactor_tab">' +
'<input type="file" id="redactor_file" name="file" />' +
'</div>' +
'<div id="redactor_tab2" class="redactor_tab" style="display: none;">' +
'<div id="redactor_image_box"></div>' +
'</div>' +
'</form>' +
'<div id="redactor_tab3" class="redactor_tab" style="display: none;">' +
'<label>' + RLANG.image_web_link + '</label>' +
'<input name="redactor_file_link" id="redactor_file_link" class="redactor_input" />' +
'</div>' +
'<div id="redactor_modal_footer">' +
'<span class="redactor_btns_box">' +
'<input type="button" name="upload" id="redactor_upload_btn" value="' + RLANG.insert + '" />' +
'<a href="javascript:void(null);" id="redactor_btn_modal_close">' + RLANG.cancel + '</a>' +
'</span>' +
'</div>',
modal_link: String() +
'<form id="redactorInsertLinkForm" method="post" action="">' +
'<div id="redactor_tabs">' +
'<a href="javascript:void(null);" class="redactor_tabs_act">URL</a>' +
'<a href="javascript:void(null);">Email</a>' +
'<a href="javascript:void(null);">' + RLANG.anchor + '</a>' +
'</div>' +
'<input type="hidden" id="redactor_tab_selected" value="1" />' +
'<div class="redactor_tab" id="redactor_tab1">' +
'<label>URL</label><input id="redactor_link_url" class="redactor_input" />' +
'<label>' + RLANG.text + '</label><input class="redactor_input redactor_link_text" id="redactor_link_url_text" />' +
'</div>' +
'<div class="redactor_tab" id="redactor_tab2" style="display: none;">' +
'<label>Email</label><input id="redactor_link_mailto" class="redactor_input" />' +
'<label>' + RLANG.text + '</label><input class="redactor_input redactor_link_text" id="redactor_link_mailto_text" />' +
'</div>' +
'<div class="redactor_tab" id="redactor_tab3" style="display: none;">' +
'<label>' + RLANG.anchor + '</label><input class="redactor_input" id="redactor_link_anchor" />' +
'<label>' + RLANG.text + '</label><input class="redactor_input redactor_link_text" id="redactor_link_anchor_text" />' +
'</div>' +
'</form>' +
'<div id="redactor_modal_footer">' +
'<span class="redactor_btns_box">' +
'<input type="button" id="redactor_insert_link_btn" value="' + RLANG.insert + '" />' +
'<a href="javascript:void(null);" id="redactor_btn_modal_close">' + RLANG.cancel + '</a>' +
'</span>' +
'</div>',
modal_table: String() +
'<label>' + RLANG.rows + '</label>' +
'<input size="5" value="2" id="redactor_table_rows" />' +
'<label>' + RLANG.columns + '</label>' +
'<input size="5" value="3" id="redactor_table_columns" />' +
'<div id="redactor_modal_footer">' +
'<span class="redactor_btns_box">' +
'<input type="button" name="upload" id="redactor_insert_table_btn" value="' + RLANG.insert + '" />' +
'<a href="javascript:void(null);" id="redactor_btn_modal_close">' + RLANG.cancel + '</a>' +
'</span>' +
'</div>',
modal_video: String() +
'<form id="redactorInsertVideoForm">' +
'<label>' + RLANG.video_html_code + '</label>' +
'<textarea id="redactor_insert_video_area" style="width: 99%; height: 160px;"></textarea>' +
'</form>' +
'<div id="redactor_modal_footer">' +
'<span class="redactor_btns_box">' +
'<input type="button" id="redactor_insert_video_btn" value="' + RLANG.insert + '" />' +
'<a href="javascript:void(null);" id="redactor_btn_modal_close">' + RLANG.cancel + '</a>' +
'</span>' +
'</div>',
toolbar: {
html:
{
title: RLANG.html,
func: 'toggle'
},
formatting:
{
title: RLANG.formatting,
func: 'show',
dropdown:
{
p:
{
title: RLANG.paragraph,
exec: 'formatblock'
},
blockquote:
{
title: RLANG.quote,
exec: 'formatblock',
className: 'redactor_format_blockquote'
},
pre:
{
title: RLANG.code,
exec: 'formatblock',
className: 'redactor_format_pre'
},
h1:
{
title: RLANG.header1,
exec: 'formatblock',
className: 'redactor_format_h1'
},
h2:
{
title: RLANG.header2,
exec: 'formatblock',
className: 'redactor_format_h2'
},
h3:
{
title: RLANG.header3,
exec: 'formatblock',
className: 'redactor_format_h3'
},
h4:
{
title: RLANG.header4,
exec: 'formatblock',
className: 'redactor_format_h4'
}
}
},
bold:
{
title: RLANG.bold,
exec: 'bold'
},
italic:
{
title: RLANG.italic,
exec: 'italic'
},
deleted:
{
title: RLANG.deleted,
exec: 'strikethrough'
},
unorderedlist:
{
title: '• ' + RLANG.unorderedlist,
exec: 'insertunorderedlist'
},
orderedlist:
{
title: '1. ' + RLANG.orderedlist,
exec: 'insertorderedlist'
},
outdent:
{
title: '< ' + RLANG.outdent,
exec: 'outdent'
},
indent:
{
title: '> ' + RLANG.indent,
exec: 'indent'
},
image:
{
title: RLANG.image,
func: 'showImage'
},
video:
{
title: RLANG.video,
func: 'showVideo'
},
file:
{
title: RLANG.file,
func: 'showFile'
},
table:
{
title: RLANG.table,
func: 'show',
dropdown:
{
insert_table:
{
title: RLANG.insert_table,
func: 'showTable'
},
separator_drop1:
{
name: 'separator'
},
insert_row_above:
{
title: RLANG.insert_row_above,
func: 'insertRowAbove'
},
insert_row_below:
{
title: RLANG.insert_row_below,
func: 'insertRowBelow'
},
insert_column_left:
{
title: RLANG.insert_column_left,
func: 'insertColumnLeft'
},
insert_column_right:
{
title: RLANG.insert_column_right,
func: 'insertColumnRight'
},
separator_drop2:
{
name: 'separator'
},
add_head:
{
title: RLANG.add_head,
func: 'addHead'
},
delete_head:
{
title: RLANG.delete_head,
func: 'deleteHead'
},
separator_drop3:
{
name: 'separator'
},
delete_column:
{
title: RLANG.delete_column,
func: 'deleteColumn'
},
delete_row:
{
title: RLANG.delete_row,
func: 'deleteRow'
},
delete_table:
{
title: RLANG.delete_table,
func: 'deleteTable'
}
}
},
link:
{
title: RLANG.link,
func: 'show',
dropdown:
{
link:
{
title: RLANG.link_insert,
func: 'showLink'
},
unlink:
{
title: RLANG.unlink,
exec: 'unlink'
}
}
},
fontcolor:
{
title: RLANG.fontcolor,
func: 'show'
},
backcolor:
{
title: RLANG.backcolor,
func: 'show'
},
alignleft:
{
exec: 'JustifyLeft',
title: RLANG.align_left
},
aligncenter:
{
exec: 'JustifyCenter',
title: RLANG.align_center
},
alignright:
{
exec: 'JustifyRight',
title: RLANG.align_right
},
justify:
{
exec: 'justifyfull',
title: RLANG.align_justify
},
horizontalrule:
{
exec: 'inserthorizontalrule',
title: RLANG.horizontalrule
},
fullscreen:
{
title: RLANG.fullscreen,
func: 'fullscreen'
}
}
}, options, this.$el.data());
this.dropdowns = [];
// Init
this.init();
};
// Functionality
Redactor.prototype = {
// Initialization
init: function()
{
// get path to styles
this.getPath();
if (this.opts.toolbar !== false)
{
$.extend(this.opts.toolbar, this.opts.buttonsCustom);
$.each(this.opts.buttonsAdd, $.proxy(function(i,s)
{
this.opts.buttons.push(s);
}, this));
}
// get dimensions
this.height = this.$el.css('height');
this.width = this.$el.css('width');
// construct editor
this.build();
// get html
var html = this.$el.val();
// preformatter
html = this.preformater(html);
// conver newlines to p
if (this.opts.autoformat)
{
html = this.paragraphy(html);
}
// enable
this.$editor = this.enable(html);
// focus always on page
this.observeFocus();
// cleanup
if (this.opts.cleanUp === true)
{
$(this.doc).bind('paste', $.proxy(function(e)
{
setTimeout($.proxy(function ()
{
var marker = Math.floor(Math.random() * 99999);
var marker_text = '';
if ($.browser.mozilla) marker_text = ' ';
var node = $('<span rel="pastemarkerend" id="pastemarkerend' + marker + '">' + marker_text + '</span>');
this.insertNodeAtCaret(node.get(0));
this.pasteCleanUp(marker);
}, this), 100);
}, this));
}
// keyup
$(this.doc).keyup($.proxy(function(e)
{
var key = e.keyCode || e.which;
// callback as you type
if (typeof this.opts.keyupCallback === 'function')
{
this.opts.keyupCallback(this, e);
}
if (this.opts.autoformat)
{
// if empty
if (key === 8 || key === 46)
{
return this.formatEmpty(e);
}
// new line p
if (key === 13 && !e.shiftKey && !e.ctrlKey && !e.metaKey)
{
return this.formatNewLine(e);
}
}
this.syncCode();
}, this));
// toolbar
this.buildToolbar();
// resizer
if (this.opts.autoresize === false)
{
this.buildResizer();
}
else
{
this.observeAutoResize();
}
// shortcuts
this.shortcuts();
// autosave
this.autoSave();
// observers
this.observeImages();
this.observeTables();
// fullscreen on start
if (this.opts.fullscreen)
{
this.opts.fullscreen = false;
this.fullscreen();
}
// focus
if (this.opts.focus)
{
this.focus();
}
// fixed
if (this.opts.fixed)
{
this.observeScroll();
$(document).scroll($.proxy(this.observeScroll, this));
}
// callback
if (typeof this.opts.callback === 'function')
{
this.opts.callback(this);
}
},
shortcuts: function()
{
$(this.doc).keydown($.proxy(function(e)
{
var key = e.keyCode || e.which;
// callback keydown
if (typeof this.opts.keydownCallback === 'function')
{
this.opts.keydownCallback(this, e);
}
if (e.ctrlKey)
{
if (key === 90)
{
this._shortcuts(e, 'undo'); // Ctrl + z
}
else if (key === 90 && e.shiftKey)
{
this._shortcuts(e, 'redo'); // Ctrl + Shift + z
}
else if (key === 77)
{
this._shortcuts(e, 'removeFormat'); // Ctrl + m
}
else if (key === 66)
{
this._shortcuts(e, 'bold'); // Ctrl + b
}
else if (key === 73)
{
this._shortcuts(e, 'italic'); // Ctrl + i
}
else if (key === 74)
{
this._shortcuts(e, 'insertunorderedlist'); // Ctrl + j
}
else if (key === 75)
{
this._shortcuts(e, 'insertorderedlist'); // Ctrl + k
}
else if (key === 76)
{
this._shortcuts(e, 'superscript'); // Ctrl + l
}
else if (key === 72)
{
this._shortcuts(e, 'subscript'); // Ctrl + h
}
}
if (!e.shiftKey && key === 9)
{
this._shortcuts(e, 'indent'); // Tab
}
else if (e.shiftKey && key === 9 )
{
this._shortcuts(e, 'outdent'); // Shift + tab
}
// safari shift key + enter
if ($.browser.webkit && navigator.userAgent.indexOf('Chrome') === -1)
{
return this.safariShiftKeyEnter(e, key);
}
}, this));
},
_shortcuts: function(e, cmd)
{
if (e.preventDefault)
{
e.preventDefault();
}
this.execCommand(cmd, false);
},
getPath: function()
{
if (this.opts.path !== false)
{
return this.opts.path;
}
$('script').each($.proxy(function(i,s)
{
if (s.src)
{
// Match redactor.js or redactor.min.js, followed by an optional querystring (often used for cache purposes)
var regexp = new RegExp(/\/redactor(\.min)?\.js(\?.*)?/);
if (s.src.match(regexp))
{
this.opts.path = s.src.replace(regexp, '');
}
}
}, this));
},
build: function()
{
// container
this.$box = $('<div class="redactor_box"></div>');
// frame
this.$frame = $('<iframe frameborder="0" scrolling="auto" style="height: ' + this.height + ';" class="redactor_frame"></iframe>');
// hide textarea
this.$el.css('width', '100%').hide();
// append box and frame
this.$box.insertAfter(this.$el).append(this.$frame).append(this.$el);
},
write: function(html)
{
this.doc.open();
this.doc.write(html);
this.doc.close();
},
enable: function(html)
{
this.doc = this.getDoc(this.$frame.get(0));
if (this.doc !== null)
{
this.write(this.setDoc(html));
return $(this.doc).find('#page');
}
else
{
return false;
}
},
setDoc: function(html)
{
var frameHtml = '<!DOCTYPE html>\n' +
'<html><head><link media="all" type="text/css" href="' + this.opts.path + '/css/' + this.opts.css + '" rel="stylesheet"></head>' +
'<body><div id="page" contenteditable="true" dir="' + this.opts.direction + '">' +
html +
'</div></body></html>';
return frameHtml;
},
getDoc: function(frame)
{
if (frame.contentDocument)
{
return frame.contentDocument;
}
else if (frame.contentWindow && frame.contentWindow.document)
{
return frame.contentWindow.document;
}
else if (frame.document)
{
return frame.document;
}
else
{
return null;
}
},
focus: function()
{
this.$editor.focus();
},
syncCode: function()
{
var html = this.formatting(this.$editor.html());
this.$el.val(html);
},
// API functions
setCode: function(html)
{
html = this.preformater(html);
this.$editor.html(html).focus();
this.syncCode();
},
getCode: function()
{
var html = this.$editor ? this.$editor.html() : this.$el.val();
html = this.reformater(html);
return html;
},
insertHtml: function(html)
{
this.execCommand('inserthtml', html);
this.observeImages();
},
destroy: function()
{
var html = this.getCode();
this.$box.after(this.$el);
this.$box.remove();
this.$el.val(html).show();
for (var i = 0; i < this.dropdowns.length; i++)
{
this.dropdowns[i].remove();
delete(this.dropdowns[i]);
}
},
handler: function()
{
$.ajax({
url: this.opts.handler,
type: 'POST',
data: 'redactor=' + escape(encodeURIComponent(this.getCode())),
success: $.proxy(function(data)
{
this.setCode(data);
this.syncCode();
}, this)
});
},
// end API functions
// OBSERVERS
observeFocus: function()
{
if ($.browser.msie)
{
return false;
}
if ($(this.doc).find('body').height() < $(this.$frame.get(0).contentWindow).height())
{
$(this.doc).click($.proxy(function(e) { this.$editor.focus(); }, this));
}
},
observeImages: function()
{
if (this.opts.observeImages === false)
{
return false;
}
$(this.doc).find('img').each($.proxy(function(i,s)
{
if ($.browser.msie) $(s).attr('unselectable', 'on');
this.resizeImage(s);
}, this));
},
observeTables: function()
{
$(this.doc).find('body').find('table').click($.proxy(this.tableObserver, this));
},
observeScroll: function()
{
var scrolltop = $(document).scrollTop();
var boxtop = this.$box.offset().top;
if (scrolltop > boxtop)
{
this.fixed = true;
this.$toolbar.css({ position: 'fixed', width: '100%' });
}
else
{
this.fixed = false;
this.$toolbar.css({ position: 'relative', width: 'auto' });
}
},
observeAutoResize: function()
{
this.$editor.css({ 'min-height': this.$el.height() + 'px' });
$(this.doc).find('body').css({ 'overflow': 'hidden' });
this.setAutoSize(false);
$(this.doc).keyup($.proxy(this.setAutoSize, this));
},
setAutoSize: function(e)
{
var key = false;
if (e !== false)
{
key = e.keyCode || e.which;
}
var height = this.$editor.outerHeight(true);
if (e === true && (key === 8 || key === 46))
{
this.$frame.height(height);
}
else
{
this.$frame.height(height+30);
}
},
// EXECCOMMAND
execCommand: function(cmd, param)
{
if (this.opts.visual && this.doc)
{
try
{
if ($.browser.msie)
{
this.focus();
}
if (cmd === 'inserthtml' && $.browser.msie)
{
this.doc.selection.createRange().pasteHTML(param);
}
else if (cmd === 'formatblock' && $.browser.msie)
{
this.doc.execCommand(cmd, false, '<' +param + '>');
}
else
{
this.doc.execCommand(cmd, false, param);
}
this.syncCode();
this.focus();
if (typeof this.opts.execCommandCallback === 'function')
{
this.opts.execCommandCallback(this, cmd);
}
}
catch (e) { }
}
},
// FORMAT NEW LINE
formatNewLine: function(e)
{
var parent = this.getParentNode();
if (parent.nodeName === 'DIV' && parent.id === 'page')
{
if (e.preventDefault)
{
e.preventDefault();
}
var element = $(this.getCurrentNode());
if (element.get(0).tagName === 'DIV' && (element.html() === '' || element.html() === '<br>'))
{
var newElement = $('<p>').append(element.clone().get(0).childNodes);
element.replaceWith(newElement);
newElement.html('<br />');
this.setFocusNode(newElement.get(0));
this.syncCode();
return false;
}
else
{
this.syncCode();
}
// convert links
if (this.opts.convertLinks)
{
this.$editor.linkify();
}
}
else
{
this.syncCode();
return true;
}
},
// SAFARI SHIFT KEY + ENTER
safariShiftKeyEnter: function(e, key)
{
if (e.shiftKey && key === 13)
{
e.preventDefault();
var node1 = $('<span><br /></span>');
this.insertNodeAtCaret(node1.get(0));
this.setFocusNode(node1.get(0));
this.syncCode();
return false;
}
else
{
return true;
}
},
// FORMAT EMPTY
formatEmpty: function(e)
{
var html = $.trim(this.$editor.html());
if ($.browser.mozilla)
{
html = html.replace(/<br>/gi, '');
}
if (html === '')
{
if (e.preventDefault)
{
e.preventDefault();
}
var nodehtml = this.opts.allEmptyHtml;
if ($.browser.mozilla)
{
nodehtml = this.opts.mozillaEmptyHtml;
}
var node = $(nodehtml).get(0);
this.$editor.html(node);
this.setFocusNode(node);
this.syncCode();
return false;
}
else
{
this.syncCode();
}
},
// PARAGRAPHY
paragraphy: function (str)
{
str = $.trim(str);
if (str === '')
{
if (!$.browser.mozilla)
{
return this.opts.allEmptyHtml;
}
else
{
return this.opts.mozillaEmptyHtml;
}
}
// convert div to p
if (this.opts.convertDivs) str = str.replace(/<div(.*?)>([\w\W]*?)<\/div>/gi, '<p>$2</p>');
// inner functions
var X = function(x, a, b) { return x.replace(new RegExp(a, 'g'), b); };
var R = function(a, b) { return X(str, a, b); };
// block elements
var blocks = '(table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|address|math|style|script|object|input|param|p|h[1-6])';
str += '\n';
R('<br />\\s*<br />', '\n\n');
R('(<' + blocks + '[^>]*>)', '\n$1');
R('(</' + blocks + '>)', '$1\n\n');
R('\r\n|\r', '\n'); // newlines
R('\n\n+', '\n\n'); // remove duplicates
R('\n?((.|\n)+?)$', '<p>$1</p>\n'); // including one at the end
R('<p>\\s*?</p>', ''); // remove empty p
R('<p>(<div[^>]*>\\s*)', '$1<p>');
R('<p>([^<]+)\\s*?(</(div|address|form)[^>]*>)', '<p>$1</p>$2');
R('<p>\\s*(</?' + blocks + '[^>]*>)\\s*</p>', '$1');
R('<p>(<li.+?)</p>', '$1');
R('<p>\\s*(</?' + blocks + '[^>]*>)', '$1');
R('(</?' + blocks + '[^>]*>)\\s*</p>', '$1');
R('(</?' + blocks + '[^>]*>)\\s*<br />', '$1');
R('<br />(\\s*</?(p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)', '$1');
// pre
if (str.indexOf('<pre') != -1)
{
R('(<pre(.|\n)*?>)((.|\n)*?)</pre>', function(m0, m1, m2, m3)
{
return X(m1, '\\\\([\'\"\\\\])', '$1') + X(X(X(m3, '<p>', '\n'), '</p>|<br />', ''), '\\\\([\'\"\\\\])', '$1') + '</pre>';
});
}
return R('\n</p>$', '</p>');
},
// PREPARE FORMATER
preformater: function(html)
{
if (html !== null)
{
html = html.replace(/<br>/gi,'<br />');
//html = html.replace(/<blockquote\b[^>]*>([\w\W]*?)<p>([\w\W]*?)<\/p>([\w\W]*?)<\/blockquote[^>]*>/gi,'<blockquote>$1$2<br />$3</blockquote>');
html = html.replace(/<strong\b[^>]*>([\w\W]*?)<\/strong[^>]*>/gi,'<b>$1</b>');
html = html.replace(/<em\b[^>]*>([\w\W]*?)<\/em[^>]*>/gi,'<i>$1</i>');
html = html.replace(/<del\b[^>]*>([\w\W]*?)<\/del[^>]*>/gi,'<strike>$1</strike>');
}
else
{
html = '';
}
return html;
},
// REVERT FORMATER
reformater: function(html)
{
html = html.replace(/<br>/gi,'<br />');
html = html.replace(/<b\b[^>]*>([\w\W]*?)<\/b[^>]*>/gi,'<strong>$1</strong>');
html = html.replace(/<i\b[^>]*>([\w\W]*?)<\/i[^>]*>/gi,'<em>$1</em>');
html = html.replace(/<strike\b[^>]*>([\w\W]*?)<\/strike[^>]*>/gi,'<del>$1</del>');
html = html.replace(/<span(.*?)style="font-weight: bold;">([\w\W]*?)<\/span>/gi, "<strong>$2</strong>");
html = html.replace(/<span(.*?)style="font-style: italic;">([\w\W]*?)<\/span>/gi, "<em>$2</em>");
html = html.replace(/<span(.*?)style="font-weight: bold; font-style: italic;">([\w\W]*?)<\/span>/gi, "<em><strong>$2</strong></em>");
html = html.replace(/<span(.*?)style="font-style: italic; font-weight: bold;">([\w\W]*?)<\/span>/gi, "<strong><em>$2</em></strong>");
return html;
},
// REMOVE TAGS
stripTags: function(html)
{
var allowed = ["code", "span", "div", "label", "a", "br", "p", "b", "i", "del", "strike", "img", "video", "audio", "iframe", "object", "embed", "param", "blockquote", "mark", "cite", "small", "ul", "ol", "li", "hr", "dl", "dt", "dd", "sup", "sub", "big", "pre", "code", "figure", "figcaption", "strong", "em", "table", "tr", "td", "th", "tbody", "thead", "tfoot", "h1", "h2", "h3", "h4", "h5", "h6"];
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
return html.replace(tags, function ($0, $1)
{
return $.inArray($1.toLowerCase(), allowed) > '-1' ? $0 : '';
});
},
cleanStyles: function (properties, str, m)
{
var attr = m.split('=');
var prop = attr[1].split(';');
var t = '';
$.each(prop, function(z,s)
{
if (typeof s == 'undefined') return true;
if (s == '"' || s == "'") return true;
s = s.replace(/(^"|^')/,'').replace(/("$|'$)/,'').replace(/"(.*?)"/gi, '');
s = $.trim(s);
var p = s.split(':');
if (typeof p[1] !== 'undefined' && (p[1].search('pt') === -1 && p[1].search('cm') === -1))
{
if ($.inArray($.trim(p[0]), properties) != '-1') t += s + '; ';
}
});
return str.replace(m, 'style="' + t + '"');
},
// PASTE CLEANUP
pasteCleanUp: function(marker)
{
var html = this.$editor.html();
// remove comments and php tags
html = html.replace(/<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi, '')
// remove formatting
html = this.formattingRemove(html);
// remove tags
html = this.stripTags(html);
// remove classes
if (this.opts.removeClasses)
{
html = html.replace(/ class="([\w\W]*?)"/gi, '');
}
else
{
html = html.replace(/\s*class="TOC(.*?)"/gi, "" );
html = html.replace(/\s*class="Heading(.*?)"/gi, "" );
html = html.replace(/\s*class="Body(.*?)"/gi, "" );
html = html.replace(/\sclass="Nonformat"/gi, '');
html = html.replace(/\sclass="Mso(.*?)"/gi, '');
html = html.replace(/\sclass="Apple(.*?)"/gi, '');
html = html.replace(/"Times New Roman"/gi, '');
}
var attributes = ['width', 'height', 'src', 'style', 'href', 'frameborder', 'class', 'id', 'rel', 'unselectable'];
var properties = ['color', 'background-color', 'font-style', 'margin', 'margin-top', 'margin-bottom', 'margin-left', 'margin-right', 'text-align', 'width', 'height', 'cursor', 'float'];
// remove attributes
var matches = html.match(/([\w\-.:]+)\s*=\s*("[^"]*"|'[^']*'|[\w\-.:]+)/gi);
$.each(matches, $.proxy(function(i,m)
{
var attr = m.split('=');
if ($.inArray(attr[0], attributes) == '-1')
{
html = html.replace(m, '');
}
// remove styles
if (this.opts.removeStyles === false && attr[0] == 'style')
{
html = this.cleanStyles(properties, html, m);
}
}, this));
// remove styles
if (this.opts.removeStyles === false)
{
html = html.replace(/background-color:(\s+)transparent;\s/gi, '');
html = html.replace(/font-style:(\s+)normal;\s/gi, '');
}
else
{
html = html.replace(/ style="([\w\W]*?)"/gi, '');
}
// remove empty styles
html = html.replace(/((\s{2,})?|\s)style=(""|'')/gi, '');
// remove nbsp
html = html.replace(/( ){1,}/gi, ' ');
// remove empty span
html = html.replace(/<span(\s)?>(\s)?<\/span>/gi, ' ');
// remove double white spaces
html = html.replace(/\s{2,}/g, ' ');
// remove span without styles
html = html.replace(/<span>([\w\W]*?)<\/span>/gi, '$1');
html = html.replace(/<span>([\w\W]*?)<\/span>/gi, '$1');
html = html.replace(/<span(\s)?>([\w\W]*?)<\/span>/gi, '$2');
// empty tags
html = this.formattingEmptyTags(html);
// add formatting before
html = this.formattingAddBefore(html);
// add formatting after
html = this.formattingAddAfter(html);
// indenting
html = this.formattingIndenting(html);
// dirty paragraphs
html = html.replace(/<p><div>/gi, "");
html = html.replace(/<p>\s+\n+<(.*?)/gi, "<$1");
html = html.replace(/<\/(.*?)>\s+\n+<\/p>/gi, "</$1>");
html = html.replace(/<p style="(.*?)">(\s)?<\/p>/gi, '');
html = html.replace(/<p style="(.*?)"><\/p>/gi, '');
// remove google docs marker
html = html.replace(/<b\sid="internal-source-marker(.*?)">([\w\W]*?)<\/b>/gi, "$2");
// trim spaces
html = html.replace(/; ">/gi, ';">');
// SET HTML
this.$editor.html(html);
// RETURN FOCUS
var node = $(this.doc.body).find('#pastemarkerend' + marker).get(0);
this.setFocusNode(node);
this.syncCode();
setTimeout($.proxy(function()
{
// remove pastemarker
$(this.doc.body).find('span[rel=pastemarkerend]').remove();
if (this.opts.autoresize === true) this.setAutoSize(false);
this.observeImages();
this.observeTables();
}, this), 100);
},
// TEXTAREA CODE FORMATTING
formattingRemove: function(html)
{
html = html.replace(/\s{2,}/g, ' ');
html = html.replace(/\n/g, ' ');
html = html.replace(/[\t]*/g, '');
html = html.replace(/\n\s*\n/g, "\n");
html = html.replace(/^[\s\n]*/g, '');
html = html.replace(/[\s\n]*$/g, '');
html = html.replace(/>\s+</g, '><');
return html;
},
formattingIndenting: function(html)
{
html = html.replace(/<li/g, "\t<li");
html = html.replace(/<tr/g, "\t<tr");
html = html.replace(/<td/g, "\t\t<td");
html = html.replace(/<\/tr>/g, "\t</tr>");
return html;
},
formattingEmptyTags: function(html)
{
var etags = ["<pre></pre>","<blockquote>\\s*</blockquote>","<em>\\s*</em>","<ul></ul>","<ol></ol>","<li></li>","<table></table>","<tr></tr>","<span>\\s*<span>", "<span> <span>", "<b>\\s*</b>", "<b> </b>", "<p>\\s*</p>", "<p> </p>", "<p>\\s*<br>\\s*</p>", "<div>\\s*</div>", "<div>\\s*<br>\\s*</div>"];
for (var i = 0; i < etags.length; ++i)
{
var bbb = etags[i];
html = html.replace(new RegExp(bbb,'gi'), "");
}
return html;
},
formattingAddBefore: function(html)
{
var lb = '\r\n';
var btags = ["<p", "<form","</ul>", '</ol>', "<fieldset","<legend","<object","<embed","<select","<option","<input","<textarea","<pre","<blockquote","<ul","<ol","<li","<dl","<dt","<dd","<table", "<thead","<tbody","<caption","</caption>","<th","<tr","<td","<figure"];
for (var i = 0; i < btags.length; ++i)
{
var eee = btags[i];
html = html.replace(new RegExp(eee,'gi'),lb+eee);
}
return html;
},
formattingAddAfter: function(html)
{
var lb = '\r\n';
var atags = ['</p>', '</div>', '</h1>', '</h2>', '</h3>', '</h4>', '</h5>', '</h6>', '<br>', '<br />', '</dl>', '</dt>', '</dd>', '</form>', '</blockquote>', '</pre>', '</legend>', '</fieldset>', '</object>', '</embed>', '</textarea>', '</select>', '</option>', '</table>', '</thead>', '</tbody>', '</tr>', '</td>', '</th>', '</figure>'];
for (var i = 0; i < atags.length; ++i)
{
var aaa = atags[i];
html = html.replace(new RegExp(aaa,'gi'),aaa+lb);
}
return html;
},
formatting: function(html)
{
// lowercase
if ($.browser.msie)
{
var match = html.match(/<(.*?)>/gi);
$.each(match, function(i,s)
{
html = html.replace(s, s.toLowerCase());
})
html = html.replace(/style="(.*?)"/gi, function(w) { return w.toLowerCase(); });
html = html.replace(/ jQuery(.*?)=\"(.*?)\"/gi, '');
}
html = html.replace(/<span([\w\W]*?)style="color:(.*?);"><span([\w\W]*?)style="background-color:(.*?);">([\w\W]*?)<\/span><\/span>/gi, '<span style="color: $2; background-color: $4;">$5</span>');
html = html.replace(/<span([\w\W]*?)style="background-color:(.*?);"><span([\w\W]*?)style="color:(.*?);">([\w\W]*?)<\/span><\/span>/gi, '<span style="color: $2; background-color: $4;">$5</span>');
html = html.replace(/<span([\w\W]*?)color="(.*?)">([\w\W]*?)<\/span\>/gi, '<span$1style="color: $2;">$3</span>');
html = html.replace(/<font([\w\W]*?)color="(.*?)">([\w\W]*?)<\/font\>/gi, '<span$1style="color: $2;">$3</span>');
html = html.replace(/<span style="(.*?)"\s+style="(.*?)"[\s]*>([\w\W]*?)<\/span\>/gi, '<span style="$1;$2">$3</span>');
html = html.replace(/<font([\w\W]*?)>([\w\W]*?)<\/font\>/gi, "<span$1>$2</span>");
html = html.replace(/<span>([\w\W]*?)<\/span>/gi, '$1');
if (this.opts.xhtml)
{
html = html.replace(/<br>/gi,'<br />');
html = html.replace(/<br ?\/?>$/gi,'');
html = html.replace(/^<br ?\/?>/gi,'');
html = html.replace(/(<img [^>]+[^\/])>/gi,'$1 />');
}
// mini clean
html = html.replace(/<p><p>/g, '<p>');
html = html.replace(/<\/p><\/p>/g, '</p>');
html = html.replace(/<hr(.*?)>/g, '<hr />');
html = html.replace(/<p> /g, '<p>');
html = html.replace(/<p><ul>/g, '<ul>');
html = html.replace(/<p><ol>/g, '<ol>');
html = html.replace(/<\/ul><\/p>/g, '</ul>');
html = html.replace(/<\/ol><\/p>/g, '</ol>');
html = html.replace( /<p(.*?)> <\/p>/gi, '');
// remove formatting
html = this.formattingRemove(html);
// empty tags
html = this.formattingEmptyTags(html);
// add formatting before
html = this.formattingAddBefore(html);
// add formatting after
html = this.formattingAddAfter(html);
// indenting
html = this.formattingIndenting(html);
return html;
},
// TOGGLE
toggle: function()
{
var html;
if (this.opts.visual)
{
this.$frame.hide();
html = this.$editor.html();
html = $.trim(this.formatting(html));
this.$el.val(html).show().focus();
this.setBtnActive('html');
this.opts.visual = false;
}
else
{
this.$el.hide();
this.$editor.html(this.$el.val());
this.$frame.show();
if (this.$editor.html() === '')
{
if (!$.browser.mozilla)
{
html = this.opts.allEmptyHtml;
}
else
{
html = this.opts.mozillaEmptyHtml;
}
this.setCode(html);
}
this.focus();
this.setBtnInactive('html');
this.opts.visual = true;
this.observeImages();
this.observeTables();
if (this.opts.autoresize === true) this.setAutoSize(false);
}
},
// AUTOSAVE
autoSave: function()
{
if (this.opts.autosave === false)
{
return false;
}
setInterval($.proxy(function()
{
$.post(this.opts.autosave, { data: this.getCode() });
}, this), this.opts.interval*1000);
},
// TOOLBAR
buildToolbar: function()
{
if (this.opts.toolbar === false)
{
return false;
}
this.$toolbar = $('<ul>').addClass('redactor_toolbar');
this.$box.prepend(this.$toolbar);
$.each(this.opts.buttons, $.proxy(function(i,key)
{
if (key !== '|' && typeof this.opts.toolbar[key] !== 'undefined')
{
var s = this.opts.toolbar[key];
if (this.opts.fileUpload === false && key === 'file')
{
return true;
}
var li = $('<li>');
if (key === 'fullscreen')
{
$(li).addClass('redactor_toolbar_right');
}
var a = this.buildButton(key, s);
// dropdown
if (key === 'backcolor' || key === 'fontcolor' || typeof(s.dropdown) !== 'undefined')
{
var dropdown = $('<div class="redactor_dropdown" style="display: none;">');
if (key === 'backcolor' || key === 'fontcolor')
{
dropdown = this.buildColorPicker(dropdown, key);
}
else
{
dropdown = this.buildDropdown(dropdown, s.dropdown);
}
this.dropdowns.push(dropdown.appendTo($(document.body)));
// observing dropdown
this.hdlHideDropDown = $.proxy(function(e) { this.hideDropDown(e, dropdown, key); }, this);
this.hdlShowDropDown = $.proxy(function(e) { this.showDropDown(e, dropdown, key); }, this);
a.click(this.hdlShowDropDown);
}
this.$toolbar.append($(li).append(a));
}
if (key === '|')
{
this.$toolbar.append($('<li class="redactor_separator"></li>'));
}
}, this));
$(document).click(this.hdlHideDropDown);
$(this.doc).click(this.hdlHideDropDown);
},
buildButton: function(key, s)
{
var button = $('<a href="javascript:void(null);" title="' + s.title + '" class="redactor_btn_' + key + '"><span> </span></a>');
if (typeof s.func === 'undefined')
{
button.click($.proxy(function() { this.execCommand(s.exec, key); }, this));
}
else if (s.func !== 'show')
{
button.click($.proxy(function(e) { this[s.func](e); }, this));
}
if (typeof s.callback !== 'undefined')
{
button.click($.proxy(function(e) { s.callback(this, e, key); }, this));
}
return button;
},
buildDropdown: function(dropdown, obj)
{
$.each(obj, $.proxy(
function (x, d)
{
if (typeof(d.className) === 'undefined')
{
d.className = '';
}
var drop_a;
if (typeof d.name !== 'undefined' && d.name === 'separator')
{
drop_a = $('<a class="redactor_separator_drop">');
}
else
{
drop_a = $('<a href="javascript:void(null);" class="' + d.className + '">' + d.title + '</a>');
if (typeof(d.func) === 'undefined')
{
$(drop_a).click($.proxy(function() { this.execCommand(d.exec, x); }, this));
}
else
{
$(drop_a).click($.proxy(function(e) { this[d.func](e); }, this));
}
}
$(dropdown).append(drop_a);
}, this)
);
return dropdown;
},
buildColorPicker: function(dropdown, key)
{
var mode;
if (key === 'backcolor')
{
if ($.browser.msie)
{
mode = 'BackColor';
}
else
{
mode = 'hilitecolor';
}
}
else
{
mode = 'forecolor';
}
$(dropdown).width(210);
var len = this.opts.colors.length;
for (var i = 0; i < len; ++i)
{
var color = this.opts.colors[i];
var swatch = $('<a rel="' + color + '" href="javascript:void(null);" class="redactor_color_link"></a>').css({ 'backgroundColor': color });
$(dropdown).append(swatch);
var _self = this;
$(swatch).click(function()
{
_self.execCommand(mode, $(this).attr('rel'));
});
}
var elnone = $('<a href="javascript:void(null);" class="redactor_color_none"></a>').html(RLANG.none);
if (key === 'backcolor')
{
elnone.click($.proxy(this.setBackgroundNone, this));
}
else
{
elnone.click($.proxy(this.setColorNone, this));
}
$(dropdown).append(elnone);
return dropdown;
},
setBackgroundNone: function()
{
$(this.getParentNode()).css('background-color', 'transparent');
this.syncCode();
},
setColorNone: function()
{
$(this.getParentNode()).attr('color', '').css('color', '');
this.syncCode();
},
// DROPDOWNS
showDropDown: function(e, dropdown, key)
{
if (this.getBtn(key).hasClass('dropact'))
{
this.hideAllDropDown();
}
else
{
this.hideAllDropDown();
this.setBtnActive(key);
this.getBtn(key).addClass('dropact');
var left = this.getBtn(key).offset().left;
if (this.opts.fixed && this.fixed)
{
$(dropdown).css({ position: 'fixed', left: left + 'px', top: '30px' }).show();
}
else
{
var top = this.$toolbar.offset().top + 30;
$(dropdown).css({ position: 'absolute', left: left + 'px', top: top + 'px' }).show();
}
}
},
hideAllDropDown: function()
{
this.$toolbar.find('a.dropact').removeClass('act').removeClass('dropact');
$('.redactor_dropdown').hide();
},
hideDropDown: function(e, dropdown, key)
{
if (!$(e.target).parent().hasClass('dropact'))
{
$(dropdown).removeClass('act');
this.showedDropDown = false;
this.hideAllDropDown();
}
},
// SELECTION AND NODE MANIPULATION
getSelection: function ()
{
if (this.$frame.get(0).contentWindow.getSelection)
{
return this.$frame.get(0).contentWindow.getSelection();
}
else if (this.$frame.get(0).contentWindow.document.selection)
{
return this.$frame.get(0).contentWindow.document.selection.createRange();
}
},
getParentNode: function()
{
if (window.getSelection)
{
return this.getSelection().getRangeAt(0).startContainer.parentNode;
}
else if (document.selection)
{
return this.getSelection().parentElement();
}
},
getCurrentNode: function()
{
if (window.getSelection)
{
return this.getSelection().getRangeAt(0).startContainer;
}
else if (document.selection)
{
return this.getSelection();
}
},
setFocusNode: function(node, toStart)
{
var range = this.doc.createRange();
var selection = this.getSelection();
toStart = toStart ? 0 : 1;
if (selection !== null)
{
range.selectNodeContents(node);
selection.addRange(range);
selection.collapse(node, toStart);
}
this.focus();
},
insertNodeAtCaret: function (node)
{
if (typeof window.getSelection !== "undefined")
{
var sel = this.getSelection();
if (sel.rangeCount)
{
var range = sel.getRangeAt(0);
range.collapse(false);
range.insertNode(node);
range = range.cloneRange();
range.selectNodeContents(node);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
}
}
else if (typeof document.selection !== "undefined" && document.selection.type !== "Control")
{
var html = (node.nodeType === 1) ? node.outerHTML : node.data;
var id = "marker_" + ("" + Math.random()).slice(2);
html += '<span id="' + id + '"></span>';
var textRange = this.getSelection();
textRange.collapse(false);
textRange.pasteHTML(html);
var markerSpan = document.getElementById(id);
textRange.moveToElementText(markerSpan);
textRange.select();
markerSpan.parentNode.removeChild(markerSpan);
}
},
// BUTTONS MANIPULATIONS
getBtn: function(key)
{
return $(this.$toolbar.find('a.redactor_btn_' + key));
},
setBtnActive: function(key)
{
this.getBtn(key).addClass('act');
},
setBtnInactive: function(key)
{
this.getBtn(key).removeClass('act');
},
changeBtnIcon: function(key, classname)
{
this.getBtn(key).addClass('redactor_btn_' + classname);
},
removeBtnIcon: function(key, classname)
{
this.getBtn(key).removeClass('redactor_btn_' + classname);
},
removeBtn: function(key)
{
this.getBtn(key).remove();
},
addBtn: function(key, obj)
{
this.$toolbar.append($('<li>').append(this.buildButton(key, obj)));
},
// FULLSCREEN
fullscreen: function()
{
var html;
if (this.opts.fullscreen === false)
{
this.changeBtnIcon('fullscreen', 'normalscreen');
this.setBtnActive('fullscreen');
this.opts.fullscreen = true;
this.height = this.$frame.css('height');
this.width = (this.$box.width() - 2) + 'px';
html = this.getCode();
this.tmpspan = $('<span></span>');
this.$box.addClass('redactor_box_fullscreen').after(this.tmpspan);
$(document.body).prepend(this.$box).css('overflow', 'hidden');
this.$editor = this.enable(html);
$(this.doc).click($.proxy(this.hideAllDropDown, this));
// focus always on page
this.observeFocus();
this.observeImages();
this.observeTables();
this.$box.find('.redactor_resizer').hide();
this.fullScreenResize();
$(window).resize($.proxy(this.fullScreenResize, this));
$(document).scrollTop(0,0);
this.focus();
}
else
{
this.removeBtnIcon('fullscreen', 'normalscreen');
this.setBtnInactive('fullscreen');
this.opts.fullscreen = false;
$(window).unbind('resize', $.proxy(this.fullScreenResize, this));
$(document.body).css('overflow', '');
html = this.getCode();
this.$box.removeClass('redactor_box_fullscreen').css('width', 'auto');
this.tmpspan.after(this.$box).remove();
this.$editor = this.enable(html);
this.observeImages();
this.observeTables();
if (this.opts.autoresize)
{
this.observeAutoResize();
}
this.$box.find('.redactor_resizer').show();
$(this.doc).click($.proxy(this.hideAllDropDown, this));
// focus always on page
this.observeFocus();
this.syncCode();
this.$frame.css('height', this.height);
this.$el.css('height', this.height);
this.focus();
}
},
fullScreenResize: function()
{
if (this.opts.fullscreen === false)
{
return false;
}
var height = $(window).height() - 42;
this.$box.width($(window).width() - 2);
this.$frame.height(height);
this.$el.height(height);
},
// RESIZE
buildResizer: function()
{
if (this.opts.resize === false)
{
return false;
}
this.$resizer = $('<div class="redactor_resizer">—</div>');
this.$box.append(this.$resizer);
this.$resizer.mousedown($.proxy(this.initResize, this));
},
initResize: function(e)
{
if (e.preventDefault)
{
e.preventDefault();
}
this.splitter = e.target;
if (this.opts.visual)
{
this.element_resize = this.$frame;
this.element_resize.get(0).style.visibility = 'hidden';
this.element_resize_parent = this.$el;
}
else
{
this.element_resize = this.$el;
this.element_resize_parent = this.$frame;
}
this.stopResizeHdl = $.proxy(this.stopResize, this);
this.startResizeHdl = $.proxy(this.startResize, this);
this.resizeHdl = $.proxy(this.resize, this);
$(document).mousedown(this.startResizeHdl);
$(document).mouseup(this.stopResizeHdl);
$(this.splitter).mouseup(this.stopResizeHdl);
this.null_point = false;
this.h_new = false;
this.h = this.element_resize.height();
},
startResize: function()
{
$(document).mousemove(this.resizeHdl);
},
resize: function(e)
{
if (e.preventDefault)
{
e.preventDefault();
}
var y = e.pageY;
if (this.null_point === false)
{
this.null_point = y;
}
if (this.h_new === false)
{
this.h_new = this.element_resize.height();
}
var s_new = (this.h_new + y - this.null_point) - 10;
if (s_new <= 30)
{
return true;
}
if (s_new >= 0)
{
this.element_resize.get(0).style.height = s_new + 'px';
this.element_resize_parent.get(0).style.height = s_new + 'px';
}
},
stopResize: function(e)
{
$(document).unbind('mousemove', this.resizeHdl);
$(document).unbind('mousedown', this.startResizeHdl);
$(document).unbind('mouseup', this.stopResizeHdl);
$(this.splitter).unbind('mouseup', this.stopResizeHdl);
this.element_resize.get(0).style.visibility = 'visible';
},
// RESIZE IMAGES
resizeImage: function(resize)
{
var clicked = false;
var clicker = false;
var start_x;
var start_y;
var ratio = $(resize).width()/$(resize).height();
var y = 1;
var x = 1;
var min_w = 1;
var min_h = 1;
$(resize).hover(function() { $(resize).css('cursor', 'nw-resize'); }, function() { $(resize).css('cursor','default'); clicked=false; });
$(resize).mousedown(function(e)
{
if (e.preventDefault)
{
e.preventDefault();
}
clicked = true;
clicker = true;
start_x = Math.round(e.pageX - $(resize).eq(0).offset().left);
start_y = Math.round(e.pageY - $(resize).eq(0).offset().top);
});
$(resize).mouseup($.proxy(function(e)
{
clicked = false;
this.syncCode();
if (this.opts.autoresize === true) this.setAutoSize(false);
}, this));
$(resize).click($.proxy(function(e)
{
if (clicker)
{
this.imageEdit(e);
}
}, this));
$(resize).mousemove(function(e)
{
if (clicked)
{
clicker = false;
var mouse_x = Math.round(e.pageX - $(this).eq(0).offset().left) - start_x;
var mouse_y = Math.round(e.pageY - $(this).eq(0).offset().top) - start_y;
var div_h = $(resize).height();
var new_h = parseInt(div_h, 10) + mouse_y;
var new_w = new_h*ratio;
if (x === 1 || (typeof(x) === "number" && new_w < x && new_w > min_w))
{
$(resize).width(new_w);
}
if (y === 1 || (typeof(y) === "number" && new_h < y && new_h > min_h))
{
$(resize).height(new_h);
}
start_x = Math.round(e.pageX - $(this).eq(0).offset().left);
start_y = Math.round(e.pageY - $(this).eq(0).offset().top);
}
});
},
// TABLE
showTable: function()
{
this.modalInit(RLANG.table, 'table', 300, $.proxy(function()
{
$('#redactor_insert_table_btn').click($.proxy(this.insertTable, this));
}, this),
function()
{
$('#redactor_table_rows').focus();
}
);
},
insertTable: function()
{
var rows = $('#redactor_table_rows').val();
var columns = $('#redactor_table_columns').val();
var table_box = $('<div></div>');
var tableid = Math.floor(Math.random() * 99999);
var table = $('<table id="table' + tableid + '"><tbody></tbody></table>');
for (var i = 0; i < rows; i++)
{
var row = $('<tr></tr>');
for (var z = 0; z < columns; z++)
{
var column = $('<td> </td>');
$(row).append(column);
}
$(table).append(row);
}
$(table_box).append(table);
var html = $(table_box).html();
if ($.browser.msie)
{
html += '<p></p>';
}
else
{
html += '<p> </p>';
}
this.execCommand('inserthtml', html);
this.modalClose();
this.$table = $(this.doc).find('body').find('#table' + tableid);
this.$table.click($.proxy(this.tableObserver, this));
if (this.opts.autoresize === true) this.setAutoSize(false);
},
tableObserver: function(e)
{
this.$table = $(e.target).parents('table');
this.$table_tr = this.$table.find('tr');
this.$table_td = this.$table.find('td');
this.$table_td.removeClass('current');
this.$tbody = $(e.target).parents('tbody');
this.$thead = $(this.$table).find('thead');
this.$current_td = $(e.target);
this.$current_td.addClass('current');
this.$current_tr = $(e.target).parents('tr');
},
deleteTable: function()
{
$(this.$table).remove();
this.$table = false;
this.syncCode();
},
deleteRow: function()
{
$(this.$current_tr).remove();
this.syncCode();
},
deleteColumn: function()
{
var index = $(this.$current_td).get(0).cellIndex;
$(this.$table).find('tr').each(function()
{
$(this).find('td').eq(index).remove();
});
this.syncCode();
},
addHead: function()
{
if ($(this.$table).find('thead').size() !== 0)
{
this.deleteHead();
}
else
{
var tr = $(this.$table).find('tr').first().clone();
tr.find('td').html(' ');
this.$thead = $('<thead></thead>');
this.$thead.append(tr);
$(this.$table).prepend(this.$thead);
this.syncCode();
}
},
deleteHead: function()
{
$(this.$thead).remove();
this.$thead = false;
this.syncCode();
},
insertRowAbove: function()
{
this.insertRow('before');
},
insertRowBelow: function()
{
this.insertRow('after');
},
insertColumnLeft: function()
{
this.insertColumn('before');
},
insertColumnRight: function()
{
this.insertColumn('after');
},
insertRow: function(type)
{
var new_tr = $(this.$current_tr).clone();
new_tr.find('td').html(' ');
if (type === 'after')
{
$(this.$current_tr).after(new_tr);
}
else
{
$(this.$current_tr).before(new_tr);
}
this.syncCode();
},
insertColumn: function(type)
{
var index = 0;
this.$current_td.addClass('current');
this.$current_tr.find('td').each(function(i,s)
{
if ($(s).hasClass('current'))
{
index = i;
}
});
this.$table_tr.each(function(i,s)
{
var current = $(s).find('td').eq(index);
var td = current.clone();
td.html(' ');
if (type === 'after')
{
$(current).after(td);
}
else
{
$(current).before(td);
}
});
this.syncCode();
},
// INSERT VIDEO
showVideo: function()
{
if ($.browser.msie)
{
this.markerIE();
}
this.modalInit(RLANG.video, 'video', 600, $.proxy(function()
{
$('#redactor_insert_video_btn').click($.proxy(this.insertVideo, this));
}, this),
function()
{
$('#redactor_insert_video_area').focus();
}
);
},
insertVideo: function()
{
var data = $('#redactor_insert_video_area').val();
data = this.stripTags(data);
if ($.browser.msie)
{
$(this.doc.getElementById('span' + this.spanid)).after(data).remove();
this.syncCode();
}
else
{
this.execCommand('inserthtml', data);
}
this.modalClose();
if (this.opts.autoresize === true)
{
this.setAutoSize(false);
}
},
// INSERT IMAGE
imageEdit: function(e)
{
var $el = $(e.target);
var parent = $el.parent();
var handler = $.proxy(function()
{
$('#redactor_file_alt').val($el.attr('alt'));
$('#redactor_image_edit_src').attr('href', $el.attr('src'));
$('#redactor_form_image_align').val($el.css('float'));
if ($(parent).get(0).tagName === 'A')
{
$('#redactor_file_link').val($(parent).attr('href'));
}
$('#redactor_image_delete_btn').click($.proxy(function() { this.imageDelete($el); }, this));
$('#redactorSaveBtn').click($.proxy(function() { this.imageSave($el); }, this));
}, this);
this.modalInit(RLANG.image, 'image_edit', 380, handler);
},
imageDelete: function(el)
{
$(el).remove();
this.modalClose();
this.syncCode();
if (this.opts.autoresize === true)
{
this.setAutoSize(false);
}
},
imageSave: function(el)
{
var parent = $(el).parent();
$(el).attr('alt', $('#redactor_file_alt').val());
var floating = $('#redactor_form_image_align').val();
if (floating === 'left')
{
$(el).css({ 'float': 'left', margin: '0 10px 10px 0' });
}
else if (floating === 'right')
{
$(el).css({ 'float': 'right', margin: '0 0 10px 10px' });
}
else
{
$(el).css({ 'float': 'none', margin: '0' });
}
// as link
var link = $.trim($('#redactor_file_link').val());
if (link !== '')
{
if ($(parent).get(0).tagName !== 'A')
{
$(el).replaceWith('<a href="' + link + '">' + this.outerHTML(el) + '</a>');
}
else
{
$(parent).attr('href', link);
}
}
else
{
if ($(parent).get(0).tagName === 'A')
{
$(parent).replaceWith(this.outerHTML(el));
}
}
this.modalClose();
this.observeImages();
this.syncCode();
},
showImage: function()
{
if ($.browser.msie)
{
this.markerIE();
}
var handler = $.proxy(function()
{
// json
if (this.opts.imageGetJson !== false)
{
$.getJSON(this.opts.imageGetJson, $.proxy(function(data) {
$.each(data, $.proxy(function(key, val)
{
var img = $('<img src="' + val.thumb + '" rel="' + val.image + '" />');
$('#redactor_image_box').append(img);
$(img).click($.proxy(this.imageSetThumb, this));
}, this));
}, this));
}
else
{
$('#redactor_tabs a').eq(1).remove();
}
if (this.opts.imageUpload !== false)
{
// dragupload
if (this.isMobile() === false)
{
if ($('#redactor_file').size() !== 0)
{
$('#redactor_file').dragupload(
{
url: this.opts.imageUpload,
success: $.proxy(this.imageUploadCallback, this)
});
}
}
// ajax upload
this.uploadInit('redactor_file', { auto: true, url: this.opts.imageUpload, success: $.proxy(this.imageUploadCallback, this) });
}
else
{
$('.redactor_tab').hide();
if (this.opts.imageGetJson === false)
{
$('#redactor_tabs').remove();
$('#redactor_tab3').show();
}
else
{
var tabs = $('#redactor_tabs a');
tabs.eq(0).remove();
tabs.eq(1).addClass('redactor_tabs_act');
$('#redactor_tab2').show();
}
}
$('#redactor_upload_btn').click($.proxy(this.imageUploadCallbackLink, this));
}, this);
var endCallback = $.proxy(function()
{
if (this.opts.imageUpload === false && this.opts.imageGetJson === false)
{
$('#redactor_file_link').focus();
}
}, this);
this.modalInit(RLANG.image, 'image', 570, handler, endCallback, true);
},
imageSetThumb: function(e)
{
this._imageSet('<img alt="" src="' + $(e.target).attr('rel') + '" />', true);
},
imageUploadCallbackLink: function()
{
if ($('#redactor_file_link').val() !== '')
{
var data = '<img src="' + $('#redactor_file_link').val() + '" />';
this._imageSet(data, true);
}
else
{
this.modalClose();
}
},
imageUploadCallback: function(data)
{
this._imageSet(data);
},
_imageSet: function(json, link)
{
var html = '', data = '';
if (link !== true)
{
data = $.parseJSON(json);
html = '<p><img src="' + data.filelink + '" /></p>';
}
else
{
html = json;
}
this.focus();
if ($.browser.msie)
{
$(this.doc.getElementById('span' + this.spanid)).after(html).remove();
this.syncCode();
}
else
{
this.execCommand('inserthtml', html);
}
// upload image callback
if (link !== true && typeof this.opts.imageUploadCallback === 'function')
{
this.opts.imageUploadCallback(this, data);
}
this.modalClose();
$(this.doc).find('img').load($.proxy(function()
{
this.setAutoSize(false);
}, this));
this.observeImages();
},
// INSERT LINK
showLink: function()
{
var handler = $.proxy(function()
{
var sel = this.getSelection();
var url = '', text = '';
if ($.browser.msie)
{
var parent = this.getParentNode();
if (parent.nodeName === 'A')
{
this.insert_link_node = $(parent);
text = this.insert_link_node.text();
url = this.insert_link_node.attr('href');
}
else
{
if (this.oldIE())
{
text = sel.text;
}
else
{
text = sel.toString();
}
this.spanid = Math.floor(Math.random() * 99999);
var html = '<span id="span' + this.spanid + '">' + text + '</span>';
if (text !== '')
{
html = '<span id="span' + this.spanid + '">' + text + '</span>';
}
this.execCommand('inserthtml', html);
}
}
else
{
if (sel && sel.anchorNode && sel.anchorNode.parentNode.tagName === 'A')
{
url = sel.anchorNode.parentNode.href;
text = sel.anchorNode.parentNode.text;
if (sel.toString() === '')
{
this.insert_link_node = sel.anchorNode.parentNode;
}
}
else
{
text = sel.toString();
url = '';
}
}
$('.redactor_link_text').val(text);
var turl = url.replace(top.location.href, '');
if (url.search('mailto:') === 0)
{
this.setModalTab(2);
$('#redactor_tab_selected').val(2);
$('#redactor_link_mailto').val(url.replace('mailto:', ''));
}
else if (turl.search(/^#/gi) === 0)
{
this.setModalTab(3);
$('#redactor_tab_selected').val(3);
$('#redactor_link_anchor').val(turl.replace(/^#/gi, ''));
}
else
{
$('#redactor_link_url').val(url);
}
$('#redactor_insert_link_btn').click($.proxy(this.insertLink, this));
}, this);
var endCallback = function(url)
{
$('#redactor_link_url').focus();
};
this.modalInit(RLANG.link, 'link', 460, handler, endCallback);
},
insertLink: function()
{
var tab_selected = $('#redactor_tab_selected').val();
var link = '', text = '';
if (tab_selected === '1') // url
{
link = $('#redactor_link_url').val();
text = $('#redactor_link_url_text').val();
}
else if (tab_selected === '2') // mailto
{
link = 'mailto:' + $('#redactor_link_mailto').val();
text = $('#redactor_link_mailto_text').val();
}
else if (tab_selected === '3') // anchor
{
link = '#' + $('#redactor_link_anchor').val();
text = $('#redactor_link_anchor_text').val();
}
this._insertLink('<a href="' + link + '">' + text + '</a> ', $.trim(text), link);
},
_insertLink: function(a, text, link)
{
if (text != '')
{
if (this.insert_link_node)
{
$(this.insert_link_node).text(text);
$(this.insert_link_node).attr('href', link);
this.syncCode();
}
else
{
if ($.browser.msie)
{
$(this.doc.getElementById('span' + this.spanid)).replaceWith(a);
this.syncCode();
}
else
{
this.execCommand('inserthtml', a);
}
}
}
this.modalClose();
},
// INSERT FILE
showFile: function()
{
if ($.browser.msie)
{
this.markerIE();
}
var handler = $.proxy(function()
{
var sel = this.getSelection();
var text = '';
if (this.oldIE())
{
text = sel.text;
}
else
{
text = sel.toString();
}
$('#redactor_filename').val(text);
// dragupload
if (this.isMobile() === false)
{
$('#redactor_file').dragupload(
{
url: this.opts.fileUpload,
success: $.proxy(function(data)
{
this.fileUploadCallback(data);
}, this)
});
}
this.uploadInit('redactor_file', { auto: true, url: this.opts.fileUpload, success: $.proxy(function(data) {
this.fileUploadCallback(data);
}, this)});
}, this);
this.modalInit(RLANG.file, 'file', 500, handler);
},
fileUploadCallback: function(json)
{
var data = $.parseJSON(json);
var text = $('#redactor_filename').val();
if (text === '')
{
text = data.filename;
}
var link = '<a href="' + data.filelink + '">' + text + '</a>';
// chrome fix
if ($.browser.webkit && !!window.chrome)
{
link = link + ' ';
}
if ($.browser.msie)
{
if (text !== '')
{
$(this.doc.getElementById('span' + this.spanid)).replaceWith(link);
}
else
{
$(this.doc.getElementById('span' + this.spanid)).after(link).remove();
}
this.syncCode();
}
else
{
this.execCommand('inserthtml', link);
}
// file upload callback
if (typeof this.opts.fileUploadCallback === 'function')
{
this.opts.fileUploadCallback(this, data);
}
this.modalClose();
},
// MODAL
modalInit: function(title, url, width, handler, endCallback, scroll)
{
// modal overlay
if ($('#redactor_modal_overlay').size() === 0)
{
this.overlay = $('<div id="redactor_modal_overlay" style="display: none;"></div>');
$('body').prepend(this.overlay);
}
if (this.opts.overlay)
{
$('#redactor_modal_overlay').show();
$('#redactor_modal_overlay').click($.proxy(this.modalClose, this));
}
if ($('#redactor_modal').size() === 0)
{
this.modal = $('<div id="redactor_modal" style="display: none;"><div id="redactor_modal_close">×</div><div id="redactor_modal_header"></div><div id="redactor_modal_inner"></div></div>');
$('body').append(this.modal);
}
$('#redactor_modal_close').click($.proxy(this.modalClose, this));
this.hdlModalClose = $.proxy(function(e) { if ( e.keyCode === 27) { this.modalClose(); } }, this);
$(document).keyup(this.hdlModalClose);
$(this.doc).keyup(this.hdlModalClose);
$('#redactor_modal_inner').html(this.opts['modal_' + url]);
$('#redactor_modal_header').html(title);
// tabs
if ($('#redactor_tabs').size() !== 0)
{
var that = this;
$('#redactor_tabs a').each(function(i,s)
{
i++;
$(s).click(function()
{
$('#redactor_tabs a').removeClass('redactor_tabs_act');
$(this).addClass('redactor_tabs_act');
$('.redactor_tab').hide();
$('#redactor_tab' + i).show();
$('#redactor_tab_selected').val(i);
if (that.isMobile() === false)
{
var height = $('#redactor_modal').outerHeight();
$('#redactor_modal').css('margin-top', '-' + (height+10)/2 + 'px');
}
});
});
}
$('#redactor_btn_modal_close').click($.proxy(this.modalClose, this));
// callback
if (typeof(handler) === 'function')
{
handler();
}
// setup
var height = $('#redactor_modal').outerHeight();
if (this.isMobile() === false)
{
$('#redactor_modal').css({ position: 'fixed', top: '50%', left: '50%', width: width + 'px', height: 'auto', marginTop: '-' + (height+10)/2 + 'px', marginLeft: '-' + (width+60)/2 + 'px' }).fadeIn('fast');
}
else
{
$('#redactor_modal').css({ position: 'absolute', width: '96%', height: 'auto', top: '20px', left: '0', marginTop: '0px', marginLeft: '2%' }).show();
this.scrolltop();
}
// end callback
if (typeof(endCallback) === 'function')
{
endCallback();
}
if (scroll === true)
{
$('#redactor_image_box').height(300).css('overflow', 'auto');
}
},
modalClose: function()
{
$('#redactor_modal_close').unbind('click', this.modalClose);
$('#redactor_modal').fadeOut('fast', $.proxy(function()
{
$('#redactor_modal_inner').html('');
if (this.opts.overlay)
{
$('#redactor_modal_overlay').hide();
$('#redactor_modal_overlay').unbind('click', this.modalClose);
}
$(document).unbind('keyup', this.hdlModalClose);
$(this.doc).unbind('keyup', this.hdlModalClose);
}, this));
},
setModalTab: function(num)
{
$('.redactor_tab').hide();
var tabs = $('#redactor_tabs a');
tabs.removeClass('redactor_tabs_act');
tabs.eq(num-1).addClass('redactor_tabs_act');
$('#redactor_tab' + num).show();
},
// UPLOAD
uploadInit: function(element, options)
{
// Upload Options
this.uploadOptions = {
url: false,
success: false,
start: false,
trigger: false,
auto: false,
input: false
};
$.extend(this.uploadOptions, options);
// Test input or form
if ($('#' + element).size() !== 0 && $('#' + element).get(0).tagName === 'INPUT')
{
this.uploadOptions.input = $('#' + element);
this.element = $($('#' + element).get(0).form);
}
else
{
this.element = $('#' + element);
}
this.element_action = this.element.attr('action');
// Auto or trigger
if (this.uploadOptions.auto)
{
$(this.uploadOptions.input).change($.proxy(function()
{
this.element.submit(function(e) { return false; });
this.uploadSubmit();
}, this));
}
else if (this.uploadOptions.trigger)
{
$('#' + this.uploadOptions.trigger).click($.proxy(this.uploadSubmit, this));
}
},
uploadSubmit : function()
{
this.uploadForm(this.element, this.uploadFrame());
},
uploadFrame : function()
{
this.id = 'f' + Math.floor(Math.random() * 99999);
var d = document.createElement('div');
var iframe = '<iframe style="display:none" src="about:blank" id="'+this.id+'" name="'+this.id+'"></iframe>';
d.innerHTML = iframe;
document.body.appendChild(d);
// Start
if (this.uploadOptions.start)
{
this.uploadOptions.start();
}
$('#' + this.id).load($.proxy(this.uploadLoaded, this));
return this.id;
},
uploadForm : function(f, name)
{
if (this.uploadOptions.input)
{
var formId = 'redactorUploadForm' + this.id;
var fileId = 'redactorUploadFile' + this.id;
this.form = $('<form action="' + this.uploadOptions.url + '" method="POST" target="' + name + '" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = this.uploadOptions.input;
var newElement = $(oldElement).clone();
$(oldElement).attr('id', fileId);
$(oldElement).before(newElement);
$(oldElement).appendTo(this.form);
$(this.form).css('position', 'absolute');
$(this.form).css('top', '-2000px');
$(this.form).css('left', '-2000px');
$(this.form).appendTo('body');
this.form.submit();
}
else
{
f.attr('target', name);
f.attr('method', 'POST');
f.attr('enctype', 'multipart/form-data');
f.attr('action', this.uploadOptions.url);
this.element.submit();
}
},
uploadLoaded : function()
{
var i = $('#' + this.id);
var d;
if (i.contentDocument)
{
d = i.contentDocument;
}
else if (i.contentWindow)
{
d = i.contentWindow.document;
}
else
{
d = window.frames[this.id].document;
}
if (d.location.href === "about:blank")
{
return true;
}
// Success
if (this.uploadOptions.success)
{
// Remove bizarre <pre> tag wrappers around our json data:
var rawString = d.body.innerHTML;
var jsonString = rawString.match(/\{.*\}/)[0];
this.uploadOptions.success(jsonString);
}
this.element.attr('action', this.element_action);
this.element.attr('target', '');
},
// UTILITY
markerIE: function()
{
this.spanid = Math.floor(Math.random() * 99999);
this.execCommand('inserthtml', '<span id="span' + this.spanid + '"></span>');
},
oldIE: function()
{
if ($.browser.msie && parseInt($.browser.version, 10) < 9)
{
return true;
}
return false;
},
outerHTML: function(s)
{
return $("<p>").append($(s).eq(0).clone()).html();
},
normalize: function(str)
{
return parseInt(str.replace('px',''), 10);
},
isMobile: function()
{
if (/(iPhone|iPod|iPad|BlackBerry|Android)/.test(navigator.userAgent))
{
return true;
}
else
{
return false;
}
},
scrolltop: function()
{
$('html,body').animate({ scrollTop: 0 }, 500);
}
};
// API
$.fn.getDoc = function()
{
return $(this.data('redactor').doc);
};
$.fn.getFrame = function()
{
return this.data('redactor').$frame;
};
$.fn.getEditor = function()
{
return this.data('redactor').$editor;
};
$.fn.getCode = function()
{
return this.data('redactor').getCode();
};
$.fn.getText = function()
{
return this.data('redactor').$editor.text();
};
$.fn.setCode = function(html)
{
this.data('redactor').setCode(html);
};
$.fn.insertHtml = function(html)
{
this.data('redactor').insertHtml(html);
};
$.fn.destroyEditor = function()
{
this.data('redactor').destroy();
this.removeData('redactor');
};
$.fn.setFocus = function()
{
this.data('redactor').focus();
};
$.fn.execCommand = function(cmd, param)
{
this.data('redactor').execCommand(cmd, param);
};
})(jQuery);
/*
Plugin Drag and drop Upload v1.0.1
http://imperavi.com/
Copyright 2012, Imperavi Ltd.
*/
(function($){
"use strict";
// Initialization
$.fn.dragupload = function(options)
{
return this.each(function() {
var obj = new Construct(this, options);
obj.init();
});
};
// Options and variables
function Construct(el, options) {
this.opts = $.extend({
url: false,
success: false,
preview: false,
text: RLANG.drop_file_here,
atext: RLANG.or_choose
}, options);
this.$el = $(el);
}
// Functionality
Construct.prototype = {
init: function()
{
if (!$.browser.opera && !$.browser.msie)
{
this.droparea = $('<div class="redactor_droparea"></div>');
this.dropareabox = $('<div class="redactor_dropareabox">' + this.opts.text + '</div>');
this.dropalternative = $('<div class="redactor_dropalternative">' + this.opts.atext + '</div>');
this.droparea.append(this.dropareabox);
this.$el.before(this.droparea);
this.$el.before(this.dropalternative);
// drag over
this.dropareabox.bind('dragover', $.proxy(function() { return this.ondrag(); }, this));
// drag leave
this.dropareabox.bind('dragleave', $.proxy(function() { return this.ondragleave(); }, this));
var uploadProgress = $.proxy(function(e)
{
var percent = parseInt(e.loaded / e.total * 100, 10);
this.dropareabox.text('Loading ' + percent + '%');
}, this);
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload)
{
xhr.upload.addEventListener('progress', uploadProgress, false);
}
var provider = function () { return xhr; };
// drop
this.dropareabox.get(0).ondrop = $.proxy(function(event)
{
event.preventDefault();
this.dropareabox.removeClass('hover').addClass('drop');
var file = event.dataTransfer.files[0];
var fd = new FormData();
fd.append('file', file);
$.ajax({
dataType: 'html',
url: this.opts.url,
data: fd,
xhr: provider,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: $.proxy(function(data)
{
if (this.opts.success !== false)
{
this.opts.success(data);
}
if (this.opts.preview === true)
{
this.dropareabox.html(data);
}
}, this)
});
}, this);
}
},
ondrag: function()
{
this.dropareabox.addClass('hover');
return false;
},
ondragleave: function()
{
this.dropareabox.removeClass('hover');
return false;
}
};
})(jQuery);
// Define: Linkify plugin from stackoverflow
(function($){
"use strict";
var url1 = /(^|<|\s)(www\..+?\..+?)(\s|>|$)/g,
url2 = /(^|<|\s)(((https?|ftp):\/\/|mailto:).+?)(\s|>|$)/g,
linkifyThis = function ()
{
var childNodes = this.childNodes,
i = childNodes.length;
while(i--)
{
var n = childNodes[i];
if (n.nodeType === 3)
{
var html = n.nodeValue;
if (html)
{
html = html.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(url1, '$1<a href="http://$2">$2</a>$3')
.replace(url2, '$1<a href="$2">$2</a>$5');
$(n).after(html).remove();
}
}
else if (n.nodeType === 1 && !/^(a|button|textarea)$/i.test(n.tagName))
{
linkifyThis.call(n);
}
}
};
$.fn.linkify = function ()
{
this.each(linkifyThis);
};
})(jQuery);
| JavaScript |
var RELANG = {};
RELANG['tr'] = {
html: 'HTML',
video: 'Video',
image: 'Görsel',
table: 'Tablo',
link: 'Bağlantı',
link_insert: 'Bağlantı Ekle ...',
unlink: 'Bağlantı Kaldır',
formatting: 'Stiller',
paragraph: 'Paragraf',
quote: 'Alıntı',
code: 'Kod',
header1: 'Başlık 1',
header2: 'Başlık 2',
header3: 'Başlık 3',
header4: 'Başlık 4',
bold: 'Kalın',
italic: 'Eğik',
fontcolor: 'Yazı rengi',
backcolor: 'Arkaplan rengi',
unorderedlist: 'Sırasız liste',
orderedlist: 'Sıralı liste',
outdent: 'Girintiyi azalt',
indent: 'Girintiyi artır',
cancel: 'İptal',
insert: 'Ekle',
save: 'Kaydet',
_delete: 'Sil',
insert_table: 'Tablo ekle',
insert_row_above: 'Yukarı satır ekle',
insert_row_below: 'Alta satır ekle',
insert_column_left: 'Sola sütun ekle',
insert_column_right: 'Sağa sütun ekle',
delete_column: 'Sütun sil',
delete_row: 'Satır sil',
delete_table: 'Tablo sil',
rows: 'Satırlar',
columns: 'Sütunlar',
add_head: 'Başlık ekle',
delete_head: 'Başlık sil',
title: 'Başlık',
image_position: 'Pozisyon',
none: 'hiçbiri',
left: 'sol',
right: 'sağ',
image_web_link: 'Görselin web bağlantısı',
text: 'Yazı',
mailto: 'E-Posta',
web: 'URL',
video_html_code: 'Video embed kodu',
file: 'Dosya',
upload: 'Yükle',
download: 'İndir',
choose: 'Seç',
or_choose: 'Veya seç',
drop_file_here: 'Dosyayı buraya bırak',
align_left: 'Sola hizala',
align_center: 'Ortala',
align_right: 'Sağa hizala',
align_justify: 'Satır uzunluğuna ayarla',
horizontalrule: 'Yatay çizgi',
fullscreen: 'Tam ekran',
deleted: 'Silindi',
anchor: 'Çapa'
};
| JavaScript |
var RELANG = {};
RELANG['ru'] = {
html: 'Код',
video: 'Видео',
image: 'Изображение',
table: 'Таблица',
link: 'Ссылка',
link_insert: 'Вставить ссылку ...',
unlink: 'Удалить ссылку',
formatting: 'Форматирование',
paragraph: 'Обычный текст',
quote: 'Цитата',
code: 'Код',
header1: 'Заголовок 1',
header2: 'Заголовок 2',
header3: 'Заголовок 3',
header4: 'Заголовок 4',
bold: 'Полужирный',
italic: 'Наклонный',
fontcolor: 'Цвет текста',
backcolor: 'Заливка текста',
unorderedlist: 'Обычный список',
orderedlist: 'Нумерованный список',
outdent: 'Уменьшить отступ',
indent: 'Увеличить отступ',
cancel: 'Отменить',
insert: 'Вставить',
save: 'Сохранить',
_delete: 'Удалить',
insert_table: 'Вставить таблицу',
insert_row_above: 'Добавить строку сверху',
insert_row_below: 'Добавить строку снизу',
insert_column_left: 'Добавить столбец слева',
insert_column_right: 'Добавить столбец справа',
delete_column: 'Удалить столбец',
delete_row: 'Удалить строку',
delete_table: 'Удалить таблицу',
rows: 'Строки',
columns: 'Столбцы',
add_head: 'Добавить заголовок',
delete_head: 'Удалить заголовок',
title: 'Подсказка',
image_position: 'Обтекание текстом',
none: 'Нет',
left: 'Cлева',
right: 'Cправа',
image_web_link: 'Cсылка на изображение',
text: 'Текст',
mailto: 'Эл. почта',
web: 'URL',
video_html_code: 'Код видео ролика',
file: 'Файл',
upload: 'Загрузить',
download: 'Скачать',
choose: 'Выбрать',
or_choose: 'Или выберите',
drop_file_here: 'Перетащите файл сюда',
align_left: 'По левому краю',
align_center: 'По центру',
align_right: 'По правому краю',
align_justify: 'Выровнять текст по ширине',
horizontalrule: 'Горизонтальная линейка',
fullscreen: 'Во весь экран',
deleted: 'Зачеркнутый',
anchor: 'Якорь'
};
| JavaScript |
var RELANG = {};
RELANG['ko'] = {
html: 'HTML',
video: '비디오',
image: '이미지',
table: '표',
link: '링크',
link_insert: '링크 삽입...',
unlink: '링크 삭제',
formatting: '스타일',
paragraph: '단락',
quote: '인용',
code: '코드',
header1: '헤더 1',
header2: '헤더 2',
header3: '헤더 3',
header4: '헤더 4',
bold: '굵게',
italic: '기울임꼴',
fontcolor: '글자색',
backcolor: '배경색',
unorderedlist: '글머리기호',
orderedlist: '번호매기기',
outdent: '내어쓰기',
indent: '들여쓰기',
cancel: '취소',
insert: '삽입',
save: '저장',
_delete: '삭제',
insert_table: '표 삽입',
insert_row_above: '열을 위에 추가',
insert_row_below: '열을 아래에 추가',
insert_column_left: '행을 왼쪽에 추가',
insert_column_right: '행을 오른쪽에 추가',
delete_column: '컬럼 삭제',
delete_row: '행 삭제',
delete_table: '표 삭제',
rows: '열',
columns: '행',
add_head: '표 헤더 추가',
delete_head: '표 헤더 체거',
title: '제목',
image_position: '이미지 위치',
none: '없음',
left: '왼쪽',
right: '오른쪽',
image_web_link: '이미지 링크',
text: '텍스트',
mailto: '메일',
web: 'URL',
video_html_code: '비디오 삽입(embed) 코드',
file: '파일',
upload: '업로드',
download: '다운로드',
choose: '선택',
or_choose: '또는 선택',
drop_file_here: '파일을 여기에 떨굼',
align_left: '왼쪽정렬',
align_center: '가운데정렬',
align_right: '오른쪽정렬',
align_justify: '가지런히정렬',
horizontalrule: '수평선',
fullscreen: '전체화면',
deleted: '취소선',
anchor: '링크'
};
| JavaScript |
//@chen1706@gmail.com
var RELANG = {};
RELANG['zh_cn'] = {
html: 'HTML代码',
video: '视频',
image: '图片',
table: '表格',
link: '链接',
link_insert: '插入链接',
unlink: '取消链接',
formatting: '样式',
paragraph: '段落',
quote: '引用',
code: '代码',
header1: '一级标题',
header2: '二级标题',
header3: '三级标题',
header4: '四级标题',
bold: '粗体',
italic: '斜体',
fontcolor: '字体颜色',
backcolor: '背景颜色',
unorderedlist: '项目编号',
orderedlist: '数字编号',
outdent: '减少缩进',
indent: '增加缩进',
cancel: '取消',
insert: '插入',
save: '保存',
_delete: '删除',
insert_table: '插入表格',
insert_row_above: '在上方插入',
insert_row_below: '在下方插入',
insert_column_left: '在左侧插入',
insert_column_right: '在右侧插入',
delete_column: '删除整列',
delete_row: '删除整行',
delete_table: '删除表格',
rows: '行',
columns: '列',
add_head: '添加标题',
delete_head: '删除标题',
title: '标题',
image_position: '位置',
none: '无',
left: '左',
right: '右',
image_web_link: '图片网页链接',
text: '文本',
mailto: '邮箱',
web: '网址',
video_html_code: '视频嵌入代码',
file: '文件',
upload: '上传',
download: '下载',
choose: '选择',
or_choose: '或选择',
drop_file_here: '将文件拖拽至此区域',
align_left: '左对齐',
align_center: '居中',
align_right: '右对齐',
align_justify: '两端对齐',
horizontalrule: '水平线',
fullscreen: '全屏',
deleted: '删除',
anchor: '锚点'
};
| JavaScript |
var RELANG = {};
RELANG['fr'] = {
html: 'Code HTML',
video: 'Vidéo',
image: 'Image',
table: 'Tableau',
link: 'Lien URL',
link_insert: 'Insérer/Modifier un lien',
unlink: 'Nettoyer le lien',
styles: 'Styles',
paragraph: 'Paragraphe',
quote: 'Citation',
code: 'Code',
header1: 'Titre 1',
header2: 'Titre 2',
header3: 'Titre 3',
header4: 'Titre 4',
format: 'Format',
bold: 'Gras',
italic: 'Italique',
superscript: 'Diacritique',
strikethrough: 'Rayé',
fontcolor: 'Couleur du texte',
backcolor: 'Couleur du fond de ligne',
removeformat: 'Nettoyer le format',
lists: 'Listes',
unorderedlist: 'Liste à puce',
orderedlist: 'Liste numérotée',
outdent: 'Diminuer l\'alinéa',
indent: 'Augmenter l\'alinéa',
redo: 'Refaire',
undo: 'Défaire',
cut: 'Couper',
cancel: 'Annuler',
insert: 'Insérer',
save: 'Sauvegarder',
_delete: 'Supprimer',
insert_table: 'Insérer le tableau',
insert_row_above: 'Ajouter une ligne au dessus',
insert_row_below: 'Ajouter une ligne en dessous',
insert_column_left: 'Ajouter une colonne à gauche',
insert_column_right: 'Ajouter une colonne à droite',
delete_column: 'Supprimer la colonne',
delete_row: 'Supprimer la ligne',
delete_table: 'Supprimer le tableau',
Rows: 'Lignes ',
Columns: 'Colonnes',
add_head: 'Ajouter un titre',
delete_head: 'Supprimer le titre',
title: 'Titre',
image_view: 'Voir l\'image',
image_position: 'Position de l\'image',
none: 'aucun',
left: 'à gauche',
right: 'à droite',
image_web_link: 'lien de l\'image',
text: 'Texte',
mailto: 'Envoyer à ',
web: 'URL',
video_html_code: 'Code HTML de la vidéo',
file: 'Fichier',
upload: 'Envoyer',
download: 'Télécharger',
choose: 'Choisir',
or_choose: 'ou',
drop_file_here: 'Glissez-déposez le fichier ici',
align_left: 'Aligner à gauche',
align_center: 'Aligner au centre',
align_right: 'Aligner à droite',
align_justify: 'Justifier',
horizontalrule: 'Ligne horizontale',
fullscreen: 'Plein écran',
deleted: 'Supprimer',
none: 'aucun',
anchor: 'Ancre'
}; | JavaScript |
var RELANG = {};
RELANG['fa'] = {
html: 'اچ تی ام ال',
video: 'درج ویدیو...',
image: 'درج تصویر',
table: 'جدول',
link: 'پیوند',
link_insert: 'درج پیوند ...',
unlink: 'از بین بردن پیوند',
formatting: 'فالب بندی',
paragraph: 'پراگراف',
quote: 'نقل قول',
code: 'کد',
header1: 'سرامد 1',
header2: 'سرامد 2',
header3: 'سرامد 3',
header4: 'سرامد 4',
bold: 'درشت',
italic: 'خمیده',
fontcolor: 'رنگ قلم',
backcolor: 'رنگ ضمینه',
unorderedlist: 'فهرست نامرتب',
orderedlist: 'فهرست مرتب شده',
outdent: 'بیرو رفتگی',
indent: 'تو رفتگی',
cancel: 'انصراف',
insert: 'درج',
save: 'ذخیره',
_delete: 'حذف',
insert_table: 'درج جدول ..',
insert_row_above: 'سطر جدید در بالا',
insert_row_below: 'سطر جدید در پائین',
insert_column_left: 'ستون جدید در سمت چپ',
insert_column_right: 'ستون جدید در سمت راست',
delete_column: 'حذف ستون',
delete_row: 'حذف سطر',
delete_table: 'حذف جدول',
rows: 'سطرها',
columns: 'ستونها',
add_head: 'درج سر ستون ',
delete_head: 'حذف سرستون',
title: 'عنوان',
image_position: 'موقعیت',
none: 'هیچیک',
left: 'چپ',
right: 'راست',
image_web_link: 'آدرس تصویر در اینترنت',
text: 'متن',
mailto: 'ایمیل',
web: 'آدرس',
video_html_code: 'کد نمایش ویدئو',
file: 'درج فایل ....',
upload: 'بارگزاری',
download: 'بارگیری',
choose: 'انتخاب کنید',
or_choose: 'یا انتخاب کنید',
drop_file_here: 'این فایل ها حذف شوند',
align_left: 'چپ جین',
align_center: 'وسط چین',
align_right: 'راست چین',
align_justify: 'کشیده',
horizontalrule: 'درج خط جدا کننده',
fullscreen: 'نمایش کامل',
deleted: 'حذف شده',
anchor: 'قلاب'
};
| JavaScript |
var RELANG = {};
RELANG['eo'] = {
html: 'HTML', // substantive
video: 'Enŝovu Videon...', // imperative
image: 'Enŝovu Bildon...', // imperative
table: 'Tabelo', // substantive
link: 'Ligu', // imperative
link_insert: 'Enŝovu Ligilon ...', // imperative
unlink: 'Malligu', // imperative
formatting: 'Tekstaranĝo', // substantive
paragraph: 'Paragrafo', // substantive
quote: 'Citaĵo', // substantive
code: 'Kodo', // substantive
header1: 'Kapo 1', // substantive
header2: 'Kapo 2', // substantive
header3: 'Kapo 3', // substantive
header4: 'Kapo 4', // substantive
bold: 'Grasa', // adjective
italic: 'Kursiva', // adjective
fontcolor: 'Tipara koloro', // substantive
backcolor: 'Fona koloro', // substantive
unorderedlist: 'Malorda Listo', // substantive
orderedlist: 'Orda Listo', // substantive
outdent: 'Malkrommarĝenu', // imperative
indent: 'Krommarĝenu', // imperative
cancel: 'Rezignu', // imperative
insert: 'Enŝovu', // imperative
save: 'Konservu', // imperative
_delete: 'Forigu', // imperative
insert_table: 'Enŝovu Tabelon...', // imperative
insert_row_above: 'Enŝovu Vico Supren', // imperative
insert_row_below: 'Enŝovu Vico Malsupren', // imperative
insert_column_left: 'Enŝovu Kolumno Maldekstren', // imperative
insert_column_right: 'Enŝovu Kolumno Dekstre', // imperative
delete_column: 'Forigu Kolumnon', // imperative
delete_row: 'Forigu Vicon', // imperative
delete_table: 'Forigu Tabelon', // imperative
rows: 'Vicoj', // substantive (plural)
columns: 'Kolumnoj', // substantive (plural)
add_head: 'Enŝovu Kapon', // imperative
delete_head: 'Forigu Kapon', // imperative
title: 'Titolo', // substantive
image_position: 'Bildloko', // substantive
none: 'Neniu', // determiner
left: 'Maldekstra', // adjective
right: 'Dekstra', // adjective
image_web_link: 'Bilda Hiperligilo', // substantive
text: 'Teksto', // substantive
mailto: 'Retpoŝto', // substantive
web: 'URL', // substantive
video_html_code: 'Videa Enkorpigita Kodo', // substantive
file: 'Enŝovu Dosieron...', // imperative
upload: 'Alŝutu', // imperative
download: 'Elŝutu', // imperative
choose: 'Elektu', // imperative
or_choose: 'Aŭ Elektu', // imperative
drop_file_here: 'Demetu Dosiero Ĉi Tien', // imperative
align_left: 'Ĝisrandigu Maldekstren', // imperative
align_center: 'Centrigu', // imperative
align_right: 'Ĝisrandigu Dekstren', // imperative
align_justify: 'Ĝisrandigu', // imperative
horizontalrule: 'Enŝovu Horizontala Linion', // imperative
fullscreen: 'Plenekrana', // adjective
deleted: 'Foriga', // adjective
anchor: 'Ankro' // substantive
};
| JavaScript |
var RELANG = {};
RELANG['de'] = {
html: 'HTML',
video: 'Video',
image: 'Bilder',
table: 'Tabelle',
link: 'Link',
link_insert: 'Link einfügen ...',
unlink: 'Link entfernen',
formatting: 'Formatvorlagen',
paragraph: 'Absatz',
quote: 'Zitat',
code: 'Code',
header1: 'Überschrift 1',
header2: 'Überschrift 2',
header3: 'Überschrift 3',
header4: 'Überschrift 4',
bold: 'Fett',
italic: 'Kursiv',
fontcolor: 'Schriftfarbe',
backcolor: 'Texthervorhebungsfarbe',
unorderedlist: 'Aufzählungszeichen',
orderedlist: 'Nummerierung',
outdent: 'Einzug verkleinern',
indent: 'Einzug vergrößern',
redo: 'Wiederholen',
undo: 'Rückgängig',
cut: 'Ausschneiden',
cancel: 'Abbrechen',
insert: 'Einfügen',
save: 'Speichern',
_delete: 'Löschen',
insert_table: 'Tabelle einfügen',
insert_row_above: 'Zeile oberhalb einfügen',
insert_row_below: 'Zeile unterhalb einfügen',
insert_column_left: 'Spalte links einfügen',
insert_column_right: 'Spalte rechts einfügen',
delete_column: 'Spalte löschen',
delete_row: 'Zeile löschen',
delete_table: 'Tabelle löschen',
rows: 'Zeilen',
columns: 'Spalten',
add_head: 'Titel einfügen',
delete_head: 'Titel entfernen',
title: 'Title',
image_view: 'Bilder',
image_position: 'Textumbruch',
none: 'Keine',
left: 'Links',
right: 'Rechts',
image_web_link: 'Bilder Link',
text: 'Text',
mailto: 'Email',
web: 'URL',
video_html_code: 'Video-Einbettungscode',
file: 'Datei',
upload: 'Hochladen',
download: 'Download',
choose: 'Auswählen',
or_choose: 'Oder, wählen Sie eine Datei aus',
drop_file_here: 'Ziehen Sie eine Datei hier hin',
align_left: 'Linksbündig',
align_center: 'Mitte',
align_right: 'Rechtsbündig',
align_justify: 'Blocksatz',
horizontalrule: 'Horizontale Linie',
fullscreen: 'Vollbild',
deleted: 'Durchgestrichen',
anchor: 'Anker'
}; | JavaScript |
var RELANG = {};
RELANG['by'] = {
html: 'Код',
video: 'Відэа',
image: 'Малюнак',
table: 'Табліца',
link: 'Спасылка',
link_insert: 'Уставіць спасылку ...',
unlink: 'Выдаліць спасылку',
formatting: 'Стылі',
paragraph: 'Звычайны тэкст',
quote: 'Цытата',
code: 'Код',
header1: 'Загаловак 1',
header2: 'Загаловак 2',
bold: 'Паўтлусты',
italic: 'Нахільны',
fontcolor: 'Колер тэксту',
backcolor: 'Заліванне тэксту',
unorderedlist: 'Звычайны спіс',
orderedlist: 'Нумараваны спіс',
outdent: 'Паменьшыць водступ',
indent: 'Павялічыць водступ',
cancel: 'Адмяніць',
insert: 'Уставіць',
save: 'Захаваць',
_delete: 'Выдаліць',
insert_table: 'Уставіць табліцу',
insert_row_above: 'Дадаць радок зверху',
insert_row_below: 'Дадаць радок знізу',
insert_column_left: 'Дадаць слупок злева',
insert_column_right: 'Дадаць слупок справа',
delete_column: 'Выдаліць слупок',
delete_row: 'Выдаліць радок',
delete_table: 'Выдаліць табліцу',
rows: 'Радкі',
columns: 'Стаўбцы',
add_head: 'Дадаць загаловак',
delete_head: 'Выдаліць загаловак',
title: 'Падказка',
image_view: 'Запампаваць малюнак',
image_position: 'Абцяканне тэкстам',
none: 'Няма',
left: 'Злева',
right: 'Справа',
image_web_link: 'Спасылка на малюнак',
text: 'Тэкст',
mailto: 'Эл. пошта ',
web: 'URL',
video_html_code: 'Код відэа роліка',
file: 'Файл',
upload: 'Загрузіць',
download: 'Запампаваць',
choose: 'Выбраць',
or_choose: 'Ці іншае',
drop_file_here: 'Перацягніце файл сюды',
align_left: 'Па левым краі',
align_center: 'Па цэнтры',
align_right: 'Па правым краі',
align_justify: 'Выраўнаваць тэкст па шырыні',
horizontalrule: 'Гарызантальная лінейка',
fullscreen: 'Ва ўвесь экран',
deleted: 'Закрэслены',
anchor: 'Anchor'
}; | JavaScript |
var RELANG = {};
RELANG['lv'] = {
html: 'HTML кods',
video: 'Video',
image: 'Attēls',
table: 'Tabula',
link: 'Saite',
link_insert: 'Iekļaut saiti ...',
unlink: 'Noņemt saiti',
formatting: 'Stili',
paragraph: 'Vienkāršs teksts',
quote: 'Citāts',
code: 'Kods',
header1: 'Virsraksts 1',
header2: 'Virsraksts 2',
header3: 'Virsraksts 3',
header4: 'Virsraksts 4',
bold: 'Pustrekns',
italic: 'Slīps',
fontcolor: 'Teksta krāsa',
backcolor: 'Fona krāsa',
unorderedlist: 'Parasts saraksts',
orderedlist: 'Numurēts saraksts',
outdent: 'Samazināt atkāpi',
indent: 'Palielināt atkāpi',
cancel: 'Atcelt',
insert: 'Iespraust',
save: 'Saglabāt',
_delete: 'Dzēst',
insert_table: 'Iespraust tabulu',
insert_row_above: 'Pievienot rindu no augšas',
insert_row_below: 'Pievienot rindu no apakšas',
insert_column_left: 'Pievienot stabiņu no kreisās puses',
insert_column_right: 'Pievienot stabiņu no labās puses',
delete_column: 'Dzēst stabiņu',
delete_row: 'Dzēst rindu',
delete_table: 'Dzēst tabulu',
rows: 'Rindas',
columns: 'Stabiņi',
add_head: 'Pievienot virsrakstu',
delete_head: 'Dzēst virsrakstu',
title: 'Uzvedne',
image_position: 'Аttēla apliece',
none: 'nav',
left: 'pa kreisi',
right: 'pa labi',
image_web_link: 'vai saite uz attēlu',
text: 'Teksts',
mailto: 'E-pasts',
web: 'URL',
video_html_code: 'Videoklipu kods',
file: 'Fails',
upload: 'Augšupielāde',
download: 'Lejupielāde',
choose: 'Izvēlieties',
or_choose: 'Vai izvēlieties',
drop_file_here: 'Vilkt failu uz šejieni',
align_left: 'Izlīdzināt pa labi',
align_center: 'Izlīdzināt pa kreisi',
align_right: 'Izlīdzināt pret centru',
align_justify: 'Izlīdzināt malas',
horizontalrule: 'Horizontāla līnija',
fullscreen: 'Pa visu ekrānu',
anchor: 'Anchor'
}; | JavaScript |
var RELANG = {};
RELANG['it'] = {
html: 'HTML',
video: 'Video',
image: 'Immagine',
table: 'Tabella',
link: 'Collegamento',
link_insert: 'Inserisci un collegamento ...',
unlink: 'Rimuovi il collegamento',
formatting: 'Stili',
paragraph: 'Paragrafo',
quote: 'Quote',
code: 'Codice',
header1: 'H1',
header2: 'H2',
header3: 'H3',
header4: 'H4',
bold: 'Grassetto',
italic: 'Corsivo',
superscript: 'Superscript',
strikethrough: 'Strikethrough',
fontcolor: 'Colore del font',
backcolor: 'Colore di sfondo',
unorderedlist: 'Elenco puntato',
orderedlist: 'Elenco numerato',
outdent: 'Outdent',
indent: 'Indent',
cancel: 'Cancella',
insert: 'Inserisci',
save: 'Salva',
_delete: 'rimuovi',
insert_table: 'Inserisci tabella',
insert_row_above: 'Inserisci una riga sopra',
insert_row_below: 'Inserisci una riga sotto',
insert_column_left: 'Aggiungi una colonna a sinistra',
insert_column_right: 'Aggiungi una colonna a destra',
delete_column: 'Cancella colonna',
delete_row: 'Cancella riga',
delete_table: 'Cancella tabella',
rows: 'Righe',
columns: 'Colonne',
add_head: 'Aggiungi head',
delete_head: 'Cancella head',
title: 'Titolo',
image_position: 'Posizione',
none: 'Nessun',
left: 'Sinistra',
right: 'Destra',
image_web_link: 'URL immagine',
text: 'Testo',
mailto: 'Email',
web: 'URL',
video_html_code: 'Embed code filmato',
file: 'File',
upload: 'Upload',
download: 'Download',
choose: 'Scegli',
or_choose: 'O Scegli',
drop_file_here: 'Trascina il file qui',
align_left: 'Allinea a sinistra',
align_center: 'Allinea al centro',
align_right: 'Allinea a destra',
align_justify: 'Giustifica',
horizontalrule: 'Orizzonatale',
fullscreen: 'Schermo intero',
deleted: 'Cancellato',
anchor: 'Ancora'
};
| JavaScript |
var RELANG = {};
RELANG['sk'] = {
html: 'HTML',
video: 'Video',
image: 'Obrázok',
table: 'Tabulka',
link: 'Odkaz',
link_insert: 'Vložiť odkaz ...',
unlink: 'Odstrániť odkaz',
formatting: 'Štýl',
paragraph: 'Odstavec',
quote: 'Citácia',
code: 'Kód',
header1: 'Nadpis 1',
header2: 'Nadpis 2',
header3: 'Nadpis 3',
header4: 'Nadpis 4',
bold: 'Tučné',
italic: 'Kurzíva',
fontcolor: 'Farba písma',
backcolor: 'Farba pozadia',
unorderedlist: 'Zoznam s odrážkami',
orderedlist: 'Číslovaný zoznam',
outdent: 'Zmenšiť odsadenie',
indent: 'Zväčšiť odsadenie',
cancel: 'Zrušiť',
insert: 'Vložiť',
save: 'Uložiť',
_delete: 'Smazať',
insert_table: 'Vložiť tabulku',
insert_row_above: 'Pridať riadok hore',
insert_row_below: 'Pridať riadok dole',
insert_column_left: 'Pridať stĺpec vľavo',
insert_column_right: 'Pridať stľpec vpravo',
delete_column: 'Zmazať stľpec',
delete_row: 'Zmazať riadok',
delete_table: 'Zmazať tabulku',
rows: 'Riadky',
columns: 'Stľpce',
add_head: 'Pridať záhlavie',
delete_head: 'Zmazať záhlavie',
title: 'Titulok',
image_position: 'Pozícia',
none: 'žiadny',
left: 'vľavo',
right: 'vpravo',
image_web_link: 'Odkaz na obrázok',
text: 'Text',
mailto: 'Email',
web: 'URL',
video_html_code: 'Kód pre vloženie videa na stránku',
file: 'Súbor',
upload: 'Nahrát',
download: 'Stiahnúť',
choose: 'Vybrať',
or_choose: 'alebo',
drop_file_here: 'Pretiahnite súbor sem',
align_left: 'Zarovnať vľavo',
align_center: 'Zarovnať na stred',
align_right: 'Zarovnať vpravo',
align_justify: 'Zarovnať do bloku',
horizontalrule: 'Vodorovná čiara',
fullscreen: 'Celá obrazovka',
deleted: 'Prečiarknuté',
anchor: 'Záložka'
};
| JavaScript |
var RELANG = {};
RELANG['nl'] = {
html: 'HTML',
video: 'Video',
image: 'Afbeelding',
table: 'Tabel',
link: 'Link',
link_insert: 'Link invoegen...',
unlink: 'Link ontkoppelen',
formatting: 'Stijlen',
paragraph: 'Paragraaf',
quote: 'Citaat',
code: 'Code',
header1: 'Kop 1',
header2: 'Kop 2',
header3: 'Kop 3',
header4: 'Kop 4',
bold: 'Vet',
italic: 'Cursief',
fontcolor: 'Tekstkleur',
backcolor: 'Achtergrondkleur',
unorderedlist: 'Ongeordende lijst',
orderedlist: 'Geordende lijst',
outdent: 'Uitspringen',
indent: 'Inspringen',
redo: 'Opnieuw maken',
undo: 'Ongedaan maken',
cut: 'Knippen',
cancel: 'Annuleren',
insert: 'Invoegen',
save: 'Opslaan',
_delete: 'Verwijderen',
insert_table: 'Tabel invoegen',
insert_row_above: 'Rij hierboven invoegen',
insert_row_below: 'Rij hieronder invoegen',
insert_column_left: 'Kolom links toevoegen',
insert_column_right: 'Kolom rechts toevoegen',
delete_column: 'Verwijder kolom',
delete_row: 'Verwijder rij',
delete_table: 'Verwijder tabel',
rows: 'Rijen',
columns: 'Kolommen',
add_head: 'Titel toevoegen',
delete_head: 'Titel verwijderen',
title: 'Titel',
image_position: 'Positie',
none: 'geen',
left: 'links',
right: 'rechts',
image_web_link: 'Afbeelding link',
text: 'Tekst',
mailto: 'Email',
web: 'URL',
video_html_code: 'Video embed code',
file: 'Bestand',
upload: 'Uploaden',
download: 'Downloaden',
choose: 'Kies',
or_choose: 'Of kies',
drop_file_here: 'Sleep bestand hier',
align_left: 'Links uitlijnen',
align_center: 'Centreren',
align_right: 'Rechts uitlijnen',
align_justify: 'Uitvullen',
horizontalrule: 'Horizontale lijn',
fullscreen: 'Volledig scherm',
deleted: 'Verwijderd',
anchor: 'Anker'
};
| JavaScript |
var RELANG = {};
RELANG['es'] = {
html: 'HTML',
video: 'Video',
image: 'Imagen',
table: 'Tabla',
link: 'Enlace',
link_insert: 'Insertar enlace ...',
unlink: 'Desenlazar',
formatting: 'Estilos',
paragraph: 'Párrafo',
quote: 'Comillas',
code: 'Código',
header1: 'Cabecera 1',
header2: 'Cabecera 2',
header3: 'Cabecera 3',
header4: 'Cabecera 4',
bold: 'Negrita',
italic: 'Itálica',
fontcolor: 'Color fuente',
backcolor: 'Color fondo',
unorderedlist: 'Lista sin orden',
orderedlist: 'Lista ordenada',
outdent: 'Disminuir sangrado',
indent: 'Sangrar',
cancel: 'Cancelar',
insert: 'Añadir',
save: 'Guardar',
_delete: 'Borrar',
insert_table: 'Añadir tabla',
insert_row_above: 'Añadir fila arriba',
insert_row_below: 'Añadir fila debajo',
insert_column_left: 'Añadir columna a la izquierda',
insert_column_right: 'Añadir column a la derecha',
delete_column: 'Borrar columna',
delete_row: 'Borrar fila',
delete_table: 'Borrar tabla',
rows: 'Filas',
columns: 'Columnas',
add_head: 'Añadir cabecera',
delete_head: 'Borrar cabecera',
title: 'Título',
image_position: 'Posición',
none: 'ninguna',
left: 'izquierda',
right: 'derecha',
image_web_link: 'Enlace de imagen web',
text: 'Texto',
mailto: 'Email',
web: 'URL',
video_html_code: 'Código embebido del video',
file: 'Fichero',
upload: 'Cargar',
download: 'Descargar',
choose: 'Seleccionar',
or_choose: 'O seleccionar',
drop_file_here: 'Soltar el fichero aquí',
align_left: 'Alinear a la izquierda',
align_center: 'Alinear al centro',
align_right: 'Alinear a la derecha',
align_justify: 'Justificar',
horizontalrule: 'Trazo horizontal',
fullscreen: 'Pantalla completa',
deleted: 'Borrado',
anchor: 'Anclaje o anchor'
}; | JavaScript |
var RELANG = {};
RELANG['sq'] = {
html: 'HTML',
video: 'Video',
image: 'Fotografi',
table: 'Tabelë',
link: 'Link',
link_insert: 'Lidh linq ...',
unlink: 'Hiq linkun',
formatting: 'Stilet',
paragraph: 'Paragraf',
quote: 'Kuotë',
code: 'Kod',
header1: 'Header 1',
header2: 'Header 2',
header3: 'Header 3',
header4: 'Header 4',
bold: 'Te trasha / Bold',
italic: 'Kursive / Italic',
fontcolor: 'Ngjyra e shkronjave',
backcolor: 'Ngjyra e mbrapavisë së shkronjave',
unorderedlist: 'Liste pa renditje',
orderedlist: 'Liste me renditje',
outdent: 'Outdent',
indent: 'Indent',
redo: 'Ribëj',
undo: 'Zhbëj',
cut: 'Cut',
cancel: 'Anulo',
insert: 'Insert',
save: 'Ruaje',
_delete: 'Fshije',
insert_table: 'Shto tabelë',
insert_row_above: 'Shto rresht sipër',
insert_row_below: 'Shto rresht përfundi',
insert_column_left: 'Shto kolonë majtas',
insert_column_right: 'Shto kolonë djathtas',
delete_column: 'Fshije kolonën',
delete_row: 'Fshije rreshtin',
delete_table: 'Fshije tabelën',
rows: 'Rreshta',
columns: 'Kolona',
add_head: 'Shto titujt e tabelës',
delete_head: 'Fshije titujt e tabelës',
title: 'Titulli',
image_position: 'Pozita',
none: 'Normale',
left: 'Majtas',
right: 'Djathtas',
image_web_link: 'Linku i fotografisë në internet',
text: 'Teksti',
mailto: 'Email',
web: 'URL',
video_html_code: 'Video embed code',
file: 'Fajll',
upload: 'Ngarko',
download: 'Shkarko',
choose: 'Zgjedh',
or_choose: 'Ose zgjedh',
drop_file_here: 'Gjuaje fajllin këtu',
align_left: 'Rreshtoje majtas',
align_center: 'Rreshtoje në mes',
align_right: 'Rreshtoje djathtas',
align_justify: 'Rreshtoje të gjithin njejt',
horizontalrule: 'Vizë horizontale',
fullscreen: 'Pamje e plotë',
deleted: 'E fshirë',
anchor: 'Anchor'
};
| JavaScript |
var RELANG = {};
RELANG['ua'] = {
html: 'Код',
video: 'Відео',
image: 'Зображення',
table: 'Таблиця',
link: 'Посилання',
link_insert: 'Вставити посилання ...',
unlink: 'Видалити посилання',
formatting: 'Стилі',
paragraph: 'Звичайний текст',
quote: 'Цитата',
code: 'Код',
header1: 'Заголовок 1',
header2: 'Заголовок 2',
header3: 'Заголовок 3',
header4: 'Заголовок 4',
bold: 'Жирний',
italic: 'Похилий',
fontcolor: 'Колір тексту',
backcolor: 'Заливка тексту',
unorderedlist: 'Звичайний список',
orderedlist: 'Нумерований список',
outdent: 'Зменшити відступ',
indent: 'Збільшити відступ',
cancel: 'Скасувати',
insert: 'Вставити',
save: 'Зберегти',
_delete: 'Видалити',
insert_table: 'Вставити таблицю',
insert_row_above: 'Додати рядок зверху',
insert_row_below: 'Додати рядок знизу',
insert_column_left: 'Додати стовпець ліворуч',
insert_column_right: 'Додати стовпець праворуч',
delete_column: 'Видалити стовпець',
delete_row: 'Видалити рядок',
delete_table: 'Видалити таблицю',
rows: 'Рядки',
columns: 'Стовпці',
add_head: 'Додати заголовок',
delete_head: 'Видалити заголовок',
title: 'Підказка',
image_view: 'Завантажити зображення',
image_position: 'Обтікання текстом',
none: 'ні',
left: 'ліворуч',
right: 'праворуч',
image_web_link: 'Посилання на зображення',
text: 'Текст',
mailto: 'Ел. пошта',
web: 'URL',
video_html_code: 'Код відео ролика',
file: 'Файл',
upload: 'Завантажити',
download: 'Завантажити',
choose: 'Вибрати',
or_choose: 'Або виберіть',
drop_file_here: 'Перетягніть файл сюди',
align_left: 'По лівому краю',
align_center: 'По центру',
align_right: 'По правому краю',
align_justify: 'Вирівняти текст по ширині',
horizontalrule: 'Горизонтальная лінійка',
fullscreen: 'На весь екран',
deleted: 'Закреслений',
anchor: 'Anchor'
}; | JavaScript |
var RELANG = {};
RELANG['pt_br'] = {
html: 'Ver HTML',
video: 'Vídeo',
image: 'Imagem',
table: 'Tabela',
link: 'Link',
link_insert: 'Inserir link...',
unlink: 'Remover link',
formatting: 'Estilos',
paragraph: 'Parágrafo',
quote: 'Citação',
code: 'Código',
header1: 'Título 1',
header2: 'Título 2',
header3: 'Título 3',
header4: 'Título 4',
bold: 'Negrito',
italic: 'Itálico',
fontcolor: 'Cor da fonte',
backcolor: 'Cor do fundo',
unorderedlist: 'Lista não ordenada',
orderedlist: 'Lista ordenada',
outdent: 'Remover identação',
indent: 'Identar',
cancel: 'Cancelar',
insert: 'Inserir',
save: 'Salvar',
_delete: 'Remover',
insert_table: 'Inserir tabela',
add_cell: 'Adicionar coluna',
delete_cell: 'Remover coluna',
add_row: 'Adicionar linha',
delete_row: 'Remover linha',
thead: 'Cabeçalho',
delete_table: 'Remover tabela',
insert_row_above: 'Adicionar linha acima',
insert_row_below: 'Adicionar linha abaixo',
insert_column_left: 'Adicionar coluna à esquerda',
insert_column_right: 'Adicionar coluna da direita',
delete_column: 'Remover Coluna',
delete_row: 'Remover linha',
delete_table: 'Remover tabela',
rows: 'Linhas',
columns: 'Colunas',
add_head: 'Adicionar cabeçalho',
delete_head: 'Remover cabeçalho',
title: 'Título',
image_position: 'Posição',
none: 'nenhum',
left: 'esquerda',
right: 'direita',
image_web_link: 'link para uma imagem',
text: 'Texto',
mailto: 'Email',
web: 'URL',
video_html_code: 'Video embed code',
file: 'Arquivo',
upload: 'Upload',
download: 'Download',
choose: 'Escolha',
or_choose: 'Ou escolha',
drop_file_here: 'Arraste um arquivo até aqui',
align_left: 'Alinhar a esquerda',
align_center: 'Centralizar',
align_right: 'Alinhar a direita',
align_justify: 'Justificar',
horizontalrule: 'Linha horizontal',
fullscreen: 'Tela cheia',
deleted: 'Removido',
anchor: 'Anchor'
};
| JavaScript |
var RELANG = {};
RELANG['pl'] = {
html: 'Źródło',
video: 'Wideo',
image: 'Obrazek',
table: 'Tabela',
link: 'Link',
link_insert: 'Wstaw link ...',
unlink: 'Usuń link',
formatting: 'Style',
paragraph: 'Zwykły tekst',
quote: 'Cytat',
code: 'Kod źródłowy',
header1: 'Nagłówek 1',
header2: 'Nagłówek 2',
header3: 'Nagłówek 3',
header4: 'Nagłówek 4',
bold: 'Pogrubiony',
italic: 'Pochylony',
fontcolor: 'Kolor tekstu',
backcolor: 'Kolor tła',
unorderedlist: 'Wypunktowanie',
orderedlist: 'Numeracja',
outdent: 'Zwiększ wcięcie',
indent: 'Zmniejsz wcięcie',
cancel: 'Anuluj',
insert: 'Wstaw',
save: 'Zachowaj',
_delete: 'Usuń',
insert_table: 'Wstaw tabele',
insert_row_above: 'Dodaj wiersz na górze',
insert_row_below: 'Dodaj wiersz na dole',
insert_column_left: 'Dodaj kolumnę po lewej',
insert_column_right: 'Dodaj kolumnę po prawej',
delete_column: 'Usuń kolumnę',
delete_row: 'Usuń wiersz',
delete_table: 'Usuń tabele',
rows: 'Wiersze',
columns: 'Kolumny',
add_head: 'Dodaj nagłówek',
delete_head: 'Usuń nagłówek',
title: 'Wskazówka',
image_position: 'Obramowanie',
none: 'nie ma',
left: 'od lewej',
right: 'od prawej',
image_web_link: 'albo link do obrazku',
text: 'Tekst',
mailto: 'Poczta e-mail',
web: 'URL',
video_html_code: 'Kod źródłowy pliku wideo',
file: 'Plik',
upload: 'Wgraj na serwer',
download: 'Pobierz',
choose: 'Choose',
or_choose: 'Or choose',
drop_file_here: 'Drop file here',
align_left: 'Align left',
align_center: 'Align center',
align_right: 'Align right',
align_justify: 'Justify',
horizontalrule: 'Horizontal rule',
fullscreen: 'Fullscreen',
deleted: 'Deleted',
anchor: 'Anchor'
}; | JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.