code
stringlengths 1
2.08M
| language
stringclasses 1
value |
|---|---|
/*! SWFObject v2.2 <http://code.google.com/p/swfobject/>
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject = function() {
var UNDEF = "undefined",
OBJECT = "object",
SHOCKWAVE_FLASH = "Shockwave Flash",
SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
FLASH_MIME_TYPE = "application/x-shockwave-flash",
EXPRESS_INSTALL_ID = "SWFObjectExprInst",
ON_READY_STATE_CHANGE = "onreadystatechange",
win = window,
doc = document,
nav = navigator,
plugin = false,
domLoadFnArr = [main],
regObjArr = [],
objIdArr = [],
listenersArr = [],
storedAltContent,
storedAltContentId,
storedCallbackFn,
storedCallbackObj,
isDomLoaded = false,
isExpressInstallActive = false,
dynamicStylesheet,
dynamicStylesheetMedia,
autoHideShow = true,
/* Centralized function for browser feature detection
- User agent string detection is only used when no good alternative is possible
- Is executed directly for optimal performance
*/
ua = function() {
var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
u = nav.userAgent.toLowerCase(),
p = nav.platform.toLowerCase(),
windows = p ? /win/.test(p) : /win/.test(u),
mac = p ? /mac/.test(p) : /mac/.test(u),
webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html
playerVersion = [0,0,0],
d = null;
if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
d = nav.plugins[SHOCKWAVE_FLASH].description;
if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
plugin = true;
ie = false; // cascaded feature detection for Internet Explorer
d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0;
}
}
else if (typeof win.ActiveXObject != UNDEF) {
try {
var a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
if (a) { // a will return null when ActiveX is disabled
d = a.GetVariable("$version");
if (d) {
ie = true; // cascaded feature detection for Internet Explorer
d = d.split(" ")[1].split(",");
playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
}
catch(e) {}
}
return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac };
}(),
/* Cross-browser onDomLoad
- Will fire an event as soon as the DOM of a web page is loaded
- Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/
- Regular onload serves as fallback
*/
onDomLoad = function() {
if (!ua.w3) { return; }
if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically
callDomLoadFunctions();
}
if (!isDomLoaded) {
if (typeof doc.addEventListener != UNDEF) {
doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false);
}
if (ua.ie && ua.win) {
doc.attachEvent(ON_READY_STATE_CHANGE, function() {
if (doc.readyState == "complete") {
doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee);
callDomLoadFunctions();
}
});
if (win == top) { // if not inside an iframe
(function(){
if (isDomLoaded) { return; }
try {
doc.documentElement.doScroll("left");
}
catch(e) {
setTimeout(arguments.callee, 0);
return;
}
callDomLoadFunctions();
})();
}
}
if (ua.wk) {
(function(){
if (isDomLoaded) { return; }
if (!/loaded|complete/.test(doc.readyState)) {
setTimeout(arguments.callee, 0);
return;
}
callDomLoadFunctions();
})();
}
addLoadEvent(callDomLoadFunctions);
}
}();
function callDomLoadFunctions() {
if (isDomLoaded) { return; }
try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early
var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span"));
t.parentNode.removeChild(t);
}
catch (e) { return; }
isDomLoaded = true;
var dl = domLoadFnArr.length;
for (var i = 0; i < dl; i++) {
domLoadFnArr[i]();
}
}
function addDomLoadEvent(fn) {
if (isDomLoaded) {
fn();
}
else {
domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
}
}
/* Cross-browser onload
- Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
- Will fire an event as soon as a web page including all of its assets are loaded
*/
function addLoadEvent(fn) {
if (typeof win.addEventListener != UNDEF) {
win.addEventListener("load", fn, false);
}
else if (typeof doc.addEventListener != UNDEF) {
doc.addEventListener("load", fn, false);
}
else if (typeof win.attachEvent != UNDEF) {
addListener(win, "onload", fn);
}
else if (typeof win.onload == "function") {
var fnOld = win.onload;
win.onload = function() {
fnOld();
fn();
};
}
else {
win.onload = fn;
}
}
/* Main function
- Will preferably execute onDomLoad, otherwise onload (as a fallback)
*/
function main() {
if (plugin) {
testPlayerVersion();
}
else {
matchVersions();
}
}
/* Detect the Flash Player version for non-Internet Explorer browsers
- Detecting the plug-in version via the object element is more precise than using the plugins collection item's description:
a. Both release and build numbers can be detected
b. Avoid wrong descriptions by corrupt installers provided by Adobe
c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports
- Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available
*/
function testPlayerVersion() {
var b = doc.getElementsByTagName("body")[0];
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
var t = b.appendChild(o);
if (t) {
var counter = 0;
(function(){
if (typeof t.GetVariable != UNDEF) {
var d = t.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
else if (counter < 10) {
counter++;
setTimeout(arguments.callee, 10);
return;
}
b.removeChild(o);
t = null;
matchVersions();
})();
}
else {
matchVersions();
}
}
/* Perform Flash Player and SWF version matching; static publishing only
*/
function matchVersions() {
var rl = regObjArr.length;
if (rl > 0) {
for (var i = 0; i < rl; i++) { // for each registered object element
var id = regObjArr[i].id;
var cb = regObjArr[i].callbackFn;
var cbObj = {success:false, id:id};
if (ua.pv[0] > 0) {
var obj = getElementById(id);
if (obj) {
if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match!
setVisibility(id, true);
if (cb) {
cbObj.success = true;
cbObj.ref = getObjectById(id);
cb(cbObj);
}
}
else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported
var att = {};
att.data = regObjArr[i].expressInstall;
att.width = obj.getAttribute("width") || "0";
att.height = obj.getAttribute("height") || "0";
if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); }
if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); }
// parse HTML object param element's name-value pairs
var par = {};
var p = obj.getElementsByTagName("param");
var pl = p.length;
for (var j = 0; j < pl; j++) {
if (p[j].getAttribute("name").toLowerCase() != "movie") {
par[p[j].getAttribute("name")] = p[j].getAttribute("value");
}
}
showExpressInstall(att, par, id, cb);
}
else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF
displayAltContent(obj);
if (cb) { cb(cbObj); }
}
}
}
else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content)
setVisibility(id, true);
if (cb) {
var o = getObjectById(id); // test whether there is an HTML object element or not
if (o && typeof o.SetVariable != UNDEF) {
cbObj.success = true;
cbObj.ref = o;
}
cb(cbObj);
}
}
}
}
}
function getObjectById(objectIdStr) {
var r = null;
var o = getElementById(objectIdStr);
if (o && o.nodeName == "OBJECT") {
if (typeof o.SetVariable != UNDEF) {
r = o;
}
else {
var n = o.getElementsByTagName(OBJECT)[0];
if (n) {
r = n;
}
}
}
return r;
}
/* Requirements for Adobe Express Install
- only one instance can be active at a time
- fp 6.0.65 or higher
- Win/Mac OS only
- no Webkit engines older than version 312
*/
function canExpressInstall() {
return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312);
}
/* Show the Adobe Express Install dialog
- Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
*/
function showExpressInstall(att, par, replaceElemIdStr, callbackFn) {
isExpressInstallActive = true;
storedCallbackFn = callbackFn || null;
storedCallbackObj = {success:false, id:replaceElemIdStr};
var obj = getElementById(replaceElemIdStr);
if (obj) {
if (obj.nodeName == "OBJECT") { // static publishing
storedAltContent = abstractAltContent(obj);
storedAltContentId = null;
}
else { // dynamic publishing
storedAltContent = obj;
storedAltContentId = replaceElemIdStr;
}
att.id = EXPRESS_INSTALL_ID;
if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; }
if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; }
doc.title = doc.title.slice(0, 47) + " - Flash Player Installation";
var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn",
fv = "MMredirectURL=" + encodeURI(window.location).toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title;
if (typeof par.flashvars != UNDEF) {
par.flashvars += "&" + fv;
}
else {
par.flashvars = fv;
}
// IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
// because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
if (ua.ie && ua.win && obj.readyState != 4) {
var newObj = createElement("div");
replaceElemIdStr += "SWFObjectNew";
newObj.setAttribute("id", replaceElemIdStr);
obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
obj.parentNode.removeChild(obj);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
createSWF(att, par, replaceElemIdStr);
}
}
/* Functions to abstract and display alternative content
*/
function displayAltContent(obj) {
if (ua.ie && ua.win && obj.readyState != 4) {
// IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
// because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
var el = createElement("div");
obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content
el.parentNode.replaceChild(abstractAltContent(obj), el);
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
obj.parentNode.removeChild(obj);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
else {
obj.parentNode.replaceChild(abstractAltContent(obj), obj);
}
}
function abstractAltContent(obj) {
var ac = createElement("div");
if (ua.win && ua.ie) {
ac.innerHTML = obj.innerHTML;
}
else {
var nestedObj = obj.getElementsByTagName(OBJECT)[0];
if (nestedObj) {
var c = nestedObj.childNodes;
if (c) {
var cl = c.length;
for (var i = 0; i < cl; i++) {
if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) {
ac.appendChild(c[i].cloneNode(true));
}
}
}
}
}
return ac;
}
/* Cross-browser dynamic SWF creation
*/
function createSWF(attObj, parObj, id) {
var r, el = getElementById(id);
if (ua.wk && ua.wk < 312) { return r; }
if (el) {
if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
attObj.id = id;
}
if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML
var att = "";
for (var i in attObj) {
if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries
if (i.toLowerCase() == "data") {
parObj.movie = attObj[i];
}
else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
att += ' class="' + attObj[i] + '"';
}
else if (i.toLowerCase() != "classid") {
att += ' ' + i + '="' + attObj[i] + '"';
}
}
}
var par = "";
for (var j in parObj) {
if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries
par += '<param name="' + j + '" value="' + parObj[j] + '" />';
}
}
el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only)
r = getElementById(attObj.id);
}
else { // well-behaving browsers
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
for (var m in attObj) {
if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries
if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
o.setAttribute("class", attObj[m]);
}
else if (m.toLowerCase() != "classid") { // filter out IE specific attribute
o.setAttribute(m, attObj[m]);
}
}
}
for (var n in parObj) {
if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element
createObjParam(o, n, parObj[n]);
}
}
el.parentNode.replaceChild(o, el);
r = o;
}
}
return r;
}
function createObjParam(el, pName, pValue) {
var p = createElement("param");
p.setAttribute("name", pName);
p.setAttribute("value", pValue);
el.appendChild(p);
}
/* Cross-browser SWF removal
- Especially needed to safely and completely remove a SWF in Internet Explorer
*/
function removeSWF(id) {
var obj = getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (ua.ie && ua.win) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
removeObjectInIE(id);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
else {
obj.parentNode.removeChild(obj);
}
}
}
function removeObjectInIE(id) {
var obj = getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
/* Functions to optimize JavaScript compression
*/
function getElementById(id) {
var el = null;
try {
el = doc.getElementById(id);
}
catch (e) {}
return el;
}
function createElement(el) {
return doc.createElement(el);
}
/* Updated attachEvent function for Internet Explorer
- Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
*/
function addListener(target, eventType, fn) {
target.attachEvent(eventType, fn);
listenersArr[listenersArr.length] = [target, eventType, fn];
}
/* Flash Player and SWF content version matching
*/
function hasPlayerVersion(rv) {
var pv = ua.pv, v = rv.split(".");
v[0] = parseInt(v[0], 10);
v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
v[2] = parseInt(v[2], 10) || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
}
/* Cross-browser dynamic CSS creation
- Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
*/
function createCSS(sel, decl, media, newStyle) {
if (ua.ie && ua.mac) { return; }
var h = doc.getElementsByTagName("head")[0];
if (!h) { return; } // to also support badly authored HTML pages that lack a head element
var m = (media && typeof media == "string") ? media : "screen";
if (newStyle) {
dynamicStylesheet = null;
dynamicStylesheetMedia = null;
}
if (!dynamicStylesheet || dynamicStylesheetMedia != m) {
// create dynamic stylesheet + get a global reference to it
var s = createElement("style");
s.setAttribute("type", "text/css");
s.setAttribute("media", m);
dynamicStylesheet = h.appendChild(s);
if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) {
dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1];
}
dynamicStylesheetMedia = m;
}
// add style rule
if (ua.ie && ua.win) {
if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) {
dynamicStylesheet.addRule(sel, decl);
}
}
else {
if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) {
dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
}
}
}
function setVisibility(id, isVisible) {
if (!autoHideShow) { return; }
var v = isVisible ? "visible" : "hidden";
if (isDomLoaded && getElementById(id)) {
getElementById(id).style.visibility = v;
}
else {
createCSS("#" + id, "visibility:" + v);
}
}
/* Filter to avoid XSS attacks
*/
function urlEncodeIfNecessary(s) {
var regex = /[\\\"<>\.;]/;
var hasBadChars = regex.exec(s) != null;
return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s;
}
/* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
*/
var cleanup = function() {
if (ua.ie && ua.win) {
window.attachEvent("onunload", function() {
// remove listeners to avoid memory leaks
var ll = listenersArr.length;
for (var i = 0; i < ll; i++) {
listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
}
// cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
var il = objIdArr.length;
for (var j = 0; j < il; j++) {
removeSWF(objIdArr[j]);
}
// cleanup library's main closures to avoid memory leaks
for (var k in ua) {
ua[k] = null;
}
ua = null;
for (var l in swfobject) {
swfobject[l] = null;
}
swfobject = null;
});
}
}();
return {
/* Public API
- Reference: http://code.google.com/p/swfobject/wiki/documentation
*/
registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) {
if (ua.w3 && objectIdStr && swfVersionStr) {
var regObj = {};
regObj.id = objectIdStr;
regObj.swfVersion = swfVersionStr;
regObj.expressInstall = xiSwfUrlStr;
regObj.callbackFn = callbackFn;
regObjArr[regObjArr.length] = regObj;
setVisibility(objectIdStr, false);
}
else if (callbackFn) {
callbackFn({success:false, id:objectIdStr});
}
},
getObjectById: function(objectIdStr) {
if (ua.w3) {
return getObjectById(objectIdStr);
}
},
embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) {
var callbackObj = {success:false, id:replaceElemIdStr};
if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) {
setVisibility(replaceElemIdStr, false);
addDomLoadEvent(function() {
widthStr += ""; // auto-convert to string
heightStr += "";
var att = {};
if (attObj && typeof attObj === OBJECT) {
for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs
att[i] = attObj[i];
}
}
att.data = swfUrlStr;
att.width = widthStr;
att.height = heightStr;
var par = {};
if (parObj && typeof parObj === OBJECT) {
for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs
par[j] = parObj[j];
}
}
if (flashvarsObj && typeof flashvarsObj === OBJECT) {
for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs
if (typeof par.flashvars != UNDEF) {
par.flashvars += "&" + k + "=" + flashvarsObj[k];
}
else {
par.flashvars = k + "=" + flashvarsObj[k];
}
}
}
if (hasPlayerVersion(swfVersionStr)) { // create SWF
var obj = createSWF(att, par, replaceElemIdStr);
if (att.id == replaceElemIdStr) {
setVisibility(replaceElemIdStr, true);
}
callbackObj.success = true;
callbackObj.ref = obj;
}
else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install
att.data = xiSwfUrlStr;
showExpressInstall(att, par, replaceElemIdStr, callbackFn);
return;
}
else { // show alternative content
setVisibility(replaceElemIdStr, true);
}
if (callbackFn) { callbackFn(callbackObj); }
});
}
else if (callbackFn) { callbackFn(callbackObj); }
},
switchOffAutoHideShow: function() {
autoHideShow = false;
},
ua: ua,
getFlashPlayerVersion: function() {
return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
},
hasFlashPlayerVersion: hasPlayerVersion,
createSWF: function(attObj, parObj, replaceElemIdStr) {
if (ua.w3) {
return createSWF(attObj, parObj, replaceElemIdStr);
}
else {
return undefined;
}
},
showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) {
if (ua.w3 && canExpressInstall()) {
showExpressInstall(att, par, replaceElemIdStr, callbackFn);
}
},
removeSWF: function(objElemIdStr) {
if (ua.w3) {
removeSWF(objElemIdStr);
}
},
createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) {
if (ua.w3) {
createCSS(selStr, declStr, mediaStr, newStyleBoolean);
}
},
addDomLoadEvent: addDomLoadEvent,
addLoadEvent: addLoadEvent,
getQueryParamValue: function(param) {
var q = doc.location.search || doc.location.hash;
if (q) {
if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark
if (param == null) {
return urlEncodeIfNecessary(q);
}
var pairs = q.split("&");
for (var i = 0; i < pairs.length; i++) {
if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1)));
}
}
}
return "";
},
// For internal usage only
expressInstallCallback: function() {
if (isExpressInstallActive) {
var obj = getElementById(EXPRESS_INSTALL_ID);
if (obj && storedAltContent) {
obj.parentNode.replaceChild(storedAltContent, obj);
if (storedAltContentId) {
setVisibility(storedAltContentId, true);
if (ua.ie && ua.win) { storedAltContent.style.display = "block"; }
}
if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); }
}
isExpressInstallActive = false;
}
}
};
}();
|
JavaScript
|
var userAgent = navigator.userAgent.toLowerCase();
jQuery.browser = {
version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
safari: /webkit/.test( userAgent ),
opera: /opera/.test( userAgent ),
msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};
function thumb_images(uploadid,returnid) {
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#att-status").html().substring(1);
if(in_content=='') return false;
if(!IsImg(in_content)) {
alert('选择的类型必须为图片类型');
return false;
}
if($('#'+returnid+'_preview').attr('src')) {
$('#'+returnid+'_preview').attr('src',in_content);
}
$('#'+returnid).val(in_content);
}
function change_images(uploadid,returnid){
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#att-status").html().substring(1);
var in_filename = d.$("#att-name").html().substring(1);
var str = $('#'+returnid).html();
var contents = in_content.split('|');
var filenames = in_filename.split('|');
$('#'+returnid+'_tips').css('display','none');
if(contents=='') return true;
$.each( contents, function(i, n) {
var ids = parseInt(Math.random() * 10000 + 10*i);
var filename = filenames[i].substr(0,filenames[i].indexOf('.'));
str += "<li id='image"+ids+"'><input type='text' name='"+returnid+"_url[]' value='"+n+"' style='width:310px;' ondblclick='image_priview(this.value);' class='input-text'> <input type='text' name='"+returnid+"_alt[]' value='"+filename+"' style='width:160px;' class='input-text' onfocus=\"if(this.value == this.defaultValue) this.value = ''\" onblur=\"if(this.value.replace(' ','') == '') this.value = this.defaultValue;\"> <a href=\"javascript:remove_div('image"+ids+"')\">移除</a> </li>";
});
$('#'+returnid).html(str);
}
function change_multifile(uploadid,returnid){
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#att-status").html().substring(1);
var in_filename = d.$("#att-name").html().substring(1);
var str = '';
var contents = in_content.split('|');
var filenames = in_filename.split('|');
$('#'+returnid+'_tips').css('display','none');
if(contents=='') return true;
$.each( contents, function(i, n) {
var ids = parseInt(Math.random() * 10000 + 10*i);
var filename = filenames[i].substr(0,filenames[i].indexOf('.'));
str += "<li id='multifile"+ids+"'><input type='text' name='"+returnid+"_fileurl[]' value='"+n+"' style='width:310px;' class='input-text'> <input type='text' name='"+returnid+"_filename[]' value='"+filename+"' style='width:160px;' class='input-text' onfocus=\"if(this.value == this.defaultValue) this.value = ''\" onblur=\"if(this.value.replace(' ','') == '') this.value = this.defaultValue;\"> <a href=\"javascript:remove_div('multifile"+ids+"')\">移除</a> </li>";
});
$('#'+returnid).append(str);
}
function add_multifile(returnid) {
var ids = parseInt(Math.random() * 10000);
var str = "<li id='multifile"+ids+"'><input type='text' name='"+returnid+"_fileurl[]' value='' style='width:310px;' class='input-text'> <input type='text' name='"+returnid+"_filename[]' value='附件说明' style='width:160px;' class='input-text'> <a href=\"javascript:remove_div('multifile"+ids+"')\">移除</a> </li>";
$('#'+returnid).append(str);
}
function set_title_color(color) {
$('#title').css('color',color);
$('#style_color').val(color);
}
//-----------------------
function check_content(obj) {
if($.browser.msie) {
CKEDITOR.instances[obj].insertHtml('');
CKEDITOR.instances[obj].focusManager.hasFocus;
}
top.art.dialog({id:'check_content_id'}).close();
return true;
}
function image_priview(img) {
window.top.art.dialog({title:'图片查看',fixed:true, content:'<img src="'+img+'" />',id:'image_priview',time:5});
}
function remove_div(id) {
$('#'+id).remove();
}
function input_font_bold() {
if($('#title').css('font-weight') == '700' || $('#title').css('font-weight')=='bold') {
$('#title').css('font-weight','normal');
$('#style_font_weight').val('');
} else {
$('#title').css('font-weight','bold');
$('#style_font_weight').val('bold');
}
}
function ruselinkurl() {
if($('#islink').attr('checked')==true) {
$('#linkurl').attr('disabled','');
var oEditor = CKEDITOR.instances.content;
oEditor.insertHtml(' ');
return false;
} else {
$('#linkurl').attr('disabled','true');
}
}
function close_window() {
if($('#title').val() !='') {
art.dialog({content:'内容已经录入,确定离开将不保存数据!', fixed:true,yesText:'我要关闭',noText:'返回保存数据',style:'confirm', id:'bnt4_test'}, function(){
window.close();
}, function(){
});
} else {
window.close();
}
return false;
}
function ChangeInput (objSelect,objInput) {
if (!objInput) return;
var str = objInput.value;
var arr = str.split(",");
for (var i=0; i<arr.length; i++){
if(objSelect.value==arr[i])return;
}
if(objInput.value=='' || objInput.value==0 || objSelect.value==0){
objInput.value=objSelect.value
}else{
objInput.value+=','+objSelect.value
}
}
//移除相关文章
function remove_relation(sid,id) {
var relation_ids = $('#relation').val();
if(relation_ids !='' ) {
$('#'+sid).remove();
var r_arr = relation_ids.split('|');
var newrelation_ids = '';
$.each(r_arr, function(i, n){
if(n!=id) {
if(i==0) {
newrelation_ids = n;
} else {
newrelation_ids = newrelation_ids+'|'+n;
}
}
});
$('#relation').val(newrelation_ids);
}
}
//显示相关文章
function show_relation(modelid,id) {
$.getJSON("?m=content&c=content&a=public_getjson_ids&modelid="+modelid+"&id="+id, function(json){
var newrelation_ids = '';
if(json==null) {
alert('没有添加相关文章');
return false;
}
$.each(json, function(i, n){
newrelation_ids += "<li id='"+n.sid+"'>·<span>"+n.title+"</span><a href='javascript:;' class='close' onclick=\"remove_relation('"+n.sid+"',"+n.id+")\"></a></li>";
});
$('#relation_text').html(newrelation_ids);
});
}
//移除ID
function remove_id(id) {
$('#'+id).remove();
}
function strlen_verify(obj, checklen, maxlen) {
var v = obj.value, charlen = 0, maxlen = !maxlen ? 200 : maxlen, curlen = maxlen, len = strlen(v);
for(var i = 0; i < v.length; i++) {
if(v.charCodeAt(i) < 0 || v.charCodeAt(i) > 255) {
curlen -= charset == 'utf-8' ? 2 : 1;
}
}
if(curlen >= len) {
$('#'+checklen).html(curlen - len);
} else {
obj.value = mb_cutstr(v, maxlen, true);
}
}
function mb_cutstr(str, maxlen, dot) {
var len = 0;
var ret = '';
var dot = !dot ? '...' : '';
maxlen = maxlen - dot.length;
for(var i = 0; i < str.length; i++) {
len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset == 'utf-8' ? 3 : 2) : 1;
if(len > maxlen) {
ret += dot;
break;
}
ret += str.substr(i, 1);
}
return ret;
}
function strlen(str) {
return ($.browser.msie && str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;
}
|
JavaScript
|
$(document).ready(function() {
var q = $("#q").val();
var typeid = $("#typeid").val();
search_history = getcookie('search_history');
if(search_history!=null && search_history!='') {
search_s = search_history.split(",");
var exists = in_array(q+'|'+typeid, search_s);
//不存在
if(exists==-1) {
if(search_s.length > 5) {
search_history = search_history.replace(search_s[0]+',', "");
}
search_history += ','+q+'|'+typeid;
}
//搜索历史
var history_html = '';
for(i=0;i<search_s.length;i++) {
var j = search_s.length - i - 1;
search_s_arr = search_s[j].split("|");
var keyword = search_s_arr[0];
var keywordtypeid = search_s_arr[1];
history_html += '<li><a href="?m=search&c=index&a=init&typeid='+keywordtypeid+'&q='+keyword+'">'+keyword+'</a></li>';
}
$('#history_ul').html(history_html);
} else {
search_history = q+'|'+typeid;
}
setcookie('search_history', search_history, '1000');
function in_array(v, a) {
var i;
for(i = 0; i < a.length; i++) {
if(v === a[i]) {
return i;
}
}
return -1;
}
});
|
JavaScript
|
/*
* Async Treeview 0.1 - Lazy-loading extension for Treeview
*
* http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
*
* Copyright (c) 2007 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id$
*
*/
;(function($) {
function load(settings, root, child, container) {
function createNode(parent) {
var current = $("<li/>").attr("id", this.id || "").attr("class", this.liclass || "").html("<span>" + this.text + "</span>").appendTo(parent);
if (this.classes) {
current.children("span").addClass(this.classes);
}
if (this.expanded) {
current.addClass("open");
}
if (this.hasChildren || this.children && this.children.length) {
var branch = $("<ul/>").appendTo(current);
if (this.hasChildren) {
current.addClass("hasChildren");
createNode.call({
classes: "placeholder",
text: " ",
children:[]
}, branch);
}
if (this.children && this.children.length) {
$.each(this.children, createNode, [branch])
}
}
}
$.ajax($.extend(true, {
url: settings.url,
dataType: "json",
data: {
root: root
},
success: function(response) {
child.empty();
$.each(response, createNode, [child]);
$(container).treeview({add: child});
}
}, settings.ajax));
/*
$.getJSON(settings.url, {root: root}, function(response) {
function createNode(parent) {
var current = $("<li/>").attr("id", this.id || "").html("<span>" + this.text + "</span>").appendTo(parent);
if (this.classes) {
current.children("span").addClass(this.classes);
}
if (this.expanded) {
current.addClass("open");
}
if (this.hasChildren || this.children && this.children.length) {
var branch = $("<ul/>").appendTo(current);
if (this.hasChildren) {
current.addClass("hasChildren");
createNode.call({
classes: "placeholder",
text: " ",
children:[]
}, branch);
}
if (this.children && this.children.length) {
$.each(this.children, createNode, [branch])
}
}
}
child.empty();
$.each(response, createNode, [child]);
$(container).treeview({add: child});
});
*/
}
var proxied = $.fn.treeview;
$.fn.treeview = function(settings) {
if (!settings.url) {
return proxied.apply(this, arguments);
}
var container = this;
if (!container.children().size())
load(settings, "source", this, container);
var userToggle = settings.toggle;
return proxied.call(this, $.extend({}, settings, {
collapsed: true,
toggle: function() {
var $this = $(this);
if ($this.hasClass("hasChildren")) {
var childList = $this.removeClass("hasChildren").find("ul");
load(settings, this.id, childList, container);
}
if (userToggle) {
userToggle.apply(this, arguments);
}
}
}));
};
})(jQuery);
|
JavaScript
|
function confirmurl(url,message) {
url = url+'&pc_hash='+pc_hash;
if(confirm(message)) redirect(url);
}
function redirect(url) {
location.href = url;
}
//滚动条
$(function(){
$(":text").addClass('input-text');
})
/**
* 全选checkbox,注意:标识checkbox id固定为为check_box
* @param string name 列表check名称,如 uid[]
*/
function selectall(name) {
if ($("#check_box").attr("checked")==false) {
$("input[name='"+name+"']").each(function() {
this.checked=false;
});
} else {
$("input[name='"+name+"']").each(function() {
this.checked=true;
});
}
}
function openwinx(url,name,w,h) {
if(!w) w=screen.width-4;
if(!h) h=screen.height-95;
url = url+'&pc_hash='+pc_hash;
window.open(url,name,"top=100,left=400,width=" + w + ",height=" + h + ",toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no");
}
//弹出对话框
function omnipotent(id,linkurl,title,close_type,w,h) {
if(!w) w=700;
if(!h) h=500;
art.dialog({id:id,iframe:linkurl, title:title, width:w, height:h, lock:true},
function(){
if(close_type==1) {
art.dialog({id:id}).close()
} else {
var d = art.dialog({id:id}).data.iframe;
var form = d.document.getElementById('dosubmit');form.click();
}
return false;
},
function(){
art.dialog({id:id}).close()
});void(0);
}
|
JavaScript
|
function open_menu(id,name,container,file,path,title,key, func) {
returnid= id;
returnfile = file;
returnname = name;
returnfunc = func;
var content = '<div class="linkage-menu"><h6><a href="javascript:;" onclick="get_menu_parent(this,0,\''+path+'\', \''+title+'\', \''+key+'\')" class="rt"><<返回主菜单</a><span>'+name+'</span> <a href="javascript:;" onclick="get_menu_parent(this,\'\',\''+path+'\', \''+title+'\', \''+key+'\')" id="parent_'+id+'" parentid="0"><img src="statics/images/icon/old-edit-redo.png" width="16" height="16" alt="返回上一级" /></a></h6><div class="ib-a menu" id="ul_'+id+'">';
for (i=0; i < container.length; i++)
{
content += '<a href="javascript:;" onclick="get_menu_child(\''+container[i][0]+'\',\''+container[i][1]+'\',\''+container[i][2]+'\',\''+path+'\',\''+title+'\',\''+key+'\')">'+container[i][1]+'</a>';
}
content += '</div></div>';
art.dialog({title:name,id:'edit_'+id,content:content,width:'422',height:'200',style:'none_icon ui_content_m'});
}
var level = 0;
function get_menu_child(nodeid,nodename,parentid,path,title,key) {
var content = container = '';
var url = "api.php?op=get_menu&act=ajax_getlist&parentid="+nodeid+"&cachefile="+returnfile+"&path="+path+'&title='+title+'&key='+key;
$.getJSON(url+'&callback=?',function(data){
if(data) {
level = 1;
$.each(data, function(i,data){
container = data.split(',');
content += '<a href="javascript:;" onclick="get_menu_child(\''+container[0]+'\',\''+container[1]+'\',\''+container[2]+'\',\''+path+'\',\''+title+'\',\''+key+'\')">'+container[1]+'</a>';
})
$("#ul_"+returnid).html(content);
get_menu_path(container[2],returnid,path);
$("#parent_"+returnid).attr('parentid',parentid);
} else {
get_menu_val(nodename,nodeid,path);
$("input[name='info["+returnid+"]']").val(nodeid);
//$("#"+returnid).after('<input type="hidden" name="info['+returnid+']" value="'+nodeid+'">');
art.dialog({id:'edit_'+returnid}).close();
}
})
}
function get_menu_parent(obj,parentid,path,title,key) {
var linkageid = parentid ? parentid : $(obj).attr('parentid');
var content = container = '';
var url = "api.php?op=get_menu&act=ajax_getlist&parentid="+linkageid+"&cachefile="+returnfile+"&path="+path+'&title='+title+'&key='+key;
$.getJSON(url+'&callback=?',function(data){
if(data) {
$.each(data, function(i,data){
container = data.split(',');
content += '<a href="javascript:;" onclick="get_menu_child(\''+container[0]+'\',\''+container[1]+'\',\''+container[2]+'\',\''+path+'\',\''+title+'\',\''+key+'\')">'+container[1]+'</a>';
})
get_menu_path(container[2],returnid,path);
$("#parent_"+returnid).attr('parentid',container[4]);
$("#ul_"+returnid).html(content);
} else {
$("#"+returnid).val(nodename);
art.dialog({id:'edit_'+returnid}).close();
}
})
}
function get_menu_path(nodeid,returnid,path) {
var show_path = '';
var url = "api.php?op=get_menu&act=ajax_getpath&parentid="+nodeid+"&keyid="+returnfile+'&path='+path;
$.getJSON(url+'&callback=?',function(data){
if(data) {
$.each(data, function(i,data){
if (data) {
show_path += data+" > ";
} else {
show_path += returnname;
}
})
$("#parent_"+returnid).siblings('span').html(show_path);
}
})
}
function get_menu_val(nodename,nodeid,cachepath) {
var path = $("#parent_"+returnid).siblings('span').html();
if(level==0) $("#"+returnid).html(nodename);
else $("#"+returnid).html(path+nodename);
var url = "api.php?op=get_menu&act=ajax_gettopparent&id="+nodeid+"&keyid="+returnfile+'&path='+cachepath;
$.getJSON(url+'&callback=?',function(data){
if(data) {
}
if (returnfunc) {
obj=new Object();
obj.value = data;
get_additional(obj);
}
})
level = 0;
}
|
JavaScript
|
(function($){
$.fn.mlnColsel=function(data,setting){
var dataObj={"Items":[
{"name":"mlnColsel","topid":"-1","colid":"-1","value":"-1","fun":function(){alert("undefined!");}}
]};
var settingObj={
title:"请选择",
value:"-1",
width:100
};
settingObj=$.extend(settingObj,setting);
dataObj=$.extend(dataObj,data);
var $this=$(this);
var $colselbox=$(document.createElement("a")).addClass("colselect").attr({"href":"javascript:;"});
var $colseltext=$(document.createElement("span")).text(settingObj.title);
var $coldrop=$(document.createElement("ul")).addClass("dropmenu");
var selectInput = $.browser.msie?document.createElement("<input name="+$this.attr("id")+" />"):document.createElement("input");
selectInput.type="hidden";
selectInput.value=settingObj.value;
selectInput.setAttribute("name",'info['+$this.attr("id")+']');
var ids=$this.attr("id");
$this.onselectstart=function(){return false;};
$this.onselect=function(){document.selection.empty()};
$colselbox.append($colseltext);
$this.addClass("colsel").append($colselbox).append($coldrop).append(selectInput);
$(dataObj.Items).each(function(i,n){
var $item=$(document.createElement("li"));
if(n.topid==0){
$coldrop.append($item);
$item.html("<span>"+n.name+"</span>").attr({"values":n.value,"id":"col_"+ids+"_"+n.colid});
}else{
if($("#col_"+ids+"_"+n.topid).find("ul").length<=0){
$("#col_"+ids+"_"+n.topid).append("<ul class=\"dropmenu rootmenu\"></ul>");
$("#col_"+ids+"_"+n.topid).find("ul:first").append($item);
$item.html("<span>"+n.name+"</span>").attr({"values":n.value,"id":"col_"+ids+"_"+n.colid});
}else{
$("#col_"+ids+"_"+n.topid).find("ul:first").append($item);
$item.html("<span>"+n.name+"</span>").attr({"values":n.value,"id":"col_"+ids+"_"+n.colid});
}
}
});
$this.find("li").each(function(){
$(this).click(function(event){
$colselbox.children("span").text($(this).find("span:first").text());
$(selectInput).val($(this).attr("values"));
hideMenu();
event.stopPropagation();
});
if($(this).find("ul").length>0){
$(this).addClass("menuout");
$(this).hover(function(){
$(this).removeClass("menuout");
$(this).addClass("menuhover");
$(this).find("ul:first").fadeIn("fast")
},function(){
$(this).removeClass("menuhover");
$(this).addClass("menuout");
$(this).find("ul").each(function(){
$(this).fadeOut("fast");
});
});
}else{
$(this).addClass("norout");
$(this).hover(function(){
$(this).removeClass("norout");
$(this).addClass("norhover");
},function(){
$(this).removeClass("norhover");
$(this).addClass("norout");
});
}
});
function hideMenu(){
$this.bOpen=0;
$(".rootmenu").hide();
$coldrop.slideUp("fast");
$(document).unbind("click",hideMenu);
}
function openMenu(){
$coldrop.slideDown("fast");
$this.bOpen=1;
}
$colselbox.click(function(event){
$(this).blur();
if($this.bOpen){
hideMenu();
}else{
openMenu();
$(document).bind("click",hideMenu);
}
event.stopPropagation();
});
$(".rootmenu").each(function(){
$(this).css({"left":135+"px"});
});
}
})(jQuery);
|
JavaScript
|
function open_linkage(id,name,container,linkageid) {
returnid= id;
returnkeyid = linkageid;
var content = '<div class="linkage-menu"><h6><a href="javascript:;" onclick="get_parent(this,0)" class="rt"><<返回主菜单</a><span>'+name+'</span> <a href="javascript:;" onclick="get_parent(this)" id="parent_'+id+'" parentid="0"><img src="statics/images/icon/old-edit-redo.png" width="16" height="16" alt="返回上一级" /></a></h6><div class="ib-a menu" id="ul_'+id+'">';
for (i=0; i < container.length; i++)
{
content += '<a href="javascript:;" onclick="get_child(\''+container[i][0]+'\',\''+container[i][1]+'\',\''+container[i][2]+'\')">'+container[i][1]+'</a>';
}
content += '</div></div>';
art.dialog({title:name,id:'edit_'+id,content:content,width:'422',height:'200',style:'none_icon ui_content_m'});
}
var level = 0;
function get_child(nodeid,nodename,parentid) {
var content = container = '';
var url = "api.php?op=get_linkage&act=ajax_getlist&parentid="+nodeid+"&keyid="+returnkeyid;
$.getJSON(url+'&callback=?',function(data){
if(data) {
level = 1;
$.each(data, function(i,data){
container = data.split(',');
content += '<a href="javascript:;" onclick="get_child(\''+container[0]+'\',\''+container[1]+'\',\''+container[2]+'\')">'+container[1]+'</a>';
})
$("#ul_"+returnid).html(content);
get_path(container[2],returnid);
$("#parent_"+returnid).attr('parentid',container[2]);
} else {
set_val(nodename,nodeid);
$("input[name='info["+returnid+"]']").val(nodeid);
//$("#"+returnid).after('<input type="hidden" name="info['+returnid+']" value="'+nodeid+'">');
art.dialog({id:'edit_'+returnid}).close();
}
})
}
function get_parent(obj,parentid) {
var linkageid = parentid ? parentid : $(obj).attr('parentid');
var content = container = '';
var url = "api.php?op=get_linkage&act=ajax_getlist&linkageid="+linkageid+"&keyid="+returnkeyid;
$.getJSON(url+'&callback=?',function(data){
if(data) {
$.each(data, function(i,data){
container = data.split(',');
content += '<a href="javascript:;" onclick="get_child(\''+container[0]+'\',\''+container[1]+'\',\''+container[2]+'\')">'+container[1]+'</a>';
})
get_path(container[2],returnid);
$("#parent_"+returnid).attr('parentid',container[2]);
$("#ul_"+returnid).html(content);
} else {
$("#"+returnid).val(nodename);
art.dialog({id:'edit_'+returnid}).close();
}
})
}
function get_path(nodeid,returnid) {
var show_path = '';
var url = "api.php?op=get_linkage&act=ajax_getpath&parentid="+nodeid+"&keyid="+returnkeyid;
$.getJSON(url+'&callback=?',function(data){
if(data) {
$.each(data, function(i,data){
show_path += data+" > ";
})
$("#parent_"+returnid).siblings('span').html(show_path);
}
})
}
function set_val(nodename,nodeid) {
var path = $("#parent_"+returnid).siblings('span').html();
if(level==0) $("#"+returnid).html(nodename);
else $("#"+returnid).html(path+nodename);
var url = "api.php?op=get_linkage&act=ajax_gettopparent&linkageid="+nodeid+"&keyid="+returnkeyid;
$.getJSON(url+'&callback=?',function(data){
if(data) {
$("#city").val(data);
}
})
level = 0;
}
|
JavaScript
|
Calendar.LANG("cn", "中文", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "今天",
today: "今天", // appears in bottom bar
wk: "周",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "AM",
PM: "PM",
mn : [ "一月",
"二月",
"三月",
"四月",
"五月",
"六月",
"七月",
"八月",
"九月",
"十月",
"十一月",
"十二月"],
smn : [ "一月",
"二月",
"三月",
"四月",
"五月",
"六月",
"七月",
"八月",
"九月",
"十月",
"十一月",
"十二月"],
dn : [ "日",
"一",
"二",
"三",
"四",
"五",
"六",
"日" ],
sdn : [ "日",
"一",
"二",
"三",
"四",
"五",
"六",
"日" ]
});
|
JavaScript
|
/**
* Copyright (c) 2010 Anders Ekdahl (http://coffeescripter.com/)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Version: 1.2.4
*
* Demo and documentation: http://coffeescripter.com/code/ad-gallery/
*/
(function($) {
$.fn.adGallery = function(options) {
var defaults = { loader_image: 'statics/images/yp/loader.gif',
start_at_index: 0,
description_wrapper: false,
thumb_opacity: 0.7,
animate_first_image: false,
animation_speed: 400,
width: false,
height: false,
display_next_and_prev: true,
display_back_and_forward: true,
scroll_jump: 0, // If 0, it jumps the width of the container
slideshow: {
enable: false,
autostart: false,
speed: 5000,
start_label: 'Start',
stop_label: 'Stop',
stop_on_scroll: true,
countdown_prefix: '(',
countdown_sufix: ')',
onStart: false,
onStop: false
},
effect: 'slide-hori', // or 'slide-vert', 'fade', or 'resize', 'none'
enable_keyboard_move: true,
cycle: true,
callbacks: {
init: false,
afterImageVisible: false,
beforeImageVisible: false
}
};
var settings = $.extend(false, defaults, options);
if(options && options.slideshow) {
settings.slideshow = $.extend(false, defaults.slideshow, options.slideshow);
};
if(!settings.slideshow.enable) {
settings.slideshow.autostart = false;
};
var galleries = [];
$(this).each(function() {
var gallery = new AdGallery(this, settings);
galleries[galleries.length] = gallery;
});
// Sorry, breaking the jQuery chain because the gallery instances
// are returned so you can fiddle with them
return galleries;
};
function VerticalSlideAnimation(img_container, direction, desc) {
var current_top = parseInt(img_container.css('top'), 10);
if(direction == 'left') {
var old_image_top = '-'+ this.image_wrapper_height +'px';
img_container.css('top', this.image_wrapper_height +'px');
} else {
var old_image_top = this.image_wrapper_height +'px';
img_container.css('top', '-'+ this.image_wrapper_height +'px');
};
if(desc) {
desc.css('bottom', '-'+ desc[0].offsetHeight +'px');
desc.animate({bottom: 0}, this.settings.animation_speed * 2);
};
if(this.current_description) {
this.current_description.animate({bottom: '-'+ this.current_description[0].offsetHeight +'px'}, this.settings.animation_speed * 2);
};
return {old_image: {top: old_image_top},
new_image: {top: current_top}};
};
function HorizontalSlideAnimation(img_container, direction, desc) {
var current_left = parseInt(img_container.css('left'), 10);
if(direction == 'left') {
var old_image_left = '-'+ this.image_wrapper_width +'px';
img_container.css('left',this.image_wrapper_width +'px');
} else {
var old_image_left = this.image_wrapper_width +'px';
img_container.css('left','-'+ this.image_wrapper_width +'px');
};
if(desc) {
desc.css('bottom', '-'+ desc[0].offsetHeight +'px');
desc.animate({bottom: 0}, this.settings.animation_speed * 2);
};
if(this.current_description) {
this.current_description.animate({bottom: '-'+ this.current_description[0].offsetHeight +'px'}, this.settings.animation_speed * 2);
};
return {old_image: {left: old_image_left},
new_image: {left: current_left}};
};
function ResizeAnimation(img_container, direction, desc) {
var image_width = img_container.width();
var image_height = img_container.height();
var current_left = parseInt(img_container.css('left'), 10);
var current_top = parseInt(img_container.css('top'), 10);
img_container.css({width: 0, height: 0, top: this.image_wrapper_height / 2, left: this.image_wrapper_width / 2});
return {old_image: {width: 0,
height: 0,
top: this.image_wrapper_height / 2,
left: this.image_wrapper_width / 2},
new_image: {width: image_width,
height: image_height,
top: current_top,
left: current_left}};
};
function FadeAnimation(img_container, direction, desc) {
img_container.css('opacity', 0);
return {old_image: {opacity: 0},
new_image: {opacity: 1}};
};
// Sort of a hack, will clean this up... eventually
function NoneAnimation(img_container, direction, desc) {
img_container.css('opacity', 0);
return {old_image: {opacity: 0},
new_image: {opacity: 1},
speed: 0};
};
function AdGallery(wrapper, settings) {
this.init(wrapper, settings);
};
AdGallery.prototype = {
// Elements
wrapper: false,
image_wrapper: false,
gallery_info: false,
nav: false,
loader: false,
preloads: false,
thumbs_wrapper: false,
scroll_back: false,
scroll_forward: false,
next_link: false,
prev_link: false,
slideshow: false,
image_wrapper_width: 0,
image_wrapper_height: 0,
current_index: 0,
current_image: false,
current_description: false,
nav_display_width: 0,
settings: false,
images: false,
in_transition: false,
animations: false,
init: function(wrapper, settings) {
var context = this;
this.wrapper = $(wrapper);
this.settings = settings;
this.setupElements();
this.setupAnimations();
if(this.settings.width) {
this.image_wrapper_width = this.settings.width;
this.image_wrapper.width(this.settings.width);
this.wrapper.width(this.settings.width);
} else {
this.image_wrapper_width = this.image_wrapper.width();
};
if(this.settings.height) {
this.image_wrapper_height = this.settings.height;
this.image_wrapper.height(this.settings.height);
} else {
this.image_wrapper_height = this.image_wrapper.height();
};
this.nav_display_width = this.nav.width();
this.current_index = 0;
this.current_image = false;
this.current_description = false;
this.in_transition = false;
this.findImages();
if(this.settings.display_next_and_prev) {
this.initNextAndPrev();
};
// The slideshow needs a callback to trigger the next image to be shown
// but we don't want to give it access to the whole gallery instance
var nextimage_callback = function(callback) {
return context.nextImage(callback);
};
this.slideshow = new AdGallerySlideshow(nextimage_callback, this.settings.slideshow);
this.controls.append(this.slideshow.create());
if(this.settings.slideshow.enable) {
this.slideshow.enable();
} else {
this.slideshow.disable();
};
if(this.settings.display_back_and_forward) {
this.initBackAndForward();
};
if(this.settings.enable_keyboard_move) {
this.initKeyEvents();
};
var start_at = parseInt(this.settings.start_at_index, 10);
if(window.location.hash && window.location.hash.indexOf('#ad-image') === 0) {
start_at = window.location.hash.replace(/[^0-9]+/g, '');
// Check if it's a number
if((start_at * 1) != start_at) {
start_at = this.settings.start_at_index;
};
};
this.loading(true);
this.showImage(start_at,
function() {
// We don't want to start the slideshow before the image has been
// displayed
if(context.settings.slideshow.autostart) {
context.preloadImage(start_at + 1);
context.slideshow.start();
};
}
);
this.fireCallback(this.settings.callbacks.init);
},
setupAnimations: function() {
this.animations = {
'slide-vert': VerticalSlideAnimation,
'slide-hori': HorizontalSlideAnimation,
'resize': ResizeAnimation,
'fade': FadeAnimation,
'none': NoneAnimation
};
},
setupElements: function() {
this.controls = this.wrapper.find('.ad-controls');
this.gallery_info = $('<p class="ad-info"></p>');
this.controls.append(this.gallery_info);
this.image_wrapper = this.wrapper.find('.ad-image-wrapper');
this.image_wrapper.empty();
this.nav = this.wrapper.find('.ad-nav');
this.thumbs_wrapper = this.nav.find('.ad-thumbs');
this.preloads = $('<div class="ad-preloads"></div>');
this.loader = $('<img class="ad-loader" src="'+ this.settings.loader_image +'">');
this.image_wrapper.append(this.loader);
this.loader.hide();
$(document.body).append(this.preloads);
},
loading: function(bool) {
if(bool) {
this.loader.show();
} else {
this.loader.hide();
};
},
addAnimation: function(name, fn) {
if($.isFunction(fn)) {
this.animations[name] = fn;
};
},
findImages: function() {
var context = this;
this.images = [];
var thumb_wrapper_width = 0;
var thumbs_loaded = 0;
var thumbs = this.thumbs_wrapper.find('a');
var thumb_count = thumbs.length;
if(this.settings.thumb_opacity < 1) {
thumbs.find('img').css('opacity', this.settings.thumb_opacity);
};
thumbs.each(
function(i) {
var link = $(this);
var image_src = link.attr('href');
var thumb = link.find('img');
// Check if the thumb has already loaded
if(!context.isImageLoaded(thumb[0])) {
thumb.load(
function() {
thumb_wrapper_width += this.parentNode.parentNode.offsetWidth;
thumbs_loaded++;
}
);
} else{
thumb_wrapper_width += thumb[0].parentNode.parentNode.offsetWidth;
thumbs_loaded++;
};
link.addClass('ad-thumb'+ i);
link.click(
function() {
context.showImage(i);
context.slideshow.stop();
return false;
}
).hover(
function() {
if(!$(this).is('.ad-active') && context.settings.thumb_opacity < 1) {
$(this).find('img').fadeTo(300, 1);
};
context.preloadImage(i);
},
function() {
if(!$(this).is('.ad-active') && context.settings.thumb_opacity < 1) {
$(this).find('img').fadeTo(300, context.settings.thumb_opacity);
};
}
);
var link = false;
if(thumb.data('ad-link')) {
link = thumb.data('ad-link');
} else if(thumb.attr('longdesc') && thumb.attr('longdesc').length) {
link = thumb.attr('longdesc');
};
var desc = false;
if(thumb.data('ad-desc')) {
desc = thumb.data('ad-desc');
} else if(thumb.attr('alt') && thumb.attr('alt').length) {
desc = thumb.attr('alt');
};
var title = false;
if(thumb.data('ad-title')) {
title = thumb.data('ad-title');
} else if(thumb.attr('title') && thumb.attr('title').length) {
title = thumb.attr('title');
};
context.images[i] = { thumb: thumb.attr('src'), image: image_src, error: false,
preloaded: false, desc: desc, title: title, size: false,
link: link };
}
);
// Wait until all thumbs are loaded, and then set the width of the ul
var inter = setInterval(
function() {
if(thumb_count == thumbs_loaded) {
thumb_wrapper_width -= 100;
var list = context.nav.find('.ad-thumb-list'),
list_num = list.children().length,
list_width = list.children().eq(0).width();
list.css('width', (list_width+5)*list_num +'px');
clearInterval(inter);
};
},
100
);
},
initKeyEvents: function() {
var context = this;
$(document).keydown(
function(e) {
if(e.keyCode == 39) {
// right arrow
context.nextImage();
context.slideshow.stop();
} else if(e.keyCode == 37) {
// left arrow
context.prevImage();
context.slideshow.stop();
};
}
);
},
initNextAndPrev: function() {
this.next_link = $('<div class="ad-next"><div class="ad-next-image"></div></div>');
this.prev_link = $('<div class="ad-prev"><div class="ad-prev-image"></div></div>');
this.image_wrapper.append(this.next_link);
this.image_wrapper.append(this.prev_link);
var context = this;
this.prev_link.add(this.next_link).mouseover(
function(e) {
// IE 6 hides the wrapper div, so we have to set it's width
$(this).css('height', context.image_wrapper_height);
$(this).find('div').show();
}
).mouseout(
function(e) {
$(this).find('div').hide();
}
).click(
function() {
if($(this).is('.ad-next')) {
context.nextImage();
context.slideshow.stop();
} else {
context.prevImage();
context.slideshow.stop();
};
}
).find('div').css('opacity', 0.7);
},
initBackAndForward: function() {
var context = this;
this.scroll_forward = $('<div class="ad-forward"></div>');
this.scroll_back = $('<div class="ad-back"></div>');
this.nav.append(this.scroll_forward);
this.nav.prepend(this.scroll_back);
var has_scrolled = 0;
var thumbs_scroll_interval = false;
$(this.scroll_back).add(this.scroll_forward).click(
function() {
// We don't want to jump the whole width, since an image
// might be cut at the edge
var width = context.nav_display_width - 50;
if(context.settings.scroll_jump > 0) {
var width = context.settings.scroll_jump;
};
if($(this).is('.ad-forward')) {
var left = context.thumbs_wrapper.scrollLeft() + width;
} else {
var left = context.thumbs_wrapper.scrollLeft() - width;
};
if(context.settings.slideshow.stop_on_scroll) {
context.slideshow.stop();
};
context.thumbs_wrapper.animate({scrollLeft: left +'px'});
return false;
}
).css('opacity', 0.6).hover(
function() {
var direction = 'left';
if($(this).is('.ad-forward')) {
direction = 'right';
};
thumbs_scroll_interval = setInterval(
function() {
has_scrolled++;
// Don't want to stop the slideshow just because we scrolled a pixel or two
if(has_scrolled > 30 && context.settings.slideshow.stop_on_scroll) {
context.slideshow.stop();
};
var left = context.thumbs_wrapper.scrollLeft() + 1;
if(direction == 'left') {
left = context.thumbs_wrapper.scrollLeft() - 1;
};
context.thumbs_wrapper.scrollLeft(left);
},
10
);
$(this).css('opacity', 1);
},
function() {
has_scrolled = 0;
clearInterval(thumbs_scroll_interval);
$(this).css('opacity', 0.6);
}
);
},
_afterShow: function() {
this.gallery_info.html((this.current_index + 1) +' / '+ this.images.length);
if(!this.settings.cycle) {
// Needed for IE
this.prev_link.show().css('height', this.image_wrapper_height);
this.next_link.show().css('height', this.image_wrapper_height);
if(this.current_index == (this.images.length - 1)) {
this.next_link.hide();
};
if(this.current_index == 0) {
this.prev_link.hide();
};
};
this.fireCallback(this.settings.callbacks.afterImageVisible);
},
/**
* Checks if the image is small enough to fit inside the container
* If it's not, shrink it proportionally
*/
_getContainedImageSize: function(image_width, image_height) {
if(image_height > this.image_wrapper_height) {
var ratio = image_width / image_height;
image_height = this.image_wrapper_height;
image_width = this.image_wrapper_height * ratio;
};
if(image_width > this.image_wrapper_width) {
var ratio = image_height / image_width;
image_width = this.image_wrapper_width;
image_height = this.image_wrapper_width * ratio;
};
return {width: image_width, height: image_height};
},
/**
* If the image dimensions are smaller than the wrapper, we position
* it in the middle anyway
*/
_centerImage: function(img_container, image_width, image_height) {
img_container.css('top', '0px');
if(image_height < this.image_wrapper_height) {
var dif = this.image_wrapper_height - image_height;
img_container.css('top', (dif / 2) +'px');
};
img_container.css('left', '0px');
if(image_width < this.image_wrapper_width) {
var dif = this.image_wrapper_width - image_width;
img_container.css('left', (dif / 2) +'px');
};
},
_getDescription: function(image) {
var desc = false;
if(image.desc.length || image.title.length) {
var title = '';
if(image.title.length) {
title = '<strong class="ad-description-title">'+ image.title +'</strong>';
};
var desc = '';
if(image.desc.length) {
desc = '<span>'+ image.desc +'</span>';
};
desc = $('<p class="ad-image-description">'+ title + desc +'</p>');
};
return desc;
},
/**
* @param function callback Gets fired when the image has loaded, is displaying
* and it's animation has finished
*/
showImage: function(index, callback) {
if(this.images[index] && !this.in_transition) {
var context = this;
var image = this.images[index];
this.in_transition = true;
if(!image.preloaded) {
this.loading(true);
this.preloadImage(index, function() {
context.loading(false);
context._showWhenLoaded(index, callback);
});
} else {
this._showWhenLoaded(index, callback);
};
};
},
/**
* @param function callback Gets fired when the image has loaded, is displaying
* and it's animation has finished
*/
_showWhenLoaded: function(index, callback) {
if(this.images[index]) {
var context = this;
var image = this.images[index];
var img_container = $(document.createElement('div')).addClass('ad-image');
var img = $(new Image()).attr('src', image.image);
if(image.link) {
var link = $('<a href="'+ image.link +'" target="_blank"></a>');
link.append(img);
img_container.append(link);
} else {
img_container.append(img);
}
this.image_wrapper.prepend(img_container);
var size = this._getContainedImageSize(image.size.width, image.size.height);
img.attr('width', size.width);
img.attr('height', size.height);
img_container.css({width: size.width +'px', height: size.height +'px'});
this._centerImage(img_container, size.width, size.height);
var desc = this._getDescription(image, img_container);
if(desc) {
if(!this.settings.description_wrapper) {
img_container.append(desc);
var width = size.width - parseInt(desc.css('padding-left'), 10) - parseInt(desc.css('padding-right'), 10);
desc.css('width', width +'px');
} else {
this.settings.description_wrapper.append(desc);
}
};
this.highLightThumb(this.nav.find('.ad-thumb'+ index));
var direction = 'right';
if(this.current_index < index) {
direction = 'left';
};
this.fireCallback(this.settings.callbacks.beforeImageVisible);
if(this.current_image || this.settings.animate_first_image) {
var animation_speed = this.settings.animation_speed;
var easing = 'swing';
var animation = this.animations[this.settings.effect].call(this, img_container, direction, desc);
if(typeof animation.speed != 'undefined') {
animation_speed = animation.speed;
};
if(typeof animation.easing != 'undefined') {
easing = animation.easing;
};
if(this.current_image) {
var old_image = this.current_image;
var old_description = this.current_description;
old_image.animate(animation.old_image, animation_speed, easing,
function() {
old_image.remove();
if(old_description) old_description.remove();
}
);
};
img_container.animate(animation.new_image, animation_speed, easing,
function() {
context.current_index = index;
context.current_image = img_container;
context.current_description = desc;
context.in_transition = false;
context._afterShow();
context.fireCallback(callback);
}
);
} else {
this.current_index = index;
this.current_image = img_container;
context.current_description = desc;
this.in_transition = false;
context._afterShow();
this.fireCallback(callback);
};
};
},
nextIndex: function() {
if(this.current_index == (this.images.length - 1)) {
if(!this.settings.cycle) {
return false;
};
var next = 0;
} else {
var next = this.current_index + 1;
};
return next;
},
nextImage: function(callback) {
var next = this.nextIndex();
if(next === false) return false;
this.preloadImage(next + 1);
this.showImage(next, callback);
return true;
},
prevIndex: function() {
if(this.current_index == 0) {
if(!this.settings.cycle) {
return false;
};
var prev = this.images.length - 1;
} else {
var prev = this.current_index - 1;
};
return prev;
},
prevImage: function(callback) {
var prev = this.prevIndex();
if(prev === false) return false;
this.preloadImage(prev - 1);
this.showImage(prev, callback);
return true;
},
preloadAll: function() {
var context = this;
var i = 0;
function preloadNext() {
if(i < context.images.length) {
i++;
context.preloadImage(i, preloadNext);
};
};
context.preloadImage(i, preloadNext);
},
preloadImage: function(index, callback) {
if(this.images[index]) {
var image = this.images[index];
if(!this.images[index].preloaded) {
var img = $(new Image());
img.attr('src', image.image);
if(!this.isImageLoaded(img[0])) {
this.preloads.append(img);
var context = this;
img.load(
function() {
image.preloaded = true;
image.size = { width: this.width, height: this.height };
context.fireCallback(callback);
}
).error(
function() {
image.error = true;
image.preloaded = false;
image.size = false;
}
);
} else {
image.preloaded = true;
image.size = { width: img[0].width, height: img[0].height };
this.fireCallback(callback);
};
} else {
this.fireCallback(callback);
};
};
},
isImageLoaded: function(img) {
if(typeof img.complete != 'undefined' && !img.complete) {
return false;
};
if(typeof img.naturalWidth != 'undefined' && img.naturalWidth == 0) {
return false;
};
return true;
},
highLightThumb: function(thumb) {
this.thumbs_wrapper.find('.ad-active').removeClass('ad-active');
thumb.addClass('ad-active');
if(this.settings.thumb_opacity < 1) {
this.thumbs_wrapper.find('a:not(.ad-active) img').fadeTo(300, this.settings.thumb_opacity);
thumb.find('img').fadeTo(300, 1);
};
var left = thumb[0].parentNode.offsetLeft;
left -= (this.nav_display_width / 2) - (thumb[0].offsetWidth / 2);
this.thumbs_wrapper.animate({scrollLeft: left +'px'});
},
fireCallback: function(fn) {
if($.isFunction(fn)) {
fn.call(this);
};
}
};
function AdGallerySlideshow(nextimage_callback, settings) {
this.init(nextimage_callback, settings);
};
AdGallerySlideshow.prototype = {
start_link: false,
stop_link: false,
countdown: false,
controls: false,
settings: false,
nextimage_callback: false,
enabled: false,
running: false,
countdown_interval: false,
init: function(nextimage_callback, settings) {
var context = this;
this.nextimage_callback = nextimage_callback;
this.settings = settings;
},
create: function() {
this.start_link = $('<span class="ad-slideshow-start">'+ this.settings.start_label +'</span>');
this.stop_link = $('<span class="ad-slideshow-stop">'+ this.settings.stop_label +'</span>');
this.countdown = $('<span class="ad-slideshow-countdown"></span>');
this.controls = $('<div class="ad-slideshow-controls"></div>');
this.controls.append(this.start_link).append(this.stop_link).append(this.countdown);
this.countdown.hide();
var context = this;
this.start_link.click(
function() {
context.start();
}
);
this.stop_link.click(
function() {
context.stop();
}
);
$(document).keydown(
function(e) {
if(e.keyCode == 83) {
// 's'
if(context.running) {
context.stop();
} else {
context.start();
};
};
}
);
return this.controls;
},
disable: function() {
this.enabled = false;
this.stop();
this.controls.hide();
},
enable: function() {
this.enabled = true;
this.controls.show();
},
toggle: function() {
if(this.enabled) {
this.disable();
} else {
this.enable();
};
},
start: function() {
if(this.running || !this.enabled) return false;
var context = this;
this.running = true;
this.controls.addClass('ad-slideshow-running');
this._next();
this.fireCallback(this.settings.onStart);
return true;
},
stop: function() {
if(!this.running) return false;
this.running = false;
this.countdown.hide();
this.controls.removeClass('ad-slideshow-running');
clearInterval(this.countdown_interval);
this.fireCallback(this.settings.onStop);
return true;
},
_next: function() {
var context = this;
var pre = this.settings.countdown_prefix;
var su = this.settings.countdown_sufix;
clearInterval(context.countdown_interval);
this.countdown.show().html(pre + (this.settings.speed / 1000) + su);
var slide_timer = 0;
this.countdown_interval = setInterval(
function() {
slide_timer += 1000;
if(slide_timer >= context.settings.speed) {
var whenNextIsShown = function() {
// A check so the user hasn't stoped the slideshow during the
// animation
if(context.running) {
context._next();
};
slide_timer = 0;
};
if(!context.nextimage_callback(whenNextIsShown)) {
context.stop();
};
slide_timer = 0;
};
var sec = parseInt(context.countdown.text().replace(/[^0-9]/g, ''), 10);
sec--;
if(sec > 0) {
context.countdown.html(pre + sec + su);
};
},
1000
);
},
fireCallback: function(fn) {
if($.isFunction(fn)) {
fn.call(this);
};
}
};
})(jQuery);
|
JavaScript
|
/**
* Styleswitch stylesheet switcher built on jQuery
* Under an Attribution, Share Alike License
* Download by http://www.codefans.net
* By Kelvin Luck ( http://www.kelvinluck.com/ )
**/
(function($)
{
$(document).ready(function() {
$('.styleswitch').click(function()
{
switchStylestyle(this.getAttribute("rel"));
return false;
});
var c = readCookie('style');
if (c) switchStylestyle(c);
});
function switchStylestyle(styleName)
{
var ifrm = $("#rightMain").contents();
$('link[@rel*=style][title]').each(function(i)
{
this.disabled = true;
if (this.getAttribute('title') == styleName) this.disabled = false;
});
ifrm.find('link[@rel*=style][title]').each(function(i)
{
this.disabled = true;
if (this.getAttribute('title') == styleName) this.disabled = false;
});
createCookie('style', styleName, 365);
}
})(jQuery);
// cookie functions http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days)
{
if (days)
{
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name)
{
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++)
{
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name)
{
createCookie(name,"",-1);
}
// /cookie functions
|
JavaScript
|
Array.prototype.in_array = function(e){
for(i=0;i<this.length && this[i]!=e;i++);
return !(i==this.length);
}
function remove_all(){
$("#checkbox :checkbox").attr("checked",false);
$("#relation_text").html("");
$.get(ajax_url, {m:'yp', c:'index', a:'pk', action:'remove', catid:catid, random:Math.random()});
$("#relation").val("");
c_sum();
};
$("#checkbox :checkbox").click(function (){
var q = $(this),
num = 4,
id = q.val(),
title = q.attr('title'),
img = q.attr('img'),
sid = 'v1'+id,
relation_ids = $('#relation').val(),
relation_ids = relation_ids.replace(/(^_*)|(_*$)/g, ""),
r_arr = relation_ids.split('-');
if($("#comparison").css("display")=="none"){
$("#comparison").fadeIn("slow");
}
if(q.attr("checked")==false){
$('#'+sid).remove();
$.get(ajax_url, {m:'yp', c:'index', a:'pk', action:'reduce', id:id, catid:catid, random:Math.random()});
if(relation_ids !='' ) {
var newrelation_ids = '';
$.each(r_arr, function(i, n){
if(n!=id) {
if(i==0) {
newrelation_ids = n;
} else {
newrelation_ids = newrelation_ids+'-'+n;
}
}
});
$('#relation').val(newrelation_ids);
}
c_sum();
}else{
if(r_arr.in_array(id)){
q.checked=false;
alert("抱歉,已经选择了该信息");
return false;
}
if(r_arr.length>=num){
q.checked=false;
alert("抱歉,您只能选择"+r_arr.length+"款商品对比");
return false;
}else{
$.get(ajax_url, {m:'yp', c:'index', a:'pk', action:'add', id:id, title:title, thumb:img, catid:catid, random:Math.random()});
var str = "<li style='display:none' id='"+sid+"'><img src="+img+" height='45'/><p>"+title+"</p><a href='javascript:;' class='close' onclick=\"remove_relation('"+sid+"',"+id+")\">X</a></li>";
$('#relation_text').append(str);
$("#"+sid).fadeIn("slow");
if(relation_ids =='' ){
$('#relation').val(id);
}else{
relation_ids = relation_ids+'-'+id;
$('#relation').val(relation_ids);
}
c_sum();
$('#'+sid+' img').LoadImage(true, 120, 60,'statics/images/s_nopic.gif');
}
}
});
function remove_relation(sid,id){
$('#'+sid).remove();
$.get(ajax_url, {m:'yp', c:'index', a:'pk', action:'reduce', id:id, catid:catid, random:Math.random()});
$("#c_"+id).attr("checked",false);
$("#c_h_"+id).attr("checked",false);
var relation_ids = $('#relation').val(),
r_arr = relation_ids.split('-'),
newrelation_ids = '';
if(relation_ids!=''){
$.each(r_arr, function(i, n){
if(n!=id) {
if(i==0) {
newrelation_ids = n;
} else {
newrelation_ids = newrelation_ids+'-'+n;
}
}
});
$('#relation').val(newrelation_ids);
}
c_sum();
return false;
}
function comp_btn() {
var relation_ids = $('#relation').val(),
_rel = relation_ids.replace(/(^_*)|(_*$)/g, "");
if($("#comp_num").text()>1){
//alert(_rel);
window.open(ajax_url+"?m=yp&c=index&a=pk&catid="+catid+"&modelid="+modelid+"&pk="+_rel);
}else{
alert("请选择2~4个需要对比的商品!");
}
};
function c_sum(){
var relation_ids = $('#relation').val(),
relation_ids = relation_ids.replace(/(^_*)|(_*$)/g, ""),
r_arr = relation_ids.split('-');
if(relation_ids){
$("#comp_num").text(r_arr.length);
}else{
$("#comp_num").text('0');
}
}
//浮动
(function($) {
$.fn.extend({
"followDiv": function(str) {
var _self = this,
_h = _self.height() ;
var pos;
switch (str) {
case "right":
pos = { "right": "0px", "top": "27px" };
break;
}
topIE6 = parseInt(pos.top) + $(window).scrollTop();
_self.animate({'top':topIE6},500);
/*FF和IE7可以通过position:fixed来定位,*/
//_self.css({ "position": "fixed", "z-index": "9999" }).css(pos);
/*ie6需要动态设置距顶端高度top.*/
// if ($.browser.msie && $.browser.version == 6) {
//_self.css('position', 'absolute');
$(window).scroll(function() {
topIE6 = parseInt(pos.top) + $(window).scrollTop();
//_self.css('top', topIE6);
$(_self).stop().animate({top:topIE6},300)
});
// }
return _self; //返回this,使方法可链。
}
});
})(jQuery);
$("body").append('<div id="comparison"><div class="title"><span id="comp_num">1</span>/4对比栏<a href="javascript:;" onclick="$(this).parent().parent().hide()" class="colse">X</a></div><input type="hidden" id="relation" value="" /><ul id="relation_text"></ul><center><a href="javascript:void(0);" onclick="comp_btn()" id="comp_btn">开始对比</a><br><a href="javascript:;" class="remove_all" onclick="remove_all();">清空对比栏</a></center></div>');
$("#comparison").followDiv("right");
|
JavaScript
|
//Chrome Drop Down Menu- Author: Dynamic Drive (http://www.dynamicdrive.com)
//Last updated: June 14th, 06'
var cssdropdown={
disappeardelay: 250, //set delay in miliseconds before menu disappears onmouseout
disablemenuclick: false, //when user clicks on a menu item with a drop down menu, disable menu item's link?
enableswipe: 1, //enable swipe effect? 1 for yes, 0 for no
//No need to edit beyond here////////////////////////
dropmenuobj: null, ie: document.all, firefox: document.getElementById&&!document.all, swipetimer: undefined, bottomclip:0,
getposOffset:function(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
},
swipeeffect:function(){
if (this.bottomclip<parseInt(this.dropmenuobj.offsetHeight)){
this.bottomclip+=10+(this.bottomclip/10) //unclip drop down menu visibility gradually
this.dropmenuobj.style.clip="rect(0 auto "+this.bottomclip+"px 0)"
}
else
return
this.swipetimer=setTimeout("cssdropdown.swipeeffect()", 10)
},
showhide:function(obj, e){
if (this.ie || this.firefox)
this.dropmenuobj.style.left=this.dropmenuobj.style.top="-500px"
if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover"){
if (this.enableswipe==1){
if (typeof this.swipetimer!="undefined")
clearTimeout(this.swipetimer)
obj.clip="rect(0 auto 0 0)" //hide menu via clipping
this.bottomclip=0
this.swipeeffect()
}
obj.visibility="visible"
}
else if (e.type=="click")
obj.visibility="hidden"
},
iecompattest:function(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
},
clearbrowseredge:function(obj, whichedge){
var edgeoffset=0
if (whichedge=="rightedge"){
var windowedge=this.ie && !window.opera? this.iecompattest().scrollLeft+this.iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetWidth
if (windowedge-this.dropmenuobj.x < this.dropmenuobj.contentmeasure) //move menu to the left?
edgeoffset=this.dropmenuobj.contentmeasure-obj.offsetWidth
}
else{
var topedge=this.ie && !window.opera? this.iecompattest().scrollTop : window.pageYOffset
var windowedge=this.ie && !window.opera? this.iecompattest().scrollTop+this.iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetHeight
if (windowedge-this.dropmenuobj.y < this.dropmenuobj.contentmeasure){ //move up?
edgeoffset=this.dropmenuobj.contentmeasure+obj.offsetHeight
if ((this.dropmenuobj.y-topedge)<this.dropmenuobj.contentmeasure) //up no good either?
edgeoffset=this.dropmenuobj.y+obj.offsetHeight-topedge
}
}
return edgeoffset
},
dropit:function(obj, e, dropmenuID){
if (this.dropmenuobj!=null) //hide previous menu
this.dropmenuobj.style.visibility="hidden" //hide menu
this.clearhidemenu()
if (this.ie||this.firefox){
obj.onmouseout=function(){cssdropdown.delayhidemenu()}
obj.onclick=function(){return !cssdropdown.disablemenuclick} //disable main menu item link onclick?
this.dropmenuobj=document.getElementById(dropmenuID)
this.dropmenuobj.onmouseover=function(){cssdropdown.clearhidemenu()}
this.dropmenuobj.onmouseout=function(){cssdropdown.dynamichide(e)}
this.dropmenuobj.onclick=function(){cssdropdown.delayhidemenu()}
this.showhide(this.dropmenuobj.style, e)
this.dropmenuobj.x=this.getposOffset(obj, "left")
this.dropmenuobj.y=this.getposOffset(obj, "top")
this.dropmenuobj.style.left=this.dropmenuobj.x-this.clearbrowseredge(obj, "rightedge")+obj.offsetWidth+0+"px"
this.dropmenuobj.style.top=this.dropmenuobj.y-this.clearbrowseredge(obj, "bottomedge")+obj.offsetHeight-42+"px"
}
},
contains_firefox:function(a, b) {
while (b.parentNode)
if ((b = b.parentNode) == a)
return true;
return false;
},
dynamichide:function(e){
var evtobj=window.event? window.event : e
if (this.ie&&!this.dropmenuobj.contains(evtobj.toElement))
this.delayhidemenu()
else if (this.firefox&&e.currentTarget!= evtobj.relatedTarget&& !this.contains_firefox(evtobj.currentTarget, evtobj.relatedTarget))
this.delayhidemenu()
},
delayhidemenu:function(){
this.delayhide=setTimeout("cssdropdown.dropmenuobj.style.visibility='hidden'",this.disappeardelay) //hide menu
},
clearhidemenu:function(){
if (this.delayhide!="undefined")
clearTimeout(this.delayhide)
},
startchrome:function(){
for (var ids=0; ids<arguments.length; ids++){
var menuitems=document.getElementById(arguments[ids]).getElementsByTagName("a")
for (var i=0; i<menuitems.length; i++){
if (menuitems[i].getAttribute("rel") && $(menuitems[i]).attr('rel') == 'dropmenu1'){
var relvalue=menuitems[i].getAttribute("rel")
menuitems[i].onmouseover=function(e){
var event=typeof e!="undefined"? e : window.event
cssdropdown.dropit(this,event,this.getAttribute("rel"))
}
}
}
}
}
}
|
JavaScript
|
$(function() {
//IE6 PNG透明
$(document).pngFix();
if($('.listView').length > 0 || $('.price').length > 0 ){
cssdropdown.startchrome("main");
};
//Footer
$('#footer').height($('body').height()-$('#wrapper').height()-31);
//返回页面顶部按纽跟随
$('#goTop').click(function(){
$('html,body').animate({scrollTop: '0px'}, 600);
return false;
});
//picList
$('.picList .listCo ul li a.image').each(function(){
$(this).css('background','url('+$(this).attr('rev')+') no-repeat');
})
$('a.single_image').fancybox({'titleShow':true});
if($('.picList').length > 0){
$("a[rel=photoGroup]").fancybox({
'transitionIn' : 'none',
'transitionOut' : 'none',
'titlePosition' : 'inside',
'titleFormat' : function(title, currentArray, currentIndex, currentOpts) {
return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' ' + title : '') + '</span>';
}
});
$("a[rel=photoGroup]").hover(function(){
$(this).parent().find("a.btn").fadeIn("fast");
});
$("a[rel=photoGroup]").parent().hover(function(){
},function(){
$(this).find("a.btn").fadeOut("fast");
})
};
if($('.listView').length > 0){
$(".subMenu .btn").fancybox({
'width' : 430,
'height' : 260,
'autoScale' : false,
'transitionIn' : 'none',
'transitionOut' : 'none',
'type' : 'iframe'
});
$("a[rel=photoGroup]").fancybox({
'transitionIn' : 'none',
'transitionOut' : 'none',
'titlePosition' : 'inside',
'titleFormat' : function(title, currentArray, currentIndex, currentOpts) {
return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' ' + title : '') + '</span>';
}
});
};
if($('.product').length > 0){
$("a[rel=photoGroup]").fancybox({
'transitionIn' : 'none',
'transitionOut' : 'none',
'titlePosition' : 'inside',
'titleFormat' : function(title, currentArray, currentIndex, currentOpts) {
return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' ' + title : '') + '</span>';
}
});
};
if($('.price').length > 0){
$("a[rel=photoGroup]").fancybox({
'transitionIn' : 'none',
'transitionOut' : 'none',
'titlePosition' : 'inside',
'titleFormat' : function(title, currentArray, currentIndex, currentOpts) {
return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' ' + title : '') + '</span>';
}
});
};
if($('.createBtn').length > 0){
$(".createBtn").fancybox({
'width' : 430,
'height' : 260,
'autoScale' : false,
'transitionIn' : 'none',
'transitionOut' : 'none',
'type' : 'iframe'
});
}
if($('.batchupload').length > 0){
$(".batchupload").fancybox({
'width' : 500,
'height' : 450,
'autoScale' : false,
'transitionIn' : 'none',
'transitionOut' : 'none',
'type' : 'iframe'
});
}
//tab选项卡
$("a.tabs").click(function () {
$(this).parent().find("a.current").removeClass("current");
$(this).addClass("current");
$("#"+$(this).siblings().attr("rel")).hide();
//$(this).parent().parent().find(".tabsCo").hide();
var content_show = $(this).attr("rel");
$("#"+content_show).show();
return false;
});
$(".cate div h3").click(function(){
if($(this).next("ul").css("display")=="none"){
$(this).next("ul").css("display","inline");
$(this).next("br").css("display","block");
}else{
$(this).next("ul").css("display","none");
$(this).next("br").css("display","none");
}
})
//更改首选清单
$('#orderList input:checkbox').live('click', function() {
$('#orderList input:checkbox').attr("checked", false);
$.getJSON('index.php?m=order&c=index&a=setSelected', {id:$(this).val()});
$(this).attr("checked", true);
});
})
//点评
function dianping(elem, a, id, modelid) {
var _font = $(elem).next("."+a);
$.getJSON('index.php?m=content&c=index&a=ajax_update', {t:a, modelid:modelid, id:id});
_font.html(parseInt(_font.html())+1);
}
//添加到清单
function addOrder(id) {
$.getJSON('index.php?m=order&c=order_detail&a=add', {productid:id, ajax:1}, function(data){
if(data.code == true) {
$('#msgBox').html("<div class='suc'>"+data.msg+"</div>");
$('#msgBox').fadeIn("fast");
setTimeout(function(){$("#msgBox").fadeOut("fast");},800);
} else {
$('#msgBox').html("<div class='err'>"+data.msg+"</div>");
$('#msgBox').fadeIn("fast");
setTimeout(function(){$("#msgBox").fadeOut("fast");},3000);
}
//alert(data.msg);
});
}
|
JavaScript
|
/*
* Easy Slider 1.5 - jQuery plugin
* written by Alen Grakalic
* http://cssglobe.com/post/4004/easy-slider-15-the-easiest-jquery-plugin-for-sliding
*
* Copyright (c) 2009 Alen Grakalic (http://cssglobe.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* Built for jQuery library
* http://jquery.com
*
*/
/*
* markup example for $("#slider").easySlider();
*
* <div id="slider">
* <ul>
* <li><img src="images/01.jpg" alt="" /></li>
* <li><img src="images/02.jpg" alt="" /></li>
* <li><img src="images/03.jpg" alt="" /></li>
* <li><img src="images/04.jpg" alt="" /></li>
* <li><img src="images/05.jpg" alt="" /></li>
* </ul>
* </div>
*
*/
(function($) {
$.fn.easySlider = function(options){
// default configuration properties
var defaults = {
prevId: 'prevBtn',
num: 'num',
prevText: 'Previous',
nextId: 'nextBtn',
nextText: 'Next',
controlsShow: true,
controlsBefore: '',
controlsAfter: '',
controlsFade: true,
firstId: 'firstBtn',
firstText: 'First',
firstShow: false,
lastId: 'lastBtn',
lastText: 'Last',
lastShow: false,
vertical: false,
speed: 800,
auto: false,
pause: 2000,
continuous: false
};
var options = $.extend(defaults, options);
this.each(function() {
var obj = $(this);
var s = $("li", obj).length;
var w = $("li", obj).width();
var h = $("li", obj).height();
obj.width(w);
obj.height(h);
obj.css("overflow","hidden");
var ts = s-1;
var t = 0;
$("ul", obj).css('width',s*w);
if(!options.vertical) $("li", obj).css('float','left');
if(options.controlsShow){
var html = options.controlsBefore;
if(options.firstShow) html += '<span id="'+ options.firstId +'"><a href=\"javascript:void(0);\">'+ options.firstText +'</a></span>';
html += ' <span id="'+ options.prevId +'"><a href=\"javascript:void(0);\">'+ options.prevText +'</a></span>';
html += ' <span id="'+ options.num +'">'+(t+1)+' / '+(ts+1)+'</span>';
html += ' <span id="'+ options.nextId +'"><a href=\"javascript:void(0);\">'+ options.nextText +'</a></span>';
if(options.lastShow) html += ' <span id="'+ options.lastId +'"><a href=\"javascript:void(0);\">'+ options.lastText +'</a></span>';
html += options.controlsAfter;
$(obj).after(html);
};
$("a","#"+options.nextId).click(function(){
animate("next",true);
});
$("a","#"+options.prevId).click(function(){
animate("prev",true);
});
$("a","#"+options.firstId).click(function(){
animate("first",true);
});
$("a","#"+options.lastId).click(function(){
animate("last",true);
});
function animate(dir,clicked){
var ot = t;
switch(dir){
case "next":
t = (ot>=ts) ? (options.continuous ? 0 : ts) : t+1;
break;
case "prev":
t = (t<=0) ? (options.continuous ? ts : 0) : t-1;
break;
case "first":
t = 0;
break;
case "last":
t = ts;
break;
default:
break;
};
$("#num").html(""+(t+1)+" / "+(ts+1));
var diff = Math.abs(ot-t);
var speed = diff*options.speed;
if(!options.vertical) {
p = (t*w*-1);
$("ul",obj).animate(
{ marginLeft: p },
speed
);
} else {
p = (t*h*-1);
$("ul",obj).animate(
{ marginTop: p },
speed
);
};
if(!options.continuous && options.controlsFade){
if(t==ts){
$("a","#"+options.nextId).hide();
$("a","#"+options.lastId).hide();
} else {
$("a","#"+options.nextId).show();
$("a","#"+options.lastId).show();
};
if(t==0){
$("a","#"+options.prevId).hide();
$("a","#"+options.firstId).hide();
} else {
$("a","#"+options.prevId).show();
$("a","#"+options.firstId).show();
};
};
if(clicked) clearTimeout(timeout);
if(options.auto && dir=="next" && !clicked){;
timeout = setTimeout(function(){
animate("next",false);
},diff*options.speed+options.pause);
};
};
// init
var timeout;
if(options.auto){;
timeout = setTimeout(function(){
animate("next",false);
},options.pause);
};
if(!options.continuous && options.controlsFade){
$("a","#"+options.prevId).hide();
$("a","#"+options.firstId).hide();
};
});
};
})(jQuery);
|
JavaScript
|
/**
* --------------------------------------------------------------------
* jQuery-Plugin "pngFix"
* Version: 1.2, 09.03.2009
* by Andreas Eberhard, andreas.eberhard@gmail.com
* http://jquery.andreaseberhard.de/
*
* Copyright (c) 2007 Andreas Eberhard
* Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
*
* Changelog:
* 09.03.2009 Version 1.2
* - Update for jQuery 1.3.x, removed @ from selectors
* 11.09.2007 Version 1.1
* - removed noConflict
* - added png-support for input type=image
* - 01.08.2007 CSS background-image support extension added by Scott Jehl, scott@filamentgroup.com, http://www.filamentgroup.com
* 31.05.2007 initial Version 1.0
* --------------------------------------------------------------------
* @example $(function(){$(document).pngFix();});
* @desc Fixes all PNG's in the document on document.ready
*
* jQuery(function(){jQuery(document).pngFix();});
* @desc Fixes all PNG's in the document on document.ready when using noConflict
*
* @example $(function(){$('div.examples').pngFix();});
* @desc Fixes all PNG's within div with class examples
*
* @example $(function(){$('div.examples').pngFix( { blankgif:'ext.gif' } );});
* @desc Fixes all PNG's within div with class examples, provides blank gif for input with png
* --------------------------------------------------------------------
*/
(function($) {
jQuery.fn.pngFix = function(settings) {
// Settings
settings = jQuery.extend({
blankgif: 'blank.gif'
}, settings);
var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
if (jQuery.browser.msie && (ie55 || ie6)) {
//fix images with png-source
jQuery(this).find("img[src$=.png]").each(function() {
jQuery(this).attr('width',jQuery(this).width());
jQuery(this).attr('height',jQuery(this).height());
var prevStyle = '';
var strNewHTML = '';
var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
if (this.style.border) {
prevStyle += 'border:'+this.style.border+';';
this.style.border = '';
}
if (this.style.padding) {
prevStyle += 'padding:'+this.style.padding+';';
this.style.padding = '';
}
if (this.style.margin) {
prevStyle += 'margin:'+this.style.margin+';';
this.style.margin = '';
}
var imgStyle = (this.style.cssText);
strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
strNewHTML += imgStyle+'"></span>';
if (prevStyle != ''){
strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
}
jQuery(this).hide();
jQuery(this).after(strNewHTML);
});
// fix css background pngs
jQuery(this).find("*").each(function(){
var bgIMG = jQuery(this).css('background-image');
if(bgIMG.indexOf(".png")!=-1){
var iebg = bgIMG.split('url("')[1].split('")')[0];
jQuery(this).css('background-image', 'none');
jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
}
});
//fix input with png-source
jQuery(this).find("input[src$=.png]").each(function() {
var bgIMG = jQuery(this).attr('src');
jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
jQuery(this).attr('src', settings.blankgif)
});
}
return jQuery;
};
})(jQuery);
|
JavaScript
|
// Simple Set Clipboard System
// Author: Joseph Huckaby
var ZeroClipboard = {
version: "1.0.7",
clients: {}, // registered upload clients on page, indexed by id
moviePath: 'ZeroClipboard.swf', // URL to movie
nextId: 1, // ID of next movie
$: function(thingy) {
// simple DOM lookup utility function
if (typeof(thingy) == 'string') thingy = document.getElementById(thingy);
if (!thingy.addClass) {
// extend element with a few useful methods
thingy.hide = function() { this.style.display = 'none'; };
thingy.show = function() { this.style.display = ''; };
thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; };
thingy.removeClass = function(name) {
var classes = this.className.split(/\s+/);
var idx = -1;
for (var k = 0; k < classes.length; k++) {
if (classes[k] == name) { idx = k; k = classes.length; }
}
if (idx > -1) {
classes.splice( idx, 1 );
this.className = classes.join(' ');
}
return this;
};
thingy.hasClass = function(name) {
return !!this.className.match( new RegExp("\\s*" + name + "\\s*") );
};
}
return thingy;
},
setMoviePath: function(path) {
// set path to ZeroClipboard.swf
this.moviePath = path;
},
dispatch: function(id, eventName, args) {
// receive event from flash movie, send to client
var client = this.clients[id];
if (client) {
client.receiveEvent(eventName, args);
}
},
register: function(id, client) {
// register new client to receive events
this.clients[id] = client;
},
getDOMObjectPosition: function(obj, stopObj) {
// get absolute coordinates for dom element
var info = {
left: 0,
top: 0,
width: obj.width ? obj.width : obj.offsetWidth,
height: obj.height ? obj.height : obj.offsetHeight
};
while (obj && (obj != stopObj)) {
info.left += obj.offsetLeft;
info.top += obj.offsetTop;
obj = obj.offsetParent;
}
return info;
},
Client: function(elem) {
// constructor for new simple upload client
this.handlers = {};
// unique ID
this.id = ZeroClipboard.nextId++;
this.movieId = 'ZeroClipboardMovie_' + this.id;
// register client with singleton to receive flash events
ZeroClipboard.register(this.id, this);
// create movie
if (elem) this.glue(elem);
}
};
ZeroClipboard.Client.prototype = {
id: 0, // unique ID for us
ready: false, // whether movie is ready to receive events or not
movie: null, // reference to movie object
clipText: '', // text to copy to clipboard
handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor
cssEffects: true, // enable CSS mouse effects on dom container
handlers: null, // user event handlers
glue: function(elem, appendElem, stylesToAdd) {
// glue to DOM element
// elem can be ID or actual DOM element object
this.domElement = ZeroClipboard.$(elem);
// float just above object, or zIndex 99 if dom element isn't set
var zIndex = 99;
if (this.domElement.style.zIndex) {
zIndex = parseInt(this.domElement.style.zIndex, 10) + 1;
}
if (typeof(appendElem) == 'string') {
appendElem = ZeroClipboard.$(appendElem);
}
else if (typeof(appendElem) == 'undefined') {
appendElem = document.getElementsByTagName('body')[0];
}
// find X/Y position of domElement
var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem);
// create floating DIV above element
this.div = document.createElement('div');
var style = this.div.style;
style.position = 'absolute';
style.left = '' + box.left + 'px';
style.top = '' + box.top + 'px';
style.width = '' + box.width + 'px';
style.height = '' + box.height + 'px';
style.zIndex = zIndex;
if (typeof(stylesToAdd) == 'object') {
for (addedStyle in stylesToAdd) {
style[addedStyle] = stylesToAdd[addedStyle];
}
}
// style.backgroundColor = '#f00'; // debug
appendElem.appendChild(this.div);
this.div.innerHTML = this.getHTML( box.width, box.height );
},
getHTML: function(width, height) {
// return HTML for movie
var html = '';
var flashvars = 'id=' + this.id +
'&width=' + width +
'&height=' + height;
if (navigator.userAgent.match(/MSIE/)) {
// IE gets an OBJECT tag
var protocol = location.href.match(/^https/i) ? 'https://' : 'http://';
html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>';
}
else {
// all other browsers get an EMBED tag
html += '<embed id="'+this.movieId+'" src="'+ZeroClipboard.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />';
}
return html;
},
hide: function() {
// temporarily hide floater offscreen
if (this.div) {
this.div.style.left = '-2000px';
}
},
show: function() {
// show ourselves after a call to hide()
this.reposition();
},
destroy: function() {
// destroy control and floater
if (this.domElement && this.div) {
this.hide();
this.div.innerHTML = '';
var body = document.getElementsByTagName('body')[0];
try { body.removeChild( this.div ); } catch(e) {;}
this.domElement = null;
this.div = null;
}
},
reposition: function(elem) {
// reposition our floating div, optionally to new container
// warning: container CANNOT change size, only position
if (elem) {
this.domElement = ZeroClipboard.$(elem);
if (!this.domElement) this.hide();
}
if (this.domElement && this.div) {
var box = ZeroClipboard.getDOMObjectPosition(this.domElement);
var style = this.div.style;
style.left = '' + box.left + 'px';
style.top = '' + box.top + 'px';
}
},
setText: function(newText) {
// set text to be copied to clipboard
this.clipText = newText;
if (this.ready) this.movie.setText(newText);
},
addEventListener: function(eventName, func) {
// add user event listener for event
// event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel
eventName = eventName.toString().toLowerCase().replace(/^on/, '');
if (!this.handlers[eventName]) this.handlers[eventName] = [];
this.handlers[eventName].push(func);
},
setHandCursor: function(enabled) {
// enable hand cursor (true), or default arrow cursor (false)
this.handCursorEnabled = enabled;
if (this.ready) this.movie.setHandCursor(enabled);
},
setCSSEffects: function(enabled) {
// enable or disable CSS effects on DOM container
this.cssEffects = !!enabled;
},
receiveEvent: function(eventName, args) {
// receive event from flash
eventName = eventName.toString().toLowerCase().replace(/^on/, '');
// special behavior for certain events
switch (eventName) {
case 'load':
// movie claims it is ready, but in IE this isn't always the case...
// bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function
this.movie = document.getElementById(this.movieId);
if (!this.movie) {
var self = this;
setTimeout( function() { self.receiveEvent('load', null); }, 1 );
return;
}
// firefox on pc needs a "kick" in order to set these in certain cases
if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) {
var self = this;
setTimeout( function() { self.receiveEvent('load', null); }, 100 );
this.ready = true;
return;
}
this.ready = true;
this.movie.setText( this.clipText );
this.movie.setHandCursor( this.handCursorEnabled );
break;
case 'mouseover':
if (this.domElement && this.cssEffects) {
this.domElement.addClass('hover');
if (this.recoverActive) this.domElement.addClass('active');
}
break;
case 'mouseout':
if (this.domElement && this.cssEffects) {
this.recoverActive = false;
if (this.domElement.hasClass('active')) {
this.domElement.removeClass('active');
this.recoverActive = true;
}
this.domElement.removeClass('hover');
}
break;
case 'mousedown':
if (this.domElement && this.cssEffects) {
this.domElement.addClass('active');
}
break;
case 'mouseup':
if (this.domElement && this.cssEffects) {
this.domElement.removeClass('active');
this.recoverActive = false;
}
break;
} // switch eventName
if (this.handlers[eventName]) {
for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) {
var func = this.handlers[eventName][idx];
if (typeof(func) == 'function') {
// actual function reference
func(this, args);
}
else if ((typeof(func) == 'object') && (func.length == 2)) {
// PHP style object + method, i.e. [myObject, 'myMethod']
func[0][ func[1] ](this, args);
}
else if (typeof(func) == 'string') {
// name of function
window[func](this, args);
}
} // foreach event handler defined
} // user defined handler for event
}
};
|
JavaScript
|
/*
* jQuery Color Animations
* Copyright 2007 John Resig
* Released under the MIT and GPL licenses.
*/
(function(jQuery){
// We override the animation for all of these color styles
jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
jQuery.fx.step[attr] = function(fx){
if ( fx.colorFunction == undefined || fx.state == 0 ) {
fx.start = getColor( fx.elem, attr );
fx.end = getRGB( fx.end );
if ( fx.start == undefined ) {
fx.start = [ 255,255,255,0 ];
} else {
if ( fx.start[3] == undefined ) // if alpha channel is not spotted
fx.start[3] = 1; // assume it is fully opaque
if ( fx.start[3] == 0 ) // if alpha is present and fully transparent
fx.start[0] = fx.start[1] = fx.start[2] = 255; // assume starting with white
}
if ( fx.end[3] == undefined ) // if alpha channel is not spotted
fx.end[3] = 1; // assume it is fully opaque
fx.colorFunction = ( fx.start[3] == 1 && fx.end[3] == 1 ? calcRGB : calcRGBa );
}
fx.elem.style[attr] = fx.colorFunction();
}
});
var calcRGB = function() {
return 'rgb(' +
Math.max(Math.min( parseInt((this.pos * (this.end[0] - this.start[0])) + this.start[0]), 255), 0) + ',' +
Math.max(Math.min( parseInt((this.pos * (this.end[1] - this.start[1])) + this.start[1]), 255), 0) + ',' +
Math.max(Math.min( parseInt((this.pos * (this.end[2] - this.start[2])) + this.start[2]), 255), 0) + ')';
};
var calcRGBa = function() {
return 'rgba(' +
Math.max(Math.min( parseInt((this.pos * (this.end[0] - this.start[0])) + this.start[0]), 255), 0) + ',' +
Math.max(Math.min( parseInt((this.pos * (this.end[1] - this.start[1])) + this.start[1]), 255), 0) + ',' +
Math.max(Math.min( parseInt((this.pos * (this.end[2] - this.start[2])) + this.start[2]), 255), 0) + ',' +
Math.max(Math.min( parseFloat((this.pos * (this.end[3] - this.start[3])) + this.start[3]), 1), 0) + ')';
};
// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/
// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
var result;
// Check if we're already dealing with an array of colors
if ( color && color.constructor == Array && color.length >= 3 )
return color;
// Look for rgb(num,num,num)
if (result = /rgba?\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,?\s*((?:[0-9](?:\.[0-9]+)?)?)\s*\)/.exec(color))
return [ parseInt(result[1]), parseInt(result[2]), parseInt(result[3]), parseFloat(result[4]||1) ];
// Look for rgb(num%,num%,num%)
if (result = /rgba?\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,?\s*((?:[0-9](?:\.[0-9]+)?)?)\s*\)/.exec(color))
return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55, parseFloat(result[4]||1)];
// Look for #a0b1c2
if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
// Look for #fff
if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
// Otherwise, we're most likely dealing with a named color
var colorName = jQuery.trim(color).toLowerCase();
if ( colors[colorName] != undefined )
return colors[colorName];
return [ 255, 255, 255, 0 ];
}
function getColor(elem, attr) {
var color;
do {
color = jQuery.curCSS(elem, attr);
// Keep going until we find an element that has color, or we hit the body
if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
break;
attr = "backgroundColor";
} while ( elem = elem.parentNode );
return getRGB(color);
};
// Some named colors to work with
// From Interface by Stefan Petre
// http://interface.eyecon.ro/
var colors = {
aqua:[0,255,255],
azure:[240,255,255],
beige:[245,245,220],
black:[0,0,0],
blue:[0,0,255],
brown:[165,42,42],
cyan:[0,255,255],
darkblue:[0,0,139],
darkcyan:[0,139,139],
darkgrey:[169,169,169],
darkgreen:[0,100,0],
darkkhaki:[189,183,107],
darkmagenta:[139,0,139],
darkolivegreen:[85,107,47],
darkorange:[255,140,0],
darkorchid:[153,50,204],
darkred:[139,0,0],
darksalmon:[233,150,122],
darkviolet:[148,0,211],
fuchsia:[255,0,255],
gold:[255,215,0],
green:[0,128,0],
indigo:[75,0,130],
khaki:[240,230,140],
lightblue:[173,216,230],
lightcyan:[224,255,255],
lightgreen:[144,238,144],
lightgrey:[211,211,211],
lightpink:[255,182,193],
lightyellow:[255,255,224],
lime:[0,255,0],
magenta:[255,0,255],
maroon:[128,0,0],
navy:[0,0,128],
olive:[128,128,0],
orange:[255,165,0],
pink:[255,192,203],
purple:[128,0,128],
violet:[128,0,128],
red:[255,0,0],
silver:[192,192,192],
white:[255,255,255],
yellow:[255,255,0]
};
})(jQuery);
|
JavaScript
|
function flash(url,w,h,bg,win,vars){
var s=
"<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://www.yongtu.net/swflash.cab#version=8,0,0,0' width='"+w+"' height='"+h+"' align='middle'>"+
"<param name='movie' value='"+url+"' />"+
"<param name='wmode' value='"+win+"' />"+
"<param name='quality' value='high' />"+
"<param name='FlashVars' value='"+vars+"' />"+
"<param name='bgcolor' value='"+bg+"' />"+
"<embed src='"+url+"' wmode='"+win+"' menu='false' quality='high' bgcolor='"+bg+"' width='"+w+"' height='"+h+"' align='middle' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' />"+
"</object>";
document.write(s);
}
|
JavaScript
|
/**
* jquery.scrollFollow.js
* Copyright (c) 2008 Net Perspective (http://kitchen.net-perspective.com/)
* Licensed under the MIT License (http://www.opensource.org/licenses/mit-license.php)
*
* @author R.A. Ray
*
* @projectDescription jQuery plugin for allowing an element to animate down as the user scrolls the page.
*
* @version 0.4.0
*
* @requires jquery.js (tested with 1.2.6)
* @requires ui.core.js (tested with 1.5.2)
*
* @optional jquery.cookie.js (http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/)
* @optional jquery.easing.js (http://gsgd.co.uk/sandbox/jquery/easing/ - tested with 1.3)
*
* @param speed int - Duration of animation (in milliseconds)
* default: 500
* @param offset int - Number of pixels box should remain from top of viewport
* default: 0
* @param easing string - Any one of the easing options from the easing plugin - Requires jQuery Easing Plugin < http://gsgd.co.uk/sandbox/jquery/easing/ >
* default: 'linear'
* @param container string - ID of the containing div
* default: box's immediate parent
* @param killSwitch string - ID of the On/Off toggle element
* default: 'killSwitch'
* @param onText string - killSwitch text to be displayed if sliding is enabled
* default: 'Turn Slide Off'
* @param offText string - killSwitch text to be displayed if sliding is disabled
* default: 'Turn Slide On'
* @param relativeTo string - Scroll animation can be relative to either the 'top' or 'bottom' of the viewport
* default: 'top'
* @param delay int - Time between the end of the scroll and the beginning of the animation in milliseconds
* default: 0
*/
( function( $ ) {
$.scrollFollow = function ( box, options )
{
// Convert box into a jQuery object
box = $( box );
// 'box' is the object to be animated
var position = box.css( 'position' );
function ani()
{
// The script runs on every scroll which really means many times during a scroll.
// We don't want multiple slides to queue up.
box.queue( [ ] );
// A bunch of values we need to determine where to animate to
var viewportHeight = parseInt( $( window ).height() );
var pageScroll = parseInt( $( document ).scrollTop() );
var parentTop = parseInt( box.cont.offset().top);
var parentHeight = parseInt( box.cont.attr( 'offsetHeight' ) );
var boxHeight = parseInt( box.attr( 'offsetHeight' ) + ( parseInt( box.css( 'marginTop' ) ) || 0 ) + ( parseInt( box.css( 'marginBottom' ) ) || 0 ) );
var aniTop;
// Make sure the user wants the animation to happen
if ( isActive )
{
// If the box should animate relative to the top of the window
if ( options.relativeTo == 'top' )
{
// Don't animate until the top of the window is close enough to the top of the box
if ( box.initialOffsetTop >= ( pageScroll + options.offset ) )
{
aniTop = box.initialTop;
}
else
{
aniTop = Math.min( ( Math.max( ( -parentTop ), ( pageScroll - box.initialOffsetTop + box.initialTop ) ) + options.offset ), ( parentHeight - boxHeight - box.paddingAdjustment ) );
}
}
// If the box should animate relative to the bottom of the window
else if ( options.relativeTo == 'bottom' )
{
// Don't animate until the bottom of the window is close enough to the bottom of the box
if ( ( box.initialOffsetTop + boxHeight ) >= ( pageScroll + options.offset + viewportHeight ) )
{
aniTop = box.initialTop;
}
else
{
aniTop = Math.min( ( pageScroll + viewportHeight - boxHeight - options.offset ), ( parentHeight - boxHeight ) );
}
}
// Checks to see if the relevant scroll was the last one
// "-20" is to account for inaccuracy in the timeout
if ( ( new Date().getTime() - box.lastScroll ) >= ( options.delay - 20 ) )
{
box.animate(
{
top: aniTop
}, options.speed, options.easing
);
}
}
};
// For user-initiated stopping of the slide
var isActive = true;
if ( $.cookie != undefined )
{
if( $.cookie( 'scrollFollowSetting' + box.attr( 'id' ) ) == 'false' )
{
var isActive = false;
$( '#' + options.killSwitch ).text( options.offText )
.toggle(
function ()
{
isActive = true;
$( this ).text( options.onText );
$.cookie( 'scrollFollowSetting' + box.attr( 'id' ), true, { expires: 365, path: '/'} );
ani();
},
function ()
{
isActive = false;
$( this ).text( options.offText );
box.animate(
{
top: box.initialTop
}, options.speed, options.easing
);
$.cookie( 'scrollFollowSetting' + box.attr( 'id' ), false, { expires: 365, path: '/'} );
}
);
}
else
{
$( '#' + options.killSwitch ).text( options.onText )
.toggle(
function ()
{
isActive = false;
$( this ).text( options.offText );
box.animate(
{
top: box.initialTop
}, 0
);
$.cookie( 'scrollFollowSetting' + box.attr( 'id' ), false, { expires: 365, path: '/'} );
},
function ()
{
isActive = true;
$( this ).text( options.onText );
$.cookie( 'scrollFollowSetting' + box.attr( 'id' ), true, { expires: 365, path: '/'} );
ani();
}
);
}
}
// If no parent ID was specified, and the immediate parent does not have an ID
// options.container will be undefined. So we need to figure out the parent element.
if ( options.container == '')
{
box.cont = box.parent();
}
else
{
box.cont = $( '#' + options.container );
}
// Finds the default positioning of the box.
box.initialOffsetTop = parseInt( box.offset().top );
box.initialTop = parseInt( box.css( 'top' ) ) || 0;
// Hack to fix different treatment of boxes positioned 'absolute' and 'relative'
if ( box.css( 'position' ) == 'relative' )
{
box.paddingAdjustment = parseInt( box.cont.css( 'paddingTop' ) ) + parseInt( box.cont.css( 'paddingBottom' ) );
}
else
{
box.paddingAdjustment = 0;
}
// Animate the box when the page is scrolled
$( window ).scroll( function ()
{
// Sets up the delay of the animation
$.fn.scrollFollow.interval = setTimeout( function(){ ani();} , options.delay );
// To check against right before setting the animation
box.lastScroll = new Date().getTime();
}
);
// Animate the box when the page is resized
$( window ).resize( function ()
{
// Sets up the delay of the animation
$.fn.scrollFollow.interval = setTimeout( function(){ ani();} , options.delay );
// To check against right before setting the animation
box.lastScroll = new Date().getTime();
}
);
// Run an initial animation on page load
box.lastScroll = 0;
ani();
};
$.fn.scrollFollow = function ( options )
{
options = options || {};
options.relativeTo = options.relativeTo || 'top';
options.speed = options.speed || 500;
options.offset = options.offset || 0;
options.easing = options.easing || 'swing';
options.container = options.container || this.parent().attr( 'id' );
options.killSwitch = options.killSwitch || 'killSwitch';
options.onText = options.onText || 'Turn Slide Off';
options.offText = options.offText || 'Turn Slide On';
options.delay = options.delay || 0;
this.each( function()
{
new $.scrollFollow( this, options );
}
);
return this;
};
})( jQuery );
|
JavaScript
|
var phpcms_path = '/';
var cookie_pre = 'sYQDUGqqzH';
var cookie_domain = '';
var cookie_path = '/';
function getcookie(name) {
name = cookie_pre+name;
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while(i < clen) {
var j = i + alen;
if(document.cookie.substring(i, j) == arg) return getcookieval(j);
i = document.cookie.indexOf(" ", i) + 1;
if(i == 0) break;
}
return null;
}
function setcookie(name, value, days) {
name = cookie_pre+name;
var argc = setcookie.arguments.length;
var argv = setcookie.arguments;
var secure = (argc > 5) ? argv[5] : false;
var expire = new Date();
if(days==null || days==0) days=1;
expire.setTime(expire.getTime() + 3600000*24*days);
document.cookie = name + "=" + escape(value) + ("; path=" + cookie_path) + ((cookie_domain == '') ? "" : ("; domain=" + cookie_domain)) + ((secure == true) ? "; secure" : "") + ";expires="+expire.toGMTString();
}
function delcookie(name) {
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = getcookie(name);
name = cookie_pre+name;
document.cookie = name+"="+cval+";expires="+exp.toGMTString();
}
function getcookieval(offset) {
var endstr = document.cookie.indexOf (";", offset);
if(endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
|
JavaScript
|
/* Copyright (c) 2009 Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* See http://kelvinluck.com/assets/jquery/jScrollPane/
* $Id: jScrollPane.js 93 2010-06-01 08:17:28Z kelvin.luck $
*/
/**
* Replace the vertical scroll bars on any matched elements with a fancy
* styleable (via CSS) version. With JS disabled the elements will
* gracefully degrade to the browsers own implementation of overflow:auto.
* If the mousewheel plugin has been included on the page then the scrollable areas will also
* respond to the mouse wheel.
*
* @example jQuery(".scroll-pane").jScrollPane();
*
* @name jScrollPane
* @type jQuery
* @param Object settings hash with options, described below.
* scrollbarWidth - The width of the generated scrollbar in pixels
* scrollbarMargin - The amount of space to leave on the side of the scrollbar in pixels
* wheelSpeed - The speed the pane will scroll in response to the mouse wheel in pixels
* showArrows - Whether to display arrows for the user to scroll with
* arrowSize - The height of the arrow buttons if showArrows=true
* animateTo - Whether to animate when calling scrollTo and scrollBy
* dragMinHeight - The minimum height to allow the drag bar to be
* dragMaxHeight - The maximum height to allow the drag bar to be
* animateInterval - The interval in milliseconds to update an animating scrollPane (default 100)
* animateStep - The amount to divide the remaining scroll distance by when animating (default 3)
* maintainPosition- Whether you want the contents of the scroll pane to maintain it's position when you re-initialise it - so it doesn't scroll as you add more content (default true)
* tabIndex - The tabindex for this jScrollPane to control when it is tabbed to when navigating via keyboard (default 0)
* enableKeyboardNavigation - Whether to allow keyboard scrolling of this jScrollPane when it is focused (default true)
* animateToInternalLinks - Whether the move to an internal link (e.g. when it's focused by tabbing or by a hash change in the URL) should be animated or instant (default false)
* scrollbarOnLeft - Display the scrollbar on the left side? (needs stylesheet changes, see examples.html)
* reinitialiseOnImageLoad - Whether the jScrollPane should automatically re-initialise itself when any contained images are loaded (default false)
* topCapHeight - The height of the "cap" area between the top of the jScrollPane and the top of the track/ buttons
* bottomCapHeight - The height of the "cap" area between the bottom of the jScrollPane and the bottom of the track/ buttons
* observeHash - Whether jScrollPane should attempt to automagically scroll to the correct place when an anchor inside the scrollpane is linked to (default true)
* @return jQuery
* @cat Plugins/jScrollPane
* @author Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
*/
(function($) {
$.jScrollPane = {
active : []
};
$.fn.jScrollPane = function(settings)
{
settings = $.extend({}, $.fn.jScrollPane.defaults, settings);
var rf = function() { return false; };
return this.each(
function()
{
var $this = $(this);
var paneEle = this;
var currentScrollPosition = 0;
var paneWidth;
var paneHeight;
var trackHeight;
var trackOffset = settings.topCapHeight;
var $container;
if ($(this).parent().is('.jScrollPaneContainer')) {
$container = $(this).parent();
currentScrollPosition = settings.maintainPosition ? $this.position().top : 0;
var $c = $(this).parent();
paneWidth = $c.innerWidth();
paneHeight = $c.outerHeight();
$('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown, >.jScrollCap', $c).remove();
$this.css({'top':0});
} else {
$this.data('originalStyleTag', $this.attr('style'));
// Switch the element's overflow to hidden to ensure we get the size of the element without the scrollbars [http://plugins.jquery.com/node/1208]
$this.css('overflow', 'hidden');
this.originalPadding = $this.css('paddingTop') + ' ' + $this.css('paddingRight') + ' ' + $this.css('paddingBottom') + ' ' + $this.css('paddingLeft');
this.originalSidePaddingTotal = (parseInt($this.css('paddingLeft')) || 0) + (parseInt($this.css('paddingRight')) || 0);
paneWidth = $this.innerWidth();
paneHeight = $this.innerHeight();
$container = $('<div></div>')
.attr({'className':'jScrollPaneContainer'})
.css(
{
'height':paneHeight+'px',
'width':paneWidth+'px'
}
);
if (settings.enableKeyboardNavigation) {
$container.attr(
'tabindex',
settings.tabIndex
);
}
$this.wrap($container);
$container = $this.parent();
// deal with text size changes (if the jquery.em plugin is included)
// and re-initialise the scrollPane so the track maintains the
// correct size
$(document).bind(
'emchange',
function(e, cur, prev)
{
$this.jScrollPane(settings);
}
);
}
trackHeight = paneHeight;
if (settings.reinitialiseOnImageLoad) {
// code inspired by jquery.onImagesLoad: http://plugins.jquery.com/project/onImagesLoad
// except we re-initialise the scroll pane when each image loads so that the scroll pane is always up to size...
// TODO: Do I even need to store it in $.data? Is a local variable here the same since I don't pass the reinitialiseOnImageLoad when I re-initialise?
var $imagesToLoad = $.data(paneEle, 'jScrollPaneImagesToLoad') || $('img', $this);
var loadedImages = [];
if ($imagesToLoad.length) {
$imagesToLoad.each(function(i, val) {
$(this).bind('load readystatechange', function() {
if($.inArray(i, loadedImages) == -1){ //don't double count images
loadedImages.push(val); //keep a record of images we've seen
$imagesToLoad = $.grep($imagesToLoad, function(n, i) {
return n != val;
});
$.data(paneEle, 'jScrollPaneImagesToLoad', $imagesToLoad);
var s2 = $.extend(settings, {reinitialiseOnImageLoad:false});
$this.jScrollPane(s2); // re-initialise
}
}).each(function(i, val) {
if(this.complete || this.complete===undefined) {
//needed for potential cached images
this.src = this.src;
}
});
});
};
}
var p = this.originalSidePaddingTotal;
var realPaneWidth = paneWidth - settings.scrollbarWidth - settings.scrollbarMargin - p;
var cssToApply = {
'height':'auto',
'width': realPaneWidth + 'px'
}
if(settings.scrollbarOnLeft) {
cssToApply.paddingLeft = settings.scrollbarMargin + settings.scrollbarWidth + 'px';
} else {
cssToApply.paddingRight = settings.scrollbarMargin + 'px';
}
$this.css(cssToApply);
var contentHeight = $this.outerHeight();
var percentInView = paneHeight / contentHeight;
var isScrollable = percentInView < .99;
$container[isScrollable ? 'addClass' : 'removeClass']('jScrollPaneScrollable');
if (isScrollable) {
$container.append(
$('<div></div>').addClass('jScrollCap jScrollCapTop').css({height:settings.topCapHeight}),
$('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append(
$('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append(
$('<div></div>').attr({'className':'jScrollPaneDragTop'}).css({'width':settings.scrollbarWidth+'px'}),
$('<div></div>').attr({'className':'jScrollPaneDragBottom'}).css({'width':settings.scrollbarWidth+'px'})
)
),
$('<div></div>').addClass('jScrollCap jScrollCapBottom').css({height:settings.bottomCapHeight})
);
var $track = $('>.jScrollPaneTrack', $container);
var $drag = $('>.jScrollPaneTrack .jScrollPaneDrag', $container);
var currentArrowDirection;
var currentArrowTimerArr = [];// Array is used to store timers since they can stack up when dealing with keyboard events. This ensures all timers are cleaned up in the end, preventing an acceleration bug.
var currentArrowInc;
var whileArrowButtonDown = function()
{
if (currentArrowInc > 4 || currentArrowInc % 4 == 0) {
positionDrag(dragPosition + currentArrowDirection * mouseWheelMultiplier);
}
currentArrowInc++;
};
if (settings.enableKeyboardNavigation) {
$container.bind(
'keydown.jscrollpane',
function(e)
{
switch (e.keyCode) {
case 38: //up
currentArrowDirection = -1;
currentArrowInc = 0;
whileArrowButtonDown();
currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
return false;
case 40: //down
currentArrowDirection = 1;
currentArrowInc = 0;
whileArrowButtonDown();
currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
return false;
case 33: // page up
case 34: // page down
// TODO
return false;
default:
}
}
).bind(
'keyup.jscrollpane',
function(e)
{
if (e.keyCode == 38 || e.keyCode == 40) {
for (var i = 0; i < currentArrowTimerArr.length; i++) {
clearInterval(currentArrowTimerArr[i]);
}
return false;
}
}
);
}
if (settings.showArrows) {
var currentArrowButton;
var currentArrowInterval;
var onArrowMouseUp = function(event)
{
$('html').unbind('mouseup', onArrowMouseUp);
currentArrowButton.removeClass('jScrollActiveArrowButton');
clearInterval(currentArrowInterval);
};
var onArrowMouseDown = function() {
$('html').bind('mouseup', onArrowMouseUp);
currentArrowButton.addClass('jScrollActiveArrowButton');
currentArrowInc = 0;
whileArrowButtonDown();
currentArrowInterval = setInterval(whileArrowButtonDown, 100);
};
$container
.append(
$('<a></a>')
.attr(
{
'href':'javascript:;',
'className':'jScrollArrowUp',
'tabindex':-1
}
)
.css(
{
'width':settings.scrollbarWidth+'px',
'top':settings.topCapHeight + 'px'
}
)
.html('Scroll up')
.bind('mousedown', function()
{
currentArrowButton = $(this);
currentArrowDirection = -1;
onArrowMouseDown();
this.blur();
return false;
})
.bind('click', rf),
$('<a></a>')
.attr(
{
'href':'javascript:;',
'className':'jScrollArrowDown',
'tabindex':-1
}
)
.css(
{
'width':settings.scrollbarWidth+'px',
'bottom':settings.bottomCapHeight + 'px'
}
)
.html('Scroll down')
.bind('mousedown', function()
{
currentArrowButton = $(this);
currentArrowDirection = 1;
onArrowMouseDown();
this.blur();
return false;
})
.bind('click', rf)
);
var $upArrow = $('>.jScrollArrowUp', $container);
var $downArrow = $('>.jScrollArrowDown', $container);
}
if (settings.arrowSize) {
trackHeight = paneHeight - settings.arrowSize - settings.arrowSize;
trackOffset += settings.arrowSize;
} else if ($upArrow) {
var topArrowHeight = $upArrow.height();
settings.arrowSize = topArrowHeight;
trackHeight = paneHeight - topArrowHeight - $downArrow.height();
trackOffset += topArrowHeight;
}
trackHeight -= settings.topCapHeight + settings.bottomCapHeight;
$track.css({'height': trackHeight+'px', top:trackOffset+'px'})
var $pane = $(this).css({'position':'absolute', 'overflow':'visible'});
var currentOffset;
var maxY;
var mouseWheelMultiplier;
// store this in a seperate variable so we can keep track more accurately than just updating the css property..
var dragPosition = 0;
var dragMiddle = percentInView*paneHeight/2;
// pos function borrowed from tooltip plugin and adapted...
var getPos = function (event, c) {
var p = c == 'X' ? 'Left' : 'Top';
return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
};
var ignoreNativeDrag = function() { return false; };
var initDrag = function()
{
ceaseAnimation();
currentOffset = $drag.offset(false);
currentOffset.top -= dragPosition;
maxY = trackHeight - $drag[0].offsetHeight;
mouseWheelMultiplier = 2 * settings.wheelSpeed * maxY / contentHeight;
};
var onStartDrag = function(event)
{
initDrag();
dragMiddle = getPos(event, 'Y') - dragPosition - currentOffset.top;
$('html').bind('mouseup', onStopDrag).bind('mousemove', updateScroll).bind('mouseleave', onStopDrag)
if ($.browser.msie) {
$('html').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag);
}
return false;
};
var onStopDrag = function()
{
$('html').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll);
dragMiddle = percentInView*paneHeight/2;
if ($.browser.msie) {
$('html').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag);
}
};
var positionDrag = function(destY)
{
$container.scrollTop(0);
destY = destY < 0 ? 0 : (destY > maxY ? maxY : destY);
dragPosition = destY;
$drag.css({'top':destY+'px'});
var p = destY / maxY;
$this.data('jScrollPanePosition', (paneHeight-contentHeight)*-p);
$pane.css({'top':((paneHeight-contentHeight)*p) + 'px'});
$this.trigger('scroll');
if (settings.showArrows) {
$upArrow[destY == 0 ? 'addClass' : 'removeClass']('disabled');
$downArrow[destY == maxY ? 'addClass' : 'removeClass']('disabled');
}
};
var updateScroll = function(e)
{
positionDrag(getPos(e, 'Y') - currentOffset.top - dragMiddle);
};
var dragH = Math.max(Math.min(percentInView*(paneHeight-settings.arrowSize*2), settings.dragMaxHeight), settings.dragMinHeight);
$drag.css(
{'height':dragH+'px'}
).bind('mousedown', onStartDrag);
var trackScrollInterval;
var trackScrollInc;
var trackScrollMousePos;
var doTrackScroll = function()
{
if (trackScrollInc > 8 || trackScrollInc%4==0) {
positionDrag((dragPosition - ((dragPosition - trackScrollMousePos) / 2)));
}
trackScrollInc ++;
};
var onStopTrackClick = function()
{
clearInterval(trackScrollInterval);
$('html').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove);
};
var onTrackMouseMove = function(event)
{
trackScrollMousePos = getPos(event, 'Y') - currentOffset.top - dragMiddle;
};
var onTrackClick = function(event)
{
initDrag();
onTrackMouseMove(event);
trackScrollInc = 0;
$('html').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
trackScrollInterval = setInterval(doTrackScroll, 100);
doTrackScroll();
return false;
};
$track.bind('mousedown', onTrackClick);
$container.bind(
'mousewheel',
function (event, delta) {
delta = delta || (event.wheelDelta ? event.wheelDelta / 120 : (event.detail) ?
-event.detail/3 : 0);
initDrag();
ceaseAnimation();
var d = dragPosition;
positionDrag(dragPosition - delta * mouseWheelMultiplier);
var dragOccured = d != dragPosition;
return !dragOccured;
}
);
var _animateToPosition;
var _animateToInterval;
function animateToPosition()
{
var diff = (_animateToPosition - dragPosition) / settings.animateStep;
if (diff > 1 || diff < -1) {
positionDrag(dragPosition + diff);
} else {
positionDrag(_animateToPosition);
ceaseAnimation();
}
}
var ceaseAnimation = function()
{
if (_animateToInterval) {
clearInterval(_animateToInterval);
delete _animateToPosition;
}
};
var scrollTo = function(pos, preventAni)
{
if (typeof pos == "string") {
// Legal hash values aren't necessarily legal jQuery selectors so we need to catch any
// errors from the lookup...
try {
$e = $(pos, $this);
} catch (err) {
return;
}
if (!$e.length) return;
pos = $e.offset().top - $this.offset().top;
}
ceaseAnimation();
var maxScroll = contentHeight - paneHeight;
pos = pos > maxScroll ? maxScroll : pos;
$this.data('jScrollPaneMaxScroll', maxScroll);
var destDragPosition = pos/maxScroll * maxY;
if (preventAni || !settings.animateTo) {
positionDrag(destDragPosition);
} else {
$container.scrollTop(0);
_animateToPosition = destDragPosition;
_animateToInterval = setInterval(animateToPosition, settings.animateInterval);
}
};
$this[0].scrollTo = scrollTo;
$this[0].scrollBy = function(delta)
{
var currentPos = -parseInt($pane.css('top')) || 0;
scrollTo(currentPos + delta);
};
initDrag();
scrollTo(-currentScrollPosition, true);
// Deal with it when the user tabs to a link or form element within this scrollpane
$('*', this).bind(
'focus',
function(event)
{
var $e = $(this);
// loop through parents adding the offset top of any elements that are relatively positioned between
// the focused element and the jScrollPaneContainer so we can get the true distance from the top
// of the focused element to the top of the scrollpane...
var eleTop = 0;
var preventInfiniteLoop = 100;
while ($e[0] != $this[0]) {
eleTop += $e.position().top;
$e = $e.offsetParent();
if (!preventInfiniteLoop--) {
return;
}
}
var viewportTop = -parseInt($pane.css('top')) || 0;
var maxVisibleEleTop = viewportTop + paneHeight;
var eleInView = eleTop > viewportTop && eleTop < maxVisibleEleTop;
if (!eleInView) {
var destPos = eleTop - settings.scrollbarMargin;
if (eleTop > viewportTop) { // element is below viewport - scroll so it is at bottom.
destPos += $(this).height() + 15 + settings.scrollbarMargin - paneHeight;
}
scrollTo(destPos);
}
}
)
if (settings.observeHash) {
if (location.hash && location.hash.length > 1) {
setTimeout(function(){
scrollTo(location.hash);
}, $.browser.safari ? 100 : 0);
}
// use event delegation to listen for all clicks on links and hijack them if they are links to
// anchors within our content...
$(document).bind('click', function(e){
$target = $(e.target);
if ($target.is('a')) {
var h = $target.attr('href');
if (h && h.substr(0, 1) == '#' && h.length > 1) {
setTimeout(function(){
scrollTo(h, !settings.animateToInternalLinks);
}, $.browser.safari ? 100 : 0);
}
}
});
}
// Deal with dragging and selecting text to make the scrollpane scroll...
function onSelectScrollMouseDown(e)
{
$(document).bind('mousemove.jScrollPaneDragging', onTextSelectionScrollMouseMove);
$(document).bind('mouseup.jScrollPaneDragging', onSelectScrollMouseUp);
}
var textDragDistanceAway;
var textSelectionInterval;
function onTextSelectionInterval()
{
direction = textDragDistanceAway < 0 ? -1 : 1;
$this[0].scrollBy(textDragDistanceAway / 2);
}
function clearTextSelectionInterval()
{
if (textSelectionInterval) {
clearInterval(textSelectionInterval);
textSelectionInterval = undefined;
}
}
function onTextSelectionScrollMouseMove(e)
{
var offset = $this.parent().offset().top;
var maxOffset = offset + paneHeight;
var mouseOffset = getPos(e, 'Y');
textDragDistanceAway = mouseOffset < offset ? mouseOffset - offset : (mouseOffset > maxOffset ? mouseOffset - maxOffset : 0);
if (textDragDistanceAway == 0) {
clearTextSelectionInterval();
} else {
if (!textSelectionInterval) {
textSelectionInterval = setInterval(onTextSelectionInterval, 100);
}
}
}
function onSelectScrollMouseUp(e)
{
$(document)
.unbind('mousemove.jScrollPaneDragging')
.unbind('mouseup.jScrollPaneDragging');
clearTextSelectionInterval();
}
$container.bind('mousedown.jScrollPane', onSelectScrollMouseDown);
$.jScrollPane.active.push($this[0]);
} else {
$this.css(
{
'height':paneHeight+'px',
'width':paneWidth-this.originalSidePaddingTotal+'px',
'padding':this.originalPadding
}
);
$this[0].scrollTo = $this[0].scrollBy = function() {};
// clean up listeners
$this.parent().unbind('mousewheel').unbind('mousedown.jScrollPane').unbind('keydown.jscrollpane').unbind('keyup.jscrollpane');
}
}
)
};
$.fn.jScrollPaneRemove = function()
{
$(this).each(function()
{
$this = $(this);
var $c = $this.parent();
if ($c.is('.jScrollPaneContainer')) {
$this.css(
{
'top':'',
'height':'',
'width':'',
'padding':'',
'overflow':'',
'position':''
}
);
$this.attr('style', $this.data('originalStyleTag'));
$c.after($this).remove();
}
});
}
$.fn.jScrollPane.defaults = {
scrollbarWidth : 10,
scrollbarMargin : 5,
wheelSpeed : 18,
showArrows : false,
arrowSize : 0,
animateTo : false,
dragMinHeight : 1,
dragMaxHeight : 99999,
animateInterval : 100,
animateStep: 3,
maintainPosition: true,
scrollbarOnLeft: false,
reinitialiseOnImageLoad: false,
tabIndex : 0,
enableKeyboardNavigation: true,
animateToInternalLinks: false,
topCapHeight: 0,
bottomCapHeight: 0,
observeHash: true
};
// clean up the scrollTo expandos
$(window)
.bind('unload', function() {
var els = $.jScrollPane.active;
for (var i=0; i<els.length; i++) {
els[i].scrollTo = els[i].scrollBy = null;
}
}
);
})(jQuery);
|
JavaScript
|
/**
* 会员中心公用js
*
*/
/**
* 隐藏html element
*/
function hide_element(name) {
$('#'+name+'').fadeOut("slow");
}
/**
* 显示html element
*/
function show_element(name) {
$('#'+name+'').fadeIn("slow");
}
$(document).ready(function(){
$("input.input-text").blur(function () { this.className='input-text'; } );
$("input.input-text',input[type='password'],textarea").focus(function () { this.className='input-focus'; } );
});
/**
* url跳转
*/
function redirect(url) {
if(url.indexOf('://') == -1 && url.substr(0, 1) != '/' && url.substr(0, 1) != '?') url = $('base').attr('href')+url;
location.href = url;
}
function thumb_images(uploadid,returnid) {
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#att-status").html().substring(1);
if(in_content=='') return false;
if($('#'+returnid+'_preview').attr('src')) {
$('#'+returnid+'_preview').attr('src',in_content);
}
$('#'+returnid).val(in_content);
}
function change_images(uploadid,returnid){
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#att-status").html().substring(1);
var str = $('#'+returnid).html();
var contents = in_content.split('|');
$('#'+returnid+'_tips').css('display','none');
$.each( contents, function(i, n) {
var ids = parseInt(Math.random() * 10000 + 10*i);
str += "<div id='image"+ids+"'><input type='text' name='"+returnid+"_url[]' value='"+n+"' style='width:360px;' ondblclick='image_priview(this.value);' class='input-text'> <input type='text' name='"+returnid+"_alt[]' value='图片说明"+(i+1)+"' style='width:100px;' class='input-text' onfocus=\"if(this.value == this.defaultValue) this.value = ''\" onblur=\"if(this.value.replace(' ','') == '') this.value = this.defaultValue;\"> <a href=\"javascript:remove_div('image"+ids+"')\">移除</a> </div><div class='bk10'></div>";
});
$('#'+returnid).html(str);
}
function image_priview(img) {
window.top.art.dialog({title:'图片查看',fixed:true, content:'<img src="'+img+'" />',id:'image_priview',time:5});
}
function remove_div(id) {
$('#'+id).html(' ');
}
function select_catids() {
$('#addbutton').attr('disabled','');
}
//商业用户会添加 num,普通用户默认为5
function transact(update,fromfiled,tofiled, num) {
if(update=='delete') {
var fieldvalue = $('#'+tofiled).val();
$("#"+tofiled+" option").each(function() {
if($(this).val() == fieldvalue){
$(this).remove();
}
});
} else {
var fieldvalue = $('#'+fromfiled).val();
var have_exists = 0;
var len = $("#"+tofiled+" option").size();
if(len>=num) {
alert('最多添加 '+num+' 项');
return false;
}
$("#"+tofiled+" option").each(function() {
if($(this).val() == fieldvalue){
have_exists = 1;
alert('已经添加到列表中');
return false;
}
});
if(have_exists==0) {
obj = $('#'+fromfiled+' option:selected');
text = obj.text();
text = text.replace('│', '');
text = text.replace('├ ', '');
text = text.replace('└ ', '');
text = text.trim();
fieldvalue = "<option value='"+fieldvalue+"'>"+text+"</option>"
$('#'+tofiled).append(fieldvalue);
$('#deletebutton').attr('disabled','');
}
}
}
function omnipotent(id,linkurl,title,close_type,w,h) {
if(!w) w=700;
if(!h) h=500;
art.dialog({id:id,iframe:linkurl, title:title, width:w, height:h, lock:true},
function(){
if(close_type==1) {
art.dialog({id:id}).close()
} else {
var d = art.dialog({id:id}).data.iframe;
var form = d.document.getElementById('dosubmit');form.click();
}
return false;
},
function(){
art.dialog({id:id}).close()
});void(0);
}
String.prototype.trim = function() {
var str = this,
whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
for (var i = 0,len = str.length; i < len; i++) {
if (whitespace.indexOf(str.charAt(i)) === -1) {
str = str.substring(i);
break;
}
}
for (i = str.length - 1; i >= 0; i--) {
if (whitespace.indexOf(str.charAt(i)) === -1) {
str = str.substring(0, i + 1);
break;
}
}
return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}
|
JavaScript
|
function FileProgress(file, targetID) {
this.fileProgressID = file.id;
this.opacity = 100;
this.height = 0;
this.fileProgressWrapper = document.getElementById(this.fileProgressID);
if (!this.fileProgressWrapper) {
this.fileProgressWrapper = document.createElement("div");
this.fileProgressWrapper.className = "progressWrapper";
this.fileProgressWrapper.id = this.fileProgressID;
this.fileProgressElement = document.createElement("div");
this.fileProgressElement.className = "progressContainer";
var progressCancel = document.createElement("a");
progressCancel.className = "progressCancel";
progressCancel.href = "#";
progressCancel.style.visibility = "hidden";
progressCancel.appendChild(document.createTextNode(" "));
var progressText = document.createElement("div");
progressText.className = "progressName";
progressText.appendChild(document.createTextNode(file.name));
var progressBar = document.createElement("div");
progressBar.className = "progressBarInProgress";
var progressStatus = document.createElement("div");
progressStatus.className = "progressBarStatus";
progressStatus.innerHTML = " ";
this.fileProgressElement.appendChild(progressCancel);
this.fileProgressElement.appendChild(progressText);
this.fileProgressElement.appendChild(progressStatus);
this.fileProgressElement.appendChild(progressBar);
this.fileProgressWrapper.appendChild(this.fileProgressElement);
document.getElementById(targetID).appendChild(this.fileProgressWrapper);
} else {
this.fileProgressElement = this.fileProgressWrapper.firstChild;
this.reset();
}
this.height = this.fileProgressWrapper.offsetHeight;
this.setTimer(null);
}
FileProgress.prototype.setTimer = function (timer) {
this.fileProgressElement["FP_TIMER"] = timer;
};
FileProgress.prototype.getTimer = function (timer) {
return this.fileProgressElement["FP_TIMER"] || null;
};
FileProgress.prototype.reset = function () {
this.fileProgressElement.className = "progressContainer";
this.fileProgressElement.childNodes[2].innerHTML = " ";
this.fileProgressElement.childNodes[2].className = "progressBarStatus";
this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
this.fileProgressElement.childNodes[3].style.width = "0%";
this.appear();
};
FileProgress.prototype.setProgress = function (percentage) {
this.fileProgressElement.className = "progressContainer green";
this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
this.fileProgressElement.childNodes[3].style.width = percentage + "%";
this.appear();
};
FileProgress.prototype.setComplete = function () {
this.fileProgressElement.parentNode.className = "progresshidden";
var oSelf = this;
};
FileProgress.prototype.setError = function () {
this.fileProgressElement.className = "progressContainer red";
this.fileProgressElement.childNodes[3].className = "progressBarError";
this.fileProgressElement.childNodes[3].style.width = "";
var oSelf = this;
this.setTimer(setTimeout(function () {
oSelf.disappear();
}, 5000));
};
FileProgress.prototype.setCancelled = function () {
this.fileProgressElement.className = "progressContainer";
this.fileProgressElement.childNodes[3].className = "progressBarError";
this.fileProgressElement.childNodes[3].style.width = "";
var oSelf = this;
this.setTimer(setTimeout(function () {
oSelf.disappear();
}, 2000));
};
FileProgress.prototype.setStatus = function (status) {
this.fileProgressElement.childNodes[2].innerHTML = status;
};
// Show/Hide the cancel button
FileProgress.prototype.toggleCancel = function (show, swfUploadInstance) {
this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
if (swfUploadInstance) {
var fileID = this.fileProgressID;
this.fileProgressElement.childNodes[0].onclick = function () {
swfUploadInstance.cancelUpload(fileID);
return false;
};
}
};
FileProgress.prototype.appear = function () {
if (this.getTimer() !== null) {
clearTimeout(this.getTimer());
this.setTimer(null);
}
if (this.fileProgressWrapper.filters) {
try {
this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 100;
} catch (e) {
// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=100)";
}
} else {
this.fileProgressWrapper.style.opacity = 1;
}
this.fileProgressWrapper.style.height = "";
this.height = this.fileProgressWrapper.offsetHeight;
this.opacity = 100;
this.fileProgressWrapper.style.display = "";
};
// Fades out and clips away the FileProgress box.
FileProgress.prototype.disappear = function () {
var reduceOpacityBy = 15;
var reduceHeightBy = 4;
var rate = 30; // 15 fps
if (this.opacity > 0) {
this.opacity -= reduceOpacityBy;
if (this.opacity < 0) {
this.opacity = 0;
}
if (this.fileProgressWrapper.filters) {
try {
this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = this.opacity;
} catch (e) {
// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + this.opacity + ")";
}
} else {
this.fileProgressWrapper.style.opacity = this.opacity / 100;
}
}
if (this.height > 0) {
this.height -= reduceHeightBy;
if (this.height < 0) {
this.height = 0;
}
this.fileProgressWrapper.style.height = this.height + "px";
}
if (this.height > 0 || this.opacity > 0) {
var oSelf = this;
this.setTimer(setTimeout(function () {
oSelf.disappear();
}, rate));
} else {
this.fileProgressWrapper.style.display = "none";
this.setTimer(null);
}
};
|
JavaScript
|
function att_show(serverData,file)
{
var serverData = serverData.replace(/<div.*?<\/div>/g,'');
var data = serverData.split(',');
var id = data[0];
var src = data[1];
var ext = data[2];
var filename = data[3];
if(id == 0) {
alert(src)
return false;
}
if(ext == 1) {
var img = '<a href="javascript:;" onclick="javascript:att_cancel(this,'+id+',\'upload\')" class="on"><div class="icon"></div><img src="'+src+'" width="80" imgid="'+id+'" path="'+src+'" title="'+filename+'"/></a>';
} else {
var img = '<a href="javascript:;" onclick="javascript:att_cancel(this,'+id+',\'upload\')" class="on"><div class="icon"></div><img src="statics/images/ext/'+ext+'.png" width="80" imgid="'+id+'" path="'+src+'" title="'+filename+'"/></a>';
}
$.get('index.php?m=attachment&c=attachments&a=swfupload_json&aid='+id+'&src='+src+'&filename='+filename);
$('#fsUploadProgress').append('<li><div id="attachment_'+id+'" class="img-wrap"></div></li>');
$('#attachment_'+id).html(img);
$('#att-status').append('|'+src);
$('#att-name').append('|'+filename);
}
function att_insert(obj,id)
{
var uploadfile = $("#attachment_"+id+"> img").attr('path');
$('#att-status').append('|'+uploadfile);
}
function att_cancel(obj,id,source){
var src = $(obj).children("img").attr("path");
var filename = $(obj).children("img").attr("title");
if($(obj).hasClass('on')){
$(obj).removeClass("on");
var imgstr = $("#att-status").html();
var length = $("a[class='on']").children("img").length;
var strs = filenames = '';
for(var i=0;i<length;i++){
strs += '|'+$("a[class='on']").children("img").eq(i).attr('path');
filenames += '|'+$("a[class='on']").children("img").eq(i).attr('title');
}
$('#att-status').html(strs);
$('#att-name').html(filenames);
if(source=='upload') $('#att-status-del').append('|'+id);
} else {
$(obj).addClass("on");
$('#att-status').append('|'+src);
$('#att-name').append('|'+filename);
var imgstr_del = $("#att-status-del").html();
var imgstr_del_obj = $("a[class!='on']").children("img")
var length_del = imgstr_del_obj.length;
var strs_del='';
for(var i=0;i<length_del;i++){strs_del += '|'+imgstr_del_obj.eq(i).attr('imgid');}
if(source=='upload') $('#att-status-del').html(strs_del);
}
}
//swfupload functions
function fileDialogStart() {
/* I don't need to do anything here */
}
function fileQueued(file) {
if(file!= null){
try {
var progress = new FileProgress(file, this.customSettings.progressTarget);
progress.toggleCancel(true, this);
} catch (ex) {
this.debug(ex);
}
}
}
function fileDialogComplete(numFilesSelected, numFilesQueued)
{
try {
if (this.getStats().files_queued > 0) {
document.getElementById(this.customSettings.cancelButtonId).disabled = false;
}
/* I want auto start and I can do that here */
//this.startUpload();
} catch (ex) {
this.debug(ex);
}
}
function uploadStart(file)
{
var progress = new FileProgress(file, this.customSettings.progressTarget);
progress.setStatus("正在上传请稍后...");
return true;
}
function uploadProgress(file, bytesLoaded, bytesTotal)
{
var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
var progress = new FileProgress(file, this.customSettings.progressTarget);
progress.setProgress(percent);
progress.setStatus("正在上传("+percent+" %)请稍后...");
}
function uploadSuccess(file, serverData)
{
att_show(serverData,file);
var progress = new FileProgress(file, this.customSettings.progressTarget);
progress.setComplete();
progress.setStatus("文件上传成功");
}
function uploadComplete(file)
{
if (this.getStats().files_queued > 0)
{
this.startUpload();
}
}
function uploadError(file, errorCode, message) {
var msg;
switch (errorCode)
{
case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
msg = "上传错误: " + message;
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
msg = "上传错误";
break;
case SWFUpload.UPLOAD_ERROR.IO_ERROR:
msg = "服务器 I/O 错误";
break;
case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
msg = "服务器安全认证错误";
break;
case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
msg = "附件安全检测失败,上传终止";
break;
case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
msg = '上传取消';
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
msg = '上传终止';
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
msg = '单次上传文件数限制为 '+swfu.settings.file_upload_limit+' 个';
break;
default:
msg = message;
break;
}
var progress = new FileProgress(file,this.customSettings.progressTarget);
progress.setError();
progress.setStatus(msg);
}
function fileQueueError(file, errorCode, message)
{
var errormsg;
switch (errorCode) {
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
errormsg = "请不要上传空文件";
break;
case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
errormsg = "队列文件数量超过设定值";
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
errormsg = "文件尺寸超过设定值";
break;
case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
errormsg = "文件类型不合法";
default:
errormsg = '上传错误,请与管理员联系!';
break;
}
var progress = new FileProgress('file',this.customSettings.progressTarget);
progress.setError();
progress.setStatus(errormsg);
}
|
JavaScript
|
var SWFUpload;
if (SWFUpload == undefined) {
SWFUpload = function (settings) {
this.initSWFUpload(settings);
};
}
SWFUpload.prototype.initSWFUpload = function (settings) {
try {
this.customSettings = {}; // A container where developers can place their own settings associated with this instance.
this.settings = settings;
this.eventQueue = [];
this.movieName = "SWFUpload_" + SWFUpload.movieCount++;
this.movieElement = null;
// Setup global control tracking
SWFUpload.instances[this.movieName] = this;
// Load the settings. Load the Flash movie.
this.initSettings();
this.loadFlash();
this.displayDebugInfo();
} catch (ex) {
delete SWFUpload.instances[this.movieName];
throw ex;
}
};
/* *************** */
/* Static Members */
/* *************** */
SWFUpload.instances = {};
SWFUpload.movieCount = 0;
SWFUpload.version = "2.2.0 2009-03-25";
SWFUpload.QUEUE_ERROR = {
QUEUE_LIMIT_EXCEEDED : -100,
FILE_EXCEEDS_SIZE_LIMIT : -110,
ZERO_BYTE_FILE : -120,
INVALID_FILETYPE : -130
};
SWFUpload.UPLOAD_ERROR = {
HTTP_ERROR : -200,
MISSING_UPLOAD_URL : -210,
IO_ERROR : -220,
SECURITY_ERROR : -230,
UPLOAD_LIMIT_EXCEEDED : -240,
UPLOAD_FAILED : -250,
SPECIFIED_FILE_ID_NOT_FOUND : -260,
FILE_VALIDATION_FAILED : -270,
FILE_CANCELLED : -280,
UPLOAD_STOPPED : -290
};
SWFUpload.FILE_STATUS = {
QUEUED : -1,
IN_PROGRESS : -2,
ERROR : -3,
COMPLETE : -4,
CANCELLED : -5
};
SWFUpload.BUTTON_ACTION = {
SELECT_FILE : -100,
SELECT_FILES : -110,
START_UPLOAD : -120
};
SWFUpload.CURSOR = {
ARROW : -1,
HAND : -2
};
SWFUpload.WINDOW_MODE = {
WINDOW : "window",
TRANSPARENT : "transparent",
OPAQUE : "opaque"
};
// Private: takes a URL, determines if it is relative and converts to an absolute URL
// using the current site. Only processes the URL if it can, otherwise returns the URL untouched
SWFUpload.completeURL = function(url) {
if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) {
return url;
}
var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");
var indexSlash = window.location.pathname.lastIndexOf("/");
if (indexSlash <= 0) {
path = "/";
} else {
path = window.location.pathname.substr(0, indexSlash) + "/";
}
return /*currentURL +*/ path + url;
};
/* ******************** */
/* Instance Members */
/* ******************** */
// Private: initSettings ensures that all the
// settings are set, getting a default value if one was not assigned.
SWFUpload.prototype.initSettings = function () {
this.ensureDefault = function (settingName, defaultValue) {
this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
};
// Upload backend settings
this.ensureDefault("upload_url", "");
this.ensureDefault("preserve_relative_urls", false);
this.ensureDefault("file_post_name", "Filedata");
this.ensureDefault("post_params", {});
this.ensureDefault("use_query_string", false);
this.ensureDefault("requeue_on_error", false);
this.ensureDefault("http_success", []);
this.ensureDefault("assume_success_timeout", 0);
// File Settings
this.ensureDefault("file_types", "*.*");
this.ensureDefault("file_types_description", "All Files");
this.ensureDefault("file_size_limit", 0); // Default zero means "unlimited"
this.ensureDefault("file_upload_limit", 0);
this.ensureDefault("file_queue_limit", 0);
// Flash Settings
this.ensureDefault("flash_url", "swfupload.swf");
this.ensureDefault("prevent_swf_caching", true);
// Button Settings
this.ensureDefault("button_image_url", "");
this.ensureDefault("button_width", 1);
this.ensureDefault("button_height", 1);
this.ensureDefault("button_text", "");
this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");
this.ensureDefault("button_text_top_padding", 0);
this.ensureDefault("button_text_left_padding", 0);
this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
this.ensureDefault("button_disabled", false);
this.ensureDefault("button_placeholder_id", "");
this.ensureDefault("button_placeholder", null);
this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW);
this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW);
// Debug Settings
this.ensureDefault("debug", false);
this.settings.debug_enabled = this.settings.debug; // Here to maintain v2 API
// Event Handlers
this.settings.return_upload_start_handler = this.returnUploadStart;
this.ensureDefault("swfupload_loaded_handler", null);
this.ensureDefault("file_dialog_start_handler", null);
this.ensureDefault("file_queued_handler", null);
this.ensureDefault("file_queue_error_handler", null);
this.ensureDefault("file_dialog_complete_handler", null);
this.ensureDefault("upload_start_handler", null);
this.ensureDefault("upload_progress_handler", null);
this.ensureDefault("upload_error_handler", null);
this.ensureDefault("upload_success_handler", null);
this.ensureDefault("upload_complete_handler", null);
this.ensureDefault("debug_handler", this.debugMessage);
this.ensureDefault("custom_settings", {});
// Other settings
this.customSettings = this.settings.custom_settings;
// Update the flash url if needed
if (!!this.settings.prevent_swf_caching) {
this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime();
}
if (!this.settings.preserve_relative_urls) {
//this.settings.flash_url = SWFUpload.completeURL(this.settings.flash_url); // Don't need to do this one since flash doesn't look at it
this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url);
this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url);
}
delete this.ensureDefault;
};
// Private: loadFlash replaces the button_placeholder element with the flash movie.
SWFUpload.prototype.loadFlash = function () {
var targetElement, tempParent;
// Make sure an element with the ID we are going to use doesn't already exist
if (document.getElementById(this.movieName) !== null) {
throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
}
// Get the element where we will be placing the flash movie
targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder;
if (targetElement == undefined) {
throw "Could not find the placeholder element: " + this.settings.button_placeholder_id;
}
// Append the container and load the flash
tempParent = document.createElement("div");
tempParent.innerHTML = this.getFlashHTML(); // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);
// Fix IE Flash/Form bug
if (window[this.movieName] == undefined) {
window[this.movieName] = this.getMovieElement();
}
};
// Private: getFlashHTML generates the object tag needed to embed the flash in to the document
SWFUpload.prototype.getFlashHTML = function () {
// Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay
return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',
'<param name="wmode" value="', this.settings.button_window_mode, '" />',
'<param name="movie" value="', this.settings.flash_url, '" />',
'<param name="quality" value="high" />',
'<param name="menu" value="false" />',
'<param name="allowScriptAccess" value="always" />',
'<param name="flashvars" value="' + this.getFlashVars() + '" />',
'</object>'].join("");
};
// Private: getFlashVars builds the parameter string that will be passed
// to flash in the flashvars param.
SWFUpload.prototype.getFlashVars = function () {
// Build a string from the post param object
var paramString = this.buildParamString();
var httpSuccessString = this.settings.http_success.join(",");
// Build the parameter string
return ["movieName=", encodeURIComponent(this.movieName),
"&uploadURL=", encodeURIComponent(this.settings.upload_url),
"&useQueryString=", encodeURIComponent(this.settings.use_query_string),
"&requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
"&httpSuccess=", encodeURIComponent(httpSuccessString),
"&assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout),
"&params=", encodeURIComponent(paramString),
"&filePostName=", encodeURIComponent(this.settings.file_post_name),
"&fileTypes=", encodeURIComponent(this.settings.file_types),
"&fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
"&fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
"&fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
"&fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
"&debugEnabled=", encodeURIComponent(this.settings.debug_enabled),
"&buttonImageURL=", encodeURIComponent(this.settings.button_image_url),
"&buttonWidth=", encodeURIComponent(this.settings.button_width),
"&buttonHeight=", encodeURIComponent(this.settings.button_height),
"&buttonText=", encodeURIComponent(this.settings.button_text),
"&buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),
"&buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),
"&buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
"&buttonAction=", encodeURIComponent(this.settings.button_action),
"&buttonDisabled=", encodeURIComponent(this.settings.button_disabled),
"&buttonCursor=", encodeURIComponent(this.settings.button_cursor)
].join("");
};
// Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload
// The element is cached after the first lookup
SWFUpload.prototype.getMovieElement = function () {
if (this.movieElement == undefined) {
this.movieElement = document.getElementById(this.movieName);
}
if (this.movieElement === null) {
throw "Could not find Flash element";
}
return this.movieElement;
};
// Private: buildParamString takes the name/value pairs in the post_params setting object
// and joins them up in to a string formatted "name=value&name=value"
SWFUpload.prototype.buildParamString = function () {
var postParams = this.settings.post_params;
var paramStringPairs = [];
if (typeof(postParams) === "object") {
for (var name in postParams) {
if (postParams.hasOwnProperty(name)) {
paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
}
}
}
return paramStringPairs.join("&");
};
// Public: Used to remove a SWFUpload instance from the page. This method strives to remove
// all references to the SWF, and other objects so memory is properly freed.
// Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state.
// Credits: Major improvements provided by steffen
SWFUpload.prototype.destroy = function () {
try {
// Make sure Flash is done before we try to remove it
this.cancelUpload(null, false);
// Remove the SWFUpload DOM nodes
var movieElement = null;
movieElement = this.getMovieElement();
if (movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
// Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround)
for (var i in movieElement) {
try {
if (typeof(movieElement[i]) === "function") {
movieElement[i] = null;
}
} catch (ex1) {}
}
// Remove the Movie Element from the page
try {
movieElement.parentNode.removeChild(movieElement);
} catch (ex) {}
}
// Remove IE form fix reference
window[this.movieName] = null;
// Destroy other references
SWFUpload.instances[this.movieName] = null;
delete SWFUpload.instances[this.movieName];
this.movieElement = null;
this.settings = null;
this.customSettings = null;
this.eventQueue = null;
this.movieName = null;
return true;
} catch (ex2) {
return false;
}
};
// Public: displayDebugInfo prints out settings and configuration
// information about this SWFUpload instance.
// This function (and any references to it) can be deleted when placing
// SWFUpload in production.
SWFUpload.prototype.displayDebugInfo = function () {
this.debug(
[
"---SWFUpload Instance Info---\n",
"Version: ", SWFUpload.version, "\n",
"Movie Name: ", this.movieName, "\n",
"Settings:\n",
"\t", "upload_url: ", this.settings.upload_url, "\n",
"\t", "flash_url: ", this.settings.flash_url, "\n",
"\t", "use_query_string: ", this.settings.use_query_string.toString(), "\n",
"\t", "requeue_on_error: ", this.settings.requeue_on_error.toString(), "\n",
"\t", "http_success: ", this.settings.http_success.join(", "), "\n",
"\t", "assume_success_timeout: ", this.settings.assume_success_timeout, "\n",
"\t", "file_post_name: ", this.settings.file_post_name, "\n",
"\t", "post_params: ", this.settings.post_params.toString(), "\n",
"\t", "file_types: ", this.settings.file_types, "\n",
"\t", "file_types_description: ", this.settings.file_types_description, "\n",
"\t", "file_size_limit: ", this.settings.file_size_limit, "\n",
"\t", "file_upload_limit: ", this.settings.file_upload_limit, "\n",
"\t", "file_queue_limit: ", this.settings.file_queue_limit, "\n",
"\t", "debug: ", this.settings.debug.toString(), "\n",
"\t", "prevent_swf_caching: ", this.settings.prevent_swf_caching.toString(), "\n",
"\t", "button_placeholder_id: ", this.settings.button_placeholder_id.toString(), "\n",
"\t", "button_placeholder: ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n",
"\t", "button_image_url: ", this.settings.button_image_url.toString(), "\n",
"\t", "button_width: ", this.settings.button_width.toString(), "\n",
"\t", "button_height: ", this.settings.button_height.toString(), "\n",
"\t", "button_text: ", this.settings.button_text.toString(), "\n",
"\t", "button_text_style: ", this.settings.button_text_style.toString(), "\n",
"\t", "button_text_top_padding: ", this.settings.button_text_top_padding.toString(), "\n",
"\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",
"\t", "button_action: ", this.settings.button_action.toString(), "\n",
"\t", "button_disabled: ", this.settings.button_disabled.toString(), "\n",
"\t", "custom_settings: ", this.settings.custom_settings.toString(), "\n",
"Event Handlers:\n",
"\t", "swfupload_loaded_handler assigned: ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",
"\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",
"\t", "file_queued_handler assigned: ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",
"\t", "file_queue_error_handler assigned: ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",
"\t", "upload_start_handler assigned: ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",
"\t", "upload_progress_handler assigned: ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",
"\t", "upload_error_handler assigned: ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",
"\t", "upload_success_handler assigned: ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",
"\t", "upload_complete_handler assigned: ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",
"\t", "debug_handler assigned: ", (typeof this.settings.debug_handler === "function").toString(), "\n"
].join("")
);
};
/* Note: addSetting and getSetting are no longer used by SWFUpload but are included
the maintain v2 API compatibility
*/
// Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used.
SWFUpload.prototype.addSetting = function (name, value, default_value) {
if (value == undefined) {
return (this.settings[name] = default_value);
} else {
return (this.settings[name] = value);
}
};
// Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found.
SWFUpload.prototype.getSetting = function (name) {
if (this.settings[name] != undefined) {
return this.settings[name];
}
return "";
};
// Private: callFlash handles function calls made to the Flash element.
// Calls are made with a setTimeout for some functions to work around
// bugs in the ExternalInterface library.
SWFUpload.prototype.callFlash = function (functionName, argumentArray) {
argumentArray = argumentArray || [];
var movieElement = this.getMovieElement();
var returnValue, returnString;
// Flash's method if calling ExternalInterface methods (code adapted from MooTools).
try {
returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
returnValue = eval(returnString);
} catch (ex) {
throw "Call to " + functionName + " failed";
}
// Unescape file post param values
if (returnValue != undefined && typeof returnValue.post === "object") {
returnValue = this.unescapeFilePostParams(returnValue);
}
return returnValue;
};
/* *****************************
-- Flash control methods --
Your UI should use these
to operate SWFUpload
***************************** */
// WARNING: this function does not work in Flash Player 10
// Public: selectFile causes a File Selection Dialog window to appear. This
// dialog only allows 1 file to be selected.
SWFUpload.prototype.selectFile = function () {
this.callFlash("SelectFile");
};
// WARNING: this function does not work in Flash Player 10
// Public: selectFiles causes a File Selection Dialog window to appear/ This
// dialog allows the user to select any number of files
// Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names.
// If the selection name length is too long the dialog will fail in an unpredictable manner. There is no work-around
// for this bug.
SWFUpload.prototype.selectFiles = function () {
this.callFlash("SelectFiles");
};
// Public: startUpload starts uploading the first file in the queue unless
// the optional parameter 'fileID' specifies the ID
SWFUpload.prototype.startUpload = function (fileID) {
this.callFlash("StartUpload", [fileID]);
};
// Public: cancelUpload cancels any queued file. The fileID parameter may be the file ID or index.
// If you do not specify a fileID the current uploading file or first file in the queue is cancelled.
// If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter.
SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) {
if (triggerErrorEvent !== false) {
triggerErrorEvent = true;
}
this.callFlash("CancelUpload", [fileID, triggerErrorEvent]);
};
// Public: stopUpload stops the current upload and requeues the file at the beginning of the queue.
// If nothing is currently uploading then nothing happens.
SWFUpload.prototype.stopUpload = function () {
this.callFlash("StopUpload");
};
/* ************************
* Settings methods
* These methods change the SWFUpload settings.
* SWFUpload settings should not be changed directly on the settings object
* since many of the settings need to be passed to Flash in order to take
* effect.
* *********************** */
// Public: getStats gets the file statistics object.
SWFUpload.prototype.getStats = function () {
return this.callFlash("GetStats");
};
// Public: setStats changes the SWFUpload statistics. You shouldn't need to
// change the statistics but you can. Changing the statistics does not
// affect SWFUpload accept for the successful_uploads count which is used
// by the upload_limit setting to determine how many files the user may upload.
SWFUpload.prototype.setStats = function (statsObject) {
this.callFlash("SetStats", [statsObject]);
};
// Public: getFile retrieves a File object by ID or Index. If the file is
// not found then 'null' is returned.
SWFUpload.prototype.getFile = function (fileID) {
if (typeof(fileID) === "number") {
return this.callFlash("GetFileByIndex", [fileID]);
} else {
return this.callFlash("GetFile", [fileID]);
}
};
// Public: addFileParam sets a name/value pair that will be posted with the
// file specified by the Files ID. If the name already exists then the
// exiting value will be overwritten.
SWFUpload.prototype.addFileParam = function (fileID, name, value) {
return this.callFlash("AddFileParam", [fileID, name, value]);
};
// Public: removeFileParam removes a previously set (by addFileParam) name/value
// pair from the specified file.
SWFUpload.prototype.removeFileParam = function (fileID, name) {
this.callFlash("RemoveFileParam", [fileID, name]);
};
// Public: setUploadUrl changes the upload_url setting.
SWFUpload.prototype.setUploadURL = function (url) {
this.settings.upload_url = url.toString();
this.callFlash("SetUploadURL", [url]);
};
// Public: setPostParams changes the post_params setting
SWFUpload.prototype.setPostParams = function (paramsObject) {
this.settings.post_params = paramsObject;
this.callFlash("SetPostParams", [paramsObject]);
};
// Public: addPostParam adds post name/value pair. Each name can have only one value.
SWFUpload.prototype.addPostParam = function (name, value) {
this.settings.post_params[name] = value;
this.callFlash("SetPostParams", [this.settings.post_params]);
};
// Public: removePostParam deletes post name/value pair.
SWFUpload.prototype.removePostParam = function (name) {
delete this.settings.post_params[name];
this.callFlash("SetPostParams", [this.settings.post_params]);
};
// Public: setFileTypes changes the file_types setting and the file_types_description setting
SWFUpload.prototype.setFileTypes = function (types, description) {
this.settings.file_types = types;
this.settings.file_types_description = description;
this.callFlash("SetFileTypes", [types, description]);
};
// Public: setFileSizeLimit changes the file_size_limit setting
SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
this.settings.file_size_limit = fileSizeLimit;
this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
};
// Public: setFileUploadLimit changes the file_upload_limit setting
SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
this.settings.file_upload_limit = fileUploadLimit;
this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
};
// Public: setFileQueueLimit changes the file_queue_limit setting
SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
this.settings.file_queue_limit = fileQueueLimit;
this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
};
// Public: setFilePostName changes the file_post_name setting
SWFUpload.prototype.setFilePostName = function (filePostName) {
this.settings.file_post_name = filePostName;
this.callFlash("SetFilePostName", [filePostName]);
};
// Public: setUseQueryString changes the use_query_string setting
SWFUpload.prototype.setUseQueryString = function (useQueryString) {
this.settings.use_query_string = useQueryString;
this.callFlash("SetUseQueryString", [useQueryString]);
};
// Public: setRequeueOnError changes the requeue_on_error setting
SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
this.settings.requeue_on_error = requeueOnError;
this.callFlash("SetRequeueOnError", [requeueOnError]);
};
// Public: setHTTPSuccess changes the http_success setting
SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) {
if (typeof http_status_codes === "string") {
http_status_codes = http_status_codes.replace(" ", "").split(",");
}
this.settings.http_success = http_status_codes;
this.callFlash("SetHTTPSuccess", [http_status_codes]);
};
// Public: setHTTPSuccess changes the http_success setting
SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) {
this.settings.assume_success_timeout = timeout_seconds;
this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]);
};
// Public: setDebugEnabled changes the debug_enabled setting
SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
this.settings.debug_enabled = debugEnabled;
this.callFlash("SetDebugEnabled", [debugEnabled]);
};
// Public: setButtonImageURL loads a button image sprite
SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
if (buttonImageURL == undefined) {
buttonImageURL = "";
}
this.settings.button_image_url = buttonImageURL;
this.callFlash("SetButtonImageURL", [buttonImageURL]);
};
// Public: setButtonDimensions resizes the Flash Movie and button
SWFUpload.prototype.setButtonDimensions = function (width, height) {
this.settings.button_width = width;
this.settings.button_height = height;
var movie = this.getMovieElement();
if (movie != undefined) {
movie.style.width = width + "px";
movie.style.height = height + "px";
}
this.callFlash("SetButtonDimensions", [width, height]);
};
// Public: setButtonText Changes the text overlaid on the button
SWFUpload.prototype.setButtonText = function (html) {
this.settings.button_text = html;
this.callFlash("SetButtonText", [html]);
};
// Public: setButtonTextPadding changes the top and left padding of the text overlay
SWFUpload.prototype.setButtonTextPadding = function (left, top) {
this.settings.button_text_top_padding = top;
this.settings.button_text_left_padding = left;
this.callFlash("SetButtonTextPadding", [left, top]);
};
// Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button
SWFUpload.prototype.setButtonTextStyle = function (css) {
this.settings.button_text_style = css;
this.callFlash("SetButtonTextStyle", [css]);
};
// Public: setButtonDisabled disables/enables the button
SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
this.settings.button_disabled = isDisabled;
this.callFlash("SetButtonDisabled", [isDisabled]);
};
// Public: setButtonAction sets the action that occurs when the button is clicked
SWFUpload.prototype.setButtonAction = function (buttonAction) {
this.settings.button_action = buttonAction;
this.callFlash("SetButtonAction", [buttonAction]);
};
// Public: setButtonCursor changes the mouse cursor displayed when hovering over the button
SWFUpload.prototype.setButtonCursor = function (cursor) {
this.settings.button_cursor = cursor;
this.callFlash("SetButtonCursor", [cursor]);
};
/* *******************************
Flash Event Interfaces
These functions are used by Flash to trigger the various
events.
All these functions a Private.
Because the ExternalInterface library is buggy the event calls
are added to a queue and the queue then executed by a setTimeout.
This ensures that events are executed in a determinate order and that
the ExternalInterface bugs are avoided.
******************************* */
SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
// Warning: Don't call this.debug inside here or you'll create an infinite loop
if (argumentArray == undefined) {
argumentArray = [];
} else if (!(argumentArray instanceof Array)) {
argumentArray = [argumentArray];
}
var self = this;
if (typeof this.settings[handlerName] === "function") {
// Queue the event
this.eventQueue.push(function () {
this.settings[handlerName].apply(this, argumentArray);
});
// Execute the next queued event
setTimeout(function () {
self.executeNextEvent();
}, 0);
} else if (this.settings[handlerName] !== null) {
throw "Event handler " + handlerName + " is unknown or is not a function";
}
};
// Private: Causes the next event in the queue to be executed. Since events are queued using a setTimeout
// we must queue them in order to garentee that they are executed in order.
SWFUpload.prototype.executeNextEvent = function () {
// Warning: Don't call this.debug inside here or you'll create an infinite loop
var f = this.eventQueue ? this.eventQueue.shift() : null;
if (typeof(f) === "function") {
f.apply(this);
}
};
// Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have
// properties that contain characters that are not valid for JavaScript identifiers. To work around this
// the Flash Component escapes the parameter names and we must unescape again before passing them along.
SWFUpload.prototype.unescapeFilePostParams = function (file) {
var reg = /[$]([0-9a-f]{4})/i;
var unescapedPost = {};
var uk;
if (file != undefined) {
for (var k in file.post) {
if (file.post.hasOwnProperty(k)) {
uk = k;
var match;
while ((match = reg.exec(uk)) !== null) {
uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
}
unescapedPost[uk] = file.post[k];
}
}
file.post = unescapedPost;
}
return file;
};
// Private: Called by Flash to see if JS can call in to Flash (test if External Interface is working)
SWFUpload.prototype.testExternalInterface = function () {
try {
return this.callFlash("TestExternalInterface");
} catch (ex) {
return false;
}
};
// Private: This event is called by Flash when it has finished loading. Don't modify this.
// Use the swfupload_loaded_handler event setting to execute custom code when SWFUpload has loaded.
SWFUpload.prototype.flashReady = function () {
// Check that the movie element is loaded correctly with its ExternalInterface methods defined
var movieElement = this.getMovieElement();
if (!movieElement) {
this.debug("Flash called back ready but the flash movie can't be found.");
return;
}
this.cleanUp(movieElement);
this.queueEvent("swfupload_loaded_handler");
};
// Private: removes Flash added fuctions to the DOM node to prevent memory leaks in IE.
// This function is called by Flash each time the ExternalInterface functions are created.
SWFUpload.prototype.cleanUp = function (movieElement) {
// Pro-actively unhook all the Flash functions
try {
if (this.movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");
for (var key in movieElement) {
try {
if (typeof(movieElement[key]) === "function") {
movieElement[key] = null;
}
} catch (ex) {
}
}
}
} catch (ex1) {
}
// Fix Flashes own cleanup code so if the SWFMovie was removed from the page
// it doesn't display errors.
window["__flash__removeCallback"] = function (instance, name) {
try {
if (instance) {
instance[name] = null;
}
} catch (flashEx) {
}
};
};
/* This is a chance to do something before the browse window opens */
SWFUpload.prototype.fileDialogStart = function () {
this.queueEvent("file_dialog_start_handler");
};
/* Called when a file is successfully added to the queue. */
SWFUpload.prototype.fileQueued = function (file) {
file = this.unescapeFilePostParams(file);
this.queueEvent("file_queued_handler", file);
};
/* Handle errors that occur when an attempt to queue a file fails. */
SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
file = this.unescapeFilePostParams(file);
this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
};
/* Called after the file dialog has closed and the selected files have been queued.
You could call startUpload here if you want the queued files to begin uploading immediately. */
SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) {
this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]);
};
SWFUpload.prototype.uploadStart = function (file) {
file = this.unescapeFilePostParams(file);
this.queueEvent("return_upload_start_handler", file);
};
SWFUpload.prototype.returnUploadStart = function (file) {
var returnValue;
if (typeof this.settings.upload_start_handler === "function") {
file = this.unescapeFilePostParams(file);
returnValue = this.settings.upload_start_handler.call(this, file);
} else if (this.settings.upload_start_handler != undefined) {
throw "upload_start_handler must be a function";
}
// Convert undefined to true so if nothing is returned from the upload_start_handler it is
// interpretted as 'true'.
if (returnValue === undefined) {
returnValue = true;
}
returnValue = !!returnValue;
this.callFlash("ReturnUploadStart", [returnValue]);
};
SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
file = this.unescapeFilePostParams(file);
this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
};
SWFUpload.prototype.uploadError = function (file, errorCode, message) {
file = this.unescapeFilePostParams(file);
this.queueEvent("upload_error_handler", [file, errorCode, message]);
};
SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) {
file = this.unescapeFilePostParams(file);
this.queueEvent("upload_success_handler", [file, serverData, responseReceived]);
};
SWFUpload.prototype.uploadComplete = function (file) {
file = this.unescapeFilePostParams(file);
this.queueEvent("upload_complete_handler", file);
};
/* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the
internal debug console. You can override this event and have messages written where you want. */
SWFUpload.prototype.debug = function (message) {
this.queueEvent("debug_handler", message);
};
/* **********************************
Debug Console
The debug console is a self contained, in page location
for debug message to be sent. The Debug Console adds
itself to the body if necessary.
The console is automatically scrolled as messages appear.
If you are using your own debug handler or when you deploy to production and
have debug disabled you can remove these functions to reduce the file size
and complexity.
********************************** */
// Private: debugMessage is the default debug_handler. If you want to print debug messages
// call the debug() function. When overriding the function your own function should
// check to see if the debug setting is true before outputting debug information.
SWFUpload.prototype.debugMessage = function (message) {
if (this.settings.debug) {
var exceptionMessage, exceptionValues = [];
// Check for an exception object and print it nicely
if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
for (var key in message) {
if (message.hasOwnProperty(key)) {
exceptionValues.push(key + ": " + message[key]);
}
}
exceptionMessage = exceptionValues.join("\n") || "";
exceptionValues = exceptionMessage.split("\n");
exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
SWFUpload.Console.writeLine(exceptionMessage);
} else {
SWFUpload.Console.writeLine(message);
}
}
};
SWFUpload.Console = {};
SWFUpload.Console.writeLine = function (message) {
var console, documentForm;
try {
console = document.getElementById("SWFUpload_Console");
if (!console) {
documentForm = document.createElement("form");
document.getElementsByTagName("body")[0].appendChild(documentForm);
console = document.createElement("textarea");
console.id = "SWFUpload_Console";
console.style.fontFamily = "monospace";
console.setAttribute("wrap", "off");
console.wrap = "off";
console.style.overflow = "auto";
console.style.width = "700px";
console.style.height = "350px";
console.style.margin = "5px";
documentForm.appendChild(console);
}
console.value += message + "\n";
console.scrollTop = console.scrollHeight - console.clientHeight;
} catch (ex) {
alert("Exception: " + ex.name + " Message: " + ex.message);
}
};
|
JavaScript
|
function flashupload(uploadid, name, textareaid, funcName, args, module, catid, authkey) {
var args = args ? '&args='+args : '';
var setting = '&module='+module+'&catid='+catid+'&authkey='+authkey;
window.top.art.dialog({title:name,id:uploadid,iframe:'index.php?m=attachment&c=attachments&a=swfupload'+args+setting,width:'500',height:'420'}, function(){ if(funcName) {funcName.apply(this,[uploadid,textareaid]);}else {submit_ckeditor(uploadid,textareaid);}}, function(){window.top.art.dialog({id:uploadid}).close()});
}
function submit_ckeditor(uploadid,textareaid){
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#att-status").html();
var del_content = d.$("#att-status-del").html();
insert2editor(textareaid,in_content,del_content)
}
function submit_images(uploadid,returnid){
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#att-status").html().substring(1);
var in_content = in_content.split('|');
IsImg(in_content[0]) ? $('#'+returnid).attr("value",in_content[0]) : alert('选择的类型必须为图片类型');
}
function submit_attachment(uploadid,returnid){
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#att-status").html().substring(1);
var in_content = in_content.split('|');
$('#'+returnid).attr("value",in_content[0]);
}
function submit_files(uploadid,returnid){
var d = window.top.art.dialog({id:uploadid}).data.iframe;
var in_content = d.$("#att-status").html().substring(1);
var in_content = in_content.split('|');
var new_filepath = in_content[0].replace(uploadurl,'/');
$('#'+returnid).attr("value",new_filepath);
}
function insert2editor(id,in_content,del_content) {
if(in_content == '') {return false;}
var data = in_content.substring(1).split('|');
var img = '';
for (var n in data) {
img += IsImg(data[n]) ? '<img src="'+data[n]+'" /><br />' : (IsSwf(data[n]) ? '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="quality" value="high" /><param name="movie" value="'+data[n]+'" /><embed pluginspage="http://www.macromedia.com/go/getflashplayer" quality="high" src="'+data[n]+'" type="application/x-shockwave-flash" width="460"></embed></object>' :'<a href="'+data[n]+'" />'+data[n]+'</a><br />') ;
}
$.get("index.php?m=attachment&c=attachments&a=swfdelete",{data: del_content},function(data){});
CKEDITOR.instances[id].insertHtml(img);
}
function IsImg(url){
var sTemp;
var b=false;
var opt="jpg|gif|png|bmp|jpeg";
var s=opt.toUpperCase().split("|");
for (var i=0;i<s.length ;i++ ){
sTemp=url.substr(url.length-s[i].length-1);
sTemp=sTemp.toUpperCase();
s[i]="."+s[i];
if (s[i]==sTemp){
b=true;
break;
}
}
return b;
}
function IsSwf(url){
var sTemp;
var b=false;
var opt="swf";
var s=opt.toUpperCase().split("|");
for (var i=0;i<s.length ;i++ ){
sTemp=url.substr(url.length-s[i].length-1);
sTemp=sTemp.toUpperCase();
s[i]="."+s[i];
if (s[i]==sTemp){
b=true;
break;
}
}
return b;
}
|
JavaScript
|
/*
* sGallery 1.0 - simple gallery with jQuery
* made by bujichong 2009-11-25
* 作者:不羁虫 2009-11-25
* http://hi.baidu.com/bujichong/
* 欢迎交流转载,但请尊重作者劳动成果,标明插件来源及作者
*/
(function ($) {
$.fn.sGallery = function (o) {
return new $sG(this, o);
//alert('do');
};
var settings = {
thumbObj:null,//预览对象
titleObj:null,//标题
botLast:null,//按钮上一个
botNext:null,//按钮下一个
thumbNowClass:'now',//预览对象当前的class,默认为now
slideTime:800,//平滑过渡时间
autoChange:true,//是否自动切换
changeTime:5000,//自动切换时间
delayTime:100//鼠标经过时反应的延迟时间
};
$.sGalleryLong = function(e, o) {
this.options = $.extend({}, settings, o || {});
var _self = $(e);
var set = this.options;
var thumb;
var size = _self.size();
var nowIndex = 0; //定义全局指针
var index;//定义全局指针
var startRun;//预定义自动运行参数
var delayRun;//预定义延迟运行参数
//初始化
_self.eq(0).show();
//主切换函数
function fadeAB () {
if (nowIndex != index) {
if (set.thumbObj!=null) {
$(set.thumbObj).removeClass().eq(index).addClass(set.thumbNowClass);}
_self.eq(nowIndex).stop(false,true).fadeOut(set.slideTime);
_self.eq(index).stop(true,true).fadeIn(set.slideTime);
$(set.titleObj).eq(nowIndex).hide();//新增加title
$(set.titleObj).eq(index).show();//新增加title
nowIndex = index;
if (set.autoChange==true) {
clearInterval(startRun);//重置自动切换函数
startRun = setInterval(runNext,set.changeTime);}
}
}
//切换到下一个
function runNext() {
index = (nowIndex+1)%size;
fadeAB();
}
//点击任一图片
if (set.thumbObj!=null) {
thumb = $(set.thumbObj);
//初始化
thumb.eq(0).addClass(set.thumbNowClass);
thumb.bind("mousemove",function(event){
index = thumb.index($(this));
fadeAB();
delayRun = setTimeout(fadeAB,set.delayTime);
clearTimeout(delayRun);
event.stopPropagation();
})
}
//点击上一个
if (set.botNext!=null) {
var botNext = $(set.botNext);
botNext.mousemove(function () {
runNext();
return false;
});
}
//点击下一个
if (set.botLast!=null) {
var botLast = $(set.botLast);
botLast.mousemove(function () {
index = (nowIndex+size-1)%size;
fadeAB();
return false;
});
}
//自动运行
if (set.autoChange==true) {
startRun = setInterval(runNext,set.changeTime);
}
}
var $sG = $.sGalleryLong;
})(jQuery);
function slide(Name,Class,Width,Height,fun){
$(Name).width(Width);
$(Name).height(Height);
if(fun == true){
$(Name).append('<div class="title-bg"></div><div class="title"></div><div class="change"></div>')
var atr = $(Name+' div.changeDiv a');
var sum = atr.length;
for(i=1;i<=sum;i++){
var title = atr.eq(i-1).attr("title");
var href = atr.eq(i-1).attr("href");
$(Name+' .change').append('<i>'+i+'</i>');
$(Name+' .title').append('<a href="'+href+'">'+title+'</a>');
}
$(Name+' .change i').eq(0).addClass('cur');
}
$(Name+' div.changeDiv a').sGallery({//对象指向层,层内包含图片及标题
titleObj:Name+' div.title a',
thumbObj:Name+' .change i',
thumbNowClass:Class
});
$(Name+" .title-bg").width(Width);
}
//缩略图
jQuery.fn.LoadImage=function(scaling,width,height,loadpic){
if(loadpic==null)loadpic="../images/msg_img/loading.gif";
return this.each(function(){
var t=$(this);
var src=$(this).attr("src")
var img=new Image();
img.src=src;
//自动缩放图片
var autoScaling=function(){
if(scaling){
if(img.width>0 && img.height>0){
if(img.width/img.height>=width/height){
if(img.width>width){
t.width(width);
t.height((img.height*width)/img.width);
}else{
t.width(img.width);
t.height(img.height);
}
}
else{
if(img.height>height){
t.height(height);
t.width((img.width*height)/img.height);
}else{
t.width(img.width);
t.height(img.height);
}
}
}
}
}
//处理ff下会自动读取缓存图片
if(img.complete){
autoScaling();
return;
}
$(this).attr("src","");
var loading=$("<img alt=\"加载中...\" title=\"图片加载中...\" src=\""+loadpic+"\" />");
t.hide();
t.after(loading);
$(img).load(function(){
autoScaling();
loading.remove();
t.attr("src",this.src);
t.show();
//$('.photo_prev a,.photo_next a').height($('#big-pic img').height());
});
});
}
//向上滚动代码
function startmarquee(elementID,h,n,speed,delay){
var t = null;
var box = '#' + elementID;
$(box).hover(function(){
clearInterval(t);
}, function(){
t = setInterval(start,delay);
}).trigger('mouseout');
function start(){
$(box).children('ul:first').animate({marginTop: '-='+h},speed,function(){
$(this).css({marginTop:'0'}).find('li').slice(0,n).appendTo(this);
})
}
}
//TAB切换
function SwapTab(name,title,content,Sub,cur){
$(name+' '+title).mouseover(function(){
$(this).addClass(cur).siblings().removeClass(cur);
$(content+" > "+Sub).eq($(name+' '+title).index(this)).show().siblings().hide();
});
}
|
JavaScript
|
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
// config.language = 'fr';
config.uiColor = '#f7f5f4';
config.width = '';
config.removePlugins = 'elementspath,scayt';
config.disableNativeSpellChecker = false;
config.resize_dir = 'vertical';
config.keystrokes =[[ CKEDITOR.CTRL + 13 /*Enter*/, 'maximize' ]];
config.extraPlugins = 'capture';
};
//CKEDITOR.plugins.load('pgrfilemanager');
function insert_page(editorid)
{
var editor = CKEDITOR.instances[editorid];
editor.insertHtml('[page]');
if($('#paginationtype').val()) {
$('#paginationtype').val(2);
$('#paginationtype').css("color","red");
}
}
function insert_page_title(editorid,insertdata)
{
if(insertdata)
{
var editor = CKEDITOR.instances[editorid];
var data = editor.getData();
var page_title_value = $("#page_title_value").val();
if(page_title_value=='')
{
$("#msg_page_title_value").html("<font color='red'>请输入子标题</font>");
return false;
}
page_title_value = '[page]'+page_title_value+'[/page]';
editor.insertHtml(page_title_value);
$("#page_title_value").val('');
$("#msg_page_title_value").html('');
if($('#paginationtype').val()) {
$('#paginationtype').val(2);
$('#paginationtype').css("color","red");
}
}
else
{
$("#page_title_div").slideDown("fast");
}
}
var objid = MM_objid = key = 0;
function file_list(fn,url,obj) {
$('#MM_file_list_editor1').append('<div id="MM_file_list_'+fn+'">'+url+' <a href=\'#\' onMouseOver=\'javascript:FilePreview("'+url+'", 1);\' onMouseout=\'javascript:FilePreview("", 0);\'>查看</a> | <a href="javascript:insertHTMLToEditor(\'<img src='+url+'>\',\''+fn+'\')">插入</A> | <a href="javascript:del_file(\''+fn+'\',\''+url+'\','+fn+')">删除</a><br>');
}
|
JavaScript
|
/*
Copyright (c) 2005-2011, PHPCMS V9- Rocing Chan. All rights reserved.
For licensing, see http://www.phpcms.cn.com/license
*/
(function()
{
var loadcapture =
{
exec : function( editor )
{
var pluginNameExt = 'capture';
ext_editor = editor.name;
if(CKEDITOR.env.ie) {
try{
//var t = new ActiveXObject("WEBCAPTURECTRL.WebCaptureCtrlCtrl.1");
return document.getElementById("PC_Capture").ShowCaptureWindow();
} catch(e){
CKEDITOR.dialog.add(pluginNameExt, function( api )
{
var dialogDefinition =
{
title : editor.lang.capture.notice,
minWidth : 350,
minHeight : 80,
contents : [
{
id : 'tab1',
label : 'Label',
title : 'Title',
padding : 0,
elements :
[
{
type : 'html',
html : editor.lang.capture.notice_tips
}
]
}
],
buttons : [ CKEDITOR.dialog.cancelButton ]
};
return dialogDefinition;
});
editor.addCommand(pluginNameExt, new CKEDITOR.dialogCommand(pluginNameExt));
editor.execCommand(pluginNameExt);
}
} else {
alert(editor.lang.capture.unsport_tips);
return false;
}
}
};
var pluginName = 'capture';
CKEDITOR.plugins.add('capture',
{
lang: ['zh-cn'],
init: function(editor)
{
if ( CKEDITOR.env.ie ) {
editor.addCommand(pluginName, loadcapture);
editor.ui.addButton('Capture',
{
label: editor.lang.capture.title,
command: pluginName,
icon: CKEDITOR.plugins.getPath('capture') + 'capture.png'
});
}
}
});
})();
function pc_screen(param){
var oEditor = CKEDITOR.instances[ext_editor];
var data = oEditor.getData();
var imgtag = "<img src="+param+"><BR>";
oEditor.insertHtml(imgtag);
}
|
JavaScript
|
/*
Copyright (c) 2003-2010, PHPCMS - PHPCMS TEAM. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('capture','zh-cn',
{
capture:
{
title:'PHPCMS在线截图',
notice:'PHPCMS在线截图控件安装',
notice_tips:'<p id="Capture">你还没有安装截图插件!<br />请使用 <a href="http://www.phpcms.cn/capture/" id="CaptureDownWeb" target="_blank">在线安装</a><font>(荐)</font> 或者 <a href="http://www.phpcms.cn/capture/capture.exe" id="CaptureDown" target="_blank">立即下载</a> 方式来安装插件。</p>',
unsport_tips:'对不起,本功能暂时只支持IE浏览器'
}
}
);
|
JavaScript
|
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add('uicolor',{requires:['dialog'],lang:['en'],init:function(a){if(CKEDITOR.env.ie6Compat)return;a.addCommand('uicolor',new CKEDITOR.dialogCommand('uicolor'));a.ui.addButton('UIColor',{label:a.lang.uicolor.title,command:'uicolor',icon:this.path+'uicolor.gif'});CKEDITOR.dialog.add('uicolor',this.path+'dialogs/uicolor.js');CKEDITOR.scriptLoader.load(CKEDITOR.getUrl('plugins/uicolor/yui/yui.js'));a.element.getDocument().appendStyleSheet(CKEDITOR.getUrl('plugins/uicolor/yui/assets/yui.css'));}});
|
JavaScript
|
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
|
JavaScript
|
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
|
JavaScript
|
$(document).ready(function() {
$("#q").suggest("?m=search&c=index&a=public_get_suggest_keyword&url="+encodeURIComponent('http://www.google.cn/complete/search?hl=zh-CN&q='+$("#q").val()), {
onSelect: function() {
alert(this.value);
}
});
});
var google={
ac:{
h:function(results){
if(results[1].length > 0) {
var data = '<ul>';
for (var i=0;i<results[1].length;i++) {
if(results[1][i]==null || typeof(results[1][i])=='undefined') {
} else {
data += '<li><a href="javascript:;" onmousedown="s(\''+results[1][i][0]+'\')">'+results[1][i][0]+'</a></li>';
}
}
data += '</ul>';
$("#sr_infos").html(data);
} else {
$("#sr_infos").hide();
}
}
}
};
function s(name) {
$("#q").val(name);
window.location.href='?m=search&c=index&a=init&q='+name;
}
|
JavaScript
|
$(document).ready(function(){
//获取锚点即当前图片id
var picid = location.hash;
picid = picid.substring(1);
if(isNaN(picid) || picid=='' || picid==null) {
picid = 1;
}
picid = parseInt(picid);
//图集图片总数
var totalnum = $("#pictureurls li").length;
//如果当前图片id大于图片数,显示第一张图片
if(picid > totalnum || picid < 1) {
picid = 1;
next_picid = 1; //下一张图片id
} else {
next_picid = picid + 1;
}
url = $("#pictureurls li:nth-child("+picid+") img").attr("rel");
$("#big-pic").html("<img src='"+url+"' onload='loadpic("+next_picid+")'>");
$('#big-pic img').LoadImage(true, 890, 650,$("#load_pic").attr('rel'));
$("#picnum").html("("+picid+"/"+totalnum+")");
$("#picinfo").html($("#pictureurls li:nth-child("+picid+") img").attr("alt"));
$("#pictureurls li").click(function(){
i = $(this).index() + 1;
showpic(i);
});
//加载时图片滚动到中间
var _w = $('.cont li').width()*$('.cont li').length;
if(picid>2) {
movestep = picid - 3;
} else {
movestep = 0;
}
$(".cont ul").css({"left":-+$('.cont li').width()*movestep});
//点击图片滚动
$('.cont ul').width(_w);
$(".cont li").click( function () {
if($(this).index()>2){
movestep = $(this).index() - 2;
$(".cont ul").css({"left":-+$('.cont li').width()*movestep});
}
});
//当前缩略图添加样式
$("#pictureurls li:nth-child("+picid+")").addClass("on");
});
$(document).keyup(function(e) {
var currKey=0,e=e||event;
currKey=e.keyCode||e.which||e.charCode;
switch(currKey) {
case 37: // left
showpic('pre');
break;
case 39: // up
showpic('next');
break;
case 13: // enter
var nextpicurl = $('#nextPicsBut').attr('href');
if(nextpicurl !== '' || nextpicurl !== 'null') {
window.location=nextpicurl;
}
break;
}
});
function showpic(type, replay) {
//隐藏重复播放div
$("#endSelect").hide();
//图集图片总数
var totalnum = $("#pictureurls li").length;
if(type=='next' || type=='pre') {
//获取锚点即当前图片id
var picid = location.hash;
picid = picid.substring(1);
if(isNaN(picid) || picid=='' || picid==null) {
picid = 1;
}
picid = parseInt(picid);
if(type=='next') {
i = picid + 1;
//如果是最后一张图片,指针指向第一张
if(i > totalnum) {
$("#endSelect").show();
i=1;
next_picid=1;
//重新播放
if(replay!=1) {
return false;
} else {
$("#endSelect").hide();
}
} else {
next_picid = parseInt(i) + 1;
}
} else if (type=='pre') {
i = picid - 1;
//如果是第一张图片,指针指向最后一张
if(i < 1) {
i=totalnum;
next_picid = totalnum;
} else {
next_picid = parseInt(i) - 1;
}
}
url = $("#pictureurls li:nth-child("+i+") img").attr("rel");
$("#big-pic").html("<img src='"+url+"' onload='loadpic("+next_picid+")'>");
$('#big-pic img').LoadImage(true, 890, 650,$("#load_pic").attr('rel'));
$("#picnum").html("("+i+"/"+totalnum+")");
$("#picinfo").html($("#pictureurls li:nth-child("+i+") img").attr("alt"));
//更新锚点
location.hash = i;
type = i;
//点击图片滚动
var _w = $('.cont li').width()*$('.cont li').length;
if(i>2) {
movestep = i - 3;
} else {
movestep = 0;
}
$(".cont ul").css({"left":-+$('.cont li').width()*movestep});
} else if(type=='big') {
//获取锚点即当前图片id
var picid = location.hash;
picid = picid.substring(1);
if(isNaN(picid) || picid=='' || picid==null) {
picid = 1;
}
picid = parseInt(picid);
url = $("#pictureurls li:nth-child("+picid+") img").attr("rel");
window.open(url);
} else {
url = $("#pictureurls li:nth-child("+type+") img").attr("rel");
$("#big-pic").html("<img src='"+url+"'>");
$('#big-pic img').LoadImage(true, 890, 650,$("#load_pic").attr('rel'));
$("#picnum").html("("+type+"/"+totalnum+")");
$("#picinfo").html($("#pictureurls li:nth-child("+type+") img").attr("alt"));
location.hash = type;
}
$("#pictureurls li").each(function(i){
j = i+1;
if(j==type) {
$("#pictureurls li:nth-child("+j+")").addClass("on");
} else {
$("#pictureurls li:nth-child("+j+")").removeClass();
}
});
}
//预加载图片
function loadpic(id) {
url = $("#pictureurls li:nth-child("+id+") img").attr("rel");
$("#load_pic").html("<img src='"+url+"'>");
}
|
JavaScript
|
var regexEnum =
{
intege:"^-?[1-9]\\d*$", //整数
intege1:"^[1-9]\\d*$", //正整数
intege2:"^-[1-9]\\d*$", //负整数
num:"^([+-]?)\\d*\\.?\\d+$", //数字
num1:"^[1-9]\\d*|0$", //正数(正整数 + 0)
num2:"^-[1-9]\\d*|0$", //负数(负整数 + 0)
decmal:"^([+-]?)\\d*\\.\\d+$", //浮点数
decmal1:"^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*$", //正浮点数
decmal2:"^-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*)$", //负浮点数
decmal3:"^-?([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0)$", //浮点数
decmal4:"^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0$", //非负浮点数(正浮点数 + 0)
decmal5:"^(-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*))|0?.0+|0$", //非正浮点数(负浮点数 + 0)
email:"^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$", //邮件
color:"^[a-fA-F0-9]{6}$", //颜色
url:"^http[s]?:\\/\\/([\\w-]+\\.)+[\\w-]+([\\w-./?%&=]*)?$", //url
chinese:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+$", //仅中文
ascii:"^[\\x00-\\xFF]+$", //仅ACSII字符
zipcode:"^\\d{6}$", //邮编
mobile:"^(1)[0-9]{9}$", //手机
ip4:"^(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)$", //ip地址
notempty:"^\\S+$", //非空
picture:"(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$", //图片
rar:"(.*)\\.(rar|zip|7zip|tgz)$", //压缩文件
date:"^\\d{4}(\\-|\\/|\.)\\d{1,2}\\1\\d{1,2}$", //日期
qq:"^[1-9]*[1-9][0-9]*$", //QQ号码
tel:"^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$", //电话号码的函数(包括验证国内区号,国际区号,分机号)
username:"^\\w+$", //用来用户注册。匹配由数字、26个英文字母或者下划线组成的字符串
letter:"^[A-Za-z]+$", //字母
letter_u:"^[A-Z]+$", //大写字母
letter_l:"^[a-z]+$", //小写字母
idcard:"^[1-9]([0-9]{14}|[0-9]{17})$", //身份证
ps_username:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2D_\\w]+$" //中文、字母、数字 _
}
function isCardID(sId){
var iSum=0 ;
var info="" ;
if(!/^\d{17}(\d|x)$/i.test(sId)) return "你输入的身份证长度或格式错误";
sId=sId.replace(/x$/i,"a");
if(aCity[parseInt(sId.substr(0,2))]==null) return "你的身份证地区非法";
sBirthday=sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2));
var d=new Date(sBirthday.replace(/-/g,"/")) ;
if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate()))return "身份证上的出生日期非法";
for(var i = 17;i>=0;i --) iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11) ;
if(iSum%11!=1) return "你输入的身份证号非法";
return true;//aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女")
}
//短时间,形如 (13:04:06)
function isTime(str)
{
var a = str.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/);
if (a == null) {return false}
if (a[1]>24 || a[3]>60 || a[4]>60)
{
return false;
}
return true;
}
//短日期,形如 (2003-12-05)
function isDate(str)
{
var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
if(r==null)return false;
var d= new Date(r[1], r[3]-1, r[4]);
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
}
//长时间,形如 (2003-12-05 13:04:06)
function isDateTime(str)
{
var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
var r = str.match(reg);
if(r==null) return false;
var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]);
}
|
JavaScript
|
var phpcms_path = '/';
var cookie_pre = 'sYQDUGqqzH';
var cookie_domain = '';
var cookie_path = '/';
function getcookie(name) {
name = cookie_pre+name;
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while(i < clen) {
var j = i + alen;
if(document.cookie.substring(i, j) == arg) return getcookieval(j);
i = document.cookie.indexOf(" ", i) + 1;
if(i == 0) break;
}
return null;
}
function setcookie(name, value, days) {
name = cookie_pre+name;
var argc = setcookie.arguments.length;
var argv = setcookie.arguments;
var secure = (argc > 5) ? argv[5] : false;
var expire = new Date();
if(days==null || days==0) days=1;
expire.setTime(expire.getTime() + 3600000*24*days);
document.cookie = name + "=" + escape(value) + ("; path=" + cookie_path) + ((cookie_domain == '') ? "" : ("; domain=" + cookie_domain)) + ((secure == true) ? "; secure" : "") + ";expires="+expire.toGMTString();
}
function delcookie(name) {
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = getcookie(name);
name = cookie_pre+name;
document.cookie = name+"="+cval+";expires="+exp.toGMTString();
}
function getcookieval(offset) {
var endstr = document.cookie.indexOf (";", offset);
if(endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
|
JavaScript
|
var ColorHex=new Array('00','33','66','99','CC','FF')
var SpColorHex=new Array('FF0000','00FF00','0000FF','FFFF00','00FFFF','FF00FF')
var current=null
var colorTable=''
function colorpicker(showid,fun) {
for (i=0;i<2;i++) {
for (j=0;j<6;j++) {
colorTable=colorTable+'<tr height=12>'
colorTable=colorTable+'<td width=11 onmouseover="onmouseover_color(\'000\')" onclick="select_color(\''+showid+'\',\'000\','+fun+')" style="background-color:#000">'
if (i==0){
colorTable=colorTable+'<td width=11 onmouseover="onmouseover_color(\''+ColorHex[j]+ColorHex[j]+ColorHex[j]+'\')" onclick="select_color(\''+showid+'\',\''+ColorHex[j]+ColorHex[j]+ColorHex[j]+'\','+fun+')" style="background-color:#'+ColorHex[j]+ColorHex[j]+ColorHex[j]+'">'
} else {
colorTable=colorTable+'<td width=11 onmouseover="onmouseover_color(\''+SpColorHex[j]+'\')" onclick="select_color(\''+showid+'\',\''+SpColorHex[j]+'\','+fun+')" style="background-color:#'+SpColorHex[j]+'">'}
colorTable=colorTable+'<td width=11 onmouseover="onmouseover_color(\'000\')" onclick="select_color(\''+showid+'\',\'000\','+fun+')" style="background-color:#000">'
for (k=0;k<3;k++) {
for (l=0;l<6;l++) {
colorTable=colorTable+'<td width=11 onmouseover="onmouseover_color(\''+ColorHex[k+i*3]+ColorHex[l]+ColorHex[j]+'\')" onclick="select_color(\''+showid+'\',\''+ColorHex[k+i*3]+ColorHex[l]+ColorHex[j]+'\','+fun+')" style="background-color:#'+ColorHex[k+i*3]+ColorHex[l]+ColorHex[j]+'">'
}
}
}
}
colorTable='<div style="position:relative;width:253px; height:176px"><a href="javascript:;" onclick="closeBox();" class="close-own">X</a><table width=253 border="0" cellspacing="0" cellpadding="0" style="border:1px #000 solid;border-bottom:none;border-collapse: collapse" bordercolor="000000">'
+'<tr height=30><td colspan=21 bgcolor=#eeeeee>'
+'<table cellpadding="0" cellspacing="1" border="0" style="border-collapse: collapse">'
+'<tr><td width="3"><td><input type="text" name="DisColor" size="6" id="background_colorId" disabled style="border:solid 1px #000000;background-color:#ffff00"></td>'
+'<td width="3"><td><input type="text" name="HexColor" size="7" id="input_colorId" style="border:inset 1px;font-family:Arial;" value="#000000"></td><td><a href="javascript:;" onclick="clear_title();"> clear</a></td></tr></table></td></table>'
+'<table border="1" cellspacing="0" cellpadding="0" style="border-collapse: collapse" bordercolor="000000" style="cursor:hand;">'
+colorTable+'</table></div>';
$('#'+showid).html(colorTable);
colorTable = '';
}
function onmouseover_color(color) {
var color = '#'+color;
$('#background_colorId').css('background-color',color);
$('#input_colorId').val(color);
}
function select_color(showid,color,fun) {
var color = '#'+color;
//$('#title').css('color',color);
if(fun) {
fun.apply(this,[color]);
}
$('#'+showid).html(' ');
}
function closeBox(){
$(".colorpanel").html(' ');
}
function clear_title() {
$('#title').css('color','');
$('#title_colorpanel').html(' ');
}
|
JavaScript
|
/*! SWFObject v2.2 <http://code.google.com/p/swfobject/>
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject = function() {
var UNDEF = "undefined",
OBJECT = "object",
SHOCKWAVE_FLASH = "Shockwave Flash",
SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
FLASH_MIME_TYPE = "application/x-shockwave-flash",
EXPRESS_INSTALL_ID = "SWFObjectExprInst",
ON_READY_STATE_CHANGE = "onreadystatechange",
win = window,
doc = document,
nav = navigator,
plugin = false,
domLoadFnArr = [main],
regObjArr = [],
objIdArr = [],
listenersArr = [],
storedAltContent,
storedAltContentId,
storedCallbackFn,
storedCallbackObj,
isDomLoaded = false,
isExpressInstallActive = false,
dynamicStylesheet,
dynamicStylesheetMedia,
autoHideShow = true,
/* Centralized function for browser feature detection
- User agent string detection is only used when no good alternative is possible
- Is executed directly for optimal performance
*/
ua = function() {
var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
u = nav.userAgent.toLowerCase(),
p = nav.platform.toLowerCase(),
windows = p ? /win/.test(p) : /win/.test(u),
mac = p ? /mac/.test(p) : /mac/.test(u),
webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html
playerVersion = [0,0,0],
d = null;
if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
d = nav.plugins[SHOCKWAVE_FLASH].description;
if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
plugin = true;
ie = false; // cascaded feature detection for Internet Explorer
d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0;
}
}
else if (typeof win.ActiveXObject != UNDEF) {
try {
var a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
if (a) { // a will return null when ActiveX is disabled
d = a.GetVariable("$version");
if (d) {
ie = true; // cascaded feature detection for Internet Explorer
d = d.split(" ")[1].split(",");
playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
}
catch(e) {}
}
return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac };
}(),
/* Cross-browser onDomLoad
- Will fire an event as soon as the DOM of a web page is loaded
- Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/
- Regular onload serves as fallback
*/
onDomLoad = function() {
if (!ua.w3) { return; }
if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically
callDomLoadFunctions();
}
if (!isDomLoaded) {
if (typeof doc.addEventListener != UNDEF) {
doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false);
}
if (ua.ie && ua.win) {
doc.attachEvent(ON_READY_STATE_CHANGE, function() {
if (doc.readyState == "complete") {
doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee);
callDomLoadFunctions();
}
});
if (win == top) { // if not inside an iframe
(function(){
if (isDomLoaded) { return; }
try {
doc.documentElement.doScroll("left");
}
catch(e) {
setTimeout(arguments.callee, 0);
return;
}
callDomLoadFunctions();
})();
}
}
if (ua.wk) {
(function(){
if (isDomLoaded) { return; }
if (!/loaded|complete/.test(doc.readyState)) {
setTimeout(arguments.callee, 0);
return;
}
callDomLoadFunctions();
})();
}
addLoadEvent(callDomLoadFunctions);
}
}();
function callDomLoadFunctions() {
if (isDomLoaded) { return; }
try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early
var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span"));
t.parentNode.removeChild(t);
}
catch (e) { return; }
isDomLoaded = true;
var dl = domLoadFnArr.length;
for (var i = 0; i < dl; i++) {
domLoadFnArr[i]();
}
}
function addDomLoadEvent(fn) {
if (isDomLoaded) {
fn();
}
else {
domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
}
}
/* Cross-browser onload
- Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
- Will fire an event as soon as a web page including all of its assets are loaded
*/
function addLoadEvent(fn) {
if (typeof win.addEventListener != UNDEF) {
win.addEventListener("load", fn, false);
}
else if (typeof doc.addEventListener != UNDEF) {
doc.addEventListener("load", fn, false);
}
else if (typeof win.attachEvent != UNDEF) {
addListener(win, "onload", fn);
}
else if (typeof win.onload == "function") {
var fnOld = win.onload;
win.onload = function() {
fnOld();
fn();
};
}
else {
win.onload = fn;
}
}
/* Main function
- Will preferably execute onDomLoad, otherwise onload (as a fallback)
*/
function main() {
if (plugin) {
testPlayerVersion();
}
else {
matchVersions();
}
}
/* Detect the Flash Player version for non-Internet Explorer browsers
- Detecting the plug-in version via the object element is more precise than using the plugins collection item's description:
a. Both release and build numbers can be detected
b. Avoid wrong descriptions by corrupt installers provided by Adobe
c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports
- Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available
*/
function testPlayerVersion() {
var b = doc.getElementsByTagName("body")[0];
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
var t = b.appendChild(o);
if (t) {
var counter = 0;
(function(){
if (typeof t.GetVariable != UNDEF) {
var d = t.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
else if (counter < 10) {
counter++;
setTimeout(arguments.callee, 10);
return;
}
b.removeChild(o);
t = null;
matchVersions();
})();
}
else {
matchVersions();
}
}
/* Perform Flash Player and SWF version matching; static publishing only
*/
function matchVersions() {
var rl = regObjArr.length;
if (rl > 0) {
for (var i = 0; i < rl; i++) { // for each registered object element
var id = regObjArr[i].id;
var cb = regObjArr[i].callbackFn;
var cbObj = {success:false, id:id};
if (ua.pv[0] > 0) {
var obj = getElementById(id);
if (obj) {
if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match!
setVisibility(id, true);
if (cb) {
cbObj.success = true;
cbObj.ref = getObjectById(id);
cb(cbObj);
}
}
else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported
var att = {};
att.data = regObjArr[i].expressInstall;
att.width = obj.getAttribute("width") || "0";
att.height = obj.getAttribute("height") || "0";
if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); }
if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); }
// parse HTML object param element's name-value pairs
var par = {};
var p = obj.getElementsByTagName("param");
var pl = p.length;
for (var j = 0; j < pl; j++) {
if (p[j].getAttribute("name").toLowerCase() != "movie") {
par[p[j].getAttribute("name")] = p[j].getAttribute("value");
}
}
showExpressInstall(att, par, id, cb);
}
else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF
displayAltContent(obj);
if (cb) { cb(cbObj); }
}
}
}
else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content)
setVisibility(id, true);
if (cb) {
var o = getObjectById(id); // test whether there is an HTML object element or not
if (o && typeof o.SetVariable != UNDEF) {
cbObj.success = true;
cbObj.ref = o;
}
cb(cbObj);
}
}
}
}
}
function getObjectById(objectIdStr) {
var r = null;
var o = getElementById(objectIdStr);
if (o && o.nodeName == "OBJECT") {
if (typeof o.SetVariable != UNDEF) {
r = o;
}
else {
var n = o.getElementsByTagName(OBJECT)[0];
if (n) {
r = n;
}
}
}
return r;
}
/* Requirements for Adobe Express Install
- only one instance can be active at a time
- fp 6.0.65 or higher
- Win/Mac OS only
- no Webkit engines older than version 312
*/
function canExpressInstall() {
return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312);
}
/* Show the Adobe Express Install dialog
- Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
*/
function showExpressInstall(att, par, replaceElemIdStr, callbackFn) {
isExpressInstallActive = true;
storedCallbackFn = callbackFn || null;
storedCallbackObj = {success:false, id:replaceElemIdStr};
var obj = getElementById(replaceElemIdStr);
if (obj) {
if (obj.nodeName == "OBJECT") { // static publishing
storedAltContent = abstractAltContent(obj);
storedAltContentId = null;
}
else { // dynamic publishing
storedAltContent = obj;
storedAltContentId = replaceElemIdStr;
}
att.id = EXPRESS_INSTALL_ID;
if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; }
if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; }
doc.title = doc.title.slice(0, 47) + " - Flash Player Installation";
var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn",
fv = "MMredirectURL=" + win.location.toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title;
if (typeof par.flashvars != UNDEF) {
par.flashvars += "&" + fv;
}
else {
par.flashvars = fv;
}
// IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
// because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
if (ua.ie && ua.win && obj.readyState != 4) {
var newObj = createElement("div");
replaceElemIdStr += "SWFObjectNew";
newObj.setAttribute("id", replaceElemIdStr);
obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
obj.parentNode.removeChild(obj);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
createSWF(att, par, replaceElemIdStr);
}
}
/* Functions to abstract and display alternative content
*/
function displayAltContent(obj) {
if (ua.ie && ua.win && obj.readyState != 4) {
// IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
// because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
var el = createElement("div");
obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content
el.parentNode.replaceChild(abstractAltContent(obj), el);
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
obj.parentNode.removeChild(obj);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
else {
obj.parentNode.replaceChild(abstractAltContent(obj), obj);
}
}
function abstractAltContent(obj) {
var ac = createElement("div");
if (ua.win && ua.ie) {
ac.innerHTML = obj.innerHTML;
}
else {
var nestedObj = obj.getElementsByTagName(OBJECT)[0];
if (nestedObj) {
var c = nestedObj.childNodes;
if (c) {
var cl = c.length;
for (var i = 0; i < cl; i++) {
if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) {
ac.appendChild(c[i].cloneNode(true));
}
}
}
}
}
return ac;
}
/* Cross-browser dynamic SWF creation
*/
function createSWF(attObj, parObj, id) {
var r, el = getElementById(id);
if (ua.wk && ua.wk < 312) { return r; }
if (el) {
if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
attObj.id = id;
}
if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML
var att = "";
for (var i in attObj) {
if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries
if (i.toLowerCase() == "data") {
parObj.movie = attObj[i];
}
else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
att += ' class="' + attObj[i] + '"';
}
else if (i.toLowerCase() != "classid") {
att += ' ' + i + '="' + attObj[i] + '"';
}
}
}
var par = "";
for (var j in parObj) {
if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries
par += '<param name="' + j + '" value="' + parObj[j] + '" />';
}
}
el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only)
r = getElementById(attObj.id);
}
else { // well-behaving browsers
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
for (var m in attObj) {
if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries
if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
o.setAttribute("class", attObj[m]);
}
else if (m.toLowerCase() != "classid") { // filter out IE specific attribute
o.setAttribute(m, attObj[m]);
}
}
}
for (var n in parObj) {
if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element
createObjParam(o, n, parObj[n]);
}
}
el.parentNode.replaceChild(o, el);
r = o;
}
}
return r;
}
function createObjParam(el, pName, pValue) {
var p = createElement("param");
p.setAttribute("name", pName);
p.setAttribute("value", pValue);
el.appendChild(p);
}
/* Cross-browser SWF removal
- Especially needed to safely and completely remove a SWF in Internet Explorer
*/
function removeSWF(id) {
var obj = getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (ua.ie && ua.win) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
removeObjectInIE(id);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
else {
obj.parentNode.removeChild(obj);
}
}
}
function removeObjectInIE(id) {
var obj = getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
/* Functions to optimize JavaScript compression
*/
function getElementById(id) {
var el = null;
try {
el = doc.getElementById(id);
}
catch (e) {}
return el;
}
function createElement(el) {
return doc.createElement(el);
}
/* Updated attachEvent function for Internet Explorer
- Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
*/
function addListener(target, eventType, fn) {
target.attachEvent(eventType, fn);
listenersArr[listenersArr.length] = [target, eventType, fn];
}
/* Flash Player and SWF content version matching
*/
function hasPlayerVersion(rv) {
var pv = ua.pv, v = rv.split(".");
v[0] = parseInt(v[0], 10);
v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
v[2] = parseInt(v[2], 10) || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
}
/* Cross-browser dynamic CSS creation
- Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
*/
function createCSS(sel, decl, media, newStyle) {
if (ua.ie && ua.mac) { return; }
var h = doc.getElementsByTagName("head")[0];
if (!h) { return; } // to also support badly authored HTML pages that lack a head element
var m = (media && typeof media == "string") ? media : "screen";
if (newStyle) {
dynamicStylesheet = null;
dynamicStylesheetMedia = null;
}
if (!dynamicStylesheet || dynamicStylesheetMedia != m) {
// create dynamic stylesheet + get a global reference to it
var s = createElement("style");
s.setAttribute("type", "text/css");
s.setAttribute("media", m);
dynamicStylesheet = h.appendChild(s);
if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) {
dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1];
}
dynamicStylesheetMedia = m;
}
// add style rule
if (ua.ie && ua.win) {
if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) {
dynamicStylesheet.addRule(sel, decl);
}
}
else {
if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) {
dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
}
}
}
function setVisibility(id, isVisible) {
if (!autoHideShow) { return; }
var v = isVisible ? "visible" : "hidden";
if (isDomLoaded && getElementById(id)) {
getElementById(id).style.visibility = v;
}
else {
createCSS("#" + id, "visibility:" + v);
}
}
/* Filter to avoid XSS attacks
*/
function urlEncodeIfNecessary(s) {
var regex = /[\\\"<>\.;]/;
var hasBadChars = regex.exec(s) != null;
return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s;
}
/* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
*/
var cleanup = function() {
if (ua.ie && ua.win) {
window.attachEvent("onunload", function() {
// remove listeners to avoid memory leaks
var ll = listenersArr.length;
for (var i = 0; i < ll; i++) {
listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
}
// cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
var il = objIdArr.length;
for (var j = 0; j < il; j++) {
removeSWF(objIdArr[j]);
}
// cleanup library's main closures to avoid memory leaks
for (var k in ua) {
ua[k] = null;
}
ua = null;
for (var l in swfobject) {
swfobject[l] = null;
}
swfobject = null;
});
}
}();
return {
/* Public API
- Reference: http://code.google.com/p/swfobject/wiki/documentation
*/
registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) {
if (ua.w3 && objectIdStr && swfVersionStr) {
var regObj = {};
regObj.id = objectIdStr;
regObj.swfVersion = swfVersionStr;
regObj.expressInstall = xiSwfUrlStr;
regObj.callbackFn = callbackFn;
regObjArr[regObjArr.length] = regObj;
setVisibility(objectIdStr, false);
}
else if (callbackFn) {
callbackFn({success:false, id:objectIdStr});
}
},
getObjectById: function(objectIdStr) {
if (ua.w3) {
return getObjectById(objectIdStr);
}
},
embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) {
var callbackObj = {success:false, id:replaceElemIdStr};
if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) {
setVisibility(replaceElemIdStr, false);
addDomLoadEvent(function() {
widthStr += ""; // auto-convert to string
heightStr += "";
var att = {};
if (attObj && typeof attObj === OBJECT) {
for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs
att[i] = attObj[i];
}
}
att.data = swfUrlStr;
att.width = widthStr;
att.height = heightStr;
var par = {};
if (parObj && typeof parObj === OBJECT) {
for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs
par[j] = parObj[j];
}
}
if (flashvarsObj && typeof flashvarsObj === OBJECT) {
for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs
if (typeof par.flashvars != UNDEF) {
par.flashvars += "&" + k + "=" + flashvarsObj[k];
}
else {
par.flashvars = k + "=" + flashvarsObj[k];
}
}
}
if (hasPlayerVersion(swfVersionStr)) { // create SWF
var obj = createSWF(att, par, replaceElemIdStr);
if (att.id == replaceElemIdStr) {
setVisibility(replaceElemIdStr, true);
}
callbackObj.success = true;
callbackObj.ref = obj;
}
else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install
att.data = xiSwfUrlStr;
showExpressInstall(att, par, replaceElemIdStr, callbackFn);
return;
}
else { // show alternative content
setVisibility(replaceElemIdStr, true);
}
if (callbackFn) { callbackFn(callbackObj); }
});
}
else if (callbackFn) { callbackFn(callbackObj); }
},
switchOffAutoHideShow: function() {
autoHideShow = false;
},
ua: ua,
getFlashPlayerVersion: function() {
return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
},
hasFlashPlayerVersion: hasPlayerVersion,
createSWF: function(attObj, parObj, replaceElemIdStr) {
if (ua.w3) {
return createSWF(attObj, parObj, replaceElemIdStr);
}
else {
return undefined;
}
},
showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) {
if (ua.w3 && canExpressInstall()) {
showExpressInstall(att, par, replaceElemIdStr, callbackFn);
}
},
removeSWF: function(objElemIdStr) {
if (ua.w3) {
removeSWF(objElemIdStr);
}
},
createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) {
if (ua.w3) {
createCSS(selStr, declStr, mediaStr, newStyleBoolean);
}
},
addDomLoadEvent: addDomLoadEvent,
addLoadEvent: addLoadEvent,
getQueryParamValue: function(param) {
var q = doc.location.search || doc.location.hash;
if (q) {
if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark
if (param == null) {
return urlEncodeIfNecessary(q);
}
var pairs = q.split("&");
for (var i = 0; i < pairs.length; i++) {
if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1)));
}
}
}
return "";
},
// For internal usage only
expressInstallCallback: function() {
if (isExpressInstallActive) {
var obj = getElementById(EXPRESS_INSTALL_ID);
if (obj && storedAltContent) {
obj.parentNode.replaceChild(storedAltContent, obj);
if (storedAltContentId) {
setVisibility(storedAltContentId, true);
if (ua.ie && ua.win) { storedAltContent.style.display = "block"; }
}
if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); }
}
isExpressInstallActive = false;
}
}
};
}();
|
JavaScript
|
function checkradio(radio)
{
var result = false;
for(var i=0; i<radio.length; i++)
{
if(radio[i].checked)
{
result = true;
break;
}
}
return result;
}
function checkselect(select)
{
var result = false;
for(var i=0;i<select.length;i++)
{
if(select[i].selected && select[i].value!='' && select[i].value!=0)
{
result = true;
break;
}
}
return result;
}
var set_show = false;
jQuery.fn.checkFormorder = function(m,func){
mode = (m==1) ? 1 : 0;
var form=jQuery(this);
var elements = form.find('input[require],select[require],textarea[require]');
elements.blur(function(index){
return validator.check(jQuery(this));
});
form.submit(function(){
var ok = true;
var errIndex= new Array();
var n=0;
elements.each(function(i){
if(validator.check(jQuery(this))==false){
ok = false;
errIndex[n++]=i;
};
});
if(ok==false){
elements.eq(errIndex[0]).focus().select();
return false;
}
if(document.getElementById('video_uploader') && !upLoading)
{
uploadFile();
return false;
}
if($('#f_filed_1') && set_show==false)
{
$("select[@id=catids] option").each(function()
{
$(this).attr('selected','selected');
});
}
if($('#hava_checked').val()==0)
{
YP_checkform();
return false;
}
func();
return false;
});
}
|
JavaScript
|
jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
var path = options.path ? '; path=' + options.path : '';
var domain = options.domain ? '; domain=' + options.domain : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else { // only name given, get cookie
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};
|
JavaScript
|
/*
* Facebox (for jQuery)
* version: 1.2 (05/05/2008)
* @requires jQuery v1.2 or later
*
* Examples at http://famspam.com/facebox/
*
* Licensed under the MIT:
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
*
* Usage:
*
* jQuery(document).ready(function() {
* jQuery('a[rel*=facebox]').facebox()
* })
*
* <a href="#terms" rel="facebox">Terms</a>
* Loads the #terms div in the box
*
* <a href="terms.html" rel="facebox">Terms</a>
* Loads the terms.html page in the box
*
* <a href="terms.png" rel="facebox">Terms</a>
* Loads the terms.png image in the box
*
*
* You can also use it programmatically:
*
* jQuery.facebox('some html')
*
* The above will open a facebox with "some html" as the content.
*
* jQuery.facebox(function($) {
* $.get('blah.html', function(data) { $.facebox(data) })
* })
*
* The above will show a loading screen before the passed function is called,
* allowing for a better ajaxy experience.
*
* The facebox function can also display an ajax page or image:
*
* jQuery.facebox({ ajax: 'remote.html' })
* jQuery.facebox({ image: 'dude.jpg' })
*
* Want to close the facebox? Trigger the 'close.facebox' document event:
*
* jQuery(document).trigger('close.facebox')
*
* Facebox also has a bunch of other hooks:
*
* loading.facebox
* beforeReveal.facebox
* reveal.facebox (aliased as 'afterReveal.facebox')
* init.facebox
*
* Simply bind a function to any of these hooks:
*
* $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
*
*/
(function($) {
$.facebox = function(data, klass) {
$.facebox.loading()
if (data.ajax) fillFaceboxFromAjax(data.ajax)
else if (data.image) fillFaceboxFromImage(data.image)
else if (data.div) fillFaceboxFromHref(data.div)
else if ($.isFunction(data)) data.call($)
else $.facebox.reveal(data, klass)
}
/*
* Public, $.facebox methods
*/
$.extend($.facebox, {
settings: {
opacity : 0,
overlay : true,
loadingImage : 'resources/images/loading.gif',
closeImage : 'resources/images/closelabel.gif',
imageTypes : [ 'png', 'jpg', 'jpeg', 'gif' ],
faceboxHtml : '\
<div id="facebox" style="display:none;"> \
<div class="popup"> \
<table> \
<tbody> \
<tr> \
<td class="tl"/><td class="b"/><td class="tr"/> \
</tr> \
<tr> \
<td class="b"/> \
<td class="body"> \
<div class="content"> \
</div> \
<div class="footer"> \
<a href="#" class="close"> \
<img src="resources/images/closelabel.gif" title="close" class="close_image" /> \
</a> \
</div> \
</td> \
<td class="b"/> \
</tr> \
<tr> \
<td class="bl"/><td class="b"/><td class="br"/> \
</tr> \
</tbody> \
</table> \
</div> \
</div>'
},
loading: function() {
init()
if ($('#facebox .loading').length == 1) return true
showOverlay()
$('#facebox .content').empty()
$('#facebox .body').children().hide().end().
append('<div class="loading"><img src="'+$.facebox.settings.loadingImage+'"/></div>')
$('#facebox').css({
top: getPageScroll()[1] + (getPageHeight() / 10),
left: 385.5
}).show()
$(document).bind('keydown.facebox', function(e) {
if (e.keyCode == 27) $.facebox.close()
return true
})
$(document).trigger('loading.facebox')
},
reveal: function(data, klass) {
$(document).trigger('beforeReveal.facebox')
if (klass) $('#facebox .content').addClass(klass)
$('#facebox .content').append(data)
$('#facebox .loading').remove()
$('#facebox .body').children().fadeIn('normal')
$('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2))
$(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
},
close: function() {
$(document).trigger('close.facebox')
return false
}
})
/*
* Public, $.fn methods
*/
$.fn.facebox = function(settings) {
init(settings)
function clickHandler() {
$.facebox.loading(true)
// support for rel="facebox.inline_popup" syntax, to add a class
// also supports deprecated "facebox[.inline_popup]" syntax
var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
if (klass) klass = klass[1]
fillFaceboxFromHref(this.href, klass)
return false
}
return this.click(clickHandler)
}
/*
* Private methods
*/
// called one time to setup facebox on this page
function init(settings) {
if ($.facebox.settings.inited) return true
else $.facebox.settings.inited = true
$(document).trigger('init.facebox')
makeCompatible()
var imageTypes = $.facebox.settings.imageTypes.join('|')
$.facebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')
if (settings) $.extend($.facebox.settings, settings)
$('body').append($.facebox.settings.faceboxHtml)
var preload = [ new Image(), new Image() ]
preload[0].src = $.facebox.settings.closeImage
preload[1].src = $.facebox.settings.loadingImage
$('#facebox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
preload.push(new Image())
preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
})
$('#facebox .close').click($.facebox.close)
$('#facebox .close_image').attr('src', $.facebox.settings.closeImage)
}
// getPageScroll() by quirksmode.com
function getPageScroll() {
var xScroll, yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
xScroll = self.pageXOffset;
} else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
yScroll = document.documentElement.scrollTop;
xScroll = document.documentElement.scrollLeft;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
xScroll = document.body.scrollLeft;
}
return new Array(xScroll,yScroll)
}
// Adapted from getPageSize() by quirksmode.com
function getPageHeight() {
var windowHeight
if (self.innerHeight) { // all except Explorer
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowHeight = document.body.clientHeight;
}
return windowHeight
}
// Backwards compatibility
function makeCompatible() {
var $s = $.facebox.settings
$s.loadingImage = $s.loading_image || $s.loadingImage
$s.closeImage = $s.close_image || $s.closeImage
$s.imageTypes = $s.image_types || $s.imageTypes
$s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
}
// Figures out what you want to display and displays it
// formats are:
// div: #id
// image: blah.extension
// ajax: anything else
function fillFaceboxFromHref(href, klass) {
// div
if (href.match(/#/)) {
var url = window.location.href.split('#')[0]
var target = href.replace(url,'')
$.facebox.reveal($(target).clone().show(), klass)
// image
} else if (href.match($.facebox.settings.imageTypesRegexp)) {
fillFaceboxFromImage(href, klass)
// ajax
} else {
fillFaceboxFromAjax(href, klass)
}
}
function fillFaceboxFromImage(href, klass) {
var image = new Image()
image.onload = function() {
$.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
}
image.src = href
}
function fillFaceboxFromAjax(href, klass) {
$.get(href, function(data) { $.facebox.reveal(data, klass) })
}
function skipOverlay() {
return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null
}
function showOverlay() {
if (skipOverlay()) return
if ($('facebox_overlay').length == 0)
$("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')
$('#facebox_overlay').hide().addClass("facebox_overlayBG")
.css('opacity', $.facebox.settings.opacity)
.click(function() { $(document).trigger('close.facebox') })
.fadeIn(200)
return false
}
function hideOverlay() {
if (skipOverlay()) return
$('#facebox_overlay').fadeOut(200, function(){
$("#facebox_overlay").removeClass("facebox_overlayBG")
$("#facebox_overlay").addClass("facebox_hide")
$("#facebox_overlay").remove()
})
return false
}
/*
* Bindings
*/
$(document).bind('close.facebox', function() {
$(document).unbind('keydown.facebox')
$('#facebox').fadeOut(function() {
$('#facebox .content').removeClass().addClass('content')
hideOverlay()
$('#facebox .loading').remove()
})
})
})(jQuery);
|
JavaScript
|
$(document).ready(function(){
//Sidebar Accordion Menu:
$("#main-nav li ul").hide(); //Hide all sub menus
$("#main-nav li a.current").parent().find("ul").slideToggle("slow"); // Slide down the current menu item's sub menu
$("#main-nav li a.nav-top-item").click( // When a top menu item is clicked...
function () {
$("#main-nav li a.nav-top-item").attr('class', 'nav-top-item');
$(this).attr('class', 'nav-top-item current');
$(this).parent().siblings().find("ul").slideUp("normal"); // Slide up all sub menus except the one clicked
$(this).next().slideToggle("normal"); // Slide down the clicked sub menu
return false;
}
);
$("#main-nav li a.no-submenu").click( // When a menu item with no sub menu is clicked...
function () {
window.location.href=(this.href); // Just open the link instead of a sub menu
return false;
}
);
// Sidebar Accordion Menu Hover Effect:
$("#main-nav li .nav-top-item").hover(
function () {
$(this).stop();
$(this).animate({ paddingRight: "25px" }, 200);
},
function () {
$(this).stop();
$(this).animate({ paddingRight: "15px" });
}
);
//Minimize Content Box
$(".content-box-header h3").css({ "cursor":"s-resize" }); // Give the h3 in Content Box Header a different cursor
$(".content-box-header-toggled").next().hide(); // Hide the content of the header if it has the class "content-box-header-toggled"
$(".content-box-header h3").click( // When the h3 is clicked...
function () {
$(this).parent().parent().find(".content-box-content").toggle(); // Toggle the Content Box
$(this).parent().toggleClass("content-box-header-toggled"); // Give the Content Box Header a special class for styling and hiding
$(this).parent().find(".content-box-tabs").toggle(); // Toggle the tabs
}
);
// Content box tabs:
$('.content-box .content-box-content div.tab-content').hide(); // Hide the content divs
$('.content-box-content div.default-tab').show(); // Show the div with class "default-tab"
$('ul.content-box-tabs li a.default-tab').addClass('current'); // Set the class of the default tab link to "current"
//Close button:
$(".close").click(
function () {
$(this).parent().fadeTo(400, 0, function () { // Links with the class "close" will close parent
$(this).slideUp(600);
});
return false;
}
);
// Alternating table rows:
$('tbody tr:even').addClass("alt-row"); // Add class "alt-row" to even table rows
// Check all checkboxes when the one in a table head is checked:
$('.check-all').click(
function(){
$(this).parent().parent().parent().parent().find("input[type='checkbox']").attr('checked', $(this).is(':checked'));
}
)
// Initialise Facebox Modal window:
$('a[rel*=modal]').facebox(); // Applies modal window to any link with attribute rel="modal"
// Initialise jQuery WYSIWYG:
$(".wysiwyg").wysiwyg();
});
|
JavaScript
|
/**
* WYSIWYG - jQuery plugin 0.5
*
* Copyright (c) 2008-2009 Juan M Martinez
* http://plugins.jquery.com/project/jWYSIWYG
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* $Id: $
*/
(function( $ )
{
$.fn.document = function()
{
var element = this[0];
if ( element.nodeName.toLowerCase() == 'iframe' )
return element.contentWindow.document;
/*
return ( $.browser.msie )
? document.frames[element.id].document
: element.contentWindow.document // contentDocument;
*/
else
return $(this);
};
$.fn.documentSelection = function()
{
var element = this[0];
if ( element.contentWindow.document.selection )
return element.contentWindow.document.selection.createRange().text;
else
return element.contentWindow.getSelection().toString();
};
$.fn.wysiwyg = function( options )
{
if ( arguments.length > 0 && arguments[0].constructor == String )
{
var action = arguments[0].toString();
var params = [];
for ( var i = 1; i < arguments.length; i++ )
params[i - 1] = arguments[i];
if ( action in Wysiwyg )
{
return this.each(function()
{
$.data(this, 'wysiwyg')
.designMode();
Wysiwyg[action].apply(this, params);
});
}
else return this;
}
var controls = {};
/**
* If the user set custom controls, we catch it, and merge with the
* defaults controls later.
*/
if ( options && options.controls )
{
var controls = options.controls;
delete options.controls;
}
var options = $.extend({
html : '<'+'?xml version="1.0" encoding="UTF-8"?'+'><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">STYLE_SHEET</head><body style="font-family: Arial, Helvetica, sans-serif !important; font-size: 13px; height: 100%; line-height: 1.5em !important;">INITIAL_CONTENT</body></html>',
css : {},
debug : false,
autoSave : true, // http://code.google.com/p/jwysiwyg/issues/detail?id=11
rmUnwantedBr : true, // http://code.google.com/p/jwysiwyg/issues/detail?id=15
brIE : true,
controls : {},
messages : {}
}, options);
options.messages = $.extend(true, options.messages, Wysiwyg.MSGS_EN);
options.controls = $.extend(true, options.controls, Wysiwyg.TOOLBAR);
for ( var control in controls )
{
if ( control in options.controls )
$.extend(options.controls[control], controls[control]);
else
options.controls[control] = controls[control];
}
// not break the chain
return this.each(function()
{
Wysiwyg(this, options);
});
};
function Wysiwyg( element, options )
{
return this instanceof Wysiwyg
? this.init(element, options)
: new Wysiwyg(element, options);
}
$.extend(Wysiwyg, {
insertImage : function( szURL, attributes )
{
var self = $.data(this, 'wysiwyg');
if ( self.constructor == Wysiwyg && szURL && szURL.length > 0 )
{
if ( attributes )
{
self.editorDoc.execCommand('insertImage', false, '#jwysiwyg#');
var img = self.getElementByAttributeValue('img', 'src', '#jwysiwyg#');
if ( img )
{
img.src = szURL;
for ( var attribute in attributes )
{
img.setAttribute(attribute, attributes[attribute]);
}
}
}
else
{
self.editorDoc.execCommand('insertImage', false, szURL);
}
}
},
createLink : function( szURL )
{
var self = $.data(this, 'wysiwyg');
if ( self.constructor == Wysiwyg && szURL && szURL.length > 0 )
{
var selection = $(self.editor).documentSelection();
if ( selection.length > 0 )
{
self.editorDoc.execCommand('unlink', false, []);
self.editorDoc.execCommand('createLink', false, szURL);
}
else if ( self.options.messages.nonSelection )
alert(self.options.messages.nonSelection);
}
},
setContent : function( newContent )
{
var self = $.data(this, 'wysiwyg');
self.setContent( newContent );
self.saveContent();
},
clear : function()
{
var self = $.data(this, 'wysiwyg');
self.setContent('');
self.saveContent();
},
MSGS_EN : {
nonSelection : 'select the text you wish to link'
},
TOOLBAR : {
bold : { visible : true, tags : ['b', 'strong'], css : { fontWeight : 'bold' } },
italic : { visible : true, tags : ['i', 'em'], css : { fontStyle : 'italic' } },
strikeThrough : { visible : false, tags : ['s', 'strike'], css : { textDecoration : 'line-through' } },
underline : { visible : false, tags : ['u'], css : { textDecoration : 'underline' } },
separator00 : { visible : false, separator : true },
justifyLeft : { visible : false, css : { textAlign : 'left' } },
justifyCenter : { visible : false, tags : ['center'], css : { textAlign : 'center' } },
justifyRight : { visible : false, css : { textAlign : 'right' } },
justifyFull : { visible : false, css : { textAlign : 'justify' } },
separator01 : { visible : false, separator : true },
indent : { visible : false },
outdent : { visible : false },
separator02 : { visible : false, separator : true },
subscript : { visible : false, tags : ['sub'] },
superscript : { visible : false, tags : ['sup'] },
separator03 : { visible : false, separator : true },
undo : { visible : false },
redo : { visible : false },
separator04 : { visible : false, separator : true },
insertOrderedList : { visible : false, tags : ['ol'] },
insertUnorderedList : { visible : false, tags : ['ul'] },
insertHorizontalRule : { visible : false, tags : ['hr'] },
separator05 : { separator : true },
createLink : {
visible : true,
exec : function()
{
var selection = $(this.editor).documentSelection();
if ( selection.length > 0 )
{
if ( $.browser.msie )
this.editorDoc.execCommand('createLink', true, null);
else
{
var szURL = prompt('URL', 'http://');
if ( szURL && szURL.length > 0 )
{
this.editorDoc.execCommand('unlink', false, []);
this.editorDoc.execCommand('createLink', false, szURL);
}
}
}
else if ( this.options.messages.nonSelection )
alert(this.options.messages.nonSelection);
},
tags : ['a']
},
insertImage : {
visible : true,
exec : function()
{
if ( $.browser.msie )
this.editorDoc.execCommand('insertImage', true, null);
else
{
var szURL = prompt('URL', 'http://');
if ( szURL && szURL.length > 0 )
this.editorDoc.execCommand('insertImage', false, szURL);
}
},
tags : ['img']
},
separator06 : { separator : true },
h1mozilla : { visible : true && $.browser.mozilla, className : 'h1', command : 'heading', arguments : ['h1'], tags : ['h1'] },
h2mozilla : { visible : true && $.browser.mozilla, className : 'h2', command : 'heading', arguments : ['h2'], tags : ['h2'] },
h3mozilla : { visible : true && $.browser.mozilla, className : 'h3', command : 'heading', arguments : ['h3'], tags : ['h3'] },
h1 : { visible : true && !( $.browser.mozilla ), className : 'h1', command : 'formatBlock', arguments : ['Heading 1'], tags : ['h1'] },
h2 : { visible : true && !( $.browser.mozilla ), className : 'h2', command : 'formatBlock', arguments : ['Heading 2'], tags : ['h2'] },
h3 : { visible : true && !( $.browser.mozilla ), className : 'h3', command : 'formatBlock', arguments : ['Heading 3'], tags : ['h3'] },
separator07 : { visible : false, separator : true },
cut : { visible : false },
copy : { visible : false },
paste : { visible : false },
separator08 : { separator : true && !( $.browser.msie ) },
increaseFontSize : { visible : true && !( $.browser.msie ), tags : ['big'] },
decreaseFontSize : { visible : true && !( $.browser.msie ), tags : ['small'] },
separator09 : { separator : true },
html : {
visible : false,
exec : function()
{
if ( this.viewHTML )
{
this.setContent( $(this.original).val() );
$(this.original).hide();
}
else
{
this.saveContent();
$(this.original).show();
}
this.viewHTML = !( this.viewHTML );
}
},
removeFormat : {
visible : true,
exec : function()
{
this.editorDoc.execCommand('removeFormat', false, []);
this.editorDoc.execCommand('unlink', false, []);
}
}
}
});
$.extend(Wysiwyg.prototype,
{
original : null,
options : {},
element : null,
editor : null,
init : function( element, options )
{
var self = this;
this.editor = element;
this.options = options || {};
$.data(element, 'wysiwyg', this);
var newX = element.width || element.clientWidth;
var newY = element.height || element.clientHeight;
if ( element.nodeName.toLowerCase() == 'textarea' )
{
this.original = element;
if ( newX == 0 && element.cols )
newX = ( element.cols * 8 ) + 21;
if ( newY == 0 && element.rows )
newY = ( element.rows * 16 ) + 16;
var editor = this.editor = $('<iframe></iframe>').css({
minHeight : ( newY - 6 ).toString() + 'px',
width : ( newX - 8 ).toString() + 'px'
}).attr('id', $(element).attr('id') + 'IFrame');
if ( $.browser.msie )
{
this.editor
.css('height', ( newY ).toString() + 'px');
/**
var editor = $('<span></span>').css({
width : ( newX - 6 ).toString() + 'px',
height : ( newY - 8 ).toString() + 'px'
}).attr('id', $(element).attr('id') + 'IFrame');
editor.outerHTML = this.editor.outerHTML;
*/
}
}
var panel = this.panel = $('<ul></ul>').addClass('panel');
this.appendControls();
this.element = $('<div></div>').css({
width : ( newX > 0 ) ? ( newX ).toString() + 'px' : '100%'
}).addClass('wysiwyg')
.append(panel)
.append( $('<div><!-- --></div>').css({ clear : 'both' }) )
.append(editor);
$(element)
// .css('display', 'none')
.hide()
.before(this.element);
this.viewHTML = false;
this.initialHeight = newY - 8;
/**
* @link http://code.google.com/p/jwysiwyg/issues/detail?id=52
*/
this.initialContent = $(element).val();
this.initFrame();
if ( this.initialContent.length == 0 )
this.setContent('');
if ( this.options.autoSave )
$('form').submit(function() { self.saveContent(); });
$('form').bind('reset', function()
{
self.setContent( self.initialContent );
self.saveContent();
});
},
initFrame : function()
{
var self = this;
var style = '';
/**
* @link http://code.google.com/p/jwysiwyg/issues/detail?id=14
*/
if ( this.options.css && this.options.css.constructor == String )
style = '<link rel="stylesheet" type="text/css" media="screen" href="' + this.options.css + '" />';
this.editorDoc = $(this.editor).document();
this.editorDoc_designMode = false;
try {
this.editorDoc.designMode = 'on';
this.editorDoc_designMode = true;
} catch ( e ) {
// Will fail on Gecko if the editor is placed in an hidden container element
// The design mode will be set ones the editor is focused
$(this.editorDoc).focus(function()
{
self.designMode();
});
}
this.editorDoc.open();
this.editorDoc.write(
this.options.html
.replace(/INITIAL_CONTENT/, this.initialContent)
.replace(/STYLE_SHEET/, style)
);
this.editorDoc.close();
this.editorDoc.contentEditable = 'true';
if ( $.browser.msie )
{
/**
* Remove the horrible border it has on IE.
*/
setTimeout(function() { $(self.editorDoc.body).css('border', 'none'); }, 0);
}
$(this.editorDoc).click(function( event )
{
self.checkTargets( event.target ? event.target : event.srcElement);
});
/**
* @link http://code.google.com/p/jwysiwyg/issues/detail?id=20
*/
$(this.original).focus(function()
{
$(self.editorDoc.body).focus();
});
if ( this.options.autoSave )
{
/**
* @link http://code.google.com/p/jwysiwyg/issues/detail?id=11
*/
$(this.editorDoc).keydown(function() { self.saveContent(); })
.keyup(function() { self.saveContent(); })
.mousedown(function() { self.saveContent(); });
}
if ( this.options.css )
{
setTimeout(function()
{
if ( self.options.css.constructor == String )
{
/**
* $(self.editorDoc)
* .find('head')
* .append(
* $('<link rel="stylesheet" type="text/css" media="screen" />')
* .attr('href', self.options.css)
* );
*/
}
else
$(self.editorDoc).find('body').css(self.options.css);
}, 0);
}
$(this.editorDoc).keydown(function( event )
{
if ( $.browser.msie && self.options.brIE && event.keyCode == 13 )
{
var rng = self.getRange();
rng.pasteHTML('<br />');
rng.collapse(false);
rng.select();
return false;
}
});
},
designMode : function()
{
if ( !( this.editorDoc_designMode ) )
{
try {
this.editorDoc.designMode = 'on';
this.editorDoc_designMode = true;
} catch ( e ) {}
}
},
getSelection : function()
{
return ( window.getSelection ) ? window.getSelection() : document.selection;
},
getRange : function()
{
var selection = this.getSelection();
if ( !( selection ) )
return null;
return ( selection.rangeCount > 0 ) ? selection.getRangeAt(0) : selection.createRange();
},
getContent : function()
{
return $( $(this.editor).document() ).find('body').html();
},
setContent : function( newContent )
{
$( $(this.editor).document() ).find('body').html(newContent);
},
saveContent : function()
{
if ( this.original )
{
var content = this.getContent();
if ( this.options.rmUnwantedBr )
content = ( content.substr(-4) == '<br>' ) ? content.substr(0, content.length - 4) : content;
$(this.original).val(content);
}
},
appendMenu : function( cmd, args, className, fn )
{
var self = this;
var args = args || [];
$('<li></li>').append(
$('<a><!-- --></a>').addClass(className || cmd)
).mousedown(function() {
if ( fn ) fn.apply(self); else self.editorDoc.execCommand(cmd, false, args);
if ( self.options.autoSave ) self.saveContent();
}).appendTo( this.panel );
},
appendMenuSeparator : function()
{
$('<li class="separator"></li>').appendTo( this.panel );
},
appendControls : function()
{
for ( var name in this.options.controls )
{
var control = this.options.controls[name];
if ( control.separator )
{
if ( control.visible !== false )
this.appendMenuSeparator();
}
else if ( control.visible )
{
this.appendMenu(
control.command || name, control.arguments || [],
control.className || control.command || name || 'empty', control.exec
);
}
}
},
checkTargets : function( element )
{
for ( var name in this.options.controls )
{
var control = this.options.controls[name];
var className = control.className || control.command || name || 'empty';
$('.' + className, this.panel).removeClass('active');
if ( control.tags )
{
var elm = element;
do {
if ( elm.nodeType != 1 )
break;
if ( $.inArray(elm.tagName.toLowerCase(), control.tags) != -1 )
$('.' + className, this.panel).addClass('active');
} while ( elm = elm.parentNode );
}
if ( control.css )
{
var elm = $(element);
do {
if ( elm[0].nodeType != 1 )
break;
for ( var cssProperty in control.css )
if ( elm.css(cssProperty).toString().toLowerCase() == control.css[cssProperty] )
$('.' + className, this.panel).addClass('active');
} while ( elm = elm.parent() );
}
}
},
getElementByAttributeValue : function( tagName, attributeName, attributeValue )
{
var elements = this.editorDoc.getElementsByTagName(tagName);
for ( var i = 0; i < elements.length; i++ )
{
var value = elements[i].getAttribute(attributeName);
if ( $.browser.msie )
{
/** IE add full path, so I check by the last chars. */
value = value.substr(value.length - attributeValue.length);
}
if ( value == attributeValue )
return elements[i];
}
return false;
}
});
})(jQuery);
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','cy',{placeholder:{title:"Priodweddau'r Daliwr Geiriau",toolbar:'Creu Daliwr Geiriau',text:'Testun y Daliwr Geiriau',edit:"Golygu'r Dailwr Geiriau",textMissing:"Mae'n rhaid i'r daliwr geiriau gynnwys testun."}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','tr',{placeholder:{title:'Yer tutucu özellikleri',toolbar:'Yer tutucu oluşturun',text:'Yer tutucu metini',edit:'Yer tutucuyu düzenle',textMissing:'Yer tutucu metin içermelidir.'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','nb',{placeholder:{title:'Egenskaper for plassholder',toolbar:'Opprett plassholder',text:'Tekst for plassholder',edit:'Rediger plassholder',textMissing:'Plassholderen må inneholde tekst.'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','fr',{placeholder:{title:"Propriétés de l'Espace réservé",toolbar:"Créer l'Espace réservé",text:"Texte de l'Espace réservé",edit:"Modifier l'Espace réservé",textMissing:"L'Espace réservé doit contenir du texte."}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','fa',{placeholder:{title:'ویژگیهای محل نگهداری',toolbar:'ایجاد یک محل نگهداری',text:'متن محل نگهداری',edit:'ویرایش محل نگهداری',textMissing:'محل نگهداری باید محتوی متن باشد.'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','eo',{placeholder:{title:'Atributoj de la rezervita spaco',toolbar:'Krei la rezervitan spacon',text:'Texto de la rezervita spaco',edit:'Modifi la rezervitan spacon',textMissing:'La rezervita spaco devas enteni tekston.'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','uk',{placeholder:{title:'Налаштування Заповнювача',toolbar:'Створити Заповнювач',text:'Текст Заповнювача',edit:'Редагувати Заповнювач',textMissing:'Заповнювач повинен містити текст.'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','he',{placeholder:{title:'מאפייני שומר מקום',toolbar:'צור שומר מקום',text:'תוכן שומר המקום',edit:'ערוך שומר מקום',textMissing:'שומר המקום חייב להכיל טקסט.'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','de',{placeholder:{title:'Platzhalter Einstellungen',toolbar:'Platzhalter erstellen',text:'Platzhalter Text',edit:'Platzhalter bearbeiten',textMissing:'Der Platzhalter muss einen Text beinhalten.'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','no',{placeholder:{title:'Egenskaper for plassholder',toolbar:'Opprett plassholder',text:'Tekst for plassholder',edit:'Rediger plassholder',textMissing:'Plassholderen må inneholde tekst.'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','el',{placeholder:{title:'Ιδιότητες Υποκατάστατου Κειμένου',toolbar:'Δημιουργία Υποκατάσταστου Κειμένου',text:'Υποκαθιστόμενο Κείμενο',edit:'Επεξεργασία Υποκατάσταστου Κειμένου',textMissing:'Πρέπει να υπάρχει υποκαθιστόμενο κείμενο.'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','vi',{placeholder:{title:'Thuộc tính đặt chỗ',toolbar:'Tạo đặt chỗ',text:'Văn bản đặt chỗ',edit:'Edit Placeholder',textMissing:'The placeholder must contain text.'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','it',{placeholder:{title:'Proprietà segnaposto',toolbar:'Crea segnaposto',text:'Testo segnaposto',edit:'Modifica segnaposto',textMissing:'Il segnaposto deve contenere del testo.'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','nl',{placeholder:{title:'Eigenschappen placeholder',toolbar:'Placeholder aanmaken',text:'Placeholder tekst',edit:'Placeholder wijzigen',textMissing:'De placeholder moet tekst bevatten.'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','da',{placeholder:{title:'Egenskaber for pladsholder',toolbar:'Opret pladsholder',text:'Tekst til pladsholder',edit:'Rediger pladsholder',textMissing:'Pladsholder skal indeholde tekst'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','et',{placeholder:{title:'Kohahoidja omadused',toolbar:'Kohahoidja loomine',text:'Kohahoidja tekst',edit:'Kohahoidja muutmine',textMissing:'Kohahoidja peab sisaldama teksti.'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','pl',{placeholder:{title:'Właściwości wypełniacza',toolbar:'Utwórz wypełniacz',text:'Tekst wypełnienia',edit:'Edytuj wypełnienie',textMissing:'Wypełnienie musi posiadać jakiś tekst.'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','cs',{placeholder:{title:'Vlastnosti vyhrazeného prostoru',toolbar:'Vytvořit vyhrazený prostor',text:'Vyhrazený text',edit:'Upravit vyhrazený prostor',textMissing:'Vyhrazený prostor musí obsahovat text.'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','hr',{placeholder:{title:'Svojstva rezerviranog mjesta',toolbar:'Napravi rezervirano mjesto',text:'Tekst rezerviranog mjesta',edit:'Uredi rezervirano mjesto',textMissing:'Rezervirano mjesto mora sadržavati tekst.'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','fi',{placeholder:{title:'Paikkamerkin ominaisuudet',toolbar:'Luo paikkamerkki',text:'Paikkamerkin teksti',edit:'Muokkaa paikkamerkkiä',textMissing:'Paikkamerkin täytyy sisältää tekstiä'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','ug',{placeholder:{title:'ئورۇن بەلگە خاسلىقى',toolbar:'ئورۇن بەلگە قۇر',text:'ئورۇن بەلگە تېكىستى',edit:'ئورۇن بەلگە تەھرىر',textMissing:'ئورۇن بەلگىسىدە چوقۇم تېكىست بولۇشى لازىم'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','zh-cn',{placeholder:{title:'占位符属性',toolbar:'创建占位符',text:'占位符文字',edit:'编辑占位符',textMissing:'占位符必需包含有文字'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','bg',{placeholder:{title:'Настройки на контейнера',toolbar:'Нов контейнер',text:'Текст за контейнера',edit:'Промяна на контейнер',textMissing:'Контейнера трябва да съдържа текст.'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','en',{placeholder:{title:'Placeholder Properties',toolbar:'Create Placeholder',text:'Placeholder Text',edit:'Edit Placeholder',textMissing:'The placeholder must contain text.'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add('docprops',{init:function(a){var b=new CKEDITOR.dialogCommand('docProps');b.modes={wysiwyg:a.config.fullPage};a.addCommand('docProps',b);CKEDITOR.dialog.add('docProps',this.path+'dialogs/docprops.js');a.ui.addButton('DocProps',{label:a.lang.docprops.label,command:'docProps'});}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','cy',{uicolor:{title:"Dewisydd Lliwiau'r UI",preview:'Rhagolwg Byw',config:"Gludwch y llinyn hwn i'ch ffeil config.js",predefined:"Setiau lliw wedi'u cyn-ddiffinio"}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','tr',{uicolor:{title:'UI Renk Seçicisi',preview:'Canlı önizleme',config:'Bu dizeyi config.js dosyasının içine yapıştırın',predefined:'Önceden tanımlanmış renk kümeleri'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','nb',{uicolor:{title:'Fargevelger for brukergrensesnitt',preview:'Forhåndsvisning i sanntid',config:'Lim inn følgende tekst i din config.js-fil',predefined:'Forhåndsdefinerte fargesett'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','fr',{uicolor:{title:'UI Sélecteur de couleur',preview:'Aperçu',config:'Collez cette chaîne de caractères dans votre fichier config.js',predefined:'Palettes de couleurs prédéfinies'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','fa',{uicolor:{title:'انتخاب رنگ UI',preview:'پیشنمایش زنده',config:'این رشته را در فایل config.js خود بچسبانید.',predefined:'مجموعه رنگ از پیش تعریف شده'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','eo',{uicolor:{title:'UI Kolorselektilo',preview:'Vidigi la aspekton',config:'Gluu tiun signoĉenon en vian dosieron config.js',predefined:'Antaŭdifinita koloraro'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','uk',{uicolor:{title:'Color Picker Інтерфейс',preview:'Перегляд наживо',config:'Вставте цей рядок у файл config.js',predefined:'Стандартний набір кольорів'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','he',{uicolor:{title:'בחירת צבע ממשק משתמש',preview:'תצוגה מקדימה',config:'הדבק את הטקסט הבא לתוך הקובץ config.js',predefined:'קבוצות צבעים מוגדרות מראש'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','de',{uicolor:{title:'UI Pipette',preview:'Live-Vorschau',config:"Fügen Sie diese Zeichenfolge in die 'config.js' Datei.",predefined:'Vordefinierte Farbsätze'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','no',{uicolor:{title:'Fargevelger for brukergrensesnitt',preview:'Forhåndsvisning i sanntid',config:'Lim inn følgende tekst i din config.js-fil',predefined:'Forhåndsdefinerte fargesett'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','el',{uicolor:{title:'Διεπαφή Επιλογέα Χρωμάτων',preview:'Ζωντανή Προεπισκόπηση',config:'Επικολλήστε αυτό το κείμενο στο αρχείο config.js',predefined:'Προκαθορισμένα σύνολα χρωμάτων'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','vi',{uicolor:{title:'Giao diện người dùng Color Picker',preview:'Xem trước trực tiếp',config:'Dán chuỗi này vào tập tin config.js của bạn',predefined:'Tập màu định nghĩa sẵn'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','mk',{uicolor:{title:'Палета со бои',preview:'Преглед',config:'Залепи го овој текст во config.js датотеката',predefined:'Предефинирани множества на бои'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','it',{uicolor:{title:'Selettore Colore UI',preview:'Anteprima Live',config:'Incolla questa stringa nel tuo file config.js',predefined:'Set di colori predefiniti'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','nl',{uicolor:{title:'UI Kleurenkiezer',preview:'Live voorbeeld',config:'Plak deze tekst in jouw config.js bestand',predefined:'Voorgedefinieerde kleurensets'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','da',{uicolor:{title:'Brugerflade på farvevælger',preview:'Vis liveeksempel',config:'Indsæt denne streng i din config.js fil',predefined:'Prædefinerede farveskemaer'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','et',{uicolor:{title:'Värvivalija kasutajaliides',preview:'Automaatne eelvaade',config:'Aseta see sõne oma config.js faili.',predefined:'Eelmääratud värvikomplektid'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','pl',{uicolor:{title:'Wybór koloru interfejsu',preview:'Podgląd na żywo',config:'Wklej poniższy łańcuch znaków do pliku config.js:',predefined:'Predefiniowane zestawy kolorów'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','cs',{uicolor:{title:'Výběr barvy rozhraní',preview:'Živý náhled',config:'Vložte tento řetězec do Vašeho souboru config.js',predefined:'Přednastavené sady barev'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','hr',{uicolor:{title:'UI odabir boja',preview:'Pregled uživo',config:'Zalijepite ovaj tekst u Vašu config.js datoteku.',predefined:'Već postavljeni setovi boja'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','fi',{uicolor:{title:'Käyttöliittymän värivalitsin',preview:'Esikatsele',config:'Liitä tämä merkkijono config.js tiedostoosi',predefined:'Esimääritellyt värijoukot'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','ug',{uicolor:{title:'ئىشلەتكۈچى ئارايۈزى رەڭ تاللىغۇچ',preview:'شۇئان ئالدىن كۆزىتىش',config:'بۇ ھەرپ تىزىقىنى config.js ھۆججەتكە چاپلايدۇ',predefined:'ئالدىن بەلگىلەنگەن رەڭلەر'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','zh-cn',{uicolor:{title:'用户界面颜色选择器',preview:'即时预览',config:'粘贴此字符串到你的 config.js 文件',predefined:'预定义颜色集'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','bg',{uicolor:{title:'ПИ избор на цвят',preview:'Преглед',config:'Вмъкнете този низ във Вашия config.js fajl',predefined:'Предефинирани цветови палитри'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','cy',{devTools:{title:'Gwybodaeth am yr Elfen',dialogName:'Enw ffenestr y deialog',tabName:"Enw'r tab",elementId:'ID yr Elfen',elementType:'Math yr elfen'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','tr',{devTools:{title:'Eleman Bilgisi',dialogName:'İletişim pencere ismi',tabName:'Sekme adı',elementId:'Eleman ID',elementType:'Eleman türü'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','nb',{devTools:{title:'Elementinformasjon',dialogName:'Navn på dialogvindu',tabName:'Navn på fane',elementId:'Element-ID',elementType:'Elementtype'}});
|
JavaScript
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','fr',{devTools:{title:"Information sur l'élément",dialogName:'Nom de la fenêtre de dialogue',tabName:"Nom de l'onglet",elementId:"ID de l'élément",elementType:"Type de l'élément"}});
|
JavaScript
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.