code
stringlengths 1
2.08M
| language
stringclasses 1
value |
|---|---|
/**
JSZip - A Javascript class for generating Zip files
<http://jszip.stuartk.co.uk>
(c) 2009 Stuart Knightley <stuart [at] stuartk.co.uk>
Licenced under the GPLv3 and the MIT licences
Usage:
zip = new JSZip();
zip.add("hello.txt", "Hello, World!").add("tempfile", "nothing");
zip.folder("images").add("smile.gif", base64Data, {base64: true});
zip.add("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
zip.remove("tempfile");
base64zip = zip.generate();
**/
function JSZip(compression)
{
// default : no compression
this.compression = (compression || "STORE").toUpperCase();
this.files = [];
// Where we are in the hierarchy
this.root = "";
// Default properties for a new file
this.d = {
base64: false,
binary: false,
dir: false,
date: null
};
if (!JSZip.compressions[this.compression]) {
throw compression + " is not a valid compression method !";
}
}
/**
* Add a file to the zip file
* @param name The name of the file
* @param data The file data, either raw or base64 encoded
* @param o File options
* @return this JSZip object
*/
JSZip.prototype.add = function(name, data, o)
{
o = o || {};
name = this.root+name;
if (o.base64 === true && o.binary == null) o.binary = true;
for (var opt in this.d)
{
o[opt] = o[opt] || this.d[opt];
}
// date
// @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
// @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
// @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
o.date = o.date || new Date();
var dosTime, dosDate;
dosTime = o.date.getHours();
dosTime = dosTime << 6;
dosTime = dosTime | o.date.getMinutes();
dosTime = dosTime << 5;
dosTime = dosTime | o.date.getSeconds() / 2;
dosDate = o.date.getFullYear() - 1980;
dosDate = dosDate << 4;
dosDate = dosDate | (o.date.getMonth() + 1);
dosDate = dosDate << 5;
dosDate = dosDate | o.date.getDate();
if (o.base64 === true) data = JSZipBase64.decode(data);
// decode UTF-8 strings if we are dealing with text data
if(o.binary === false) data = this.utf8encode(data);
var compression = JSZip.compressions[this.compression];
var compressedData = compression.compress(data);
var header = "";
// version needed to extract
header += "\x0A\x00";
// general purpose bit flag
header += "\x00\x00";
// compression method
header += compression.magic;
// last mod file time
header += this.decToHex(dosTime, 2);
// last mod file date
header += this.decToHex(dosDate, 2);
// crc-32
header += this.decToHex(this.crc32(data), 4);
// compressed size
header += this.decToHex(compressedData.length, 4);
// uncompressed size
header += this.decToHex(data.length, 4);
// file name length
header += this.decToHex(name.length, 2);
// extra field length
header += "\x00\x00";
// file name
this.files[name] = {header: header, data: compressedData, dir: o.dir};
return this;
};
/**
* Add a directory to the zip file
* @param name The name of the directory to add
* @return JSZip object with the new directory as the root
*/
JSZip.prototype.folder = function(name)
{
// Check the name ends with a /
if (name.substr(-1) != "/") name += "/";
// Does this folder already exist?
if (typeof this.files[name] === "undefined") this.add(name, '', {dir:true});
// Allow chaining by returning a new object with this folder as the root
var ret = this.clone();
ret.root = this.root+name;
return ret;
};
/**
* Compare a string or regular expression against all of the filenames and
* return an informational object for each that matches.
* @param string/regex The regular expression to test against
* @return An array of objects representing the matched files. In the form
* {name: "filename", data: "file data", dir: true/false}
*/
JSZip.prototype.find = function(needle)
{
var result = [], re;
if (typeof needle === "string")
{
re = new RegExp("^"+needle+"$");
}
else
{
re = needle;
}
for (var filename in this.files)
{
if (re.test(filename))
{
var file = this.files[filename];
result.push({name: filename, data: file.data, dir: !!file.dir});
}
}
return result;
};
/**
* Delete a file, or a directory and all sub-files, from the zip
* @param name the name of the file to delete
* @return this JSZip object
*/
JSZip.prototype.remove = function(name)
{
var file = this.files[name];
if (!file)
{
// Look for any folders
if (name.substr(-1) != "/") name += "/";
file = this.files[name];
}
if (file)
{
if (name.match("/") === null)
{
// file
delete this.files[name];
}
else
{
// folder
var kids = this.find(new RegExp("^"+name));
for (var i = 0; i < kids.length; i++)
{
if (kids[i].name == name)
{
// Delete this folder
delete this.files[name];
}
else
{
// Remove a child of this folder
this.remove(kids[i].name);
}
}
}
}
return this;
};
/**
* Generate the complete zip file
* @return A base64 encoded string of the zip file
*/
JSZip.prototype.generate = function(asBytes)
{
asBytes = asBytes || false;
// The central directory, and files data
var directory = [], files = [], fileOffset = 0;
for (var name in this.files)
{
if( !this.files.hasOwnProperty(name) ) { continue; }
var fileRecord = "", dirRecord = "";
fileRecord = "\x50\x4b\x03\x04" + this.files[name].header + name + this.files[name].data;
dirRecord = "\x50\x4b\x01\x02" +
// version made by (00: DOS)
"\x14\x00" +
// file header (common to file and central directory)
this.files[name].header +
// file comment length
"\x00\x00" +
// disk number start
"\x00\x00" +
// internal file attributes TODO
"\x00\x00" +
// external file attributes
(this.files[name].dir===true?"\x10\x00\x00\x00":"\x00\x00\x00\x00")+
// relative offset of local header
this.decToHex(fileOffset, 4) +
// file name
name;
fileOffset += fileRecord.length;
files.push(fileRecord);
directory.push(dirRecord);
}
var fileData = files.join("");
var dirData = directory.join("");
var dirEnd = "";
// end of central dir signature
dirEnd = "\x50\x4b\x05\x06" +
// number of this disk
"\x00\x00" +
// number of the disk with the start of the central directory
"\x00\x00" +
// total number of entries in the central directory on this disk
this.decToHex(files.length, 2) +
// total number of entries in the central directory
this.decToHex(files.length, 2) +
// size of the central directory 4 bytes
this.decToHex(dirData.length, 4) +
// offset of start of central directory with respect to the starting disk number
this.decToHex(fileData.length, 4) +
// .ZIP file comment length
"\x00\x00";
var zip = fileData + dirData + dirEnd;
return (asBytes) ? zip : JSZipBase64.encode(zip);
};
/*
* Compression methods
* This object is filled in as follow :
* name : {
* magic // the 2 bytes indentifying the compression method
* compress // function, take the uncompressed content and return it compressed.
* }
*
* STORE is the default compression method, so it's included in this file.
* Other methods should go to separated files : the user wants modularity.
*/
JSZip.compressions = {
"STORE" : {
magic : "\x00\x00",
compress : function (content) {
return content; // no compression
}
}
};
// Utility functions
JSZip.prototype.decToHex = function(dec, bytes)
{
var hex = "";
for(var i=0;i<bytes;i++) {
hex += String.fromCharCode(dec&0xff);
dec=dec>>>8;
}
return hex;
};
/**
*
* Javascript crc32
* http://www.webtoolkit.info/
*
**/
JSZip.prototype.crc32 = function(str, crc)
{
if (str === "") return "\x00\x00\x00\x00";
var table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";
if (typeof(crc) == "undefined") { crc = 0; }
var x = 0;
var y = 0;
crc = crc ^ (-1);
for( var i = 0, iTop = str.length; i < iTop; i++ ) {
y = ( crc ^ str.charCodeAt( i ) ) & 0xFF;
x = "0x" + table.substr( y * 9, 8 );
crc = ( crc >>> 8 ) ^ x;
}
return crc ^ (-1);
};
// Inspired by http://my.opera.com/GreyWyvern/blog/show.dml/1725165
JSZip.prototype.clone = function()
{
var newObj = new JSZip();
for (var i in this)
{
if (typeof this[i] !== "function")
{
newObj[i] = this[i];
}
}
return newObj;
};
JSZip.prototype.utf8encode = function(input)
{
input = encodeURIComponent(input);
input = input.replace(/%.{2,2}/g, function(m) {
var hex = m.substring(1);
return String.fromCharCode(parseInt(hex,16));
});
return input;
};
/**
*
* Base64 encode / decode
* http://www.webtoolkit.info/
*
* Hacked so that it doesn't utf8 en/decode everything
**/
var JSZipBase64 = function() {
// private property
var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
return {
// public method for encoding
encode : function(input, utf8) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function(input, utf8) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = _keyStr.indexOf(input.charAt(i++));
enc2 = _keyStr.indexOf(input.charAt(i++));
enc3 = _keyStr.indexOf(input.charAt(i++));
enc4 = _keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
return output;
}
};
}();
|
JavaScript
|
/*
* Port of a script by Masanao Izumo.
*
* Only changes : wrap all the variables in a function and add the
* main function to JSZip (DEFLATE compression method).
* Everything else was written by M. Izumo.
*
* Original code can be found here: http://www.onicos.com/staff/iz/amuse/javascript/expert/inflate.txt
*/
if(!JSZip)
{
throw "JSZip not defined";
}
/*
* Original:
* http://www.onicos.com/staff/iz/amuse/javascript/expert/deflate.txt
*/
(function(){
/* Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
* Version: 1.0.1
* LastModified: Dec 25 1999
*/
/* Interface:
* data = zip_deflate(src);
*/
/* constant parameters */
var zip_WSIZE = 32768; // Sliding Window size
var zip_STORED_BLOCK = 0;
var zip_STATIC_TREES = 1;
var zip_DYN_TREES = 2;
/* for deflate */
var zip_DEFAULT_LEVEL = 6;
var zip_FULL_SEARCH = true;
var zip_INBUFSIZ = 32768; // Input buffer size
var zip_INBUF_EXTRA = 64; // Extra buffer
var zip_OUTBUFSIZ = 1024 * 8;
var zip_window_size = 2 * zip_WSIZE;
var zip_MIN_MATCH = 3;
var zip_MAX_MATCH = 258;
var zip_BITS = 16;
// for SMALL_MEM
var zip_LIT_BUFSIZE = 0x2000;
var zip_HASH_BITS = 13;
// for MEDIUM_MEM
// var zip_LIT_BUFSIZE = 0x4000;
// var zip_HASH_BITS = 14;
// for BIG_MEM
// var zip_LIT_BUFSIZE = 0x8000;
// var zip_HASH_BITS = 15;
if(zip_LIT_BUFSIZE > zip_INBUFSIZ)
alert("error: zip_INBUFSIZ is too small");
if((zip_WSIZE<<1) > (1<<zip_BITS))
alert("error: zip_WSIZE is too large");
if(zip_HASH_BITS > zip_BITS-1)
alert("error: zip_HASH_BITS is too large");
if(zip_HASH_BITS < 8 || zip_MAX_MATCH != 258)
alert("error: Code too clever");
var zip_DIST_BUFSIZE = zip_LIT_BUFSIZE;
var zip_HASH_SIZE = 1 << zip_HASH_BITS;
var zip_HASH_MASK = zip_HASH_SIZE - 1;
var zip_WMASK = zip_WSIZE - 1;
var zip_NIL = 0; // Tail of hash chains
var zip_TOO_FAR = 4096;
var zip_MIN_LOOKAHEAD = zip_MAX_MATCH + zip_MIN_MATCH + 1;
var zip_MAX_DIST = zip_WSIZE - zip_MIN_LOOKAHEAD;
var zip_SMALLEST = 1;
var zip_MAX_BITS = 15;
var zip_MAX_BL_BITS = 7;
var zip_LENGTH_CODES = 29;
var zip_LITERALS =256;
var zip_END_BLOCK = 256;
var zip_L_CODES = zip_LITERALS + 1 + zip_LENGTH_CODES;
var zip_D_CODES = 30;
var zip_BL_CODES = 19;
var zip_REP_3_6 = 16;
var zip_REPZ_3_10 = 17;
var zip_REPZ_11_138 = 18;
var zip_HEAP_SIZE = 2 * zip_L_CODES + 1;
var zip_H_SHIFT = parseInt((zip_HASH_BITS + zip_MIN_MATCH - 1) /
zip_MIN_MATCH);
/* variables */
var zip_free_queue;
var zip_qhead, zip_qtail;
var zip_initflag;
var zip_outbuf = null;
var zip_outcnt, zip_outoff;
var zip_complete;
var zip_window;
var zip_d_buf;
var zip_l_buf;
var zip_prev;
var zip_bi_buf;
var zip_bi_valid;
var zip_block_start;
var zip_ins_h;
var zip_hash_head;
var zip_prev_match;
var zip_match_available;
var zip_match_length;
var zip_prev_length;
var zip_strstart;
var zip_match_start;
var zip_eofile;
var zip_lookahead;
var zip_max_chain_length;
var zip_max_lazy_match;
var zip_compr_level;
var zip_good_match;
var zip_nice_match;
var zip_dyn_ltree;
var zip_dyn_dtree;
var zip_static_ltree;
var zip_static_dtree;
var zip_bl_tree;
var zip_l_desc;
var zip_d_desc;
var zip_bl_desc;
var zip_bl_count;
var zip_heap;
var zip_heap_len;
var zip_heap_max;
var zip_depth;
var zip_length_code;
var zip_dist_code;
var zip_base_length;
var zip_base_dist;
var zip_flag_buf;
var zip_last_lit;
var zip_last_dist;
var zip_last_flags;
var zip_flags;
var zip_flag_bit;
var zip_opt_len;
var zip_static_len;
var zip_deflate_data;
var zip_deflate_pos;
/* objects (deflate) */
var zip_DeflateCT = function() {
this.fc = 0; // frequency count or bit string
this.dl = 0; // father node in Huffman tree or length of bit string
}
var zip_DeflateTreeDesc = function() {
this.dyn_tree = null; // the dynamic tree
this.static_tree = null; // corresponding static tree or NULL
this.extra_bits = null; // extra bits for each code or NULL
this.extra_base = 0; // base index for extra_bits
this.elems = 0; // max number of elements in the tree
this.max_length = 0; // max bit length for the codes
this.max_code = 0; // largest code with non zero frequency
}
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
var zip_DeflateConfiguration = function(a, b, c, d) {
this.good_length = a; // reduce lazy search above this match length
this.max_lazy = b; // do not perform lazy search above this match length
this.nice_length = c; // quit search above this match length
this.max_chain = d;
}
var zip_DeflateBuffer = function() {
this.next = null;
this.len = 0;
this.ptr = new Array(zip_OUTBUFSIZ);
this.off = 0;
}
/* constant tables */
var zip_extra_lbits = new Array(
0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0);
var zip_extra_dbits = new Array(
0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13);
var zip_extra_blbits = new Array(
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7);
var zip_bl_order = new Array(
16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15);
var zip_configuration_table = new Array(
new zip_DeflateConfiguration(0, 0, 0, 0),
new zip_DeflateConfiguration(4, 4, 8, 4),
new zip_DeflateConfiguration(4, 5, 16, 8),
new zip_DeflateConfiguration(4, 6, 32, 32),
new zip_DeflateConfiguration(4, 4, 16, 16),
new zip_DeflateConfiguration(8, 16, 32, 32),
new zip_DeflateConfiguration(8, 16, 128, 128),
new zip_DeflateConfiguration(8, 32, 128, 256),
new zip_DeflateConfiguration(32, 128, 258, 1024),
new zip_DeflateConfiguration(32, 258, 258, 4096));
/* routines (deflate) */
var zip_deflate_start = function(level) {
var i;
if(!level)
level = zip_DEFAULT_LEVEL;
else if(level < 1)
level = 1;
else if(level > 9)
level = 9;
zip_compr_level = level;
zip_initflag = false;
zip_eofile = false;
if(zip_outbuf != null)
return;
zip_free_queue = zip_qhead = zip_qtail = null;
zip_outbuf = new Array(zip_OUTBUFSIZ);
zip_window = new Array(zip_window_size);
zip_d_buf = new Array(zip_DIST_BUFSIZE);
zip_l_buf = new Array(zip_INBUFSIZ + zip_INBUF_EXTRA);
zip_prev = new Array(1 << zip_BITS);
zip_dyn_ltree = new Array(zip_HEAP_SIZE);
for(i = 0; i < zip_HEAP_SIZE; i++)
zip_dyn_ltree[i] = new zip_DeflateCT();
zip_dyn_dtree = new Array(2*zip_D_CODES+1);
for(i = 0; i < 2*zip_D_CODES+1; i++)
zip_dyn_dtree[i] = new zip_DeflateCT();
zip_static_ltree = new Array(zip_L_CODES+2);
for(i = 0; i < zip_L_CODES+2; i++)
zip_static_ltree[i] = new zip_DeflateCT();
zip_static_dtree = new Array(zip_D_CODES);
for(i = 0; i < zip_D_CODES; i++)
zip_static_dtree[i] = new zip_DeflateCT();
zip_bl_tree = new Array(2*zip_BL_CODES+1);
for(i = 0; i < 2*zip_BL_CODES+1; i++)
zip_bl_tree[i] = new zip_DeflateCT();
zip_l_desc = new zip_DeflateTreeDesc();
zip_d_desc = new zip_DeflateTreeDesc();
zip_bl_desc = new zip_DeflateTreeDesc();
zip_bl_count = new Array(zip_MAX_BITS+1);
zip_heap = new Array(2*zip_L_CODES+1);
zip_depth = new Array(2*zip_L_CODES+1);
zip_length_code = new Array(zip_MAX_MATCH-zip_MIN_MATCH+1);
zip_dist_code = new Array(512);
zip_base_length = new Array(zip_LENGTH_CODES);
zip_base_dist = new Array(zip_D_CODES);
zip_flag_buf = new Array(parseInt(zip_LIT_BUFSIZE / 8));
}
var zip_deflate_end = function() {
zip_free_queue = zip_qhead = zip_qtail = null;
zip_outbuf = null;
zip_window = null;
zip_d_buf = null;
zip_l_buf = null;
zip_prev = null;
zip_dyn_ltree = null;
zip_dyn_dtree = null;
zip_static_ltree = null;
zip_static_dtree = null;
zip_bl_tree = null;
zip_l_desc = null;
zip_d_desc = null;
zip_bl_desc = null;
zip_bl_count = null;
zip_heap = null;
zip_depth = null;
zip_length_code = null;
zip_dist_code = null;
zip_base_length = null;
zip_base_dist = null;
zip_flag_buf = null;
}
var zip_reuse_queue = function(p) {
p.next = zip_free_queue;
zip_free_queue = p;
}
var zip_new_queue = function() {
var p;
if(zip_free_queue != null)
{
p = zip_free_queue;
zip_free_queue = zip_free_queue.next;
}
else
p = new zip_DeflateBuffer();
p.next = null;
p.len = p.off = 0;
return p;
}
var zip_head1 = function(i) {
return zip_prev[zip_WSIZE + i];
}
var zip_head2 = function(i, val) {
return zip_prev[zip_WSIZE + i] = val;
}
/* put_byte is used for the compressed output, put_ubyte for the
* uncompressed output. However unlzw() uses window for its
* suffix table instead of its output buffer, so it does not use put_ubyte
* (to be cleaned up).
*/
var zip_put_byte = function(c) {
zip_outbuf[zip_outoff + zip_outcnt++] = c;
if(zip_outoff + zip_outcnt == zip_OUTBUFSIZ)
zip_qoutbuf();
}
/* Output a 16 bit value, lsb first */
var zip_put_short = function(w) {
w &= 0xffff;
if(zip_outoff + zip_outcnt < zip_OUTBUFSIZ - 2) {
zip_outbuf[zip_outoff + zip_outcnt++] = (w & 0xff);
zip_outbuf[zip_outoff + zip_outcnt++] = (w >>> 8);
} else {
zip_put_byte(w & 0xff);
zip_put_byte(w >>> 8);
}
}
/* ==========================================================================
* Insert string s in the dictionary and set match_head to the previous head
* of the hash chain (the most recent string with same hash key). Return
* the previous length of the hash chain.
* IN assertion: all calls to to INSERT_STRING are made with consecutive
* input characters and the first MIN_MATCH bytes of s are valid
* (except for the last MIN_MATCH-1 bytes of the input file).
*/
var zip_INSERT_STRING = function() {
zip_ins_h = ((zip_ins_h << zip_H_SHIFT)
^ (zip_window[zip_strstart + zip_MIN_MATCH - 1] & 0xff))
& zip_HASH_MASK;
zip_hash_head = zip_head1(zip_ins_h);
zip_prev[zip_strstart & zip_WMASK] = zip_hash_head;
zip_head2(zip_ins_h, zip_strstart);
}
/* Send a code of the given tree. c and tree must not have side effects */
var zip_SEND_CODE = function(c, tree) {
zip_send_bits(tree[c].fc, tree[c].dl);
}
/* Mapping from a distance to a distance code. dist is the distance - 1 and
* must not have side effects. dist_code[256] and dist_code[257] are never
* used.
*/
var zip_D_CODE = function(dist) {
return (dist < 256 ? zip_dist_code[dist]
: zip_dist_code[256 + (dist>>7)]) & 0xff;
}
/* ==========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
var zip_SMALLER = function(tree, n, m) {
return tree[n].fc < tree[m].fc ||
(tree[n].fc == tree[m].fc && zip_depth[n] <= zip_depth[m]);
}
/* ==========================================================================
* read string data
*/
var zip_read_buff = function(buff, offset, n) {
var i;
for(i = 0; i < n && zip_deflate_pos < zip_deflate_data.length; i++)
buff[offset + i] =
zip_deflate_data.charCodeAt(zip_deflate_pos++) & 0xff;
return i;
}
/* ==========================================================================
* Initialize the "longest match" routines for a new file
*/
var zip_lm_init = function() {
var j;
/* Initialize the hash table. */
for(j = 0; j < zip_HASH_SIZE; j++)
// zip_head2(j, zip_NIL);
zip_prev[zip_WSIZE + j] = 0;
/* prev will be initialized on the fly */
/* Set the default configuration parameters:
*/
zip_max_lazy_match = zip_configuration_table[zip_compr_level].max_lazy;
zip_good_match = zip_configuration_table[zip_compr_level].good_length;
if(!zip_FULL_SEARCH)
zip_nice_match = zip_configuration_table[zip_compr_level].nice_length;
zip_max_chain_length = zip_configuration_table[zip_compr_level].max_chain;
zip_strstart = 0;
zip_block_start = 0;
zip_lookahead = zip_read_buff(zip_window, 0, 2 * zip_WSIZE);
if(zip_lookahead <= 0) {
zip_eofile = true;
zip_lookahead = 0;
return;
}
zip_eofile = false;
/* Make sure that we always have enough lookahead. This is important
* if input comes from a device such as a tty.
*/
while(zip_lookahead < zip_MIN_LOOKAHEAD && !zip_eofile)
zip_fill_window();
/* If lookahead < MIN_MATCH, ins_h is garbage, but this is
* not important since only literal bytes will be emitted.
*/
zip_ins_h = 0;
for(j = 0; j < zip_MIN_MATCH - 1; j++) {
// UPDATE_HASH(ins_h, window[j]);
zip_ins_h = ((zip_ins_h << zip_H_SHIFT) ^ (zip_window[j] & 0xff)) & zip_HASH_MASK;
}
}
/* ==========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
*/
var zip_longest_match = function(cur_match) {
var chain_length = zip_max_chain_length; // max hash chain length
var scanp = zip_strstart; // current string
var matchp; // matched string
var len; // length of current match
var best_len = zip_prev_length; // best match length so far
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
var limit = (zip_strstart > zip_MAX_DIST ? zip_strstart - zip_MAX_DIST : zip_NIL);
var strendp = zip_strstart + zip_MAX_MATCH;
var scan_end1 = zip_window[scanp + best_len - 1];
var scan_end = zip_window[scanp + best_len];
/* Do not waste too much time if we already have a good match: */
if(zip_prev_length >= zip_good_match)
chain_length >>= 2;
// Assert(encoder->strstart <= window_size-MIN_LOOKAHEAD, "insufficient lookahead");
do {
// Assert(cur_match < encoder->strstart, "no future");
matchp = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2:
*/
if(zip_window[matchp + best_len] != scan_end ||
zip_window[matchp + best_len - 1] != scan_end1 ||
zip_window[matchp] != zip_window[scanp] ||
zip_window[++matchp] != zip_window[scanp + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scanp += 2;
matchp++;
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
} while(zip_window[++scanp] == zip_window[++matchp] &&
zip_window[++scanp] == zip_window[++matchp] &&
zip_window[++scanp] == zip_window[++matchp] &&
zip_window[++scanp] == zip_window[++matchp] &&
zip_window[++scanp] == zip_window[++matchp] &&
zip_window[++scanp] == zip_window[++matchp] &&
zip_window[++scanp] == zip_window[++matchp] &&
zip_window[++scanp] == zip_window[++matchp] &&
scanp < strendp);
len = zip_MAX_MATCH - (strendp - scanp);
scanp = strendp - zip_MAX_MATCH;
if(len > best_len) {
zip_match_start = cur_match;
best_len = len;
if(zip_FULL_SEARCH) {
if(len >= zip_MAX_MATCH) break;
} else {
if(len >= zip_nice_match) break;
}
scan_end1 = zip_window[scanp + best_len-1];
scan_end = zip_window[scanp + best_len];
}
} while((cur_match = zip_prev[cur_match & zip_WMASK]) > limit
&& --chain_length != 0);
return best_len;
}
/* ==========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead, and sets eofile if end of input file.
* IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
* OUT assertions: at least one byte has been read, or eofile is set;
* file reads are performed for at least two bytes (required for the
* translate_eol option).
*/
var zip_fill_window = function() {
var n, m;
// Amount of free space at the end of the window.
var more = zip_window_size - zip_lookahead - zip_strstart;
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if(more == -1) {
/* Very unlikely, but possible on 16 bit machine if strstart == 0
* and lookahead == 1 (input done one byte at time)
*/
more--;
} else if(zip_strstart >= zip_WSIZE + zip_MAX_DIST) {
/* By the IN assertion, the window is not empty so we can't confuse
* more == 0 with more == 64K on a 16 bit machine.
*/
// Assert(window_size == (ulg)2*WSIZE, "no sliding with BIG_MEM");
// System.arraycopy(window, WSIZE, window, 0, WSIZE);
for(n = 0; n < zip_WSIZE; n++)
zip_window[n] = zip_window[n + zip_WSIZE];
zip_match_start -= zip_WSIZE;
zip_strstart -= zip_WSIZE; /* we now have strstart >= MAX_DIST: */
zip_block_start -= zip_WSIZE;
for(n = 0; n < zip_HASH_SIZE; n++) {
m = zip_head1(n);
zip_head2(n, m >= zip_WSIZE ? m - zip_WSIZE : zip_NIL);
}
for(n = 0; n < zip_WSIZE; n++) {
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
m = zip_prev[n];
zip_prev[n] = (m >= zip_WSIZE ? m - zip_WSIZE : zip_NIL);
}
more += zip_WSIZE;
}
// At this point, more >= 2
if(!zip_eofile) {
n = zip_read_buff(zip_window, zip_strstart + zip_lookahead, more);
if(n <= 0)
zip_eofile = true;
else
zip_lookahead += n;
}
}
/* ==========================================================================
* Processes a new input file and return its compressed length. This
* function does not perform lazy evaluationof matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
var zip_deflate_fast = function() {
while(zip_lookahead != 0 && zip_qhead == null) {
var flush; // set if current block must be flushed
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
zip_INSERT_STRING();
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if(zip_hash_head != zip_NIL &&
zip_strstart - zip_hash_head <= zip_MAX_DIST) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
zip_match_length = zip_longest_match(zip_hash_head);
/* longest_match() sets match_start */
if(zip_match_length > zip_lookahead)
zip_match_length = zip_lookahead;
}
if(zip_match_length >= zip_MIN_MATCH) {
// check_match(strstart, match_start, match_length);
flush = zip_ct_tally(zip_strstart - zip_match_start,
zip_match_length - zip_MIN_MATCH);
zip_lookahead -= zip_match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if(zip_match_length <= zip_max_lazy_match) {
zip_match_length--; // string at strstart already in hash table
do {
zip_strstart++;
zip_INSERT_STRING();
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
* these bytes are garbage, but it does not matter since
* the next lookahead bytes will be emitted as literals.
*/
} while(--zip_match_length != 0);
zip_strstart++;
} else {
zip_strstart += zip_match_length;
zip_match_length = 0;
zip_ins_h = zip_window[zip_strstart] & 0xff;
// UPDATE_HASH(ins_h, window[strstart + 1]);
zip_ins_h = ((zip_ins_h<<zip_H_SHIFT) ^ (zip_window[zip_strstart + 1] & 0xff)) & zip_HASH_MASK;
//#if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
}
} else {
/* No match, output a literal byte */
flush = zip_ct_tally(0, zip_window[zip_strstart] & 0xff);
zip_lookahead--;
zip_strstart++;
}
if(flush) {
zip_flush_block(0);
zip_block_start = zip_strstart;
}
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
while(zip_lookahead < zip_MIN_LOOKAHEAD && !zip_eofile)
zip_fill_window();
}
}
var zip_deflate_better = function() {
/* Process the input block. */
while(zip_lookahead != 0 && zip_qhead == null) {
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
zip_INSERT_STRING();
/* Find the longest match, discarding those <= prev_length.
*/
zip_prev_length = zip_match_length;
zip_prev_match = zip_match_start;
zip_match_length = zip_MIN_MATCH - 1;
if(zip_hash_head != zip_NIL &&
zip_prev_length < zip_max_lazy_match &&
zip_strstart - zip_hash_head <= zip_MAX_DIST) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
zip_match_length = zip_longest_match(zip_hash_head);
/* longest_match() sets match_start */
if(zip_match_length > zip_lookahead)
zip_match_length = zip_lookahead;
/* Ignore a length 3 match if it is too distant: */
if(zip_match_length == zip_MIN_MATCH &&
zip_strstart - zip_match_start > zip_TOO_FAR) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
zip_match_length--;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if(zip_prev_length >= zip_MIN_MATCH &&
zip_match_length <= zip_prev_length) {
var flush; // set if current block must be flushed
// check_match(strstart - 1, prev_match, prev_length);
flush = zip_ct_tally(zip_strstart - 1 - zip_prev_match,
zip_prev_length - zip_MIN_MATCH);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted.
*/
zip_lookahead -= zip_prev_length - 1;
zip_prev_length -= 2;
do {
zip_strstart++;
zip_INSERT_STRING();
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
* these bytes are garbage, but it does not matter since the
* next lookahead bytes will always be emitted as literals.
*/
} while(--zip_prev_length != 0);
zip_match_available = 0;
zip_match_length = zip_MIN_MATCH - 1;
zip_strstart++;
if(flush) {
zip_flush_block(0);
zip_block_start = zip_strstart;
}
} else if(zip_match_available != 0) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
if(zip_ct_tally(0, zip_window[zip_strstart - 1] & 0xff)) {
zip_flush_block(0);
zip_block_start = zip_strstart;
}
zip_strstart++;
zip_lookahead--;
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
zip_match_available = 1;
zip_strstart++;
zip_lookahead--;
}
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
while(zip_lookahead < zip_MIN_LOOKAHEAD && !zip_eofile)
zip_fill_window();
}
}
var zip_init_deflate = function() {
if(zip_eofile)
return;
zip_bi_buf = 0;
zip_bi_valid = 0;
zip_ct_init();
zip_lm_init();
zip_qhead = null;
zip_outcnt = 0;
zip_outoff = 0;
if(zip_compr_level <= 3)
{
zip_prev_length = zip_MIN_MATCH - 1;
zip_match_length = 0;
}
else
{
zip_match_length = zip_MIN_MATCH - 1;
zip_match_available = 0;
}
zip_complete = false;
}
/* ==========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
var zip_deflate_internal = function(buff, off, buff_size) {
var n;
if(!zip_initflag)
{
zip_init_deflate();
zip_initflag = true;
if(zip_lookahead == 0) { // empty
zip_complete = true;
return 0;
}
}
if((n = zip_qcopy(buff, off, buff_size)) == buff_size)
return buff_size;
if(zip_complete)
return n;
if(zip_compr_level <= 3) // optimized for speed
zip_deflate_fast();
else
zip_deflate_better();
if(zip_lookahead == 0) {
if(zip_match_available != 0)
zip_ct_tally(0, zip_window[zip_strstart - 1] & 0xff);
zip_flush_block(1);
zip_complete = true;
}
return n + zip_qcopy(buff, n + off, buff_size - n);
}
var zip_qcopy = function(buff, off, buff_size) {
var n, i, j;
n = 0;
while(zip_qhead != null && n < buff_size)
{
i = buff_size - n;
if(i > zip_qhead.len)
i = zip_qhead.len;
// System.arraycopy(qhead.ptr, qhead.off, buff, off + n, i);
for(j = 0; j < i; j++)
buff[off + n + j] = zip_qhead.ptr[zip_qhead.off + j];
zip_qhead.off += i;
zip_qhead.len -= i;
n += i;
if(zip_qhead.len == 0) {
var p;
p = zip_qhead;
zip_qhead = zip_qhead.next;
zip_reuse_queue(p);
}
}
if(n == buff_size)
return n;
if(zip_outoff < zip_outcnt) {
i = buff_size - n;
if(i > zip_outcnt - zip_outoff)
i = zip_outcnt - zip_outoff;
// System.arraycopy(outbuf, outoff, buff, off + n, i);
for(j = 0; j < i; j++)
buff[off + n + j] = zip_outbuf[zip_outoff + j];
zip_outoff += i;
n += i;
if(zip_outcnt == zip_outoff)
zip_outcnt = zip_outoff = 0;
}
return n;
}
/* ==========================================================================
* Allocate the match buffer, initialize the various tables and save the
* location of the internal file attribute (ascii/binary) and method
* (DEFLATE/STORE).
*/
var zip_ct_init = function() {
var n; // iterates over tree elements
var bits; // bit counter
var length; // length value
var code; // code value
var dist; // distance index
if(zip_static_dtree[0].dl != 0) return; // ct_init already called
zip_l_desc.dyn_tree = zip_dyn_ltree;
zip_l_desc.static_tree = zip_static_ltree;
zip_l_desc.extra_bits = zip_extra_lbits;
zip_l_desc.extra_base = zip_LITERALS + 1;
zip_l_desc.elems = zip_L_CODES;
zip_l_desc.max_length = zip_MAX_BITS;
zip_l_desc.max_code = 0;
zip_d_desc.dyn_tree = zip_dyn_dtree;
zip_d_desc.static_tree = zip_static_dtree;
zip_d_desc.extra_bits = zip_extra_dbits;
zip_d_desc.extra_base = 0;
zip_d_desc.elems = zip_D_CODES;
zip_d_desc.max_length = zip_MAX_BITS;
zip_d_desc.max_code = 0;
zip_bl_desc.dyn_tree = zip_bl_tree;
zip_bl_desc.static_tree = null;
zip_bl_desc.extra_bits = zip_extra_blbits;
zip_bl_desc.extra_base = 0;
zip_bl_desc.elems = zip_BL_CODES;
zip_bl_desc.max_length = zip_MAX_BL_BITS;
zip_bl_desc.max_code = 0;
// Initialize the mapping length (0..255) -> length code (0..28)
length = 0;
for(code = 0; code < zip_LENGTH_CODES-1; code++) {
zip_base_length[code] = length;
for(n = 0; n < (1<<zip_extra_lbits[code]); n++)
zip_length_code[length++] = code;
}
// Assert (length == 256, "ct_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
zip_length_code[length-1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for(code = 0 ; code < 16; code++) {
zip_base_dist[code] = dist;
for(n = 0; n < (1<<zip_extra_dbits[code]); n++) {
zip_dist_code[dist++] = code;
}
}
// Assert (dist == 256, "ct_init: dist != 256");
dist >>= 7; // from now on, all distances are divided by 128
for( ; code < zip_D_CODES; code++) {
zip_base_dist[code] = dist << 7;
for(n = 0; n < (1<<(zip_extra_dbits[code]-7)); n++)
zip_dist_code[256 + dist++] = code;
}
// Assert (dist == 256, "ct_init: 256+dist != 512");
// Construct the codes of the static literal tree
for(bits = 0; bits <= zip_MAX_BITS; bits++)
zip_bl_count[bits] = 0;
n = 0;
while(n <= 143) { zip_static_ltree[n++].dl = 8; zip_bl_count[8]++; }
while(n <= 255) { zip_static_ltree[n++].dl = 9; zip_bl_count[9]++; }
while(n <= 279) { zip_static_ltree[n++].dl = 7; zip_bl_count[7]++; }
while(n <= 287) { zip_static_ltree[n++].dl = 8; zip_bl_count[8]++; }
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
zip_gen_codes(zip_static_ltree, zip_L_CODES + 1);
/* The static distance tree is trivial: */
for(n = 0; n < zip_D_CODES; n++) {
zip_static_dtree[n].dl = 5;
zip_static_dtree[n].fc = zip_bi_reverse(n, 5);
}
// Initialize the first block of the first file:
zip_init_block();
}
/* ==========================================================================
* Initialize a new block.
*/
var zip_init_block = function() {
var n; // iterates over tree elements
// Initialize the trees.
for(n = 0; n < zip_L_CODES; n++) zip_dyn_ltree[n].fc = 0;
for(n = 0; n < zip_D_CODES; n++) zip_dyn_dtree[n].fc = 0;
for(n = 0; n < zip_BL_CODES; n++) zip_bl_tree[n].fc = 0;
zip_dyn_ltree[zip_END_BLOCK].fc = 1;
zip_opt_len = zip_static_len = 0;
zip_last_lit = zip_last_dist = zip_last_flags = 0;
zip_flags = 0;
zip_flag_bit = 1;
}
/* ==========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
var zip_pqdownheap = function(
tree, // the tree to restore
k) { // node to move down
var v = zip_heap[k];
var j = k << 1; // left son of k
while(j <= zip_heap_len) {
// Set j to the smallest of the two sons:
if(j < zip_heap_len &&
zip_SMALLER(tree, zip_heap[j + 1], zip_heap[j]))
j++;
// Exit if v is smaller than both sons
if(zip_SMALLER(tree, v, zip_heap[j]))
break;
// Exchange v with the smallest son
zip_heap[k] = zip_heap[j];
k = j;
// And continue down the tree, setting j to the left son of k
j <<= 1;
}
zip_heap[k] = v;
}
/* ==========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
var zip_gen_bitlen = function(desc) { // the tree descriptor
var tree = desc.dyn_tree;
var extra = desc.extra_bits;
var base = desc.extra_base;
var max_code = desc.max_code;
var max_length = desc.max_length;
var stree = desc.static_tree;
var h; // heap index
var n, m; // iterate over the tree elements
var bits; // bit length
var xbits; // extra bits
var f; // frequency
var overflow = 0; // number of elements with bit length too large
for(bits = 0; bits <= zip_MAX_BITS; bits++)
zip_bl_count[bits] = 0;
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[zip_heap[zip_heap_max]].dl = 0; // root of the heap
for(h = zip_heap_max + 1; h < zip_HEAP_SIZE; h++) {
n = zip_heap[h];
bits = tree[tree[n].dl].dl + 1;
if(bits > max_length) {
bits = max_length;
overflow++;
}
tree[n].dl = bits;
// We overwrite tree[n].dl which is no longer needed
if(n > max_code)
continue; // not a leaf node
zip_bl_count[bits]++;
xbits = 0;
if(n >= base)
xbits = extra[n - base];
f = tree[n].fc;
zip_opt_len += f * (bits + xbits);
if(stree != null)
zip_static_len += f * (stree[n].dl + xbits);
}
if(overflow == 0)
return;
// This happens for example on obj2 and pic of the Calgary corpus
// Find the first bit length which could increase:
do {
bits = max_length - 1;
while(zip_bl_count[bits] == 0)
bits--;
zip_bl_count[bits]--; // move one leaf down the tree
zip_bl_count[bits + 1] += 2; // move one overflow item as its brother
zip_bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while(overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for(bits = max_length; bits != 0; bits--) {
n = zip_bl_count[bits];
while(n != 0) {
m = zip_heap[--h];
if(m > max_code)
continue;
if(tree[m].dl != bits) {
zip_opt_len += (bits - tree[m].dl) * tree[m].fc;
tree[m].fc = bits;
}
n--;
}
}
}
/* ==========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
var zip_gen_codes = function(tree, // the tree to decorate
max_code) { // largest code with non zero frequency
var next_code = new Array(zip_MAX_BITS+1); // next code value for each bit length
var code = 0; // running code value
var bits; // bit index
var n; // code index
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for(bits = 1; bits <= zip_MAX_BITS; bits++) {
code = ((code + zip_bl_count[bits-1]) << 1);
next_code[bits] = code;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
// Assert (code + encoder->bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
// Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for(n = 0; n <= max_code; n++) {
var len = tree[n].dl;
if(len == 0)
continue;
// Now reverse the bits
tree[n].fc = zip_bi_reverse(next_code[len]++, len);
// Tracec(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].fc, next_code[len]-1));
}
}
/* ==========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
var zip_build_tree = function(desc) { // the tree descriptor
var tree = desc.dyn_tree;
var stree = desc.static_tree;
var elems = desc.elems;
var n, m; // iterate over heap elements
var max_code = -1; // largest code with non zero frequency
var node = elems; // next internal node of the tree
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
zip_heap_len = 0;
zip_heap_max = zip_HEAP_SIZE;
for(n = 0; n < elems; n++) {
if(tree[n].fc != 0) {
zip_heap[++zip_heap_len] = max_code = n;
zip_depth[n] = 0;
} else
tree[n].dl = 0;
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while(zip_heap_len < 2) {
var xnew = zip_heap[++zip_heap_len] = (max_code < 2 ? ++max_code : 0);
tree[xnew].fc = 1;
zip_depth[xnew] = 0;
zip_opt_len--;
if(stree != null)
zip_static_len -= stree[xnew].dl;
// new is 0 or 1 so it does not have extra bits
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for(n = zip_heap_len >> 1; n >= 1; n--)
zip_pqdownheap(tree, n);
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
do {
n = zip_heap[zip_SMALLEST];
zip_heap[zip_SMALLEST] = zip_heap[zip_heap_len--];
zip_pqdownheap(tree, zip_SMALLEST);
m = zip_heap[zip_SMALLEST]; // m = node of next least frequency
// keep the nodes sorted by frequency
zip_heap[--zip_heap_max] = n;
zip_heap[--zip_heap_max] = m;
// Create a new node father of n and m
tree[node].fc = tree[n].fc + tree[m].fc;
// depth[node] = (char)(MAX(depth[n], depth[m]) + 1);
if(zip_depth[n] > zip_depth[m] + 1)
zip_depth[node] = zip_depth[n];
else
zip_depth[node] = zip_depth[m] + 1;
tree[n].dl = tree[m].dl = node;
// and insert the new node in the heap
zip_heap[zip_SMALLEST] = node++;
zip_pqdownheap(tree, zip_SMALLEST);
} while(zip_heap_len >= 2);
zip_heap[--zip_heap_max] = zip_heap[zip_SMALLEST];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
zip_gen_bitlen(desc);
// The field len is now set, we can generate the bit codes
zip_gen_codes(tree, max_code);
}
/* ==========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree. Updates opt_len to take into account the repeat
* counts. (The contribution of the bit length codes will be added later
* during the construction of bl_tree.)
*/
var zip_scan_tree = function(tree,// the tree to be scanned
max_code) { // and its largest code of non zero frequency
var n; // iterates over all tree elements
var prevlen = -1; // last emitted length
var curlen; // length of current code
var nextlen = tree[0].dl; // length of next code
var count = 0; // repeat count of the current code
var max_count = 7; // max repeat count
var min_count = 4; // min repeat count
if(nextlen == 0) {
max_count = 138;
min_count = 3;
}
tree[max_code + 1].dl = 0xffff; // guard
for(n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[n + 1].dl;
if(++count < max_count && curlen == nextlen)
continue;
else if(count < min_count)
zip_bl_tree[curlen].fc += count;
else if(curlen != 0) {
if(curlen != prevlen)
zip_bl_tree[curlen].fc++;
zip_bl_tree[zip_REP_3_6].fc++;
} else if(count <= 10)
zip_bl_tree[zip_REPZ_3_10].fc++;
else
zip_bl_tree[zip_REPZ_11_138].fc++;
count = 0; prevlen = curlen;
if(nextlen == 0) {
max_count = 138;
min_count = 3;
} else if(curlen == nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ==========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
var zip_send_tree = function(tree, // the tree to be scanned
max_code) { // and its largest code of non zero frequency
var n; // iterates over all tree elements
var prevlen = -1; // last emitted length
var curlen; // length of current code
var nextlen = tree[0].dl; // length of next code
var count = 0; // repeat count of the current code
var max_count = 7; // max repeat count
var min_count = 4; // min repeat count
/* tree[max_code+1].dl = -1; */ /* guard already set */
if(nextlen == 0) {
max_count = 138;
min_count = 3;
}
for(n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[n+1].dl;
if(++count < max_count && curlen == nextlen) {
continue;
} else if(count < min_count) {
do { zip_SEND_CODE(curlen, zip_bl_tree); } while(--count != 0);
} else if(curlen != 0) {
if(curlen != prevlen) {
zip_SEND_CODE(curlen, zip_bl_tree);
count--;
}
// Assert(count >= 3 && count <= 6, " 3_6?");
zip_SEND_CODE(zip_REP_3_6, zip_bl_tree);
zip_send_bits(count - 3, 2);
} else if(count <= 10) {
zip_SEND_CODE(zip_REPZ_3_10, zip_bl_tree);
zip_send_bits(count-3, 3);
} else {
zip_SEND_CODE(zip_REPZ_11_138, zip_bl_tree);
zip_send_bits(count-11, 7);
}
count = 0;
prevlen = curlen;
if(nextlen == 0) {
max_count = 138;
min_count = 3;
} else if(curlen == nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ==========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
var zip_build_bl_tree = function() {
var max_blindex; // index of last bit length code of non zero freq
// Determine the bit length frequencies for literal and distance trees
zip_scan_tree(zip_dyn_ltree, zip_l_desc.max_code);
zip_scan_tree(zip_dyn_dtree, zip_d_desc.max_code);
// Build the bit length tree:
zip_build_tree(zip_bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for(max_blindex = zip_BL_CODES-1; max_blindex >= 3; max_blindex--) {
if(zip_bl_tree[zip_bl_order[max_blindex]].dl != 0) break;
}
/* Update opt_len to include the bit length tree and counts */
zip_opt_len += 3*(max_blindex+1) + 5+5+4;
// Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// encoder->opt_len, encoder->static_len));
return max_blindex;
}
/* ==========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
var zip_send_all_trees = function(lcodes, dcodes, blcodes) { // number of codes for each tree
var rank; // index in bl_order
// Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
// Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
// Tracev((stderr, "\nbl counts: "));
zip_send_bits(lcodes-257, 5); // not +255 as stated in appnote.txt
zip_send_bits(dcodes-1, 5);
zip_send_bits(blcodes-4, 4); // not -3 as stated in appnote.txt
for(rank = 0; rank < blcodes; rank++) {
// Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
zip_send_bits(zip_bl_tree[zip_bl_order[rank]].dl, 3);
}
// send the literal tree
zip_send_tree(zip_dyn_ltree,lcodes-1);
// send the distance tree
zip_send_tree(zip_dyn_dtree,dcodes-1);
}
/* ==========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
var zip_flush_block = function(eof) { // true if this is the last block for a file
var opt_lenb, static_lenb; // opt_len and static_len in bytes
var max_blindex; // index of last bit length code of non zero freq
var stored_len; // length of input block
stored_len = zip_strstart - zip_block_start;
zip_flag_buf[zip_last_flags] = zip_flags; // Save the flags for the last 8 items
// Construct the literal and distance trees
zip_build_tree(zip_l_desc);
// Tracev((stderr, "\nlit data: dyn %ld, stat %ld",
// encoder->opt_len, encoder->static_len));
zip_build_tree(zip_d_desc);
// Tracev((stderr, "\ndist data: dyn %ld, stat %ld",
// encoder->opt_len, encoder->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = zip_build_bl_tree();
// Determine the best encoding. Compute first the block length in bytes
opt_lenb = (zip_opt_len +3+7)>>3;
static_lenb = (zip_static_len+3+7)>>3;
// Trace((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
// opt_lenb, encoder->opt_len,
// static_lenb, encoder->static_len, stored_len,
// encoder->last_lit, encoder->last_dist));
if(static_lenb <= opt_lenb)
opt_lenb = static_lenb;
if(stored_len + 4 <= opt_lenb // 4: two words for the lengths
&& zip_block_start >= 0) {
var i;
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
zip_send_bits((zip_STORED_BLOCK<<1)+eof, 3); /* send block type */
zip_bi_windup(); /* align on byte boundary */
zip_put_short(stored_len);
zip_put_short(~stored_len);
// copy block
/*
p = &window[block_start];
for(i = 0; i < stored_len; i++)
put_byte(p[i]);
*/
for(i = 0; i < stored_len; i++)
zip_put_byte(zip_window[zip_block_start + i]);
} else if(static_lenb == opt_lenb) {
zip_send_bits((zip_STATIC_TREES<<1)+eof, 3);
zip_compress_block(zip_static_ltree, zip_static_dtree);
} else {
zip_send_bits((zip_DYN_TREES<<1)+eof, 3);
zip_send_all_trees(zip_l_desc.max_code+1,
zip_d_desc.max_code+1,
max_blindex+1);
zip_compress_block(zip_dyn_ltree, zip_dyn_dtree);
}
zip_init_block();
if(eof != 0)
zip_bi_windup();
}
/* ==========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
var zip_ct_tally = function(
dist, // distance of matched string
lc) { // match length-MIN_MATCH or unmatched char (if dist==0)
zip_l_buf[zip_last_lit++] = lc;
if(dist == 0) {
// lc is the unmatched char
zip_dyn_ltree[lc].fc++;
} else {
// Here, lc is the match length - MIN_MATCH
dist--; // dist = match distance - 1
// Assert((ush)dist < (ush)MAX_DIST &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)D_CODE(dist) < (ush)D_CODES, "ct_tally: bad match");
zip_dyn_ltree[zip_length_code[lc]+zip_LITERALS+1].fc++;
zip_dyn_dtree[zip_D_CODE(dist)].fc++;
zip_d_buf[zip_last_dist++] = dist;
zip_flags |= zip_flag_bit;
}
zip_flag_bit <<= 1;
// Output the flags if they fill a byte
if((zip_last_lit & 7) == 0) {
zip_flag_buf[zip_last_flags++] = zip_flags;
zip_flags = 0;
zip_flag_bit = 1;
}
// Try to guess if it is profitable to stop the current block here
if(zip_compr_level > 2 && (zip_last_lit & 0xfff) == 0) {
// Compute an upper bound for the compressed length
var out_length = zip_last_lit * 8;
var in_length = zip_strstart - zip_block_start;
var dcode;
for(dcode = 0; dcode < zip_D_CODES; dcode++) {
out_length += zip_dyn_dtree[dcode].fc * (5 + zip_extra_dbits[dcode]);
}
out_length >>= 3;
// Trace((stderr,"\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ",
// encoder->last_lit, encoder->last_dist, in_length, out_length,
// 100L - out_length*100L/in_length));
if(zip_last_dist < parseInt(zip_last_lit/2) &&
out_length < parseInt(in_length/2))
return true;
}
return (zip_last_lit == zip_LIT_BUFSIZE-1 ||
zip_last_dist == zip_DIST_BUFSIZE);
/* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
/* ==========================================================================
* Send the block data compressed using the given Huffman trees
*/
var zip_compress_block = function(
ltree, // literal tree
dtree) { // distance tree
var dist; // distance of matched string
var lc; // match length or unmatched char (if dist == 0)
var lx = 0; // running index in l_buf
var dx = 0; // running index in d_buf
var fx = 0; // running index in flag_buf
var flag = 0; // current flags
var code; // the code to send
var extra; // number of extra bits to send
if(zip_last_lit != 0) do {
if((lx & 7) == 0)
flag = zip_flag_buf[fx++];
lc = zip_l_buf[lx++] & 0xff;
if((flag & 1) == 0) {
zip_SEND_CODE(lc, ltree); /* send a literal byte */
// Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
// Here, lc is the match length - MIN_MATCH
code = zip_length_code[lc];
zip_SEND_CODE(code+zip_LITERALS+1, ltree); // send the length code
extra = zip_extra_lbits[code];
if(extra != 0) {
lc -= zip_base_length[code];
zip_send_bits(lc, extra); // send the extra length bits
}
dist = zip_d_buf[dx++];
// Here, dist is the match distance - 1
code = zip_D_CODE(dist);
// Assert (code < D_CODES, "bad d_code");
zip_SEND_CODE(code, dtree); // send the distance code
extra = zip_extra_dbits[code];
if(extra != 0) {
dist -= zip_base_dist[code];
zip_send_bits(dist, extra); // send the extra distance bits
}
} // literal or match pair ?
flag >>= 1;
} while(lx < zip_last_lit);
zip_SEND_CODE(zip_END_BLOCK, ltree);
}
/* ==========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
var zip_Buf_size = 16; // bit size of bi_buf
var zip_send_bits = function(
value, // value to send
length) { // number of bits
/* If not enough room in bi_buf, use (valid) bits from bi_buf and
* (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
* unused bits in value.
*/
if(zip_bi_valid > zip_Buf_size - length) {
zip_bi_buf |= (value << zip_bi_valid);
zip_put_short(zip_bi_buf);
zip_bi_buf = (value >> (zip_Buf_size - zip_bi_valid));
zip_bi_valid += length - zip_Buf_size;
} else {
zip_bi_buf |= value << zip_bi_valid;
zip_bi_valid += length;
}
}
/* ==========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
var zip_bi_reverse = function(
code, // the value to invert
len) { // its bit length
var res = 0;
do {
res |= code & 1;
code >>= 1;
res <<= 1;
} while(--len > 0);
return res >> 1;
}
/* ==========================================================================
* Write out any remaining bits in an incomplete byte.
*/
var zip_bi_windup = function() {
if(zip_bi_valid > 8) {
zip_put_short(zip_bi_buf);
} else if(zip_bi_valid > 0) {
zip_put_byte(zip_bi_buf);
}
zip_bi_buf = 0;
zip_bi_valid = 0;
}
var zip_qoutbuf = function() {
if(zip_outcnt != 0) {
var q, i;
q = zip_new_queue();
if(zip_qhead == null)
zip_qhead = zip_qtail = q;
else
zip_qtail = zip_qtail.next = q;
q.len = zip_outcnt - zip_outoff;
// System.arraycopy(zip_outbuf, zip_outoff, q.ptr, 0, q.len);
for(i = 0; i < q.len; i++)
q.ptr[i] = zip_outbuf[zip_outoff + i];
zip_outcnt = zip_outoff = 0;
}
}
var zip_deflate = function(str, level) {
var i, j;
zip_deflate_data = str;
zip_deflate_pos = 0;
if(typeof level == "undefined")
level = zip_DEFAULT_LEVEL;
zip_deflate_start(level);
var buff = new Array(1024);
var aout = [];
while((i = zip_deflate_internal(buff, 0, buff.length)) > 0) {
var cbuf = new Array(i);
for(j = 0; j < i; j++){
cbuf[j] = String.fromCharCode(buff[j]);
}
aout[aout.length] = cbuf.join("");
}
zip_deflate_data = null; // G.C.
return aout.join("");
}
//
// end of the script of Masanao Izumo.
//
// we add the compression method for JSZip
JSZip.compressions["DEFLATE"] = {
magic : "\x08\x00",
compress : function (content) {
return zip_deflate(content);
}
}
})();
|
JavaScript
|
/*
* QUnit - A JavaScript Unit Testing Framework
*
* http://docs.jquery.com/QUnit
*
* Copyright (c) 2009 John Resig, Jörn Zaefferer
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*/
(function(window) {
var QUnit = {
// Initialize the configuration options
init: function init() {
config = {
stats: { all: 0, bad: 0 },
moduleStats: { all: 0, bad: 0 },
started: +new Date,
blocking: false,
autorun: false,
assertions: [],
filters: [],
queue: []
};
var tests = id("qunit-tests"),
banner = id("qunit-banner"),
result = id("qunit-testresult");
if ( tests ) {
tests.innerHTML = "";
}
if ( banner ) {
banner.className = "";
}
if ( result ) {
result.parentNode.removeChild( result );
}
},
// call on start of module test to prepend name to all tests
module: function module(name, testEnvironment) {
synchronize(function() {
if ( config.currentModule ) {
QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all );
}
config.currentModule = name;
config.moduleTestEnvironment = testEnvironment;
config.moduleStats = { all: 0, bad: 0 };
QUnit.moduleStart( name );
});
},
asyncTest: function asyncTest(testName, expected, callback) {
if ( arguments.length === 2 ) {
callback = expected;
expected = 0;
}
QUnit.test(testName, expected, callback, true);
},
test: function test(testName, expected, callback, async) {
var name = testName, testEnvironment = {};
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
if ( config.currentModule ) {
name = config.currentModule + " module: " + name;
}
if ( !validTest(name) ) {
return;
}
synchronize(function() {
QUnit.testStart( testName );
testEnvironment = extend({
setup: function() {},
teardown: function() {}
}, config.moduleTestEnvironment);
config.assertions = [];
config.expected = null;
if ( arguments.length >= 3 ) {
config.expected = callback;
callback = arguments[2];
}
try {
if ( !config.pollution ) {
saveGlobal();
}
testEnvironment.setup.call(testEnvironment);
} catch(e) {
QUnit.ok( false, "Setup failed on " + name + ": " + e.message );
}
if ( async ) {
QUnit.stop();
}
try {
callback.call(testEnvironment);
} catch(e) {
fail("Test " + name + " died, exception and test follows", e, callback);
QUnit.ok( false, "Died on test #" + (config.assertions.length + 1) + ": " + e.message );
// else next test will carry the responsibility
saveGlobal();
// Restart the tests if they're blocking
if ( config.blocking ) {
start();
}
}
});
synchronize(function() {
try {
checkPollution();
testEnvironment.teardown.call(testEnvironment);
} catch(e) {
QUnit.ok( false, "Teardown failed on " + name + ": " + e.message );
}
try {
reset();
} catch(e) {
fail("reset() failed, following Test " + name + ", exception and reset fn follows", e, reset);
}
if ( config.expected && config.expected != config.assertions.length ) {
QUnit.ok( false, "Expected " + config.expected + " assertions, but " + config.assertions.length + " were run" );
}
var good = 0, bad = 0,
tests = id("qunit-tests");
config.stats.all += config.assertions.length;
config.moduleStats.all += config.assertions.length;
if ( tests ) {
var ol = document.createElement("ol");
ol.style.display = "none";
for ( var i = 0; i < config.assertions.length; i++ ) {
var assertion = config.assertions[i];
var li = document.createElement("li");
li.className = assertion.result ? "pass" : "fail";
li.innerHTML = assertion.message || "(no message)";
ol.appendChild( li );
if ( assertion.result ) {
good++;
} else {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
var b = document.createElement("strong");
b.innerHTML = name + " <b style='color:black;'>(<b class='fail'>" + bad + "</b>, <b class='pass'>" + good + "</b>, " + config.assertions.length + ")</b>";
addEvent(b, "click", function() {
var next = b.nextSibling, display = next.style.display;
next.style.display = display === "none" ? "block" : "none";
});
addEvent(b, "dblclick", function(e) {
var target = (e || window.event).target;
if ( target.nodeName.toLowerCase() === "strong" ) {
var text = "", node = target.firstChild;
while ( node.nodeType === 3 ) {
text += node.nodeValue;
node = node.nextSibling;
}
text = text.replace(/(^\s*|\s*$)/g, "");
if ( window.location ) {
window.location.href = window.location.href.match(/^(.+?)(\?.*)?$/)[1] + "?" + encodeURIComponent(text);
}
}
});
var li = document.createElement("li");
li.className = bad ? "fail" : "pass";
li.appendChild( b );
li.appendChild( ol );
tests.appendChild( li );
if ( bad ) {
var toolbar = id("qunit-testrunner-toolbar");
if ( toolbar ) {
toolbar.style.display = "block";
id("qunit-filter-pass").disabled = null;
id("qunit-filter-missing").disabled = null;
}
}
} else {
for ( var i = 0; i < config.assertions.length; i++ ) {
if ( !config.assertions[i].result ) {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
}
QUnit.testDone( testName, bad, config.assertions.length );
if ( !window.setTimeout && !config.queue.length ) {
done();
}
});
if ( window.setTimeout && !config.doneTimer ) {
config.doneTimer = window.setTimeout(function(){
if ( !config.queue.length ) {
done();
} else {
synchronize( done );
}
}, 13);
}
},
/**
* Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
*/
expect: function expect(asserts) {
config.expected = asserts;
},
/**
* Asserts true.
* @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
*/
ok: function ok(a, msg) {
QUnit.log(a, msg);
config.assertions.push({
result: !!a,
message: msg
});
},
/**
* Checks that the first two arguments are equal, with an optional message.
* Prints out both actual and expected values.
*
* Prefered to ok( actual == expected, message )
*
* @example equals( format("Received {0} bytes.", 2), "Received 2 bytes." );
*
* @param Object actual
* @param Object expected
* @param String message (optional)
*/
equals: function equals(actual, expected, message) {
push(expected == actual, actual, expected, message);
},
same: function(a, b, message) {
push(QUnit.equiv(a, b), a, b, message);
},
start: function start() {
// A slight delay, to avoid any current callbacks
if ( window.setTimeout ) {
window.setTimeout(function() {
if ( config.timeout ) {
clearTimeout(config.timeout);
}
config.blocking = false;
process();
}, 13);
} else {
config.blocking = false;
process();
}
},
stop: function stop(timeout) {
config.blocking = true;
if ( timeout && window.setTimeout ) {
config.timeout = window.setTimeout(function() {
QUnit.ok( false, "Test timed out" );
start();
}, timeout);
}
},
/**
* Resets the test setup. Useful for tests that modify the DOM.
*/
reset: function reset() {
if ( window.jQuery ) {
jQuery("#main").html( config.fixture );
jQuery.event.global = {};
jQuery.ajaxSettings = extend({}, config.ajaxSettings);
}
},
/**
* Trigger an event on an element.
*
* @example triggerEvent( document.body, "click" );
*
* @param DOMElement elem
* @param String type
*/
triggerEvent: function triggerEvent( elem, type, event ) {
if ( document.createEvent ) {
event = document.createEvent("MouseEvents");
event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
elem.dispatchEvent( event );
} else if ( elem.fireEvent ) {
elem.fireEvent("on"+type);
}
},
// Logging callbacks
done: function done(failures, total) {},
log: function log(result, message) {},
testStart: function testStart(name) {},
testDone: function testDone(name, failures, total) {},
moduleStart: function moduleStart(name) {},
moduleDone: function moduleDone(name, failures, total) {}
};
// Maintain internal state
var config = {
// The queue of tests to run
queue: [],
// block until document ready
blocking: true
};
// Load paramaters
(function() {
var location = window.location || { search: "", protocol: "file:" },
GETParams = location.search.slice(1).split('&');
for ( var i = 0; i < GETParams.length; i++ ) {
GETParams[i] = decodeURIComponent( GETParams[i] );
if ( GETParams[i] === "noglobals" ) {
GETParams.splice( i, 1 );
i--;
config.noglobals = true;
}
}
// restrict modules/tests by get parameters
config.filters = GETParams;
// Figure out if we're running the tests from a server or not
QUnit.isLocal = !!(location.protocol === 'file:');
})();
// Expose the API as global variables, unless an 'exports'
// object exists, in that case we assume we're in CommonJS
if ( typeof exports === "undefined" || typeof require === "undefined" ) {
extend(window, QUnit);
window.QUnit = QUnit;
} else {
extend(exports, QUnit);
exports.QUnit = QUnit;
}
if ( typeof document === "undefined" || document.readyState === "complete" ) {
config.autorun = true;
}
addEvent(window, "load", function() {
// Initialize the config, saving the execution queue
var oldconfig = extend({}, config);
QUnit.init();
extend(config, oldconfig);
config.blocking = false;
var userAgent = id("qunit-userAgent");
if ( userAgent ) {
userAgent.innerHTML = navigator.userAgent;
}
var toolbar = id("qunit-testrunner-toolbar");
if ( toolbar ) {
toolbar.style.display = "none";
var filter = document.createElement("input");
filter.type = "checkbox";
filter.id = "qunit-filter-pass";
filter.disabled = true;
addEvent( filter, "click", function() {
var li = document.getElementsByTagName("li");
for ( var i = 0; i < li.length; i++ ) {
if ( li[i].className.indexOf("pass") > -1 ) {
li[i].style.display = filter.checked ? "none" : "block";
}
}
});
toolbar.appendChild( filter );
var label = document.createElement("label");
label.setAttribute("for", "filter-pass");
label.innerHTML = "Hide passed tests";
toolbar.appendChild( label );
var missing = document.createElement("input");
missing.type = "checkbox";
missing.id = "qunit-filter-missing";
missing.disabled = true;
addEvent( missing, "click", function() {
var li = document.getElementsByTagName("li");
for ( var i = 0; i < li.length; i++ ) {
if ( li[i].className.indexOf("fail") > -1 && li[i].innerHTML.indexOf('missing test - untested code is broken code') > - 1 ) {
li[i].parentNode.parentNode.style.display = missing.checked ? "none" : "block";
}
}
});
toolbar.appendChild( missing );
label = document.createElement("label");
label.setAttribute("for", "filter-missing");
label.innerHTML = "Hide missing tests (untested code is broken code)";
toolbar.appendChild( label );
}
var main = id('main');
if ( main ) {
config.fixture = main.innerHTML;
}
if ( window.jQuery ) {
config.ajaxSettings = window.jQuery.ajaxSettings;
}
start();
});
function done() {
if ( config.doneTimer && window.clearTimeout ) {
window.clearTimeout( config.doneTimer );
config.doneTimer = null;
}
if ( config.queue.length ) {
config.doneTimer = window.setTimeout(function(){
if ( !config.queue.length ) {
done();
} else {
synchronize( done );
}
}, 13);
return;
}
config.autorun = true;
// Log the last module results
if ( config.currentModule ) {
QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all );
}
var banner = id("qunit-banner"),
tests = id("qunit-tests"),
html = ['Tests completed in ',
+new Date - config.started, ' milliseconds.<br/>',
'<span class="bad">', config.stats.all - config.stats.bad, '</span> tests of <span class="all">', config.stats.all, '</span> passed, ', config.stats.bad,' failed.'].join('');
if ( banner ) {
banner.className += " " + (config.stats.bad ? "fail" : "pass");
}
if ( tests ) {
var result = id("qunit-testresult");
if ( !result ) {
result = document.createElement("p");
result.id = "qunit-testresult";
result.className = "result";
tests.parentNode.insertBefore( result, tests.nextSibling );
}
result.innerHTML = html;
}
QUnit.done( config.stats.bad, config.stats.all );
}
function validTest( name ) {
var i = config.filters.length,
run = false;
if ( !i ) {
return true;
}
while ( i-- ) {
var filter = config.filters[i],
not = filter.charAt(0) == '!';
if ( not ) {
filter = filter.slice(1);
}
if ( name.indexOf(filter) !== -1 ) {
return !not;
}
if ( not ) {
run = true;
}
}
return run;
}
function push(result, actual, expected, message) {
message = message || (result ? "okay" : "failed");
QUnit.ok( result, result ? message + ": " + expected : message + ", expected: " + QUnit.jsDump.parse(expected) + " result: " + QUnit.jsDump.parse(actual) );
}
function synchronize( callback ) {
config.queue.push( callback );
if ( config.autorun && !config.blocking ) {
process();
}
}
function process() {
while ( config.queue.length && !config.blocking ) {
config.queue.shift()();
}
}
function saveGlobal() {
config.pollution = [];
if ( config.noglobals ) {
for ( var key in window ) {
config.pollution.push( key );
}
}
}
function checkPollution( name ) {
var old = config.pollution;
saveGlobal();
var newGlobals = diff( old, config.pollution );
if ( newGlobals.length > 0 ) {
ok( false, "Introduced global variable(s): " + newGlobals.join(", ") );
config.expected++;
}
var deletedGlobals = diff( config.pollution, old );
if ( deletedGlobals.length > 0 ) {
ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") );
config.expected++;
}
}
// returns a new Array with the elements that are in a but not in b
function diff( a, b ) {
var result = a.slice();
for ( var i = 0; i < result.length; i++ ) {
for ( var j = 0; j < b.length; j++ ) {
if ( result[i] === b[j] ) {
result.splice(i, 1);
i--;
break;
}
}
}
return result;
}
function fail(message, exception, callback) {
if ( typeof console !== "undefined" && console.error && console.warn ) {
console.error(message);
console.error(exception);
console.warn(callback.toString());
} else if ( window.opera && opera.postError ) {
opera.postError(message, exception, callback.toString);
}
}
function extend(a, b) {
for ( var prop in b ) {
a[prop] = b[prop];
}
return a;
}
function addEvent(elem, type, fn) {
if ( elem.addEventListener ) {
elem.addEventListener( type, fn, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, fn );
} else {
fn();
}
}
function id(name) {
return !!(typeof document !== "undefined" && document && document.getElementById) &&
document.getElementById( name );
}
// Test for equality any JavaScript type.
// Discussions and reference: http://philrathe.com/articles/equiv
// Test suites: http://philrathe.com/tests/equiv
// Author: Philippe Rathé <prathe@gmail.com>
QUnit.equiv = function () {
var innerEquiv; // the real equiv function
var callers = []; // stack to decide between skip/abort functions
// Determine what is o.
function hoozit(o) {
if (o.constructor === String) {
return "string";
} else if (o.constructor === Boolean) {
return "boolean";
} else if (o.constructor === Number) {
if (isNaN(o)) {
return "nan";
} else {
return "number";
}
} else if (typeof o === "undefined") {
return "undefined";
// consider: typeof null === object
} else if (o === null) {
return "null";
// consider: typeof [] === object
} else if (o instanceof Array) {
return "array";
// consider: typeof new Date() === object
} else if (o instanceof Date) {
return "date";
// consider: /./ instanceof Object;
// /./ instanceof RegExp;
// typeof /./ === "function"; // => false in IE and Opera,
// true in FF and Safari
} else if (o instanceof RegExp) {
return "regexp";
} else if (typeof o === "object") {
return "object";
} else if (o instanceof Function) {
return "function";
} else {
return undefined;
}
}
// Call the o related callback with the given arguments.
function bindCallbacks(o, callbacks, args) {
var prop = hoozit(o);
if (prop) {
if (hoozit(callbacks[prop]) === "function") {
return callbacks[prop].apply(callbacks, args);
} else {
return callbacks[prop]; // or undefined
}
}
}
var callbacks = function () {
// for string, boolean, number and null
function useStrictEquality(b, a) {
if (b instanceof a.constructor || a instanceof b.constructor) {
// to catch short annotaion VS 'new' annotation of a declaration
// e.g. var i = 1;
// var j = new Number(1);
return a == b;
} else {
return a === b;
}
}
return {
"string": useStrictEquality,
"boolean": useStrictEquality,
"number": useStrictEquality,
"null": useStrictEquality,
"undefined": useStrictEquality,
"nan": function (b) {
return isNaN(b);
},
"date": function (b, a) {
return hoozit(b) === "date" && a.valueOf() === b.valueOf();
},
"regexp": function (b, a) {
return hoozit(b) === "regexp" &&
a.source === b.source && // the regex itself
a.global === b.global && // and its modifers (gmi) ...
a.ignoreCase === b.ignoreCase &&
a.multiline === b.multiline;
},
// - skip when the property is a method of an instance (OOP)
// - abort otherwise,
// initial === would have catch identical references anyway
"function": function () {
var caller = callers[callers.length - 1];
return caller !== Object &&
typeof caller !== "undefined";
},
"array": function (b, a) {
var i;
var len;
// b could be an object literal here
if ( ! (hoozit(b) === "array")) {
return false;
}
len = a.length;
if (len !== b.length) { // safe and faster
return false;
}
for (i = 0; i < len; i++) {
if ( ! innerEquiv(a[i], b[i])) {
return false;
}
}
return true;
},
"object": function (b, a) {
var i;
var eq = true; // unless we can proove it
var aProperties = [], bProperties = []; // collection of strings
// comparing constructors is more strict than using instanceof
if ( a.constructor !== b.constructor) {
return false;
}
// stack constructor before traversing properties
callers.push(a.constructor);
for (i in a) { // be strict: don't ensures hasOwnProperty and go deep
aProperties.push(i); // collect a's properties
if ( ! innerEquiv(a[i], b[i])) {
eq = false;
}
}
callers.pop(); // unstack, we are done
for (i in b) {
bProperties.push(i); // collect b's properties
}
// Ensures identical properties name
return eq && innerEquiv(aProperties.sort(), bProperties.sort());
}
};
}();
innerEquiv = function () { // can take multiple arguments
var args = Array.prototype.slice.apply(arguments);
if (args.length < 2) {
return true; // end transition
}
return (function (a, b) {
if (a === b) {
return true; // catch the most you can
} else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || hoozit(a) !== hoozit(b)) {
return false; // don't lose time with error prone cases
} else {
return bindCallbacks(a, callbacks, [b, a]);
}
// apply transition with (1..n) arguments
})(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1));
};
return innerEquiv;
}();
/**
* jsDump
* Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
* Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php)
* Date: 5/15/2008
* @projectDescription Advanced and extensible data dumping for Javascript.
* @version 1.0.0
* @author Ariel Flesler
* @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
*/
QUnit.jsDump = (function() {
function quote( str ) {
return '"' + str.toString().replace(/"/g, '\\"') + '"';
};
function literal( o ) {
return o + '';
};
function join( pre, arr, post ) {
var s = jsDump.separator(),
base = jsDump.indent(),
inner = jsDump.indent(1);
if ( arr.join )
arr = arr.join( ',' + s + inner );
if ( !arr )
return pre + post;
return [ pre, inner + arr, base + post ].join(s);
};
function array( arr ) {
var i = arr.length, ret = Array(i);
this.up();
while ( i-- )
ret[i] = this.parse( arr[i] );
this.down();
return join( '[', ret, ']' );
};
var reName = /^function (\w+)/;
var jsDump = {
parse:function( obj, type ) { //type is used mostly internally, you can fix a (custom)type in advance
var parser = this.parsers[ type || this.typeOf(obj) ];
type = typeof parser;
return type == 'function' ? parser.call( this, obj ) :
type == 'string' ? parser :
this.parsers.error;
},
typeOf:function( obj ) {
var type = typeof obj,
f = 'function';//we'll use it 3 times, save it
return type != 'object' && type != f ? type :
!obj ? 'null' :
obj.exec ? 'regexp' :// some browsers (FF) consider regexps functions
obj.getHours ? 'date' :
obj.scrollBy ? 'window' :
obj.nodeName == '#document' ? 'document' :
obj.nodeName ? 'node' :
obj.item ? 'nodelist' : // Safari reports nodelists as functions
obj.callee ? 'arguments' :
obj.call || obj.constructor != Array && //an array would also fall on this hack
(obj+'').indexOf(f) != -1 ? f : //IE reports functions like alert, as objects
'length' in obj ? 'array' :
type;
},
separator:function() {
return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? ' ' : ' ';
},
indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing
if ( !this.multiline )
return '';
var chr = this.indentChar;
if ( this.HTML )
chr = chr.replace(/\t/g,' ').replace(/ /g,' ');
return Array( this._depth_ + (extra||0) ).join(chr);
},
up:function( a ) {
this._depth_ += a || 1;
},
down:function( a ) {
this._depth_ -= a || 1;
},
setParser:function( name, parser ) {
this.parsers[name] = parser;
},
// The next 3 are exposed so you can use them
quote:quote,
literal:literal,
join:join,
//
_depth_: 1,
// This is the list of parsers, to modify them, use jsDump.setParser
parsers:{
window: '[Window]',
document: '[Document]',
error:'[ERROR]', //when no parser is found, shouldn't happen
unknown: '[Unknown]',
'null':'null',
undefined:'undefined',
'function':function( fn ) {
var ret = 'function',
name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE
if ( name )
ret += ' ' + name;
ret += '(';
ret = [ ret, this.parse( fn, 'functionArgs' ), '){'].join('');
return join( ret, this.parse(fn,'functionCode'), '}' );
},
array: array,
nodelist: array,
arguments: array,
object:function( map ) {
var ret = [ ];
this.up();
for ( var key in map )
ret.push( this.parse(key,'key') + ': ' + this.parse(map[key]) );
this.down();
return join( '{', ret, '}' );
},
node:function( node ) {
var open = this.HTML ? '<' : '<',
close = this.HTML ? '>' : '>';
var tag = node.nodeName.toLowerCase(),
ret = open + tag;
for ( var a in this.DOMAttrs ) {
var val = node[this.DOMAttrs[a]];
if ( val )
ret += ' ' + a + '=' + this.parse( val, 'attribute' );
}
return ret + close + open + '/' + tag + close;
},
functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function
var l = fn.length;
if ( !l ) return '';
var args = Array(l);
while ( l-- )
args[l] = String.fromCharCode(97+l);//97 is 'a'
return ' ' + args.join(', ') + ' ';
},
key:quote, //object calls it internally, the key part of an item in a map
functionCode:'[code]', //function calls it internally, it's the content of the function
attribute:quote, //node calls it internally, it's an html attribute value
string:quote,
date:quote,
regexp:literal, //regex
number:literal,
'boolean':literal
},
DOMAttrs:{//attributes to dump from nodes, name=>realName
id:'id',
name:'name',
'class':'className'
},
HTML:true,//if true, entities are escaped ( <, >, \t, space and \n )
indentChar:' ',//indentation unit
multiline:true //if true, items in a collection, are separated by a \n, else just a space.
};
return jsDump;
})();
})(this);
|
JavaScript
|
/*
Document : acd.main
Created on : 14/11/2012, 03:16:31 PM
Author : acazares
Description:
script base
*/
var servlet = 'requestController.jsf';
$(function(){
$(".userMenuBox").bind('click', function(){
$('.menuUser').fadeIn('slow', function() {
setTimeout(function(){$('.menuUser').fadeOut('slow')}, 3000);
});
});
setInterval(function(){
$(".blinking").fadeToggle("slow");
}, 300);
$("#lblRegistro").bind("click", function(){
location.href="faces/usuario.xhtml?action=nuevo";
});
$("#formLogin").submit(function(e){
if($('#username').val().length==0){
$('#username').css("background-color","yellow");
$('#username').focus();
}else{
$('#username').css("background-color","#fff");
}
if($('#pass').val().length==0){
$('#pass').css("background-color","yellow");
$('#pass').focus();
return false;
}else{
$('#pass').css("background-color","#fff");
}
if($('#username').val().length==0){
return false;
}
extras = 'user='+$('#username').val()+'&pass='+$('#pass').val()
$.ajax({
dataType : "json",
url : servlet+'?action=login&'+extras,
//url : 'requestController.jsp?action=logout',
success: function(data) {//alert(data);
JSONdata = eval(data)
if(JSONdata.id !=null){
location.href='?';
}else{
$("#msgErrorLogin").css("display","inline")
$("#username").val("");
$("#pass").val("");
}
}
});
return false;
});
$("#btnLogout").bind('click', function(){
$.ajax({
dataType : "json",
url : servlet+'?action=logout',
//url : 'requestController.jsp?action=logout',
//url : 'http://localhost:8080/jv3/faces/index.xhtml',
success: function(data) {//alert(data);
location.href='?';
}
});
});
});
|
JavaScript
|
var wdWidth = $(window).width();
var wdHeight = $(window).height();
$(document).ready( function(){
$('#BigLeft').hover( function (){
$('#HiddenMenu').animate({'top': '-55'}, 600);
}, function(){
$('#HiddenMenu').mouseleave( function (){
$('#HiddenMenu').animate({'top': '-375'}, 300);
});
});
$('#ImgList img').click( function(){
var src = $(this).attr('src');
$('#PreviewBig').find('img').attr('src', src );
});
$('#Zoom').css({
'top': $('#poss').offset().top,
'left': $('#poss').offset().left
});
var deTop = $('#PreviewBig').find('img').offset().top + 25;
var deLeft = $('#PreviewBig').find('img').offset().left + 25;
var oZoom = $('#Zoom').hide();
$('#PreviewBig').find('img').mouseenter( function(){
var src = $(this).attr('src');
var tmpName = src.split('/')[1];
src = src.replace(tmpName, 'b_' + tmpName);
oZoom.css({'background-image': 'url(' + src + ')'}).show();
$('#PdMain').find('.Right').hide();
}).mousemove( function(e){
var x = e.pageX - deLeft;
var y = e.pageY - deTop;
$('title').text(e.pageX+ '-'+ deLeft);
oZoom.css({
'background-position': x + 'px ' + y + 'px'
});
}).mouseout( function(){
oZoom.fadeOut('normal');
$('#PdMain').find('.Right').show();
});
});
|
JavaScript
|
var wdWidth = $(window).width();
var wdHeight = $(window).height();
var Center = {
X: Math.floor(wdWidth/2),
Y: Math.floor(wdHeight/2)
}
var Unit = {
X: Math.floor(wdWidth/100),
Y: Math.floor(wdHeight/100)
}
// set layout
function initialSize(){
if (wdWidth <= 1100 && wdWidth >= 1000){
$('#Bigest').css({
'width': 350,
'height': 220
});
$('.Medium').css({
'width': 260,
'height': 170
});
} else if (wdWidth <= 1400 && wdWidth > 1100) {
$('#Bigest').css({
'width': 380,
'height': 240
});
$('.Medium').css({
'width': 280,
'height': 190
});
} else if (wdWidth > 1400) {
$('#Bigest').css({
'width': 450,
'height': 290
});
$('.Medium').css({
'width': 290,
'height': 190
});
}
}
function initialPos(){
$('#Bigest').css({
'top': Center.Y - 110 + 60,
'left': Center.X - 175
});
if (wdWidth <= 1100 && wdWidth >= 1000){
$('#Box1').css({
'top': 190,
'left': -20
});
$('#Box2').css({
'top': 300,
'left': 80
});
$('#Box3').css({
'top': 180,
'left': 900
});
$('#Box4').css({
'top': 250,
'left': 800
});
$('#Box5').css({
'top': 350,
'left': 850
});
$('#Box6').css({
'top': 350,
'left': -120
});
} else if (wdWidth <= 1550 && wdWidth > 1100) {
$('#Box1').css({
'top': 190,
'left': 20
});
$('#Box2').css({
'top': 300,
'left': 120
});
$('#Box3').css({
'top': 180,
'left': 1000
});
$('#Box4').css({
'top': 270,
'left': 1100
});
$('#Box5').css({
'top': 380,
'left': 1050
});
$('#Box6').css({
'top': 450,
'left': 100
});
} else if (wdWidth > 1550) {
$('#Box1').css({
'top': 190,
'left': 50
});
$('#Box2').css({
'top': 450,
'left': 120
});
$('#Box3').css({
'top': 180,
'left': 1090
});
$('#Box4').css({
'top': 550,
'left': 1150
});
$('#Box5').css({
'top': 350,
'left': 1200
});
$('#Box6').css({
'top': 350,
'left': 270
});
}
}
$(document).ready( function(){
initialSize();
initialPos();
$('#MiddleContainer').css('height', wdHeight - 405);
$('.BoxMoving').hover( function(){
});
var tmpMouseX = 0;
var tmpMouseY = 0;
var isFirst = true;
// $('body').mousemove( function(e){
// var isRow = Math.abs(tmpMouseX - e.pageX) > Math.abs(tmpMouseY - e.pageY);
// var isDir = (tmpMouseX - e.pageX) > 0;
// $('title').text(wdWidth);
// if(isFirst){
// isFirst = false;
// } else{
// $('.BoxMoving').each( function(){
// var tmp = $(this).offset().left;
// $(this).css('left', tmp + (tmpMouseX - e.pageX)/4);
// });
// }
// tmpMouseX = e.pageX;
// tmpMouseY = e.pageY;
// });
$('#BigLeft').hover( function (){
$('#HiddenMenu').animate({'top': '-125'}, 600);
}, function(){
$('#HiddenMenu').mouseleave( function (){
$('#HiddenMenu').animate({'top': '-375'}, 300);
});
});
$('.BoxMoving').hover( function(){
$(this).find('.BoxBottom').animate({'height' : '80px'}, 600);
$(this).find('.BoxDescript').show();
$(this).find('a').show();
}, function(){
$(this).find('.BoxDescript').hide();
$(this).find('a').hide();
$(this).find('.BoxBottom').animate({'height' : '30px'}, 600);
});
var B1 = {
x: 0,
y: 0
}
var B2 = {
x: 0,
y: 0
}
$('.BoxMoving').hover(function(){
$(this).css('z-index', '5');
var cX = $(this).offset().left;
var cY = $(this).offset().top;
B1.x = $('#Box2').offset().left;
B1.y = $('#Box2').offset().top;
B2.x = $('#Box6').offset().left;
B2.y = $('#Box6').offset().top;
if($(this).attr('id') == 'Box1'){
$('#Box2').animate({
'top': cY + 280,
'left': cX + 70
}, 500);
$('#Box6').animate({
'top': cY + 80,
'left': cX + 500
}, 500);
}
}, function(){
$(this).css('z-index', '3');
if($(this).attr('id') == 'Box1'){
$('#Box2').animate({
'top': B1.y,
'left': B1.x
}, 500);
$('#Box6').animate({
'top': B2.y,
'left': B2.x
}, 500);
}
});
// Language
$('#CenterHibrid').removeClass('UK').addClass('VN').attr('title', 'Chuyển sang tiếng việt');
$('.Eng').show();
$('.Vie').hide();
$('#CenterHibrid').click(function () {
if ($(this).is('.VN')) {
$(this).removeClass('VN').addClass('UK').attr('title', 'Go to english version');
$('.Vie').show();
$('.Eng').hide();
} else {
$(this).removeClass('UK').addClass('VN').attr('title', 'Chuyển sang tiếng việt');
$('.Eng').show();
$('.Vie').hide();
}
});
});
|
JavaScript
|
var $lang={
errAlertMsg: "\u4E0D\u5408\u6CD5\u7684\u65E5\u671F\u683C\u5F0F\u6216\u8005\u65E5\u671F\u8D85\u51FA\u9650\u5B9A\u8303\u56F4,\u9700\u8981\u64A4\u9500\u5417?",
aWeekStr: ["\u5468","\u65E5","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D"],
aLongWeekStr:["\u5468","\u661F\u671F\u65E5","\u661F\u671F\u4E00","\u661F\u671F\u4E8C","\u661F\u671F\u4E09","\u661F\u671F\u56DB","\u661F\u671F\u4E94","\u661F\u671F\u516D"],
aMonStr: ["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00","\u5341\u4E8C"],
aLongMonStr: ["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00\u6708","\u5341\u4E8C\u6708"],
clearStr: "\u6E05\u7A7A",
todayStr: "\u4ECA\u5929",
okStr: "\u786E\u5B9A",
updateStr: "\u786E\u5B9A",
timeStr: "\u65F6\u95F4",
quickStr: "\u5FEB\u901F\u9009\u62E9",
err_1: '\u6700\u5C0F\u65E5\u671F\u4E0D\u80FD\u5927\u4E8E\u6700\u5927\u65E5\u671F!'
}
|
JavaScript
|
var $lang={
errAlertMsg: "Invalid date or the date out of range,redo or not?",
aWeekStr: ["wk", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
aLongWeekStr:["wk","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],
aMonStr: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
aLongMonStr: ["January","February","March","April","May","June","July","August","September","October","November","December"],
clearStr: "Clear",
todayStr: "Today",
okStr: "OK",
updateStr: "OK",
timeStr: "Time",
quickStr: "Quick Selection",
err_1: 'MinDate Cannot be bigger than MaxDate!'
}
|
JavaScript
|
var $lang={
errAlertMsg: "\u4E0D\u5408\u6CD5\u7684\u65E5\u671F\u683C\u5F0F\u6216\u8005\u65E5\u671F\u8D85\u51FA\u9650\u5B9A\u7BC4\u570D,\u9700\u8981\u64A4\u92B7\u55CE?",
aWeekStr: ["\u5468","\u65E5","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D"],
aLongWeekStr:["\u5468","\u661F\u671F\u65E5","\u661F\u671F\u4E00","\u661F\u671F\u4E8C","\u661F\u671F\u4E09","\u661F\u671F\u56DB","\u661F\u671F\u4E94","\u661F\u671F\u516D"],
aMonStr: ["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00","\u5341\u4E8C"],
aLongMonStr: ["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00\u6708","\u5341\u4E8C\u6708"],
clearStr: "\u6E05\u7A7A",
todayStr: "\u4ECA\u5929",
okStr: "\u78BA\u5B9A",
updateStr: "\u78BA\u5B9A",
timeStr: "\u6642\u9593",
quickStr: "\u5FEB\u901F\u9078\u64C7",
err_1: '\u6700\u5C0F\u65E5\u671F\u4E0D\u80FD\u5927\u65BC\u6700\u5927\u65E5\u671F!'
}
|
JavaScript
|
//可以自动关闭的提示
function jsAutoMsg(msgtitle, url) {
$("#btnSave").attr("disabled", "disabled");
var str = "<div id=\"jsAutoMsg\" class=\"pcent correct\">" + msgtitle + "</div>";
$("body").append(str);
$("#jsAutoMsg").show();
//3秒后清除提示
setTimeout(function() {
$("#jsAutoMsg").remove();
if (url == "back") {
history.back(-1);
} else if (url != "") {
location.href = url;
}
}, 3000);
}
//遮罩提示窗口
function jsLayMsg(w, h, options) {
$("#jsLayMsg").remove();
var cssname = "";
//提示窗口的样式
switch (options.mscss) {
case "Success":
cssname = "icon-01";
break;
case "Error":
cssname = "icon-02";
break;
default:
cssname = "icon-03";
break;
}
//向页面插入标记
var str = "<div id='jsLayMsg' title='" + options.title + "'><p class='" + cssname + "'>" + options.msbox + "</p></div>";
$("body").append(str);
$("#jsLayMsg").dialog({
//title: null,
//show: null,
bgiframe: true,
autoOpen: false,
width: w,
//height: h,
resizable: false,
closeOnEscape: false,
draggable:false,
buttons: { "确定": function() { $(this).dialog("close"); }},
close: function() {
if (options.url == "back") {
history.back(-1);
} else if (options.url != "") {
location.href = options.url;
}
},
modal: true
});
$("#jsLayMsg").dialog("open");
}
|
JavaScript
|
$(function() {
$(".input,.login_input,.textarea").focus(function() {
$(this).addClass("focus");
}).blur(function() {
$(this).removeClass("focus");
});
//输入框提示,获取拥有HintTitle,HintInfo属性的对象
$("[HintTitle],[HintInfo]").focus(function(event) {
$("*").stop(); //停止所有正在运行的动画
$("#HintMsg").remove(); //先清除,防止重复出错
var HintHtml = "<ul id=\"HintMsg\"><li class=\"HintTop\"></li><li class=\"HintInfo\"><b>" + $(this).attr("HintTitle") + "</b>" + $(this).attr("HintInfo") + "</li><li class=\"HintFooter\"></li></ul>"; //设置显示的内容
var offset = $(this).offset(); //取得事件对象的位置
$("body").append(HintHtml); //添加节点
$("#HintMsg").fadeTo(0, 0.85); //对象的透明度
var HintHeight = $("#HintMsg").height(); //取得容器高度
$("#HintMsg").css({ "top": offset.top - HintHeight + "px", "left": offset.left + "px" }).fadeIn(500);
}).blur(function(event) {
$("#HintMsg").remove(); //删除UL
});
});
|
JavaScript
|
/*!
* artDialog iframeTools
* Date: 2011-11-25 13:54
* http://code.google.com/p/artdialog/
* (c) 2009-2011 TangBin, http://www.planeArt.cn
*
* This is licensed under the GNU LGPL, version 2.1 or later.
* For details, see: http://creativecommons.org/licenses/LGPL/2.1/
*/
;(function ($, window, artDialog, undefined) {
var _topDialog, _proxyDialog, _zIndex,
_data = '@ARTDIALOG.DATA',
_open = '@ARTDIALOG.OPEN',
_opener = '@ARTDIALOG.OPENER',
_winName = window.name = window.name
|| '@ARTDIALOG.WINNAME' + + new Date,
_isIE6 = window.VBArray && !window.XMLHttpRequest;
$(function () {
!window.jQuery && document.compatMode === 'BackCompat'
// 不支持怪异模式,请用主流的XHTML1.0或者HTML5的DOCTYPE申明
&& alert('artDialog Error: document.compatMode === "BackCompat"');
});
/** 获取 artDialog 可跨级调用的最高层的 window 对象 */
var _top = artDialog.top = function () {
var top = window,
test = function (name) {
try {
var doc = window[name].document; // 跨域|无权限
doc.getElementsByTagName; // chrome 本地安全限制
} catch (e) {
return false;
};
return window[name].artDialog
// 框架集无法显示第三方元素
&& doc.getElementsByTagName('frameset').length === 0;
};
if (test('top')) {
top = window.top;
} else if (test('parent')) {
top = window.parent;
};
return top;
}();
artDialog.parent = _top; // 兼容v4.1之前版本,未来版本将删除此
_topDialog = _top.artDialog;
// 获取顶层页面对话框叠加值
_zIndex = function () {
return _topDialog.defaults.zIndex;
};
/**
* 跨框架数据共享接口
* @see http://www.planeart.cn/?p=1554
* @param {String} 存储的数据名
* @param {Any} 将要存储的任意数据(无此项则返回被查询的数据)
*/
artDialog.data = function (name, value) {
var top = artDialog.top,
cache = top[_data] || {};
top[_data] = cache;
if (value !== undefined) {
cache[name] = value;
} else {
return cache[name];
};
return cache;
};
/**
* 数据共享删除接口
* @param {String} 删除的数据名
*/
artDialog.removeData = function (name) {
var cache = artDialog.top[_data];
if (cache && cache[name]) delete cache[name];
};
/** 跨框架普通对话框 */
artDialog.through = _proxyDialog = function () {
var api = _topDialog.apply(this, arguments);
// 缓存从当前 window(可能为iframe)调出所有跨框架对话框,
// 以便让当前 window 卸载前去关闭这些对话框。
// 因为iframe注销后也会从内存中删除其创建的对象,这样可以防止回调函数报错
if (_top !== window) artDialog.list[api.config.id] = api;
return api;
};
// 框架页面卸载前关闭所有穿越的对话框
_top !== window && $(window).bind('unload', function () {
var list = artDialog.list, config;
for (var i in list) {
if (list[i]) {
config = list[i].config;
if (config) config.duration = 0; // 取消动画
list[i].close();
//delete list[i];
};
};
});
/**
* 弹窗 (iframe)
* @param {String} 地址
* @param {Object} 配置参数. 这里传入的回调函数接收的第1个参数为iframe内部window对象
* @param {Boolean} 是否允许缓存. 默认true
*/
artDialog.open = function (url, options, cache) {
options = options || {};
var api, DOM,
$content, $main, iframe, $iframe, $idoc, iwin, ibody,
top = artDialog.top,
initCss = 'position:absolute;left:-9999em;top:-9999em;border:none 0;background:transparent',
loadCss = 'width:100%;height:100%;border:none 0';
if (cache === false) {
var ts = + new Date,
ret = url.replace(/([?&])_=[^&]*/, "$1_=" + ts );
url = ret + ((ret === url) ? (/\?/.test(url) ? "&" : "?") + "_=" + ts : "");
};
var load = function () {
var iWidth, iHeight,
loading = DOM.content.find('.aui_loading'),
aConfig = api.config;
$content.addClass('aui_state_full');
loading && loading.hide();
try {
iwin = iframe.contentWindow;
$idoc = $(iwin.document);
ibody = iwin.document.body;
} catch (e) {// 跨域
iframe.style.cssText = loadCss;
aConfig.follow
? api.follow(aConfig.follow)
: api.position(aConfig.left, aConfig.top);
options.init && options.init.call(api, iwin, top);
options.init = null;
return;
};
// 获取iframe内部尺寸
iWidth = aConfig.width === 'auto'
? $idoc.width() + (_isIE6 ? 0 : parseInt($(ibody).css('marginLeft')))
: aConfig.width;
iHeight = aConfig.height === 'auto'
? $idoc.height()
: aConfig.height;
// 适应iframe尺寸
setTimeout(function () {
iframe.style.cssText = loadCss;
}, 0);// setTimeout: 防止IE6~7对话框样式渲染异常
api.size(iWidth, iHeight);
// 调整对话框位置
aConfig.follow
? api.follow(aConfig.follow)
: api.position(aConfig.left, aConfig.top);
options.init && options.init.call(api, iwin, top);
options.init = null;
};
var config = {
zIndex: _zIndex(),
init: function () {
api = this;
DOM = api.DOM;
$main = DOM.main;
$content = DOM.content;
iframe = api.iframe = top.document.createElement('iframe');
iframe.src = url;
iframe.name = 'Open' + api.config.id;
iframe.style.cssText = initCss;
iframe.setAttribute('frameborder', 0, 0);
iframe.setAttribute('allowTransparency', true);
$iframe = $(iframe);
api.content().appendChild(iframe);
iwin = iframe.contentWindow;
try {
iwin.name = iframe.name;
artDialog.data(iframe.name + _open, api);
artDialog.data(iframe.name + _opener, window);
} catch (e) {};
$iframe.bind('load', load);
},
close: function () {
$iframe.css('display', 'none').unbind('load', load);
if (options.close && options.close.call(this, iframe.contentWindow, top) === false) {
return false;
};
$content.removeClass('aui_state_full');
// 重要!需要重置iframe地址,否则下次出现的对话框在IE6、7无法聚焦input
// IE删除iframe后,iframe仍然会留在内存中出现上述问题,置换src是最容易解决的方法
$iframe[0].src = 'about:blank';
$iframe.remove();
try {
artDialog.removeData(iframe.name + _open);
artDialog.removeData(iframe.name + _opener);
} catch (e) {};
}
};
// 回调函数第一个参数指向iframe内部window对象
if (typeof options.ok === 'function') config.ok = function () {
return options.ok.call(api, iframe.contentWindow, top);
};
if (typeof options.cancel === 'function') config.cancel = function () {
return options.cancel.call(api, iframe.contentWindow, top);
};
delete options.content;
for (var i in options) {
if (config[i] === undefined) config[i] = options[i];
};
return _proxyDialog(config);
};
/** 引用open方法扩展方法(在open打开的iframe内部私有方法) */
artDialog.open.api = artDialog.data(_winName + _open);
/** 引用open方法触发来源页面window(在open打开的iframe内部私有方法) */
artDialog.opener = artDialog.data(_winName + _opener) || window;
artDialog.open.origin = artDialog.opener; // 兼容v4.1之前版本,未来版本将删除此
/** artDialog.open 打开的iframe页面里关闭对话框快捷方法 */
artDialog.close = function () {
var api = artDialog.data(_winName + _open);
api && api.close();
return false;
};
// 点击iframe内容切换叠加高度
_top != window && $(document).bind('mousedown', function () {
var api = artDialog.open.api;
api && api.zIndex();
});
/**
* Ajax填充内容
* @param {String} 地址
* @param {Object} 配置参数
* @param {Boolean} 是否允许缓存. 默认true
*/
artDialog.load = function(url, options, cache){
cache = cache || false;
var opt = options || {};
var config = {
zIndex: _zIndex(),
init: function(here){
var api = this,
aConfig = api.config;
$.ajax({
url: url,
success: function (content) {
api.content(content);
opt.init && opt.init.call(api, here);
},
cache: cache
});
}
};
delete options.content;
for (var i in opt) {
if (config[i] === undefined) config[i] = opt[i];
};
return _proxyDialog(config);
};
/**
* 警告
* @param {String} 消息内容
*/
artDialog.alert = function (content, callback) {
return _proxyDialog({
id: 'Alert',
zIndex: _zIndex(),
icon: 'warning',
fixed: true,
lock: true,
content: content,
ok: true,
close: callback
});
};
/**
* 确认
* @param {String} 消息内容
* @param {Function} 确定按钮回调函数
* @param {Function} 取消按钮回调函数
*/
artDialog.confirm = function (content, yes, no) {
return _proxyDialog({
id: 'Confirm',
zIndex: _zIndex(),
icon: 'question',
fixed: true,
lock: true,
opacity: .1,
content: content,
ok: function (here) {
return yes.call(this, here);
},
cancel: function (here) {
return no && no.call(this, here);
}
});
};
/**
* 提问
* @param {String} 提问内容
* @param {Function} 回调函数. 接收参数:输入值
* @param {String} 默认值
*/
artDialog.prompt = function (content, yes, value) {
value = value || '';
var input;
return _proxyDialog({
id: 'Prompt',
zIndex: _zIndex(),
icon: 'question',
fixed: true,
lock: true,
opacity: .1,
content: [
'<div style="margin-bottom:5px;font-size:12px">',
content,
'</div>',
'<div>',
'<input value="',
value,
'" style="width:18em;padding:6px 4px" />',
'</div>'
].join(''),
init: function () {
input = this.DOM.content.find('input')[0];
input.select();
input.focus();
},
ok: function (here) {
return yes && yes.call(this, input.value, here);
},
cancel: true
});
};
/**
* 短暂提示
* @param {String} 提示内容
* @param {Number} 显示时间 (默认1.5秒)
*/
artDialog.tips = function (content, time) {
return _proxyDialog({
id: 'Tips',
zIndex: _zIndex(),
title: false,
cancel: false,
fixed: true,
lock: false
})
.content('<div style="padding: 0 1em;">' + content + '</div>')
.time(time || 1.5);
};
// 增强artDialog拖拽体验
// - 防止鼠标落入iframe导致不流畅
// - 对超大对话框拖动优化
$(function () {
var event = artDialog.dragEvent;
if (!event) return;
var $window = $(window),
$document = $(document),
positionType = _isIE6 ? 'absolute' : 'fixed',
dragEvent = event.prototype,
mask = document.createElement('div'),
style = mask.style;
style.cssText = 'display:none;position:' + positionType + ';left:0;top:0;width:100%;height:100%;'
+ 'cursor:move;filter:alpha(opacity=0);opacity:0;background:#FFF';
document.body.appendChild(mask);
dragEvent._start = dragEvent.start;
dragEvent._end = dragEvent.end;
dragEvent.start = function () {
var DOM = artDialog.focus.DOM,
main = DOM.main[0],
iframe = DOM.content[0].getElementsByTagName('iframe')[0];
dragEvent._start.apply(this, arguments);
style.display = 'block';
style.zIndex = artDialog.defaults.zIndex + 3;
if (positionType === 'absolute') {
style.width = $window.width() + 'px';
style.height = $window.height() + 'px';
style.left = $document.scrollLeft() + 'px';
style.top = $document.scrollTop() + 'px';
};
if (iframe && main.offsetWidth * main.offsetHeight > 307200) {
main.style.visibility = 'hidden';
};
};
dragEvent.end = function () {
var dialog = artDialog.focus;
dragEvent._end.apply(this, arguments);
style.display = 'none';
if (dialog) dialog.DOM.main[0].style.visibility = 'visible';
};
});
})(this.art || this.jQuery, this, this.artDialog);
|
JavaScript
|
$.extend({
includePath: '',
include: function (file) {
var files = typeof file == "string" ? [file] : file;
for (var i = 0; i < files.length; i++) {
var name = files[i].replace(/^\s|\s$/g, "");
var att = name.split('.');
var ext = att[att.length - 1].toLowerCase();
var isCSS = ext == "css";
var tag = isCSS ? "link" : "script";
var attr = isCSS ? " type='text/css' rel='stylesheet' " : " language='javascript' type='text/javascript' ";
var link = (isCSS ? "href" : "src") + "='" + $.includePath + name + "'";
if ($(tag + "[" + link + "]").length == 0) document.write("<" + tag + attr + link + "></" + tag + ">");
}
}
});
$(function () {
//文本框焦点
$("input.webSearch").focus(function () {
$(this).addClass("webfocus");
}).blur(function () {
$(this).removeClass("webfocus");
});
})
|
JavaScript
|
myFocus.extend({//*********************搜狐体育******************
mF_sohusports:function(par,F){
var box=F.$(par.id);
F.addList(box,['txt','num']);
var pic=F.$li('pic',box),txt=F.$li('txt',box),num=F.$li('num',box),n=txt.length;
//CSS
for(var i=0;i<n;i++){pic[i].style.display=txt[i].style.display='none';}
//PLAY
eval(F.switchMF(function(){
pic[index].style.display='none';
txt[index].style.display='none';
num[index].className='';
},function(){
F.fadeIn(pic[next]);
txt[next].style.display='';
num[next].className='current';
}))
eval(F.bind('num','par.trigger',par.delay));
}
});
|
JavaScript
|
myFocus.extend({//*********************配件商城风格******************
mF_peijianmall:function(par,F){
var box=F.$(par.id);
F.addList(box,['txt']);
var pics=F.$c('pic',box),txt=F.$li('txt',box),n=txt.length,param={};//运行时相关参数
pics.innerHTML+=pics.innerHTML;//无缝复制
//CSS
var pic=F.$li('pic',box),dir=par.direction,dis=par.width;//先假设左右
for(var i=0;i<pic.length;i++) pic[i].style.cssText='width:'+par.width+'px;height:'+par.height+'px;'//消除上下li间的多余间隙
if(dir=='left'||dir=='right') {pics.style.cssText='width:'+2*dis*n+'px;';pics.className+=' '+dir;}//左右运动设定
else {dis=par.height; pics.style.height=2*dis*n + 'px';}//上下运动设定
if(dir=='bottom'||dir=='right') pics.style[dir]=0+'px';//向下或向右的特殊处理
//CSS++
var txtH=isNaN(par.txtHeight/1)?34:par.txtHeight;//设置默认的文字高度
if(txtH===0) for(var i=0;i<n;i++) txt[i].innerHTML='';
//PLAY
eval(F.switchMF(function(){
txt[index>=n?(index-n):index].className = '';
},function(){
param[dir]=-dis*next;
F.slide(pics,param,par.duration,par.easing);
txt[next>=n?(next-n):next].className = 'current';
},'par.less','dir'));
eval(F.bind('txt','par.trigger',par.delay));
}
});
myFocus.set.params('mF_peijianmall',{//可选个性参数
less:true,//是否无缝,可选:true(是) | false(否)
duration:800,//过渡时间(毫秒),时间越大速度越小
direction:'left',//运动方向,可选:'top'(向上) | 'bottom'(向下) | 'left'(向左) | 'right'(向右)
easing:'easeOut'//运动形式,可选:'easeOut'(快出慢入) | 'easeIn'(慢出快入) | 'easeInOut'(慢出慢入) | 'swing'(摇摆运动) | 'linear'(匀速运动)
});
|
JavaScript
|
myFocus.extend({//*********************tbhuabao******************
mF_tbhuabao:function(par,F){
var box=F.$(par.id);
F.addList(box,['dot','txt','prev','next']);F.wrap([F.$c('pic',box)],'win');
var pics=F.$c('pic',box),dot=F.$li('dot',box),txt=F.$li('txt',box),pre=F.$c('prev',box),nex=F.$c('next',box),n=txt.length;
pics.innerHTML+=pics.innerHTML;//无缝复制
for(var i=0;i<n;i++) dot[i].innerHTML='<a href="javascript:;">•</a>';//小点
pre.innerHTML='<a href="javascript:;">‹</a>';nex.innerHTML='<a href="javascript:;">›</a>';//前后箭头
//CSS
var win=F.$c('win',box),pic=F.$li('pic',box),dots=F.$c('dot',box),dotH=32,arTop=par.height/2-32;
box.style.height=par.height+dotH+'px';
win.style.cssText='width:'+par.width+'px;height:'+par.height+'px;';
pics.style.width=par.width*2*n+'px';
for(var i=0;i<n;i++) txt[i].style.bottom=dotH+'px';
for(var i=0;i<2*n;i++) pic[i].style.cssText='width:'+par.width+'px;height:'+par.height+'px;';//滑动固定其大小
pre.style.cssText=nex.style.cssText='top:'+arTop+'px;';
//PLAY
eval(F.switchMF(function(){
txt[index>=n?(index-n):index].style.display='none';
dot[index>=n?(index-n):index].className = '';
},function(){
F.slide(pics,{left:-par.width*next});
txt[next>=n?(next-n):next].style.display='block';
dot[next>=n?(next-n):next].className = 'current';
},'par.less'));
eval(F.bind('dot','par.trigger',par.delay));
eval(F.turn('pre','nex'));
}
});
myFocus.set.params('mF_tbhuabao',{less:true});//支持无缝设置
|
JavaScript
|
myFocus.extend({//*********************淘宝2010主页风格******************
mF_taobao2010:function(par,F){
var box=F.$(par.id);
F.addList(box,['txt','num']);
var pics=F.$c('pic',box),txt=F.$li('txt',box),num=F.$li('num',box);
var n=txt.length,param={};//运行时相关参数
pics.innerHTML+=pics.innerHTML;//无缝复制
//CSS
var pic=F.$li('pic',box),dir=par.direction,dis=par.width;//先假设左右
for(var i=0;i<pic.length;i++) pic[i].style.cssText='width:'+par.width+'px;height:'+par.height+'px;'//消除上下li间的多余间隙
if(dir=='left'||dir=='right') {pics.style.cssText='width:'+2*dis*n+'px;';pics.className+=' '+dir;}//左右运动设定
else {dis=par.height; pics.style.height=2*dis*n + 'px';}//上下运动设定
if(dir=='bottom'||dir=='right') pics.style[dir]=0+'px';//向下或向右的特殊处理
//PLAY
eval(F.switchMF(function(){
txt[index>=n?(index-n):index].style.display='none';
num[index>=n?(index-n):index].className = '';
},function(){
param[dir]=-dis*next;
F.slide(pics,param,par.duration,par.easing);
txt[next>=n?(next-n):next].style.display='block';
num[next>=n?(next-n):next].className = 'current';
},'par.less','dir'))
eval(F.bind('num','par.trigger',par.delay));
}
});
myFocus.set.params('mF_taobao2010',{//可选个性参数
less:true,//是否无缝,可选:true(是)/false(否)
duration:600,//过渡时间(毫秒),时间越大速度越小
direction:'top',//运动方向,可选:'top'(向上) | 'bottom'(向下) | 'left'(向左) | 'right'(向右)
easing:'easeOut'//运动形式,可选:'easeOut'(快出慢入) | 'easeIn'(慢出快入) | 'easeInOut'(慢出慢入) | 'swing'(摇摆运动) | 'linear'(匀速运动)
});
|
JavaScript
|
myFocus.extend({//*********************kiki******************
mF_kiki:function(par,F){
var box=F.$(par.id);
F.addList(box,['txt','btn','prev','next']);
var pic=F.$li('pic',box),txt=F.$li('txt',box),btn=F.$li('btn',box),pre=F.$c('prev',box),nex=F.$c('next',box),n=txt.length;
F.wrap([pre,nex],'con'),pre.innerHTML='<a href="javascript:;">PREV</a> |',nex.innerHTML='<a href="javascript:;">NEXT</a>';
//CSS
var d1=par.width/2,d2=par.height/2,txtH=isNaN(par.txtHeight/1)?30:par.txtHeight;//设置默认的文字高度;
box.style.height=par.height+txtH+'px';
//PLAY
var s1,s2=1;//方向选择
switch(par.turn){
case 'left':s1=1,s2=1;break;
case 'right':s1=1,s2=-1;break;
case 'up':s1=2,s2=1;break;
case 'down':s1=2,s2=-1;break;
}
eval(F.switchMF(function(){},function(){
btn[prev].className='',btn[next].className='current';
var tt=s1==1?1:(s1==2?2:Math.round(1+(Math.random()*(2-1)))),dis,d,p_s1={},p_s2={},p_e={};
dis=tt==1?d1:d2,d=s2*dis,p_s1[tt==1?'left':'top']=d,p_s2[tt==1?'left':'top']=-d,p_e[tt==1?'left':'top']=0;
if(!first){F.stop(pic[prev]),pic[prev].style.cssText='left:0;top:0;z-index:3';}
if(!first){F.stop(pic[next]),pic[next].style.cssText='left:0;top:0;z-index:2';}
F.slide(pic[prev],p_s2,300,'linear',function(){txt[prev].style.display='none',this.style.zIndex=1,F.slide(this,p_e,800,'easeOut',function(){this.style.zIndex='';});});
F.slide(pic[next],p_s1,300,'linear',function(){txt[next].style.display='block',this.style.zIndex=3,F.slide(this,p_e,800,'easeOut');});
}));
eval(F.bind('btn','par.trigger',0));
eval(F.turn('pre','nex'));
}
});
myFocus.set.params('mF_kiki',{turn:'random'})//翻牌方向,可选:'left'(左)|'right'(右)|'up'(上)|'down'(下)|'random'(单向随机)
|
JavaScript
|
myFocus.extend({//*********************pithy******************
mF_pithy_tb:function(par,F){
var box=F.$(par.id);
F.addList(box,['thumb','txt','prev','next']);
var pics=F.$c('pic',box),thus=F.$c('thumb',box),thu=F.$li('thumb',box),txt=F.$li('txt',box),pre=F.$c('prev',box),nex=F.$c('next',box),n=txt.length;
pics.innerHTML+=pics.innerHTML;//无缝复制
//CSS
var pic=F.$li('pic',box),sw=par.width/4,sh=Math.floor(par.height/4);
box.style.width=5*sw+4+'px';
pics.style.height=2*par.height*n + 'px';
thus.style.cssText='width:'+sw+'px;height:'+sh*n+'px;';
for(var i=0;i<n;i++){
thu[i].style.cssText='width:'+(sw-17)+'px;height:'+(sh-10)+'px';//减去总padding
F.$$('span',thu[i])[0].style.cssText='width:'+(sw-7-1)+'px;height:'+(sh-2)+'px';//减去1px边框和pading
}
for(var i=0;i<2*n;i++) pic[i].style.height=par.height+'px';//消除间隙
pre.style.right=sw+40+'px';nex.style.right=sw+16+'px';//相差nex的宽=24
//PLAY
eval(F.switchMF(function(){
txt[index>=n?(index-n):index].style.display='none';
thu[index>=n?(index-n):index].className = '';
},function(){
F.slide(pics,{top:-par.height*next},600);
txt[next>=n?(next-n):next].style.display='block';
thu[next>=n?(next-n):next].className = 'current';
eval(F.scroll('thus','"top"','sh',4));
},'par.less','"top"'));
eval(F.bind('thu','"click"'));//让其只支持click点击
eval(F.turn('pre','nex'));
}
});
myFocus.set.params('mF_pithy_tb',{less:true});
|
JavaScript
|
myFocus.extend({
mF_classicHB:function(par,F){//*********************经典怀旧系列二--海报风格******************
var box=F.$(par.id);//定义焦点图盒子
F.addList(box,['txt','num']);//添加ul列表
var pic=F.$li('pic',box),txt=F.$li('txt',box),num=F.$li('num',box),n=pic.length;//定义焦点图元素
//CSS
var txtH=isNaN(par.txtHeight/1)?20:par.txtHeight;//设置默认的文字高度
for(var i=0;i<n;i++){
pic[i].style.cssText="display:none;top:-"+0.1*par.height+"px;left:-"+0.1*par.width+"px;width:"+1.2*par.width+"px;height:"+1.2*par.height+"px;"
txt[i].style.top=-txtH+'px';
}
//PLAY
eval(F.switchMF(function(){
F.stop(pic[index]).stop(txt[index]);
pic[index].style.cssText="display:none;top:-"+0.1*par.height+"px;left:-"+0.1*par.width+"px;width:"+1.2*par.width+"px;height:"+1.2*par.height+"px;"
txt[index].style.top=-txtH+'px';
F.slide(num[index],{width:16},200),num[index].className='';
},function(){
F.fadeIn(pic[next],300).slide(pic[next],{width:par.width,height:par.height,top:0,left:0},300)
F.slide(txt[next],{top:0},300);
F.slide(num[next],{width:26},200),num[next].className='current';
}))
eval(F.bind('num','par.trigger',par.delay));
}
});
|
JavaScript
|
myFocus.extend({//*********************趣玩风格******************
mF_quwan:function(par,F){
var box=F.$(par.id);
F.addList(box,['txt','num']);
var pic=F.$li('pic',box),txt=F.$li('txt',box),num=F.$li('num',box),n=txt.length;
//CSS
var numH=num[0].offsetHeight;
for(var i=0;i<n;i++){
box.style.height=par.height+numH+1+'px';
txt[i].style.cssText='bottom:'+(numH+1)+'px;';
}
//PLAY
eval(F.switchMF(function(){
pic[index].style.display='none';
txt[index].style.display='none';
num[index].className='';
},function(){
F.fadeIn(pic[next]);
txt[next].style.display='block';
num[next].className='current';
}));
eval(F.bind('num','par.trigger',par.delay));
}
});
|
JavaScript
|
myFocus.extend({//*********************液动风格******************
mF_liquid:function(par,F){
var box=F.$(par.id);
F.addList(box,['mod','txt','num']);F.$c('mod',box).innerHTML=F.$c('pic',box).innerHTML;
var pic=F.$li('pic',box),mod=F.$li('mod',box),txt=F.$li('txt',box),num=F.$li('num',box),n=pic.length;
//CSS
var imod=(function(){for(var a=[],i=0;i<n;i++) a.push(F.$$('img',mod[i])[0]);return a;})();
for(var i=0;i<n;i++){
pic[i].style.cssText='width:0px;z-index:1;';
imod[i].style.cssText='width:'+par.width*10+'px;height:'+par.height+'px;left:'+par.width+'px;';
}
//PLAY
eval(F.switchMF(function(){
F.stop(pic[index]).stop(imod[index]);
pic[index].style.width=0+'px';
imod[index].style.left=par.width+'px';
txt[index].style.display='none';
num[index].className = '';
},function(){
F.slide(imod[next],{left:0},100,'linear',function(){F.slide(pic[next],{width:par.width},700).slide(this,{left:-9*par.width},700)});
txt[next].style.display='block';
num[next].className = 'current';
}));
eval(F.bind('num','par.trigger',0));//延迟固定为0以兼容IE6
}
});
|
JavaScript
|
myFocus.extend({
mF_classicHC:function(par,F){//*********************经典怀旧系列一--慧聪风格******************
var box=F.$(par.id);//定义焦点图盒子
F.addList(box,['txt','num-bg','num']);//添加ul列表
var pic=F.$li('pic',box),txt=F.$li('txt',box),num=F.$li('num',box),n=pic.length;//定义焦点图元素
//CSS
var txtH=isNaN(par.txtHeight/1)?26:par.txtHeight;//设置默认的文字高度
box.style.width=par.width+2+'px';box.style.height=par.height+txtH+2+'px';
F.$c('num-bg',box).style.bottom=F.$c('num',box).style.bottom=txtH+1+'px';
for(var i=0;i<n;i++){
pic[i].style.display='none';
txt[i].style.cssText='display:none;top:'+(par.height+2)+'px;width:'+(par.width+2)+'px';
}
//PLAY
eval(F.switchMF(function(){
pic[index].style.display='none';
txt[index].style.display='none';
num[index].className='';
},function(){
F.fadeIn(pic[next]);
txt[next].style.display='';
num[next].className='current';
}))
eval(F.bind('num','par.trigger',par.delay));
}
});
|
JavaScript
|
myFocus.extend({//*********************ladyQ******************
mF_ladyQ:function(par,F){
var box=F.$(par.id);
F.addList(box,['txt','num','cout']);F.wrap([F.$c('num',box)],'num_box');
var pic=F.$li('pic',box),txt=F.$li('txt',box),num=F.$li('num',box),cout=F.$c('cout',box),n=txt.length,over=false,start=true;
//CSS
var numH=28,coutW=par.width-23*n-6;
box.style.height=par.height+numH+'px';
cout.style.cssText='top:'+(par.height+4)+'px;width:'+coutW+'px';
for(var i=0;i<n;i++) txt[i].style.bottom=numH-1+'px',pic[i].style.display='none';
//PLAY
eval(F.switchMF(function(){
pic[index].style.zIndex=1;
if(!start) F.slide(pic[index],{opacity:0},600,'easeOut',function(){this.index=''});
txt[index].style.display='none';
num[index].className='';
F.stop(cout),cout.style.width=coutW+'px';
if(!over) F.slide(cout,{width:0},_t,'linear');
},function(){
F.slide(pic[next],{opacity:1},600,'easeInOut');
txt[next].style.display='block';
num[next].className='current',start=false;
}));
eval(F.bind('num','par.trigger',par.delay));
F.addEvent(box,'mouseover',function(){F.stop(cout),cout.style.width=coutW+'px',over=true;});
F.addEvent(box,'mouseout',function(){F.slide(cout,{width:0},_t,'linear'),over=false;});
}
});
|
JavaScript
|
myFocus.extend({//*********************2010世博******************
mF_expo2010:function(par,F){
var box=F.$(par.id);//定义焦点图盒子
F.addList(box,['txt-bg','txt','num']);//添加ul列表
var pic=F.$li('pic',box),txt=F.$li('txt',box),num=F.$li('num',box),n=pic.length;//定义焦点图元素
//CSS
var H='default'?36:par.txtHeight+60;
for(var i=0;i<n;i++){
pic[i].style.display="none";
txt[i].style.bottom=-H+'px';
}
//PLAY
eval(F.switchMF(function(){
F.fadeOut(pic[index]);
num[index].className='';
},function(){
F.fadeIn(pic[next]);
F.slide(txt[prev],{bottom:-H},200,'swing',function(){F.slide(txt[next],{bottom:0},200,'easeOut')});
num[next].className='current';
}))
eval(F.bind('num','par.trigger',200));//固定其延迟
}
});
|
JavaScript
|
myFocus.extend({//*********************luluJQ******************
mF_luluJQ:function(par,F){
var box=F.$(par.id),pics=F.$c('pic',box);
for(var i=0,l=F.$$('a',pics);i<l.length;i++) l[i].innerHTML+='<span><b>'+F.$$('img',pics)[i].alt+'</b><i></i></span>';
var pics=F.$c('pic',box),pic=F.$li('pic',box),txt=F.$$('span',pics),txtBg=F.$$('i',pics),n=pic.length;
//CSS
var pad=par.pad||32,txtH=isNaN(par.txtHeight/1)?34:par.txtHeight;//设置默认的文字高度;
box.style.width=par.width+(n-1)*pad+'px';
for(var i=0;i<n;i++){
if(i>0) pic[i].style.left=par.width+(i-1)*pad+'px';
if(i>0&&par.gray) F.alterSRC(pic[i],'-2');
txt[i].style.cssText=txtBg[i].style.cssText='height:'+txtH+'px;line-height:'+txtH+'px;'
}
//PLAY
eval(F.switchMF(function(){
F.slide(txt[index],{top:0});
if(par.gray) F.alterSRC(pic[index],'-2');
},function(){
for(var i=0;i<n;i++){
if(i<=next) F.slide(pic[i],{left:i*pad});
else F.slide(pic[i],{left:par.width+i*pad-pad});
}
F.slide(txt[next],{top:-txtH});
if(par.gray) F.alterSRC(pic[next],'-2',true);
}))
eval(F.bind('pic','par.trigger',par.delay));
}
});
myFocus.set.params('mF_luluJQ',{//可选个性参数
pad:68,//图片留边宽度(像素)
gray:false//非当前图片是否变灰,可选:true(是) | false(否),如果要变灰,请先准备图片灰色的副本并命名为:"原来图片的名字-2"
});
|
JavaScript
|
myFocus__AGENT__.extend({//*********************mF_slide3D******************
mF_slide3D:function(par,F){
var box=F.$(par.id);
F.addList(box,['mask11','mask12','mask21','mask22','num','next']);
var pics=F.$c('pic',box),num=F.$li('num',box),m11=F.$c('mask11',box),m12=F.$c('mask12',box),m21=F.$c('mask21',box),m22=F.$c('mask22',box),nex=F.$c('next',box),n=num.length;
pics.innerHTML+=pics.innerHTML;
nex.innerHTML='NEXT';
//PLAY
var pic=F.$li('pic',box),d=Math.ceil(par.height/6);
eval(F.switchMF(function(){
m11.style.cssText=m12.style.cssText='border-width:0px '+par.width/2+'px;';
m21.style.cssText=m22.style.cssText='border-width:'+d+'px 0px;';
num[index].className='';
},function(){
pic[n].innerHTML=pic[prev].innerHTML;
pic[n+1].innerHTML=pic[next].innerHTML;
F.$$('img',pic[n])[0].style.cssText='width:'+par.width+'px;height:'+par.height+'px';
F.$$('img',pic[n+1])[0].style.cssText='width:0px;height:'+par.height+'px';
F.slide(F.$$('img',pic[n])[0],{width:0});
F.slide(F.$$('img',pic[n+1])[0],{width:par.width});
F.slide(m11,{borderLeftWidth:0,borderRightWidth:0,borderTopWidth:d,borderBottomWidth:d});
F.slide(m12,{borderLeftWidth:0,borderRightWidth:0,borderTopWidth:d,borderBottomWidth:d});
F.slide(m21,{borderLeftWidth:par.width/2,borderRightWidth:par.width/2,borderTopWidth:0,borderBottomWidth:0});
F.slide(m22,{borderLeftWidth:par.width/2,borderRightWidth:par.width/2,borderTopWidth:0,borderBottomWidth:0});
num[next].className='current';
}));
eval(F.bind('num','par.trigger',par.delay));
eval(F.turn('nex','nex'));
}
});
|
JavaScript
|
myFocus.extend({//*********************太平洋电脑网风格******************
mF_pconline:function(par,F){
var box=F.$(par.id);
F.addList(box,['txt','num']);
var pic=F.$li('pic',box),txt=F.$li('txt',box),num=F.$li('num',box),n=txt.length;
//CSS
var txtH=isNaN(par.txtHeight/1)?28:par.txtHeight;//设置默认的文字高度
box.style.height=par.height+txtH+'px';
//PLAY
eval(F.switchMF(function(){
pic[index].style.display='none';
txt[index].style.display='none';
num[index].className='';
},function(){
F.fadeIn(pic[next],par.duration);
txt[next].style.display='block';
num[next].className='current';
}));
eval(F.bind('num','par.trigger',par.delay));
}
});
myFocus.set.params('mF_pconline',{duration:300});
|
JavaScript
|
myFocus.extend({//*********************51xflash******************
mF_51xflash:function(par,F){
var box=F.$(par.id);
F.addList(box,['txt','play']);F.wrap([F.$c('pic',box)],'cont')
var cont=F.$c('cont',box),pics=F.$c('pic',cont),pic=F.$li('pic',cont),txt=F.$li('txt',box),btn=F.$c('play',box);
var n=pic.length;//运行时相关参数
//CSS
var pad=4,w=(par.width/3),h=(par.height-pad*2)/3,disX=w+pad,disY=h+pad,txtH=isNaN(par.txtHeight/1)?34:par.txtHeight;
box.style.cssText='width:'+(par.width+disX)+'px;height:'+(par.height+txtH+(txtH==0?0:pad))+'px;';//焦点图盒子
cont.style.cssText='width:'+(par.width+disX)+'px;height:'+par.height+'px;';//图片盒子
for(var i=0;i<n;i++){
txt[i].style.display='none';
pic[i].style.cssText='width:'+w+'px;height:'+h+'px;top:'+disY*(i-1)+'px;';
}
//PLAY
eval(F.switchMF(function(){
txt[index].style.display='none';
},function(){
pic[prev].style.zIndex=2,pic[next].style.zIndex=1;
F.slide(pic[prev],{right:0,top:parseInt(pic[next].style.top),width:w,height:h},400,'easeOut',function(){this.style.zIndex=''});
F.slide(pic[next],{right:disX,top:0,width:par.width,height:par.height},400);
txt[next].style.display='';
}))
eval(F.bind('pic','"click"'));
eval(F.toggle('btn','play','stop'));
}
});
|
JavaScript
|
myFocus.extend({//*********************淘宝商城风格******************
mF_taobaomall:function(par,F){
var box=F.$(par.id);
F.addList(box,['txt']);F.wrap([F.$c('pic',box)],'cont')
var cont=F.$c('cont',box),pics=F.$c('pic',box),txt=F.$li('txt',box);
var n=txt.length,param={};//运行时相关参数
pics.innerHTML+=pics.innerHTML;//无缝复制
//CSS
var pic=F.$li('pic',cont),dir=par.direction,dis=par.width;//先假设左右
for(var i=0;i<pic.length;i++) pic[i].style.cssText='width:'+par.width+'px;height:'+par.height+'px;'//消除上下li间的多余间隙
if(dir=='left'||dir=='right') {pics.style.cssText='width:'+2*dis*n+'px;';pics.className+=' '+dir;}//左右运动设定
else {dis=par.height; pics.style.height=2*dis*n + 'px';}//上下运动设定
if(dir=='bottom'||dir=='right') pics.style[dir]=0+'px';//向下或向右的特殊处理
//CSS++
var txtH=isNaN(par.txtHeight/1)?28:par.txtHeight;//设置默认的文字高度
box.style.cssText='height:'+(par.height+txtH+1)+'px;';
cont.style.cssText='width:'+par.width+'px;height:'+par.height+'px;';
for(var i=0;i<n;i++) txt[i].style.width=(par.width-n-1)/n+1+'px';
txt[n-1].style.border=0;
F.$c('txt',box).style.width=2*par.width+'px';
//PLAY
eval(F.switchMF(function(){
txt[index>=n?(index-n):index].className = '';
},function(){
param[dir]=-dis*next;
F.slide(pics,param,par.duration,par.easing);
txt[next>=n?(next-n):next].className = 'current';
},'par.less','dir'));
eval(F.bind('txt','par.trigger',par.delay));
}
});
myFocus.set.params('mF_taobaomall',{//可选个性参数
less:true,//是否无缝:true(是)| false(否)
duration:600,//过渡时间(毫秒),时间越大速度越小
direction:'top',//运动方向,可选:'top'(向上) | 'bottom'(向下) | 'left'(向左) | 'right'(向右)
easing:'easeOut'//运动形式,可选:'easeOut'(快出慢入) | 'easeIn'(慢出快入) | 'easeInOut'(慢出慢入) | 'swing'(摇摆运动) | 'linear'(匀速运动)
});
|
JavaScript
|
myFocus.extend({//*********************雷柏风格******************
mF_rapoo:function(par,F){
var box=F.$(par.id);
F.addList(box,['txt','num','prev','next']);
var pic=F.$li('pic',box),txt=F.$li('txt',box),num=F.$li('num',box),pre=F.$c('prev',box),nex=F.$c('next',box);
var n=txt.length;//运行时相关参数
pre.innerHTML='<a href="javascript:;">‹</a>';nex.innerHTML='<a href="javascript:;">›</a>';//前后箭头
//CSS
var txts=F.$c('txt',box),nums=F.$c('num',box),txtW=par.txtWidth=='default'?68:par.txtWidth||68;//设置默认的文字宽度;
txts.style.width=(n-1)*24+txtW+'px';nums.style.width=n*24+6+txtW+'px';
pre.style.right=parseInt(nums.style.width)+26+'px';
for(var i=0;i<n;i++){
txt[i].style.left=i*24+'px';
pic[i].style.left=par.width+'px';
}
//PLAY
eval(F.switchMF(function(){
txt[index].style.width=0+'px';
num[index].className='';
for(var i=0;i<n;i++) num[i].style.marginLeft=6+'px';
nex.style.right=88+'px'
},function(){
pic[next].style.zIndex=1;
F.slide(pic[next],{left:0},400,'easeInOut',function(){this.style.zIndex='';if(prev!==next){pic[prev].style.left=par.width+'px';}}).slide(txt[next],{width:txtW},400,'easeInOut').slide(nex,{right:14},400,'easeInOut');
if(next<n-1) F.slide(num[next+1],{marginLeft:txtW+12},400,'easeInOut');
num[next].className='current';
}));
eval(F.bind('num','"click"',par.delay));//让其只支持click点击
eval(F.turn('pre','nex'));
}
});
myFocus.set.params('mF_rapoo',{//可选个性参数
txtWidth:68//文字段宽度(像素)
});
|
JavaScript
|
myFocus.extend({//*********************奇艺******************
mF_qiyi:function(par,F){
var box=F.$(par.id);
F.addList(box,['txt','num']);F.wrap([F.$c('pic',box),F.$c('txt',box)],'swt');
var swt=F.$c('swt',box),pic=F.$li('pic',swt),txt=F.$li('txt',swt),num=F.$li('num',box),n=txt.length;
//CSS
var txtH=isNaN(par.txtHeight/1)?34:par.txtHeight;//设置默认的文字高度
swt.style.width=par.width*n+'px';
for(var i=0;i<n;i++) pic[i].style.width=par.width+'px';
//PLAY
eval(F.switchMF(function(){
num[index].className='';
},function(){
txt[next].style.top=0+'px';//复位
F.slide(swt,{left:-par.width*next},800,'easeOut',function(){F.slide(txt[next],{top:-txtH})});
num[next].className='current';
}))
eval(F.bind('num','par.trigger',par.delay));
}
});
|
JavaScript
|
myFocus.extend({//*********************YSlide--翻页效果******************
mF_YSlider:function(par,F){
var box=F.$(par.id);
F.addList(box,['rePic','txt','num']);F.$c('rePic',box).innerHTML=F.$c('pic',box).innerHTML;//复制
var pic=F.$li('pic',box),rePic=F.$li('rePic',box),txt=F.$li('txt',box),num=F.$li('num',box),n=pic.length;
//PLAY
var s=par.direct=='one'?1:0,d1=par.width,d2=par.height;
eval(F.switchMF(function(){
var r=s?1:Math.round(1+(Math.random()*(2-1))),dis,d,p={};
dis=r==1?d1:d2,d=Math.round(Math.random()+s)?dis:-dis,p[r==1?'left':'top']=d;
pic[index].style.display=txt[index].style.display='none';
rePic[index].style.cssText='left:0;top:0;display:block;filter:alpha(opacity=100);opacity:1;';
F.slide(rePic[index],p,500,'swing').fadeOut(rePic[index],500);
num[index].className='';
},function(){
pic[next].style.display=txt[next].style.display='block';
num[next].className='current';
}))
eval(F.bind('num','par.trigger',par.delay));
}
});
myFocus.set.params('mF_YSlider',{direct:'random'});//切出方向,可选:'random'(随机) | 'one'(单向/向右)
|
JavaScript
|
myFocus.extend({//*********************games******************
mF_games_tb:function(par,F){
var box=F.$(par.id);
F.addList(box,['thumb','txt','prev','next']);F.wrap([F.$c('thumb',box)],'win');
var pics=F.$c('pic',box),win=F.$c('win',box),thus=F.$c('thumb',box),thu=F.$li('thumb',box),txt=F.$li('txt',box),pre=F.$c('prev',box),nex=F.$c('next',box),n=txt.length;
pre.innerHTML='<a href="javascript:;">‹</a>';nex.innerHTML='<a href="javascript:;">›</a>';//前后箭头
//CSS
var pic=F.$li('pic',box),winW=par.width-20,sw=Math.floor(winW/3),sh=par.height/par.width*(sw-14)+28;//参考*按比例求高
box.style.height=par.height+sh+'px';
win.style.cssText='width:'+winW+'px;height:'+sh+'px;';
thus.style.width=sw*n+'px';
for(var i=0;i<n;i++){
thu[i].style.cssText='width:'+(sw-14)+'px;height:'+(sh-28)+'px';//减去总padding
F.$$('span',thu[i])[0].style.cssText='width:'+(sw-14)+'px;height:'+(sh-28)+'px';//参考*
txt[i].style.bottom=sh+'px';
}
pre.style.cssText=nex.style.cssText='height:'+(sh-28+6)+'px;line-height:'+(sh-28+6)+'px;';
//PLAY
eval(F.switchMF(function(){
pic[index].style.display='none';
txt[index].style.display='none';
thu[index].className = '';
},function(){
F.fadeIn(pic[next]);
txt[next].style.display='block';
thu[next].className = 'current';
eval(F.scroll('thus','"left"','sw',4));
}));
eval(F.bind('thu','"click"'));//让其只支持click点击
eval(F.turn('pre','nex'));
}
});
|
JavaScript
|
myFocus.extend({
mF_liuzg:function(par,F){//*********************绚丽切片风格******************
var box=F.$(par.id);
F.addList(box,['txt','num']);//添加ul列表
var pics=F.$c('pic',box),pic=F.$li('pic',box),n=pic.length;
var c=par.height%par.chip?8:par.chip,h=par.height/c,html=[];
for(var i=0;i<c;i++){
html.push('<li><div>');
for(var j=0;j<n;j++) html.push(pic[j].innerHTML);
html.push('</div></li>');
}
pics.innerHTML=html.join('');
//CSS
var pic=F.$li('pic',box),txt=F.$li('txt',box),btn=F.$li('num',box),wrap=F.$$('div',pics);
for(var i=0;i<c;i++){//初始化样式设置
pic[i].style.cssText='width:'+par.width+'px;height:'+h+'px;';
wrap[i].style.cssText='height:'+par.height*n+'px;top:'+-i*h+'px;';
F.$$('a',pic[i])[0].style.height=par.height+'px';
}
//PLAY
eval(F.switchMF(function(){
txt[index].style.display='none';
btn[index].className = '';
},function(){
var tt=par.type===4?Math.round(1+(Math.random()*(3-1))):par.type;//效果选择
var dur=tt===1?1200:300;
for(var i=0;i<c;i++){
F.slide(wrap[i],{top:-next*c*h-i*h},tt===3?Math.round(300+(Math.random()*(1200-300))):dur);
dur=tt===1?dur-150:dur+150;
}
txt[next].style.display='block';
btn[next].className = 'current';
}))
eval(F.bind('btn','par.trigger',par.delay));
}
});
myFocus.set.params('mF_liuzg',{//可选个性参数
chip:8,//图片切片数量,能被焦点图的高整除才有效,默认为8片
type:4////切片效果,可选:1(甩头) | 2(甩尾) | 3(凌乱) | 4(随机)
});
|
JavaScript
|
myFocus.extend({//*********************fscreen******************
mF_fscreen_tb:function(par,F){
var box=F.$(par.id);
F.addList(box,['thu-bg','thumb','txt','prev','next']);F.wrap([F.$c('thumb',box)],'win');
var pics=F.$c('pic',box),thuBg=F.$c('thu-bg',box),win=F.$c('win',box),thus=F.$c('thumb',box),thu=F.$li('thumb',box),txt=F.$li('txt',box),pre=F.$c('prev',box),nex=F.$c('next',box),n=txt.length;
pre.innerHTML='<a href="javascript:;">‹</a>';nex.innerHTML='<a href="javascript:;">›</a>';//前后箭头
//CSS
var pic=F.$li('pic',box),winW=par.width-20,sw=Math.floor(winW/4),sh=par.height/par.width*(sw-36)+16;//参考*按比例求高
thuBg.style.height=sh+'px';
win.style.cssText='width:'+winW+'px;height:'+sh+'px;';
thus.style.width=sw*n+'px';
for(var i=0;i<n;i++){
thu[i].style.cssText=F.$$('span',thu[i])[0].style.cssText='width:'+(sw-36)+'px;height:'+(sh-16)+'px';//减去总padding(*)
txt[i].style.left=-par.width+'px';
}
pre.style.cssText=nex.style.cssText='height:'+(sh-16)+'px;line-height:'+(sh-20)+'px;';//-padding
//PLAY
eval(F.switchMF(function(){
for(var i=0;i<n;i++){
F.stop(txt[i]);
txt[i].style.left=-par.width+'px';
}
pic[index].style.display='none';
thu[index].className = '';
},function(){
F.fadeIn(pic[next],300,function(){F.slide(txt[next],{left:0})});
thu[next].className = 'current';
eval(F.scroll('thus','"left"','sw',4));
}));
eval(F.bind('thu','"click"'));//让其只支持click点击
eval(F.turn('pre','nex'));
}
});
|
JavaScript
|
/*!
* jquery.scrollLoading.js
* by zhangxinxu http://www.zhangxinxu.com
* 2010-11-19 v1.0
* 2012-01-13 v1.1 偏移值计算修改 position → offset
*/
(function($) {
$.fn.scrollLoading = function(options) {
var defaults = {
attr: "data-url"
};
var params = $.extend({}, defaults, options || {});
params.cache = [];
$(this).each(function() {
var node = this.nodeName.toLowerCase(), url = $(this).attr(params["attr"]);
if (!url) { return; }
//重组
var data = {
obj: $(this),
tag: node,
url: url
};
params.cache.push(data);
});
//动态显示数据
var loading = function() {
var st = $(window).scrollTop(), sth = st + $(window).height();
$.each(params.cache, function(i, data) {
var o = data.obj, tag = data.tag, url = data.url;
if (o) {
post = o.offset().top; posb = post + o.height();
if ((post > st && post < sth) || (posb > st && posb < sth)) {
//在浏览器窗口内
if (tag === "img") {
//图片,改变src
o.attr("src", url);
} else {
o.load(url);
}
data.obj = null;
}
}
});
return false;
};
//事件触发
//加载完毕即执行
loading();
//滚动执行
$(window).bind("scroll", loading);
};
})(jQuery);
|
JavaScript
|
/*
* Translated default messages for the jQuery validation plugin.
* Locale: CN
*/
jQuery.extend(jQuery.validator.messages, {
required: "必填信息",
remote: "请修正该信息",
email: "电子邮件格式有误",
url: "请输入合法的网址",
date: "请输入合法的日期",
dateISO: "请输入合法的日期 (ISO).",
number: "请输入合法的数字",
digits: "只能输入整数",
creditcard: "请输入合法的信用卡号",
equalTo: "请再次输入相同的值",
accept: "请输入拥有合法后缀名的字符串",
maxlength: jQuery.validator.format("长度最多 {0} 个字符"),
minlength: jQuery.validator.format("长度最少 {0} 个字符"),
rangelength: jQuery.validator.format("长度要在 {0} 和 {1} 之间"),
range: jQuery.validator.format("请输入一个介于 {0} 和 {1} 之间的值"),
max: jQuery.validator.format("请输入一个最大为 {0} 的值"),
min: jQuery.validator.format("请输入一个最小为 {0} 的值")
});
|
JavaScript
|
/**
* jQuery Validation Plugin 1.9.0
*
* http://bassistance.de/jquery-plugins/jquery-plugin-validation/
* http://docs.jquery.com/Plugins/Validation
*
* Copyright (c) 2006 - 2011 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
*/
(function() {
function stripHtml(value) {
// remove html tags and space chars
return value.replace(/<.[^<>]*?>/g, ' ').replace(/ | /gi, ' ')
// remove numbers and punctuation
.replace(/[0-9.(),;:!?%#$'"_+=\/-]*/g,'');
}
jQuery.validator.addMethod("maxWords", function(value, element, params) {
return this.optional(element) || stripHtml(value).match(/\b\w+\b/g).length < params;
}, jQuery.validator.format("Please enter {0} words or less."));
jQuery.validator.addMethod("minWords", function(value, element, params) {
return this.optional(element) || stripHtml(value).match(/\b\w+\b/g).length >= params;
}, jQuery.validator.format("Please enter at least {0} words."));
jQuery.validator.addMethod("rangeWords", function(value, element, params) {
return this.optional(element) || stripHtml(value).match(/\b\w+\b/g).length >= params[0] && value.match(/bw+b/g).length < params[1];
}, jQuery.validator.format("Please enter between {0} and {1} words."));
})();
jQuery.validator.addMethod("letterswithbasicpunc", function(value, element) {
return this.optional(element) || /^[a-z-.,()'\"\s]+$/i.test(value);
}, "Letters or punctuation only please");
jQuery.validator.addMethod("alphanumeric", function(value, element) {
return this.optional(element) || /^\w+$/i.test(value);
}, "Letters, numbers, spaces or underscores only please");
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please");
jQuery.validator.addMethod("nowhitespace", function(value, element) {
return this.optional(element) || /^\S+$/i.test(value);
}, "No white space please");
jQuery.validator.addMethod("ziprange", function(value, element) {
return this.optional(element) || /^90[2-5]\d\{2}-\d{4}$/.test(value);
}, "Your ZIP-code must be in the range 902xx-xxxx to 905-xx-xxxx");
jQuery.validator.addMethod("integer", function(value, element) {
return this.optional(element) || /^-?\d+$/.test(value);
}, "A positive or negative non-decimal number please");
/**
* Return true, if the value is a valid vehicle identification number (VIN).
*
* Works with all kind of text inputs.
*
* @example <input type="text" size="20" name="VehicleID" class="{required:true,vinUS:true}" />
* @desc Declares a required input element whose value must be a valid vehicle identification number.
*
* @name jQuery.validator.methods.vinUS
* @type Boolean
* @cat Plugins/Validate/Methods
*/
jQuery.validator.addMethod(
"vinUS",
function(v){
if (v.length != 17)
return false;
var i, n, d, f, cd, cdv;
var LL = ["A","B","C","D","E","F","G","H","J","K","L","M","N","P","R","S","T","U","V","W","X","Y","Z"];
var VL = [1,2,3,4,5,6,7,8,1,2,3,4,5,7,9,2,3,4,5,6,7,8,9];
var FL = [8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2];
var rs = 0;
for(i = 0; i < 17; i++){
f = FL[i];
d = v.slice(i,i+1);
if(i == 8){
cdv = d;
}
if(!isNaN(d)){
d *= f;
}
else{
for(n = 0; n < LL.length; n++){
if(d.toUpperCase() === LL[n]){
d = VL[n];
d *= f;
if(isNaN(cdv) && n == 8){
cdv = LL[n];
}
break;
}
}
}
rs += d;
}
cd = rs % 11;
if(cd == 10){cd = "X";}
if(cd == cdv){return true;}
return false;
},
"The specified vehicle identification number (VIN) is invalid."
);
/**
* Return true, if the value is a valid date, also making this formal check dd/mm/yyyy.
*
* @example jQuery.validator.methods.date("01/01/1900")
* @result true
*
* @example jQuery.validator.methods.date("01/13/1990")
* @result false
*
* @example jQuery.validator.methods.date("01.01.1900")
* @result false
*
* @example <input name="pippo" class="{dateITA:true}" />
* @desc Declares an optional input element whose value must be a valid date.
*
* @name jQuery.validator.methods.dateITA
* @type Boolean
* @cat Plugins/Validate/Methods
*/
jQuery.validator.addMethod(
"dateITA",
function(value, element) {
var check = false;
var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if( re.test(value)){
var adata = value.split('/');
var gg = parseInt(adata[0],10);
var mm = parseInt(adata[1],10);
var aaaa = parseInt(adata[2],10);
var xdata = new Date(aaaa,mm-1,gg);
if ( ( xdata.getFullYear() == aaaa ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == gg ) )
check = true;
else
check = false;
} else
check = false;
return this.optional(element) || check;
},
"Please enter a correct date"
);
jQuery.validator.addMethod("dateNL", function(value, element) {
return this.optional(element) || /^\d\d?[\.\/-]\d\d?[\.\/-]\d\d\d?\d?$/.test(value);
}, "Vul hier een geldige datum in."
);
jQuery.validator.addMethod("time", function(value, element) {
return this.optional(element) || /^([01]\d|2[0-3])(:[0-5]\d){0,2}$/.test(value);
}, "Please enter a valid time, between 00:00 and 23:59");
jQuery.validator.addMethod("time12h", function(value, element) {
return this.optional(element) || /^((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))$/i.test(value);
}, "Please enter a valid time, between 00:00 am and 12:00 pm");
/**
* matches US phone number format
*
* where the area code may not start with 1 and the prefix may not start with 1
* allows '-' or ' ' as a separator and allows parens around area code
* some people may want to put a '1' in front of their number
*
* 1(212)-999-2345
* or
* 212 999 2344
* or
* 212-999-0983
*
* but not
* 111-123-5434
* and not
* 212 123 4567
*/
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
jQuery.validator.addMethod('phoneUK', function(phone_number, element) {
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(\(?(0|\+44)[1-9]{1}\d{1,4}?\)?\s?\d{3,4}\s?\d{3,4})$/);
}, 'Please specify a valid phone number');
jQuery.validator.addMethod('mobileUK', function(phone_number, element) {
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^((0|\+44)7(5|6|7|8|9){1}\d{2}\s?\d{6})$/);
}, 'Please specify a valid mobile number');
// TODO check if value starts with <, otherwise don't try stripping anything
jQuery.validator.addMethod("strippedminlength", function(value, element, param) {
return jQuery(value).text().length >= param;
}, jQuery.validator.format("Please enter at least {0} characters"));
// same as email, but TLD is optional
jQuery.validator.addMethod("email2", function(value, element, param) {
return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)*(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
}, jQuery.validator.messages.email);
// same as url, but TLD is optional
jQuery.validator.addMethod("url2", function(value, element, param) {
return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)*(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
}, jQuery.validator.messages.url);
// NOTICE: Modified version of Castle.Components.Validator.CreditCardValidator
// Redistributed under the the Apache License 2.0 at http://www.apache.org/licenses/LICENSE-2.0
// Valid Types: mastercard, visa, amex, dinersclub, enroute, discover, jcb, unknown, all (overrides all other settings)
jQuery.validator.addMethod("creditcardtypes", function(value, element, param) {
if (/[^0-9-]+/.test(value))
return false;
value = value.replace(/\D/g, "");
var validTypes = 0x0000;
if (param.mastercard)
validTypes |= 0x0001;
if (param.visa)
validTypes |= 0x0002;
if (param.amex)
validTypes |= 0x0004;
if (param.dinersclub)
validTypes |= 0x0008;
if (param.enroute)
validTypes |= 0x0010;
if (param.discover)
validTypes |= 0x0020;
if (param.jcb)
validTypes |= 0x0040;
if (param.unknown)
validTypes |= 0x0080;
if (param.all)
validTypes = 0x0001 | 0x0002 | 0x0004 | 0x0008 | 0x0010 | 0x0020 | 0x0040 | 0x0080;
if (validTypes & 0x0001 && /^(51|52|53|54|55)/.test(value)) { //mastercard
return value.length == 16;
}
if (validTypes & 0x0002 && /^(4)/.test(value)) { //visa
return value.length == 16;
}
if (validTypes & 0x0004 && /^(34|37)/.test(value)) { //amex
return value.length == 15;
}
if (validTypes & 0x0008 && /^(300|301|302|303|304|305|36|38)/.test(value)) { //dinersclub
return value.length == 14;
}
if (validTypes & 0x0010 && /^(2014|2149)/.test(value)) { //enroute
return value.length == 15;
}
if (validTypes & 0x0020 && /^(6011)/.test(value)) { //discover
return value.length == 16;
}
if (validTypes & 0x0040 && /^(3)/.test(value)) { //jcb
return value.length == 16;
}
if (validTypes & 0x0040 && /^(2131|1800)/.test(value)) { //jcb
return value.length == 15;
}
if (validTypes & 0x0080) { //unknown
return true;
}
return false;
}, "Please enter a valid credit card number.");
jQuery.validator.addMethod("ipv4", function(value, element, param) {
return this.optional(element) || /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/i.test(value);
}, "Please enter a valid IP v4 address.");
jQuery.validator.addMethod("ipv6", function(value, element, param) {
return this.optional(element) || /^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$/i.test(value);
}, "Please enter a valid IP v6 address.");
/**
* Return true if the field value matches the given format RegExp
*
* @example jQuery.validator.methods.pattern("AR1004",element,/^AR\d{4}$/)
* @result true
*
* @example jQuery.validator.methods.pattern("BR1004",element,/^AR\d{4}$/)
* @result false
*
* @name jQuery.validator.methods.pattern
* @type Boolean
* @cat Plugins/Validate/Methods
*/
jQuery.validator.addMethod("pattern", function(value, element, param) {
return this.optional(element) || param.test(value);
}, "Invalid format.");
/**
* 自定义验证规则——增加对select的验证
*/
jQuery.validator.addMethod(
"selectNone", // name验证方法名
function (value, element) // 验证规则
{
if (value=="") // select默认值需要设置为"none"(当然可以自定义其他值)
{
return false;
}
else {
return true;
}
},
"请选择正确的选项!" // 默认验证消息(自定义规则信息的国际化是否不起作用?)
);
jQuery.validator.addMethod(
"selectZero", // name验证方法名
function (value, element) // 验证规则
{
if (value == "0") // select默认值需要设置为"none"(当然可以自定义其他值)
{
return false;
}
else {
return true;
}
},
"请选择正确的选项!" // 默认验证消息(自定义规则信息的国际化是否不起作用?)
);
jQuery.validator.addMethod("isTel", function (value, element) {
var tel = /^\d{3,4}-?\d{7,9}$/; //电话号码格式010-12345678
return this.optional(element) || (tel.test(value));
}, "请正确填写您的电话号码");
|
JavaScript
|
/*!
* jQuery Form Plugin
* version: 2.96 (16-FEB-2012)
* @requires jQuery v1.3.2 or later
*
* Examples and documentation at: http://malsup.com/jquery/form/
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
;(function($) {
/*
Usage Note:
-----------
Do not use both ajaxSubmit and ajaxForm on the same form. These
functions are mutually exclusive. Use ajaxSubmit if you want
to bind your own submit handler to the form. For example,
$(document).ready(function() {
$('#myForm').bind('submit', function(e) {
e.preventDefault(); // <-- important
$(this).ajaxSubmit({
target: '#output'
});
});
});
Use ajaxForm when you want the plugin to manage all the event binding
for you. For example,
$(document).ready(function() {
$('#myForm').ajaxForm({
target: '#output'
});
});
You can also use ajaxForm with delegation (requires jQuery v1.7+), so the
form does not have to exist when you invoke ajaxForm:
$('#myForm').ajaxForm({
delegation: true,
target: '#output'
});
When using ajaxForm, the ajaxSubmit function will be invoked for you
at the appropriate time.
*/
/**
* ajaxSubmit() provides a mechanism for immediately submitting
* an HTML form using AJAX.
*/
$.fn.ajaxSubmit = function(options) {
// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
var method, action, url, $form = this;
if (typeof options == 'function') {
options = { success: options };
}
method = this.attr('method');
action = this.attr('action');
url = (typeof action === 'string') ? $.trim(action) : '';
url = url || window.location.href || '';
if (url) {
// clean url (don't include hash vaue)
url = (url.match(/^([^#]+)/)||[])[1];
}
options = $.extend(true, {
url: url,
success: $.ajaxSettings.success,
type: method || 'GET',
iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
}, options);
// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinyMCE or FCKEditor
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
// provide opportunity to alter form data before it is serialized
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var traditional = options.traditional;
if ( traditional === undefined ) {
traditional = $.ajaxSettings.traditional;
}
var qx,n,v,a = this.formToArray(options.semantic);
if (options.data) {
options.extraData = options.data;
qx = $.param(options.data, traditional);
}
// give pre-submit callback an opportunity to abort the submit
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
// fire vetoable 'validate' event
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a, traditional);
if (qx) {
q = ( q ? (q + '&' + qx) : qx );
}
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null; // data is null for 'get'
}
else {
options.data = q; // data is the query string for 'post'
}
var callbacks = [];
if (options.resetForm) {
callbacks.push(function() { $form.resetForm(); });
}
if (options.clearForm) {
callbacks.push(function() { $form.clearForm(options.includeHidden); });
}
// perform a load on the target only if dataType is not provided
if (!options.dataType && options.target) {
var oldSuccess = options.success || function(){};
callbacks.push(function(data) {
var fn = options.replaceTarget ? 'replaceWith' : 'html';
$(options.target)[fn](data).each(oldSuccess, arguments);
});
}
else if (options.success) {
callbacks.push(options.success);
}
options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
var context = options.context || options; // jQuery 1.4+ supports scope context
for (var i=0, max=callbacks.length; i < max; i++) {
callbacks[i].apply(context, [data, status, xhr || $form, $form]);
}
};
// are there files to upload?
var fileInputs = $('input:file:enabled[value]', this); // [value] (issue #113)
var hasFileInputs = fileInputs.length > 0;
var mp = 'multipart/form-data';
var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
var fileAPI = !!(hasFileInputs && fileInputs.get(0).files && window.FormData);
log("fileAPI :" + fileAPI);
var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI;
// options.iframe allows user to force iframe mode
// 06-NOV-09: now defaulting to iframe mode if file input is detected
if (options.iframe !== false && (options.iframe || shouldUseFrame)) {
// hack to fix Safari hang (thanks to Tim Molendijk for this)
// see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
if (options.closeKeepAlive) {
$.get(options.closeKeepAlive, function() {
fileUploadIframe(a);
});
}
else {
fileUploadIframe(a);
}
}
else if ((hasFileInputs || multipart) && fileAPI) {
options.progress = options.progress || $.noop;
fileUploadXhr(a);
}
else {
$.ajax(options);
}
// fire 'notify' event
this.trigger('form-submit-notify', [this, options]);
return this;
// XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)
function fileUploadXhr(a) {
var formdata = new FormData();
for (var i=0; i < a.length; i++) {
if (a[i].type == 'file')
continue;
formdata.append(a[i].name, a[i].value);
}
$form.find('input:file:enabled').each(function(){
var name = $(this).attr('name'), files = this.files;
if (name) {
for (var i=0; i < files.length; i++)
formdata.append(name, files[i]);
}
});
if (options.extraData) {
for (var k in options.extraData)
formdata.append(k, options.extraData[k])
}
options.data = null;
var s = $.extend(true, {}, $.ajaxSettings, options, {
contentType: false,
processData: false,
cache: false,
type: 'POST'
});
//s.context = s.context || s;
s.data = null;
var beforeSend = s.beforeSend;
s.beforeSend = function(xhr, o) {
o.data = formdata;
if(xhr.upload) { // unfortunately, jQuery doesn't expose this prop (http://bugs.jquery.com/ticket/10190)
xhr.upload.onprogress = function(event) {
o.progress(event.position, event.total);
};
}
if(beforeSend)
beforeSend.call(o, xhr, options);
};
$.ajax(s);
}
// private function for handling file uploads (hat tip to YAHOO!)
function fileUploadIframe(a) {
var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;
var useProp = !!$.fn.prop;
if (a) {
if ( useProp ) {
// ensure that every serialized input is still enabled
for (i=0; i < a.length; i++) {
el = $(form[a[i].name]);
el.prop('disabled', false);
}
} else {
for (i=0; i < a.length; i++) {
el = $(form[a[i].name]);
el.removeAttr('disabled');
}
};
}
if ($(':input[name=submit],:input[id=submit]', form).length) {
// if there is an input with a name or id of 'submit' then we won't be
// able to invoke the submit fn on the form (at least not x-browser)
alert('Error: Form elements must not have name or id of "submit".');
return;
}
s = $.extend(true, {}, $.ajaxSettings, options);
s.context = s.context || s;
id = 'jqFormIO' + (new Date().getTime());
if (s.iframeTarget) {
$io = $(s.iframeTarget);
n = $io.attr('name');
if (n == null)
$io.attr('name', id);
else
id = n;
}
else {
$io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />');
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
}
io = $io[0];
xhr = { // mock object
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {},
abort: function(status) {
var e = (status === 'timeout' ? 'timeout' : 'aborted');
log('aborting upload... ' + e);
this.aborted = 1;
$io.attr('src', s.iframeSrc); // abort op in progress
xhr.error = e;
s.error && s.error.call(s.context, xhr, e, status);
g && $.event.trigger("ajaxError", [xhr, s, e]);
s.complete && s.complete.call(s.context, xhr, e);
}
};
g = s.global;
// trigger ajax global events so that activity/block indicators work like normal
if (g && ! $.active++) {
$.event.trigger("ajaxStart");
}
if (g) {
$.event.trigger("ajaxSend", [xhr, s]);
}
if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
if (s.global) {
$.active--;
}
return;
}
if (xhr.aborted) {
return;
}
// add submitting element to data if we know it
sub = form.clk;
if (sub) {
n = sub.name;
if (n && !sub.disabled) {
s.extraData = s.extraData || {};
s.extraData[n] = sub.value;
if (sub.type == "image") {
s.extraData[n+'.x'] = form.clk_x;
s.extraData[n+'.y'] = form.clk_y;
}
}
}
var CLIENT_TIMEOUT_ABORT = 1;
var SERVER_ABORT = 2;
function getDoc(frame) {
var doc = frame.contentWindow ? frame.contentWindow.document : frame.contentDocument ? frame.contentDocument : frame.document;
return doc;
}
// Rails CSRF hack (thanks to Yvan Barthelemy)
var csrf_token = $('meta[name=csrf-token]').attr('content');
var csrf_param = $('meta[name=csrf-param]').attr('content');
if (csrf_param && csrf_token) {
s.extraData = s.extraData || {};
s.extraData[csrf_param] = csrf_token;
}
// take a breath so that pending repaints get some cpu time before the upload starts
function doSubmit() {
// make sure form attrs are set
var t = $form.attr('target'), a = $form.attr('action');
// update form attrs in IE friendly way
form.setAttribute('target',id);
if (!method) {
form.setAttribute('method', 'POST');
}
if (a != s.url) {
form.setAttribute('action', s.url);
}
// ie borks in some cases when setting encoding
if (! s.skipEncodingOverride && (!method || /post/i.test(method))) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
// support timout
if (s.timeout) {
timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
}
// look for server aborts
function checkState() {
try {
var state = getDoc(io).readyState;
log('state = ' + state);
if (state.toLowerCase() == 'uninitialized')
setTimeout(checkState,50);
}
catch(e) {
log('Server abort: ' , e, ' (', e.name, ')');
cb(SERVER_ABORT);
timeoutHandle && clearTimeout(timeoutHandle);
timeoutHandle = undefined;
}
}
// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (s.extraData) {
for (var n in s.extraData) {
extraInputs.push(
$('<input type="hidden" name="'+n+'">').attr('value',s.extraData[n])
.appendTo(form)[0]);
}
}
if (!s.iframeTarget) {
// add iframe to doc and submit the form
$io.appendTo('body');
io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
}
setTimeout(checkState,15);
form.submit();
}
finally {
// reset attrs and remove "extra" input elements
form.setAttribute('action',a);
if(t) {
form.setAttribute('target', t);
} else {
$form.removeAttr('target');
}
$(extraInputs).remove();
}
}
if (s.forceSync) {
doSubmit();
}
else {
setTimeout(doSubmit, 10); // this lets dom updates render
}
var data, doc, domCheckCount = 50, callbackProcessed;
function cb(e) {
if (xhr.aborted || callbackProcessed) {
return;
}
try {
doc = getDoc(io);
}
catch(ex) {
log('cannot access response document: ', ex);
e = SERVER_ABORT;
}
if (e === CLIENT_TIMEOUT_ABORT && xhr) {
xhr.abort('timeout');
return;
}
else if (e == SERVER_ABORT && xhr) {
xhr.abort('server abort');
return;
}
if (!doc || doc.location.href == s.iframeSrc) {
// response not received yet
if (!timedOut)
return;
}
io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
var status = 'success', errMsg;
try {
if (timedOut) {
throw 'timeout';
}
var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
log('isXml='+isXml);
if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) {
if (--domCheckCount) {
// in some browsers (Opera) the iframe DOM is not always traversable when
// the onload callback fires, so we loop a bit to accommodate
log('requeing onLoad callback, DOM not available');
setTimeout(cb, 250);
return;
}
// let this fall through because server response could be an empty document
//log('Could not access iframe DOM after mutiple tries.');
//throw 'DOMException: not available';
}
//log('response detected');
var docRoot = doc.body ? doc.body : doc.documentElement;
xhr.responseText = docRoot ? docRoot.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
if (isXml)
s.dataType = 'xml';
xhr.getResponseHeader = function(header){
var headers = {'content-type': s.dataType};
return headers[header];
};
// support for XHR 'status' & 'statusText' emulation :
if (docRoot) {
xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status;
xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
}
var dt = (s.dataType || '').toLowerCase();
var scr = /(json|script|text)/.test(dt);
if (scr || s.textarea) {
// see if user embedded response in textarea
var ta = doc.getElementsByTagName('textarea')[0];
if (ta) {
xhr.responseText = ta.value;
// support for XHR 'status' & 'statusText' emulation :
xhr.status = Number( ta.getAttribute('status') ) || xhr.status;
xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
}
else if (scr) {
// account for browsers injecting pre around json response
var pre = doc.getElementsByTagName('pre')[0];
var b = doc.getElementsByTagName('body')[0];
if (pre) {
xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;
}
else if (b) {
xhr.responseText = b.textContent ? b.textContent : b.innerText;
}
}
}
else if (dt == 'xml' && !xhr.responseXML && xhr.responseText != null) {
xhr.responseXML = toXml(xhr.responseText);
}
try {
data = httpData(xhr, dt, s);
}
catch (e) {
status = 'parsererror';
xhr.error = errMsg = (e || status);
}
}
catch (e) {
log('error caught: ',e);
status = 'error';
xhr.error = errMsg = (e || status);
}
if (xhr.aborted) {
log('upload aborted');
status = null;
}
if (xhr.status) { // we've set xhr.status
status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
}
// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
if (status === 'success') {
s.success && s.success.call(s.context, data, 'success', xhr);
g && $.event.trigger("ajaxSuccess", [xhr, s]);
}
else if (status) {
if (errMsg == undefined)
errMsg = xhr.statusText;
s.error && s.error.call(s.context, xhr, status, errMsg);
g && $.event.trigger("ajaxError", [xhr, s, errMsg]);
}
g && $.event.trigger("ajaxComplete", [xhr, s]);
if (g && ! --$.active) {
$.event.trigger("ajaxStop");
}
s.complete && s.complete.call(s.context, xhr, status);
callbackProcessed = true;
if (s.timeout)
clearTimeout(timeoutHandle);
// clean up
setTimeout(function() {
if (!s.iframeTarget)
$io.remove();
xhr.responseXML = null;
}, 100);
}
var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else {
doc = (new DOMParser()).parseFromString(s, 'text/xml');
}
return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
};
var parseJSON = $.parseJSON || function(s) {
return window['eval']('(' + s + ')');
};
var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4
var ct = xhr.getResponseHeader('content-type') || '',
xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if (xml && data.documentElement.nodeName === 'parsererror') {
$.error && $.error('parsererror');
}
if (s && s.dataFilter) {
data = s.dataFilter(data, type);
}
if (typeof data === 'string') {
if (type === 'json' || !type && ct.indexOf('json') >= 0) {
data = parseJSON(data);
} else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
$.globalEval(data);
}
}
return data;
};
}
};
/**
* ajaxForm() provides a mechanism for fully automating form submission.
*
* The advantages of using this method instead of ajaxSubmit() are:
*
* 1: This method will include coordinates for <input type="image" /> elements (if the element
* is used to submit the form).
* 2. This method will include the submit element's name/value data (for the element that was
* used to submit the form).
* 3. This method binds the submit() method to the form for you.
*
* The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
* passes the options argument along after properly binding events for submit elements and
* the form itself.
*/
$.fn.ajaxForm = function(options) {
options = options || {};
options.delegation = options.delegation && $.isFunction($.fn.on);
// in jQuery 1.3+ we can fix mistakes with the ready state
if (!options.delegation && this.length === 0) {
var o = { s: this.selector, c: this.context };
if (!$.isReady && o.s) {
log('DOM not ready, queuing ajaxForm');
$(function() {
$(o.s,o.c).ajaxForm(options);
});
return this;
}
// is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
return this;
}
if ( options.delegation ) {
$(document)
.off('submit.form-plugin', this.selector, doAjaxSubmit)
.off('click.form-plugin', this.selector, captureSubmittingElement)
.on('submit.form-plugin', this.selector, options, doAjaxSubmit)
.on('click.form-plugin', this.selector, options, captureSubmittingElement);
return this;
}
return this.ajaxFormUnbind()
.bind('submit.form-plugin', options, doAjaxSubmit)
.bind('click.form-plugin', options, captureSubmittingElement);
};
// private event handlers
function doAjaxSubmit(e) {
var options = e.data;
if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
e.preventDefault();
$(this).ajaxSubmit(options);
}
}
function captureSubmittingElement(e) {
var target = e.target;
var $el = $(target);
if (!($el.is(":submit,input:image"))) {
// is this a child element of the submit el? (ex: a span within a button)
var t = $el.closest(':submit');
if (t.length == 0) {
return;
}
target = t[0];
}
var form = this;
form.clk = target;
if (target.type == 'image') {
if (e.offsetX != undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') {
var offset = $el.offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - target.offsetLeft;
form.clk_y = e.pageY - target.offsetTop;
}
}
// clear form vars
setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
};
// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
return this.unbind('submit.form-plugin click.form-plugin');
};
/**
* formToArray() gathers form element data into an array of objects that can
* be passed to any of the following ajax functions: $.get, $.post, or load.
* Each object in the array has both a 'name' and 'value' property. An example of
* an array for a simple login form might be:
*
* [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
*
* It is this array that is passed to pre-submit callback functions provided to the
* ajaxSubmit() and ajaxForm() methods.
*/
$.fn.formToArray = function(semantic) {
var a = [];
if (this.length === 0) {
return a;
}
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) {
return a;
}
var i,j,n,v,el,max,jmax;
for(i=0, max=els.length; i < max; i++) {
el = els[i];
n = el.name;
if (!n) {
continue;
}
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(!el.disabled && form.clk == el) {
a.push({name: n, value: $(el).val(), type: el.type });
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
continue;
}
v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
for(j=0, jmax=v.length; j < jmax; j++) {
a.push({name: n, value: v[j]});
}
}
else if (v !== null && typeof v != 'undefined') {
a.push({name: n, value: v, type: el.type});
}
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle it here
var $input = $(form.clk), input = $input[0];
n = input.name;
if (n && !input.disabled && input.type == 'image') {
a.push({name: n, value: $input.val()});
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
}
return a;
};
/**
* Serializes form data into a 'submittable' string. This method will return a string
* in the format: name1=value1&name2=value2
*/
$.fn.formSerialize = function(semantic) {
//hand off to jQuery.param for proper encoding
return $.param(this.formToArray(semantic));
};
/**
* Serializes all field elements in the jQuery object into a query string.
* This method will return a string in the format: name1=value1&name2=value2
*/
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) {
return;
}
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i=0,max=v.length; i < max; i++) {
a.push({name: n, value: v[i]});
}
}
else if (v !== null && typeof v != 'undefined') {
a.push({name: this.name, value: v});
}
});
//hand off to jQuery.param for proper encoding
return $.param(a);
};
/**
* Returns the value(s) of the element in the matched set. For example, consider the following form:
*
* <form><fieldset>
* <input name="A" type="text" />
* <input name="A" type="text" />
* <input name="B" type="checkbox" value="B1" />
* <input name="B" type="checkbox" value="B2"/>
* <input name="C" type="radio" value="C1" />
* <input name="C" type="radio" value="C2" />
* </fieldset></form>
*
* var v = $(':text').fieldValue();
* // if no values are entered into the text inputs
* v == ['','']
* // if values entered into the text inputs are 'foo' and 'bar'
* v == ['foo','bar']
*
* var v = $(':checkbox').fieldValue();
* // if neither checkbox is checked
* v === undefined
* // if both checkboxes are checked
* v == ['B1', 'B2']
*
* var v = $(':radio').fieldValue();
* // if neither radio is checked
* v === undefined
* // if first radio is checked
* v == ['C1']
*
* The successful argument controls whether or not the field element must be 'successful'
* (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
* The default value of the successful argument is true. If this value is false the value(s)
* for each element is returned.
*
* Note: This method *always* returns an array. If no valid value can be determined the
* array will be empty, otherwise it will contain one or more values.
*/
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
continue;
}
v.constructor == Array ? $.merge(val, v) : val.push(v);
}
return val;
};
/**
* Returns the value of the field element.
*/
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (successful === undefined) {
successful = true;
}
if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1)) {
return null;
}
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) {
return null;
}
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index+1 : ops.length);
for(var i=(one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = op.value;
if (!v) { // extra pain for IE...
v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
}
if (one) {
return v;
}
a.push(v);
}
}
return a;
}
return $(el).val();
};
/**
* Clears the form data. Takes the following actions on the form's input fields:
* - input text fields will have their 'value' property set to the empty string
* - select elements will have their 'selectedIndex' property set to -1
* - checkbox and radio inputs will have their 'checked' property set to false
* - inputs of type submit, button, reset, and hidden will *not* be effected
* - button elements will *not* be effected
*/
$.fn.clearForm = function(includeHidden) {
return this.each(function() {
$('input,select,textarea', this).clearFields(includeHidden);
});
};
/**
* Clears the selected form elements.
*/
$.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (re.test(t) || tag == 'textarea' || (includeHidden && /hidden/.test(t)) ) {
this.value = '';
}
else if (t == 'checkbox' || t == 'radio') {
this.checked = false;
}
else if (tag == 'select') {
this.selectedIndex = -1;
}
});
};
/**
* Resets the form data. Causes all form elements to be reset to their original value.
*/
$.fn.resetForm = function() {
return this.each(function() {
// guard against an input with the name of 'reset'
// note that IE reports the reset function as an 'object'
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
this.reset();
}
});
};
/**
* Enables or disables any matching elements.
*/
$.fn.enable = function(b) {
if (b === undefined) {
b = true;
}
return this.each(function() {
this.disabled = !b;
});
};
/**
* Checks/unchecks any matching checkboxes or radio buttons and
* selects/deselects and matching option elements.
*/
$.fn.selected = function(select) {
if (select === undefined) {
select = true;
}
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio') {
this.checked = select;
}
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
});
};
// expose debug var
$.fn.ajaxSubmit.debug = false;
// helper fn for console logging
function log() {
if (!$.fn.ajaxSubmit.debug)
return;
var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
if (window.console && window.console.log) {
window.console.log(msg);
}
else if (window.opera && window.opera.postError) {
window.opera.postError(msg);
}
};
})(jQuery);
|
JavaScript
|
// plugin author : chenjinfa@gmail.com
// plugin name : $.include
// $.include('file/ajaxa.js');$.include('file/ajaxa.css');
// or $.includePath = 'file/';$.include(['ajaxa.js','ajaxa.css']);
$.extend({
includePath: '',
include: function (file) {
var files = typeof file == "string" ? [file] : file;
for (var i = 0; i < files.length; i++) {
var name = files[i].replace(/^\s|\s$/g, "");
var att = name.split('.');
var ext = att[att.length - 1].toLowerCase();
var isCSS = ext == "css";
var tag = isCSS ? "link" : "script";
var attr = isCSS ? " type='text/css' rel='stylesheet' " : " language='javascript' type='text/javascript' ";
var link = (isCSS ? "href" : "src") + "='" + $.includePath + name + "'";
if ($(tag + "[" + link + "]").length == 0) document.write("<" + tag + attr + link + "></" + tag + ">");
}
}
});
|
JavaScript
|
//上传事件
function _upfile(i) {
$(".seeupfile").remove();
var obj1 = $(i);
var fid = i.form.id;
var strUrl = _strBasePath() + "ajaxtools/fileupload.ashx?f=" + $(obj1).attr("name") + "&t=add";
$("#" + fid).ajaxSubmit({
beforeSubmit: function (formData, jqForm, options) {
_fileuploadEffect('display', i);
},
success: function (data) {
_fileuploadEffect('hide', i);
if ($(obj1).parent().parent().find("input.filedisplay").attr("value") != "") {
$(obj1).parent().parent().parent().find("input[type='hidden']").val().replace($(obj1).parent().parent().find("input.filedisplay").attr("value"), data.msbox);
} else {
if ($(obj1).parent().parent().parent().find("input[type='hidden']").val() == "") {
$(obj1).parent().parent().parent().find("input[type='hidden']").val(data.msbox + ",");
}
else {
$(obj1).parent().parent().parent().find("input[type='hidden']").val($(obj1).parent().parent().parent().find("input[type='hidden']").val() + data.msbox + ",");
}
}
if ($(obj1).parent().parent().parent().hasClass("m")) {
$(obj1).parent().parent().parent().append(_jsfileuploadInputHtml(_jsfileuploadGetNewName($(obj1).attr("name"))));
}
$(obj1).parent().parent().find("input.filedisplay").attr("value", data.msbox);
//$(obj1).attr("disabled", "false");
getHtmlTools(obj1, "up");
},
error: function (data, status, e) {
alert("上传失败,错误信息:" + e);
},
url: strUrl,
dataType: "json",
timeout: 600000
});
}
function _updel(i,t) {
var obj1 = $(i);
//$(obj1).parent().find("input[type='file']").attr("disabled", "true");
var submitUrl = _strBasePath() + "ajaxtools/fileupload.ashx?f=" + $(obj1).parent().find("input.filedisplay").attr("value") + "&t=del&dt=" + t;
$.ajax({
url: submitUrl,
timeout: 600000,
dataType: "json",
success: function (data) {
if (data.msg == "1") {
$(obj1).parent().parent().find("input[type='hidden']").val($(obj1).parent().parent().find("input[type='hidden']").val().replace($(obj1).parent().find("input.filedisplay").attr("value") + ",", ""));
if ($(obj1).parent().parent().hasClass("m")) {
$(obj1).parent().remove();
}
else {
$(obj1).parent().parent().find("input[type='hidden']").val("");
$(obj1).parent().find("input.filedisplay").attr("value", "");
$(i).next().remove();
$(i).remove();
}
}
else {
alert(data.msbox);
}
}
});
}
function _upsee(i, t) {
if ($(i).text() == "预") {
$("a._filesee").text("预");
$(i).text("关");
$(".seeupfile").remove();
var obj1 = $(i);
var cHtml = "";
var objImg;
if (t.indexOf("edit_") < 0) {
objImg = _strBasePath() + "/upload/temp/" + $(obj1).parent().find("input.filedisplay").attr("value");
}
else {
objImg = _strBasePath() + t.replace("edit_", "") + $(obj1).parent().find("input.filedisplay").attr("value");
}
var ni = new Image();
ni.onload = function () {
var width = ni.width;
}
ni.src = objImg;
cHtml = "<div class=\"seeupfile\" name=\"1\" width='" + ni.width + "' height='" + ni.width + "' >";
cHtml += "<img src=\"" + objImg + "\" alter=\"点击关闭\" />";
cHtml += "</div>"
$(obj1).append(cHtml);
} else {
if ($(i).text() == "关") {
$($(i)).find("div").remove();
$(i).text("预")
}
}
}
$(function () {
var j = 0;
$.each($(".fileUpload"), function () {
//alert($(this).html())
if ($(this).find("input[type='hidden']").attr("value") != "" && $(this).find("input[type='hidden']").attr("value").length > 0) {
var arrFileList = new Array();
arrFileList = $(this).find("input[type='hidden']").attr("value").split(",");
//alert($(this).html())
if (!$(this).hasClass("m")) {
$(this).find(".filedisplay").val(arrFileList[0]);
getHtmlTools($(this).find("input[type='file']"), "edit_" + $(this).attr("path"));
} else {
for (var n = 0; n < arrFileList.length; n++) {
if (arrFileList[n] != "") {
$(_jsfileuploadInputHtml("nf" + "_" + j + "_" + n)).insertBefore($(this).find(".fileTools:eq(" + n + ")"));
//$(this).append();
//$(this).parent().find(".filedisplay").attr("value", arrFileList[n]);
$(this).find("input[name='" + "nf" + "_" + j + "_" + n + "']").parent().parent().find(".filedisplay").val(arrFileList[n]);
getHtmlTools($(this).find("input[name='" + "nf" + "_" + j + "_" + n + "']"), "edit_" + $(this).attr("path"));
}
}
}
}
j++;
});
})
///生成新的上传工具
function _jsfileuploadInputHtml(o) {
var inputHtml = "<div class=\"fileTools\">";
inputHtml += "<input type=\"text\" class=\"input w160 filedisplay\" />";
inputHtml += "<a href=\"javascript:void(0);\" class=\"files\">";
inputHtml += "<input type=\"file\" onchange=\"_upfile(this)\" class=\"upload\" name=\"" + o + "\" runat=\"server\" />";
inputHtml += "上传</a>";
inputHtml += "<span class=\"uploading\">正在上传,请稍候...</span>";
inputHtml += "</div>";
return inputHtml;
}
///多个上传时生成新地ID
function _jsfileuploadGetNewName(name) {
if (name == null) {
name = "newt";
}
var lastPlace = name.lastIndexOf("_");
var oldname = name.substr(lastPlace + 1, name.length - lastPlace - 1);
var r = /^[0-9]*[1-9][0-9]*$/; //正整数
if (!r.test(oldname)) {
newName = name + "_1";
}
else {
var _name = name.substr(0, lastPlace);
if (!isNaN(parseInt(oldname))) {
var i = parseInt(oldname);
newName = _name + "_" + (i + 1).toString();
}
else {
newName = name + "_1";
}
}
return newName;
}
//loading按钮
function _fileuploadEffect(type, i) {
if (type == 'display') {
//隐藏上传按钮
$($(i)).parent().nextAll(".files").eq(0).hide();
//显示LOADING图片
$($(i)).parent().nextAll(".uploading").eq(0).show();
}
if (type == 'hide') {
$($(i)).parent().nextAll(".files").eq(0).show();
$($(i)).parent().nextAll(".uploading").eq(0).hide();
}
}
//工具
function getHtmlTools(o,t) {
$(o).parent().parent().find("a._filedel,a._filesee").remove();
$(o).parent().parent().append("<a href=\"javascript:;\" class=\"_filedel\" onclick=\"_updel(this,'" + t + "')\">删</a><a href=\"javascript:;\" class=\"_filesee\" onclick=\"_upsee(this,'" + t + "')\">预</a>");
}
///上传ajax处理文件路径
function _strBasePath() {
var baseUrl = document.domain;
var port = document.location.port;
if (port != "") {
port = ":" + port;
}
return "http://" + baseUrl + port + "/";
}
|
JavaScript
|
/*
http://www.JSON.org/json2.js
2011-02-23
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, strict: false, regexp: false */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
var JSON;
if (!JSON) {
JSON = {};
}
(function () {
"use strict";
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0 ? '[]' : gap ?
'[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
'[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0 ? '{}' : gap ?
'{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
'{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
|
JavaScript
|
/**
* jQuery Initial input value replacer
*
* Sets input value attribute to a starting value
* @author Marco "DWJ" Solazzi - hello@dwightjack.com
* @license Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
* @copyright Copyright (c) 2008 Marco Solazzi
* @version 0.1
* @requires jQuery 1.2.x
*/
(function (jQuery) {
/**
* Setting input initialization
*
* @param {String|Object|Bool} text Initial value of the field. Can be either a string, a jQuery reference (example: $("#element")), or boolean false (default) to search for related label
* @param {Object} [opts] An object containing options:
* color (initial text color, default : "#666"),
* e (event which triggers initial text clearing, default: "focus"),
* force (execute this script even if input value is not empty, default: false)
* keep (if value of field is empty on blur, re-apply initial text, default: true)
*/
jQuery.fn.inputLabel = function(text,opts) {
o = jQuery.extend({ color: "#666", e:"focus", force : false, keep : true}, opts || {});
var clearInput = function (e) {
var target = jQuery(e.target);
var value = jQuery.trim(target.val());
if (e.type == e.data.obj.e && value == e.data.obj.innerText) {
jQuery(target).css("color", "").val("");
if (!e.data.obj.keep) {
jQuery(target).unbind(e.data.obj.e+" blur",clearInput);
}
} else if (e.type == "blur" && value == "" && e.data.obj.keep) {
jQuery(this).css("color", e.data.obj.color).val(e.data.obj.innerText);
}
};
return this.each(function () {
o.innerText = (text || false);
if (!o.innerText) {
var id = jQuery(this).attr("id");
o.innerText = jQuery(this).parents("form").find("label[for=" + id + "]").hide().text();
}
else
if (typeof o.innerText != "string") {
o.innerText = jQuery(o.innerText).text();
}
o.innerText = jQuery.trim(o.innerText);
if (o.force || jQuery(this).val() == "") {
jQuery(this).css("color", o.color).val(o.innerText);
}
jQuery(this).bind(o.e+" blur",{obj:o},clearInput);
});
};
})(jQuery);
|
JavaScript
|
; (function ($) {
$.fn.extend({
hasScrollBarX: function () {
return this[0].scrollWidth > this[0].clientWidth;
},
hasScrollBarY: function () {
return this[0].scrollHeight > this[0].clientHeight;
},
hasScrollBar: function () {
return this.hasScrollBarX() || this.hasScrollBarY();
},
params: function(a,b){
return a + b;
}
});
})(jQuery)
;(function ($) {
$.fn.oms_autocomplate = function (options) {
var timer;
var childindex = -1;
var _seft = this;
$(_seft).attr("autocomplete", "off");
var defaults = { url: null, maxHeight: 412, paramTypeSelector: "", select: function (event, ui) {
this.value = ui.item.value;
if (ui.item.redirecturl != undefined && $.trim(ui.item.redirecturl) != '') {
window.top.location = $.trim(ui.item.redirecturl);
}
}
};
var opt = $.extend({}, defaults, options);
function search_keyup(e) {
var the = this;
if ((e.keyCode == 38 || e.keyCode == 40) && this.value != "") {
window.clearInterval(timer);
}
if (e.keyCode == 13) {
if (childindex > -1) {
getElem().css("display", "none");
$(the).trigger('selected', [{ item: getElem().find('li:eq(' + childindex + ')').data('data')}]);
childindex = -1;
}
} else {
if (the.value != "") {
if(!getElem().filter(":hidden")[0] && (e.keyCode == 38 || e.keyCode == 40))
{
return;
}
$.get(opt.url, { key: the.value, type: (opt.paramTypeSelector != '' ? $(opt.paramTypeSelector).attr('title') : "") ,time:new Date().toString()}, function (serverdata) {
getElem().children("ul").empty();
var data = eval(serverdata);
$.each(data, function (i) {
var li = $('<li style="padding:2px 0px 2px 5px; height:16px; line-height:16px; cursor:pointer;overflow:hidden;position:relative;">' + this.label + '</li>');
li.data('value', this.value);
li.data('label', this.label);
li.data('data', this);
li.bind('click', function () {
$(the).trigger('selected', [{ item: data[i]}]);
});
getElem().children("ul").append(li).css("overflow", "auto");
});
if (getElem().find("li").length == 0) {
getElem().css("display", "none");
return false;
} else {
childindex = -1;
getElem().find("li").each(function (i) {
$(this).hover(function () {
childindex = i;
getElem().find("li").css({ backgroundColor: "", color: "#666666" });
this.style.backgroundColor = "#FA8F5C";
this.style.color = "#FFF";
}, function () { });
});
}
if (getElem().filter(":hidden")[0]) {
getElem().css({ height: "0px", display: "block" });
}
var tw = opt.inputWidth != null && opt.inputWidth > 0 ? opt.inputWidth : $(the).outerWidth();
var th = opt.inputHeight != null && opt.inputHeight > 0 ? opt.inputHeight : $(the).outerHeight();
var h = Math.min(opt.maxHeight, getElem().find("li").outerHeight() * $("#oms_autocomplate").find("li").length + 10);
var l = parseInt($(the).offset().left) - parseInt($(the).css("marginLeft"));
var tt = parseInt($(the).offset().top) - parseInt($(the).css("marginTop"));
var t = tt + parseInt(th);
var clientH = $(document).height();
getElem().css({ width: tw, left: l }).children("ul").height(h - 10);
if (clientH - t >= h) {
getElem().stop().css({ top: t }).animate({ height: h }, 0);
} else {
if (getElem().height() == 0) {
getElem().stop().css({ top: tt, height: "0px" }).animate({ top: tt - h - 2, height: h }, 0);
} else {
getElem().stop().animate({ top: tt - h - 2, height: h }, 0);
}
}
});
} else {
getElem().css("display", "none");
}
}
}
function search_keydown(e) {
var len = getElem().find("li").length;
if (e.keyCode == 38) {
window.clearInterval(timer);
if (len > 0) {
if (childindex <= 0) {
childindex = len - 1;
} else {
childindex--;
}
getElem().find("li").css({ backgroundColor: "", color: "#666666" }).eq(childindex).css({ backgroundColor: "#FA8F5C", color: "#FFF" });
scrollUL(getElem().children("ul")[0], childindex, e.keyCode);
timer = window.setInterval(function () {
if (childindex <= 0) {
childindex = len - 1;
} else {
childindex--;
}
getElem().find("li").css({ backgroundColor: "", color: "#666666" }).eq(childindex).css({ backgroundColor: "#FA8F5C", color: "#FFF" });
scrollUL(getElem().children("ul")[0], childindex, e.keyCode);
}, 850);
}
} else if (e.keyCode == 40) {
window.clearInterval(timer);
if (len > 0) {
if (childindex >= len - 1) {
childindex = 0;
} else {
childindex++;
}
getElem().find("li").css({ backgroundColor: "", color: "#666666" }).eq(childindex).css({ backgroundColor: "#FA8F5C", color: "#FFF" });
scrollUL(getElem().children("ul")[0], childindex, e.keyCode);
timer = window.setInterval(function () {
if (childindex >= len - 1) {
childindex = 0;
} else {
childindex++;
}
getElem().find("li").css({ backgroundColor: "", color: "#666666" }).eq(childindex).css({ backgroundColor: "#FA8F5C", color: "#FFF" });
scrollUL(getElem().children("ul")[0], childindex, e.keyCode);
}, 850);
}
} else if (e.keyCode == 13) {
if (childindex > -1) {
return false;
}
}
}
function scrollUL(ul, index, keyCode) {
var liTop = $(ul).find('li').eq(index).offset().top;
var liHeight = $(ul).find('li').eq(index).outerHeight();
var ulTop = $(ul).offset().top;
var ulscroTop = $(ul).scrollTop();
var ulborderTop = $(ul).css("border-top-width").replace('px', '');
var ulheight = $(ul).height();
var lioffsetulTop = liTop - ulTop - ulborderTop + ulscroTop;
if ($(ul).hasScrollBarY()) {
if (!(lioffsetulTop > ulscroTop && ulscroTop + ulheight > lioffsetulTop + liHeight)) {
switch (keyCode) {
case 38:
$(ul).scrollTop(lioffsetulTop);
break;
case 40:
$(ul).scrollTop(lioffsetulTop - ulheight + liHeight);
break;
}
}
}
}
function getElem() {
var el = $("#oms_autocomplate");
if (el.length == 0) {
el = $('<ul id="oms_autocomplate" style="display:none;position:absolute;list-style-type:none;margin:0;padding:0;border:1px solid #e12b29;overflow:hidden; background-color:#FFFFFF;z-index:10010;max-height:' + opt.maxHeight + 'px;"><ul style="border:5px solid #f8f1cf;margin:0;padding:0;overflow:auto;position:relative;"></ul></ul>').appendTo(document.body);
}
return el;
}
$('html,body').click(function () {
getElem().css("display", "none");
childindex = -1;
});
return this.each(function () {
$(this).keyup(search_keyup).keydown(search_keydown).bind('selected', opt.select);
});
};
})(jQuery);
;(function ($) {
$.fn.oms_autocomplateV2 = function (options) {
var timer;
var childindex = -1;
var _seft = this;
$(_seft).attr("autocomplete", "off");
var defaults = { url: null, maxHeight: 412, paramTypeSelector: "", clickDown: false, select: function (event, ui) {
this.value = ui.item.value;
if (ui.item.redirecturl != undefined && $.trim(ui.item.redirecturl) != '') {
window.top.location = $.trim(ui.item.redirecturl);
}
}, beforeajaxfunc: function (event) {}
};
var opt = $.extend({}, defaults, options);
function search_keyup(e) {
var the = this;
if (e.keyCode == 38 || e.keyCode == 40) {
window.clearInterval(timer);
}
if (e.keyCode == 13) {
if (childindex > -1) {
getElem().css("display", "none");
$(the).trigger('selected', [{ item: getElem().find('li:eq(' + childindex + ')').data('data')}]);
childindex = -1;
}
} else {
if (the.value != "" || opt.clickDown) {
if(!getElem().filter(":hidden")[0] && (e.keyCode == 38 || e.keyCode == 40))
{
return;
}
$(the).trigger('beforeajaxfunc');
$.get(opt.url, { key: the.value, type: (opt.paramTypeSelector != '' ? $(opt.paramTypeSelector).attr('title') : "") ,time:new Date().toString()}, function (serverdata) {
getElem().children("ul").empty();
var data = eval(serverdata);
$.each(data, function (i) {
var li = $('<li style="padding:2px 0px 2px 5px; height:16px; line-height:16px; cursor:pointer;overflow:hidden;position:relative;">' + this.label + '</li>');
li.data('value', this.value);
li.data('label', this.label);
li.data('data', this);
li.bind('click', function () {
$(the).trigger('selected', [{ item: data[i]}]);
});
getElem().children("ul").append(li).css("overflow", "auto");
});
if (getElem().find("li").length == 0) {
getElem().css("display", "none");
return false;
} else {
childindex = -1;
getElem().find("li").each(function (i) {
$(this).hover(function () {
childindex = i;
getElem().find("li").css({ backgroundColor: "", color: "#666666" });
this.style.backgroundColor = "#FA8F5C";
this.style.color = "#FFF";
}, function () { });
});
}
if (getElem().filter(":hidden")[0]) {
getElem().css({ height: "0px", display: "block" });
}
var tw = opt.inputWidth != null && opt.inputWidth > 0 ? opt.inputWidth : $(the).outerWidth();
var th = opt.inputHeight != null && opt.inputHeight > 0 ? opt.inputHeight : $(the).outerHeight();
var h = Math.min(opt.maxHeight, getElem().find("li").outerHeight() * $("#oms_autocomplate").find("li").length + 10);
var l = parseInt($(the).offset().left) - parseInt($(the).css("marginLeft"));
var tt = parseInt($(the).offset().top) - parseInt($(the).css("marginTop"));
var t = tt + parseInt(th);
var clientH = $(document).height();
getElem().css({ width: tw, left: l }).children("ul").height(h - 10);
if (clientH - t >= h) {
getElem().stop().css({ top: t }).animate({ height: h }, 0);
} else {
if (getElem().height() == 0) {
getElem().stop().css({ top: tt, height: "0px" }).animate({ top: tt - h - 2, height: h }, 0);
} else {
getElem().stop().animate({ top: tt - h - 2, height: h }, 0);
}
}
});
} else {
getElem().css("display", "none");
}
}
}
function search_keydown(e) {
var len = getElem().find("li").length;
if (e.keyCode == 38) {
window.clearInterval(timer);
if (len > 0) {
if (childindex <= 0) {
childindex = len - 1;
} else {
childindex--;
}
getElem().find("li").css({ backgroundColor: "", color: "#666666" }).eq(childindex).css({ backgroundColor: "#FA8F5C", color: "#FFF" });
scrollUL(getElem().children("ul")[0], childindex, e.keyCode);
timer = window.setInterval(function () {
if (childindex <= 0) {
childindex = len - 1;
} else {
childindex--;
}
getElem().find("li").css({ backgroundColor: "", color: "#666666" }).eq(childindex).css({ backgroundColor: "#FA8F5C", color: "#FFF" });
scrollUL(getElem().children("ul")[0], childindex, e.keyCode);
}, 850);
}
} else if (e.keyCode == 40) {
window.clearInterval(timer);
if (len > 0) {
if (childindex >= len - 1) {
childindex = 0;
} else {
childindex++;
}
getElem().find("li").css({ backgroundColor: "", color: "#666666" }).eq(childindex).css({ backgroundColor: "#FA8F5C", color: "#FFF" });
scrollUL(getElem().children("ul")[0], childindex, e.keyCode);
timer = window.setInterval(function () {
if (childindex >= len - 1) {
childindex = 0;
} else {
childindex++;
}
getElem().find("li").css({ backgroundColor: "", color: "#666666" }).eq(childindex).css({ backgroundColor: "#FA8F5C", color: "#FFF" });
scrollUL(getElem().children("ul")[0], childindex, e.keyCode);
}, 850);
}
} else if (e.keyCode == 13) {
if (childindex > -1) {
return false;
}
}
}
function scrollUL(ul, index, keyCode) {
var liTop = $(ul).find('li').eq(index).offset().top;
var liHeight = $(ul).find('li').eq(index).outerHeight();
var ulTop = $(ul).offset().top;
var ulscroTop = $(ul).scrollTop();
var ulborderTop = $(ul).css("border-top-width").replace('px', '');
var ulheight = $(ul).height();
var lioffsetulTop = liTop - ulTop - ulborderTop + ulscroTop;
if ($(ul).hasScrollBarY()) {
if (!(lioffsetulTop > ulscroTop && ulscroTop + ulheight > lioffsetulTop + liHeight)) {
switch (keyCode) {
case 38:
$(ul).scrollTop(lioffsetulTop);
break;
case 40:
$(ul).scrollTop(lioffsetulTop - ulheight + liHeight);
break;
}
}
}
}
function getElem() {
var el = $("#oms_autocomplate");
if (el.length == 0) {
el = $('<div id="oms_autocomplate" style="display:none;position:absolute;list-style-type:none;margin:0;padding:0;border:1px solid #e12b29;overflow:hidden; background-color:#FFFFFF;z-index:10010;max-height:' + opt.maxHeight + 'px;"><ul style="border:5px solid #f8f1cf;margin:0;padding:0;overflow:auto;position:relative;"></ul></div>').appendTo(document.body);
}
return el;
}
$('html,body').click(function () {
getElem().css("display", "none");
childindex = -1;
});
return this.each(function () {
$(this).keydown(search_keydown).keyup(search_keyup).bind('selected', opt.select).bind('beforeajaxfunc', opt.beforeajaxfunc);
if(opt.clickDown){
$(this).click(search_keyup);
}
});
};
})(jQuery);
|
JavaScript
|
function setTab(name, cursel, n) {
for (i = 1; i <= n; i++) {
var menu = document.getElementById(name + i);
var con = document.getElementById("con_" + name + "_" + i);
menu.className = i == cursel ? "hover" : "";
con.style.display = i == cursel ? "block" : "none";
}
}
$(function () {
SoFolderCondition(); //点击收起
SoGetMoreBrand(); //点击更多品牌
SoAlpha();
SoAjaxThumbViews(); //点击Views Tab
SoThumbViewsHover('div.dealerLiMc,div.brandsDealer,div.productPic,div.braAbout1,div.brandsgc');
SoAjaxTab('products');
SoSlider("#infiniteCarousel");
SoAjaxViewTab(".searchBrand");
$("#searchTypeList").find("a").click(function () {
$("#searchTypeList").hide();
})
$(".topSearch1").hover(function () {
$(this).find("ol").show();
}, function () {
$(this).find("ol").hide();
})
//搜索选择
$("#searchTypeList > a").click(function () {
$("#searchTypeDisplay").html($(this).text());
$("#searchTypeList > a").removeClass("Searcha");
$(this).addClass("Searcha");
})
});
function SoFolderCondition() {
$('div.prlifl1>div.prsq>a').toggle(function () {
var o = $(this);
o.parents('div.prlifl1').siblings('div.prlifl2').find('div.prlifl20').slideUp('slow');
o.addClass('on');
o.text("展开");
return false;
}, function () {
var o = $(this);
o.parents('div.prlifl1').siblings('div.prlifl2').find('div.prlifl20').slideDown('slow');
o.removeClass('on');
o.text("收起");
return false;
});
}
function SoGetMoreBrand() {
$('dt.prWhole>a').toggle(function() {
var o = $(this);
o.parent('dt.prWhole').siblings('dt.dt1').find('a.ahide').show();
o.addClass('on');
return false;
}, function() {
var o = $(this);
o.parent('dt.prWhole').siblings('dt.dt1').find('a.ahide').hide();
o.removeClass('on');
return false;
});
}
function SoAlpha() {
$('div.prlifl1>div.pren li').hover(function() {
var o = $(this);
var oa = o.find('a.a1')
var oText = oa.text();
oa.addClass('prena');
$("div.prentc[alphaid='" + oText + "' ]").show();
}, function() {
var o = $(this);
var oa = o.find('a.a1')
var oText = oa.text();
oa.removeClass('prena');
$("div.prentc[alphaid='" + oText + "' ]").hide();
});
$('div.prlifl1>div.pren a').click(function() {
return false;
});
}
function SoAjaxThumbViews() {
SoAjaxViewTab('productView');
}
function SoAjaxViewTab(obj) {
$('.' + obj + '>.hd>ul>li').click(function () {
var o = $(this);
var objPa = o.parent('ul');
var objSib = objPa.find('li');
var index = objSib.index(o);
objSib.not(o).removeClass('on');
var objItemList = objPa.parent('.hd').siblings('.bd');
var itemTarget = objItemList.find('.item').eq(index);
objItemList.find('.item').not(itemTarget).hide();
//如果已经ajax 请求过 //暂时注释掉,静态页面无AJAX 方法 否则IE6 测试报错
// var ajaxid = o.attr('ajaxid');
// if (itemTarget.html().length <= 0) {
// $.ajax({
// type: "GET",
// cache: true,
// url: "/xxx/somepage.aspx?ajax=" + ajaxid,
// error: function () {
// },
// beforeSend: function () {
// },
// success: function (d) {
// }
// });
// }
//存在on属性
if (o.attr('class') == 'on') {
o.removeClass('on');
itemTarget.slideUp('slow');
itemTarget.parent('div.bd').css({ "padding-bottom": "0px" });
}
else {
o.addClass('on');
itemTarget.show();
itemTarget.parent('div.bd').css({ "padding-bottom": "10px" });
}
$(this).find('a').blur();
return false;
});
}
function SoThumbViewsHover(obj) {
var config = {
over: makeShow, //
timeout: 200, //
out: makeHide //
};
if ($('div.productView').get(0) != null) {
$(obj).hoverIntent(config);
}
}
function makeShow() {
var o = $(this);
if (o.find('li.on').size() > 0) {
o.find('div.bd').css({ "padding-bottom": "10px" }).show();
}
else {
o.find('div.bd').css({ "padding-bottom": "0" }).show();
}
o.css({ "padding-bottom": "0" }).find('div.productView').fadeIn("slow");
}
function makeHide() {
var o = $(this);
if (o.find('li.on').size() > 0) {
}
else {
o.find('div.bd').css({ "padding-bottom": "10px" }).hide();
o.css({ "padding-bottom": "35px" }).find('div.productView').hide();
}
}
function SoAjaxTab(obj) {
$('.' + obj + '>.hd>ul>li').click(function () {
var o = $(this);
var objPa = o.parent('ul');
var objSib = objPa.find('li');
var index = objSib.index(o);
objSib.removeClass('on');
o.addClass('on');
var objItemList = objPa.parent('.hd').siblings('.bd');
objItemList.find('.item').hide();
var itemTarget = objItemList.find('.item').eq(index);
var ajaxid = o.attr('ajaxid');
var ajaxGetType = o.attr('name');
//如果已经ajax 请求过
//暂时注释掉,静态页面无AJAX 方法 否则IE6 测试报错
if (itemTarget.html().length <= 0) {
$.ajax({
type: "GET",
cache: true,
url: "../ashx/ajaxCommon.ashx?type=" + ajaxGetType + "&v=" + ajaxid,
error: function () {
},
beforeSend: function () {
itemTarget.html("")
},
success: function (d) {
itemTarget.html(d);
}
});
}
itemTarget.show();
$(this).find('a').blur();
return false;
});
}
function SoSlider(obj) {
var autoscrolling = true;
if ($(obj).get(0) != null) {
$(obj).infiniteCarousel().mouseover(function () {
autoscrolling = false;
}).mouseout(function () {
autoscrolling = true;
});
setInterval(function () {
if (autoscrolling) {
$(obj).trigger('next');
}
}, 5000);
}
}
String.prototype.format = function (args) {
var result = this;
if (arguments.length > 0) {
if (arguments.length == 1 && typeof (args) == "object") {
for (var key in args) {
if (args[key] != undefined) {
var reg = new RegExp("({" + key + "})", "g");
result = result.replace(reg, args[key]);
}
}
}
else {
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] != undefined) {
var reg = new RegExp("({[" + i + "]})", "g");
result = result.replace(reg, arguments[i]);
}
}
}
}
return result;
}
|
JavaScript
|
$(function () {
var baseUrl = document.domain;
var port = document.location.port;
if (port != "") {
port = ":" + port;
}
baseurl = "http://" + baseUrl + port + "/";
$("._droparea").html();
var objid = $("._droparea").attr("id");
var pid = $("._droparea").attr("id") + "_province";
var cid = $("._droparea").attr("id") + "_city";
var did = $("._droparea").attr("id") + "_district";
var tid = $("._droparea").attr("id") + "_town";
var vid = $("._droparea").attr("id") + "_value";
$("._droparea").html("<select id=\"" + pid + "\" name=\"" + pid + "\" ></select>");
$("._droparea").append("<select id=\"" + cid + "\" name=\"" + cid + "\" ></select>");
$("._droparea").append("<select id=\"" + did + "\" name=\"" + did + "\" ></select>");
$("._droparea").append("<select id=\"" + tid + "\" name=\"" + tid + "\" ></select>");
$("._droparea").append("<input type=\"hidden\" id=\"" + vid + "\" name=\"" + vid + "\" value=\"" + $("#" + objid).attr("title") + "\" runat=\"server\" />");
$.ajax({
url: baseurl+"/ajaxtools/ajaxarea.ashx",
data: "type=p&s=" + $("#" + objid).attr("title"),
async: false,
success: function (data) {
$("#" + pid).html(data);
$("#" + tid).hide();
$("#" + cid).html("<option value=\"\">请选择省份</option>");
$("#" + did).html("<option value=\"\">请选择城市</option>");
},
error: function (d, m) {
alert(m);
}
});
if ($("#" + objid).attr("title") != null && $("#" + objid).attr("title") != "" && $("#" + objid).attr("title").length == 6) {
$.ajax({
url: baseurl+"/ajaxtools/ajaxarea.ashx",
data: "type=edit&s=" + $("#" + objid).attr("title"),
dataType: "json",
async: false,
success: function (data) {
$.each(data, function (i) {
if (data[i].type == "city") {
$("#" + cid).append("<option value=\"" + data[i].areacode + "\" selected=\"true\">" + data[i].areaname + "</option>");
}
if (data[i].type == "district") {
$("#" + did).append("<option value=\"" + data[i].areacode + "\" selected=\"true\">" + data[i].areaname + "</option>");
}
if (data[i].type != null && data[i].type == "town") {
$("#" + tid).show();
$("#" + tid).append("<option value=\"" + data[i].areacode + "\" selected=\"true\">" + data[i].areaname + "</option>");
}
else {
$("#" + tid).hide();
}
});
},
error: function (d, m) {
alert(m);
}
});
}
$("#" + pid).live("change", function () {
if ($(this).val() != "" && $(this).val() != "0") {
$.ajax({
url: baseurl + "/ajaxtools/ajaxarea.ashx",
data: "type=c&p=" + $(this).val(),
success: function (data) {
$("#" + cid).hide();
$("#" + cid).show();
$("#" + cid).html("");
$("#" + cid).html(data);
$("#" + did).html("<option value=\"\">请选择城市</option>");
$("#" + tid).hide();
},
error: function (d, m) {
alert(m);
}
});
$("#" + vid).attr("value", $(this).val());
}
})
$("#" + cid).live("change", function () {
if ($(this).val() != "" && $(this).val() != "0") {
$.ajax({
url: baseurl + "/ajaxtools/ajaxarea.ashx",
data: "type=d&c=" + $(this).val(),
success: function (data) {
$("#" + did).html("");
$("#" + did).hide();
$("#" + did).show();
$("#" + did).html(data);
$("#" + tid).hide();
},
error: function (d, m) {
alert(m);
}
});
$("#" + vid).attr("value", $(this).val());
}
})
$("#" + did).live("change", function () {
if ($(this).val() != "" && $(this).val() != "0") {
$.ajax({
url: baseurl + "/ajaxtools/ajaxarea.ashx",
data: "type=t&d=" + $(this).val(),
success: function (data) {
if ($(data).html() != null || $(data).html() != "") {
$("#" + tid).html("");
$("#" + tid).hide();
$("#" + tid).show();
$("#" + tid).html(data);
} else {
$("#" + tid).hide();
}
},
error: function (d, m) {
alert(m);
}
});
$("#" + vid).attr("value", $(this).val());
}
else {
$("#" + tid).hide();
}
});
$("#" + tid).live("change", function () {
if ($(this).val() != "" && $(this).val() != "0") {
$("#" + vid).attr("value", $(this).val());
}
});
})
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.lang({
source : 'Source',
preview : 'Preview',
undo : 'Undo(Ctrl+Z)',
redo : 'Redo(Ctrl+Y)',
cut : 'Cut(Ctrl+X)',
copy : 'Copy(Ctrl+C)',
paste : 'Paste(Ctrl+V)',
plainpaste : 'Paste as plain text',
wordpaste : 'Paste from Word',
selectall : 'Select all',
justifyleft : 'Align left',
justifycenter : 'Align center',
justifyright : 'Align right',
justifyfull : 'Align full',
insertorderedlist : 'Ordered list',
insertunorderedlist : 'Unordered list',
indent : 'Increase indent',
outdent : 'Decrease indent',
subscript : 'Subscript',
superscript : 'Superscript',
formatblock : 'Paragraph format',
fontname : 'Font family',
fontsize : 'Font size',
forecolor : 'Text color',
hilitecolor : 'Highlight color',
bold : 'Bold(Ctrl+B)',
italic : 'Italic(Ctrl+I)',
underline : 'Underline(Ctrl+U)',
strikethrough : 'Strikethrough',
removeformat : 'Remove format',
image : 'Image',
flash : 'Flash',
media : 'Embeded media',
table : 'Table',
tablecell : 'Cell',
hr : 'Insert horizontal line',
emoticons : 'Insert emoticon',
link : 'Link',
unlink : 'Unlink',
fullscreen : 'Toggle fullscreen mode(Esc)',
about : 'About',
print : 'Print',
filemanager : 'File Manager',
code : 'Insert code',
map : 'Google Maps',
lineheight : 'Line height',
clearhtml : 'Clear HTML code',
pagebreak : 'Insert Page Break',
quickformat : 'Quick Format',
insertfile : 'Insert file',
template : 'Insert Template',
anchor : 'Anchor',
yes : 'OK',
no : 'Cancel',
close : 'Close',
editImage : 'Image properties',
deleteImage : 'Delete image',
editFlash : 'Flash properties',
deleteFlash : 'Delete flash',
editMedia : 'Media properties',
deleteMedia : 'Delete media',
editLink : 'Link properties',
deleteLink : 'Unlink',
tableprop : 'Table properties',
tablecellprop : 'Cell properties',
tableinsert : 'Insert table',
tabledelete : 'Delete table',
tablecolinsertleft : 'Insert column left',
tablecolinsertright : 'Insert column right',
tablerowinsertabove : 'Insert row above',
tablerowinsertbelow : 'Insert row below',
tablerowmerge : 'Merge down',
tablecolmerge : 'Merge right',
tablerowsplit : 'Split row',
tablecolsplit : 'Split column',
tablecoldelete : 'Delete column',
tablerowdelete : 'Delete row',
noColor : 'Default',
invalidImg : "Please type valid URL.\nAllowed file extension: jpg,gif,bmp,png",
invalidMedia : "Please type valid URL.\nAllowed file extension: swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb",
invalidWidth : "The width must be number.",
invalidHeight : "The height must be number.",
invalidBorder : "The border must be number.",
invalidUrl : "Please type valid URL.",
invalidRows : 'Invalid rows.',
invalidCols : 'Invalid columns.',
invalidPadding : 'The padding must be number.',
invalidSpacing : 'The spacing must be number.',
invalidJson : 'Invalid JSON string.',
uploadSuccess : 'Upload success.',
cutError : 'Currently not supported by your browser, use keyboard shortcut(Ctrl+X) instead.',
copyError : 'Currently not supported by your browser, use keyboard shortcut(Ctrl+C) instead.',
pasteError : 'Currently not supported by your browser, use keyboard shortcut(Ctrl+V) instead.',
ajaxLoading : 'Loading ...',
uploadLoading : 'Uploading ...',
uploadError : 'Upload Error',
'plainpaste.comment' : 'Use keyboard shortcut(Ctrl+V) to paste the text into the window.',
'wordpaste.comment' : 'Use keyboard shortcut(Ctrl+V) to paste the text into the window.',
'link.url' : 'URL',
'link.linkType' : 'Target',
'link.newWindow' : 'New window',
'link.selfWindow' : 'Same window',
'flash.url' : 'URL',
'flash.width' : 'Width',
'flash.height' : 'Height',
'flash.upload' : 'Upload',
'flash.viewServer' : 'Browse',
'media.url' : 'URL',
'media.width' : 'Width',
'media.height' : 'Height',
'media.autostart' : 'Auto start',
'media.upload' : 'Upload',
'media.viewServer' : 'Browse',
'image.remoteImage' : 'Insert URL',
'image.localImage' : 'Upload',
'image.remoteUrl' : 'URL',
'image.localUrl' : 'File',
'image.size' : 'Size',
'image.width' : 'Width',
'image.height' : 'Height',
'image.resetSize' : 'Reset dimensions',
'image.align' : 'Align',
'image.defaultAlign' : 'Default',
'image.leftAlign' : 'Left',
'image.rightAlign' : 'Right',
'image.imgTitle' : 'Title',
'image.viewServer' : 'Browse',
'filemanager.emptyFolder' : 'Blank',
'filemanager.moveup' : 'Parent folder',
'filemanager.viewType' : 'Display: ',
'filemanager.viewImage' : 'Thumbnails',
'filemanager.listImage' : 'List',
'filemanager.orderType' : 'Sorting: ',
'filemanager.fileName' : 'By name',
'filemanager.fileSize' : 'By size',
'filemanager.fileType' : 'By type',
'insertfile.url' : 'URL',
'insertfile.title' : 'Title',
'insertfile.upload' : 'Upload',
'insertfile.viewServer' : 'Browse',
'table.cells' : 'Cells',
'table.rows' : 'Rows',
'table.cols' : 'Columns',
'table.size' : 'Dimensions',
'table.width' : 'Width',
'table.height' : 'Height',
'table.percent' : '%',
'table.px' : 'px',
'table.space' : 'Space',
'table.padding' : 'Padding',
'table.spacing' : 'Spacing',
'table.align' : 'Align',
'table.textAlign' : 'Horizontal',
'table.verticalAlign' : 'Vertical',
'table.alignDefault' : 'Default',
'table.alignLeft' : 'Left',
'table.alignCenter' : 'Center',
'table.alignRight' : 'Right',
'table.alignTop' : 'Top',
'table.alignMiddle' : 'Middle',
'table.alignBottom' : 'Bottom',
'table.alignBaseline' : 'Baseline',
'table.border' : 'Border',
'table.borderWidth' : 'Width',
'table.borderColor' : 'Color',
'table.backgroundColor' : 'Background',
'map.address' : 'Address: ',
'map.search' : 'Search',
'anchor.name' : 'Anchor name',
'formatblock.formatBlock' : {
h1 : 'Heading 1',
h2 : 'Heading 2',
h3 : 'Heading 3',
h4 : 'Heading 4',
p : 'Normal'
},
'fontname.fontName' : {
'Arial' : 'Arial',
'Arial Black' : 'Arial Black',
'Comic Sans MS' : 'Comic Sans MS',
'Courier New' : 'Courier New',
'Garamond' : 'Garamond',
'Georgia' : 'Georgia',
'Tahoma' : 'Tahoma',
'Times New Roman' : 'Times New Roman',
'Trebuchet MS' : 'Trebuchet MS',
'Verdana' : 'Verdana'
},
'lineheight.lineHeight' : [
{'1' : 'Line height 1'},
{'1.5' : 'Line height 1.5'},
{'2' : 'Line height 2'},
{'2.5' : 'Line height 2.5'},
{'3' : 'Line height 3'}
],
'template.selectTemplate' : 'Template',
'template.replaceContent' : 'Replace current content',
'template.fileList' : {
'1.html' : 'Image and Text',
'2.html' : 'Table',
'3.html' : 'List'
}
}, 'en');
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.lang({
source : '原始碼',
preview : '預覽',
undo : '復原(Ctrl+Z)',
redo : '重複(Ctrl+Y)',
cut : '剪下(Ctrl+X)',
copy : '複製(Ctrl+C)',
paste : '貼上(Ctrl+V)',
plainpaste : '貼為純文字格式',
wordpaste : '自Word貼上',
selectall : '全選(Ctrl+A)',
justifyleft : '靠左對齊',
justifycenter : '置中',
justifyright : '靠右對齊',
justifyfull : '左右對齊',
insertorderedlist : '編號清單',
insertunorderedlist : '項目清單',
indent : '增加縮排',
outdent : '減少縮排',
subscript : '下標',
superscript : '上標',
formatblock : '標題',
fontname : '字體',
fontsize : '文字大小',
forecolor : '文字顏色',
hilitecolor : '背景顏色',
bold : '粗體(Ctrl+B)',
italic : '斜體(Ctrl+I)',
underline : '底線(Ctrl+U)',
strikethrough : '刪除線',
removeformat : '清除格式',
image : '影像',
flash : 'Flash',
media : '多媒體',
table : '表格',
hr : '插入水平線',
emoticons : '插入表情',
link : '超連結',
unlink : '移除超連結',
fullscreen : '最大化',
about : '關於',
print : '列印(Ctrl+P)',
fileManager : '瀏覽伺服器',
code : '插入程式代碼',
map : 'Google地圖',
lineheight : '行距',
clearhtml : '清理HTML代碼',
pagebreak : '插入分頁符號',
quickformat : '快速排版',
insertfile : '插入文件',
template : '插入樣板',
anchor : '錨點',
yes : '確定',
no : '取消',
close : '關閉',
editImage : '影像屬性',
deleteImage : '刪除影像',
editFlash : 'Flash屬性',
deleteFlash : '删除Flash',
editMedia : '多媒體屬性',
deleteMedia : '删除多媒體',
editLink : '超連結屬性',
deleteLink : '移除超連結',
tableprop : '表格屬性',
tablecellprop : '儲存格屬性',
tableinsert : '插入表格',
tabledelete : '刪除表格',
tablecolinsertleft : '向左插入列',
tablecolinsertright : '向右插入列',
tablerowinsertabove : '向上插入欄',
tablerowinsertbelow : '下方插入欄',
tablerowmerge : '向下合併單元格',
tablecolmerge : '向右合併單元格',
tablerowsplit : '分割欄',
tablecolsplit : '分割列',
tablecoldelete : '删除列',
tablerowdelete : '删除欄',
noColor : '自動',
invalidImg : "請輸入有效的URL。\n只允許jpg,gif,bmp,png格式。",
invalidMedia : "請輸入有效的URL。\n只允許swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb格式。",
invalidWidth : "寬度必須是數字。",
invalidHeight : "高度必須是數字。",
invalidBorder : "邊框必須是數字。",
invalidUrl : "請輸入有效的URL。",
invalidRows : '欄數是必須輸入項目,只允許輸入大於0的數字。',
invalidCols : '列數是必須輸入項目,只允許輸入大於0的數字。',
invalidPadding : '內距必須是數字。',
invalidSpacing : '間距必須是數字。',
invalidBorder : '边框必须为数字。',
pleaseInput : "請輸入內容。",
invalidJson : '伺服器發生故障。',
cutError : '您的瀏覽器安全設置不允許使用剪下操作,請使用快捷鍵(Ctrl+X)完成。',
copyError : '您的瀏覽器安全設置不允許使用剪下操作,請使用快捷鍵(Ctrl+C)完成。',
pasteError : '您的瀏覽器安全設置不允許使用剪下操作,請使用快捷鍵(Ctrl+V)完成。',
ajaxLoading : '加載中,請稍候 ...',
uploadLoading : '上傳中,請稍候 ...',
uploadError : '上傳錯誤',
'plainpaste.comment' : '請使用快捷鍵(Ctrl+V)把內容貼到下方區域裡。',
'wordpaste.comment' : '請使用快捷鍵(Ctrl+V)把內容貼到下方區域裡。',
'link.url' : 'URL',
'link.linkType' : '打開類型',
'link.newWindow' : '新窗口',
'link.selfWindow' : '本頁窗口',
'flash.url' : 'URL',
'flash.width' : '寬度',
'flash.height' : '高度',
'flash.upload' : '上傳',
'flash.viewServer' : '瀏覽',
'media.url' : 'URL',
'media.width' : '寬度',
'media.height' : '高度',
'media.autostart' : '自動播放',
'media.upload' : '上傳',
'media.viewServer' : '瀏覽',
'image.remoteImage' : '影像URL',
'image.localImage' : '上傳影像',
'image.remoteUrl' : '影像URL',
'image.localUrl' : '影像URL',
'image.size' : '影像大小',
'image.width' : '寬度',
'image.height' : '高度',
'image.resetSize' : '原始大小',
'image.align' : '對齊方式',
'image.defaultAlign' : '未設定',
'image.leftAlign' : '向左對齊',
'image.rightAlign' : '向右對齊',
'image.imgTitle' : '影像說明',
'image.viewServer' : '瀏覽...',
'filemanager.emptyFolder' : '空文件夾',
'filemanager.moveup' : '至上一級文件夾',
'filemanager.viewType' : '顯示方式:',
'filemanager.viewImage' : '縮略圖',
'filemanager.listImage' : '詳細信息',
'filemanager.orderType' : '排序方式:',
'filemanager.fileName' : '名稱',
'filemanager.fileSize' : '大小',
'filemanager.fileType' : '類型',
'insertfile.url' : 'URL',
'insertfile.title' : '文件說明',
'insertfile.upload' : '上傳',
'insertfile.viewServer' : '瀏覽',
'table.cells' : '儲存格數',
'table.rows' : '欄數',
'table.cols' : '列數',
'table.size' : '表格大小',
'table.width' : '寬度',
'table.height' : '高度',
'table.percent' : '%',
'table.px' : 'px',
'table.space' : '內距間距',
'table.padding' : '內距',
'table.spacing' : '間距',
'table.align' : '對齊方式',
'table.textAlign' : '水平對齊',
'table.verticalAlign' : '垂直對齊',
'table.alignDefault' : '未設定',
'table.alignLeft' : '向左對齊',
'table.alignCenter' : '置中',
'table.alignRight' : '向右對齊',
'table.alignTop' : '靠上',
'table.alignMiddle' : '置中',
'table.alignBottom' : '靠下',
'table.alignBaseline' : '基線',
'table.border' : '表格邊框',
'table.borderWidth' : '邊框',
'table.borderColor' : '顏色',
'table.backgroundColor' : '背景顏色',
'map.address' : '住所: ',
'map.search' : '尋找',
'anchor.name' : '錨點名稱',
'formatblock.formatBlock' : {
h1 : '標題 1',
h2 : '標題 2',
h3 : '標題 3',
h4 : '標題 4',
p : '一般'
},
'fontname.fontName' : {
'MingLiU' : '細明體',
'PMingLiU' : '新細明體',
'DFKai-SB' : '標楷體',
'SimSun' : '宋體',
'NSimSun' : '新宋體',
'FangSong' : '仿宋體',
'Arial' : 'Arial',
'Arial Black' : 'Arial Black',
'Times New Roman' : 'Times New Roman',
'Courier New' : 'Courier New',
'Tahoma' : 'Tahoma',
'Verdana' : 'Verdana'
},
'lineheight.lineHeight' : [
{'1' : '单倍行距'},
{'1.5' : '1.5倍行距'},
{'2' : '2倍行距'},
{'2.5' : '2.5倍行距'},
{'3' : '3倍行距'}
],
'template.selectTemplate' : '可選樣板',
'template.replaceContent' : '取代當前內容',
'template.fileList' : {
'1.html' : '影像和文字',
'2.html' : '表格',
'3.html' : '项目清單'
}
}, 'zh_TW');
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.lang({
source : 'HTML代码',
preview : '预览',
undo : '后退(Ctrl+Z)',
redo : '前进(Ctrl+Y)',
cut : '剪切(Ctrl+X)',
copy : '复制(Ctrl+C)',
paste : '粘贴(Ctrl+V)',
plainpaste : '粘贴为无格式文本',
wordpaste : '从Word粘贴',
selectall : '全选(Ctrl+A)',
justifyleft : '左对齐',
justifycenter : '居中',
justifyright : '右对齐',
justifyfull : '两端对齐',
insertorderedlist : '编号',
insertunorderedlist : '项目符号',
indent : '增加缩进',
outdent : '减少缩进',
subscript : '下标',
superscript : '上标',
formatblock : '段落',
fontname : '字体',
fontsize : '文字大小',
forecolor : '文字颜色',
hilitecolor : '文字背景',
bold : '粗体(Ctrl+B)',
italic : '斜体(Ctrl+I)',
underline : '下划线(Ctrl+U)',
strikethrough : '删除线',
removeformat : '删除格式',
image : '图片',
flash : 'Flash',
media : '视音频',
table : '表格',
tablecell : '单元格',
hr : '插入横线',
emoticons : '插入表情',
link : '超级链接',
unlink : '取消超级链接',
fullscreen : '全屏显示(Esc)',
about : '关于',
print : '打印(Ctrl+P)',
filemanager : '浏览服务器',
code : '插入程序代码',
map : 'Google地图',
lineheight : '行距',
clearhtml : '清理HTML代码',
pagebreak : '插入分页符',
quickformat : '一键排版',
insertfile : '插入文件',
template : '插入模板',
anchor : '锚点',
yes : '确定',
no : '取消',
close : '关闭',
editImage : '图片属性',
deleteImage : '删除图片',
editFlash : 'Flash属性',
deleteFlash : '删除Flash',
editMedia : '视音频属性',
deleteMedia : '删除视音频',
editLink : '超级链接属性',
deleteLink : '取消超级链接',
editAnchor : '锚点属性',
deleteAnchor : '删除锚点',
tableprop : '表格属性',
tablecellprop : '单元格属性',
tableinsert : '插入表格',
tabledelete : '删除表格',
tablecolinsertleft : '左侧插入列',
tablecolinsertright : '右侧插入列',
tablerowinsertabove : '上方插入行',
tablerowinsertbelow : '下方插入行',
tablerowmerge : '向下合并单元格',
tablecolmerge : '向右合并单元格',
tablerowsplit : '拆分行',
tablecolsplit : '拆分列',
tablecoldelete : '删除列',
tablerowdelete : '删除行',
noColor : '无颜色',
invalidImg : "请输入有效的URL地址。\n只允许jpg,gif,bmp,png格式。",
invalidMedia : "请输入有效的URL地址。\n只允许swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb格式。",
invalidWidth : "宽度必须为数字。",
invalidHeight : "高度必须为数字。",
invalidBorder : "边框必须为数字。",
invalidUrl : "请输入有效的URL地址。",
invalidRows : '行数为必选项,只允许输入大于0的数字。',
invalidCols : '列数为必选项,只允许输入大于0的数字。',
invalidPadding : '边距必须为数字。',
invalidSpacing : '间距必须为数字。',
invalidJson : '服务器发生故障。',
uploadSuccess : '上传成功。',
cutError : '您的浏览器安全设置不允许使用剪切操作,请使用快捷键(Ctrl+X)来完成。',
copyError : '您的浏览器安全设置不允许使用复制操作,请使用快捷键(Ctrl+C)来完成。',
pasteError : '您的浏览器安全设置不允许使用粘贴操作,请使用快捷键(Ctrl+V)来完成。',
ajaxLoading : '加载中,请稍候 ...',
uploadLoading : '上传中,请稍候 ...',
uploadError : '上传错误',
'plainpaste.comment' : '请使用快捷键(Ctrl+V)把内容粘贴到下面的方框里。',
'wordpaste.comment' : '请使用快捷键(Ctrl+V)把内容粘贴到下面的方框里。',
'link.url' : 'URL',
'link.linkType' : '打开类型',
'link.newWindow' : '新窗口',
'link.selfWindow' : '当前窗口',
'flash.url' : 'URL',
'flash.width' : '宽度',
'flash.height' : '高度',
'flash.upload' : '上传',
'flash.viewServer' : '浏览',
'media.url' : 'URL',
'media.width' : '宽度',
'media.height' : '高度',
'media.autostart' : '自动播放',
'media.upload' : '上传',
'media.viewServer' : '浏览',
'image.remoteImage' : '远程图片',
'image.localImage' : '本地上传',
'image.remoteUrl' : '图片地址',
'image.localUrl' : '图片地址',
'image.size' : '图片大小',
'image.width' : '宽',
'image.height' : '高',
'image.resetSize' : '重置大小',
'image.align' : '对齐方式',
'image.defaultAlign' : '默认方式',
'image.leftAlign' : '左对齐',
'image.rightAlign' : '右对齐',
'image.imgTitle' : '图片说明',
'image.viewServer' : '浏览...',
'filemanager.emptyFolder' : '空文件夹',
'filemanager.moveup' : '移到上一级文件夹',
'filemanager.viewType' : '显示方式:',
'filemanager.viewImage' : '缩略图',
'filemanager.listImage' : '详细信息',
'filemanager.orderType' : '排序方式:',
'filemanager.fileName' : '名称',
'filemanager.fileSize' : '大小',
'filemanager.fileType' : '类型',
'insertfile.url' : 'URL',
'insertfile.title' : '文件说明',
'insertfile.upload' : '上传',
'insertfile.viewServer' : '浏览',
'table.cells' : '单元格数',
'table.rows' : '行数',
'table.cols' : '列数',
'table.size' : '大小',
'table.width' : '宽度',
'table.height' : '高度',
'table.percent' : '%',
'table.px' : 'px',
'table.space' : '边距间距',
'table.padding' : '边距',
'table.spacing' : '间距',
'table.align' : '对齐方式',
'table.textAlign' : '水平对齐',
'table.verticalAlign' : '垂直对齐',
'table.alignDefault' : '默认',
'table.alignLeft' : '左对齐',
'table.alignCenter' : '居中',
'table.alignRight' : '右对齐',
'table.alignTop' : '顶部',
'table.alignMiddle' : '中部',
'table.alignBottom' : '底部',
'table.alignBaseline' : '基线',
'table.border' : '边框',
'table.borderWidth' : '边框',
'table.borderColor' : '颜色',
'table.backgroundColor' : '背景颜色',
'map.address' : '地址: ',
'map.search' : '搜索',
'anchor.name' : '锚点名称',
'formatblock.formatBlock' : {
h1 : '标题 1',
h2 : '标题 2',
h3 : '标题 3',
h4 : '标题 4',
p : '正 文'
},
'fontname.fontName' : {
'SimSun' : '宋体',
'NSimSun' : '新宋体',
'FangSong_GB2312' : '仿宋_GB2312',
'KaiTi_GB2312' : '楷体_GB2312',
'SimHei' : '黑体',
'Microsoft YaHei' : '微软雅黑',
'Arial' : 'Arial',
'Arial Black' : 'Arial Black',
'Times New Roman' : 'Times New Roman',
'Courier New' : 'Courier New',
'Tahoma' : 'Tahoma',
'Verdana' : 'Verdana'
},
'lineheight.lineHeight' : [
{'1' : '单倍行距'},
{'1.5' : '1.5倍行距'},
{'2' : '2倍行距'},
{'2.5' : '2.5倍行距'},
{'3' : '3倍行距'}
],
'template.selectTemplate' : '可选模板',
'template.replaceContent' : '替换当前内容',
'template.fileList' : {
'1.html' : '图片和文字',
'2.html' : '表格',
'3.html' : '项目编号'
}
}, 'zh_CN');
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
* Arabic Translation By daif alotaibi (http://daif.net/)
*******************************************************************************/
KindEditor.lang({
source : 'عرض المصدر',
preview : 'معاينة الصفحة',
undo : 'تراجع(Ctrl+Z)',
redo : 'إعادة التراجع(Ctrl+Y)',
cut : 'قص(Ctrl+X)',
copy : 'نسخ(Ctrl+C)',
paste : 'لصق(Ctrl+V)',
plainpaste : 'لصق كنص عادي',
wordpaste : 'لصق من مايكروسفت ورد',
selectall : 'تحديد الكل',
justifyleft : 'محاذاه لليسار',
justifycenter : 'محاذاه للوسط',
justifyright : 'محاذاه لليمين',
justifyfull : 'محاذاه تلقائية',
insertorderedlist : 'قائمة مرقمه',
insertunorderedlist : 'قائمة نقطية',
indent : 'إزاحه النص',
outdent : 'إلغاء الازاحة',
subscript : 'أسفل النص',
superscript : 'أعلى النص',
formatblock : 'Paragraph format',
fontname : 'نوع الخط',
fontsize : 'حجم الخط',
forecolor : 'لون النص',
hilitecolor : 'لون خلفية النص',
bold : 'عريض(Ctrl+B)',
italic : 'مائل(Ctrl+I)',
underline : 'خط تحت النص(Ctrl+U)',
strikethrough : 'خط على النص',
removeformat : 'إزالة التنسيق',
image : 'إدراج صورة',
flash : 'إدراج فلاش',
media : 'إدراج وسائط متعددة',
table : 'إدراج جدول',
tablecell : 'خلية',
hr : 'إدراج خط أفقي',
emoticons : 'إدراج وجه ضاحك',
link : 'رابط',
unlink : 'إزالة الرابط',
fullscreen : 'محرر ملئ الشاشة(Esc)',
about : 'حول',
print : 'طباعة',
filemanager : 'مدير الملفات',
code : 'إدراج نص برمجي',
map : 'خرائط قووقل',
lineheight : 'إرتفاع السطر',
clearhtml : 'مسح كود HTML',
pagebreak : 'إدراج فاصل صفحات',
quickformat : 'تنسيق سريع',
insertfile : 'إدراج ملف',
template : 'إدراج قالب',
anchor : 'رابط',
yes : 'موافق',
no : 'إلغاء',
close : 'إغلاق',
editImage : 'خصائص الصورة',
deleteImage : 'حذفالصورة',
editFlash : 'خصائص الفلاش',
deleteFlash : 'حذف الفلاش',
editMedia : 'خصائص الوسائط',
deleteMedia : 'حذف الوسائط',
editLink : 'خصائص الرابط',
deleteLink : 'إزالة الرابط',
tableprop : 'خصائص الجدول',
tablecellprop : 'خصائص الخلية',
tableinsert : 'إدراج جدول',
tabledelete : 'حذف جدول',
tablecolinsertleft : 'إدراج عمود لليسار',
tablecolinsertright : 'إدراج عمود لليسار',
tablerowinsertabove : 'إدراج صف للأعلى',
tablerowinsertbelow : 'إدراج صف للأسفل',
tablerowmerge : 'دمج للأسفل',
tablecolmerge : 'دمج لليمين',
tablerowsplit : 'تقسم الصف',
tablecolsplit : 'تقسيم العمود',
tablecoldelete : 'حذف العمود',
tablerowdelete : 'حذف الصف',
noColor : 'إفتراضي',
invalidImg : "الرجاء إدخال رابط صحيح.\nالملفات المسموح بها: jpg,gif,bmp,png",
invalidMedia : "الرجاء إدخال رابط صحيح.\nالملفات المسموح بها: swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb",
invalidWidth : "العرض يجب أن يكون رقم.",
invalidHeight : "الإرتفاع يجب أن يكون رقم.",
invalidBorder : "عرض الحد يجب أن يكون رقم.",
invalidUrl : "الرجاء إدخال رابط حيح.",
invalidRows : 'صفوف غير صحيح.',
invalidCols : 'أعمدة غير صحيحة.',
invalidPadding : 'The padding must be number.',
invalidSpacing : 'The spacing must be number.',
invalidJson : 'Invalid JSON string.',
uploadSuccess : 'تم رفع الملف بنجاح.',
cutError : 'حاليا غير مدعومة من المتصفح, إستخدم إختصار لوحة المفاتيح (Ctrl+X).',
copyError : 'حاليا غير مدعومة من المتصفح, إستخدم إختصار لوحة المفاتيح (Ctrl+C).',
pasteError : 'حاليا غير مدعومة من المتصفح, إستخدم إختصار لوحة المفاتيح (Ctrl+V).',
ajaxLoading : 'Loading ...',
uploadLoading : 'Uploading ...',
uploadError : 'Upload Error',
'plainpaste.comment' : 'إستخدم إختصار لوحة المفاتيح (Ctrl+V) للصق داخل النافذة.',
'wordpaste.comment' : 'إستخدم إختصار لوحة المفاتيح (Ctrl+V) للصق داخل النافذة.',
'link.url' : 'الرابط',
'link.linkType' : 'الهدف',
'link.newWindow' : 'نافذة جديدة',
'link.selfWindow' : 'نفس النافذة',
'flash.url' : 'الرابط',
'flash.width' : 'العرض',
'flash.height' : 'الإرتفاع',
'flash.upload' : 'رفع',
'flash.viewServer' : 'أستعراض',
'media.url' : 'الرابط',
'media.width' : 'العرض',
'media.height' : 'الإرتفاع',
'media.autostart' : 'تشغيل تلقائي',
'media.upload' : 'رفع',
'media.viewServer' : 'أستعراض',
'image.remoteImage' : 'إدراج الرابط',
'image.localImage' : 'رفع',
'image.remoteUrl' : 'الرابط',
'image.localUrl' : 'الملف',
'image.size' : 'الحجم',
'image.width' : 'العرض',
'image.height' : 'الإرتفاع',
'image.resetSize' : 'إستعادة الأبعاد',
'image.align' : 'محاذاة',
'image.defaultAlign' : 'الإفتراضي',
'image.leftAlign' : 'اليسار',
'image.rightAlign' : 'اليمين',
'image.imgTitle' : 'العنوان',
'image.viewServer' : 'أستعراض',
'filemanager.emptyFolder' : 'فارغ',
'filemanager.moveup' : 'المجلد الأب',
'filemanager.viewType' : 'العرض: ',
'filemanager.viewImage' : 'مصغرات',
'filemanager.listImage' : 'قائمة',
'filemanager.orderType' : 'الترتيب: ',
'filemanager.fileName' : 'بالإسم',
'filemanager.fileSize' : 'بالحجم',
'filemanager.fileType' : 'بالنوع',
'insertfile.url' : 'الرابط',
'insertfile.title' : 'العنوان',
'insertfile.upload' : 'رفع',
'insertfile.viewServer' : 'أستعراض',
'table.cells' : 'خلايا',
'table.rows' : 'صفوف',
'table.cols' : 'أعمدة',
'table.size' : 'الأبعاد',
'table.width' : 'العرض',
'table.height' : 'الإرتفاع',
'table.percent' : '%',
'table.px' : 'px',
'table.space' : 'الخارج',
'table.padding' : 'الداخل',
'table.spacing' : 'الفراغات',
'table.align' : 'محاذاه',
'table.textAlign' : 'افقى',
'table.verticalAlign' : 'رأسي',
'table.alignDefault' : 'إفتراضي',
'table.alignLeft' : 'يسار',
'table.alignCenter' : 'وسط',
'table.alignRight' : 'يمين',
'table.alignTop' : 'أعلى',
'table.alignMiddle' : 'منتصف',
'table.alignBottom' : 'أسفل',
'table.alignBaseline' : 'Baseline',
'table.border' : 'الحدود',
'table.borderWidth' : 'العرض',
'table.borderColor' : 'اللون',
'table.backgroundColor' : 'الخلفية',
'map.address' : 'العنوان: ',
'map.search' : 'بحث',
'anchor.name' : 'إسم الرابط',
'formatblock.formatBlock' : {
h1 : 'عنوان 1',
h2 : 'عنوان 2',
h3 : 'عنوان 3',
h4 : 'عنوان 4',
p : 'عادي'
},
'fontname.fontName' : {
'Arial' : 'Arial',
'Arial Black' : 'Arial Black',
'Comic Sans MS' : 'Comic Sans MS',
'Courier New' : 'Courier New',
'Garamond' : 'Garamond',
'Georgia' : 'Georgia',
'Tahoma' : 'Tahoma',
'Times New Roman' : 'Times New Roman',
'Trebuchet MS' : 'Trebuchet MS',
'Verdana' : 'Verdana'
},
'lineheight.lineHeight' : [
{'1' : 'إرتفاع السطر 1'},
{'1.5' : 'إرتفاع السطر 1.5'},
{'2' : 'إرتفاع السطر 2'},
{'2.5' : 'إرتفاع السطر 2.5'},
{'3' : 'إرتفاع السطر 3'}
],
'template.selectTemplate' : 'قالب',
'template.replaceContent' : 'إستبدال المحتوى الحالي',
'template.fileList' : {
'1.html' : 'صورة ونص',
'2.html' : 'جدول',
'3.html' : 'قائمة'
}
}, 'ar');
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2012 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @website http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
* @version 4.0.5 (2012-01-15)
*******************************************************************************/
(function (window, undefined) {
if (window.KindEditor) {
return;
}
if (!window.console) {
window.console = {};
}
if (!console.log) {
console.log = function () {};
}
var _VERSION = '4.0.5 (2012-01-15)',
_ua = navigator.userAgent.toLowerCase(),
_IE = _ua.indexOf('msie') > -1 && _ua.indexOf('opera') == -1,
_GECKO = _ua.indexOf('gecko') > -1 && _ua.indexOf('khtml') == -1,
_WEBKIT = _ua.indexOf('applewebkit') > -1,
_OPERA = _ua.indexOf('opera') > -1,
_MOBILE = _ua.indexOf('mobile') > -1,
_IOS = /ipad|iphone|ipod/.test(_ua),
_QUIRKS = document.compatMode != 'CSS1Compat',
_matches = /(?:msie|firefox|webkit|opera)[\/:\s](\d+)/.exec(_ua),
_V = _matches ? _matches[1] : '0',
_TIME = new Date().getTime();
function _isArray(val) {
if (!val) {
return false;
}
return Object.prototype.toString.call(val) === '[object Array]';
}
function _isFunction(val) {
if (!val) {
return false;
}
return Object.prototype.toString.call(val) === '[object Function]';
}
function _inArray(val, arr) {
for (var i = 0, len = arr.length; i < len; i++) {
if (val === arr[i]) {
return i;
}
}
return -1;
}
function _each(obj, fn) {
if (_isArray(obj)) {
for (var i = 0, len = obj.length; i < len; i++) {
if (fn.call(obj[i], i, obj[i]) === false) {
break;
}
}
} else {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (fn.call(obj[key], key, obj[key]) === false) {
break;
}
}
}
}
}
function _trim(str) {
return str.replace(/(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, '');
}
function _inString(val, str, delimiter) {
delimiter = delimiter === undefined ? ',' : delimiter;
return (delimiter + str + delimiter).indexOf(delimiter + val + delimiter) >= 0;
}
function _addUnit(val, unit) {
unit = unit || 'px';
return val && /^\d+$/.test(val) ? val + 'px' : val;
}
function _removeUnit(val) {
var match;
return val && (match = /(\d+)/.exec(val)) ? parseInt(match[1], 10) : 0;
}
function _escape(val) {
return val.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
function _unescape(val) {
return val.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/&/g, '&');
}
function _toCamel(str) {
var arr = str.split('-');
str = '';
_each(arr, function(key, val) {
str += (key > 0) ? val.charAt(0).toUpperCase() + val.substr(1) : val;
});
return str;
}
function _toHex(val) {
function hex(d) {
var s = parseInt(d, 10).toString(16).toUpperCase();
return s.length > 1 ? s : '0' + s;
}
return val.replace(/rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/ig,
function($0, $1, $2, $3) {
return '#' + hex($1) + hex($2) + hex($3);
}
);
}
function _toMap(val, delimiter) {
delimiter = delimiter === undefined ? ',' : delimiter;
var map = {}, arr = _isArray(val) ? val : val.split(delimiter), match;
_each(arr, function(key, val) {
if ((match = /^(\d+)\.\.(\d+)$/.exec(val))) {
for (var i = parseInt(match[1], 10); i <= parseInt(match[2], 10); i++) {
map[i.toString()] = true;
}
} else {
map[val] = true;
}
});
return map;
}
function _toArray(obj, offset) {
return Array.prototype.slice.call(obj, offset || 0);
}
function _undef(val, defaultVal) {
return val === undefined ? defaultVal : val;
}
function _invalidUrl(url) {
return !url || /[<>"]/.test(url);
}
function _addParam(url, param) {
return url.indexOf('?') >= 0 ? url + '&' + param : url + '?' + param;
}
function _extend(child, parent, proto) {
if (!proto) {
proto = parent;
parent = null;
}
var childProto;
if (parent) {
var fn = function () {};
fn.prototype = parent.prototype;
childProto = new fn();
_each(proto, function(key, val) {
childProto[key] = val;
});
} else {
childProto = proto;
}
childProto.constructor = child;
child.prototype = childProto;
child.parent = parent ? parent.prototype : null;
}
function _json(text) {
var match;
if ((match = /\{[\s\S]*\}|\[[\s\S]*\]/.exec(text))) {
text = match[0];
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
return eval('(' + text + ')');
}
throw 'JSON parse error';
}
var _round = Math.round;
var K = {
DEBUG : false,
VERSION : _VERSION,
IE : _IE,
GECKO : _GECKO,
WEBKIT : _WEBKIT,
OPERA : _OPERA,
V : _V,
TIME : _TIME,
each : _each,
isArray : _isArray,
isFunction : _isFunction,
inArray : _inArray,
inString : _inString,
trim : _trim,
addUnit : _addUnit,
removeUnit : _removeUnit,
escape : _escape,
unescape : _unescape,
toCamel : _toCamel,
toHex : _toHex,
toMap : _toMap,
toArray : _toArray,
undef : _undef,
invalidUrl : _invalidUrl,
addParam : _addParam,
extend : _extend,
json : _json
};
var _INLINE_TAG_MAP = _toMap('a,abbr,acronym,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,img,input,ins,kbd,label,map,q,s,samp,select,small,span,strike,strong,sub,sup,textarea,tt,u,var'),
_BLOCK_TAG_MAP = _toMap('address,applet,blockquote,body,center,dd,dir,div,dl,dt,fieldset,form,frameset,h1,h2,h3,h4,h5,h6,head,hr,html,iframe,ins,isindex,li,map,menu,meta,noframes,noscript,object,ol,p,pre,script,style,table,tbody,td,tfoot,th,thead,title,tr,ul'),
_SINGLE_TAG_MAP = _toMap('area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed'),
_STYLE_TAG_MAP = _toMap('b,basefont,big,del,em,font,i,s,small,span,strike,strong,sub,sup,u'),
_CONTROL_TAG_MAP = _toMap('img,table,input,textarea,button'),
_PRE_TAG_MAP = _toMap('pre,style,script'),
_NOSPLIT_TAG_MAP = _toMap('html,head,body,td,tr,table,ol,ul,li'),
_AUTOCLOSE_TAG_MAP = _toMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr'),
_FILL_ATTR_MAP = _toMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'),
_VALUE_TAG_MAP = _toMap('input,button,textarea,select');
function _getBasePath() {
var els = document.getElementsByTagName('script'), src;
for (var i = 0, len = els.length; i < len; i++) {
src = els[i].src || '';
if (/kindeditor[\w\-\.]*\.js/.test(src)) {
return src.substring(0, src.lastIndexOf('/') + 1);
}
}
return '';
}
K.basePath = _getBasePath();
K.options = {
designMode : true,
fullscreenMode : false,
filterMode : false,
wellFormatMode : true,
shadowMode : true,
loadStyleMode : true,
basePath : K.basePath,
themesPath : K.basePath + 'themes/',
langPath : K.basePath + 'lang/',
pluginsPath : K.basePath + 'plugins/',
themeType : 'default',
langType : 'zh_CN',
urlType : '',
newlineTag : 'p',
resizeType : 2,
syncType : 'form',
pasteType : 2,
dialogAlignType : 'page',
useContextmenu : true,
bodyClass : 'ke-content',
indentChar : '\t',
cssPath : '',
cssData : '',
minWidth : 650,
minHeight : 100,
minChangeSize : 5,
items : [
'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'cut', 'copy', 'paste',
'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image',
'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'map', 'code', 'pagebreak', 'anchor', 'link', 'unlink', '|', 'about'
],
noDisableItems : ['source', 'fullscreen'],
colorTable : [
['#E53333', '#E56600', '#FF9900', '#64451D', '#DFC5A4', '#FFE500'],
['#009900', '#006600', '#99BB00', '#B8D100', '#60D978', '#00D5FF'],
['#337FE5', '#003399', '#4C33E5', '#9933E5', '#CC33E5', '#EE33EE'],
['#FFFFFF', '#CCCCCC', '#999999', '#666666', '#333333', '#000000']
],
fontSizeTable : ['9px', '10px', '12px', '14px', '16px', '18px', '24px', '32px'],
htmlTags : {
font : ['color', 'size', 'face', '.background-color'],
span : [
'.color', '.background-color', '.font-size', '.font-family', '.background',
'.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.line-height'
],
div : [
'align', '.border', '.margin', '.padding', '.text-align', '.color',
'.background-color', '.font-size', '.font-family', '.font-weight', '.background',
'.font-style', '.text-decoration', '.vertical-align', '.margin-left'
],
table: [
'border', 'cellspacing', 'cellpadding', 'width', 'height', 'align', 'bordercolor',
'.padding', '.margin', '.border', 'bgcolor', '.text-align', '.color', '.background-color',
'.font-size', '.font-family', '.font-weight', '.font-style', '.text-decoration', '.background',
'.width', '.height', '.border-collapse'
],
'td,th': [
'align', 'valign', 'width', 'height', 'colspan', 'rowspan', 'bgcolor',
'.text-align', '.color', '.background-color', '.font-size', '.font-family', '.font-weight',
'.font-style', '.text-decoration', '.vertical-align', '.background', '.border'
],
a : ['href', 'target', 'name'],
embed : ['src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess'],
img : ['src', 'width', 'height', 'border', 'alt', 'title', 'align', '.width', '.height', '.border'],
'p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6' : [
'align', '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.background',
'.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.text-indent', '.margin-left'
],
pre : ['class'],
hr : ['class', '.page-break-after'],
'br,tbody,tr,strong,b,sub,sup,em,i,u,strike,s,del' : []
},
layout : '<div class="container"><div class="toolbar"></div><div class="edit"></div><div class="statusbar"></div></div>'
};
var _useCapture = false;
var _INPUT_KEY_MAP = _toMap('8,9,13,32,46,48..57,59,61,65..90,106,109..111,188,190..192,219..222');
var _CURSORMOVE_KEY_MAP = _toMap('33..40');
var _CHANGE_KEY_MAP = {};
_each(_INPUT_KEY_MAP, function(key, val) {
_CHANGE_KEY_MAP[key] = val;
});
_each(_CURSORMOVE_KEY_MAP, function(key, val) {
_CHANGE_KEY_MAP[key] = val;
});
function _bindEvent(el, type, fn) {
if (el.addEventListener){
el.addEventListener(type, fn, _useCapture);
} else if (el.attachEvent){
el.attachEvent('on' + type, fn);
}
}
function _unbindEvent(el, type, fn) {
if (el.removeEventListener){
el.removeEventListener(type, fn, _useCapture);
} else if (el.detachEvent){
el.detachEvent('on' + type, fn);
}
}
var _EVENT_PROPS = ('altKey,attrChange,attrName,bubbles,button,cancelable,charCode,clientX,clientY,ctrlKey,currentTarget,' +
'data,detail,eventPhase,fromElement,handler,keyCode,metaKey,newValue,offsetX,offsetY,originalTarget,pageX,' +
'pageY,prevValue,relatedNode,relatedTarget,screenX,screenY,shiftKey,srcElement,target,toElement,view,wheelDelta,which').split(',');
function KEvent(el, event) {
this.init(el, event);
}
_extend(KEvent, {
init : function(el, event) {
var self = this, doc = el.ownerDocument || el.document || el;
self.event = event;
_each(_EVENT_PROPS, function(key, val) {
self[val] = event[val];
});
if (!self.target) {
self.target = self.srcElement || doc;
}
if (self.target.nodeType === 3) {
self.target = self.target.parentNode;
}
if (!self.relatedTarget && self.fromElement) {
self.relatedTarget = self.fromElement === self.target ? self.toElement : self.fromElement;
}
if (self.pageX == null && self.clientX != null) {
var d = doc.documentElement, body = doc.body;
self.pageX = self.clientX + (d && d.scrollLeft || body && body.scrollLeft || 0) - (d && d.clientLeft || body && body.clientLeft || 0);
self.pageY = self.clientY + (d && d.scrollTop || body && body.scrollTop || 0) - (d && d.clientTop || body && body.clientTop || 0);
}
if (!self.which && ((self.charCode || self.charCode === 0) ? self.charCode : self.keyCode)) {
self.which = self.charCode || self.keyCode;
}
if (!self.metaKey && self.ctrlKey) {
self.metaKey = self.ctrlKey;
}
if (!self.which && self.button !== undefined) {
self.which = (self.button & 1 ? 1 : (self.button & 2 ? 3 : (self.button & 4 ? 2 : 0)));
}
switch (self.which) {
case 186 :
self.which = 59;
break;
case 187 :
case 107 :
case 43 :
self.which = 61;
break;
case 189 :
case 45 :
self.which = 109;
break;
case 42 :
self.which = 106;
break;
case 47 :
self.which = 111;
break;
case 78 :
self.which = 110;
break;
}
if (self.which >= 96 && self.which <= 105) {
self.which -= 48;
}
},
preventDefault : function() {
var ev = this.event;
if (ev.preventDefault) {
ev.preventDefault();
}
ev.returnValue = false;
},
stopPropagation : function() {
var ev = this.event;
if (ev.stopPropagation) {
ev.stopPropagation();
}
ev.cancelBubble = true;
},
stop : function() {
this.preventDefault();
this.stopPropagation();
}
});
var _eventExpendo = 'kindeditor_' + _TIME, _eventId = 0, _eventData = {};
function _getId(el) {
return el[_eventExpendo] || null;
}
function _setId(el) {
el[_eventExpendo] = ++_eventId;
return _eventId;
}
function _removeId(el) {
try {
delete el[_eventExpendo];
} catch(e) {
if (el.removeAttribute) {
el.removeAttribute(_eventExpendo);
}
}
}
function _bind(el, type, fn) {
if (type.indexOf(',') >= 0) {
_each(type.split(','), function() {
_bind(el, this, fn);
});
return;
}
var id = _getId(el);
if (!id) {
id = _setId(el);
}
if (_eventData[id] === undefined) {
_eventData[id] = {};
}
var events = _eventData[id][type];
if (events && events.length > 0) {
_unbindEvent(el, type, events[0]);
} else {
_eventData[id][type] = [];
_eventData[id].el = el;
}
events = _eventData[id][type];
if (events.length === 0) {
events[0] = function(e) {
var kevent = e ? new KEvent(el, e) : undefined;
_each(events, function(i, event) {
if (i > 0 && event) {
event.call(el, kevent);
}
});
};
}
if (_inArray(fn, events) < 0) {
events.push(fn);
}
_bindEvent(el, type, events[0]);
}
function _unbind(el, type, fn) {
if (type && type.indexOf(',') >= 0) {
_each(type.split(','), function() {
_unbind(el, this, fn);
});
return;
}
var id = _getId(el);
if (!id) {
return;
}
if (type === undefined) {
if (id in _eventData) {
_each(_eventData[id], function(key, events) {
if (key != 'el' && events.length > 0) {
_unbindEvent(el, key, events[0]);
}
});
delete _eventData[id];
_removeId(el);
}
return;
}
if (!_eventData[id]) {
return;
}
var events = _eventData[id][type];
if (events && events.length > 0) {
if (fn === undefined) {
_unbindEvent(el, type, events[0]);
delete _eventData[id][type];
} else {
_each(events, function(i, event) {
if (i > 0 && event === fn) {
events.splice(i, 1);
}
});
if (events.length == 1) {
_unbindEvent(el, type, events[0]);
delete _eventData[id][type];
}
}
var count = 0;
_each(_eventData[id], function() {
count++;
});
if (count < 2) {
delete _eventData[id];
_removeId(el);
}
}
}
function _fire(el, type) {
if (type.indexOf(',') >= 0) {
_each(type.split(','), function() {
_fire(el, this);
});
return;
}
var id = _getId(el);
if (!id) {
return;
}
var events = _eventData[id][type];
if (_eventData[id] && events && events.length > 0) {
events[0]();
}
}
function _ctrl(el, key, fn) {
var self = this;
key = /^\d{2,}$/.test(key) ? key : key.toUpperCase().charCodeAt(0);
_bind(el, 'keydown', function(e) {
if (e.ctrlKey && e.which == key && !e.shiftKey && !e.altKey) {
fn.call(el);
e.stop();
}
});
}
function _ready(fn) {
var loaded = false;
function readyFunc() {
if (!loaded) {
loaded = true;
fn(KindEditor);
}
}
function ieReadyFunc() {
if (!loaded) {
try {
document.documentElement.doScroll('left');
} catch(e) {
setTimeout(ieReadyFunc, 100);
return;
}
readyFunc();
}
}
function ieReadyStateFunc() {
if (document.readyState === 'complete') {
readyFunc();
}
}
if (document.addEventListener) {
_bind(document, 'DOMContentLoaded', readyFunc);
} else if (document.attachEvent) {
_bind(document, 'readystatechange', ieReadyStateFunc);
if (document.documentElement.doScroll && window.frameElement === undefined) {
ieReadyFunc();
}
}
_bind(window, 'load', readyFunc);
}
if (_IE) {
window.attachEvent('onunload', function() {
_each(_eventData, function(key, events) {
if (events.el) {
_unbind(events.el);
}
});
});
}
K.ctrl = _ctrl;
K.ready = _ready;
function _getCssList(css) {
var list = {},
reg = /\s*([\w\-]+)\s*:([^;]*)(;|$)/g,
match;
while ((match = reg.exec(css))) {
var key = _trim(match[1].toLowerCase()),
val = _trim(_toHex(match[2]));
list[key] = val;
}
return list;
}
function _getAttrList(tag) {
var list = {},
reg = /\s+(?:([\w\-:]+)|(?:([\w\-:]+)=([^\s"'<>]+))|(?:([\w\-:"]+)="([^"]*)")|(?:([\w\-:"]+)='([^']*)'))(?=(?:\s|\/|>)+)/g,
match;
while ((match = reg.exec(tag))) {
var key = (match[1] || match[2] || match[4] || match[6]).toLowerCase(),
val = (match[2] ? match[3] : (match[4] ? match[5] : match[7])) || '';
list[key] = val;
}
return list;
}
function _addClassToTag(tag, className) {
if (/\s+class\s*=/.test(tag)) {
tag = tag.replace(/(\s+class=["']?)([^"']*)(["']?[\s>])/, function($0, $1, $2, $3) {
if ((' ' + $2 + ' ').indexOf(' ' + className + ' ') < 0) {
return $2 === '' ? $1 + className + $3 : $1 + $2 + ' ' + className + $3;
} else {
return $0;
}
});
} else {
tag = tag.substr(0, tag.length - 1) + ' class="' + className + '">';
}
return tag;
}
function _formatCss(css) {
var str = '';
_each(_getCssList(css), function(key, val) {
str += key + ':' + val + ';';
});
return str;
}
function _formatUrl(url, mode, host, pathname) {
mode = _undef(mode, '').toLowerCase();
if (_inArray(mode, ['absolute', 'relative', 'domain']) < 0) {
return url;
}
host = host || location.protocol + '//' + location.host;
if (pathname === undefined) {
var m = location.pathname.match(/^(\/.*)\//);
pathname = m ? m[1] : '';
}
var match;
if ((match = /^(\w+:\/\/[^\/]*)/.exec(url))) {
if (match[1] !== host) {
return url;
}
} else if (/^\w+:/.test(url)) {
return url;
}
function getRealPath(path) {
var parts = path.split('/'), paths = [];
for (var i = 0, len = parts.length; i < len; i++) {
var part = parts[i];
if (part == '..') {
if (paths.length > 0) {
paths.pop();
}
} else if (part !== '' && part != '.') {
paths.push(part);
}
}
return '/' + paths.join('/');
}
if (/^\//.test(url)) {
url = host + getRealPath(url.substr(1));
} else if (!/^\w+:\/\//.test(url)) {
url = host + getRealPath(pathname + '/' + url);
}
function getRelativePath(path, depth) {
if (url.substr(0, path.length) === path) {
var arr = [];
for (var i = 0; i < depth; i++) {
arr.push('..');
}
var prefix = '.';
if (arr.length > 0) {
prefix += '/' + arr.join('/');
}
if (pathname == '/') {
prefix += '/';
}
return prefix + url.substr(path.length);
} else {
if ((match = /^(.*)\//.exec(path))) {
return getRelativePath(match[1], ++depth);
}
}
}
if (mode === 'relative') {
url = getRelativePath(host + pathname, 0).substr(2);
} else if (mode === 'absolute') {
if (url.substr(0, host.length) === host) {
url = url.substr(host.length);
}
}
return url;
}
function _formatHtml(html, htmlTags, urlType, wellFormatted, indentChar) {
urlType = urlType || '';
wellFormatted = _undef(wellFormatted, false);
indentChar = _undef(indentChar, '\t');
var fontSizeList = 'xx-small,x-small,small,medium,large,x-large,xx-large'.split(',');
html = html.replace(/(<(?:pre|pre\s[^>]*)>)([\s\S]*?)(<\/pre>)/ig, function($0, $1, $2, $3) {
return $1 + $2.replace(/<(?:br|br\s[^>]*)>/ig, '\n') + $3;
});
html = html.replace(/<(?:br|br\s[^>]*)\s*\/?>\s*<\/p>/ig, '</p>');
html = html.replace(/(<(?:p|p\s[^>]*)>)\s*(<\/p>)/ig, '$1<br />$2');
html = html.replace(/\u200B/g, '');
var htmlTagMap = {};
if (htmlTags) {
_each(htmlTags, function(key, val) {
var arr = key.split(',');
for (var i = 0, len = arr.length; i < len; i++) {
htmlTagMap[arr[i]] = _toMap(val);
}
});
if (!htmlTagMap.script) {
html = html.replace(/(<(?:script|script\s[^>]*)>)([\s\S]*?)(<\/script>)/ig, '');
}
if (!htmlTagMap.style) {
html = html.replace(/(<(?:style|style\s[^>]*)>)([\s\S]*?)(<\/style>)/ig, '');
}
}
var re = /(\s*)<(\/)?([\w\-:]+)((?:\s+|(?:\s+[\w\-:]+)|(?:\s+[\w\-:]+=[^\s"'<>]+)|(?:\s+[\w\-:"]+="[^"]*")|(?:\s+[\w\-:"]+='[^']*'))*)(\/)?>(\s*)/g;
var tagStack = [];
html = html.replace(re, function($0, $1, $2, $3, $4, $5, $6) {
var full = $0,
startNewline = $1 || '',
startSlash = $2 || '',
tagName = $3.toLowerCase(),
attr = $4 || '',
endSlash = $5 ? ' ' + $5 : '',
endNewline = $6 || '';
if (htmlTags && !htmlTagMap[tagName]) {
return '';
}
if (endSlash === '' && _SINGLE_TAG_MAP[tagName]) {
endSlash = ' /';
}
if (_INLINE_TAG_MAP[tagName]) {
if (startNewline) {
startNewline = ' ';
}
if (endNewline) {
endNewline = ' ';
}
}
if (_PRE_TAG_MAP[tagName]) {
if (startSlash) {
endNewline = '\n';
} else {
startNewline = '\n';
}
}
if (wellFormatted && tagName == 'br') {
endNewline = '\n';
}
if (_BLOCK_TAG_MAP[tagName] && !_PRE_TAG_MAP[tagName]) {
if (wellFormatted) {
if (startSlash && tagStack.length > 0 && tagStack[tagStack.length - 1] === tagName) {
tagStack.pop();
} else {
tagStack.push(tagName);
}
startNewline = '\n';
endNewline = '\n';
for (var i = 0, len = startSlash ? tagStack.length : tagStack.length - 1; i < len; i++) {
startNewline += indentChar;
if (!startSlash) {
endNewline += indentChar;
}
}
if (endSlash) {
tagStack.pop();
} else if (!startSlash) {
endNewline += indentChar;
}
} else {
startNewline = endNewline = '';
}
}
if (attr !== '') {
var attrMap = _getAttrList(full);
if (tagName === 'font') {
var fontStyleMap = {}, fontStyle = '';
_each(attrMap, function(key, val) {
if (key === 'color') {
fontStyleMap.color = val;
delete attrMap[key];
}
if (key === 'size') {
fontStyleMap['font-size'] = fontSizeList[parseInt(val, 10) - 1] || '';
delete attrMap[key];
}
if (key === 'face') {
fontStyleMap['font-family'] = val;
delete attrMap[key];
}
if (key === 'style') {
fontStyle = val;
}
});
if (fontStyle && !/;$/.test(fontStyle)) {
fontStyle += ';';
}
_each(fontStyleMap, function(key, val) {
if (val === '') {
return;
}
if (/\s/.test(val)) {
val = "'" + val + "'";
}
fontStyle += key + ':' + val + ';';
});
attrMap.style = fontStyle;
}
_each(attrMap, function(key, val) {
if (_FILL_ATTR_MAP[key]) {
attrMap[key] = key;
}
if (_inArray(key, ['src', 'href']) >= 0) {
attrMap[key] = _formatUrl(val, urlType);
}
if (htmlTags && key !== 'style' && !htmlTagMap[tagName]['*'] && !htmlTagMap[tagName][key] ||
tagName === 'body' && key === 'contenteditable' ||
/^kindeditor_\d+$/.test(key)) {
delete attrMap[key];
}
if (key === 'style' && val !== '') {
var styleMap = _getCssList(val);
_each(styleMap, function(k, v) {
if (htmlTags && !htmlTagMap[tagName].style && !htmlTagMap[tagName]['.' + k]) {
delete styleMap[k];
}
});
var style = '';
_each(styleMap, function(k, v) {
style += k + ':' + v + ';';
});
attrMap.style = style;
}
});
attr = '';
_each(attrMap, function(key, val) {
if (key === 'style' && val === '') {
return;
}
val = val.replace(/"/g, '"');
attr += ' ' + key + '="' + val + '"';
});
}
if (tagName === 'font') {
tagName = 'span';
}
return startNewline + '<' + startSlash + tagName + attr + endSlash + '>' + endNewline;
});
html = html.replace(/(<(?:pre|pre\s[^>]*)>)([\s\S]*?)(<\/pre>)/ig, function($0, $1, $2, $3) {
return $1 + $2.replace(/\n/g, '<span id="__kindeditor_pre_newline__">\n') + $3;
});
html = html.replace(/\n\s*\n/g, '\n');
html = html.replace(/<span id="__kindeditor_pre_newline__">\n/g, '\n');
return _trim(html);
}
function _clearMsWord(html, htmlTags) {
html = html.replace(/<meta[\s\S]*?>/ig, '')
.replace(/<![\s\S]*?>/ig, '')
.replace(/<style[^>]*>[\s\S]*?<\/style>/ig, '')
.replace(/<script[^>]*>[\s\S]*?<\/script>/ig, '')
.replace(/<w:[^>]+>[\s\S]*?<\/w:[^>]+>/ig, '')
.replace(/<o:[^>]+>[\s\S]*?<\/o:[^>]+>/ig, '')
.replace(/<xml>[\s\S]*?<\/xml>/ig, '')
.replace(/<(?:table|td)[^>]*>/ig, function(full) {
return full.replace(/border-bottom:([#\w\s]+)/ig, 'border:$1');
});
return _formatHtml(html, htmlTags);
}
function _mediaType(src) {
if (/\.(rm|rmvb)(\?|$)/i.test(src)) {
return 'audio/x-pn-realaudio-plugin';
}
if (/\.(swf|flv)(\?|$)/i.test(src)) {
return 'application/x-shockwave-flash';
}
return 'video/x-ms-asf-plugin';
}
function _mediaClass(type) {
if (/realaudio/i.test(type)) {
return 'ke-rm';
}
if (/flash/i.test(type)) {
return 'ke-flash';
}
return 'ke-media';
}
function _mediaAttrs(srcTag) {
return _getAttrList(unescape(srcTag));
}
function _mediaEmbed(attrs) {
var html = '<embed ';
_each(attrs, function(key, val) {
html += key + '="' + val + '" ';
});
html += '/>';
return html;
}
function _mediaImg(blankPath, attrs) {
var width = attrs.width,
height = attrs.height,
type = attrs.type || _mediaType(attrs.src),
srcTag = _mediaEmbed(attrs),
style = '';
if (width > 0) {
style += 'width:' + width + 'px;';
}
if (height > 0) {
style += 'height:' + height + 'px;';
}
var html = '<img class="' + _mediaClass(type) + '" src="' + blankPath + '" ';
if (style !== '') {
html += 'style="' + style + '" ';
}
html += 'data-ke-tag="' + escape(srcTag) + '" alt="" />';
return html;
}
K.formatUrl = _formatUrl;
K.formatHtml = _formatHtml;
K.getCssList = _getCssList;
K.getAttrList = _getAttrList;
K.mediaType = _mediaType;
K.mediaAttrs = _mediaAttrs;
K.mediaEmbed = _mediaEmbed;
K.mediaImg = _mediaImg;
K.clearMsWord = _clearMsWord;
function _contains(nodeA, nodeB) {
if (nodeA.nodeType == 9 && nodeB.nodeType != 9) {
return true;
}
while ((nodeB = nodeB.parentNode)) {
if (nodeB == nodeA) {
return true;
}
}
return false;
}
var _getSetAttrDiv = document.createElement('div');
_getSetAttrDiv.setAttribute('className', 't');
var _GET_SET_ATTRIBUTE = _getSetAttrDiv.className !== 't';
function _getAttr(el, key) {
key = key.toLowerCase();
var val = null;
if (!_GET_SET_ATTRIBUTE && el.nodeName.toLowerCase() != 'script') {
var div = el.ownerDocument.createElement('div');
div.appendChild(el.cloneNode(false));
var list = _getAttrList(_unescape(div.innerHTML));
if (key in list) {
val = list[key];
}
} else {
try {
val = el.getAttribute(key, 2);
} catch(e) {
val = el.getAttribute(key, 1);
}
}
if (key === 'style' && val !== null) {
val = _formatCss(val);
}
return val;
}
function _queryAll(expr, root) {
var exprList = expr.split(',');
if (exprList.length > 1) {
var mergedResults = [];
_each(exprList, function() {
_each(_queryAll(this, root), function() {
if (_inArray(this, mergedResults) < 0) {
mergedResults.push(this);
}
});
});
return mergedResults;
}
root = root || document;
function escape(str) {
if (typeof str != 'string') {
return str;
}
return str.replace(/([^\w\-])/g, '\\$1');
}
function stripslashes(str) {
return str.replace(/\\/g, '');
}
function cmpTag(tagA, tagB) {
return tagA === '*' || tagA.toLowerCase() === escape(tagB.toLowerCase());
}
function byId(id, tag, root) {
var arr = [],
doc = root.ownerDocument || root,
el = doc.getElementById(stripslashes(id));
if (el) {
if (cmpTag(tag, el.nodeName) && _contains(root, el)) {
arr.push(el);
}
}
return arr;
}
function byClass(className, tag, root) {
var doc = root.ownerDocument || root, arr = [], els, i, len, el;
if (root.getElementsByClassName) {
els = root.getElementsByClassName(stripslashes(className));
for (i = 0, len = els.length; i < len; i++) {
el = els[i];
if (cmpTag(tag, el.nodeName)) {
arr.push(el);
}
}
} else if (doc.querySelectorAll) {
els = doc.querySelectorAll((root.nodeName !== '#document' ? root.nodeName + ' ' : '') + tag + '.' + className);
for (i = 0, len = els.length; i < len; i++) {
el = els[i];
if (_contains(root, el)) {
arr.push(el);
}
}
} else {
els = root.getElementsByTagName(tag);
className = ' ' + className + ' ';
for (i = 0, len = els.length; i < len; i++) {
el = els[i];
if (el.nodeType == 1) {
var cls = el.className;
if (cls && (' ' + cls + ' ').indexOf(className) > -1) {
arr.push(el);
}
}
}
}
return arr;
}
function byName(name, tag, root) {
var arr = [], doc = root.ownerDocument || root,
els = doc.getElementsByName(stripslashes(name)), el;
for (var i = 0, len = els.length; i < len; i++) {
el = els[i];
if (cmpTag(tag, el.nodeName) && _contains(root, el)) {
if (el.getAttributeNode('name')) {
arr.push(el);
}
}
}
return arr;
}
function byAttr(key, val, tag, root) {
var arr = [], els = root.getElementsByTagName(tag), el;
for (var i = 0, len = els.length; i < len; i++) {
el = els[i];
if (el.nodeType == 1) {
if (val === null) {
if (_getAttr(el, key) !== null) {
arr.push(el);
}
} else {
if (val === escape(_getAttr(el, key))) {
arr.push(el);
}
}
}
}
return arr;
}
function select(expr, root) {
var arr = [], matches;
matches = /^((?:\\.|[^.#\s\[<>])+)/.exec(expr);
var tag = matches ? matches[1] : '*';
if ((matches = /#((?:[\w\-]|\\.)+)$/.exec(expr))) {
arr = byId(matches[1], tag, root);
} else if ((matches = /\.((?:[\w\-]|\\.)+)$/.exec(expr))) {
arr = byClass(matches[1], tag, root);
} else if ((matches = /\[((?:[\w\-]|\\.)+)\]/.exec(expr))) {
arr = byAttr(matches[1].toLowerCase(), null, tag, root);
} else if ((matches = /\[((?:[\w\-]|\\.)+)\s*=\s*['"]?((?:\\.|[^'"]+)+)['"]?\]/.exec(expr))) {
var key = matches[1].toLowerCase(), val = matches[2];
if (key === 'id') {
arr = byId(val, tag, root);
} else if (key === 'class') {
arr = byClass(val, tag, root);
} else if (key === 'name') {
arr = byName(val, tag, root);
} else {
arr = byAttr(key, val, tag, root);
}
} else {
var els = root.getElementsByTagName(tag), el;
for (var i = 0, len = els.length; i < len; i++) {
el = els[i];
if (el.nodeType == 1) {
arr.push(el);
}
}
}
return arr;
}
var parts = [], arr, re = /((?:\\.|[^\s>])+|[\s>])/g;
while ((arr = re.exec(expr))) {
if (arr[1] !== ' ') {
parts.push(arr[1]);
}
}
var results = [];
if (parts.length == 1) {
return select(parts[0], root);
}
var isChild = false, part, els, subResults, val, v, i, j, k, length, len, l;
for (i = 0, lenth = parts.length; i < lenth; i++) {
part = parts[i];
if (part === '>') {
isChild = true;
continue;
}
if (i > 0) {
els = [];
for (j = 0, len = results.length; j < len; j++) {
val = results[j];
subResults = select(part, val);
for (k = 0, l = subResults.length; k < l; k++) {
v = subResults[k];
if (isChild) {
if (val === v.parentNode) {
els.push(v);
}
} else {
els.push(v);
}
}
}
results = els;
} else {
results = select(part, root);
}
if (results.length === 0) {
return [];
}
}
return results;
}
function _query(expr, root) {
var arr = _queryAll(expr, root);
return arr.length > 0 ? arr[0] : null;
}
K.query = _query;
K.queryAll = _queryAll;
function _get(val) {
return K(val)[0];
}
function _getDoc(node) {
if (!node) {
return document;
}
return node.ownerDocument || node.document || node;
}
function _getWin(node) {
if (!node) {
return window;
}
var doc = _getDoc(node);
return doc.parentWindow || doc.defaultView;
}
function _setHtml(el, html) {
if (el.nodeType != 1) {
return;
}
var doc = _getDoc(el);
try {
el.innerHTML = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + html;
var temp = doc.getElementById('__kindeditor_temp_tag__');
temp.parentNode.removeChild(temp);
} catch(e) {
K(el).empty();
K('@' + html, doc).each(function() {
el.appendChild(this);
});
}
}
function _hasClass(el, cls) {
return _inString(cls, el.className, ' ');
}
function _setAttr(el, key, val) {
if (_IE && _V < 8 && key.toLowerCase() == 'class') {
key = 'className';
}
el.setAttribute(key, '' + val);
}
function _removeAttr(el, key) {
if (_IE && _V < 8 && key.toLowerCase() == 'class') {
key = 'className';
}
_setAttr(el, key, '');
el.removeAttribute(key);
}
function _getNodeName(node) {
if (!node || !node.nodeName) {
return '';
}
return node.nodeName.toLowerCase();
}
function _computedCss(el, key) {
var self = this, win = _getWin(el), camelKey = _toCamel(key), val = '';
if (win.getComputedStyle) {
var style = win.getComputedStyle(el, null);
val = style[camelKey] || style.getPropertyValue(key) || el.style[camelKey];
} else if (el.currentStyle) {
val = el.currentStyle[camelKey] || el.style[camelKey];
}
return val;
}
function _hasVal(node) {
return !!_VALUE_TAG_MAP[_getNodeName(node)];
}
function _docElement(doc) {
doc = doc || document;
return _QUIRKS ? doc.body : doc.documentElement;
}
function _docHeight(doc) {
var el = _docElement(doc);
return Math.max(el.scrollHeight, el.clientHeight);
}
function _docWidth(doc) {
var el = _docElement(doc);
return Math.max(el.scrollWidth, el.clientWidth);
}
function _getScrollPos(doc) {
doc = doc || document;
var x, y;
if (_IE || _OPERA) {
x = _docElement(doc).scrollLeft;
y = _docElement(doc).scrollTop;
} else {
x = _getWin(doc).scrollX;
y = _getWin(doc).scrollY;
}
return {x : x, y : y};
}
function KNode(node) {
this.init(node);
}
_extend(KNode, {
init : function(node) {
var self = this;
for (var i = 0, len = node.length; i < len; i++) {
self[i] = node[i].constructor === KNode ? node[i][0] : node[i];
}
self.length = node.length;
self.doc = _getDoc(self[0]);
self.name = _getNodeName(self[0]);
self.type = self.length > 0 ? self[0].nodeType : null;
self.win = _getWin(self[0]);
self._data = {};
},
each : function(fn) {
var self = this;
for (var i = 0; i < self.length; i++) {
if (fn.call(self[i], i, self[i]) === false) {
return self;
}
}
return self;
},
bind : function(type, fn) {
this.each(function() {
_bind(this, type, fn);
});
return this;
},
unbind : function(type, fn) {
this.each(function() {
_unbind(this, type, fn);
});
return this;
},
fire : function(type) {
if (this.length < 1) {
return this;
}
_fire(this[0], type);
return this;
},
hasAttr : function(key) {
if (this.length < 1) {
return false;
}
return !!_getAttr(this[0], key);
},
attr : function(key, val) {
var self = this;
if (key === undefined) {
return _getAttrList(self.outer());
}
if (typeof key === 'object') {
_each(key, function(k, v) {
self.attr(k, v);
});
return self;
}
if (val === undefined) {
val = self.length < 1 ? null : _getAttr(self[0], key);
return val === null ? '' : val;
}
self.each(function() {
_setAttr(this, key, val);
});
return self;
},
removeAttr : function(key) {
this.each(function() {
_removeAttr(this, key);
});
return this;
},
get : function(i) {
if (this.length < 1) {
return null;
}
return this[i || 0];
},
hasClass : function(cls) {
if (this.length < 1) {
return false;
}
return _hasClass(this[0], cls);
},
addClass : function(cls) {
this.each(function() {
if (!_hasClass(this, cls)) {
this.className = _trim(this.className + ' ' + cls);
}
});
return this;
},
removeClass : function(cls) {
this.each(function() {
if (_hasClass(this, cls)) {
this.className = _trim(this.className.replace(new RegExp('(^|\\s)' + cls + '(\\s|$)'), ' '));
}
});
return this;
},
html : function(val) {
var self = this;
if (val === undefined) {
if (self.length < 1 || self.type != 1) {
return '';
}
return _formatHtml(self[0].innerHTML);
}
self.each(function() {
_setHtml(this, val);
});
return self;
},
text : function() {
var self = this;
if (self.length < 1) {
return '';
}
return _IE ? self[0].innerText : self[0].textContent;
},
hasVal : function() {
if (this.length < 1) {
return false;
}
return _hasVal(this[0]);
},
val : function(val) {
var self = this;
if (val === undefined) {
if (self.length < 1) {
return '';
}
return self.hasVal() ? self[0].value : self.attr('value');
} else {
self.each(function() {
if (_hasVal(this)) {
this.value = val;
} else {
_setAttr(this, 'value' , val);
}
});
return self;
}
},
css : function(key, val) {
var self = this;
if (key === undefined) {
return _getCssList(self.attr('style'));
}
if (typeof key === 'object') {
_each(key, function(k, v) {
self.css(k, v);
});
return self;
}
if (val === undefined) {
if (self.length < 1) {
return '';
}
return self[0].style[_toCamel(key)] || _computedCss(self[0], key) || '';
}
self.each(function() {
this.style[_toCamel(key)] = val;
});
return self;
},
width : function(val) {
var self = this;
if (val === undefined) {
if (self.length < 1) {
return 0;
}
return self[0].offsetWidth;
}
return self.css('width', _addUnit(val));
},
height : function(val) {
var self = this;
if (val === undefined) {
if (self.length < 1) {
return 0;
}
return self[0].offsetHeight;
}
return self.css('height', _addUnit(val));
},
opacity : function(val) {
this.each(function() {
if (this.style.opacity === undefined) {
this.style.filter = val == 1 ? '' : 'alpha(opacity=' + (val * 100) + ')';
} else {
this.style.opacity = val == 1 ? '' : val;
}
});
return this;
},
data : function(key, val) {
var self = this;
if (val === undefined) {
return self._data[key];
}
self._data[key] = val;
return self;
},
pos : function() {
var self = this, node = self[0], x = 0, y = 0;
if (node) {
if (node.getBoundingClientRect) {
var box = node.getBoundingClientRect(),
pos = _getScrollPos(self.doc);
x = box.left + pos.x;
y = box.top + pos.y;
} else {
while (node) {
x += node.offsetLeft;
y += node.offsetTop;
node = node.offsetParent;
}
}
}
return {x : _round(x), y : _round(y)};
},
clone : function(bool) {
if (this.length < 1) {
return new KNode([]);
}
return new KNode([this[0].cloneNode(bool)]);
},
append : function(expr) {
this.each(function() {
if (this.appendChild) {
this.appendChild(_get(expr));
}
});
return this;
},
appendTo : function(expr) {
this.each(function() {
_get(expr).appendChild(this);
});
return this;
},
before : function(expr) {
this.each(function() {
this.parentNode.insertBefore(_get(expr), this);
});
return this;
},
after : function(expr) {
this.each(function() {
if (this.nextSibling) {
this.parentNode.insertBefore(_get(expr), this.nextSibling);
} else {
this.parentNode.appendChild(_get(expr));
}
});
return this;
},
replaceWith : function(expr) {
var nodes = [];
this.each(function(i, node) {
_unbind(node);
var newNode = _get(expr);
node.parentNode.replaceChild(newNode, node);
nodes.push(newNode);
});
return K(nodes);
},
empty : function() {
var self = this;
self.each(function(i, node) {
var child = node.firstChild;
while (child) {
if (!node.parentNode) {
return;
}
var next = child.nextSibling;
child.parentNode.removeChild(child);
child = next;
}
});
return self;
},
remove : function(keepChilds) {
var self = this;
self.each(function(i, node) {
if (!node.parentNode) {
return;
}
_unbind(node);
if (keepChilds) {
var child = node.firstChild;
while (child) {
var next = child.nextSibling;
node.parentNode.insertBefore(child, node);
child = next;
}
}
node.parentNode.removeChild(node);
delete self[i];
});
self.length = 0;
self._data = {};
return self;
},
show : function(val) {
return this.css('display', val === undefined ? 'block' : val);
},
hide : function() {
return this.css('display', 'none');
},
outer : function() {
var self = this;
if (self.length < 1) {
return '';
}
var div = self.doc.createElement('div'), html;
div.appendChild(self[0].cloneNode(true));
html = _formatHtml(div.innerHTML);
div = null;
return html;
},
isSingle : function() {
return !!_SINGLE_TAG_MAP[this.name];
},
isInline : function() {
return !!_INLINE_TAG_MAP[this.name];
},
isBlock : function() {
return !!_BLOCK_TAG_MAP[this.name];
},
isStyle : function() {
return !!_STYLE_TAG_MAP[this.name];
},
isControl : function() {
return !!_CONTROL_TAG_MAP[this.name];
},
contains : function(otherNode) {
if (this.length < 1) {
return false;
}
return _contains(this[0], _get(otherNode));
},
parent : function() {
if (this.length < 1) {
return null;
}
var node = this[0].parentNode;
return node ? new KNode([node]) : null;
},
children : function() {
if (this.length < 1) {
return [];
}
var list = [], child = this[0].firstChild;
while (child) {
if (child.nodeType != 3 || _trim(child.nodeValue) !== '') {
list.push(new KNode([child]));
}
child = child.nextSibling;
}
return list;
},
first : function() {
var list = this.children();
return list.length > 0 ? list[0] : null;
},
last : function() {
var list = this.children();
return list.length > 0 ? list[list.length - 1] : null;
},
index : function() {
if (this.length < 1) {
return -1;
}
var i = -1, sibling = this[0];
while (sibling) {
i++;
sibling = sibling.previousSibling;
}
return i;
},
prev : function() {
if (this.length < 1) {
return null;
}
var node = this[0].previousSibling;
return node ? new KNode([node]) : null;
},
next : function() {
if (this.length < 1) {
return null;
}
var node = this[0].nextSibling;
return node ? new KNode([node]) : null;
},
scan : function(fn, order) {
if (this.length < 1) {
return;
}
order = (order === undefined) ? true : order;
function walk(node) {
var n = order ? node.firstChild : node.lastChild;
while (n) {
var next = order ? n.nextSibling : n.previousSibling;
if (fn(n) === false) {
return false;
}
if (walk(n) === false) {
return false;
}
n = next;
}
}
walk(this[0]);
return this;
}
});
_each(('blur,focus,focusin,focusout,load,resize,scroll,unload,click,dblclick,' +
'mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,' +
'change,select,submit,keydown,keypress,keyup,error,contextmenu').split(','), function(i, type) {
KNode.prototype[type] = function(fn) {
return fn ? this.bind(type, fn) : this.fire(type);
};
});
var _K = K;
K = function(expr, root) {
if (expr === undefined || expr === null) {
return;
}
function newNode(node) {
if (!node[0]) {
node = [];
}
return new KNode(node);
}
if (typeof expr === 'string') {
if (root) {
root = _get(root);
}
var length = expr.length;
if (expr.charAt(0) === '@') {
expr = expr.substr(1);
}
if (expr.length !== length || /<.+>/.test(expr)) {
var doc = root ? root.ownerDocument || root : document,
div = doc.createElement('div'), list = [];
div.innerHTML = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + expr;
for (var i = 0, len = div.childNodes.length; i < len; i++) {
var child = div.childNodes[i];
if (child.id == '__kindeditor_temp_tag__') {
continue;
}
list.push(child);
}
return newNode(list);
}
return newNode(_queryAll(expr, root));
}
if (expr && expr.constructor === KNode) {
return expr;
}
if (_isArray(expr)) {
return newNode(expr);
}
return newNode(_toArray(arguments));
};
_each(_K, function(key, val) {
K[key] = val;
});
window.KindEditor = K;
var _START_TO_START = 0,
_START_TO_END = 1,
_END_TO_END = 2,
_END_TO_START = 3,
_BOOKMARK_ID = 0;
function _updateCollapsed(range) {
range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);
return range;
}
function _copyAndDelete(range, isCopy, isDelete) {
var doc = range.doc, nodeList = [];
function splitTextNode(node, startOffset, endOffset) {
var length = node.nodeValue.length, centerNode;
if (isCopy) {
var cloneNode = node.cloneNode(true);
if (startOffset > 0) {
centerNode = cloneNode.splitText(startOffset);
} else {
centerNode = cloneNode;
}
if (endOffset < length) {
centerNode.splitText(endOffset - startOffset);
}
}
if (isDelete) {
var center = node;
if (startOffset > 0) {
center = node.splitText(startOffset);
range.setStart(node, startOffset);
}
if (endOffset < length) {
var right = center.splitText(endOffset - startOffset);
range.setEnd(right, 0);
}
nodeList.push(center);
}
return centerNode;
}
function removeNodes() {
if (isDelete) {
range.up().collapse(true);
}
for (var i = 0, len = nodeList.length; i < len; i++) {
var node = nodeList[i];
if (node.parentNode) {
node.parentNode.removeChild(node);
}
}
}
var copyRange = range.cloneRange().down();
var start = -1, incStart = -1, incEnd = -1, end = -1,
ancestor = range.commonAncestor(), frag = doc.createDocumentFragment();
if (ancestor.nodeType == 3) {
var textNode = splitTextNode(ancestor, range.startOffset, range.endOffset);
if (isCopy) {
frag.appendChild(textNode);
}
removeNodes();
return isCopy ? frag : range;
}
function extractNodes(parent, frag) {
var node = parent.firstChild, nextNode;
while (node) {
var testRange = new KRange(doc).selectNode(node);
start = testRange.compareBoundaryPoints(_START_TO_END, range);
if (start >= 0 && incStart <= 0) {
incStart = testRange.compareBoundaryPoints(_START_TO_START, range);
}
if (incStart >= 0 && incEnd <= 0) {
incEnd = testRange.compareBoundaryPoints(_END_TO_END, range);
}
if (incEnd >= 0 && end <= 0) {
end = testRange.compareBoundaryPoints(_END_TO_START, range);
}
if (end >= 0) {
return false;
}
nextNode = node.nextSibling;
if (start > 0) {
if (node.nodeType == 1) {
if (incStart >= 0 && incEnd <= 0) {
if (isCopy) {
frag.appendChild(node.cloneNode(true));
}
if (isDelete) {
nodeList.push(node);
}
} else {
var childFlag;
if (isCopy) {
childFlag = node.cloneNode(false);
frag.appendChild(childFlag);
}
if (extractNodes(node, childFlag) === false) {
return false;
}
}
} else if (node.nodeType == 3) {
var textNode;
if (node == copyRange.startContainer) {
textNode = splitTextNode(node, copyRange.startOffset, node.nodeValue.length);
} else if (node == copyRange.endContainer) {
textNode = splitTextNode(node, 0, copyRange.endOffset);
} else {
textNode = splitTextNode(node, 0, node.nodeValue.length);
}
if (isCopy) {
try {
frag.appendChild(textNode);
} catch(e) {}
}
}
}
node = nextNode;
}
}
extractNodes(ancestor, frag);
if (isDelete) {
range.up().collapse(true);
}
for (var i = 0, len = nodeList.length; i < len; i++) {
var node = nodeList[i];
if (node.parentNode) {
node.parentNode.removeChild(node);
}
}
return isCopy ? frag : range;
}
function _moveToElementText(range, el) {
var node = el;
while (node) {
var knode = K(node);
if (knode.name == 'marquee' || knode.name == 'select') {
return;
}
node = node.parentNode;
}
try {
range.moveToElementText(el);
} catch(e) {}
}
function _getStartEnd(rng, isStart) {
var doc = rng.parentElement().ownerDocument,
pointRange = rng.duplicate();
pointRange.collapse(isStart);
var parent = pointRange.parentElement(),
nodes = parent.childNodes;
if (nodes.length === 0) {
return {node: parent.parentNode, offset: K(parent).index()};
}
var startNode = doc, startPos = 0, cmp = -1;
var testRange = rng.duplicate();
_moveToElementText(testRange, parent);
for (var i = 0, len = nodes.length; i < len; i++) {
var node = nodes[i];
cmp = testRange.compareEndPoints('StartToStart', pointRange);
if (cmp === 0) {
return {node: node.parentNode, offset: i};
}
if (node.nodeType == 1) {
var nodeRange = rng.duplicate(), dummy, knode = K(node), newNode = node;
if (knode.isControl()) {
dummy = doc.createElement('span');
knode.after(dummy);
newNode = dummy;
startPos += knode.text().replace(/\r\n|\n|\r/g, '').length;
}
_moveToElementText(nodeRange, newNode);
testRange.setEndPoint('StartToEnd', nodeRange);
if (cmp > 0) {
startPos += nodeRange.text.replace(/\r\n|\n|\r/g, '').length;
} else {
startPos = 0;
}
if (dummy) {
K(dummy).remove();
}
} else if (node.nodeType == 3) {
testRange.moveStart('character', node.nodeValue.length);
startPos += node.nodeValue.length;
}
if (cmp < 0) {
startNode = node;
}
}
if (cmp < 0 && startNode.nodeType == 1) {
return {node: parent, offset: K(parent.lastChild).index() + 1};
}
if (cmp > 0) {
while (startNode.nextSibling && startNode.nodeType == 1) {
startNode = startNode.nextSibling;
}
}
testRange = rng.duplicate();
_moveToElementText(testRange, parent);
testRange.setEndPoint('StartToEnd', pointRange);
startPos -= testRange.text.replace(/\r\n|\n|\r/g, '').length;
if (cmp > 0 && startNode.nodeType == 3) {
var prevNode = startNode.previousSibling;
while (prevNode && prevNode.nodeType == 3) {
startPos -= prevNode.nodeValue.length;
prevNode = prevNode.previousSibling;
}
}
return {node: startNode, offset: startPos};
}
function _getEndRange(node, offset) {
var doc = node.ownerDocument || node,
range = doc.body.createTextRange();
if (doc == node) {
range.collapse(true);
return range;
}
if (node.nodeType == 1 && node.childNodes.length > 0) {
var children = node.childNodes, isStart, child;
if (offset === 0) {
child = children[0];
isStart = true;
} else {
child = children[offset - 1];
isStart = false;
}
if (!child) {
return range;
}
if (K(child).name === 'head') {
if (offset === 1) {
isStart = true;
}
if (offset === 2) {
isStart = false;
}
range.collapse(isStart);
return range;
}
if (child.nodeType == 1) {
var kchild = K(child), span;
if (kchild.isControl()) {
span = doc.createElement('span');
if (isStart) {
kchild.before(span);
} else {
kchild.after(span);
}
child = span;
}
_moveToElementText(range, child);
range.collapse(isStart);
if (span) {
K(span).remove();
}
return range;
}
node = child;
offset = isStart ? 0 : child.nodeValue.length;
}
var dummy = doc.createElement('span');
K(node).before(dummy);
_moveToElementText(range, dummy);
range.moveStart('character', offset);
K(dummy).remove();
return range;
}
function _toRange(rng) {
var doc, range;
function tr2td(start) {
if (K(start.node).name == 'tr') {
start.node = start.node.cells[start.offset];
start.offset = 0;
}
}
if (_IE) {
if (rng.item) {
doc = _getDoc(rng.item(0));
range = new KRange(doc);
range.selectNode(rng.item(0));
return range;
}
doc = rng.parentElement().ownerDocument;
var start = _getStartEnd(rng, true),
end = _getStartEnd(rng, false);
tr2td(start);
tr2td(end);
range = new KRange(doc);
range.setStart(start.node, start.offset);
range.setEnd(end.node, end.offset);
return range;
}
var startContainer = rng.startContainer;
doc = startContainer.ownerDocument || startContainer;
range = new KRange(doc);
range.setStart(startContainer, rng.startOffset);
range.setEnd(rng.endContainer, rng.endOffset);
return range;
}
function KRange(doc) {
this.init(doc);
}
_extend(KRange, {
init : function(doc) {
var self = this;
self.startContainer = doc;
self.startOffset = 0;
self.endContainer = doc;
self.endOffset = 0;
self.collapsed = true;
self.doc = doc;
},
commonAncestor : function() {
function getParents(node) {
var parents = [];
while (node) {
parents.push(node);
node = node.parentNode;
}
return parents;
}
var parentsA = getParents(this.startContainer),
parentsB = getParents(this.endContainer),
i = 0, lenA = parentsA.length, lenB = parentsB.length, parentA, parentB;
while (++i) {
parentA = parentsA[lenA - i];
parentB = parentsB[lenB - i];
if (!parentA || !parentB || parentA !== parentB) {
break;
}
}
return parentsA[lenA - i + 1];
},
setStart : function(node, offset) {
var self = this, doc = self.doc;
self.startContainer = node;
self.startOffset = offset;
if (self.endContainer === doc) {
self.endContainer = node;
self.endOffset = offset;
}
return _updateCollapsed(this);
},
setEnd : function(node, offset) {
var self = this, doc = self.doc;
self.endContainer = node;
self.endOffset = offset;
if (self.startContainer === doc) {
self.startContainer = node;
self.startOffset = offset;
}
return _updateCollapsed(this);
},
setStartBefore : function(node) {
return this.setStart(node.parentNode || this.doc, K(node).index());
},
setStartAfter : function(node) {
return this.setStart(node.parentNode || this.doc, K(node).index() + 1);
},
setEndBefore : function(node) {
return this.setEnd(node.parentNode || this.doc, K(node).index());
},
setEndAfter : function(node) {
return this.setEnd(node.parentNode || this.doc, K(node).index() + 1);
},
selectNode : function(node) {
return this.setStartBefore(node).setEndAfter(node);
},
selectNodeContents : function(node) {
var knode = K(node);
if (knode.type == 3 || knode.isSingle()) {
return this.selectNode(node);
}
var children = knode.children();
if (children.length > 0) {
return this.setStartBefore(children[0][0]).setEndAfter(children[children.length - 1][0]);
}
return this.setStart(node, 0).setEnd(node, 0);
},
collapse : function(toStart) {
if (toStart) {
return this.setEnd(this.startContainer, this.startOffset);
}
return this.setStart(this.endContainer, this.endOffset);
},
compareBoundaryPoints : function(how, range) {
var rangeA = this.get(), rangeB = range.get();
if (_IE) {
var arr = {};
arr[_START_TO_START] = 'StartToStart';
arr[_START_TO_END] = 'EndToStart';
arr[_END_TO_END] = 'EndToEnd';
arr[_END_TO_START] = 'StartToEnd';
var cmp = rangeA.compareEndPoints(arr[how], rangeB);
if (cmp !== 0) {
return cmp;
}
var nodeA, nodeB, nodeC, posA, posB;
if (how === _START_TO_START || how === _END_TO_START) {
nodeA = this.startContainer;
posA = this.startOffset;
}
if (how === _START_TO_END || how === _END_TO_END) {
nodeA = this.endContainer;
posA = this.endOffset;
}
if (how === _START_TO_START || how === _START_TO_END) {
nodeB = range.startContainer;
posB = range.startOffset;
}
if (how === _END_TO_END || how === _END_TO_START) {
nodeB = range.endContainer;
posB = range.endOffset;
}
if (nodeA === nodeB) {
var diff = posA - posB;
return diff > 0 ? 1 : (diff < 0 ? -1 : 0);
}
nodeC = nodeB;
while (nodeC && nodeC.parentNode !== nodeA) {
nodeC = nodeC.parentNode;
}
if (nodeC) {
return K(nodeC).index() >= posA ? -1 : 1;
}
nodeC = nodeA;
while (nodeC && nodeC.parentNode !== nodeB) {
nodeC = nodeC.parentNode;
}
if (nodeC) {
return K(nodeC).index() >= posB ? 1 : -1;
}
nodeC = K(nodeB).next();
if (nodeC && nodeC.contains(nodeA)) {
return 1;
}
nodeC = K(nodeA).next();
if (nodeC && nodeC.contains(nodeB)) {
return -1;
}
} else {
return rangeA.compareBoundaryPoints(how, rangeB);
}
},
cloneRange : function() {
return new KRange(this.doc).setStart(this.startContainer, this.startOffset).setEnd(this.endContainer, this.endOffset);
},
toString : function() {
var rng = this.get(), str = _IE ? rng.text : rng.toString();
return str.replace(/\r\n|\n|\r/g, '');
},
cloneContents : function() {
return _copyAndDelete(this, true, false);
},
deleteContents : function() {
return _copyAndDelete(this, false, true);
},
extractContents : function() {
return _copyAndDelete(this, true, true);
},
insertNode : function(node) {
var self = this,
sc = self.startContainer, so = self.startOffset,
ec = self.endContainer, eo = self.endOffset,
firstChild, lastChild, c, nodeCount = 1;
if (node.nodeName.toLowerCase() === '#document-fragment') {
firstChild = node.firstChild;
lastChild = node.lastChild;
nodeCount = node.childNodes.length;
}
if (sc.nodeType == 1) {
c = sc.childNodes[so];
if (c) {
sc.insertBefore(node, c);
if (sc === ec) {
eo += nodeCount;
}
} else {
sc.appendChild(node);
}
} else if (sc.nodeType == 3) {
if (so === 0) {
sc.parentNode.insertBefore(node, sc);
if (sc.parentNode === ec) {
eo += nodeCount;
}
} else if (so >= sc.nodeValue.length) {
if (sc.nextSibling) {
sc.parentNode.insertBefore(node, sc.nextSibling);
} else {
sc.parentNode.appendChild(node);
}
} else {
if (so > 0) {
c = sc.splitText(so);
} else {
c = sc;
}
sc.parentNode.insertBefore(node, c);
if (sc === ec) {
ec = c;
eo -= so;
}
}
}
if (firstChild) {
self.setStartBefore(firstChild).setEndAfter(lastChild);
} else {
self.selectNode(node);
}
if (self.compareBoundaryPoints(_END_TO_END, self.cloneRange().setEnd(ec, eo)) >= 1) {
return self;
}
return self.setEnd(ec, eo);
},
surroundContents : function(node) {
node.appendChild(this.extractContents());
return this.insertNode(node).selectNode(node);
},
isControl : function() {
var self = this,
sc = self.startContainer, so = self.startOffset,
ec = self.endContainer, eo = self.endOffset, rng;
return sc.nodeType == 1 && sc === ec && so + 1 === eo && K(sc.childNodes[so]).isControl();
},
get : function(hasControlRange) {
var self = this, doc = self.doc, node, rng;
if (!_IE) {
rng = doc.createRange();
try {
rng.setStart(self.startContainer, self.startOffset);
rng.setEnd(self.endContainer, self.endOffset);
} catch (e) {}
return rng;
}
if (hasControlRange && self.isControl()) {
rng = doc.body.createControlRange();
rng.addElement(self.startContainer.childNodes[self.startOffset]);
return rng;
}
var range = self.cloneRange().down();
rng = doc.body.createTextRange();
rng.setEndPoint('StartToStart', _getEndRange(range.startContainer, range.startOffset));
rng.setEndPoint('EndToStart', _getEndRange(range.endContainer, range.endOffset));
return rng;
},
html : function() {
return K(this.cloneContents()).outer();
},
down : function() {
var self = this;
function downPos(node, pos, isStart) {
if (node.nodeType != 1) {
return;
}
var children = K(node).children();
if (children.length === 0) {
return;
}
var left, right, child, offset;
if (pos > 0) {
left = children[pos - 1];
}
if (pos < children.length) {
right = children[pos];
}
if (left && left.type == 3) {
child = left[0];
offset = child.nodeValue.length;
}
if (right && right.type == 3) {
child = right[0];
offset = 0;
}
if (!child) {
return;
}
if (isStart) {
self.setStart(child, offset);
} else {
self.setEnd(child, offset);
}
}
downPos(self.startContainer, self.startOffset, true);
downPos(self.endContainer, self.endOffset, false);
return self;
},
up : function() {
var self = this;
function upPos(node, pos, isStart) {
if (node.nodeType != 3) {
return;
}
if (pos === 0) {
if (isStart) {
self.setStartBefore(node);
} else {
self.setEndBefore(node);
}
} else if (pos == node.nodeValue.length) {
if (isStart) {
self.setStartAfter(node);
} else {
self.setEndAfter(node);
}
}
}
upPos(self.startContainer, self.startOffset, true);
upPos(self.endContainer, self.endOffset, false);
return self;
},
enlarge : function(toBlock) {
var self = this;
self.up();
function enlargePos(node, pos, isStart) {
var knode = K(node), parent;
if (knode.type == 3 || _NOSPLIT_TAG_MAP[knode.name] || !toBlock && knode.isBlock()) {
return;
}
if (pos === 0) {
while (!knode.prev()) {
parent = knode.parent();
if (!parent || _NOSPLIT_TAG_MAP[parent.name] || !toBlock && parent.isBlock()) {
break;
}
knode = parent;
}
if (isStart) {
self.setStartBefore(knode[0]);
} else {
self.setEndBefore(knode[0]);
}
} else if (pos == knode.children().length) {
while (!knode.next()) {
parent = knode.parent();
if (!parent || _NOSPLIT_TAG_MAP[parent.name] || !toBlock && parent.isBlock()) {
break;
}
knode = parent;
}
if (isStart) {
self.setStartAfter(knode[0]);
} else {
self.setEndAfter(knode[0]);
}
}
}
enlargePos(self.startContainer, self.startOffset, true);
enlargePos(self.endContainer, self.endOffset, false);
return self;
},
shrink : function() {
var self = this, child, collapsed = self.collapsed;
while (self.startContainer.nodeType == 1 && (child = self.startContainer.childNodes[self.startOffset]) && child.nodeType == 1 && !K(child).isSingle()) {
self.setStart(child, 0);
}
if (collapsed) {
return self.collapse(collapsed);
}
while (self.endContainer.nodeType == 1 && self.endOffset > 0 && (child = self.endContainer.childNodes[self.endOffset - 1]) && child.nodeType == 1 && !K(child).isSingle()) {
self.setEnd(child, child.childNodes.length);
}
return self;
},
createBookmark : function(serialize) {
var self = this, doc = self.doc, endNode,
startNode = K('<span style="display:none;"></span>', doc)[0];
startNode.id = '__kindeditor_bookmark_start_' + (_BOOKMARK_ID++) + '__';
if (!self.collapsed) {
endNode = startNode.cloneNode(true);
endNode.id = '__kindeditor_bookmark_end_' + (_BOOKMARK_ID++) + '__';
}
if (endNode) {
self.cloneRange().collapse(false).insertNode(endNode).setEndBefore(endNode);
}
self.insertNode(startNode).setStartAfter(startNode);
return {
start : serialize ? '#' + startNode.id : startNode,
end : endNode ? (serialize ? '#' + endNode.id : endNode) : null
};
},
moveToBookmark : function(bookmark) {
var self = this, doc = self.doc,
start = K(bookmark.start, doc), end = bookmark.end ? K(bookmark.end, doc) : null;
if (!start || start.length < 1) {
return self;
}
self.setStartBefore(start[0]);
start.remove();
if (end && end.length > 0) {
self.setEndBefore(end[0]);
end.remove();
} else {
self.collapse(true);
}
return self;
},
dump : function() {
console.log('--------------------');
console.log(this.startContainer.nodeType == 3 ? this.startContainer.nodeValue : this.startContainer, this.startOffset);
console.log(this.endContainer.nodeType == 3 ? this.endContainer.nodeValue : this.endContainer, this.endOffset);
}
});
function _range(mixed) {
if (!mixed.nodeName) {
return mixed.constructor === KRange ? mixed : _toRange(mixed);
}
return new KRange(mixed);
}
K.range = _range;
K.START_TO_START = _START_TO_START;
K.START_TO_END = _START_TO_END;
K.END_TO_END = _END_TO_END;
K.END_TO_START = _END_TO_START;
function _nativeCommand(doc, key, val) {
try {
doc.execCommand(key, false, val);
} catch(e) {}
}
function _nativeCommandValue(doc, key) {
var val = '';
try {
val = doc.queryCommandValue(key);
} catch (e) {}
if (typeof val !== 'string') {
val = '';
}
return val;
}
function _getSel(doc) {
var win = _getWin(doc);
return doc.selection || win.getSelection();
}
function _getRng(doc) {
var sel = _getSel(doc), rng;
try {
if (sel.rangeCount > 0) {
rng = sel.getRangeAt(0);
} else {
rng = sel.createRange();
}
} catch(e) {}
if (_IE && (!rng || (!rng.item && rng.parentElement().ownerDocument !== doc))) {
return null;
}
return rng;
}
function _singleKeyMap(map) {
var newMap = {}, arr, v;
_each(map, function(key, val) {
arr = key.split(',');
for (var i = 0, len = arr.length; i < len; i++) {
v = arr[i];
newMap[v] = val;
}
});
return newMap;
}
function _hasAttrOrCss(knode, map) {
return _hasAttrOrCssByKey(knode, map, '*') || _hasAttrOrCssByKey(knode, map);
}
function _hasAttrOrCssByKey(knode, map, mapKey) {
mapKey = mapKey || knode.name;
if (knode.type !== 1) {
return false;
}
var newMap = _singleKeyMap(map);
if (!newMap[mapKey]) {
return false;
}
var arr = newMap[mapKey].split(',');
for (var i = 0, len = arr.length; i < len; i++) {
var key = arr[i];
if (key === '*') {
return true;
}
var match = /^(\.?)([^=]+)(?:=([^=]*))?$/.exec(key);
var method = match[1] ? 'css' : 'attr';
key = match[2];
var val = match[3] || '';
if (val === '' && knode[method](key) !== '') {
return true;
}
if (val !== '' && knode[method](key) === val) {
return true;
}
}
return false;
}
function _removeAttrOrCss(knode, map) {
if (knode.type != 1) {
return;
}
_removeAttrOrCssByKey(knode, map, '*');
_removeAttrOrCssByKey(knode, map);
}
function _removeAttrOrCssByKey(knode, map, mapKey) {
mapKey = mapKey || knode.name;
if (knode.type !== 1) {
return;
}
var newMap = _singleKeyMap(map);
if (!newMap[mapKey]) {
return;
}
var arr = newMap[mapKey].split(','), allFlag = false;
for (var i = 0, len = arr.length; i < len; i++) {
var key = arr[i];
if (key === '*') {
allFlag = true;
break;
}
var match = /^(\.?)([^=]+)(?:=([^=]*))?$/.exec(key);
key = match[2];
if (match[1]) {
key = _toCamel(key);
if (knode[0].style[key]) {
knode[0].style[key] = '';
}
} else {
knode.removeAttr(key);
}
}
if (allFlag) {
knode.remove(true);
}
}
function _getInnerNode(knode) {
var inner = knode;
while (inner.first()) {
inner = inner.first();
}
return inner;
}
function _isEmptyNode(knode) {
return knode.type == 1 && knode.html().replace(/<[^>]+>/g, '') === '';
}
function _mergeWrapper(a, b) {
a = a.clone(true);
var lastA = _getInnerNode(a), childA = a, merged = false;
while (b) {
while (childA) {
if (childA.name === b.name) {
_mergeAttrs(childA, b.attr(), b.css());
merged = true;
}
childA = childA.first();
}
if (!merged) {
lastA.append(b.clone(false));
}
merged = false;
b = b.first();
}
return a;
}
function _wrapNode(knode, wrapper) {
wrapper = wrapper.clone(true);
if (knode.type == 3) {
_getInnerNode(wrapper).append(knode.clone(false));
knode.replaceWith(wrapper);
return wrapper;
}
var nodeWrapper = knode, child;
while ((child = knode.first()) && child.children().length == 1) {
knode = child;
}
child = knode.first();
var frag = knode.doc.createDocumentFragment();
while (child) {
frag.appendChild(child[0]);
child = child.next();
}
wrapper = _mergeWrapper(nodeWrapper, wrapper);
if (frag.firstChild) {
_getInnerNode(wrapper).append(frag);
}
nodeWrapper.replaceWith(wrapper);
return wrapper;
}
function _mergeAttrs(knode, attrs, styles) {
_each(attrs, function(key, val) {
if (key !== 'style') {
knode.attr(key, val);
}
});
_each(styles, function(key, val) {
knode.css(key, val);
});
}
function _inPreElement(knode) {
while (knode && knode.name != 'body') {
if (_PRE_TAG_MAP[knode.name] || knode.name == 'div' && knode.hasClass('ke-script')) {
return true;
}
knode = knode.parent();
}
return false;
}
function KCmd(range) {
this.init(range);
}
_extend(KCmd, {
init : function(range) {
var self = this, doc = range.doc;
self.doc = doc;
self.win = _getWin(doc);
self.sel = _getSel(doc);
self.range = range;
},
selection : function(forceReset) {
var self = this, doc = self.doc, rng = _getRng(doc);
self.sel = _getSel(doc);
if (rng) {
self.range = _range(rng);
if (K(self.range.startContainer).name == 'html') {
self.range.selectNodeContents(doc.body).collapse(false);
}
return self;
}
if (forceReset) {
self.range.selectNodeContents(doc.body).collapse(false);
}
return self;
},
select : function(hasDummy) {
hasDummy = _undef(hasDummy, true);
var self = this, sel = self.sel, range = self.range.cloneRange().shrink(),
sc = range.startContainer, so = range.startOffset,
ec = range.endContainer, eo = range.endOffset,
doc = _getDoc(sc), win = self.win, rng, hasU200b = false;
if (hasDummy && sc.nodeType == 1 && range.collapsed) {
if (_IE) {
var dummy = K('<span> </span>', doc);
range.insertNode(dummy[0]);
rng = doc.body.createTextRange();
try {
rng.moveToElementText(dummy[0]);
} catch(ex) {}
rng.collapse(false);
rng.select();
dummy.remove();
win.focus();
return self;
}
if (_WEBKIT) {
var children = sc.childNodes;
if (K(sc).isInline() || so > 0 && K(children[so - 1]).isInline() || children[so] && K(children[so]).isInline()) {
range.insertNode(doc.createTextNode('\u200B'));
hasU200b = true;
}
}
}
if (_IE) {
try {
rng = range.get(true);
rng.select();
} catch(e) {}
} else {
if (hasU200b) {
range.collapse(false);
}
rng = range.get(true);
sel.removeAllRanges();
sel.addRange(rng);
}
win.focus();
return self;
},
wrap : function(val) {
var self = this, doc = self.doc, range = self.range, wrapper;
wrapper = K(val, doc);
if (range.collapsed) {
range.shrink();
range.insertNode(wrapper[0]).selectNodeContents(wrapper[0]);
return self;
}
if (wrapper.isBlock()) {
var copyWrapper = wrapper.clone(true), child = copyWrapper;
while (child.first()) {
child = child.first();
}
child.append(range.extractContents());
range.insertNode(copyWrapper[0]).selectNode(copyWrapper[0]);
return self;
}
range.enlarge();
var bookmark = range.createBookmark(), ancestor = range.commonAncestor(), isStart = false;
K(ancestor).scan(function(node) {
if (!isStart && node == bookmark.start) {
isStart = true;
return;
}
if (isStart) {
if (node == bookmark.end) {
return false;
}
var knode = K(node);
if (_inPreElement(knode)) {
return;
}
if (knode.type == 3 && _trim(node.nodeValue).length > 0) {
var parent;
while ((parent = knode.parent()) && parent.isStyle() && parent.children().length == 1) {
knode = parent;
}
_wrapNode(knode, wrapper);
}
}
});
range.moveToBookmark(bookmark);
return self;
},
split : function(isStart, map) {
var range = this.range, doc = range.doc;
var tempRange = range.cloneRange().collapse(isStart);
var node = tempRange.startContainer, pos = tempRange.startOffset,
parent = node.nodeType == 3 ? node.parentNode : node,
needSplit = false, knode;
while (parent && parent.parentNode) {
knode = K(parent);
if (map) {
if (!knode.isStyle()) {
break;
}
if (!_hasAttrOrCss(knode, map)) {
break;
}
} else {
if (_NOSPLIT_TAG_MAP[knode.name]) {
break;
}
}
needSplit = true;
parent = parent.parentNode;
}
if (needSplit) {
var dummy = doc.createElement('span');
range.cloneRange().collapse(!isStart).insertNode(dummy);
if (isStart) {
tempRange.setStartBefore(parent.firstChild).setEnd(node, pos);
} else {
tempRange.setStart(node, pos).setEndAfter(parent.lastChild);
}
var frag = tempRange.extractContents(),
first = frag.firstChild, last = frag.lastChild;
if (isStart) {
tempRange.insertNode(frag);
range.setStartAfter(last).setEndBefore(dummy);
} else {
parent.appendChild(frag);
range.setStartBefore(dummy).setEndBefore(first);
}
var dummyParent = dummy.parentNode;
if (dummyParent == range.endContainer) {
var prev = K(dummy).prev(), next = K(dummy).next();
if (prev && next && prev.type == 3 && next.type == 3) {
range.setEnd(prev[0], prev[0].nodeValue.length);
} else if (!isStart) {
range.setEnd(range.endContainer, range.endOffset - 1);
}
}
dummyParent.removeChild(dummy);
}
return this;
},
remove : function(map) {
var self = this, doc = self.doc, range = self.range;
range.enlarge();
if (range.startOffset === 0) {
var ksc = K(range.startContainer), parent;
while ((parent = ksc.parent()) && parent.isStyle() && parent.children().length == 1) {
ksc = parent;
}
range.setStart(ksc[0], 0);
ksc = K(range.startContainer);
if (ksc.isBlock()) {
_removeAttrOrCss(ksc, map);
}
var kscp = ksc.parent();
if (kscp && kscp.isBlock()) {
_removeAttrOrCss(kscp, map);
}
}
var sc, so;
if (range.collapsed) {
self.split(true, map);
sc = range.startContainer;
so = range.startOffset;
if (so > 0) {
var sb = K(sc.childNodes[so - 1]);
if (sb && _isEmptyNode(sb)) {
sb.remove();
range.setStart(sc, so - 1);
}
}
var sa = K(sc.childNodes[so]);
if (sa && _isEmptyNode(sa)) {
sa.remove();
}
if (_isEmptyNode(sc)) {
range.startBefore(sc);
sc.remove();
}
range.collapse(true);
return self;
}
self.split(true, map);
self.split(false, map);
var startDummy = doc.createElement('span'), endDummy = doc.createElement('span');
range.cloneRange().collapse(false).insertNode(endDummy);
range.cloneRange().collapse(true).insertNode(startDummy);
var nodeList = [], cmpStart = false;
K(range.commonAncestor()).scan(function(node) {
if (!cmpStart && node == startDummy) {
cmpStart = true;
return;
}
if (node == endDummy) {
return false;
}
if (cmpStart) {
nodeList.push(node);
}
});
K(startDummy).remove();
K(endDummy).remove();
sc = range.startContainer;
so = range.startOffset;
var ec = range.endContainer, eo = range.endOffset;
if (so > 0) {
var startBefore = K(sc.childNodes[so - 1]);
if (startBefore && _isEmptyNode(startBefore)) {
startBefore.remove();
range.setStart(sc, so - 1);
if (sc == ec) {
range.setEnd(ec, eo - 1);
}
}
var startAfter = K(sc.childNodes[so]);
if (startAfter && _isEmptyNode(startAfter)) {
startAfter.remove();
if (sc == ec) {
range.setEnd(ec, eo - 1);
}
}
}
var endAfter = K(ec.childNodes[range.endOffset]);
if (endAfter && _isEmptyNode(endAfter)) {
endAfter.remove();
}
var bookmark = range.createBookmark(true);
_each(nodeList, function(i, node) {
_removeAttrOrCss(K(node), map);
});
range.moveToBookmark(bookmark);
return self;
},
commonNode : function(map) {
var range = this.range;
var ec = range.endContainer, eo = range.endOffset,
node = (ec.nodeType == 3 || eo === 0) ? ec : ec.childNodes[eo - 1];
function find(node) {
var child = node, parent = node;
while (parent) {
if (_hasAttrOrCss(K(parent), map)) {
return K(parent);
}
parent = parent.parentNode;
}
while (child && (child = child.lastChild)) {
if (_hasAttrOrCss(K(child), map)) {
return K(child);
}
}
return null;
}
var cNode = find(node);
if (cNode) {
return cNode;
}
if (node.nodeType == 1 || (ec.nodeType == 3 && eo === 0)) {
var prev = K(node).prev();
if (prev) {
return find(prev);
}
}
return null;
},
commonAncestor : function(tagName) {
var range = this.range,
sc = range.startContainer, so = range.startOffset,
ec = range.endContainer, eo = range.endOffset,
startNode = (sc.nodeType == 3 || so === 0) ? sc : sc.childNodes[so - 1],
endNode = (ec.nodeType == 3 || eo === 0) ? ec : ec.childNodes[eo - 1];
function find(node) {
while (node) {
if (node.nodeType == 1) {
if (node.tagName.toLowerCase() === tagName) {
return node;
}
}
node = node.parentNode;
}
return null;
}
var start = find(startNode), end = find(endNode);
if (start && end && start === end) {
return K(start);
}
return null;
},
state : function(key) {
var self = this, doc = self.doc, bool = false;
try {
bool = doc.queryCommandState(key);
} catch (e) {}
return bool;
},
val : function(key) {
var self = this, doc = self.doc, range = self.range;
function lc(val) {
return val.toLowerCase();
}
key = lc(key);
var val = '', knode;
if (key === 'fontfamily' || key === 'fontname') {
val = _nativeCommandValue(doc, 'fontname');
val = val.replace(/['"]/g, '');
return lc(val);
}
if (key === 'formatblock') {
val = _nativeCommandValue(doc, key);
if (val === '') {
knode = self.commonNode({'h1,h2,h3,h4,h5,h6,p,div,pre,address' : '*'});
if (knode) {
val = knode.name;
}
}
if (val === 'Normal') {
val = 'p';
}
return lc(val);
}
if (key === 'fontsize') {
knode = self.commonNode({'*' : '.font-size'});
if (knode) {
val = knode.css('font-size');
}
return lc(val);
}
if (key === 'forecolor') {
knode = self.commonNode({'*' : '.color'});
if (knode) {
val = knode.css('color');
}
val = _toHex(val);
if (val === '') {
val = 'default';
}
return lc(val);
}
if (key === 'hilitecolor') {
knode = self.commonNode({'*' : '.background-color'});
if (knode) {
val = knode.css('background-color');
}
val = _toHex(val);
if (val === '') {
val = 'default';
}
return lc(val);
}
return val;
},
toggle : function(wrapper, map) {
var self = this;
if (self.commonNode(map)) {
self.remove(map);
} else {
self.wrap(wrapper);
}
return self.select();
},
bold : function() {
return this.toggle('<strong></strong>', {
span : '.font-weight=bold',
strong : '*',
b : '*'
});
},
italic : function() {
return this.toggle('<em></em>', {
span : '.font-style=italic',
em : '*',
i : '*'
});
},
underline : function() {
return this.toggle('<u></u>', {
span : '.text-decoration=underline',
u : '*'
});
},
strikethrough : function() {
return this.toggle('<s></s>', {
span : '.text-decoration=line-through',
s : '*'
});
},
forecolor : function(val) {
return this.toggle('<span style="color:' + val + ';"></span>', {
span : '.color=' + val,
font : 'color'
});
},
hilitecolor : function(val) {
return this.toggle('<span style="background-color:' + val + ';"></span>', {
span : '.background-color=' + val
});
},
fontsize : function(val) {
return this.toggle('<span style="font-size:' + val + ';"></span>', {
span : '.font-size=' + val,
font : 'size'
});
},
fontname : function(val) {
return this.fontfamily(val);
},
fontfamily : function(val) {
return this.toggle('<span style="font-family:' + val + ';"></span>', {
span : '.font-family=' + val,
font : 'face'
});
},
removeformat : function() {
var map = {
'*' : '.font-weight,.font-style,.text-decoration,.color,.background-color,.font-size,.font-family,.text-indent'
},
tags = _STYLE_TAG_MAP;
_each(tags, function(key, val) {
map[key] = '*';
});
this.remove(map);
return this.select();
},
inserthtml : function(val) {
var self = this, range = self.range;
if (val === '') {
return self;
}
if (_inPreElement(K(range.startContainer))) {
return self;
}
function pasteHtml(range, val) {
val = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + val;
var rng = range.get();
if (rng.item) {
rng.item(0).outerHTML = val;
} else {
rng.pasteHTML(val);
}
var temp = range.doc.getElementById('__kindeditor_temp_tag__');
temp.parentNode.removeChild(temp);
var newRange = _toRange(rng);
range.setEnd(newRange.endContainer, newRange.endOffset);
range.collapse(false);
self.select(false);
}
function insertHtml(range, val) {
var doc = range.doc,
frag = doc.createDocumentFragment();
K('@' + val, doc).each(function() {
frag.appendChild(this);
});
range.deleteContents();
range.insertNode(frag);
range.collapse(false);
self.select(false);
}
if (_IE) {
try {
pasteHtml(range, val);
} catch(e) {
insertHtml(range, val);
}
return self;
}
insertHtml(range, val);
return self;
},
hr : function() {
return this.inserthtml('<hr />');
},
print : function() {
this.win.print();
return this;
},
insertimage : function(url, title, width, height, border, align) {
title = _undef(title, '');
border = _undef(border, 0);
var html = '<img src="' + _escape(url) + '" data-ke-src="' + _escape(url) + '" ';
if (width) {
html += 'width="' + _escape(width) + '" ';
}
if (height) {
html += 'height="' + _escape(height) + '" ';
}
if (title) {
html += 'title="' + _escape(title) + '" ';
}
if (align) {
html += 'align="' + _escape(align) + '" ';
}
html += 'alt="' + _escape(title) + '" ';
html += '/>';
return this.inserthtml(html);
},
createlink : function(url, type) {
var self = this, doc = self.doc, range = self.range;
self.select();
var a = self.commonNode({ a : '*' });
if (a && !range.isControl()) {
range.selectNode(a.get());
self.select();
}
var html = '<a href="' + _escape(url) + '" data-ke-src="' + _escape(url) + '" ';
if (type) {
html += ' target="' + _escape(type) + '"';
}
if (range.collapsed) {
html += '>' + _escape(url) + '</a>';
return self.inserthtml(html);
}
if (range.isControl()) {
var node = K(range.startContainer.childNodes[range.startOffset]);
html += '></a>';
node.after(K(html, doc));
node.next().append(node);
range.selectNode(node[0]);
return self.select();
}
_nativeCommand(doc, 'createlink', '__kindeditor_temp_url__');
K('a[href="__kindeditor_temp_url__"]', doc).each(function() {
K(this).attr('href', url).attr('data-ke-src', url);
if (type) {
K(this).attr('target', type);
} else {
K(this).removeAttr('target');
}
});
return self;
},
unlink : function() {
var self = this, doc = self.doc, range = self.range;
self.select();
if (range.collapsed) {
var a = self.commonNode({ a : '*' });
if (a) {
range.selectNode(a.get());
self.select();
}
_nativeCommand(doc, 'unlink', null);
if (_WEBKIT && K(range.startContainer).name === 'img') {
var parent = K(range.startContainer).parent();
if (parent.name === 'a') {
parent.remove(true);
}
}
} else {
_nativeCommand(doc, 'unlink', null);
}
return self;
}
});
_each(('formatblock,selectall,justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,' +
'insertunorderedlist,indent,outdent,subscript,superscript').split(','), function(i, name) {
KCmd.prototype[name] = function(val) {
var self = this;
self.select();
_nativeCommand(self.doc, name, val);
if (!_IE || _inArray(name, 'formatblock,selectall,insertorderedlist,insertunorderedlist'.split(',')) >= 0) {
self.selection();
}
return self;
};
});
_each('cut,copy,paste'.split(','), function(i, name) {
KCmd.prototype[name] = function() {
var self = this;
if (!self.doc.queryCommandSupported(name)) {
throw 'not supported';
}
self.select();
_nativeCommand(self.doc, name, null);
return self;
};
});
function _cmd(mixed) {
if (mixed.nodeName) {
var doc = _getDoc(mixed);
mixed = _range(doc).selectNodeContents(doc.body).collapse(false);
}
return new KCmd(mixed);
}
K.cmd = _cmd;
function _drag(options) {
var moveEl = options.moveEl,
moveFn = options.moveFn,
clickEl = options.clickEl || moveEl,
beforeDrag = options.beforeDrag,
iframeFix = options.iframeFix === undefined ? true : options.iframeFix;
var docs = [document],
poss = [{ x : 0, y : 0}],
listeners = [];
if (iframeFix) {
K('iframe').each(function() {
var doc;
try {
doc = _iframeDoc(this);
K(doc);
} catch(e) {
doc = null;
}
if (doc) {
docs.push(doc);
poss.push(K(this).pos());
}
});
}
clickEl.mousedown(function(e) {
var self = clickEl.get(),
x = _removeUnit(moveEl.css('left')),
y = _removeUnit(moveEl.css('top')),
width = moveEl.width(),
height = moveEl.height(),
pageX = e.pageX,
pageY = e.pageY,
dragging = true;
if (beforeDrag) {
beforeDrag();
}
_each(docs, function(i, doc) {
function moveListener(e) {
if (dragging) {
var diffX = _round(poss[i].x + e.pageX - pageX),
diffY = _round(poss[i].y + e.pageY - pageY);
moveFn.call(clickEl, x, y, width, height, diffX, diffY);
}
e.stop();
}
function selectListener(e) {
e.stop();
}
function upListener(e) {
dragging = false;
if (self.releaseCapture) {
self.releaseCapture();
}
_each(listeners, function() {
K(this.doc).unbind('mousemove', this.move)
.unbind('mouseup', this.up)
.unbind('selectstart', this.select);
});
e.stop();
}
K(doc).mousemove(moveListener)
.mouseup(upListener)
.bind('selectstart', selectListener);
listeners.push({
doc : doc,
move : moveListener,
up : upListener,
select : selectListener
});
});
if (self.setCapture) {
self.setCapture();
}
e.stop();
});
}
function KWidget(options) {
this.init(options);
}
_extend(KWidget, {
init : function(options) {
var self = this;
self.name = options.name || '';
self.doc = options.doc || document;
self.win = _getWin(self.doc);
self.x = _addUnit(options.x);
self.y = _addUnit(options.y);
self.z = options.z;
self.width = _addUnit(options.width);
self.height = _addUnit(options.height);
self.div = K('<div style="display:block;"></div>');
self.options = options;
self._alignEl = options.alignEl;
if (self.width) {
self.div.css('width', self.width);
}
if (self.height) {
self.div.css('height', self.height);
}
if (self.z) {
self.div.css({
position : 'absolute',
left : self.x,
top : self.y,
'z-index' : self.z
});
}
if (self.z && (self.x === undefined || self.y === undefined)) {
self.autoPos(self.width, self.height);
}
if (options.cls) {
self.div.addClass(options.cls);
}
if (options.shadowMode) {
self.div.addClass('ke-shadow');
}
if (options.css) {
self.div.css(options.css);
}
if (options.src) {
K(options.src).replaceWith(self.div);
} else {
K(self.doc.body).append(self.div);
}
if (options.html) {
self.div.html(options.html);
}
if (options.autoScroll) {
if (_IE && _V < 7 || _QUIRKS) {
var scrollPos = _getScrollPos();
K(self.win).bind('scroll', function(e) {
var pos = _getScrollPos(),
diffX = pos.x - scrollPos.x,
diffY = pos.y - scrollPos.y;
self.pos(_removeUnit(self.x) + diffX, _removeUnit(self.y) + diffY, false);
});
} else {
self.div.css('position', 'fixed');
}
}
},
pos : function(x, y, updateProp) {
var self = this;
updateProp = _undef(updateProp, true);
if (x !== null) {
x = x < 0 ? 0 : _addUnit(x);
self.div.css('left', x);
if (updateProp) {
self.x = x;
}
}
if (y !== null) {
y = y < 0 ? 0 : _addUnit(y);
self.div.css('top', y);
if (updateProp) {
self.y = y;
}
}
return self;
},
autoPos : function(width, height) {
var self = this,
w = _removeUnit(width) || 0,
h = _removeUnit(height) || 0,
scrollPos = _getScrollPos();
if (self._alignEl) {
var knode = K(self._alignEl),
pos = knode.pos(),
diffX = _round(knode[0].clientWidth / 2 - w / 2),
diffY = _round(knode[0].clientHeight / 2 - h / 2);
x = diffX < 0 ? pos.x : pos.x + diffX;
y = diffY < 0 ? pos.y : pos.y + diffY;
} else {
var docEl = _docElement(self.doc);
x = _round(scrollPos.x + (docEl.clientWidth - w) / 2);
y = _round(scrollPos.y + (docEl.clientHeight - h) / 2);
}
if (!(_IE && _V < 7 || _QUIRKS)) {
x -= scrollPos.x;
y -= scrollPos.y;
}
return self.pos(x, y);
},
remove : function() {
var self = this;
if (_IE && _V < 7) {
K(self.win).unbind('scroll');
}
self.div.remove();
_each(self, function(i) {
self[i] = null;
});
return this;
},
show : function() {
this.div.show();
return this;
},
hide : function() {
this.div.hide();
return this;
},
draggable : function(options) {
var self = this;
options = options || {};
options.moveEl = self.div;
options.moveFn = function(x, y, width, height, diffX, diffY) {
if ((x = x + diffX) < 0) {
x = 0;
}
if ((y = y + diffY) < 0) {
y = 0;
}
self.pos(x, y);
};
_drag(options);
return self;
}
});
function _widget(options) {
return new KWidget(options);
}
K.WidgetClass = KWidget;
K.widget = _widget;
function _iframeDoc(iframe) {
iframe = _get(iframe);
return iframe.contentDocument || iframe.contentWindow.document;
}
function _getInitHtml(themesPath, bodyClass, cssPath, cssData) {
var arr = [
'<html><head><meta charset="utf-8" /><title>KindEditor</title>',
'<style>',
'html {margin:0;padding:0;}',
'body {margin:0;padding:5px;}',
'body, td {font:12px/1.5 "sans serif",tahoma,verdana,helvetica;}',
'body, p, div {word-wrap: break-word;}',
'p {margin:5px 0;}',
'table {border-collapse:collapse;}',
'img {border:0;}',
'table.ke-zeroborder td {border:1px dotted #AAA;}',
'img.ke-flash {',
' border:1px solid #AAA;',
' background-image:url(' + themesPath + 'common/flash.gif);',
' background-position:center center;',
' background-repeat:no-repeat;',
' width:100px;',
' height:100px;',
'}',
'img.ke-rm {',
' border:1px solid #AAA;',
' background-image:url(' + themesPath + 'common/rm.gif);',
' background-position:center center;',
' background-repeat:no-repeat;',
' width:100px;',
' height:100px;',
'}',
'img.ke-media {',
' border:1px solid #AAA;',
' background-image:url(' + themesPath + 'common/media.gif);',
' background-position:center center;',
' background-repeat:no-repeat;',
' width:100px;',
' height:100px;',
'}',
'img.ke-anchor {',
' border:1px dashed #666;',
' width:16px;',
' height:16px;',
'}',
'.ke-script {',
' display:none;',
' font-size:0;',
' width:0;',
' height:0;',
'}',
'.ke-pagebreak {',
' border:1px dotted #AAA;',
' font-size:0;',
' height:2px;',
'}',
'</style>'
];
if (!_isArray(cssPath)) {
cssPath = [cssPath];
}
_each(cssPath, function(i, path) {
if (path) {
arr.push('<link href="' + path + '" rel="stylesheet" />');
}
});
if (cssData) {
arr.push('<style>' + cssData + '</style>');
}
arr.push('</head><body ' + (bodyClass ? 'class="' + bodyClass + '"' : '') + '></body></html>');
return arr.join('\n');
}
function _elementVal(knode, val) {
return knode.hasVal() ? knode.val(val) : knode.html(val);
}
function KEdit(options) {
this.init(options);
}
_extend(KEdit, KWidget, {
init : function(options) {
var self = this;
KEdit.parent.init.call(self, options);
self.srcElement = K(options.srcElement);
self.div.addClass('ke-edit');
self.designMode = _undef(options.designMode, true);
self.beforeGetHtml = options.beforeGetHtml;
self.beforeSetHtml = options.beforeSetHtml;
self.afterSetHtml = options.afterSetHtml;
var themesPath = _undef(options.themesPath, ''),
bodyClass = options.bodyClass,
cssPath = options.cssPath,
cssData = options.cssData,
isDocumentDomain = location.host.replace(/:\d+/, '') !== document.domain,
srcScript = ('document.open();' +
(isDocumentDomain ? 'document.domain="' + document.domain + '";' : '') +
'document.close();'),
iframeSrc = _IE ? ' src="javascript:void(function(){' + encodeURIComponent(srcScript) + '}())"' : '';
self.iframe = K('<iframe class="ke-edit-iframe" hidefocus="true" frameborder="0"' + iframeSrc + '></iframe>').css('width', '100%');
self.textarea = K('<textarea class="ke-edit-textarea" hidefocus="true"></textarea>').css('width', '100%');
if (self.width) {
self.setWidth(self.width);
}
if (self.height) {
self.setHeight(self.height);
}
if (self.designMode) {
self.textarea.hide();
} else {
self.iframe.hide();
}
function ready() {
var doc = _iframeDoc(self.iframe);
doc.open();
if (isDocumentDomain) {
doc.domain = document.domain;
}
doc.write(_getInitHtml(themesPath, bodyClass, cssPath, cssData));
doc.close();
self.win = self.iframe[0].contentWindow;
self.doc = doc;
var cmd = _cmd(doc);
self.afterChange(function(e) {
cmd.selection();
});
if (_WEBKIT) {
K(doc).click(function(e) {
if (K(e.target).name === 'img') {
cmd.selection(true);
cmd.range.selectNode(e.target);
cmd.select();
}
});
}
if (_IE) {
K(doc).keydown(function(e) {
if (e.which == 8) {
cmd.selection();
var rng = cmd.range;
if (rng.isControl()) {
rng.collapse(true);
K(rng.startContainer.childNodes[rng.startOffset]).remove();
e.preventDefault();
}
}
});
}
self.cmd = cmd;
self.html(_elementVal(self.srcElement));
if (_IE) {
doc.body.disabled = true;
doc.body.contentEditable = true;
doc.body.removeAttribute('disabled');
} else {
doc.designMode = 'on';
}
if (options.afterCreate) {
options.afterCreate.call(self);
}
}
if (isDocumentDomain) {
self.iframe.bind('load', function(e) {
self.iframe.unbind('load');
if (_IE) {
ready();
} else {
setTimeout(ready, 0);
}
});
}
self.div.append(self.iframe);
self.div.append(self.textarea);
self.srcElement.hide();
!isDocumentDomain && ready();
},
setWidth : function(val) {
this.div.css('width', _addUnit(val));
return this;
},
setHeight : function(val) {
var self = this;
val = _addUnit(val);
self.div.css('height', val);
self.iframe.css('height', val);
if ((_IE && _V < 8) || _QUIRKS) {
val = _addUnit(_removeUnit(val) - 2);
}
self.textarea.css('height', val);
return self;
},
remove : function() {
var self = this, doc = self.doc;
K(doc.body).unbind();
K(doc).unbind();
K(self.win).unbind();
_elementVal(self.srcElement, self.html());
self.srcElement.show();
doc.write('');
self.iframe.unbind();
self.textarea.unbind();
KEdit.parent.remove.call(self);
},
html : function(val, isFull) {
var self = this, doc = self.doc;
if (self.designMode) {
var body = doc.body;
if (val === undefined) {
if (isFull) {
val = '<!doctype html><html>' + body.parentNode.innerHTML + '</html>';
} else {
val = body.innerHTML;
}
if (self.beforeGetHtml) {
val = self.beforeGetHtml(val);
}
if (_GECKO && val == '<br />') {
val = '';
}
return val;
}
if (self.beforeSetHtml) {
val = self.beforeSetHtml(val);
}
K(body).html(val);
if (self.afterSetHtml) {
self.afterSetHtml();
}
return self;
}
if (val === undefined) {
return self.textarea.val();
}
self.textarea.val(val);
return self;
},
design : function(bool) {
var self = this, val;
if (bool === undefined ? !self.designMode : bool) {
if (!self.designMode) {
val = self.html();
self.designMode = true;
self.html(val);
self.textarea.hide();
self.iframe.show();
}
} else {
if (self.designMode) {
val = self.html();
self.designMode = false;
self.html(val);
self.iframe.hide();
self.textarea.show();
}
}
return self.focus();
},
focus : function() {
var self = this;
self.designMode ? self.win.focus() : self.textarea[0].focus();
return self;
},
blur : function() {
var self = this;
if (_IE) {
var input = K('<input type="text" style="float:left;width:0;height:0;padding:0;margin:0;border:0;" value="" />', self.div);
self.div.append(input);
input[0].focus();
input.remove();
} else {
self.designMode ? self.win.blur() : self.textarea[0].blur();
}
return self;
},
afterChange : function(fn) {
var self = this, doc = self.doc, body = doc.body;
K(doc).keyup(function(e) {
if (!e.ctrlKey && !e.altKey && _CHANGE_KEY_MAP[e.which]) {
fn(e);
}
});
K(doc).mouseup(fn).contextmenu(fn);
K(self.win).blur(fn);
function timeoutHandler(e) {
setTimeout(function() {
fn(e);
}, 1);
}
K(body).bind('paste', timeoutHandler);
K(body).bind('cut', timeoutHandler);
return self;
}
});
function _edit(options) {
return new KEdit(options);
}
K.edit = _edit;
K.iframeDoc = _iframeDoc;
function _selectToolbar(name, fn) {
var self = this,
knode = self.get(name);
if (knode) {
if (knode.hasClass('ke-disabled')) {
return;
}
fn(knode);
}
}
function KToolbar(options) {
this.init(options);
}
_extend(KToolbar, KWidget, {
init : function(options) {
var self = this;
KToolbar.parent.init.call(self, options);
self.disableMode = _undef(options.disableMode, false);
self.noDisableItemMap = _toMap(_undef(options.noDisableItems, []));
self._itemMap = {};
self.div.addClass('ke-toolbar').bind('contextmenu,mousedown,mousemove', function(e) {
e.preventDefault();
}).attr('unselectable', 'on');
function find(target) {
var knode = K(target);
if (knode.hasClass('ke-outline')) {
return knode;
}
if (knode.hasClass('ke-toolbar-icon')) {
return knode.parent();
}
}
function hover(e, method) {
var knode = find(e.target);
if (knode) {
if (knode.hasClass('ke-disabled')) {
return;
}
if (knode.hasClass('ke-selected')) {
return;
}
knode[method]('ke-on');
}
}
self.div.mouseover(function(e) {
hover(e, 'addClass');
})
.mouseout(function(e) {
hover(e, 'removeClass');
})
.click(function(e) {
var knode = find(e.target);
if (knode) {
if (knode.hasClass('ke-disabled')) {
return;
}
self.options.click.call(this, e, knode.attr('data-name'));
}
});
},
get : function(name) {
if (this._itemMap[name]) {
return this._itemMap[name];
}
return (this._itemMap[name] = K('span.ke-icon-' + name, this.div).parent());
},
select : function(name) {
_selectToolbar.call(this, name, function(knode) {
knode.addClass('ke-selected');
});
return self;
},
unselect : function(name) {
_selectToolbar.call(this, name, function(knode) {
knode.removeClass('ke-selected').removeClass('ke-on');
});
return self;
},
enable : function(name) {
var self = this,
knode = name.get ? name : self.get(name);
if (knode) {
knode.removeClass('ke-disabled');
knode.opacity(1);
}
return self;
},
disable : function(name) {
var self = this,
knode = name.get ? name : self.get(name);
if (knode) {
knode.removeClass('ke-selected').addClass('ke-disabled');
knode.opacity(0.5);
}
return self;
},
disableAll : function(bool, noDisableItems) {
var self = this, map = self.noDisableItemMap, item;
if (noDisableItems) {
map = _toMap(noDisableItems);
}
if (bool === undefined ? !self.disableMode : bool) {
K('span.ke-outline', self.div).each(function() {
var knode = K(this),
name = knode[0].getAttribute('data-name', 2);
if (!map[name]) {
self.disable(knode);
}
});
self.disableMode = true;
} else {
K('span.ke-outline', self.div).each(function() {
var knode = K(this),
name = knode[0].getAttribute('data-name', 2);
if (!map[name]) {
self.enable(knode);
}
});
self.disableMode = false;
}
return self;
}
});
function _toolbar(options) {
return new KToolbar(options);
}
K.toolbar = _toolbar;
function KMenu(options) {
this.init(options);
}
_extend(KMenu, KWidget, {
init : function(options) {
var self = this;
options.z = options.z || 811213;
KMenu.parent.init.call(self, options);
self.centerLineMode = _undef(options.centerLineMode, true);
self.div.addClass('ke-menu').bind('click,mousedown', function(e){
e.stopPropagation();
}).attr('unselectable', 'on');
},
addItem : function(item) {
var self = this;
if (item.title === '-') {
self.div.append(K('<div class="ke-menu-separator"></div>'));
return;
}
var itemDiv = K('<div class="ke-menu-item" unselectable="on"></div>'),
leftDiv = K('<div class="ke-inline-block ke-menu-item-left"></div>'),
rightDiv = K('<div class="ke-inline-block ke-menu-item-right"></div>'),
height = _addUnit(item.height),
iconClass = _undef(item.iconClass, '');
self.div.append(itemDiv);
if (height) {
itemDiv.css('height', height);
rightDiv.css('line-height', height);
}
var centerDiv;
if (self.centerLineMode) {
centerDiv = K('<div class="ke-inline-block ke-menu-item-center"></div>');
if (height) {
centerDiv.css('height', height);
}
}
itemDiv.mouseover(function(e) {
K(this).addClass('ke-menu-item-on');
if (centerDiv) {
centerDiv.addClass('ke-menu-item-center-on');
}
})
.mouseout(function(e) {
K(this).removeClass('ke-menu-item-on');
if (centerDiv) {
centerDiv.removeClass('ke-menu-item-center-on');
}
})
.click(function(e) {
item.click.call(K(this));
e.stopPropagation();
})
.append(leftDiv);
if (centerDiv) {
itemDiv.append(centerDiv);
}
itemDiv.append(rightDiv);
if (item.checked) {
iconClass = 'ke-icon-checked';
}
if (iconClass !== '') {
leftDiv.html('<span class="ke-inline-block ke-toolbar-icon ke-toolbar-icon-url ' + iconClass + '"></span>');
}
rightDiv.html(item.title);
return self;
},
remove : function() {
var self = this;
if (self.options.beforeRemove) {
self.options.beforeRemove.call(self);
}
K('.ke-menu-item', self.div[0]).unbind();
KMenu.parent.remove.call(self);
return self;
}
});
function _menu(options) {
return new KMenu(options);
}
K.menu = _menu;
function KColorPicker(options) {
this.init(options);
}
_extend(KColorPicker, KWidget, {
init : function(options) {
var self = this;
options.z = options.z || 811213;
KColorPicker.parent.init.call(self, options);
var colors = options.colors || [
['#E53333', '#E56600', '#FF9900', '#64451D', '#DFC5A4', '#FFE500'],
['#009900', '#006600', '#99BB00', '#B8D100', '#60D978', '#00D5FF'],
['#337FE5', '#003399', '#4C33E5', '#9933E5', '#CC33E5', '#EE33EE'],
['#FFFFFF', '#CCCCCC', '#999999', '#666666', '#333333', '#000000']
];
self.selectedColor = (options.selectedColor || '').toLowerCase();
self._cells = [];
self.div.addClass('ke-colorpicker').bind('click,mousedown', function(e){
e.stopPropagation();
}).attr('unselectable', 'on');
var table = self.doc.createElement('table');
self.div.append(table);
table.className = 'ke-colorpicker-table';
table.cellPadding = 0;
table.cellSpacing = 0;
table.border = 0;
var row = table.insertRow(0), cell = row.insertCell(0);
cell.colSpan = colors[0].length;
self._addAttr(cell, '', 'ke-colorpicker-cell-top');
for (var i = 0; i < colors.length; i++) {
row = table.insertRow(i + 1);
for (var j = 0; j < colors[i].length; j++) {
cell = row.insertCell(j);
self._addAttr(cell, colors[i][j], 'ke-colorpicker-cell');
}
}
},
_addAttr : function(cell, color, cls) {
var self = this;
cell = K(cell).addClass(cls);
if (self.selectedColor === color.toLowerCase()) {
cell.addClass('ke-colorpicker-cell-selected');
}
cell.attr('title', color || self.options.noColor);
cell.mouseover(function(e) {
K(this).addClass('ke-colorpicker-cell-on');
});
cell.mouseout(function(e) {
K(this).removeClass('ke-colorpicker-cell-on');
});
cell.click(function(e) {
e.stop();
self.options.click.call(K(this), color);
});
if (color) {
cell.append(K('<div class="ke-colorpicker-cell-color" unselectable="on"></div>').css('background-color', color));
} else {
cell.html(self.options.noColor);
}
K(cell).attr('unselectable', 'on');
self._cells.push(cell);
},
remove : function() {
var self = this;
_each(self._cells, function() {
this.unbind();
});
KColorPicker.parent.remove.call(self);
return self;
}
});
function _colorpicker(options) {
return new KColorPicker(options);
}
K.colorpicker = _colorpicker;
function KUploadButton(options) {
this.init(options);
}
_extend(KUploadButton, {
init : function(options) {
var self = this,
button = K(options.button),
fieldName = options.fieldName || 'file',
url = options.url || '',
title = button.val(),
cls = button[0].className || '',
target = 'kindeditor_upload_iframe_' + new Date().getTime();
options.afterError = options.afterError || function(str) {
alert(str);
};
var html = [
'<div class="ke-inline-block ' + cls + '">',
'<iframe name="' + target + '" style="display:none;"></iframe>',
'<form class="ke-upload-area ke-form" method="post" enctype="multipart/form-data" target="' + target + '" action="' + url + '">',
'<span class="ke-button-common">',
'<input type="button" class="ke-button-common ke-button" value="' + title + '" />',
'</span>',
'<input type="file" class="ke-upload-file" name="' + fieldName + '" tabindex="-1" />',
'</form></div>'].join('');
var div = K(html, button.doc);
button.hide();
button.before(div);
self.div = div;
self.button = button;
self.iframe = K('iframe', div);
self.form = K('form', div);
self.fileBox = K('.ke-upload-file', div).width(K('.ke-button-common').width());
self.options = options;
},
submit : function() {
var self = this,
iframe = self.iframe;
iframe.bind('load', function() {
iframe.unbind();
var doc = K.iframeDoc(iframe),
pre = doc.getElementsByTagName('pre')[0],
str = '', data;
if (pre) {
str = pre.innerHTML;
} else {
str = doc.body.innerHTML;
}
try {
data = K.json(str);
} catch (e) {
self.options.afterError.call(self, '<!doctype html><html>' + doc.body.parentNode.innerHTML + '</html>');
}
if (data) {
self.options.afterUpload.call(self, data);
}
});
self.form[0].submit();
var tempForm = document.createElement('form');
self.fileBox.before(tempForm);
K(tempForm).append(self.fileBox);
tempForm.reset();
K(tempForm).remove(true);
return self;
},
remove : function() {
var self = this;
if (self.fileBox) {
self.fileBox.unbind();
}
self.div.remove();
self.button.show();
return self;
}
});
function _uploadbutton(options) {
return new KUploadButton(options);
}
K.uploadbutton = _uploadbutton;
function _createButton(arg) {
arg = arg || {};
var name = arg.name || '',
span = K('<span class="ke-button-common ke-button-outer" title="' + name + '"></span>'),
btn = K('<input class="ke-button-common ke-button" type="button" value="' + name + '" />');
if (arg.click) {
btn.click(arg.click);
}
span.append(btn);
return span;
}
function KDialog(options) {
this.init(options);
}
_extend(KDialog, KWidget, {
init : function(options) {
var self = this;
var shadowMode = _undef(options.shadowMode, true);
options.z = options.z || 811213;
options.shadowMode = false;
KDialog.parent.init.call(self, options);
var title = options.title,
body = K(options.body, self.doc),
previewBtn = options.previewBtn,
yesBtn = options.yesBtn,
noBtn = options.noBtn,
closeBtn = options.closeBtn,
showMask = _undef(options.showMask, true);
self.div.addClass('ke-dialog').bind('click,mousedown', function(e){
e.stopPropagation();
});
var contentDiv = K('<div class="ke-dialog-content"></div>').appendTo(self.div);
if (_IE && _V < 7) {
self.iframeMask = K('<iframe src="about:blank" class="ke-dialog-shadow"></iframe>').appendTo(self.div);
} else if (shadowMode) {
K('<div class="ke-dialog-shadow"></div>').appendTo(self.div);
}
var headerDiv = K('<div class="ke-dialog-header"></div>');
contentDiv.append(headerDiv);
headerDiv.html(title);
self.closeIcon = K('<span class="ke-dialog-icon-close" title="' + closeBtn.name + '"></span>').click(closeBtn.click);
headerDiv.append(self.closeIcon);
self.draggable({
clickEl : headerDiv,
beforeDrag : options.beforeDrag
});
var bodyDiv = K('<div class="ke-dialog-body"></div>');
contentDiv.append(bodyDiv);
bodyDiv.append(body);
var footerDiv = K('<div class="ke-dialog-footer"></div>');
if (previewBtn || yesBtn || noBtn) {
contentDiv.append(footerDiv);
}
_each([
{ btn : previewBtn, name : 'preview' },
{ btn : yesBtn, name : 'yes' },
{ btn : noBtn, name : 'no' }
], function() {
if (this.btn) {
var button = _createButton(this.btn);
button.addClass('ke-dialog-' + this.name);
footerDiv.append(button);
}
});
if (self.height) {
bodyDiv.height(_removeUnit(self.height) - headerDiv.height() - footerDiv.height());
}
self.div.width(self.div.width());
self.div.height(self.div.height());
self.mask = null;
if (showMask) {
var docEl = _docElement(self.doc),
docWidth = Math.max(docEl.scrollWidth, docEl.clientWidth),
docHeight = Math.max(docEl.scrollHeight, docEl.clientHeight);
self.mask = _widget({
x : 0,
y : 0,
z : self.z - 1,
cls : 'ke-dialog-mask',
width : docWidth,
height : docHeight
});
}
self.autoPos(self.div.width(), self.div.height());
self.footerDiv = footerDiv;
self.bodyDiv = bodyDiv;
self.headerDiv = headerDiv;
},
setMaskIndex : function(z) {
var self = this;
self.mask.div.css('z-index', z);
},
showLoading : function(msg) {
msg = _undef(msg, '');
var self = this, body = self.bodyDiv;
self.loading = K('<div class="ke-dialog-loading"><div class="ke-inline-block ke-dialog-loading-content" style="margin-top:' + Math.round(body.height() / 3) + 'px;">' + msg + '</div></div>')
.width(body.width()).height(body.height())
.css('top', self.headerDiv.height() + 'px');
body.css('visibility', 'hidden').after(self.loading);
return self;
},
hideLoading : function() {
this.loading && this.loading.remove();
this.bodyDiv.css('visibility', 'visible');
return this;
},
remove : function() {
var self = this;
if (self.options.beforeRemove) {
self.options.beforeRemove.call(self);
}
self.mask && self.mask.remove();
self.iframeMask && self.iframeMask.remove();
self.closeIcon.unbind();
K('input', self.div).unbind();
self.footerDiv.unbind();
self.bodyDiv.unbind();
self.headerDiv.unbind();
KDialog.parent.remove.call(self);
return self;
}
});
function _dialog(options) {
return new KDialog(options);
}
K.dialog = _dialog;
function _tabs(options) {
var self = _widget(options),
remove = self.remove,
afterSelect = options.afterSelect,
div = self.div,
liList = [];
div.addClass('ke-tabs')
.bind('contextmenu,mousedown,mousemove', function(e) {
e.preventDefault();
});
var ul = K('<ul class="ke-tabs-ul ke-clearfix"></ul>');
div.append(ul);
self.add = function(tab) {
var li = K('<li class="ke-tabs-li">' + tab.title + '</li>');
li.data('tab', tab);
liList.push(li);
ul.append(li);
};
self.selectedIndex = 0;
self.select = function(index) {
self.selectedIndex = index;
_each(liList, function(i, li) {
li.unbind();
if (i === index) {
li.addClass('ke-tabs-li-selected');
K(li.data('tab').panel).show('');
} else {
li.removeClass('ke-tabs-li-selected').removeClass('ke-tabs-li-on')
.mouseover(function() {
K(this).addClass('ke-tabs-li-on');
})
.mouseout(function() {
K(this).removeClass('ke-tabs-li-on');
})
.click(function() {
self.select(i);
});
K(li.data('tab').panel).hide();
}
});
if (afterSelect) {
afterSelect.call(self, index);
}
};
self.remove = function() {
_each(liList, function() {
this.remove();
});
ul.remove();
remove.call(self);
};
return self;
}
K.tabs = _tabs;
function _loadScript(url, fn) {
var head = document.getElementsByTagName('head')[0] || (_QUIRKS ? document.body : document.documentElement),
script = document.createElement('script');
head.appendChild(script);
script.src = url;
script.charset = 'utf-8';
script.onload = script.onreadystatechange = function() {
if (!this.readyState || this.readyState === 'loaded') {
if (fn) {
fn();
}
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
}
function _loadStyle(url) {
var head = document.getElementsByTagName('head')[0] || (_QUIRKS ? document.body : document.documentElement),
link = document.createElement('link'),
absoluteUrl = _formatUrl(url, 'absolute');
var links = K('link[rel="stylesheet"]', head);
for (var i = 0, len = links.length; i < len; i++) {
if (_formatUrl(links[i].href, 'absolute') === absoluteUrl) {
return;
}
}
head.appendChild(link);
link.href = url;
link.rel = 'stylesheet';
}
function _ajax(url, fn, method, param, dataType) {
method = method || 'GET';
dataType = dataType || 'json';
var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open(method, url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
if (fn) {
var data = _trim(xhr.responseText);
if (dataType == 'json') {
data = _json(data);
}
fn(data);
}
}
};
if (method == 'POST') {
var params = [];
_each(param, function(key, val) {
params.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));
});
try {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
} catch (e) {}
xhr.send(params.join('&'));
} else {
xhr.send(null);
}
}
K.loadScript = _loadScript;
K.loadStyle = _loadStyle;
K.ajax = _ajax;
var _plugins = {};
function _plugin(name, fn) {
if (!fn) {
return _plugins[name];
}
_plugins[name] = fn;
}
var _language = {};
function _parseLangKey(key) {
var match, ns = 'core';
if ((match = /^(\w+)\.(\w+)$/.exec(key))) {
ns = match[1];
key = match[2];
}
return { ns : ns, key : key };
}
function _lang(mixed, langType) {
langType = langType === undefined ? K.options.langType : langType;
if (typeof mixed === 'string') {
if (!_language[langType]) {
return 'no language';
}
var pos = mixed.length - 1;
if (mixed.substr(pos) === '.') {
return _language[langType][mixed.substr(0, pos)];
}
var obj = _parseLangKey(mixed);
return _language[langType][obj.ns][obj.key];
}
_each(mixed, function(key, val) {
var obj = _parseLangKey(key);
if (!_language[langType]) {
_language[langType] = {};
}
if (!_language[langType][obj.ns]) {
_language[langType][obj.ns] = {};
}
_language[langType][obj.ns][obj.key] = val;
});
}
function _getImageFromRange(range, fn) {
if (range.collapsed) {
return;
}
range = range.cloneRange().up();
var sc = range.startContainer, so = range.startOffset;
if (!_WEBKIT && !range.isControl()) {
return;
}
var img = K(sc.childNodes[so]);
if (!img || img.name != 'img') {
return;
}
if (fn(img)) {
return img;
}
}
function _bindContextmenuEvent() {
var self = this, doc = self.edit.doc;
K(doc).contextmenu(function(e) {
if (self.menu) {
self.hideMenu();
}
if (!self.useContextmenu) {
e.preventDefault();
return;
}
if (self._contextmenus.length === 0) {
return;
}
var maxWidth = 0, items = [];
_each(self._contextmenus, function() {
if (this.title == '-') {
items.push(this);
return;
}
if (this.cond && this.cond()) {
items.push(this);
if (this.width && this.width > maxWidth) {
maxWidth = this.width;
}
}
});
while (items.length > 0 && items[0].title == '-') {
items.shift();
}
while (items.length > 0 && items[items.length - 1].title == '-') {
items.pop();
}
var prevItem = null;
_each(items, function(i) {
if (this.title == '-' && prevItem.title == '-') {
delete items[i];
}
prevItem = this;
});
if (items.length > 0) {
e.preventDefault();
var pos = K(self.edit.iframe).pos(),
menu = _menu({
x : pos.x + e.clientX,
y : pos.y + e.clientY,
width : maxWidth,
css : { visibility: 'hidden' },
shadowMode : self.shadowMode
});
_each(items, function() {
if (this.title) {
menu.addItem(this);
}
});
var docEl = _docElement(menu.doc),
menuHeight = menu.div.height();
if (e.clientY + menuHeight >= docEl.clientHeight - 100) {
menu.pos(menu.x, _removeUnit(menu.y) - menuHeight);
}
menu.div.css('visibility', 'visible');
self.menu = menu;
}
});
}
function _bindNewlineEvent() {
var self = this, doc = self.edit.doc, newlineTag = self.newlineTag;
if (_IE && newlineTag !== 'br') {
return;
}
if (_GECKO && _V < 3 && newlineTag !== 'p') {
return;
}
if (_OPERA) {
return;
}
var brSkipTagMap = _toMap('h1,h2,h3,h4,h5,h6,pre,li'),
pSkipTagMap = _toMap('p,h1,h2,h3,h4,h5,h6,pre,li,blockquote');
function getAncestorTagName(range) {
var ancestor = K(range.commonAncestor());
while (ancestor) {
if (ancestor.type == 1 && !ancestor.isStyle()) {
break;
}
ancestor = ancestor.parent();
}
return ancestor.name;
}
K(doc).keydown(function(e) {
if (e.which != 13 || e.shiftKey || e.ctrlKey || e.altKey) {
return;
}
self.cmd.selection();
var tagName = getAncestorTagName(self.cmd.range);
if (tagName == 'marquee' || tagName == 'select') {
return;
}
if (newlineTag === 'br' && !brSkipTagMap[tagName]) {
e.preventDefault();
self.insertHtml('<br />');
return;
}
if (!pSkipTagMap[tagName]) {
_nativeCommand(doc, 'formatblock', '<p>');
}
});
K(doc).keyup(function(e) {
if (e.which != 13 || e.shiftKey || e.ctrlKey || e.altKey) {
return;
}
if (newlineTag == 'br') {
return;
}
self.cmd.selection();
var tagName = getAncestorTagName(self.cmd.range);
if (tagName == 'marquee' || tagName == 'select') {
return;
}
if (!pSkipTagMap[tagName]) {
_nativeCommand(doc, 'formatblock', '<p>');
}
var div = self.cmd.commonAncestor('div');
if (div) {
var p = K('<p></p>'),
child = div[0].firstChild;
while (child) {
var next = child.nextSibling;
p.append(child);
child = next;
}
div.before(p);
div.remove();
self.cmd.range.selectNodeContents(p[0]);
self.cmd.select();
}
});
}
function _bindTabEvent() {
var self = this, doc = self.edit.doc;
K(doc).keydown(function(e) {
if (e.which == 9) {
e.preventDefault();
if (self.afterTab) {
self.afterTab.call(self, e);
return;
}
var cmd = self.cmd, range = cmd.range;
range.shrink();
if (range.collapsed && range.startContainer.nodeType == 1) {
range.insertNode(K('@ ', doc)[0]);
cmd.select();
}
self.insertHtml(' ');
}
});
}
function _bindFocusEvent() {
var self = this;
K(self.edit.textarea[0], self.edit.win).focus(function(e) {
if (self.afterFocus) {
self.afterFocus.call(self, e);
}
}).blur(function(e) {
if (self.afterBlur) {
self.afterBlur.call(self, e);
}
});
}
function _removeBookmarkTag(html) {
return _trim(html.replace(/<span [^>]*id="?__kindeditor_bookmark_\w+_\d+__"?[^>]*><\/span>/ig, ''));
}
function _removeTempTag(html) {
return html.replace(/<div[^>]+class="?__kindeditor_paste__"?[^>]*>[\s\S]*?<\/div>/ig, '');
}
function _addBookmarkToStack(stack, bookmark) {
if (stack.length === 0) {
stack.push(bookmark);
return;
}
var prev = stack[stack.length - 1];
if (_removeBookmarkTag(bookmark.html) !== _removeBookmarkTag(prev.html)) {
stack.push(bookmark);
}
}
function _undoToRedo(fromStack, toStack) {
var self = this, edit = self.edit,
body = edit.doc.body,
range, bookmark;
if (fromStack.length === 0) {
return self;
}
if (edit.designMode) {
range = self.cmd.range;
bookmark = range.createBookmark(true);
bookmark.html = body.innerHTML;
} else {
bookmark = {
html : body.innerHTML
};
}
_addBookmarkToStack(toStack, bookmark);
var prev = fromStack.pop();
if (_removeBookmarkTag(bookmark.html) === _removeBookmarkTag(prev.html) && fromStack.length > 0) {
prev = fromStack.pop();
}
if (edit.designMode) {
edit.html(prev.html);
if (prev.start) {
range.moveToBookmark(prev);
self.select();
}
} else {
K(body).html(_removeBookmarkTag(prev.html));
}
return self;
}
function KEditor(options) {
var self = this;
self.options = {};
function setOption(key, val) {
if (KEditor.prototype[key] === undefined) {
self[key] = val;
}
self.options[key] = val;
}
_each(options, function(key, val) {
setOption(key, options[key]);
});
_each(K.options, function(key, val) {
if (self[key] === undefined) {
setOption(key, val);
}
});
setOption('width', _undef(self.width, self.minWidth));
setOption('height', _undef(self.height, self.minHeight));
setOption('width', _addUnit(self.width));
setOption('height', _addUnit(self.height));
if (_MOBILE && (!_IOS || _V < 534)) {
self.designMode = false;
}
var se = K(self.srcElement || '<textarea/>');
self.srcElement = se;
self.initContent = _elementVal(se);
self.plugin = {};
self.isCreated = false;
self.isLoading = false;
self._handlers = {};
self._contextmenus = [];
self._undoStack = [];
self._redoStack = [];
self._calledPlugins = {};
self._firstAddBookmark = true;
self.menu = self.contextmenu = null;
self.dialogs = [];
}
KEditor.prototype = {
lang : function(mixed) {
return _lang(mixed, this.langType);
},
loadPlugin : function(name, fn) {
var self = this;
if (_plugins[name]) {
if (self._calledPlugins[name]) {
if (fn) {
fn.call(self);
}
return self;
}
_plugins[name].call(self, KindEditor);
if (fn) {
fn.call(self);
}
self._calledPlugins[name] = true;
return self;
}
if (self.isLoading) {
return self;
}
self.isLoading = true;
_loadScript(self.pluginsPath + name + '/' + name + '.js?ver=' + encodeURIComponent(K.DEBUG ? _TIME : _VERSION), function() {
self.isLoading = false;
if (_plugins[name]) {
self.loadPlugin(name, fn);
}
});
return self;
},
handler : function(key, fn) {
var self = this;
if (!self._handlers[key]) {
self._handlers[key] = [];
}
if (_isFunction(fn)) {
self._handlers[key].push(fn);
return self;
}
_each(self._handlers[key], function() {
fn = this.call(self, fn);
});
return fn;
},
clickToolbar : function(name, fn) {
var self = this, key = 'clickToolbar' + name;
if (fn === undefined) {
if (self._handlers[key]) {
return self.handler(key);
}
self.loadPlugin(name, function() {
self.handler(key);
});
return self;
}
return self.handler(key, fn);
},
updateState : function() {
var self = this;
_each(('justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,insertunorderedlist,' +
'subscript,superscript,bold,italic,underline,strikethrough').split(','), function(i, name) {
self.cmd.state(name) ? self.toolbar.select(name) : self.toolbar.unselect(name);
});
return self;
},
addContextmenu : function(item) {
this._contextmenus.push(item);
return this;
},
afterCreate : function(fn) {
return this.handler('afterCreate', fn);
},
beforeRemove : function(fn) {
return this.handler('beforeRemove', fn);
},
beforeGetHtml : function(fn) {
return this.handler('beforeGetHtml', fn);
},
beforeSetHtml : function(fn) {
return this.handler('beforeSetHtml', fn);
},
afterSetHtml : function(fn) {
return this.handler('afterSetHtml', fn);
},
create : function() {
var self = this, fullscreenMode = self.fullscreenMode;
if (self.isCreated) {
return self;
}
if (fullscreenMode) {
_docElement().style.overflow = 'hidden';
} else {
_docElement().style.overflow = '';
}
var width = fullscreenMode ? _docElement().clientWidth + 'px' : self.width,
height = fullscreenMode ? _docElement().clientHeight + 'px' : self.height;
if ((_IE && _V < 8) || _QUIRKS) {
height = _addUnit(_removeUnit(height) + 2);
}
var container = self.container = K(self.layout);
if (fullscreenMode) {
K(document.body).append(container);
} else {
self.srcElement.before(container);
}
var toolbarDiv = K('.toolbar', container),
editDiv = K('.edit', container),
statusbar = self.statusbar = K('.statusbar', container);
container.removeClass('container')
.addClass('ke-container ke-container-' + self.themeType).css('width', width);
if (fullscreenMode) {
container.css({
position : 'absolute',
left : 0,
top : 0,
'z-index' : 811211
});
if (!_GECKO) {
self._scrollPos = _getScrollPos();
}
window.scrollTo(0, 0);
K(document.body).css({
'height' : '1px',
'overflow' : 'hidden'
});
K(document.body.parentNode).css('overflow', 'hidden');
} else {
if (self._scrollPos) {
K(document.body).css({
'height' : '',
'overflow' : ''
});
K(document.body.parentNode).css('overflow', '');
window.scrollTo(self._scrollPos.x, self._scrollPos.y);
}
}
var htmlList = [];
K.each(self.items, function(i, name) {
if (name == '|') {
htmlList.push('<span class="ke-inline-block ke-separator"></span>');
} else if (name == '/') {
htmlList.push('<div class="ke-hr"></div>');
} else {
htmlList.push('<span class="ke-outline" data-name="' + name + '" title="' + self.lang(name) + '" unselectable="on">');
htmlList.push('<span class="ke-toolbar-icon ke-toolbar-icon-url ke-icon-' + name + '" unselectable="on"></span></span>');
}
});
var toolbar = self.toolbar = _toolbar({
src : toolbarDiv,
html : htmlList.join(''),
noDisableItems : self.noDisableItems,
click : function(e, name) {
e.stop();
if (self.menu) {
var menuName = self.menu.name;
self.hideMenu();
if (menuName === name) {
return;
}
}
self.clickToolbar(name);
}
});
var editHeight = _removeUnit(height) - toolbar.div.height();
var edit = self.edit = _edit({
height : editHeight > 0 && _removeUnit(height) > self.minHeight ? editHeight : self.minHeight,
src : editDiv,
srcElement : self.srcElement,
designMode : self.designMode,
themesPath : self.themesPath,
bodyClass : self.bodyClass,
cssPath : self.cssPath,
cssData : self.cssData,
beforeGetHtml : function(html) {
html = self.beforeGetHtml(html);
return _formatHtml(html, self.filterMode ? self.htmlTags : null, self.urlType, self.wellFormatMode, self.indentChar);
},
beforeSetHtml : function(html) {
html = _formatHtml(html, self.filterMode ? self.htmlTags : null, '', false);
return self.beforeSetHtml(html);
},
afterSetHtml : function() {
self.edit = edit = this;
self.afterSetHtml();
},
afterCreate : function() {
self.edit = edit = this;
self.cmd = edit.cmd;
self._docMousedownFn = function(e) {
if (self.menu) {
self.hideMenu();
}
};
K(edit.doc, document).mousedown(self._docMousedownFn);
_bindContextmenuEvent.call(self);
_bindNewlineEvent.call(self);
_bindTabEvent.call(self);
_bindFocusEvent.call(self);
edit.afterChange(function(e) {
if (!edit.designMode) {
return;
}
self.updateState();
self.addBookmark();
if (self.options.afterChange) {
self.options.afterChange.call(self);
}
});
edit.textarea.keyup(function(e) {
if (!e.ctrlKey && !e.altKey && _INPUT_KEY_MAP[e.which]) {
if (self.options.afterChange) {
self.options.afterChange.call(self);
}
}
});
if (self.readonlyMode) {
self.readonly();
}
self.isCreated = true;
self.initContent = self.html();
self.afterCreate();
if (self.options.afterCreate) {
self.options.afterCreate.call(self);
}
}
});
statusbar.removeClass('statusbar').addClass('ke-statusbar')
.append('<span class="ke-inline-block ke-statusbar-center-icon"></span>')
.append('<span class="ke-inline-block ke-statusbar-right-icon"></span>');
K(window).unbind('resize');
function initResize() {
if (statusbar.height() === 0) {
setTimeout(initResize, 100);
return;
}
self.resize(width, height);
}
initResize();
function newResize(width, height, updateProp) {
updateProp = _undef(updateProp, true);
if (width && width >= self.minWidth) {
self.resize(width, null);
if (updateProp) {
self.width = _addUnit(width);
}
}
if (height && height >= self.minHeight) {
self.resize(null, height);
if (updateProp) {
self.height = _addUnit(height);
}
}
}
if (fullscreenMode) {
K(window).bind('resize', function(e) {
if (self.isCreated) {
newResize(_docElement().clientWidth, _docElement().clientHeight, false);
}
});
toolbar.select('fullscreen');
statusbar.first().css('visibility', 'hidden');
statusbar.last().css('visibility', 'hidden');
} else {
if (_GECKO) {
K(window).bind('scroll', function(e) {
self._scrollPos = _getScrollPos();
});
}
if (self.resizeType > 0) {
_drag({
moveEl : container,
clickEl : statusbar,
moveFn : function(x, y, width, height, diffX, diffY) {
height += diffY;
newResize(null, height);
}
});
} else {
statusbar.first().css('visibility', 'hidden');
}
if (self.resizeType === 2) {
_drag({
moveEl : container,
clickEl : statusbar.last(),
moveFn : function(x, y, width, height, diffX, diffY) {
width += diffX;
height += diffY;
newResize(width, height);
}
});
} else {
statusbar.last().css('visibility', 'hidden');
}
}
return self;
},
remove : function() {
var self = this;
if (!self.isCreated) {
return self;
}
self.beforeRemove();
if (self.menu) {
self.hideMenu();
}
_each(self.dialogs, function() {
self.hideDialog();
});
K(document).unbind('mousedown', self._docMousedownFn);
self.toolbar.remove();
self.edit.remove();
self.statusbar.last().unbind();
self.statusbar.unbind();
self.container.remove();
self.container = self.toolbar = self.edit = self.menu = null;
self.dialogs = [];
self.isCreated = false;
return self;
},
resize : function(width, height) {
var self = this;
if (width !== null) {
if (_removeUnit(width) > self.minWidth) {
self.container.css('width', _addUnit(width));
}
}
if (height !== null) {
height = _removeUnit(height) - self.toolbar.div.height() - self.statusbar.height();
if (height > 0 && _removeUnit(height) > self.minHeight) {
self.edit.setHeight(height);
}
}
return self;
},
select : function() {
this.isCreated && this.cmd.select();
return this;
},
html : function(val) {
var self = this;
if (val === undefined) {
return self.isCreated ? self.edit.html() : _elementVal(self.srcElement);
}
self.isCreated ? self.edit.html(val) : _elementVal(self.srcElement, val);
return self;
},
fullHtml : function() {
return this.isCreated ? this.edit.html(undefined, true) : '';
},
text : function(val) {
var self = this;
if (val === undefined) {
return _trim(self.html().replace(/<(?!img|embed).*?>/ig, '').replace(/ /ig, ' '));
} else {
return self.html(_escape(val));
}
},
isEmpty : function() {
return _trim(this.text().replace(/\r\n|\n|\r/, '')) === '';
},
isDirty : function() {
return _trim(this.initContent.replace(/\r\n|\n|\r|t/g, '')) !== _trim(this.html().replace(/\r\n|\n|\r|t/g, ''));
},
selectedHtml : function() {
return this.isCreated ? this.cmd.range.html() : '';
},
count : function(mode) {
var self = this;
mode = (mode || 'html').toLowerCase();
if (mode === 'html') {
return _removeBookmarkTag(_removeTempTag(self.html())).length;
}
if (mode === 'text') {
return self.text().replace(/<(?:img|embed).*?>/ig, 'K').replace(/\r\n|\n|\r/g, '').length;
}
return 0;
},
exec : function(key) {
key = key.toLowerCase();
var self = this, cmd = self.cmd,
changeFlag = _inArray(key, 'selectall,copy,paste,print'.split(',')) < 0;
if (changeFlag) {
self.addBookmark(false);
}
cmd[key].apply(cmd, _toArray(arguments, 1));
if (changeFlag) {
self.updateState();
self.addBookmark(false);
if (self.options.afterChange) {
self.options.afterChange.call(self);
}
}
return self;
},
insertHtml : function(val) {
if (!this.isCreated) {
return this;
}
val = this.beforeSetHtml(val);
this.exec('inserthtml', val);
return this;
},
appendHtml : function(val) {
this.html(this.html() + val);
if (this.isCreated) {
var cmd = this.cmd;
cmd.range.selectNodeContents(cmd.doc.body).collapse(false);
cmd.select();
}
return this;
},
sync : function() {
_elementVal(this.srcElement, this.html());
return this;
},
focus : function() {
this.isCreated ? this.edit.focus() : this.srcElement[0].focus();
return this;
},
blur : function() {
this.isCreated ? this.edit.blur() : this.srcElement[0].blur();
return this;
},
addBookmark : function(checkSize) {
checkSize = _undef(checkSize, true);
var self = this, edit = self.edit,
body = edit.doc.body,
html = _removeTempTag(body.innerHTML), bookmark;
if (checkSize && self._undoStack.length > 0) {
var prev = self._undoStack[self._undoStack.length - 1];
if (Math.abs(html.length - _removeBookmarkTag(prev.html).length) < self.minChangeSize) {
return self;
}
}
if (edit.designMode && !self._firstAddBookmark) {
var range = self.cmd.range;
bookmark = range.createBookmark(true);
bookmark.html = _removeTempTag(body.innerHTML);
range.moveToBookmark(bookmark);
} else {
bookmark = {
html : html
};
}
self._firstAddBookmark = false;
_addBookmarkToStack(self._undoStack, bookmark);
return self;
},
undo : function() {
return _undoToRedo.call(this, this._undoStack, this._redoStack);
},
redo : function() {
return _undoToRedo.call(this, this._redoStack, this._undoStack);
},
fullscreen : function(bool) {
this.fullscreenMode = (bool === undefined ? !this.fullscreenMode : bool);
return this.remove().create();
},
readonly : function(isReadonly) {
isReadonly = _undef(isReadonly, true);
var self = this, edit = self.edit, doc = edit.doc;
if (self.designMode) {
self.toolbar.disableAll(isReadonly, []);
} else {
_each(self.noDisableItems, function() {
self.toolbar[isReadonly ? 'disable' : 'enable'](this);
});
}
if (_IE) {
doc.body.contentEditable = !isReadonly;
} else {
doc.designMode = isReadonly ? 'off' : 'on';
}
edit.textarea[0].disabled = isReadonly;
},
createMenu : function(options) {
var self = this,
name = options.name,
knode = self.toolbar.get(name),
pos = knode.pos();
options.x = pos.x;
options.y = pos.y + knode.height();
options.shadowMode = _undef(options.shadowMode, self.shadowMode);
if (options.selectedColor !== undefined) {
options.cls = 'ke-colorpicker-' + self.themeType;
options.noColor = self.lang('noColor');
self.menu = _colorpicker(options);
} else {
options.cls = 'ke-menu-' + self.themeType;
options.centerLineMode = false;
self.menu = _menu(options);
}
return self.menu;
},
hideMenu : function() {
this.menu.remove();
this.menu = null;
return this;
},
hideContextmenu : function() {
this.contextmenu.remove();
this.contextmenu = null;
return this;
},
createDialog : function(options) {
var self = this, name = options.name;
options.autoScroll = _undef(options.autoScroll, true);
options.shadowMode = _undef(options.shadowMode, self.shadowMode);
options.closeBtn = _undef(options.closeBtn, {
name : self.lang('close'),
click : function(e) {
self.hideDialog();
if (_IE && self.cmd) {
self.cmd.select();
}
}
});
options.noBtn = _undef(options.noBtn, {
name : self.lang(options.yesBtn ? 'no' : 'close'),
click : function(e) {
self.hideDialog();
if (_IE && self.cmd) {
self.cmd.select();
}
}
});
if (self.dialogAlignType != 'page') {
options.alignEl = self.container;
}
options.cls = 'ke-dialog-' + self.themeType;
if (self.dialogs.length > 0) {
var firstDialog = self.dialogs[0],
parentDialog = self.dialogs[self.dialogs.length - 1];
firstDialog.setMaskIndex(parentDialog.z + 2);
options.z = parentDialog.z + 3;
options.showMask = false;
}
var dialog = _dialog(options);
self.dialogs.push(dialog);
return dialog;
},
hideDialog : function() {
var self = this;
if (self.dialogs.length > 0) {
self.dialogs.pop().remove();
}
if (self.dialogs.length > 0) {
var firstDialog = self.dialogs[0],
parentDialog = self.dialogs[self.dialogs.length - 1];
firstDialog.setMaskIndex(parentDialog.z - 1);
}
return self;
},
errorDialog : function(html) {
var self = this;
var dialog = self.createDialog({
width : 750,
title : self.lang('uploadError'),
body : '<div style="padding:10px 20px;"><iframe frameborder="0" style="width:708px;height:400px;"></iframe></div>'
});
var iframe = K('iframe', dialog.div), doc = K.iframeDoc(iframe);
doc.open();
doc.write(html);
doc.close();
K(doc.body).css('background-color', '#FFF');
iframe[0].contentWindow.focus();
return self;
}
};
function _editor(options) {
return new KEditor(options);
}
function _create(expr, options) {
options = options || {};
options.basePath = _undef(options.basePath, K.basePath);
options.themesPath = _undef(options.themesPath, options.basePath + 'themes/');
options.langPath = _undef(options.langPath, options.basePath + 'lang/');
options.pluginsPath = _undef(options.pluginsPath, options.basePath + 'plugins/');
if (_undef(options.loadStyleMode, K.options.loadStyleMode)) {
var themeType = _undef(options.themeType, K.options.themeType);
_loadStyle(options.themesPath + 'default/default.css');
_loadStyle(options.themesPath + themeType + '/' + themeType + '.css');
}
function create(editor) {
_each(_plugins, function(name, fn) {
fn.call(editor, KindEditor);
});
return editor.create();
}
var knode = K(expr);
if (!knode) {
return;
}
options.srcElement = knode[0];
if (!options.width) {
options.width = knode[0].style.width || knode.width();
}
if (!options.height) {
options.height = knode[0].style.height || knode.height();
}
var editor = new KEditor(options);
if (_language[editor.langType]) {
return create(editor);
}
_loadScript(editor.langPath + editor.langType + '.js?ver=' + encodeURIComponent(K.DEBUG ? _TIME : _VERSION), function() {
return create(editor);
});
return editor;
}
if (_IE && _V < 7) {
_nativeCommand(document, 'BackgroundImageCache', true);
}
K.editor = _editor;
K.create = _create;
K.plugin = _plugin;
K.lang = _lang;
_plugin('core', function(K) {
var self = this,
shortcutKeys = {
undo : 'Z', redo : 'Y', bold : 'B', italic : 'I', underline : 'U', print : 'P', selectall : 'A'
};
self.afterSetHtml(function() {
if (self.options.afterChange) {
self.options.afterChange.call(self);
}
});
if (self.syncType == 'form') {
var el = K(self.srcElement), hasForm = false;
while ((el = el.parent())) {
if (el.name == 'form') {
hasForm = true;
break;
}
}
if (hasForm) {
el.bind('submit', function(e) {
self.sync();
self.edit.textarea.remove();
});
var resetBtn = K('[type="reset"]', el);
resetBtn.click(function() {
self.html(self.initContent);
self.cmd.selection();
});
self.beforeRemove(function() {
el.unbind();
resetBtn.unbind();
});
}
}
self.clickToolbar('source', function() {
if (self.edit.designMode) {
self.toolbar.disableAll(true);
self.edit.design(false);
self.toolbar.select('source');
} else {
self.toolbar.disableAll(false);
self.edit.design(true);
self.toolbar.unselect('source');
}
self.designMode = self.edit.designMode;
});
self.afterCreate(function() {
if (!self.designMode) {
self.toolbar.disableAll(true).select('source');
}
});
self.clickToolbar('fullscreen', function() {
self.fullscreen();
});
var loaded = false;
self.afterCreate(function() {
K(self.edit.doc, self.edit.textarea).keyup(function(e) {
if (e.which == 27) {
setTimeout(function() {
self.fullscreen();
}, 0);
}
});
if (loaded) {
if (_IE && !self.designMode) {
return;
}
self.focus();
}
if (!loaded) {
loaded = true;
}
});
_each('undo,redo'.split(','), function(i, name) {
if (shortcutKeys[name]) {
self.afterCreate(function() {
_ctrl(this.edit.doc, shortcutKeys[name], function() {
self.clickToolbar(name);
});
});
}
self.clickToolbar(name, function() {
self[name]();
});
});
self.clickToolbar('formatblock', function() {
var blocks = self.lang('formatblock.formatBlock'),
heights = {
h1 : 28,
h2 : 24,
h3 : 18,
H4 : 14,
p : 12
},
curVal = self.cmd.val('formatblock'),
menu = self.createMenu({
name : 'formatblock',
width : self.langType == 'en' ? 200 : 150
});
_each(blocks, function(key, val) {
var style = 'font-size:' + heights[key] + 'px;';
if (key.charAt(0) === 'h') {
style += 'font-weight:bold;';
}
menu.addItem({
title : '<span style="' + style + '" unselectable="on">' + val + '</span>',
height : heights[key] + 12,
checked : (curVal === key || curVal === val),
click : function() {
self.select().exec('formatblock', '<' + key + '>').hideMenu();
}
});
});
});
self.clickToolbar('fontname', function() {
var curVal = self.cmd.val('fontname'),
menu = self.createMenu({
name : 'fontname',
width : 150
});
_each(self.lang('fontname.fontName'), function(key, val) {
menu.addItem({
title : '<span style="font-family: ' + key + ';" unselectable="on">' + val + '</span>',
checked : (curVal === key.toLowerCase() || curVal === val.toLowerCase()),
click : function() {
self.exec('fontname', key).hideMenu();
}
});
});
});
self.clickToolbar('fontsize', function() {
var curVal = self.cmd.val('fontsize'),
menu = self.createMenu({
name : 'fontsize',
width : 150
});
_each(self.fontSizeTable, function(i, val) {
menu.addItem({
title : '<span style="font-size:' + val + ';" unselectable="on">' + val + '</span>',
height : _removeUnit(val) + 12,
checked : curVal === val,
click : function() {
self.exec('fontsize', val).hideMenu();
}
});
});
});
_each('forecolor,hilitecolor'.split(','), function(i, name) {
self.clickToolbar(name, function() {
self.createMenu({
name : name,
selectedColor : self.cmd.val(name) || 'default',
colors : self.colorTable,
click : function(color) {
self.exec(name, color).hideMenu();
}
});
});
});
_each(('cut,copy,paste').split(','), function(i, name) {
self.clickToolbar(name, function() {
self.focus();
try {
self.exec(name, null);
} catch(e) {
alert(self.lang(name + 'Error'));
}
});
});
self.clickToolbar('about', function() {
var html = '<div style="margin:20px;">' +
'<div>KindEditor ' + _VERSION + '</div>' +
'<div>Copyright © <a href="http://www.kindsoft.net/" target="_blank">kindsoft.net</a> All rights reserved.</div>' +
'</div>';
self.createDialog({
name : 'about',
width : 300,
title : self.lang('about'),
body : html
});
});
self.plugin.getSelectedLink = function() {
return self.cmd.commonAncestor('a');
};
self.plugin.getSelectedImage = function() {
return _getImageFromRange(self.edit.cmd.range, function(img) {
return !/^ke-\w+$/i.test(img[0].className);
});
};
self.plugin.getSelectedFlash = function() {
return _getImageFromRange(self.edit.cmd.range, function(img) {
return img[0].className == 'ke-flash';
});
};
self.plugin.getSelectedMedia = function() {
return _getImageFromRange(self.edit.cmd.range, function(img) {
return img[0].className == 'ke-media' || img[0].className == 'ke-rm';
});
};
self.plugin.getSelectedAnchor = function() {
return _getImageFromRange(self.edit.cmd.range, function(img) {
return img[0].className == 'ke-anchor';
});
};
_each('link,image,flash,media,anchor'.split(','), function(i, name) {
var uName = name.charAt(0).toUpperCase() + name.substr(1);
_each('edit,delete'.split(','), function(j, val) {
self.addContextmenu({
title : self.lang(val + uName),
click : function() {
self.loadPlugin(name, function() {
self.plugin[name][val]();
self.hideMenu();
});
},
cond : self.plugin['getSelected' + uName],
width : 150,
iconClass : val == 'edit' ? 'ke-icon-' + name : undefined
});
});
self.addContextmenu({ title : '-' });
});
self.plugin.getSelectedTable = function() {
return self.cmd.commonAncestor('table');
};
self.plugin.getSelectedRow = function() {
return self.cmd.commonAncestor('tr');
};
self.plugin.getSelectedCell = function() {
return self.cmd.commonAncestor('td');
};
_each(('prop,cellprop,colinsertleft,colinsertright,rowinsertabove,rowinsertbelow,rowmerge,colmerge,' +
'rowsplit,colsplit,coldelete,rowdelete,insert,delete').split(','), function(i, val) {
var cond = _inArray(val, ['prop', 'delete']) < 0 ? self.plugin.getSelectedCell : self.plugin.getSelectedTable;
self.addContextmenu({
title : self.lang('table' + val),
click : function() {
self.loadPlugin('table', function() {
self.plugin.table[val]();
self.hideMenu();
});
},
cond : cond,
width : 170,
iconClass : 'ke-icon-table' + val
});
});
self.addContextmenu({ title : '-' });
_each(('selectall,justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,' +
'insertunorderedlist,indent,outdent,subscript,superscript,hr,print,' +
'bold,italic,underline,strikethrough,removeformat,unlink').split(','), function(i, name) {
if (shortcutKeys[name]) {
self.afterCreate(function() {
_ctrl(this.edit.doc, shortcutKeys[name], function() {
self.cmd.selection();
self.clickToolbar(name);
});
});
}
self.clickToolbar(name, function() {
self.focus().exec(name, null);
});
});
self.afterCreate(function() {
var doc = self.edit.doc, cmd, bookmark, div,
cls = '__kindeditor_paste__', pasting = false;
function movePastedData() {
cmd.range.moveToBookmark(bookmark);
cmd.select();
if (_WEBKIT) {
K('div.' + cls, div).each(function() {
K(this).after('<br />').remove(true);
});
K('span.Apple-style-span', div).remove(true);
K('meta', div).remove();
}
var html = div[0].innerHTML;
div.remove();
if (html === '') {
return;
}
if (self.pasteType === 2) {
if (/schemas-microsoft-com|worddocument|mso-\w+/i.test(html)) {
html = _clearMsWord(html, self.filterMode ? self.htmlTags : K.options.htmlTags);
} else {
html = _formatHtml(html, self.filterMode ? self.htmlTags : null);
html = self.beforeSetHtml(html);
}
}
if (self.pasteType === 1) {
html = html.replace(/<br[^>]*>/ig, '\n');
html = html.replace(/<\/p><p[^>]*>/ig, '\n');
html = html.replace(/<[^>]+>/g, '');
html = html.replace(/ /ig, ' ');
html = html.replace(/\n\s*\n/g, '\n');
html = html.replace(/ {2}/g, ' ');
if (self.newlineTag == 'p') {
if (/\n/.test(html)) {
html = html.replace(/^/, '<p>').replace(/$/, '</p>').replace(/\n/g, '</p><p>');
}
} else {
html = html.replace(/\n/g, '<br />$&');
}
}
self.insertHtml(html);
}
K(doc.body).bind('paste', function(e){
if (self.pasteType === 0) {
e.stop();
return;
}
if (pasting) {
return;
}
pasting = true;
K('div.' + cls, doc).remove();
cmd = self.cmd.selection();
bookmark = cmd.range.createBookmark();
div = K('<div class="' + cls + '"></div>', doc).css({
position : 'absolute',
width : '1px',
height : '1px',
overflow : 'hidden',
left : '-1981px',
top : K(bookmark.start).pos().y + 'px',
'white-space' : 'nowrap'
});
K(doc.body).append(div);
if (_IE) {
var rng = cmd.range.get(true);
rng.moveToElementText(div[0]);
rng.select();
rng.execCommand('paste');
e.preventDefault();
} else {
cmd.range.selectNodeContents(div[0]);
cmd.select();
}
setTimeout(function() {
movePastedData();
pasting = false;
}, 0);
});
});
self.beforeGetHtml(function(html) {
return html.replace(/<img[^>]*class="?ke-(flash|rm|media)"?[^>]*>/ig, function(full) {
var imgAttrs = _getAttrList(full),
styles = _getCssList(imgAttrs.style || ''),
attrs = _mediaAttrs(imgAttrs['data-ke-tag']);
attrs.width = _undef(imgAttrs.width, _removeUnit(_undef(styles.width, '')));
attrs.height = _undef(imgAttrs.height, _removeUnit(_undef(styles.height, '')));
return _mediaEmbed(attrs);
})
.replace(/<img[^>]*class="?ke-anchor"?[^>]*>/ig, function(full) {
var imgAttrs = _getAttrList(full);
return '<a name="' + unescape(imgAttrs['data-ke-name']) + '"></a>';
})
.replace(/<div\s+[^>]*data-ke-script-attr="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function(full, attr, code) {
return '<script' + unescape(attr) + '>' + unescape(code) + '</script>';
})
.replace(/(<[^>]*)data-ke-src="([^"]*)"([^>]*>)/ig, function(full, start, src, end) {
full = full.replace(/(\s+(?:href|src)=")[^"]*(")/i, '$1' + src + '$2');
full = full.replace(/\s+data-ke-src="[^"]*"/i, '');
return full;
})
.replace(/(<[^>]+\s)data-ke-(on\w+="[^"]*"[^>]*>)/ig, function(full, start, end) {
return start + end;
});
});
self.beforeSetHtml(function(html) {
return html.replace(/<embed[^>]*type="([^"]+)"[^>]*>(?:<\/embed>)?/ig, function(full) {
var attrs = _getAttrList(full);
attrs.src = _undef(attrs.src, '');
attrs.width = _undef(attrs.width, 0);
attrs.height = _undef(attrs.height, 0);
return _mediaImg(self.themesPath + 'common/blank.gif', attrs);
})
.replace(/<a[^>]*name="([^"]+)"[^>]*>(?:<\/a>)?/ig, function(full) {
var attrs = _getAttrList(full);
if (attrs.href !== undefined) {
return full;
}
return '<img class="ke-anchor" src="' + self.themesPath + 'common/anchor.gif" data-ke-name="' + escape(attrs.name) + '" />';
})
.replace(/<script([^>]*)>([\s\S]*?)<\/script>/ig, function(full, attr, code) {
return '<div class="ke-script" data-ke-script-attr="' + escape(attr) + '">' + escape(code) + '</div>';
})
.replace(/(<[^>]*)(href|src)="([^"]*)"([^>]*>)/ig, function(full, start, key, src, end) {
if (full.match(/\sdata-ke-src="[^"]*"/i)) {
return full;
}
full = start + key + '="' + src + '"' + ' data-ke-src="' + src + '"' + end;
return full;
})
.replace(/(<[^>]+\s)(on\w+="[^"]*"[^>]*>)/ig, function(full, start, end) {
return start + 'data-ke-' + end;
})
.replace(/<table[^>]*\s+border="0"[^>]*>/ig, function(full) {
if (full.indexOf('ke-zeroborder') >= 0) {
return full;
}
return _addClassToTag(full, 'ke-zeroborder');
});
});
});
})(window);
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('pagebreak', function(K) {
var self = this, name = 'pagebreak';
self.clickToolbar(name, function() {
var cmd = self.cmd, range = cmd.range;
self.focus();
range.enlarge(true);
cmd.split(true);
var tail = self.newlineTag == 'br' || K.WEBKIT ? '' : '<p id="__kindeditor_tail_tag__"></p>';
self.insertHtml('<hr style="page-break-after: always;" class="ke-pagebreak" />' + tail);
if (tail !== '') {
var p = K('#__kindeditor_tail_tag__', self.edit.doc);
range.selectNodeContents(p[0]);
p.removeAttr('id');
cmd.select();
}
});
});
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('plainpaste', function(K) {
var self = this, name = 'plainpaste';
self.clickToolbar(name, function() {
var lang = self.lang(name + '.'),
html = '<div style="padding:10px 20px;">' +
'<div style="margin-bottom:10px;">' + lang.comment + '</div>' +
'<textarea class="ke-textarea" style="width:408px;height:260px;"></textarea>' +
'</div>',
dialog = self.createDialog({
name : name,
width : 450,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var html = textarea.val();
html = K.escape(html);
html = html.replace(/ {2}/g, ' ');
if (self.newlineTag == 'p') {
html = html.replace(/^/, '<p>').replace(/$/, '</p>').replace(/\n/g, '</p><p>');
} else {
html = html.replace(/\n/g, '<br />$&');
}
self.insertHtml(html).hideDialog().focus();
}
}
}),
textarea = K('textarea', dialog.div);
textarea[0].focus();
});
});
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
// Google Maps: http://code.google.com/apis/maps/index.html
KindEditor.plugin('map', function(K) {
var self = this, name = 'map', lang = self.lang(name + '.');
self.clickToolbar(name, function() {
var html = ['<div style="padding:10px 20px;">',
'<div class="ke-dialog-row">',
lang.address + ' <input id="kindeditor_plugin_map_address" name="address" class="ke-input-text" value="" style="width:200px;" /> ',
'<span class="ke-button-common ke-button-outer">',
'<input type="button" name="searchBtn" class="ke-button-common ke-button" value="' + lang.search + '" />',
'</span>',
'</div>',
'<div class="ke-map" style="width:558px;height:360px;"></div>',
'</div>'].join('');
var dialog = self.createDialog({
name : name,
width : 600,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var geocoder = win.geocoder,
map = win.map,
center = map.getCenter().lat() + ',' + map.getCenter().lng(),
zoom = map.getZoom(),
maptype = map.getMapTypeId(),
url = 'http://maps.googleapis.com/maps/api/staticmap';
url += '?center=' + encodeURIComponent(center);
url += '&zoom=' + encodeURIComponent(zoom);
url += '&size=558x360';
url += '&maptype=' + encodeURIComponent(maptype);
url += '&markers=' + encodeURIComponent(center);
url += '&language=' + self.langType;
url += '&sensor=false';
self.exec('insertimage', url).hideDialog().focus();
}
},
beforeRemove : function() {
searchBtn.remove();
if (doc) {
doc.write('');
}
iframe.remove();
}
});
var div = dialog.div,
addressBox = K('[name="address"]', div),
searchBtn = K('[name="searchBtn"]', div),
win, doc;
var iframeHtml = ['<!doctype html><html><head>',
'<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />',
'<style>',
' html { height: 100% }',
' body { height: 100%; margin: 0; padding: 0; background-color: #FFF }',
' #map_canvas { height: 100% }',
'</style>',
'<script src="http://maps.googleapis.com/maps/api/js?sensor=false&language=' + self.langType + '"></script>',
'<script>',
'var map, geocoder;',
'function initialize() {',
' var latlng = new google.maps.LatLng(31.230393, 121.473704);',
' var options = {',
' zoom: 11,',
' center: latlng,',
' disableDefaultUI: true,',
' panControl: true,',
' zoomControl: true,',
' mapTypeControl: true,',
' scaleControl: true,',
' streetViewControl: false,',
' overviewMapControl: true,',
' mapTypeId: google.maps.MapTypeId.ROADMAP',
' };',
' map = new google.maps.Map(document.getElementById("map_canvas"), options);',
' geocoder = new google.maps.Geocoder();',
' geocoder.geocode({latLng: latlng}, function(results, status) {',
' if (status == google.maps.GeocoderStatus.OK) {',
' if (results[3]) {',
' parent.document.getElementById("kindeditor_plugin_map_address").value = results[3].formatted_address;',
' }',
' }',
' });',
'}',
'function search(address) {',
' if (!map) return;',
' geocoder.geocode({address : address}, function(results, status) {',
' if (status == google.maps.GeocoderStatus.OK) {',
' map.setZoom(11);',
' map.setCenter(results[0].geometry.location);',
' var marker = new google.maps.Marker({',
' map: map,',
' position: results[0].geometry.location',
' });',
' } else {',
' alert("Invalid address: " + address);',
' }',
' });',
'}',
'</script>',
'</head>',
'<body onload="initialize();">',
'<div id="map_canvas" style="width:100%; height:100%"></div>',
'</body></html>'].join('\n');
// TODO:用doc.write(iframeHtml)方式加载时,在IE6上第一次加载报错,暂时使用src方式
var iframe = K('<iframe class="ke-textarea" frameborder="0" src="' + self.pluginsPath + 'map/map.html" style="width:558px;height:360px;"></iframe>');
function ready() {
win = iframe[0].contentWindow;
doc = K.iframeDoc(iframe);
//doc.open();
//doc.write(iframeHtml);
//doc.close();
}
iframe.bind('load', function() {
iframe.unbind('load');
if (K.IE) {
ready();
} else {
setTimeout(ready, 0);
}
});
K('.ke-map', div).replaceWith(iframe);
// search map
searchBtn.click(function() {
win.search(addressBox.val());
});
});
});
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('flash', function(K) {
var self = this, name = 'flash', lang = self.lang(name + '.'),
allowFlashUpload = K.undef(self.allowFlashUpload, true),
allowFileManager = K.undef(self.allowFileManager, false),
uploadJson = K.undef(self.uploadJson, self.basePath + '/ashx/upload_json.ashx');
self.plugin.flash = {
edit : function() {
var html = [
'<div style="padding:10px 20px;">',
//url
'<div class="ke-dialog-row">',
'<label for="keUrl" style="width:60px;">' + lang.url + '</label>',
'<input class="ke-input-text" type="text" id="keUrl" name="url" value="" style="width:160px;" /> ',
'<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> ',
'<span class="ke-button-common ke-button-outer">',
'<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
'</span>',
'</div>',
//width
'<div class="ke-dialog-row">',
'<label for="keWidth" style="width:60px;">' + lang.width + '</label>',
'<input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="550" maxlength="4" /> ',
'</div>',
//height
'<div class="ke-dialog-row">',
'<label for="keHeight" style="width:60px;">' + lang.height + '</label>',
'<input type="text" id="keHeight" class="ke-input-text ke-input-number" name="height" value="400" maxlength="4" /> ',
'</div>',
'</div>'
].join('');
var dialog = self.createDialog({
name : name,
width : 450,
height : 200,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var url = K.trim(urlBox.val()),
width = widthBox.val(),
height = heightBox.val();
if (url == 'http://' || K.invalidUrl(url)) {
alert(self.lang('invalidUrl'));
urlBox[0].focus();
return;
}
if (!/^\d*$/.test(width)) {
alert(self.lang('invalidWidth'));
widthBox[0].focus();
return;
}
if (!/^\d*$/.test(height)) {
alert(self.lang('invalidHeight'));
heightBox[0].focus();
return;
}
var html = K.mediaImg(self.themesPath + 'common/blank.gif', {
src : url,
type : K.mediaType('.swf'),
width : width,
height : height,
quality : 'high'
});
self.insertHtml(html).hideDialog().focus();
}
}
}),
div = dialog.div,
urlBox = K('[name="url"]', div),
viewServerBtn = K('[name="viewServer"]', div),
widthBox = K('[name="width"]', div),
heightBox = K('[name="height"]', div);
urlBox.val('http://');
if (allowFlashUpload) {
var uploadbutton = K.uploadbutton({
button : K('.ke-upload-button', div)[0],
fieldName : 'imgFile',
url : K.addParam(uploadJson, 'dir=flash'),
afterUpload : function(data) {
dialog.hideLoading();
if (data.error === 0) {
var url = K.formatUrl(data.url, 'absolute');
urlBox.val(url);
if (self.afterUpload) {
self.afterUpload.call(self, url);
}
alert(self.lang('uploadSuccess'));
} else {
alert(data.message);
}
},
afterError : function(html) {
dialog.hideLoading();
self.errorDialog(html);
}
});
uploadbutton.fileBox.change(function(e) {
dialog.showLoading(self.lang('uploadLoading'));
uploadbutton.submit();
});
} else {
K('.ke-upload-button', div).hide();
urlBox.width(250);
}
if (allowFileManager) {
viewServerBtn.click(function(e) {
self.loadPlugin('filemanager', function() {
self.plugin.filemanagerDialog({
viewType : 'LIST',
dirName : 'flash',
clickFn : function(url, title) {
if (self.dialogs.length > 1) {
K('[name="url"]', div).val(url);
self.hideDialog();
}
}
});
});
});
} else {
viewServerBtn.hide();
}
var img = self.plugin.getSelectedFlash();
if (img) {
var attrs = K.mediaAttrs(img.attr('data-ke-tag'));
urlBox.val(attrs.src);
widthBox.val(K.removeUnit(img.css('width')) || attrs.width || 0);
heightBox.val(K.removeUnit(img.css('height')) || attrs.height || 0);
}
urlBox[0].focus();
urlBox[0].select();
},
'delete' : function() {
self.plugin.getSelectedFlash().remove();
}
};
self.clickToolbar(name, self.plugin.flash.edit);
});
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('preview', function(K) {
var self = this, name = 'preview', undefined;
self.clickToolbar(name, function() {
var lang = self.lang(name + '.'),
html = '<div style="padding:10px 20px;">' +
'<iframe class="ke-textarea" frameborder="0" style="width:708px;height:400px;"></iframe>' +
'</div>',
dialog = self.createDialog({
name : name,
width : 750,
title : self.lang(name),
body : html
}),
iframe = K('iframe', dialog.div),
doc = K.iframeDoc(iframe);
doc.open();
doc.write(self.fullHtml());
doc.close();
K(doc.body).css('background-color', '#FFF');
iframe[0].contentWindow.focus();
});
});
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('link', function(K) {
var self = this, name = 'link';
self.plugin.link = {
edit : function() {
var lang = self.lang(name + '.'),
html = '<div style="padding:10px 20px;">' +
//url
'<div class="ke-dialog-row">' +
'<label for="keUrl">' + lang.url + '</label>' +
'<input class="ke-input-text" type="text" id="keUrl" name="url" value="" style="width:90%;" /></div>' +
//type
'<div class="ke-dialog-row"">' +
'<label for="keType">' + lang.linkType + '</label>' +
'<select id="keType" name="type"></select>' +
'</div>' +
'</div>',
dialog = self.createDialog({
name : name,
width : 400,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var url = K.trim(urlBox.val());
if (url == 'http://' || K.invalidUrl(url)) {
alert(self.lang('invalidUrl'));
urlBox[0].focus();
return;
}
self.exec('createlink', url, typeBox.val()).hideDialog().focus();
}
}
}),
div = dialog.div,
urlBox = K('input[name="url"]', div),
typeBox = K('select[name="type"]', div);
urlBox.val('http://');
typeBox[0].options[0] = new Option(lang.newWindow, '_blank');
typeBox[0].options[1] = new Option(lang.selfWindow, '');
self.cmd.selection();
var a = self.plugin.getSelectedLink();
if (a) {
self.cmd.range.selectNode(a[0]);
self.cmd.select();
urlBox.val(a.attr('data-ke-src'));
typeBox.val(a.attr('target'));
}
urlBox[0].focus();
urlBox[0].select();
},
'delete' : function() {
self.exec('unlink', null);
}
};
self.clickToolbar(name, self.plugin.link.edit);
});
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('insertfile', function(K) {
var self = this, name = 'insertfile',
allowFileManager = K.undef(self.allowFileManager, false),
uploadJson = K.undef(self.uploadJson, self.basePath + '/ashx/upload_json.ashx'),
lang = self.lang(name + '.');
self.plugin.fileDialog = function(options) {
var fileUrl = K.undef(options.fileUrl, 'http://'),
fileTitle = K.undef(options.fileTitle, ''),
clickFn = options.clickFn;
var html = [
'<div style="padding:10px 20px;">',
'<div class="ke-dialog-row">',
'<label for="keUrl" style="width:60px;">' + lang.url + '</label>',
'<input type="text" id="keUrl" name="url" class="ke-input-text" style="width:160px;" /> ',
'<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> ',
'<span class="ke-button-common ke-button-outer">',
'<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
'</span>',
'</div>',
//title
'<div class="ke-dialog-row">',
'<label for="keTitle" style="width:60px;">' + lang.title + '</label>',
'<input type="text" id="keTitle" class="ke-input-text" name="title" value="" style="width:160px;" /></div>',
'</div>',
//form end
'</form>',
'</div>'
].join('');
var dialog = self.createDialog({
name : name,
width : 450,
height : 180,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var url = K.trim(urlBox.val()),
title = titleBox.val();
if (url == 'http://' || K.invalidUrl(url)) {
alert(self.lang('invalidUrl'));
urlBox[0].focus();
return;
}
if (K.trim(title) === '') {
title = url;
}
clickFn.call(self, url, title);
}
},
beforeRemove : function() {
viewServerBtn.remove();
uploadbutton.remove();
}
}),
div = dialog.div;
var urlBox = K('[name="url"]', div),
viewServerBtn = K('[name="viewServer"]', div),
titleBox = K('[name="title"]', div);
var uploadbutton = K.uploadbutton({
button : K('.ke-upload-button', div)[0],
fieldName : 'imgFile',
url : K.addParam(uploadJson, 'dir=file'),
afterUpload : function(data) {
dialog.hideLoading();
if (data.error === 0) {
var url = K.formatUrl(data.url, 'absolute');
urlBox.val(url);
if (self.afterUpload) {
self.afterUpload.call(self, url);
}
alert(self.lang('uploadSuccess'));
} else {
alert(data.message);
}
},
afterError : function(html) {
dialog.hideLoading();
self.errorDialog(html);
}
});
uploadbutton.fileBox.change(function(e) {
dialog.showLoading(self.lang('uploadLoading'));
uploadbutton.submit();
});
if (allowFileManager) {
viewServerBtn.click(function(e) {
self.loadPlugin('filemanager', function() {
self.plugin.filemanagerDialog({
viewType : 'LIST',
dirName : 'file',
clickFn : function(url, title) {
if (self.dialogs.length > 1) {
K('[name="url"]', div).val(url);
self.hideDialog();
}
}
});
});
});
} else {
viewServerBtn.hide();
}
urlBox.val(fileUrl);
titleBox.val(fileTitle);
urlBox[0].focus();
urlBox[0].select();
};
self.clickToolbar(name, function() {
self.plugin.fileDialog({
clickFn : function(url, title) {
var html = '<a href="' + url + '" data-ke-src="' + url + '" target="_blank">' + title + '</a>';
self.insertHtml(html).hideDialog().focus();
}
});
});
});
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('media', function(K) {
var self = this, name = 'media', lang = self.lang(name + '.'),
allowMediaUpload = K.undef(self.allowMediaUpload, true),
allowFileManager = K.undef(self.allowFileManager, false),
uploadJson = K.undef(self.uploadJson, self.basePath + '/ashx/upload_json.php');
self.plugin.media = {
edit : function() {
var html = [
'<div style="padding:10px 20px;">',
//url
'<div class="ke-dialog-row">',
'<label for="keUrl" style="width:60px;">' + lang.url + '</label>',
'<input class="ke-input-text" type="text" id="keUrl" name="url" value="" style="width:160px;" /> ',
'<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> ',
'<span class="ke-button-common ke-button-outer">',
'<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
'</span>',
'</div>',
//width
'<div class="ke-dialog-row">',
'<label for="keWidth" style="width:60px;">' + lang.width + '</label>',
'<input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="550" maxlength="4" />',
'</div>',
//height
'<div class="ke-dialog-row">',
'<label for="keHeight" style="width:60px;">' + lang.height + '</label>',
'<input type="text" id="keHeight" class="ke-input-text ke-input-number" name="height" value="400" maxlength="4" />',
'</div>',
//autostart
'<div class="ke-dialog-row">',
'<label for="keAutostart">' + lang.autostart + '</label>',
'<input type="checkbox" id="keAutostart" name="autostart" value="" /> ',
'</div>',
'</div>'
].join('');
var dialog = self.createDialog({
name : name,
width : 450,
height : 230,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var url = K.trim(urlBox.val()),
width = widthBox.val(),
height = heightBox.val();
if (url == 'http://' || K.invalidUrl(url)) {
alert(self.lang('invalidUrl'));
urlBox[0].focus();
return;
}
if (!/^\d*$/.test(width)) {
alert(self.lang('invalidWidth'));
widthBox[0].focus();
return;
}
if (!/^\d*$/.test(height)) {
alert(self.lang('invalidHeight'));
heightBox[0].focus();
return;
}
var html = K.mediaImg(self.themesPath + 'common/blank.gif', {
src : url,
type : K.mediaType(url),
width : width,
height : height,
autostart : autostartBox[0].checked ? 'true' : 'false',
loop : 'true'
});
self.insertHtml(html).hideDialog().focus();
}
}
}),
div = dialog.div,
urlBox = K('[name="url"]', div),
viewServerBtn = K('[name="viewServer"]', div),
widthBox = K('[name="width"]', div),
heightBox = K('[name="height"]', div),
autostartBox = K('[name="autostart"]', div);
urlBox.val('http://');
if (allowMediaUpload) {
var uploadbutton = K.uploadbutton({
button : K('.ke-upload-button', div)[0],
fieldName : 'imgFile',
url : K.addParam(uploadJson, 'dir=media'),
afterUpload : function(data) {
dialog.hideLoading();
if (data.error === 0) {
var url = K.formatUrl(data.url, 'absolute');
urlBox.val(url);
if (self.afterUpload) {
self.afterUpload.call(self, url);
}
alert(self.lang('uploadSuccess'));
} else {
alert(data.message);
}
},
afterError : function(html) {
dialog.hideLoading();
self.errorDialog(html);
}
});
uploadbutton.fileBox.change(function(e) {
dialog.showLoading(self.lang('uploadLoading'));
uploadbutton.submit();
});
} else {
K('.ke-upload-button', div).hide();
urlBox.width(250);
}
if (allowFileManager) {
viewServerBtn.click(function(e) {
self.loadPlugin('filemanager', function() {
self.plugin.filemanagerDialog({
viewType : 'LIST',
dirName : 'media',
clickFn : function(url, title) {
if (self.dialogs.length > 1) {
K('[name="url"]', div).val(url);
self.hideDialog();
}
}
});
});
});
} else {
viewServerBtn.hide();
}
var img = self.plugin.getSelectedMedia();
if (img) {
var attrs = K.mediaAttrs(img.attr('data-ke-tag'));
urlBox.val(attrs.src);
widthBox.val(K.removeUnit(img.css('width')) || attrs.width || 0);
heightBox.val(K.removeUnit(img.css('height')) || attrs.height || 0);
autostartBox[0].checked = (attrs.autostart === 'true');
}
urlBox[0].focus();
urlBox[0].select();
},
'delete' : function() {
self.plugin.getSelectedMedia().remove();
}
};
self.clickToolbar(name, self.plugin.media.edit);
});
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('wordpaste', function(K) {
var self = this, name = 'wordpaste';
self.clickToolbar(name, function() {
var lang = self.lang(name + '.'),
html = '<div style="padding:10px 20px;">' +
'<div style="margin-bottom:10px;">' + lang.comment + '</div>' +
'<iframe class="ke-textarea" frameborder="0" style="width:408px;height:260px;"></iframe>' +
'</div>',
dialog = self.createDialog({
name : name,
width : 450,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var str = doc.body.innerHTML;
str = K.clearMsWord(str, self.filterMode ? self.htmlTags : K.options.htmlTags);
self.insertHtml(str).hideDialog().focus();
}
}
}),
div = dialog.div,
iframe = K('iframe', div),
doc = K.iframeDoc(iframe);
if (!K.IE) {
doc.designMode = 'on';
}
doc.open();
doc.write('<!doctype html><html><head><title>WordPaste</title></head>');
doc.write('<body style="background-color:#FFF;font-size:12px;margin:2px;">');
if (!K.IE) {
doc.write('<br />');
}
doc.write('</body></html>');
doc.close();
if (K.IE) {
doc.body.contentEditable = 'true';
}
iframe[0].contentWindow.focus();
});
});
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('quickformat', function(K) {
var self = this, name = 'quickformat',
blockMap = K.toMap('blockquote,center,div,h1,h2,h3,h4,h5,h6,p');
self.clickToolbar(name, function() {
self.focus();
var doc = self.edit.doc,
range = self.cmd.range,
child = K(doc.body).first(), next,
nodeList = [], subList = [],
bookmark = range.createBookmark(true);
while(child) {
next = child.next();
if (blockMap[child.name]) {
child.html(child.html().replace(/^(\s| | )+/ig, ''));
child.css('text-indent', '2em');
} else {
subList.push(child);
}
if (!next || (blockMap[next.name] || blockMap[child.name] && !blockMap[next.name])) {
if (subList.length > 0) {
nodeList.push(subList);
}
subList = [];
}
child = next;
}
K.each(nodeList, function(i, subList) {
var wrapper = K('<p style="text-indent:2em;"></p>', doc);
subList[0].before(wrapper);
K.each(subList, function(i, knode) {
wrapper.append(knode);
});
});
range.moveToBookmark(bookmark);
self.addBookmark();
});
});
/**
--------------------------
abcd<br />
1234<br />
to
<p style="text-indent:2em;">
abcd<br />
1234<br />
</p>
--------------------------
abcd<img>1233
<p>1234</p>
to
<p style="text-indent:2em;">abcd<img>1233</p>
<p style="text-indent:2em;">1234</p>
--------------------------
*/
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('clearhtml', function(K) {
var self = this, name = 'clearhtml';
self.clickToolbar(name, function() {
self.focus();
var html = self.html();
html = html.replace(/(<script[^>]*>)([\s\S]*?)(<\/script>)/ig, '');
html = html.replace(/(<style[^>]*>)([\s\S]*?)(<\/style>)/ig, '');
html = K.formatHtml(html, {
a : ['href', 'target'],
embed : ['src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess'],
img : ['src', 'width', 'height', 'border', 'alt', 'title', '.width', '.height'],
table : ['border'],
'td,th' : ['rowspan', 'colspan'],
'div,hr,br,tbody,tr,p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6' : []
});
self.html(html);
self.cmd.selection(true);
self.addBookmark();
});
});
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('lineheight', function(K) {
var self = this, name = 'lineheight', lang = self.lang(name + '.');
self.clickToolbar(name, function() {
var curVal = '', commonNode = self.cmd.commonNode({'*' : '.line-height'});
if (commonNode) {
curVal = commonNode.css('line-height');
}
var menu = self.createMenu({
name : name,
width : 150
});
K.each(lang.lineHeight, function(i, row) {
K.each(row, function(key, val) {
menu.addItem({
title : val,
checked : curVal === key,
click : function() {
self.cmd.toggle('<span style="line-height:' + key + ';"></span>', {
span : '.line-height=' + key
});
self.updateState();
self.addBookmark();
self.hideMenu();
}
});
});
});
});
});
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('image', function(K) {
var self = this, name = 'image',
allowImageUpload = K.undef(self.allowImageUpload, true),
allowFileManager = K.undef(self.allowFileManager, false),
uploadJson = K.undef(self.uploadJson, self.basePath + '/ashx/upload_json.ashx'),
imgPath = self.basePath + 'plugins/image/images/',
lang = self.lang(name + '.');
self.plugin.imageDialog = function(options) {
var imageUrl = K.undef(options.imageUrl, 'http://'),
imageWidth = K.undef(options.imageWidth, ''),
imageHeight = K.undef(options.imageHeight, ''),
imageTitle = K.undef(options.imageTitle, ''),
imageAlign = K.undef(options.imageAlign, ''),
clickFn = options.clickFn;
var html = [
'<div style="padding:10px 20px;">',
//tabs
'<div class="tabs"></div>',
//url or file
'<div class="ke-dialog-row">',
'<div class="tab1" style="display:none;">',
'<label for="keUrl" style="width:60px;">' + lang.remoteUrl + '</label>',
'<input type="text" id="keUrl" class="ke-input-text" name="url" value="" style="width:200px;" /> ',
'<span class="ke-button-common ke-button-outer">',
'<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
'</span>',
'</div>',
'<div class="tab2" style="display:none;">',
'<label style="width:60px;">' + lang.localUrl + '</label>',
'<input type="text" name="localUrl" class="ke-input-text" tabindex="-1" style="width:200px;" readonly="true" /> ',
'<input type="button" class="ke-upload-button" value="' + lang.viewServer + '" />',
'</div>',
'</div>',
//size
'<div class="ke-dialog-row">',
'<label for="keWidth" style="width:60px;">' + lang.size + '</label>',
lang.width + ' <input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> ',
lang.height + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> ',
'<img class="ke-refresh-btn" src="' + imgPath + 'refresh.gif" width="16" height="16" alt="" style="cursor:pointer;" />',
'</div>',
//align
'<div class="ke-dialog-row">',
'<label style="width:60px;">' + lang.align + '</label>',
'<input type="radio" name="align" class="ke-inline-block" value="" checked="checked" /> <img name="defaultImg" src="' + imgPath + 'align_top.gif" width="23" height="25" alt="" />',
' <input type="radio" name="align" class="ke-inline-block" value="left" /> <img name="leftImg" src="' + imgPath + 'align_left.gif" width="23" height="25" alt="" />',
' <input type="radio" name="align" class="ke-inline-block" value="right" /> <img name="rightImg" src="' + imgPath + 'align_right.gif" width="23" height="25" alt="" />',
'</div>',
//title
'<div class="ke-dialog-row">',
'<label for="keTitle" style="width:60px;">' + lang.imgTitle + '</label>',
'<input type="text" id="keTitle" class="ke-input-text" name="title" value="" style="width:200px;" /></div>',
'</div>',
'</div>'
].join('');
var dialogWidth = allowImageUpload ? 450 : 400;
dialogHeight = allowImageUpload ? 300 : 250;
var dialog = self.createDialog({
name : name,
width : dialogWidth,
height : dialogHeight,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
// insert local image
if (tabs && tabs.selectedIndex === 1) {
dialog.showLoading(self.lang('uploadLoading'));
uploadbutton.submit();
localUrlBox.val('');
return;
}
// insert remote image
var url = K.trim(urlBox.val()),
width = widthBox.val(),
height = heightBox.val(),
title = titleBox.val(),
align = '';
alignBox.each(function() {
if (this.checked) {
align = this.value;
return false;
}
});
if (url == 'http://' || K.invalidUrl(url)) {
alert(self.lang('invalidUrl'));
urlBox[0].focus();
return;
}
if (!/^\d*$/.test(width)) {
alert(self.lang('invalidWidth'));
widthBox[0].focus();
return;
}
if (!/^\d*$/.test(height)) {
alert(self.lang('invalidHeight'));
heightBox[0].focus();
return;
}
clickFn.call(self, url, title, width, height, 0, align);
}
},
beforeRemove : function() {
viewServerBtn.remove();
widthBox.remove();
heightBox.remove();
refreshBtn.remove();
uploadbutton.remove();
}
}),
div = dialog.div;
var tabs;
if (allowImageUpload) {
tabs = K.tabs({
src : K('.tabs', div),
afterSelect : function(i) {
}
});
tabs.add({
title : lang.remoteImage,
panel : K('.tab1', div)
});
tabs.add({
title : lang.localImage,
panel : K('.tab2', div)
});
tabs.select(0);
} else {
K('.tab1', div).show();
}
var urlBox = K('[name="url"]', div),
localUrlBox = K('[name="localUrl"]', div),
viewServerBtn = K('[name="viewServer"]', div),
widthBox = K('[name="width"]', div),
heightBox = K('[name="height"]', div),
refreshBtn = K('.ke-refresh-btn', div),
titleBox = K('[name="title"]', div),
alignBox = K('[name="align"]');
var uploadbutton = K.uploadbutton({
button : K('.ke-upload-button', div)[0],
fieldName : 'imgFile',
url : K.addParam(uploadJson, 'dir=image'),
afterUpload : function(data) {
dialog.hideLoading();
if (data.error === 0) {
var width = widthBox.val(),
height = heightBox.val(),
title = titleBox.val(),
align = '';
alignBox.each(function() {
if (this.checked) {
align = this.value;
return false;
}
});
var url = K.formatUrl(data.url, 'absolute');
clickFn.call(self, url, title, width, height, 0, align);
if (self.afterUpload) {
self.afterUpload.call(self, url);
}
} else {
alert(data.message);
}
},
afterError : function(html) {
dialog.hideLoading();
self.errorDialog(html);
}
});
uploadbutton.fileBox.change(function(e) {
localUrlBox.val(uploadbutton.fileBox.val());
});
if (allowFileManager) {
viewServerBtn.click(function(e) {
self.loadPlugin('filemanager', function() {
self.plugin.filemanagerDialog({
viewType : 'VIEW',
dirName : 'image',
clickFn : function(url, title) {
if (self.dialogs.length > 1) {
K('[name="url"]', div).val(url);
self.hideDialog();
}
}
});
});
});
} else {
viewServerBtn.hide();
}
var originalWidth = 0, originalHeight = 0;
function setSize(width, height) {
widthBox.val(width);
heightBox.val(height);
originalWidth = width;
originalHeight = height;
}
refreshBtn.click(function(e) {
var tempImg = K('<img src="' + urlBox.val() + '" />', document).css({
position : 'absolute',
visibility : 'hidden',
top : 0,
left : '-1000px'
});
K(document.body).append(tempImg);
setSize(tempImg.width(), tempImg.height());
tempImg.remove();
});
widthBox.change(function(e) {
if (originalWidth > 0) {
heightBox.val(Math.round(originalHeight / originalWidth * parseInt(this.value, 10)));
}
});
heightBox.change(function(e) {
if (originalHeight > 0) {
widthBox.val(Math.round(originalWidth / originalHeight * parseInt(this.value, 10)));
}
});
urlBox.val(options.imageUrl);
setSize(options.imageWidth, options.imageHeight);
titleBox.val(options.imageTitle);
alignBox.each(function() {
if (this.value === options.imageAlign) {
this.checked = true;
return false;
}
});
urlBox[0].focus();
urlBox[0].select();
return dialog;
};
self.plugin.image = {
edit : function() {
var img = self.plugin.getSelectedImage();
self.plugin.imageDialog({
imageUrl : img ? img.attr('data-ke-src') : 'http://',
imageWidth : img ? img.width() : '',
imageHeight : img ? img.height() : '',
imageTitle : img ? img.attr('title') : '',
imageAlign : img ? img.attr('align') : '',
clickFn : function(url, title, width, height, border, align) {
self.exec('insertimage', url, title, width, height, border, align);
// Bugfix: [Firefox] 上传图片后,总是出现正在加载的样式,需要延迟执行hideDialog
setTimeout(function() {
self.hideDialog().focus();
}, 0);
}
});
},
'delete' : function() {
self.plugin.getSelectedImage().remove();
}
};
self.clickToolbar(name, self.plugin.image.edit);
});
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('anchor', function(K) {
var self = this, name = 'anchor', lang = self.lang(name + '.');
self.plugin.anchor = {
edit : function() {
var html = ['<div style="padding:10px 20px;">',
'<div class="ke-dialog-row">',
'<label for="keName">' + lang.name + '</label>',
'<input class="ke-input-text" type="text" id="keName" name="name" value="" style="width:100px;" />',
'</div>',
'</div>'].join('');
var dialog = self.createDialog({
name : name,
width : 300,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
self.insertHtml('<a name="' + nameBox.val() + '">').hideDialog().focus();
}
}
});
var div = dialog.div,
nameBox = K('input[name="name"]', div);
var img = self.plugin.getSelectedAnchor();
if (img) {
nameBox.val(unescape(img.attr('data-ke-name')));
}
nameBox[0].focus();
nameBox[0].select();
},
'delete' : function() {
self.plugin.getSelectedAnchor().remove();
}
};
self.clickToolbar(name, self.plugin.anchor.edit);
});
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
// google code prettify: http://google-code-prettify.googlecode.com/
// http://google-code-prettify.googlecode.com/
KindEditor.plugin('code', function(K) {
var self = this, name = 'code';
self.clickToolbar(name, function() {
var lang = self.lang(name + '.'),
html = ['<div style="padding:10px 20px;">',
'<div class="ke-dialog-row">',
'<select class="ke-code-type">',
'<option value="js">JavaScript</option>',
'<option value="html">HTML</option>',
'<option value="css">CSS</option>',
'<option value="php">PHP</option>',
'<option value="pl">Perl</option>',
'<option value="py">Python</option>',
'<option value="rb">Ruby</option>',
'<option value="java">Java</option>',
'<option value="vb">ASP/VB</option>',
'<option value="cpp">C/C++</option>',
'<option value="cs">C#</option>',
'<option value="xml">XML</option>',
'<option value="bsh">Shell</option>',
'<option value="">Other</option>',
'</select>',
'</div>',
'<textarea class="ke-textarea" style="width:408px;height:260px;"></textarea>',
'</div>'].join(''),
dialog = self.createDialog({
name : name,
width : 450,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var type = K('.ke-code-type', dialog.div).val(),
code = textarea.val(),
cls = type === '' ? '' : ' lang-' + type,
html = '<pre class="prettyprint' + cls + '">\n' + K.escape(code) + '</pre> ';
self.insertHtml(html).hideDialog().focus();
}
}
}),
textarea = K('textarea', dialog.div);
textarea[0].focus();
});
});
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('template', function(K) {
var self = this, name = 'template', lang = self.lang(name + '.'),
htmlPath = self.pluginsPath + name + '/html/';
function getFilePath(fileName) {
return htmlPath + fileName + '?ver=' + encodeURIComponent(K.DEBUG ? K.TIME : K.VERSION);
}
self.clickToolbar(name, function() {
var lang = self.lang(name + '.'),
arr = ['<div class="ke-plugin-template" style="padding:10px 20px;">',
'<div class="ke-header">',
// left start
'<div class="ke-left">',
lang. selectTemplate + ' <select>'];
K.each(lang.fileList, function(key, val) {
arr.push('<option value="' + key + '">' + val + '</option>');
});
html = [arr.join(''),
'</select></div>',
// right start
'<div class="ke-right">',
'<input type="checkbox" id="keReplaceFlag" name="replaceFlag" value="1" /> <label for="keReplaceFlag">' + lang.replaceContent + '</label>',
'</div>',
'<div class="ke-clearfix"></div>',
'</div>',
'<iframe class="ke-textarea" frameborder="0" style="width:458px;height:260px;background-color:#FFF;"></iframe>',
'</div>'].join('');
var dialog = self.createDialog({
name : name,
width : 500,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var doc = K.iframeDoc(iframe);
self[checkbox[0].checked ? 'html' : 'insertHtml'](doc.body.innerHTML).hideDialog().focus();
}
}
});
var selectBox = K('select', dialog.div),
checkbox = K('[name="replaceFlag"]', dialog.div),
iframe = K('iframe', dialog.div);
checkbox[0].checked = true;
iframe.attr('src', getFilePath(selectBox.val()));
selectBox.change(function() {
iframe.attr('src', getFilePath(this.value));
});
});
});
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('filemanager', function(K) {
var self = this, name = 'filemanager',
fileManagerJson = K.undef(self.fileManagerJson, self.basePath + '/ashx/file_manager_json.ashx'),
imgPath = self.pluginsPath + name + '/images/',
lang = self.lang(name + '.');
function makeFileTitle(filename, filesize, datetime) {
return filename + ' (' + Math.ceil(filesize / 1024) + 'KB, ' + datetime + ')';
}
function bindTitle(el, data) {
if (data.is_dir) {
el.attr('title', data.filename);
} else {
el.attr('title', makeFileTitle(data.filename, data.filesize, data.datetime));
}
}
self.plugin.filemanagerDialog = function(options) {
var width = K.undef(options.width, 520),
height = K.undef(options.height, 510),
dirName = K.undef(options.dirName, ''),
viewType = K.undef(options.viewType, 'VIEW').toUpperCase(), // "LIST" or "VIEW"
clickFn = options.clickFn;
var html = [
'<div style="padding:10px 20px;">',
// header start
'<div class="ke-plugin-filemanager-header">',
// left start
'<div class="ke-left">',
'<img class="ke-inline-block" name="moveupImg" src="' + imgPath + 'go-up.gif" width="16" height="16" border="0" alt="" /> ',
'<a class="ke-inline-block" name="moveupLink" href="javascript:;">' + lang.moveup + '</a>',
'</div>',
// right start
'<div class="ke-right">',
lang.viewType + ' <select class="ke-inline-block" name="viewType">',
'<option value="VIEW">' + lang.viewImage + '</option>',
'<option value="LIST">' + lang.listImage + '</option>',
'</select> ',
lang.orderType + ' <select class="ke-inline-block" name="orderType">',
'<option value="NAME">' + lang.fileName + '</option>',
'<option value="SIZE">' + lang.fileSize + '</option>',
'<option value="TYPE">' + lang.fileType + '</option>',
'</select>',
'</div>',
'<div class="ke-clearfix"></div>',
'</div>',
// body start
'<div class="ke-plugin-filemanager-body"></div>',
'</div>'
].join('');
var dialog = self.createDialog({
name : name,
width : width,
height : height,
title : self.lang(name),
body : html
}),
div = dialog.div,
bodyDiv = K('.ke-plugin-filemanager-body', div),
moveupImg = K('[name="moveupImg"]', div),
moveupLink = K('[name="moveupLink"]', div),
viewServerBtn = K('[name="viewServer"]', div),
viewTypeBox = K('[name="viewType"]', div),
orderTypeBox = K('[name="orderType"]', div);
function reloadPage(path, order, func) {
var param = 'path=' + path + '&order=' + order + '&dir=' + dirName;
dialog.showLoading(self.lang('ajaxLoading'));
K.ajax(K.addParam(fileManagerJson, param + '&' + new Date().getTime()), function(data) {
dialog.hideLoading();
func(data);
});
}
var elList = [];
function bindEvent(el, result, data, createFunc) {
var fileUrl = K.formatUrl(result.current_url + data.filename, 'absolute'),
dirPath = encodeURIComponent(result.current_dir_path + data.filename + '/');
if (data.is_dir) {
el.click(function(e) {
reloadPage(dirPath, orderTypeBox.val(), createFunc);
});
} else if (data.is_photo) {
el.click(function(e) {
clickFn.call(this, fileUrl, data.filename);
});
} else {
el.click(function(e) {
clickFn.call(this, fileUrl, data.filename);
});
}
elList.push(el);
}
function createCommon(result, createFunc) {
// remove events
K.each(elList, function() {
this.unbind();
});
moveupLink.unbind();
viewTypeBox.unbind();
orderTypeBox.unbind();
// add events
if (result.current_dir_path) {
moveupLink.click(function(e) {
reloadPage(result.moveup_dir_path, orderTypeBox.val(), createFunc);
});
}
function changeFunc() {
if (viewTypeBox.val() == 'VIEW') {
reloadPage(result.current_dir_path, orderTypeBox.val(), createView);
} else {
reloadPage(result.current_dir_path, orderTypeBox.val(), createList);
}
}
viewTypeBox.change(changeFunc);
orderTypeBox.change(changeFunc);
bodyDiv.html('');
}
function createList(result) {
createCommon(result, createList);
var table = document.createElement('table');
table.className = 'ke-table';
table.cellPadding = 0;
table.cellSpacing = 0;
table.border = 0;
bodyDiv.append(table);
var fileList = result.file_list;
for (var i = 0, len = fileList.length; i < len; i++) {
var data = fileList[i], row = K(table.insertRow(i));
row.mouseover(function(e) {
K(this).addClass('ke-on');
})
.mouseout(function(e) {
K(this).removeClass('ke-on');
});
var iconUrl = imgPath + (data.is_dir ? 'folder-16.gif' : 'file-16.gif'),
img = K('<img src="' + iconUrl + '" width="16" height="16" alt="' + data.filename + '" align="absmiddle" />'),
cell0 = K(row[0].insertCell(0)).addClass('ke-cell ke-name').append(img).append(document.createTextNode(' ' + data.filename));
if (!data.is_dir || data.has_file) {
row.css('cursor', 'pointer');
cell0.attr('title', data.filename);
bindEvent(cell0, result, data, createList);
} else {
cell0.attr('title', lang.emptyFolder);
}
K(row[0].insertCell(1)).addClass('ke-cell ke-size').html(data.is_dir ? '-' : Math.ceil(data.filesize / 1024) + 'KB');
K(row[0].insertCell(2)).addClass('ke-cell ke-datetime').html(data.datetime);
}
}
function createView(result) {
createCommon(result, createView);
var fileList = result.file_list;
for (var i = 0, len = fileList.length; i < len; i++) {
var data = fileList[i],
div = K('<div class="ke-inline-block ke-item"></div>');
bodyDiv.append(div);
var photoDiv = K('<div class="ke-inline-block ke-photo"></div>')
.mouseover(function(e) {
K(this).addClass('ke-on');
})
.mouseout(function(e) {
K(this).removeClass('ke-on');
});
div.append(photoDiv);
var fileUrl = result.current_url + data.filename,
iconUrl = data.is_dir ? imgPath + 'folder-64.gif' : (data.is_photo ? fileUrl : imgPath + 'file-64.gif');
var img = K('<img src="' + iconUrl + '" width="80" height="80" alt="' + data.filename + '" />');
if (!data.is_dir || data.has_file) {
photoDiv.css('cursor', 'pointer');
bindTitle(photoDiv, data);
bindEvent(photoDiv, result, data, createView);
} else {
photoDiv.attr('title', lang.emptyFolder);
}
photoDiv.append(img);
div.append('<div class="ke-name" title="' + data.filename + '">' + data.filename + '</div>');
}
}
viewTypeBox.val(viewType);
reloadPage('', orderTypeBox.val(), viewType == 'VIEW' ? createView : createList);
return dialog;
}
});
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('table', function(K) {
var self = this, name = 'table', lang = self.lang(name + '.'), zeroborder = 'ke-zeroborder';
// 取得下一行cell的index
function _getCellIndex(table, row, cell) {
var rowSpanCount = 0;
for (var i = 0, len = row.cells.length; i < len; i++) {
if (row.cells[i] == cell) {
break;
}
rowSpanCount += row.cells[i].rowSpan - 1;
}
return cell.cellIndex - rowSpanCount;
}
self.plugin.table = {
//insert or modify table
prop : function(isInsert) {
var html = [
'<div style="padding:10px 20px;">',
//rows, cols
'<div class="ke-dialog-row">',
'<label for="keRows" style="width:90px;">' + lang.cells + '</label>',
lang.rows + ' <input type="text" id="keRows" class="ke-input-text ke-input-number" name="rows" value="" maxlength="4" /> ',
lang.cols + ' <input type="text" class="ke-input-text ke-input-number" name="cols" value="" maxlength="4" />',
'</div>',
//width, height
'<div class="ke-dialog-row">',
'<label for="keWidth" style="width:90px;">' + lang.size + '</label>',
lang.width + ' <input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> ',
'<select name="widthType">',
'<option value="%">' + lang.percent + '</option>',
'<option value="px">' + lang.px + '</option>',
'</select> ',
lang.height + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> ',
'<select name="heightType">',
'<option value="%">' + lang.percent + '</option>',
'<option value="px">' + lang.px + '</option>',
'</select>',
'</div>',
//space, padding
'<div class="ke-dialog-row">',
'<label for="kePadding" style="width:90px;">' + lang.space + '</label>',
lang.padding + ' <input type="text" id="kePadding" class="ke-input-text ke-input-number" name="padding" value="" maxlength="4" /> ',
lang.spacing + ' <input type="text" class="ke-input-text ke-input-number" name="spacing" value="" maxlength="4" />',
'</div>',
//align
'<div class="ke-dialog-row">',
'<label for="keAlign" style="width:90px;">' + lang.align + '</label>',
'<select id="keAlign" name="align">',
'<option value="">' + lang.alignDefault + '</option>',
'<option value="left">' + lang.alignLeft + '</option>',
'<option value="center">' + lang.alignCenter + '</option>',
'<option value="right">' + lang.alignRight + '</option>',
'</select>',
'</div>',
//border
'<div class="ke-dialog-row">',
'<label for="keBorder" style="width:90px;">' + lang.border + '</label>',
lang.borderWidth + ' <input type="text" id="keBorder" class="ke-input-text ke-input-number" name="border" value="" maxlength="4" /> ',
lang.borderColor + ' <span class="ke-inline-block ke-input-color"></span>',
'</div>',
//background color
'<div class="ke-dialog-row">',
'<label for="keBgColor" style="width:90px;">' + lang.backgroundColor + '</label>',
'<span class="ke-inline-block ke-input-color"></span>',
'</div>',
'</div>'
].join('');
var picker, currentElement;
function removePicker() {
if (picker) {
picker.remove();
picker = null;
currentElement = null;
}
}
var dialog = self.createDialog({
name : name,
width : 500,
height : 300,
title : self.lang(name),
body : html,
beforeDrag : removePicker,
beforeRemove : function() {
removePicker();
colorBox.unbind();
},
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var rows = rowsBox.val(),
cols = colsBox.val(),
width = widthBox.val(),
height = heightBox.val(),
widthType = widthTypeBox.val(),
heightType = heightTypeBox.val(),
padding = paddingBox.val(),
spacing = spacingBox.val(),
align = alignBox.val(),
border = borderBox.val(),
borderColor = K(colorBox[0]).html() || '',
bgColor = K(colorBox[1]).html() || '';
if (rows == 0 || !/^\d+$/.test(rows)) {
alert(self.lang('invalidRows'));
rowsBox[0].focus();
return;
}
if (cols == 0 || !/^\d+$/.test(cols)) {
alert(self.lang('invalidRows'));
colsBox[0].focus();
return;
}
if (!/^\d*$/.test(width)) {
alert(self.lang('invalidWidth'));
widthBox[0].focus();
return;
}
if (!/^\d*$/.test(height)) {
alert(self.lang('invalidHeight'));
heightBox[0].focus();
return;
}
if (!/^\d*$/.test(padding)) {
alert(self.lang('invalidPadding'));
paddingBox[0].focus();
return;
}
if (!/^\d*$/.test(spacing)) {
alert(self.lang('invalidSpacing'));
spacingBox[0].focus();
return;
}
if (!/^\d*$/.test(border)) {
alert(self.lang('invalidBorder'));
borderBox[0].focus();
return;
}
//modify table
if (table) {
if (width !== '') {
table.width(width + widthType);
} else {
table.css('width', '');
}
if (table[0].width !== undefined) {
table.removeAttr('width');
}
if (height !== '') {
table.height(height + heightType);
} else {
table.css('height', '');
}
if (table[0].height !== undefined) {
table.removeAttr('height');
}
table.css('background-color', bgColor);
if (table[0].bgColor !== undefined) {
table.removeAttr('bgColor');
}
if (padding !== '') {
table[0].cellPadding = padding;
} else {
table.removeAttr('cellPadding');
}
if (spacing !== '') {
table[0].cellSpacing = spacing;
} else {
table.removeAttr('cellSpacing');
}
if (align !== '') {
table[0].align = align;
} else {
table.removeAttr('align');
}
if (border !== '') {
table.attr('border', border);
} else {
table.removeAttr('border');
}
if (border === '' || border === '0') {
table.addClass(zeroborder);
} else {
table.removeClass(zeroborder);
}
if (borderColor !== '') {
table.attr('borderColor', borderColor);
} else {
table.removeAttr('borderColor');
}
self.hideDialog().focus();
return;
}
//insert new table
var style = '';
if (width !== '') {
style += 'width:' + width + widthType + ';';
}
if (height !== '') {
style += 'height:' + height + heightType + ';';
}
if (bgColor !== '') {
style += 'background-color:' + bgColor + ';';
}
var html = '<table';
if (style !== '') {
html += ' style="' + style + '"';
}
if (padding !== '') {
html += ' cellpadding="' + padding + '"';
}
if (spacing !== '') {
html += ' cellspacing="' + spacing + '"';
}
if (align !== '') {
html += ' align="' + align + '"';
}
if (border !== '') {
html += ' border="' + border + '"';
}
if (border === '' || border === '0') {
html += ' class="' + zeroborder + '"';
}
if (borderColor !== '') {
html += ' bordercolor="' + borderColor + '"';
}
html += '>';
for (var i = 0; i < rows; i++) {
html += '<tr>';
for (var j = 0; j < cols; j++) {
html += '<td>' + (K.IE ? ' ' : '<br />') + '</td>';
}
html += '</tr>';
}
html += '</table>';
if (!K.IE) {
html += '<br />';
}
self.insertHtml(html);
self.select().hideDialog().focus();
self.addBookmark();
}
}
}),
div = dialog.div,
rowsBox = K('[name="rows"]', div).val(3),
colsBox = K('[name="cols"]', div).val(2),
widthBox = K('[name="width"]', div).val(100),
heightBox = K('[name="height"]', div),
widthTypeBox = K('[name="widthType"]', div),
heightTypeBox = K('[name="heightType"]', div),
paddingBox = K('[name="padding"]', div).val(2),
spacingBox = K('[name="spacing"]', div).val(0),
alignBox = K('[name="align"]', div),
borderBox = K('[name="border"]', div).val(1),
colorBox = K('.ke-input-color', div);
function setColor(box, color) {
color = color.toUpperCase();
box.css('background-color', color);
box.css('color', color === '#000000' ? '#FFFFFF' : '#000000');
box.html(color);
}
setColor(K(colorBox[0]), '#000000');
setColor(K(colorBox[1]), '');
function clickHandler(e) {
removePicker();
if (!picker || this !== currentElement) {
var box = K(this),
pos = box.pos();
picker = K.colorpicker({
x : pos.x,
y : pos.y + box.height(),
z : 811214,
selectedColor : K(this).html(),
colors : self.colorTable,
noColor : self.lang('noColor'),
shadowMode : self.shadowMode,
click : function(color) {
setColor(box, color);
removePicker();
}
});
currentElement = this;
}
}
colorBox.click(clickHandler);
// foucs and select
rowsBox[0].focus();
rowsBox[0].select();
var table;
if (isInsert) {
return;
}
//get selected table node
table = self.plugin.getSelectedTable();
if (table) {
rowsBox.val(table[0].rows.length);
colsBox.val(table[0].rows.length > 0 ? table[0].rows[0].cells.length : 0);
rowsBox.attr('disabled', true);
colsBox.attr('disabled', true);
var match,
tableWidth = table[0].style.width || table[0].width,
tableHeight = table[0].style.height || table[0].height;
if (tableWidth !== undefined && (match = /^(\d+)((?:px|%)*)$/.exec(tableWidth))) {
widthBox.val(match[1]);
widthTypeBox.val(match[2]);
} else {
widthBox.val('');
}
if (tableHeight !== undefined && (match = /^(\d+)((?:px|%)*)$/.exec(tableHeight))) {
heightBox.val(match[1]);
heightTypeBox.val(match[2]);
}
paddingBox.val(table[0].cellPadding || '');
spacingBox.val(table[0].cellSpacing || '');
alignBox.val(table[0].align || '');
borderBox.val(table[0].border === undefined ? '' : table[0].border);
setColor(K(colorBox[0]), K.toHex(table.attr('borderColor') || ''));
setColor(K(colorBox[1]), K.toHex(table[0].style.backgroundColor || table[0].bgColor || ''));
widthBox[0].focus();
widthBox[0].select();
}
},
//modify cell
cellprop : function() {
var html = [
'<div style="padding:10px 20px;">',
//width, height
'<div class="ke-dialog-row">',
'<label for="keWidth" style="width:90px;">' + lang.size + '</label>',
lang.width + ' <input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> ',
'<select name="widthType">',
'<option value="%">' + lang.percent + '</option>',
'<option value="px">' + lang.px + '</option>',
'</select> ',
lang.height + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> ',
'<select name="heightType">',
'<option value="%">' + lang.percent + '</option>',
'<option value="px">' + lang.px + '</option>',
'</select>',
'</div>',
//align
'<div class="ke-dialog-row">',
'<label for="keAlign" style="width:90px;">' + lang.align + '</label>',
lang.textAlign + ' <select id="keAlign" name="textAlign">',
'<option value="">' + lang.alignDefault + '</option>',
'<option value="left">' + lang.alignLeft + '</option>',
'<option value="center">' + lang.alignCenter + '</option>',
'<option value="right">' + lang.alignRight + '</option>',
'</select> ',
lang.verticalAlign + ' <select name="verticalAlign">',
'<option value="">' + lang.alignDefault + '</option>',
'<option value="top">' + lang.alignTop + '</option>',
'<option value="middle">' + lang.alignMiddle + '</option>',
'<option value="bottom">' + lang.alignBottom + '</option>',
'<option value="baseline">' + lang.alignBaseline + '</option>',
'</select>',
'</div>',
//border
'<div class="ke-dialog-row">',
'<label for="keBorder" style="width:90px;">' + lang.border + '</label>',
lang.borderWidth + ' <input type="text" id="keBorder" class="ke-input-text ke-input-number" name="border" value="" maxlength="4" /> ',
lang.borderColor + ' <span class="ke-inline-block ke-input-color"></span>',
'</div>',
//background color
'<div class="ke-dialog-row">',
'<label for="keBgColor" style="width:90px;">' + lang.backgroundColor + '</label>',
'<span class="ke-inline-block ke-input-color"></span>',
'</div>',
'</div>'
].join('');
var picker, currentElement;
function removePicker() {
if (picker) {
picker.remove();
picker = null;
currentElement = null;
}
}
var dialog = self.createDialog({
name : name,
width : 500,
height : 220,
title : self.lang('tablecell'),
body : html,
beforeDrag : removePicker,
beforeRemove : function() {
removePicker();
colorBox.unbind();
},
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var width = widthBox.val(),
height = heightBox.val(),
widthType = widthTypeBox.val(),
heightType = heightTypeBox.val(),
padding = paddingBox.val(),
spacing = spacingBox.val(),
textAlign = textAlignBox.val(),
verticalAlign = verticalAlignBox.val(),
border = borderBox.val(),
borderColor = K(colorBox[0]).html() || '',
bgColor = K(colorBox[1]).html() || '';
if (!/^\d*$/.test(width)) {
alert(self.lang('invalidWidth'));
widthBox[0].focus();
return;
}
if (!/^\d*$/.test(height)) {
alert(self.lang('invalidHeight'));
heightBox[0].focus();
return;
}
if (!/^\d*$/.test(border)) {
alert(self.lang('invalidBorder'));
borderBox[0].focus();
return;
}
cell.css({
width : width !== '' ? (width + widthType) : '',
height : height !== '' ? (height + heightType) : '',
'background-color' : bgColor,
'text-align' : textAlign,
'vertical-align' : verticalAlign,
'border-width' : border,
'border-style' : border !== '' ? 'solid' : '',
'border-color' : borderColor
});
self.hideDialog().focus();
self.addBookmark();
}
}
}),
div = dialog.div,
widthBox = K('[name="width"]', div).val(100),
heightBox = K('[name="height"]', div),
widthTypeBox = K('[name="widthType"]', div),
heightTypeBox = K('[name="heightType"]', div),
paddingBox = K('[name="padding"]', div).val(2),
spacingBox = K('[name="spacing"]', div).val(0),
textAlignBox = K('[name="textAlign"]', div),
verticalAlignBox = K('[name="verticalAlign"]', div),
borderBox = K('[name="border"]', div).val(1),
colorBox = K('.ke-input-color', div);
function setColor(box, color) {
color = color.toUpperCase();
box.css('background-color', color);
box.css('color', color === '#000000' ? '#FFFFFF' : '#000000');
box.html(color);
}
setColor(K(colorBox[0]), '#000000');
setColor(K(colorBox[1]), '');
function clickHandler(e) {
removePicker();
if (!picker || this !== currentElement) {
var box = K(this),
pos = box.pos();
picker = K.colorpicker({
x : pos.x,
y : pos.y + box.height(),
z : 811214,
selectedColor : K(this).html(),
colors : self.colorTable,
noColor : self.lang('noColor'),
shadowMode : self.shadowMode,
click : function(color) {
setColor(box, color);
removePicker();
}
});
currentElement = this;
}
}
colorBox.click(clickHandler);
// foucs and select
widthBox[0].focus();
widthBox[0].select();
// get selected cell
var cell = self.plugin.getSelectedCell();
var match,
cellWidth = cell[0].style.width || cell[0].width || '',
cellHeight = cell[0].style.height || cell[0].height || '';
if ((match = /^(\d+)((?:px|%)*)$/.exec(cellWidth))) {
widthBox.val(match[1]);
widthTypeBox.val(match[2]);
} else {
widthBox.val('');
}
if ((match = /^(\d+)((?:px|%)*)$/.exec(cellHeight))) {
heightBox.val(match[1]);
heightTypeBox.val(match[2]);
}
textAlignBox.val(cell[0].style.textAlign || '');
verticalAlignBox.val(cell[0].style.verticalAlign || '');
var border = cell[0].style.borderWidth || '';
if (border) {
border = parseInt(border);
}
borderBox.val(border);
setColor(K(colorBox[0]), K.toHex(cell[0].style.borderColor || ''));
setColor(K(colorBox[1]), K.toHex(cell[0].style.backgroundColor || ''));
widthBox[0].focus();
widthBox[0].select();
},
insert : function() {
this.prop(true);
},
'delete' : function() {
var table = self.plugin.getSelectedTable();
self.cmd.range.setStartBefore(table[0]).collapse(true);
self.cmd.select();
table.remove();
self.addBookmark();
},
colinsert : function(offset) {
var table = self.plugin.getSelectedTable()[0],
row = self.plugin.getSelectedRow()[0],
cell = self.plugin.getSelectedCell()[0],
index = cell.cellIndex + offset;
for (var i = 0, len = table.rows.length; i < len; i++) {
var newRow = table.rows[i],
newCell = newRow.insertCell(index);
newCell.innerHTML = K.IE ? '' : '<br />';
// 调整下一行的单元格index
index = _getCellIndex(table, newRow, newCell);
}
self.cmd.range.selectNodeContents(cell).collapse(true);
self.cmd.select();
self.addBookmark();
},
colinsertleft : function() {
this.colinsert(0);
},
colinsertright : function() {
this.colinsert(1);
},
rowinsert : function(offset) {
var table = self.plugin.getSelectedTable()[0],
row = self.plugin.getSelectedRow()[0],
cell = self.plugin.getSelectedCell()[0],
newRow;
if (offset === 1) {
newRow = table.insertRow(row.rowIndex + (cell.rowSpan - 1) + offset);
} else {
newRow = table.insertRow(row.rowIndex);
}
for (var i = 0, len = row.cells.length; i < len; i++) {
var newCell = newRow.insertCell(i);
// copy colspan
if (offset === 1 && row.cells[i].colSpan > 1) {
newCell.colSpan = row.cells[i].colSpan;
}
newCell.innerHTML = K.IE ? '' : '<br />';
}
self.cmd.range.selectNodeContents(cell).collapse(true);
self.cmd.select();
self.addBookmark();
},
rowinsertabove : function() {
this.rowinsert(0);
},
rowinsertbelow : function() {
this.rowinsert(1);
},
rowmerge : function() {
var table = self.plugin.getSelectedTable()[0],
row = self.plugin.getSelectedRow()[0],
cell = self.plugin.getSelectedCell()[0],
rowIndex = row.rowIndex, // 当前行的index
nextRowIndex = rowIndex + cell.rowSpan, // 下一行的index
nextRow = table.rows[nextRowIndex]; // 下一行
// 最后一行不能合并
if (table.rows.length <= nextRowIndex) {
return;
}
var cellIndex = _getCellIndex(table, row, cell); // 下一行单元格的index
if (nextRow.cells.length <= cellIndex) {
return;
}
var nextCell = nextRow.cells[cellIndex]; // 下一行单元格
// 上下行的colspan不一致时不能合并
if (cell.colSpan !== nextCell.colSpan) {
return;
}
cell.rowSpan += nextCell.rowSpan;
nextRow.deleteCell(cellIndex);
self.cmd.range.selectNodeContents(cell).collapse(true);
self.cmd.select();
self.addBookmark();
},
colmerge : function() {
var table = self.plugin.getSelectedTable()[0],
row = self.plugin.getSelectedRow()[0],
cell = self.plugin.getSelectedCell()[0],
rowIndex = row.rowIndex, // 当前行的index
cellIndex = cell.cellIndex,
nextCellIndex = cellIndex + 1;
// 最后一列不能合并
if (row.cells.length <= nextCellIndex) {
return;
}
var nextCell = row.cells[nextCellIndex];
// 左右列的rowspan不一致时不能合并
if (cell.rowSpan !== nextCell.rowSpan) {
return;
}
cell.colSpan += nextCell.colSpan;
row.deleteCell(nextCellIndex);
self.cmd.range.selectNodeContents(cell).collapse(true);
self.cmd.select();
self.addBookmark();
},
rowsplit : function() {
var table = self.plugin.getSelectedTable()[0],
row = self.plugin.getSelectedRow()[0],
cell = self.plugin.getSelectedCell()[0],
rowIndex = row.rowIndex;
// 不是可分割单元格
if (cell.rowSpan === 1) {
return;
}
var cellIndex = _getCellIndex(table, row, cell);
for (var i = 1, len = cell.rowSpan; i < len; i++) {
var newRow = table.rows[rowIndex + i],
newCell = newRow.insertCell(cellIndex);
if (cell.colSpan > 1) {
newCell.colSpan = cell.colSpan;
}
newCell.innerHTML = K.IE ? '' : '<br />';
// 调整下一行的单元格index
cellIndex = _getCellIndex(table, newRow, newCell);
}
K(cell).removeAttr('rowSpan');
self.cmd.range.selectNodeContents(cell).collapse(true);
self.cmd.select();
self.addBookmark();
},
colsplit : function() {
var table = self.plugin.getSelectedTable()[0],
row = self.plugin.getSelectedRow()[0],
cell = self.plugin.getSelectedCell()[0],
cellIndex = cell.cellIndex;
// 不是可分割单元格
if (cell.colSpan === 1) {
return;
}
for (var i = 1, len = cell.colSpan; i < len; i++) {
var newCell = row.insertCell(cellIndex + i);
if (cell.rowSpan > 1) {
newCell.rowSpan = cell.rowSpan;
}
newCell.innerHTML = K.IE ? '' : '<br />';
}
K(cell).removeAttr('colSpan');
self.cmd.range.selectNodeContents(cell).collapse(true);
self.cmd.select();
self.addBookmark();
},
coldelete : function() {
var table = self.plugin.getSelectedTable()[0],
row = self.plugin.getSelectedRow()[0],
cell = self.plugin.getSelectedCell()[0],
index = cell.cellIndex;
for (var i = 0, len = table.rows.length; i < len; i++) {
var newRow = table.rows[i],
newCell = newRow.cells[index];
if (newCell.colSpan > 1) {
newCell.colSpan -= 1;
if (newCell.colSpan === 1) {
K(newCell).removeAttr('colSpan');
}
} else {
newRow.deleteCell(index);
}
// 跳过不需要删除的行
if (newCell.rowSpan > 1) {
i += newCell.rowSpan - 1;
}
}
if (row.cells.length === 0) {
self.cmd.range.setStartBefore(table).collapse(true);
self.cmd.select();
K(table).remove();
} else {
self.cmd.selection(true);
}
self.addBookmark();
},
rowdelete : function() {
var table = self.plugin.getSelectedTable()[0],
row = self.plugin.getSelectedRow()[0],
cell = self.plugin.getSelectedCell()[0],
rowIndex = row.rowIndex;
// 从下到上删除
for (var i = cell.rowSpan - 1; i >= 0; i--) {
table.deleteRow(rowIndex + i);
}
if (table.rows.length === 0) {
self.cmd.range.setStartBefore(table).collapse(true);
self.cmd.select();
K(table).remove();
} else {
self.cmd.selection(true);
}
self.addBookmark();
}
};
self.clickToolbar(name, self.plugin.table.prop);
});
|
JavaScript
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('emoticons', function(K) {
var self = this, name = 'emoticons',
path = (self.emoticonsPath || self.basePath + 'plugins/emoticons/images/'),
allowPreview = self.allowPreviewEmoticons === undefined ? true : self.allowPreviewEmoticons,
currentPageNum = 1;
self.clickToolbar(name, function() {
var rows = 5, cols = 9, total = 135, startNum = 0,
cells = rows * cols, pages = Math.ceil(total / cells),
colsHalf = Math.floor(cols / 2),
wrapperDiv = K('<div class="ke-plugin-emoticons"></div>'),
elements = [],
menu = self.createMenu({
name : name,
beforeRemove : function() {
removeEvent();
}
});
menu.div.append(wrapperDiv);
var previewDiv, previewImg;
if (allowPreview) {
previewDiv = K('<div class="ke-preview"></div>').css('right', 0);
previewImg = K('<img class="ke-preview-img" src="' + path + startNum + '.gif" />');
wrapperDiv.append(previewDiv);
previewDiv.append(previewImg);
}
function bindCellEvent(cell, j, num) {
if (previewDiv) {
cell.mouseover(function() {
if (j > colsHalf) {
previewDiv.css('left', 0);
previewDiv.css('right', '');
} else {
previewDiv.css('left', '');
previewDiv.css('right', 0);
}
previewImg.attr('src', path + num + '.gif');
K(this).addClass('ke-on');
});
} else {
cell.mouseover(function() {
K(this).addClass('ke-on');
});
}
cell.mouseout(function() {
K(this).removeClass('ke-on');
});
cell.click(function(e) {
self.insertHtml('<img src="' + path + num + '.gif" border="0" alt="" />').hideMenu().focus();
e.stop();
});
}
function createEmoticonsTable(pageNum, parentDiv) {
var table = document.createElement('table');
parentDiv.append(table);
if (previewDiv) {
K(table).mouseover(function() {
previewDiv.show();
});
K(table).mouseout(function() {
previewDiv.hide();
});
elements.push(K(table));
}
table.className = 'ke-table';
table.cellPadding = 0;
table.cellSpacing = 0;
table.border = 0;
var num = (pageNum - 1) * cells + startNum;
for (var i = 0; i < rows; i++) {
var row = table.insertRow(i);
for (var j = 0; j < cols; j++) {
var cell = K(row.insertCell(j));
cell.addClass('ke-cell');
bindCellEvent(cell, j, num);
var span = K('<span class="ke-img"></span>')
.css('background-position', '-' + (24 * num) + 'px 0px')
.css('background-image', 'url(' + path + 'static.gif)');
cell.append(span);
elements.push(cell);
num++;
}
}
return table;
}
var table = createEmoticonsTable(currentPageNum, wrapperDiv);
function removeEvent() {
K.each(elements, function() {
this.unbind();
});
}
var pageDiv;
function bindPageEvent(el, pageNum) {
el.click(function(e) {
removeEvent();
table.parentNode.removeChild(table);
pageDiv.remove();
table = createEmoticonsTable(pageNum, wrapperDiv);
createPageTable(pageNum);
currentPageNum = pageNum;
e.stop();
});
}
function createPageTable(currentPageNum) {
pageDiv = K('<div class="ke-page"></div>');
wrapperDiv.append(pageDiv);
for (var pageNum = 1; pageNum <= pages; pageNum++) {
if (currentPageNum !== pageNum) {
var a = K('<a href="javascript:;">[' + pageNum + ']</a>');
bindPageEvent(a, pageNum);
pageDiv.append(a);
elements.push(a);
} else {
pageDiv.append(K('@[' + pageNum + ']'));
}
pageDiv.append(K('@ '));
}
}
createPageTable(currentPageNum);
});
});
|
JavaScript
|
/*
* Lazy Load - jQuery plugin for lazy loading images
*
* Copyright (c) 2007-2012 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* http://www.appelsiini.net/projects/lazyload
*
* Version: 1.7.2
*
*/
(function($, window) {
$window = $(window);
$.fn.lazyload = function(options) {
var elements = this;
var settings = {
threshold : 0,
failure_limit : 0,
event : "scroll",
effect : "show",
container : window,
data_attribute : "original",
skip_invisible : true,
appear : null,
load : null
};
function update() {
var counter = 0;
elements.each(function() {
var $this = $(this);
if (settings.skip_invisible && !$this.is(":visible")) {
return;
}
if ($.abovethetop(this, settings) ||
$.leftofbegin(this, settings)) {
/* Nothing. */
} else if (!$.belowthefold(this, settings) &&
!$.rightoffold(this, settings)) {
$this.trigger("appear");
} else {
if (++counter > settings.failure_limit) {
return false;
}
}
});
}
if(options) {
/* Maintain BC for a couple of versions. */
if (undefined !== options.failurelimit) {
options.failure_limit = options.failurelimit;
delete options.failurelimit;
}
if (undefined !== options.effectspeed) {
options.effect_speed = options.effectspeed;
delete options.effectspeed;
}
$.extend(settings, options);
}
/* Cache container as jQuery as object. */
$container = (settings.container === undefined ||
settings.container === window) ? $window : $(settings.container);
/* Fire one scroll event per scroll. Not one scroll event per image. */
if (0 === settings.event.indexOf("scroll")) {
$container.bind(settings.event, function(event) {
return update();
});
}
this.each(function() {
var self = this;
var $self = $(self);
self.loaded = false;
/* When appear is triggered load original image. */
$self.one("appear", function() {
if (!this.loaded) {
if (settings.appear) {
var elements_left = elements.length;
settings.appear.call(self, elements_left, settings);
}
$("<img />")
.bind("load", function() {
$self
.hide()
.attr("src", $self.data(settings.data_attribute))
[settings.effect](settings.effect_speed);
self.loaded = true;
/* Remove image from array so it is not looped next time. */
var temp = $.grep(elements, function(element) {
return !element.loaded;
});
elements = $(temp);
if (settings.load) {
var elements_left = elements.length;
settings.load.call(self, elements_left, settings);
}
})
.attr("src", $self.data(settings.data_attribute));
}
});
/* When wanted event is triggered load original image */
/* by triggering appear. */
if (0 !== settings.event.indexOf("scroll")) {
$self.bind(settings.event, function(event) {
if (!self.loaded) {
$self.trigger("appear");
}
});
}
});
/* Check if something appears when window is resized. */
$window.bind("resize", function(event) {
update();
});
/* Force initial check if images should appear. */
update();
return this;
};
/* Convenience methods in jQuery namespace. */
/* Use as $.belowthefold(element, {threshold : 100, container : window}) */
$.belowthefold = function(element, settings) {
var fold;
if (settings.container === undefined || settings.container === window) {
fold = $window.height() + $window.scrollTop();
} else {
fold = $container.offset().top + $container.height();
}
return fold <= $(element).offset().top - settings.threshold;
};
$.rightoffold = function(element, settings) {
var fold;
if (settings.container === undefined || settings.container === window) {
fold = $window.width() + $window.scrollLeft();
} else {
fold = $container.offset().left + $container.width();
}
return fold <= $(element).offset().left - settings.threshold;
};
$.abovethetop = function(element, settings) {
var fold;
if (settings.container === undefined || settings.container === window) {
fold = $window.scrollTop();
} else {
fold = $container.offset().top;
}
return fold >= $(element).offset().top + settings.threshold + $(element).height();
};
$.leftofbegin = function(element, settings) {
var fold;
if (settings.container === undefined || settings.container === window) {
fold = $window.scrollLeft();
} else {
fold = $container.offset().left;
}
return fold >= $(element).offset().left + settings.threshold + $(element).width();
};
$.inviewport = function(element, settings) {
return !$.rightofscreen(element, settings) && !$.leftofscreen(element, settings) &&
!$.belowthefold(element, settings) && !$.abovethetop(element, settings);
};
/* Custom selectors for your convenience. */
/* Use as $("img:below-the-fold").something() */
$.extend($.expr[':'], {
"below-the-fold" : function(a) { return $.belowthefold(a, {threshold : 0, container: window}); },
"above-the-top" : function(a) { return !$.belowthefold(a, {threshold : 0, container: window}); },
"right-of-screen": function(a) { return $.rightoffold(a, {threshold : 0, container: window}); },
"left-of-screen" : function(a) { return !$.rightoffold(a, {threshold : 0, container: window}); },
"in-viewport" : function(a) { return !$.inviewport(a, {threshold : 0, container: window}); },
/* Maintain BC for couple of versions. */
"above-the-fold" : function(a) { return !$.belowthefold(a, {threshold : 0, container: window}); },
"right-of-fold" : function(a) { return $.rightoffold(a, {threshold : 0, container: window}); },
"left-of-fold" : function(a) { return !$.rightoffold(a, {threshold : 0, container: window}); }
});
})(jQuery, window);
|
JavaScript
|
//==========================页面加载时JS函数开始===============================
$(document).ready(function () {
setWorkspace();
//分栏点击
$("#tableLeftMenuBar").click(function () {
if ($("#tableLeftMenu").css("display") == "block") {
$("#tableLeftMenu").hide();
$(this).find("span").html("4");
}
else {
$("#tableLeftMenu").show();
$(this).find("span").html("3");
}
})
//文本框焦点
$(".input,.login_input,.textarea,.input2").focus(function () {
if (!$(this).hasClass("tcal")) {
$(this).addClass("focus");
}
}).blur(function () {
$(this).removeClass("focus");
});
//输入框提示,获取拥有HintTitle,HintInfo属性的对象
$("[HintTitle],[HintInfo]").focus(function (event) {
$("*").stop(); //停止所有正在运行的动画
$("#HintMsg").remove(); //先清除,防止重复出错
var HintHtml = "<ul id=\"HintMsg\"><li class=\"HintTop\"></li><li class=\"HintInfo\"><b>" + $(this).attr("HintTitle") + "</b>" + $(this).attr("HintInfo") + "</li><li class=\"HintFooter\"></li></ul>"; //设置显示的内容
var offset = $(this).offset(); //取得事件对象的位置
$("body").append(HintHtml); //添加节点
$("#HintMsg").fadeTo(0, 0.85); //对象的透明度
var HintHeight = $("#HintMsg").height(); //取得容器高度
$("#HintMsg").css({ "top": offset.top - HintHeight + "px", "left": offset.left + "px" }).fadeIn(500);
}).blur(function (event) {
$("#HintMsg").remove(); //删除UL
});
//列表分组
$("div.navCur > span.t").click(function () {
$("div.navCur > span.t").removeClass("cur");
$(this).addClass("cur");
})
// //tabs
// $(".msgtable").find("a.cur").siblings().each(function (index) {
// var thisId = $(this).attr("href");
// $(thisId).css("display", "none");
// });
// $(".msgtable").find("a.t").click(function () {
// $($(this).attr("href")).css("display", "block");
// $(this).addClass("cur");
// $(this).siblings(".t").each(function (index) {
// var thisId = $(this).attr("href");
// $(thisId).css("display", "none");
// $(this).removeClass("cur");
// });
// //alert("123");
// })
//
$("#msgprint").live("click", function () {
$(this).hide();
})
//setWorkspace();
});
//==========================页面加载时JS函数结束===============================
/* 设置工作区 */
function setWorkspace(e) {
var wWidth = $(window).width();
var wHeight = $(window).height();
/*兼容性*/
if (navigator.appVersion.split("MSIE") && navigator.userAgent.indexOf('Opera') === -1 && parseFloat(navigator.appVersion.split("MSIE")[1]) < 7) wWidth = wWidth - 1; if (window.innerHeight) wHeight = window.innerHeight - 1;
//$('#workspace').width(wWidth - $('#left').width() - parseInt($('#left').css('margin-right')));
$('#sysMain').height(wHeight - 60); //alert(wWidth);
$("#tableConvertMain").width(wWidth - 170)
$("#frmmain").width($("#tableConvertMain").width());
$("#frmmain").height($("#tableConvertMain").height());
}
//===========================系统管理JS函数开始================================
//全选取消按钮函数,调用样式如:
function checkAll(chkobj) {
if ($(chkobj).text() == "全选") {
$(chkobj).text("取消");
$(".checkall input").attr("checked", true);
} else {
$(chkobj).text("全选");
$(".checkall input").attr("checked", false);
}
}
//遮罩提示窗口
function jsmsg(w, h, msgtitle, msgbox, url, msgcss) {
$("#msgdialog").remove();
var cssname = "";
switch (msgcss) {
case "Success":
cssname = "icon-01";
break;
case "Error":
cssname = "icon-02";
break;
default:
cssname = "icon-03";
break;
}
var str = "<div id='msgdialog' title='" + msgtitle + "'><p class='" + cssname + "'>" + msgbox + "</p></div>";
$("body").append(str);
$("#msgdialog").dialog({
//title: null,
//show: null,
bgiframe: true,
autoOpen: false,
width: w,
//height: h,
resizable: false,
closeOnEscape: true,
buttons: { "确定": function () { $(this).dialog("close"); } },
modal: true
});
$("#msgdialog").dialog("open");
if (url == "back") {
frmmain.history.back(-1);
} else if (url != "") {
frmmain.location.href = url;
}
}
function jsmsgCurPage(w, h, msgtitle, msgbox, url, msgcss) {
$("#msgdialog").remove();
var cssname = "";
switch (msgcss) {
case "Success":
cssname = "icon-01";
break;
case "Error":
cssname = "icon-02";
break;
default:
cssname = "icon-03";
break;
}
var str = "<div id='msgdialog' title='" + msgtitle + "'><p class='" + cssname + "'>" + msgbox + "</p></div>";
$("body").append(str);
$("#msgdialog").dialog({
//title: null,
//show: null,
bgiframe: true,
autoOpen: false,
width: w,
height: h,
resizable: false,
closeOnEscape: true,
buttons: { "确定": function () { $(this).dialog("close"); } },
modal: true
});
$("#msgdialog").dialog("open");
}
//可以自动关闭的提示
function jsprint(msgtitle, url, msgcss) {
$("#msgprint").remove();
var cssname = "";
switch (msgcss) {
case "Success":
cssname = "pcent correct";
break;
case "Error":
cssname = "pcent disable";
break;
default:
cssname = "pcent warning";
break;
}
var str = "<div id=\"msgprint\" class=\"" + cssname + "\">" + msgtitle + "</div>";
$("body").append(str);
$("#msgprint").show();
if (url == "back") {
frmmain.history.back(-1);
} else if (url != "") {
frmmain.location.href = url;
}
//3秒后清除提示
setTimeout(function () {
$("#msgprint").fadeOut(500);
//如果动画结束则删除节点
if (!$("#msgprint").is(":animated")) {
$("#msgprint").remove();
}
}, 3000);
}
//可以自动关闭的提示
function jsprintCurPage(msgtitle, url, msgcss) {
$("#msgprint").remove();
var cssname = "";
switch (msgcss) {
case "Success":
cssname = "pcent correct";
break;
case "Error":
cssname = "pcent disable";
break;
default:
cssname = "pcent warning";
break;
}
var str = "<div id=\"msgprint\" class=\"" + cssname + "\">" + msgtitle + "</div>";
$("body").append(str);
$("#msgprint").show();
var outT = 900;
var outT2 = 3000;
if (url == "thickbox") {
outT = 500;
outT2 = 1500;
}
//3秒后清除提示
setTimeout(function () {
$("#msgprint").fadeOut(outT);
//如果动画结束则删除节点
if (!$("#msgprint").is(":animated")) {
$("#msgprint").remove();
}
if (url == "back") {
this.history.back(-1);
} else if (url == "#") {
return;
} else if (url == "thickbox") {
TB_iframeContent.location.href = $("#TB_iframeContent").attr("src");
} else if (url != "") {
this.location.href = url;
}
}, outT2);
}
|
JavaScript
|
$(document).ready(function () {
$.formValidator.initConfig({ formID: "form1", theme: "ArrowSolidBox", submitOnce: false,
onError: function (msg, obj, errorlist) {
$("#errorlist").empty();
$.map(errorlist, function (msg) {
$("#errorlist").append("<li>" + msg + "</li>")
});
alert(msg);
},
ajaxPrompt: '有数据正在异步验证,请稍等...'
});
//验证工厂名
$("#txtmarkettitle").formValidator({ onShow: "请输入卖场名称,例:金盛国际家居广场(上海)", onFocus: "卖场名称至少3个字符,最多25个字符", onCorrect: "该卖场名称可以注册" }).inputValidator({ min: 3, max: 25, onError: "你输入的卖场名称非法,请确认" })//.regexValidator({regExp:"username",dataType:"enum",onError:"用户名格式不正确"})
.ajaxValidator({
dataType: "html",
async: true,
url: "../ajax/ajaxSupplerValidator.ashx?type=checkmarkettitle",
success: function (data) {
if (data.indexOf("卖场名称可以添加") > -1) { return true; } else {
return data;
}
},
buttons: $("#btnSave"),
error: function (jqXHR, textStatus, errorThrown) { alert("服务器没有返回数据,可能服务器忙,请重试" + errorThrown); },
onError: "该用卖场名称不可用,请更换用卖场名称",
onWait: "正在对用卖场名称进行合法性校验,请稍候..."
}).defaultPassed();
$("#txtphone").formValidator({ empty: true, onShow: "请输入你的联系电话,可以为空哦", onFocus: "格式例如:0577-88888888", onCorrect: "谢谢你的合作", onEmpty: "你真的不想留联系电话了吗?" }).regexValidator({ regExp: "^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$", onError: "你输入的联系电话格式不正确" });
});
|
JavaScript
|
$(document).ready(function () {
$.formValidator.initConfig({ formID: "form1", theme: "ArrowSolidBox", submitOnce: false,
onError: function (msg, obj, errorlist) {
$("#errorlist").empty();
$.map(errorlist, function (msg) {
$("#errorlist").append("<li>" + msg + "</li>")
});
alert(msg);
},
ajaxPrompt: '有数据正在异步验证,请稍等...'
});
//验证工厂名
$("#txtsku").formValidator({ onShow: "请输入产品编号", onFocus: "产品编号至少3个字符,最多25个字符", onCorrect: "该产品编号可以注册" }).inputValidator({ min: 3, max: 25, onError: "你输入的产品编号非法,请确认" })//.regexValidator({regExp:"username",dataType:"enum",onError:"用户名格式不正确"})
.ajaxValidator({
dataType: "html",
async: true,
url: "../ajax/ajaxSupplerValidator.ashx?type=checkproductsku",
success: function (data) {
if (data.indexOf("产品编号可以添加") > -1) { return true; } else {
return data;
}
},
buttons: $("#btnSave"),
error: function (jqXHR, textStatus, errorThrown) { alert("服务器没有返回数据,可能服务器忙,请重试" + errorThrown); },
onError: "该用产品编号不可用,请更换用产品编号",
onWait: "正在对用产品编号进行合法性校验,请稍候..."
}).defaultPassed();
$("#ddlbrand").formValidator({ onShow: "请选择品牌名称", onFocus: "品牌名称选择", onCorrect: "请择正确", defaultValue: "" }).inputValidator({ min: 1, onError: "请选择品牌名称!" }).defaultPassed();
});
|
JavaScript
|
$(document).ready(function () {
$.formValidator.initConfig({ formID: "form1", theme: "ArrowSolidBox", submitOnce: false,
onError: function (msg, obj, errorlist) {
$("#errorlist").empty();
$.map(errorlist, function (msg) {
$("#errorlist").append("<li>" + msg + "</li>")
});
alert(msg);
},
ajaxPrompt: '有数据正在异步验证,请稍等...'
});
//验证工厂名
$("#txttitle").formValidator({ onShow: "请输入店铺名称,例:红星美凯隆全友店", onFocus: "店铺名称至少3个字符,最多25个字符", onCorrect: "该店铺名称可以注册" }).inputValidator({ min: 3, max: 25, onError: "你输入的店铺名称非法,请确认" })//.regexValidator({regExp:"username",dataType:"enum",onError:"用户名格式不正确"})
.ajaxValidator({
dataType: "html",
async: true,
url: "../ajax/ajaxSupplerValidator.ashx?type=checkshoptitle",
success: function (data) {
if (data.indexOf("店铺名称可以添加") > -1) { return true; } else {
return data;
}
},
buttons: $("#btnSave"),
error: function (jqXHR, textStatus, errorThrown) { alert("服务器没有返回数据,可能服务器忙,请重试" + errorThrown); },
onError: "该用店铺名称不可用,请更换用店铺名称",
onWait: "正在对用店铺名称进行合法性校验,请稍候..."
}).defaultPassed();
//$("z").formValidator({ tipID: "test3Tip", onShow: "请选择你的兴趣爱好(至少选一个)", onFocus: "你至少选择1个", onCorrect: "恭喜你,你选对了" }).inputValidator({ min: 1, onError: "你选的个数不对" });
$(":checkbox").formValidator({ tipID: "chkbrandlistTip", onShow: "选择店铺销售产品品牌(至少选一个)", onFocus: "你至少选择1个", onCorrect: "正确" }).inputValidator();
$("#txtphone").formValidator({ empty: true, onShow: "请输入你的联系电话,可以为空哦", onFocus: "格式例如:0577-88888888", onCorrect: "谢谢你的合作", onEmpty: "你真的不想留联系电话了吗?" }).regexValidator({ regExp: "^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$", onError: "你输入的联系电话格式不正确" });
$("#ddlmarket").formValidator({ onShow: "选择卖场,单独店铺选择 未加入卖场 ", onFocus: "请选择卖场,单独店铺选择 未加入卖场", onCorrect: "请择正确", defaultValue: "" }).inputValidator({ min: 0, onError: "选择卖场,单独店铺选择 未加入卖场" }).defaultPassed();
$("#txtaddress").formValidator({ onShow: "请输入详细街道地址", onFocus: "请输入详细街道地址", onCorrect: "正确" }).inputValidator({ min: 3, onError: "街道地址输入不正确" });
});
|
JavaScript
|
$(document).ready(function () {
$.formValidator.initConfig({ formID: "form1", theme: "ArrowSolidBox", submitOnce: false,
onError: function (msg, obj, errorlist) {
$("#errorlist").empty();
$.map(errorlist, function (msg) {
$("#errorlist").append("<li>" + msg + "</li>")
});
alert(msg);
},
ajaxPrompt: '有数据正在异步验证,请稍等...'
});
//验证工厂名
$("#txttitle").formValidator({onShow: "请输入厂商名称", onFocus: "厂商名称至少3个字符,最多25个字符", onCorrect: "该厂商名称可以注册" }).inputValidator({ min: 3, max: 25, onError: "你输入的厂商名称非法,请确认" })//.regexValidator({regExp:"username",dataType:"enum",onError:"用户名格式不正确"})
.ajaxValidator({
dataType: "html",
async: true,
url: "../ajax/ajaxSupplerValidator.ashx?type=checkcompanytitle",
success: function (data) {
if (data.indexOf("该厂商名称可以注册") > -1) { return true; } else {
return data;
}
},
buttons: $("#btnSave"),
error: function (jqXHR, textStatus, errorThrown) { alert("服务器没有返回数据,可能服务器忙,请重试" + errorThrown); },
onError: "该用厂商名称不可用,请更换用厂商名称",
onWait: "正在对用厂商名称进行合法性校验,请稍候..."
}).defaultPassed();
$("#txtphone").formValidator({ onShow: "请输入你的联系电话", onFocus: "格式例如:0577-88888888", onCorrect: "输入正确" }).regexValidator({ regExp: "^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$", onError: "你输入的联系电话格式不正确" });
$("#txtfax").formValidator({ onShow: "请输入你的联系传真", onFocus: "格式例如:0577-88888888", onCorrect: "输入正确" }).regexValidator({ regExp: "^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$", onError: "你输入的联系传真格式不正确" });
$("#txtemail").formValidator({ empty: true, onShow: "请输入邮箱", onFocus: "邮箱6-100个字符,输入正确了才能离开焦点", onCorrect: "恭喜你,你输对了"}).inputValidator({ min: 6, max: 100, onError: "你输入的邮箱长度非法,请确认" }).regexValidator({ regExp: "^([\\w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([\\w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$", onError: "你输入的邮箱格式不正确" });
});
|
JavaScript
|
$(document).ready(function () {
$.formValidator.initConfig({ formID: "form1", theme: "ArrowSolidBox", submitOnce: false,
onError: function (msg, obj, errorlist) {
$("#errorlist").empty();
$.map(errorlist, function (msg) {
$("#errorlist").append("<li>" + msg + "</li>")
});
alert(msg);
},
ajaxPrompt: '有数据正在异步验证,请稍等...'
});
//验证工厂名
$("#txttitle").formValidator({onShow: "请输入品牌名称", onFocus: "品牌名称至少3个字符,最多25个字符", onCorrect: "该品牌名称可以注册" }).inputValidator({ min: 3, max: 25, onError: "你输入的品牌名称非法,请确认" })//.regexValidator({regExp:"username",dataType:"enum",onError:"用户名格式不正确"})
.ajaxValidator({
dataType: "html",
async: true,
url: "../ajax/ajaxSupplerValidator.ashx?type=checkbrandtitle",
success: function (data) {
if (data.indexOf("该品牌名称可以添加") > -1) { return true; } else {
return data;
}
},
buttons: $("#btnSave"),
error: function (jqXHR, textStatus, errorThrown) { alert("服务器没有返回数据,可能服务器忙,请重试" + errorThrown); },
onError: "该用品牌名称不可用,请更换用品牌名称",
onWait: "正在对用品牌名称进行合法性校验,请稍候..."
}).defaultPassed();
$("#txtletter").formValidator({onShow: "请输入品牌索引", onFocus: "品牌索引至少3个字符,最多15个字符", onCorrect: "该品牌索引可以注册" }).inputValidator({ min: 1, max: 25, onError: "你输入的品牌索引非法,请确认" })//.regexValidator({regExp:"username",dataType:"enum",onError:"用户名格式不正确"})
.ajaxValidator({
dataType: "html",
async: true,
url: "../ajax/ajaxSupplerValidator.ashx?type=checkbrandtitleletter",
success: function (data) {
if (data.indexOf("该品牌索引可以添加") > -1) { return true; } else {
return data;
}
},
buttons: $("#btnSave"),
error: function (jqXHR, textStatus, errorThrown) { alert("服务器没有返回数据,可能服务器忙,请重试" + errorThrown); },
onError: "该用品牌索引不可用,请更换用品牌索引",
onWait: "正在对用品牌索引进行合法性校验,请稍候..."
}).defaultPassed();
$("#ddlspread").formValidator({ onShow: "请选择品牌档位", onFocus: "品牌档位选择", onCorrect: "请择正确", defaultValue: "" }).inputValidator({ min: 1, onError: "请选择品牌档位!" }).defaultPassed();
$("#ddlmaterial").formValidator({ onShow: "请选择品牌材质", onFocus: "品牌牌材选择", onCorrect: "请择正确", defaultValue: "" }).inputValidator({ min: 1, onError: "请选择品牌材质!" }).defaultPassed();
$("#ddlstyle").formValidator({ onShow: "请选择品牌风格", onFocus: "品牌风格选择", onCorrect: "请择正确", defaultValue: "" }).inputValidator({ min: 1, onError: "请选择品牌风格!" }).defaultPassed();
$("#ddlcolor").formValidator({ onShow: "请选择品牌色系", onFocus: "品牌色系选择", onCorrect: "请择正确", defaultValue: "" }).inputValidator({ min: 1, onError: "请选择品牌色系!" }).defaultPassed();
});
|
JavaScript
|
$(document).ready(function () {
$.formValidator.initConfig({ formID: "form1", theme: "ArrowSolidBox", submitOnce: false,
onError: function (msg, obj, errorlist) {
$("#errorlist").empty();
$.map(errorlist, function (msg) {
$("#errorlist").append("<li>" + msg + "</li>")
});
alert(msg);
},
ajaxPrompt: '有数据正在异步验证,请稍等...'
});
//验证工厂名
$("#txtcompanytitle").formValidator({ onShow: "请输入厂商名称", onFocus: "厂商名称至少3个字符,最多25个字符", onCorrect: "该厂商名称可以注册" }).inputValidator({ min: 3, max: 25, onError: "你输入的厂商名称非法,请确认" })//.regexValidator({regExp:"username",dataType:"enum",onError:"用户名格式不正确"})
.ajaxValidator({
dataType: "html",
async: true,
url: "../ajax/ajaxSupplerValidator.ashx?type=checkcompanytitle2",
success: function (data) {
if (data.indexOf("该厂商名称可以注册") > -1) { return true; } else {
return data;
}
},
buttons: $("#btnSave"),
error: function (jqXHR, textStatus, errorThrown) { alert("服务器没有返回数据,可能服务器忙,请重试" + errorThrown); },
onError: "该用厂商名称不可用,请更换用厂商名称",
onWait: "正在对用厂商名称进行合法性校验,请稍候..."
}).defaultPassed();
$("#txtcphone").formValidator({ onShow: "请输入工厂联系电话", onFocus: "格式例如:0577-88888888", onCorrect: "谢谢你的合作" }).regexValidator({ regExp: "^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$", onError: "你输入的联系电话格式不正确" });
$("#txtbrandtitle").formValidator({ onShow: "请输入品牌名称", onFocus: "品牌名称至少3个字符,最多25个字符", onCorrect: "该品牌名称可以注册" }).inputValidator({ min: 3, max: 25, onError: "你输入的品牌名称非法,请确认" })//.regexValidator({regExp:"username",dataType:"enum",onError:"用户名格式不正确"})
.ajaxValidator({
dataType: "html",
async: true,
url: "../ajax/ajaxSupplerValidator.ashx?type=checkbrandtitle2",
success: function (data) {
if (data.indexOf("该品牌名称可以添加") > -1) { return true; } else {
return data;
}
},
buttons: $("#btnSave"),
error: function (jqXHR, textStatus, errorThrown) { alert("服务器没有返回数据,可能服务器忙,请重试" + errorThrown); },
onError: "该用品牌名称不可用,请更换用品牌名称",
onWait: "正在对用品牌名称进行合法性校验,请稍候..."
}).defaultPassed();
$("#txtbrandletter").formValidator({ onShow: "请输入品牌索引", onFocus: "品牌索引至少3个字符,最多15个字符", onCorrect: "该品牌索引可以注册" }).inputValidator({ min: 1, max: 25, onError: "你输入的品牌索引非法,请确认" })//.regexValidator({regExp:"username",dataType:"enum",onError:"用户名格式不正确"})
.ajaxValidator({
dataType: "html",
async: true,
url: "../ajax/ajaxSupplerValidator.ashx?type=checkbrandtitleletter2",
success: function (data) {
if (data.indexOf("该品牌索引可以添加") > -1) { return true; } else {
return data;
}
},
buttons: $("#btnSave"),
error: function (jqXHR, textStatus, errorThrown) { alert("服务器没有返回数据,可能服务器忙,请重试" + errorThrown); },
onError: "该用品牌索引不可用,请更换用品牌索引",
onWait: "正在对用品牌索引进行合法性校验,请稍候..."
}).defaultPassed();
});
|
JavaScript
|
$(document).ready(function () {
$.formValidator.initConfig({ formID: "form1", theme: "ArrowSolidBox", submitOnce: false,
onError: function (msg, obj, errorlist) {
$("#errorlist").empty();
$.map(errorlist, function (msg) {
$("#errorlist").append("<li>" + msg + "</li>")
});
alert(msg);
},
ajaxPrompt: '有数据正在异步验证,请稍等...'
});
//验证工厂名
$("#txttitle").formValidator({onShow: "请输入经销商名称", onFocus: "经销商名称至少3个字符,最多25个字符", onCorrect: "该经销商名称可以注册" }).inputValidator({ min: 3, max: 25, onError: "你输入的经销商名称非法,请确认" })//.regexValidator({regExp:"username",dataType:"enum",onError:"用户名格式不正确"})
.ajaxValidator({
dataType: "html",
async: true,
url: "../ajax/ajaxSupplerValidator.ashx?type=checkdealer",
success: function (data) {
if (data.indexOf("经销商名称可以添加") > -1) { return true; } else {
return data;
}
},
buttons: $("#btnSave"),
error: function (jqXHR, textStatus, errorThrown) { alert("服务器没有返回数据,可能服务器忙,请重试" + errorThrown); },
onError: "该用经销商名称不可用,请更换用经销商名称",
onWait: "正在对用经销商名称进行合法性校验,请稍候..."
}).defaultPassed();
$("#txtletter").formValidator({onShow: "请输入经销商索引", onFocus: "经销商索引至少3个字符,最多15个字符", onCorrect: "该经销商索引可以注册" }).inputValidator({ min: 1, max: 25, onError: "你输入的经销商索引非法,请确认" })//.regexValidator({regExp:"username",dataType:"enum",onError:"用户名格式不正确"})
.ajaxValidator({
dataType: "html",
async: true,
url: "../ajax/ajaxSupplerValidator.ashx?type=checkbrandtitleletter",
success: function (data) {
if (data.indexOf("该经销商索引可以添加") > -1) { return true; } else {
return data;
}
},
buttons: $("#btnSave"),
error: function (jqXHR, textStatus, errorThrown) { alert("服务器没有返回数据,可能服务器忙,请重试" + errorThrown); },
onError: "该用经销商索引不可用,请更换用经销商索引",
onWait: "正在对用经销商索引进行合法性校验,请稍候..."
}).defaultPassed();
$("#txtaddress").formValidator({ onShow: "请输入详细街道地址", onFocus: "请输入详细街道地址", onCorrect: "正确" }).inputValidator({ min: 3, onError: "街道地址输入不正确" });
$("#txtphone").formValidator({ onShow: "请输入你的联系电话", onFocus: "格式例如:0577-88888888", onCorrect: "输入正确" }).regexValidator({ regExp: "^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$", onError: "你输入的联系电话格式不正确" });
$("#txtfax").formValidator({ empty: true, onShow: "请输入你的联系传真", onFocus: "格式例如:0577-88888888", onCorrect: "输入正确" }).regexValidator({ regExp: "^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$", onError: "你输入的联系传真格式不正确" });
$("#txtemail").formValidator({ empty: true, onShow: "请输入邮箱", onFocus: "邮箱6-100个字符,输入正确了才能离开焦点", onCorrect: "恭喜你,你输对了" }).inputValidator({ min: 6, max: 100, onError: "你输入的邮箱长度非法,请确认" }).regexValidator({ regExp: "^([\\w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([\\w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$", onError: "你输入的邮箱格式不正确" });
});
|
JavaScript
|
$(document).ready(function () {
$.formValidator.initConfig({ formID: "form1", theme: "ArrowSolidBox", submitOnce: false,
onError: function (msg, obj, errorlist) {
$("#errorlist").empty();
$.map(errorlist, function (msg) {
$("#errorlist").append("<li>" + msg + "</li>")
});
alert(msg);
},
ajaxPrompt: '有数据正在异步验证,请稍等...'
});
//验证工厂名
$("#txttitle").formValidator({ onShow: "请输入系列名称", onFocus: "系列名称至少3个字符,最多25个字符", onCorrect: "该系列名称可以注册" }).inputValidator({ min: 3, max: 25, onError: "你输入的系列名称非法,请确认" })//.regexValidator({regExp:"username",dataType:"enum",onError:"用户名格式不正确"})
.ajaxValidator({
dataType: "html",
async: true,
url: "../ajax/ajaxSupplerValidator.ashx?type=checkbrandstitle",
success: function (data) {
if (data.indexOf("该系列名称可以添加") > -1) { return true; } else {
return data;
}
},
buttons: $("#btnSave"),
error: function (jqXHR, textStatus, errorThrown) { alert("服务器没有返回数据,可能服务器忙,请重试" + errorThrown); },
onError: "该用系列名称不可用,请更换用系列名称",
onWait: "正在对用系列名称进行合法性校验,请稍候..."
}).defaultPassed();
$("#ddlbrand").formValidator({ onShow: "请选择品牌名称", onFocus: "品牌名称选择", onCorrect: "请择正确", defaultValue: "" }).inputValidator({ min: 1, onError: "请选择品牌名称!" }).defaultPassed();
});
|
JavaScript
|
$(document).ready(function () {
$.formValidator.initConfig({ formID: "form1", theme: "ArrowSolidBox", submitOnce: false,
onError: function (msg, obj, errorlist) {
$("#errorlist").empty();
$.map(errorlist, function (msg) {
$("#errorlist").append("<li>" + msg + "</li>")
});
alert(msg);
},
ajaxPrompt: '有数据正在异步验证,请稍等...'
});
//验证工厂名
$("#txttitle").formValidator({ onShow: "请输入卖场名称,例:金盛国际家居广场(上海)", onFocus: "卖场名称至少3个字符,最多25个字符", onCorrect: "该卖场名称可以注册" }).inputValidator({ min: 3, max: 25, onError: "你输入的卖场名称非法,请确认" })//.regexValidator({regExp:"username",dataType:"enum",onError:"用户名格式不正确"})
.ajaxValidator({
dataType: "html",
async: true,
url: "../ajax/ajaxSupplerValidator.ashx?type=checkmarkettitle2",
success: function (data) {
if (data.indexOf("卖场名称可以添加") > -1) { return true; } else {
return data;
}
},
buttons: $("#btnSave"),
error: function (jqXHR, textStatus, errorThrown) { alert("服务器没有返回数据,可能服务器忙,请重试" + errorThrown); },
onError: "该用卖场名称不可用,请更换用卖场名称",
onWait: "正在对用卖场名称进行合法性校验,请稍候..."
}).defaultPassed();
$("#txtletter").formValidator({ onShow: "请输入卖场索引,索引为英文名或拼音", onFocus: "卖场索引至少3个字符,最多25个字符,索引为英文名或拼音", onCorrect: "该卖场索引可以使用" }).inputValidator({ min: 3, max: 25, onError: "你输入的卖场索引非法,请确认" })//.regexValidator({regExp:"username",dataType:"enum",onError:"用户名格式不正确"})
.ajaxValidator({
dataType: "html",
async: true,
url: "../ajax/ajaxSupplerValidator.ashx?type=checkmarketletter",
success: function (data) {
if (data.indexOf("卖场索引可以添加") > -1) { return true; } else {
return data;
}
},
buttons: $("#btnSave"),
error: function (jqXHR, textStatus, errorThrown) { alert("服务器没有返回数据,可能服务器忙,请重试" + errorThrown); },
onError: "该用卖场索引不可用,请更换用卖场索引",
onWait: "正在对用卖场索引进行合法性校验,请稍候..."
}).defaultPassed();
//,,,
$("#txtlphone").formValidator({ empty: true, onShow: "请输入卖场投诉服务电话", onFocus: "格式例如:0577-88888888", onCorrect: "谢谢你的合作" ,onEmpty: "" }).regexValidator({ regExp: "^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$", onError: "你输入的卖场投诉服务电话格式不正确" });
//$("#txtphone").formValidator({ onShow: "请输入你的联系电话,可以为空哦", onFocus: "格式例如:0577-88888888", onCorrect: "谢谢你的合作"}).regexValidator({ regExp: "^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$", onError: "你输入的联系电话格式不正确" });
$("#txtzphone").formValidator({ onShow: "请输入卖场招商电话", onFocus: "格式例如:0577-88888888", onCorrect: "谢谢你的合作" }).regexValidator({ regExp: "^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$", onError: "你输入的卖场招商格式不正确" });
$("#txtaddress").formValidator({ onShow: "请输入详细街道地址", onFocus: "请输入详细街道地址", onCorrect: "正确" }).inputValidator({ min: 3, onError: "街道地址输入不正确" });
});
|
JavaScript
|
$(function () {
$(".msgtable tr:nth-child(odd)").addClass("tr_bg"); //隔行变色
$(".msgtable tr").hover(
function () {
$(this).addClass("tr_hover_col");
},
function () {
$(this).removeClass("tr_hover_col");
}
);
$("input[type='text'].input").focus(function () {
if (!$(this).hasClass("tcal")) {
$(this).addClass("focus");
}
}).blur(function () {
$(this).removeClass("focus");
});
});
//设置为自动高
function SetWinHeight(obj) {
var win = obj;
if (document.getElementById) {
if (win && !window.opera) {
if (win.contentDocument && win.contentDocument.body.offsetHeight)
win.height = win.contentDocument.body.offsetHeight + 50;
else if (win.Document && win.Document.body.scrollHeight)
win.height = win.Document.body.scrollHeight + 50;
}
}
}
//全选取消按钮函数,调用样式如:
function checkAll(chkobj) {
if ($(chkobj).text() == "全选") {
$(chkobj).text("取消");
$(".checkall").each(function () {
if ($(this).attr("disabled") != 'disabled') {
$(this).find("input").attr("checked", true);
}
});
} else {
$(chkobj).text("全选");
$(".checkall input").attr("checked", false);
}
}
//遮罩提示窗口
function jsmsg(w, h, msgtitle, msgbox, url, msgcss) {
$("#msgdialog").remove();
var cssname = "";
switch (msgcss) {
case "Success":
cssname = "icon-01";
break;
case "Error":
cssname = "icon-02";
break;
default:
cssname = "icon-03";
break;
}
var str = "<div id='msgdialog' title='" + msgtitle + "'><p class='" + cssname + "'>" + msgbox + "</p></div>";
$("body").append(str);
$("#msgdialog").dialog({
//title: null,
//show: null,
bgiframe: true,
autoOpen: false,
width: w,
//height: h,
resizable: false,
closeOnEscape: true,
buttons: { "确定": function () { $(this).dialog("close"); } },
modal: true
});
$("#msgdialog").dialog("open");
if (url == "back") {
mainFrame.history.back(-1);
} else if (url != "") {
mainFrame.location.href = url;
}
}
function jsmsgCurPage(w, h, msgtitle, msgbox, url, msgcss) {
$("#msgdialog").remove();
var cssname = "";
switch (msgcss) {
case "Success":
cssname = "icon-01";
break;
case "Error":
cssname = "icon-02";
break;
default:
cssname = "icon-03";
break;
}
var str = "<div id='msgdialog' title='" + msgtitle + "'><p class='" + cssname + "'>" + msgbox + "</p></div>";
$("body").append(str);
$("#msgdialog").dialog({
//title: null,
//show: null,
bgiframe: true,
autoOpen: false,
width: w,
height: h,
resizable: false,
closeOnEscape: true,
buttons: { "确定": function () { $(this).dialog("close"); } },
modal: true
});
$("#msgdialog").dialog("open");
}
//可以自动关闭的提示
function jsprint(msgtitle, url, msgcss) {
$("#msgprint").remove();
var cssname = "";
switch (msgcss) {
case "Success":
cssname = "pcent correct";
break;
case "Error":
cssname = "pcent disable";
break;
default:
cssname = "pcent warning";
break;
}
var str = "<div id=\"msgprint\" class=\"" + cssname + "\">" + msgtitle + "</div>";
$("body").append(str);
$("#msgprint").show();
if (url == "back") {
mainFrame.history.back(-1);
} else if (url != "") {
mainFrame.location.href = url;
}
//3秒后清除提示
setTimeout(function () {
$("#msgprint").fadeOut(500);
//如果动画结束则删除节点
if (!$("#msgprint").is(":animated")) {
$("#msgprint").remove();
}
}, 3000);
}
//可以自动关闭的提示
function jsprintCurPage(msgtitle, url, msgcss) {
$("#msgprint").remove();
var cssname = "";
switch (msgcss) {
case "Success":
cssname = "pcent correct";
break;
case "Error":
cssname = "pcent disable";
break;
default:
cssname = "pcent warning";
break;
}
var str = "<div id=\"msgprint\" class=\"" + cssname + "\">" + msgtitle + "</div>";
$("body").append(str);
$("#msgprint").show();
var outT = 900;
var outT2 = 3000;
if (url == "thickbox") {
outT = 500;
outT2 = 1500;
}
//3秒后清除提示
setTimeout(function () {
$("#msgprint").fadeOut(outT);
//如果动画结束则删除节点
if (!$("#msgprint").is(":animated")) {
$("#msgprint").remove();
}
if (url == "back") {
this.history.back(-1);
} else if (url == "#") {
return;
} else if (url == "thickbox") {
TB_iframeContent.location.href = $("#TB_iframeContent").attr("src");
} else if (url != "") {
this.location.href = url;
}
}, outT2);
}
function SetPermission() {
$("#SetPermission").remove();
var str = "<div id='SetPermission' style='width:100%; position:fixed; z-index:99999999; background:#000; left:0px; top:0px; bottom:0px; right:0px; display:none;'></div>";
$("body").append(str);
$("#SetPermission").css("display", "block").animate({ opacity: 0.1 });
}
|
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:"^13[0-9]{9}|15[012356789][0-9]{8}|18[0256789][0-9]{8}|147[0-9]{8}$", //手机
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})$" //身份证
}
var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"}
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]);
}
function chkboxlistSelected() {
var a = $(":checkbox:checked");
if (a == null) return false;
if (a.length < 1)return "至少选一个";
return true;
}
|
JavaScript
|
//====================================================================================================
// [插件名称] jQuery formValidator
//----------------------------------------------------------------------------------------------------
// [描 述] jQuery formValidator表单验证插件,它是基于jQuery类库,实现了js脚本于页面的分离。对一个表
// 单对象,你只需要写一行代码就可以轻松实现20种以上的脚本控制。现支持一个表单元素累加很多种
// 校验方式,采用配置信息的思想,而不是把信息写在表单元素上,能比较完美的实现ajax请求。
//----------------------------------------------------------------------------------------------------
// [作者网名] 猫冬
// [邮 箱] wzmaodong@126.com
// [作者博客] http://wzmaodong.cnblogs.com
// [插件主页] http://www.yhuan.com
// [QQ群交流] 72280458、74106519
// [更新日期] 2011-07-24
// [版 本 号] ver4.1.1 内部测试版
// [开源协议] LGPL
//====================================================================================================
(function($) {
$.formValidator =
{
//全局配置
initConfig : function(controlOptions)
{
var settings = {};
$.extend(true, settings, initConfig_setting, controlOptions || {});
//如果是精简模式,发生错误的时候,第一个错误的控件就不获得焦点
if(settings.mode == "SingleTip"){settings.errorFocus=false};
//如果填写了表单和按钮,就注册验证事件
if(settings.formID!=""){
$("#"+settings.formID).submit(function(){
if(settings.ajaxForm!=null){
$.formValidator.ajaxForm(settings.validatorGroup,settings.ajaxForm);
return false;
}
else{
return $.formValidator.bindSubmit(settings);
}
});
}
validatorGroup_setting.push( settings );
//读取主题对应的脚步
var scriptSrcArray = fv_scriptSrc.split('/');
var jsName = scriptSrcArray[scriptSrcArray.length-1];
var themedir = fv_scriptSrc.replace(jsName,'');
$.ajax({async:false,type: "GET",url: themedir + "themes/"+settings.theme+"/js/theme.js",dataType: "script",
error :function(){alert('当前皮肤加载出错,请确认皮肤【'+settings.theme+'】是否存在')}
});
//读取主题对应的样式
if($.browser.msie)
{
var css=document.createElement("link");
css.rel="stylesheet";
css.type="text/css";
css.href=themedir+"themes/"+settings.theme+"/style/style.css";
document.getElementsByTagName("head")[0].appendChild(css);
}
else
{
var style=document.createElement('style');
style.setAttribute("type", "text/css");
var styCss = "@import url('"+themedir+"themes/"+settings.theme+"/style/style.css');";
if (style.styleSheet) {style.styleSheet.cssText=styCss;} else {style.appendChild(document.createTextNode(styCss));}
document.getElementsByTagName("head")[0].appendChild(style);
}
},
//调用验证函数
bindSubmit : function(settings)
{
if (settings.ajaxCountValid > 0 && settings.ajaxPrompt != "") {
alert(settings.ajaxPrompt);
return false;
}
return $.formValidator.pageIsValid(settings.validatorGroup);
},
//各种校验方式支持的控件类型
sustainType : function(elem,validateType)
{
var srcTag = elem.tagName;
var stype = elem.type;
switch(validateType)
{
case "formValidator":
return true;
case "inputValidator":
return (srcTag == "INPUT" || srcTag == "TEXTAREA" || srcTag == "SELECT");
case "compareValidator":
return ((srcTag == "INPUT" || srcTag == "TEXTAREA") ? (stype != "checkbox" && stype != "radio") : false);
case "ajaxValidator":
return (stype == "text" || stype == "textarea" || stype == "file" || stype == "password" || stype == "select-one");
case "regexValidator":
return ((srcTag == "INPUT" || srcTag == "TEXTAREA") ? (stype != "checkbox" && stype != "radio") : false);
case "functionValidator":
return true;
case "passwordValidator":
return stype == "password";
}
},
//如果validator对象对应的element对象的validator属性追加要进行的校验。
appendValid : function(id, setting )
{
//如果是各种校验不支持的类型,就不追加到。返回-1表示没有追加成功
var elem = $("#"+id).get(0);
var validateType = setting.validateType;
if(!$.formValidator.sustainType(elem,validateType)) return -1;
//重新初始化
if (validateType=="formValidator" || elem.settings == undefined ){elem.settings = new Array();}
var len = elem.settings.push( setting );
elem.settings[len - 1].index = len - 1;
return len - 1;
},
//获取校验组信息。
getInitConfig : function(validatorGroup)
{
var config=null;
$.each( validatorGroup_setting, function(i, n){
if(validatorGroup_setting[i].validatorGroup==validatorGroup){
config = validatorGroup_setting[i];
return false;
}
});
return config;
},
//设置显示信息
setTipState : function(elem,showclass,showmsg)
{
var initConfig = $.formValidator.getInitConfig(elem.validatorGroup);
var tip = $("#"+elem.settings[0].tipID);
if(showmsg==null || showmsg=="")
{
tip.hide();
}
else
{
if(initConfig.mode == "SingleTip")
{
//显示和保存提示信息
$("#fv_content").html(showmsg);
elem.Tooltip = showmsg;
if(showclass!="onError"){tip.hide();}
}
else
{
var html = showclass == "onShow" ? onShowHtml : (showclass == "onFocus" ? onFocusHtml : (showclass == "onCorrect" ? onCorrectHtml : onErrorHtml));
if(html.length = 0 || showmsg == "")
{
tip.hide();
}
else
{
if(elem.validatorPasswordIndex > 0 && showclass =="onCorrect"){
var setting = elem.settings[elem.validatorPasswordIndex];
var level = $.formValidator.passwordValid(elem);
showmsg = ""
if(level==-1 && setting.onErrorContinueChar!=""){
showmsg=setting.onErrorContinueChar;
}else if(level==-2 && setting.onErrorSameChar!=""){
showmsg=setting.onErrorSameChar;
}else if(level==-3 && setting.onErrorCompareSame!=""){
showmsg=setting.onErrorCompareSame;
}
if(showmsg!="")
{
$.formValidator.setTipState(elem,'onError',showmsg);
return;
}
showmsg = passwordStrengthText[level<=0?0:level - 1];
}
html = html.replace(/\$class\$/g, showclass).replace(/\$data\$/g, showmsg);
tip.html(html).show();
}
var stype = elem.type;
if(stype == "password" || stype == "text" || stype == "file")
{
jqobj = $(elem);
if(onShowClass!="" && showclass == "onShow"){jqobj.removeClass().addClass(onShowClass)};
if(onFocusClass!="" && showclass == "onFocus"){jqobj.removeClass().addClass(onFocusClass)};
if(onCorrectClass!="" && showclass == "onCorrect"){jqobj.removeClass().addClass(onCorrectClass)};
if(onErrorClass!="" && showclass == "onError"){jqobj.removeClass().addClass(onErrorClass)};
}
}
}
},
//把提示层重置成原始提示(如果有defaultPassed,应该设置为onCorrect)
resetTipState : function(validatorGroup)
{
if(validatorGroup == undefined){validatorGroup = "1"};
var initConfig = $.formValidator.getInitConfig(validatorGroup);
$.each(initConfig.validObjects,function(){
var setting = this.settings[0];
var passed = setting.defaultPassed;
$.formValidator.setTipState(this, passed ? "onCorrect" : "onShow", passed ? $.formValidator.getStatusText(this,setting.onCorrect) : setting.onShow );
});
},
//设置错误的显示信息
setFailState : function(tipID,showmsg)
{
$.formValidator.setTipState($("#"+tipID).get(0), "onError", showmsg);
},
//根据单个对象,正确:正确提示,错误:错误提示
showMessage : function(returnObj)
{
var id = returnObj.id;
var elem = $("#"+id).get(0);
var isValid = returnObj.isValid;
var setting = returnObj.setting;//正确:setting[0],错误:对应的setting[i]
var showmsg = "",showclass = "";
var intiConfig = $.formValidator.getInitConfig(elem.validatorGroup);
if (!isValid)
{
showclass = "onError";
if(setting.validateType=="ajaxValidator")
{
if(setting.lastValid=="")
{
showclass = "onLoad";
showmsg = setting.onWait;
}
else
{
showmsg = $.formValidator.getStatusText(elem,setting.onError);
}
}
else
{
showmsg = (returnObj.errormsg==""? $.formValidator.getStatusText(elem,setting.onError) : returnObj.errormsg);
}
if(intiConfig.mode == "AlertTip")
{
if(elem.validValueOld!=$(elem).val()){alert(showmsg);}
}
else
{
$.formValidator.setTipState(elem,showclass,showmsg);
}
}
else
{
//验证成功后,如果没有设置成功提示信息,则给出默认提示,否则给出自定义提示;允许为空,值为空的提示
showmsg = $.formValidator.isEmpty(id) ? setting.onEmpty : $.formValidator.getStatusText(elem,setting.onCorrect);
$.formValidator.setTipState(elem,"onCorrect",showmsg);
}
return showmsg;
},
showAjaxMessage : function(returnObj)
{
var elem = $("#"+returnObj.id).get(0);
var setting = elem.settings[returnObj.ajax];
var validValueOld = elem.validValueOld;
var validvalue = $(elem).val();
returnObj.setting = setting;
//defaultPassed还未处理
if(validValueOld!= validvalue || validValueOld == validvalue && elem.onceValided == undefined)
{
$.formValidator.ajaxValid(returnObj);
}
else
{
if(setting.isValid!=undefined && !setting.isValid){
elem.lastshowclass = "onError";
elem.lastshowmsg = $.formValidator.getStatusText(elem,setting.onError);
}
$.formValidator.setTipState(elem,elem.lastshowclass,elem.lastshowmsg);
}
},
//获取指定字符串的长度
getLength : function(id)
{
var srcjo = $("#"+id);
var elem = srcjo.get(0);
var sType = elem.type;
var len = 0;
switch(sType)
{
case "text":
case "hidden":
case "password":
case "textarea":
case "file":
var val = srcjo.val();
var setting = elem.settings[0];
//如果有显示提示内容的,要忽略掉
if(elem.isInputControl && elem.value == setting.onShowText){val=""}
var initConfig = $.formValidator.getInitConfig(elem.validatorGroup);
if (initConfig.wideWord)
{
for (var i = 0; i < val.length; i++)
{
len = len + ((val.charCodeAt(i) >= 0x4e00 && val.charCodeAt(i) <= 0x9fa5) ? 2 : 1);
}
}
else{
len = val.length;
}
break;
case "checkbox":
case "radio":
len = $("input[type='"+sType+"'][name='"+srcjo.attr("name")+"']:checked").length;
break;
case "select-one":
len = elem.options ? elem.options.selectedIndex : -1;
break;
case "select-multiple":
len = $("select[name="+elem.name+"] option:selected").length;
break;
}
return len;
},
//结合empty这个属性,判断仅仅是否为空的校验情况。
isEmpty : function(id)
{
return ($("#"+id).get(0).settings[0].empty && $.formValidator.getLength(id)==0);
},
//对外调用:判断单个表单元素是否验证通过,不带回调函数
isOneValid : function(id)
{
return $.formValidator.oneIsValid(id).isValid;
},
//验证单个是否验证通过,正确返回settings[0],错误返回对应的settings[i]
oneIsValid : function (id)
{
var returnObj = new Object();
var elem = $("#"+id).get(0);
var initConfig = $.formValidator.getInitConfig(elem.validatorGroup);
returnObj.initConfig = initConfig;
returnObj.id = id;
returnObj.ajax = -1;
returnObj.errormsg = ""; //自定义错误信息
var settings = elem.settings;
var settingslen = settings.length;
var validateType;
//只有一个formValidator的时候不检验
if (settingslen==1){settings[0].bind=false;}
if(!settings[0].bind){return null;}
$.formValidator.resetInputValue(true,initConfig,id);
for ( var i = 0 ; i < settingslen ; i ++ )
{
if(i==0){
//如果为空,直接返回正确
if($.formValidator.isEmpty(id)){
returnObj.isValid = true;
returnObj.setting = settings[0];
break;
}
continue;
}
returnObj.setting = settings[i];
validateType = settings[i].validateType;
//根据类型触发校验
switch(validateType)
{
case "inputValidator":
$.formValidator.inputValid(returnObj);
break;
case "compareValidator":
$.formValidator.compareValid(returnObj);
break;
case "regexValidator":
$.formValidator.regexValid(returnObj);
break;
case "functionValidator":
$.formValidator.functionValid(returnObj);
break;
case "ajaxValidator":
//如果是ajax校验,这里直接取上次的结果值
returnObj.ajax = i
break;
case "passwordValidator":
break;
}
//校验过一次
elem.onceValided = true;
if(!settings[i].isValid) {
returnObj.isValid = false;
returnObj.setting = settings[i];
break;
}else{
returnObj.isValid = true;
returnObj.setting = settings[0];
if (settings[i].validateType == "ajaxValidator"){break};
}
}
$.formValidator.resetInputValue(false,initConfig,id);
return returnObj;
},
//验证所有需要验证的对象,并返回是否验证成功(如果曾经触发过ajaxValidator,提交的时候就不触发校验,直接读取结果)
pageIsValid : function (validatorGroup)
{
if(validatorGroup == undefined){validatorGroup = "1"};
var isValid = true,returnObj,firstErrorMessage="",errorMessage;
var error_tip = "^",thefirstid,name,name_list="^";
var errorlist = new Array();
//设置提交状态、ajax是否出错、错误列表
var initConfig = $.formValidator.getInitConfig(validatorGroup);
initConfig.status = "sumbiting";
initConfig.ajaxCountSubmit = 0;
//遍历所有要校验的控件,如果存在ajaxValidator就先直接触发
$.each(initConfig.validObjects,function()
{
if($(this).length==0){return true};
if (this.settings[0].bind && this.validatorAjaxIndex!=undefined && this.onceValided == undefined) {
returnObj = $.formValidator.oneIsValid(this.id);
if (returnObj.ajax == this.validatorAjaxIndex) {
initConfig.status = "sumbitingWithAjax";
$.formValidator.ajaxValid(returnObj);
}
}
});
//如果有提交的时候有触发ajaxValidator,所有的处理都放在ajax里处理
if(initConfig.ajaxCountSubmit > 0){return false}
//遍历所有要校验的控件
$.each(initConfig.validObjects,function()
{
//只校验绑定的控件
if($(this).length==0){return true};
if(this.settings[0].bind){
name = this.name;
//相同name只校验一次
if (name_list.indexOf("^"+name+"^") == -1) {
onceValided = this.onceValided == undefined ? false : this.onceValided;
if(name){name_list = name_list + name + "^"};
returnObj = $.formValidator.oneIsValid(this.id);
if (returnObj) {
//校验失败,获取第一个发生错误的信息和ID
if (!returnObj.isValid) {
//记录不含ajaxValidator校验函数的校验结果
isValid = false;
errorMessage = returnObj.errormsg == "" ? returnObj.setting.onError : returnObj.errormsg;
errorlist[errorlist.length] = errorMessage;
if (thefirstid == null) {thefirstid = returnObj.id};
if(firstErrorMessage==""){firstErrorMessage=errorMessage};
}
//为了解决使用同个TIP提示问题:后面的成功或失败都不覆盖前面的失败
if (initConfig.mode != "AlertTip") {
var tipID = this.settings[0].tipID;
if (error_tip.indexOf("^" + tipID + "^") == -1) {
if (!returnObj.isValid) {error_tip = error_tip + tipID + "^"};
$.formValidator.showMessage(returnObj);
}
}
}
}
}
});
//成功或失败进行回调函数的处理,以及成功后的灰掉提交按钮的功能
if(isValid)
{
if(!initConfig.onSuccess()){return false};
if(initConfig.submitOnce){$(":submit,:button,:reset").attr("disabled",true);}
}
else
{
initConfig.onError(firstErrorMessage, $("#" + thefirstid).get(0), errorlist);
if (thefirstid && initConfig.errorFocus) {$("#" + thefirstid).focus()};
}
initConfig.status="init";
if(isValid && initConfig.debug){alert("现在正处于调试模式(debug:true),不能提交");}
return !initConfig.debug && isValid;
},
//整个表单
ajaxForm : function(validatorGroup,option,formid)
{
if(validatorGroup == undefined){validatorGroup = "1"};
var setting = {};
$.extend(true, setting, ajaxForm_setting, option || {});
var initConfig = $.formValidator.getInitConfig(validatorGroup);
if(formid==undefined){
formid = initConfig.formID;
if(formid==""){alert('表单ID未传入');return false;};
};
if(!$.formValidator.pageIsValid(validatorGroup)){return false};
var ls_url = setting.url;
var parm = $.formValidator.serialize('#'+formid);
ls_url = ls_url + (ls_url.indexOf("?") > -1 ? ("&" + parm) : ("?" + parm));
alert(ls_url);
$.ajax(
{
type : setting.type,
url : ls_url,
cache : setting.cache,
data : setting.data,
async : setting.async,
timeout : setting.timeout,
dataType : setting.dataType,
beforeSend : function(jqXHR, configs){//再服务器没有返回数据之前,先回调提交按钮
if(setting.buttons && setting.buttons.length > 0){setting.buttons.attr({"disabled":true})};
return setting.beforeSend(jqXHR, configs);
},
success : function(data, textStatus, jqXHR){setting.success(data, textStatus, jqXHR);},
complete : function(jqXHR, textStatus){
if(setting.buttons && setting.buttons.length > 0){setting.buttons.attr({"disabled":false})};
setting.complete(jqXHR, textStatus);
},
error : function(jqXHR, textStatus, errorThrown){setting.error(jqXHR, textStatus, errorThrown);}
});
},
//把编码decodeURIComponent反转之后,再escape
serialize : function(objs,initConfig)
{
if(initConfig!=undefined){$.formValidator.resetInputValue(true,initConfig)};
var parmString = $(objs).serialize();
if(initConfig!=undefined){$.formValidator.resetInputValue(false,initConfig)};
var parmArray = parmString.split("&");
var parmStringNew="";
$.each(parmArray,function(index,data){
var li_pos = data.indexOf("=");
if(li_pos >0){
var name = data.substring(0,li_pos);
var value = escape(decodeURIComponent(data.substr(li_pos+1)));
var parm = name+"="+value;
parmStringNew = parmStringNew=="" ? parm : parmStringNew + '&' + parm;
}
});
return parmStringNew;
},
//ajax校验
ajaxValid : function(returnObj)
{
var id = returnObj.id;
var srcjo = $("#"+id);
var elem = srcjo.get(0);
var initConfig = returnObj.initConfig;
var settings = elem.settings;
var setting = settings[returnObj.ajax];
var ls_url = setting.url;
//获取要传递的参数
var validatorGroup = elem.validatorGroup;
var initConfig = $.formValidator.getInitConfig(validatorGroup);
var parm = $.formValidator.serialize(initConfig.ajaxObjects);
//添加触发的控件名、随机数、传递的参数
parm = "clientid=" + id + "&" +(setting.randNumberName ? setting.randNumberName+"="+((new Date().getTime())+Math.round(Math.random() * 10000)) : "") + (parm.length > 0 ? "&" + parm : "");
ls_url = ls_url + (ls_url.indexOf("?") > -1 ? ("&" + parm) : ("?" + parm));
//发送ajax请求
$.ajax(
{
type : setting.type,
url : ls_url,
cache : setting.cache,
data : setting.data,
async : setting.async,
timeout : setting.timeout,
dataType : setting.dataType,
success : function(data, textStatus, jqXHR){
var lb_ret,ls_status,ls_msg,lb_isValid = false;
$.formValidator.dealAjaxRequestCount(validatorGroup,-1);
//根据业务判断设置显示信息
lb_ret = setting.success(data, textStatus, jqXHR);
if((typeof lb_ret)=="string")
{
ls_status = "onError";
ls_msg = lb_ret;
}
else if(lb_ret){
lb_isValid = true;
ls_status = "onCorrect";
ls_msg = settings[0].onCorrect;
}else{
ls_status = "onError";
ls_msg = $.formValidator.getStatusText(elem,setting.onError);
alert(ls_msg)
}
setting.isValid = lb_isValid;
$.formValidator.setTipState(elem,ls_status,ls_msg);
//提交的时候触发了ajax校验,等ajax校验完成,无条件重新校验
if(returnObj.initConfig.status=="sumbitingWithAjax" && returnObj.initConfig.ajaxCountSubmit == 0)
{
if (initConfig.formID != "") {
$('#' + initConfig.formID).trigger('submit');
}
}
},
complete : function(jqXHR, textStatus){
if(setting.buttons && setting.buttons.length > 0){setting.buttons.attr({"disabled":false})};
setting.complete(jqXHR, textStatus);
},
beforeSend : function(jqXHR, configs){
//本控件如果正在校验,就中断上次
if (this.lastXMLHttpRequest) {this.lastXMLHttpRequest.abort()};
this.lastXMLHttpRequest = jqXHR;
//再服务器没有返回数据之前,先回调提交按钮
if(setting.buttons && setting.buttons.length > 0){setting.buttons.attr({"disabled":true})};
var lb_ret = setting.beforeSend(jqXHR,configs);
var isValid = false;
//无论是否成功都当做失败处理
setting.isValid = false;
if((typeof lb_ret)=="boolean" && lb_ret)
{
isValid = true;
$.formValidator.setTipState(elem,"onLoad",settings[returnObj.ajax].onWait);
}else
{
isValid = false;
$.formValidator.setTipState(elem,"onError",lb_ret);
}
setting.lastValid = "-1";
if(isValid){$.formValidator.dealAjaxRequestCount(validatorGroup,1);}
return isValid;
},
error : function(jqXHR, textStatus, errorThrown){
$.formValidator.dealAjaxRequestCount(validatorGroup,-1);
$.formValidator.setTipState(elem,"onError",$.formValidator.getStatusText(elem,setting.onError));
setting.isValid = false;
setting.error(jqXHR, textStatus, errorThrown);
},
processData : setting.processData
});
},
//处理ajax的请求个数
dealAjaxRequestCount : function(validatorGroup,val)
{
var initConfig = $.formValidator.getInitConfig(validatorGroup);
initConfig.ajaxCountValid = initConfig.ajaxCountValid + val;
if (initConfig.status == "sumbitingWithAjax") {
initConfig.ajaxCountSubmit = initConfig.ajaxCountSubmit + val;
}
},
//对正则表达式进行校验(目前只针对input和textarea)
regexValid : function(returnObj)
{
var id = returnObj.id;
var setting = returnObj.setting;
var srcTag = $("#"+id).get(0).tagName;
var elem = $("#"+id).get(0);
var isValid;
//如果有输入正则表达式,就进行表达式校验
if(elem.settings[0].empty && elem.value==""){
setting.isValid = true;
}
else
{
var regexArray = setting.regExp;
setting.isValid = false;
if((typeof regexArray)=="string") regexArray = [regexArray];
$.each(regexArray, function() {
var r = this;
if(setting.dataType=="enum"){r = eval("regexEnum."+r);}
if(r==undefined || r=="")
{
return false;
}
isValid = (new RegExp(r, setting.param)).test($(elem).val());
if(setting.compareType=="||" && isValid)
{
setting.isValid = true;
return false;
}
if(setting.compareType=="&&" && !isValid)
{
return false
}
});
if(!setting.isValid) setting.isValid = isValid;
}
},
//函数校验。返回true/false表示校验是否成功;返回字符串表示错误信息,校验失败;如果没有返回值表示处理函数,校验成功
functionValid : function(returnObj)
{
var id = returnObj.id;
var setting = returnObj.setting;
var srcjo = $("#"+id);
var lb_ret = setting.fun(srcjo.val(),srcjo.get(0));
if(lb_ret != undefined)
{
if((typeof lb_ret) === "string"){
setting.isValid = false;
returnObj.errormsg = lb_ret;
}else{
setting.isValid = lb_ret;
}
}else{
setting.isValid = true;
}
},
//对input和select类型控件进行校验
inputValid : function(returnObj)
{
var id = returnObj.id;
var setting = returnObj.setting;
var srcjo = $("#"+id);
var elem = srcjo.get(0);
var val = srcjo.val();
var sType = elem.type;
var len = $.formValidator.getLength(id);
var empty = setting.empty,emptyError = false;
switch(sType)
{
case "text":
case "hidden":
case "password":
case "textarea":
case "file":
if (setting.type == "size") {
empty = setting.empty;
if(!empty.leftEmpty){
emptyError = (val.replace(/^[ \s]+/, '').length != val.length);
}
if(!emptyError && !empty.rightEmpty){
emptyError = (val.replace(/[ \s]+$/, '').length != val.length);
}
if(emptyError && empty.emptyError){returnObj.errormsg= empty.emptyError}
}
case "checkbox":
case "select-one":
case "select-multiple":
case "radio":
var lb_go_on = false;
if(sType=="select-one" || sType=="select-multiple"){setting.type = "size";}
var type = setting.type;
if (type == "size") { //获得输入的字符长度,并进行校验
if(!emptyError){lb_go_on = true}
if(lb_go_on){val = len}
}
else if (type =="date" || type =="datetime")
{
var isok = false;
if(type=="date"){lb_go_on = isDate(val)};
if(type=="datetime"){lb_go_on = isDate(val)};
if(lb_go_on){val = new Date(val);setting.min=new Date(setting.min);setting.max=new Date(setting.max);};
}else{
stype = (typeof setting.min);
if(stype =="number")
{
val = (new Number(val)).valueOf();
if(!isNaN(val)){lb_go_on = true;}
}
if(stype =="string"){lb_go_on = true;}
}
setting.isValid = false;
if(lb_go_on)
{
if(val < setting.min || val > setting.max){
if(val < setting.min && setting.onErrorMin){
returnObj.errormsg= setting.onErrorMin;
}
if(val > setting.min && setting.onErrorMax){
returnObj.errormsg= setting.onErrorMax;
}
}
else{
setting.isValid = true;
}
}
break;
}
},
//对两个控件进行比较校验
compareValid : function(returnObj)
{
var id = returnObj.id;
var setting = returnObj.setting;
var srcjo = $("#"+id);
var desjo = $("#"+setting.desID );
var ls_dataType = setting.dataType;
curvalue = srcjo.val();
ls_data = desjo.val();
if(ls_dataType=="number")
{
if(!isNaN(curvalue) && !isNaN(ls_data)){
curvalue = parseFloat(curvalue);
ls_data = parseFloat(ls_data);
}
else{
return;
}
}
if(ls_dataType=="date" || ls_dataType=="datetime")
{
var isok = false;
if(ls_dataType=="date"){isok = (isDate(curvalue) && isDate(ls_data))};
if(ls_dataType=="datetime"){isok = (isDateTime(curvalue) && isDateTime(ls_data))};
if(isok){
curvalue = new Date(curvalue);
ls_data = new Date(ls_data)
}
else{
return;
}
}
switch(setting.operateor)
{
case "=":
setting.isValid = (curvalue == ls_data);
break;
case "!=":
setting.isValid = (curvalue != ls_data);
break;
case ">":
setting.isValid = (curvalue > ls_data);
break;
case ">=":
setting.isValid = (curvalue >= ls_data);
break;
case "<":
setting.isValid = (curvalue < ls_data);
break;
case "<=":
setting.isValid = (curvalue <= ls_data);
break;
default :
setting.isValid = false;
break;
}
},
//获取密码校验等级
passwordValid : function(elem)
{
var setting = elem.settings[elem.validatorPasswordIndex];
var pwd = elem.value;
//是否为连续字符
function isContinuousChar(str){
var str = str.toLowerCase();
var flag = 0;
for(var i=0;i<str.length;i++){
if(str.charCodeAt(i) != flag+1 && flag!=0)
return false;
else
flag = str.charCodeAt(i);
}
return true;
}
//是否字符都相同
function isSameChar(str){
var str = str.toLowerCase();
var flag = 0;
for(var i=0;i<str.length;i++){
if(str.charCodeAt(i) != flag && flag!=0)
return false;
else
flag = str.charCodeAt(i);
}
return true;
}
//获取标记所在的位置,用1表示
function getFlag(val,sum,index)
{
if(sum==undefined){sum=[0,0,0,0]}
if(index==undefined){index=-1};
index ++;
sum[index] = val % 2;
val = Math.floor(val / 2);
if(val==1 || val==0){sum[index+1] = val;return sum}
sum = getFlag(val,sum,index);
return sum;
}
//判断密码各个位置的组成情况
if(pwd==""){return 0};
if(setting.onErrorContinueChar!="" && isContinuousChar(pwd)){return -1};
if(setting.onErrorSameChar!="" && isSameChar(pwd)){return -2};
if(setting.compareID!="" && $("#"+setting.compareID).val()==pwd){return -3};
var sum1 = [0, 0, 0, 0];
var specicalChars = "!,@,#,$,%,\^,&,*,?,_,~";
var len = pwd.length;
for (var i=0; i< len; i++) {
var c = pwd.charCodeAt(i);
if (c >=48 && c <=57){ //数字
sum1[0] += 1;
}else if (c >=97 && c <=122){ //小写字母
sum1[1] += 1;
}else if (c >=65 && c <=90){ //大写字母
sum1[2] += 1;
}else if(specicalChars.indexOf(pwd.substr(i,1))>=0){ //特殊字符
sum1[3] += 1;
}
}
//遍历json变量获取字符串
var returnLevel = 0;
var hasFind = true;
$.each(passwordStrengthRule,function(j,n){
var level = n.level;
var rules = n.rule;
$.each(rules,function(i,rule){
var index = 0;
//依次编译所有的、有配置(该位置==1)的节点
hasFind = true;
$.each(getFlag(rule.flag),function(k,value){
if(value==1){
val = rule.value[index++];
var val = val == 0 ? len : (val > len ? len : val);
if(sum1[k] < val){hasFind = false;return false;}
}
});
if(hasFind){returnLevel = level;return false;}
})
if(hasFind){returnLevel = level;}
});
return returnLevel;
},
//定位漂浮层
localTooltip : function(e)
{
e = e || window.event;
var mouseX = e.pageX || (e.clientX ? e.clientX + document.body.scrollLeft : 0);
var mouseY = e.pageY || (e.clientY ? e.clientY + document.body.scrollTop : 0);
$("#fvtt").css({"top":(mouseY+2)+"px","left":(mouseX-40)+"px"});
},
reloadAutoTip : function(validatorGroup)
{
if(validatorGroup == undefined) validatorGroup = "1";
var initConfig = $.formValidator.getInitConfig(validatorGroup);
$.each(initConfig.validObjects,function()
{
if(initConfig.mode == "AutoTip")
{
//获取层的ID、相对定位控件的ID和坐标
var setting = this.settings[0];
var relativeID = "#"+setting.relativeID;
var offset = $(relativeID ).offset();
var y = offset.top;
var x = $(relativeID ).width() + offset.left;
$("#"+setting.tipID).parent().show().css({left: x+"px", top: y+"px"});
}
});
},
getStatusText : function(elem,obj)
{
return ($.isFunction(obj) ? obj($(elem).val()) : obj);
},
resetInputValue : function(real,initConfig,id)
{
var showTextObjects;
if(id){
showTextObjects = $("#"+id);
}else{
showTextObjects = $(initConfig.showTextObjects);
}
showTextObjects.each(function(index,elem){
if(elem.isInputControl){
var showText = elem.settings[0].onShowText;
if(real && showText==elem.value){elem.value = ""};
if(!real && showText!="" && elem.value == ""){elem.value = showText};
}
});
}
};
//每个校验控件必须初始化的
$.fn.formValidator = function(cs)
{
cs = cs || {};
var setting = {};
//获取该校验组的全局配置信息
if(cs.validatorGroup == undefined){cs.validatorGroup = "1"};
//先合并整个配置(深度拷贝)
$.extend(true,setting, formValidator_setting);
var initConfig = $.formValidator.getInitConfig(cs.validatorGroup);
//校验索引号,和总记录数
initConfig.validCount += 1;
//如果为精简模式,tipCss要重新设置初始值
if(initConfig.mode == "SingleTip"){setting.tipCss = {left:10,top:1,width:22,height:22,display:"none"}};
//弹出消息提示模式,自动修复错误
if(initConfig.mode == "AlertTip"){setting.autoModify=true};
//先合并整个配置(深度拷贝)
$.extend(true,setting, cs || {});
return this.each(function(e)
{
//记录该控件的校验顺序号和校验组号
this.validatorIndex = initConfig.validCount - 1;
this.validatorGroup = cs.validatorGroup;
var jqobj = $(this);
//自动形成TIP
var setting_temp = {};
$.extend(true,setting_temp, setting);
//判断是否有ID
var id = jqobj.attr('id');
if(!id)
{
id = Math.ceil(Math.random()*50000000);
jqobj.attr('id', id);
}
var tip = setting_temp.tipID ? setting_temp.tipID : id+"Tip";
if(initConfig.mode == "AutoTip" || initConfig.mode == "FixTip")
{
var tipDiv = $("#"+tip);
//获取层的ID、相对定位控件的ID和坐标
if(initConfig.mode == "AutoTip" && tipDiv.length==0)
{
tipDiv = $("<div style='position:absolute;' id='"+tip+"'></div>");
var relativeID = setting_temp.relativeID ? setting_temp.relativeID : id;
var offset = $("#"+relativeID ).offset();
setting_temp.tipCss.top = offset.top + setting_temp.tipCss.top;
setting_temp.tipCss.left = $("#"+relativeID ).width() + offset.left + setting_temp.tipCss.left;
var formValidateTip = $("<div style='position:absolute;' id='"+tip+"'></div>").appendTo($("body"));
formValidateTip.css(setting_temp.tipCss);
setting.relativeID = relativeID ;
}
tipDiv.css("margin","0px").css("padding","0px").css("background","transparent");
}else if(initConfig.mode == "SingleTip"){
jqobj.showTooltips();
}
//每个控件都要保存这个配置信息、为了取数方便,冗余一份控件总体配置到控件上
setting.tipID = tip;
setting.pwdTipID = setting_temp.pwdTipID ? setting_temp.pwdTipID : setting.tipID;
setting.fixTipID = setting_temp.fixTipID ? setting_temp.fixTipID : id+"FixTip";
$.formValidator.appendValid(id,setting);
//保存控件ID
var validIndex = $.inArray(jqobj,initConfig.validObjects);
if(validIndex == -1)
{
if (setting_temp.ajax) {
var ajax = initConfig.ajaxObjects;
initConfig.ajaxObjects = ajax + (ajax != "" ? ",#" : "#") + id;
}
initConfig.validObjects.push(this);
}else{
initConfig.validObjects[validIndex] = this;
}
//初始化显示信息
if(initConfig.mode != "AlertTip"){
$.formValidator.setTipState(this,"onShow",setting.onShow);
}
var srcTag = this.tagName.toLowerCase();
var stype = this.type;
var defaultval = setting.defaultValue;
var isInputControl = stype == "password" || stype == "text" || stype == "textarea";
this.isInputControl = isInputControl;
//处理默认值
if(defaultval){
jqobj.val(defaultval);
}
//固定提示内容
var fixTip = $("#"+setting.fixTipID);
var showFixText = setting.onShowFixText;
if(fixTip.length==1 && onMouseOutFixTextHtml!="" && onMouseOnFixTextHtml!="" && showFixText != "")
{
jqobj.hover(
function () {
fixTip.html(onMouseOnFixTextHtml.replace(/\$data\$/g, showFixText));
},
function () {
fixTip.html(onMouseOutFixTextHtml.replace(/\$data\$/g, showFixText));
}
);
fixTip.css("padding","0px 0px 0px 0px").css("margin","0px 0px 0px 0px").html(onMouseOutFixTextHtml.replace(/\$data\$/g, setting.onShowFixText));
}
//获取输入框内的提示内容
var showText = setting.onShowText;
if(srcTag == "input" || srcTag=="textarea")
{
if (isInputControl) {
if(showText !=""){
showObjs = initConfig.showTextObjects;
initConfig.showTextObjects = showObjs + (showObjs != "" ? ",#" : "#") + id;
jqobj.val(showText);
jqobj.css("color",setting.onShowTextColor.mouseOutColor);
}
}
//注册获得焦点的事件。改变提示对象的文字和样式,保存原值
jqobj.focus(function()
{
if (isInputControl) {
var val = jqobj.val();
this.validValueOld = val;
if(showText==val){
this.value = "";
jqobj.css("color",setting.onShowTextColor.mouseOnColor);
}
};
if(initConfig.mode != "AlertTip"){
//保存原来的状态
var tipjq = $("#"+tip);
this.lastshowclass = tipjq.attr("class");
this.lastshowmsg = tipjq.text();
$.formValidator.setTipState(this,"onFocus",setting.onFocus);
};
if(this.validatorPasswordIndex > 0){$("#"+setting.pwdTipID).show();jqobj.trigger('keyup');}
});
//按键时候触发校验
jqobj.bind("keyup",function(){
if(this.validatorPasswordIndex > 0)
{
try{
var returnObj = $.formValidator.oneIsValid(id);
var level = $.formValidator.passwordValid(this)
if(level < 0){level=0};
if(!returnObj.isValid){level = 0};
$("#"+setting.pwdTipID).show();
$("#"+setting.pwdTipID).html(passwordStrengthStatusHtml[level]);
}catch(e)
{
alert("密码强度校验失败,错误原因:变量passwordStrengthStatusHtml语法错误或者为设置)");
}
}
});
//注册失去焦点的事件。进行校验,改变提示对象的文字和样式;出错就提示处理
jqobj.bind(setting.triggerEvent, function(){
var settings = this.settings;
//根据配置截掉左右的空格
if(settings[0].leftTrim){this.value = this.replace(/^\s*/g, "");}
if(settings[0].rightTrim){this.value = this.replace(/\s*$/g, "");}
//恢复默认值
if(isInputControl){
if(this.value == "" && showText != ""){this.value = showText}
if(this.value == showText){jqobj.css("color",setting.onShowTextColor.mouseOutColor)}
}
//进行有效性校验
var returnObj = $.formValidator.oneIsValid(id);
if(returnObj==null){return}
if(returnObj.ajax >= 0)
{
$.formValidator.showAjaxMessage(returnObj);
}
else
{
var showmsg = $.formValidator.showMessage(returnObj);
if(!returnObj.isValid)
{
//自动修正错误
var auto = setting.autoModify && isInputControl;
if(auto)
{
$(this).val(this.validValueOld);
if(initConfig.mode != "AlertTip"){$.formValidator.setTipState(this,"onShow",$.formValidator.getStatusText(this,setting.onCorrect))};
}
else
{
if(initConfig.forceValid || setting.forceValid){
alert(showmsg);this.focus();
}
}
}
}
});
}
else if (srcTag == "select")
{
jqobj.bind({
//获得焦点
focus: function(){
if (initConfig.mode != "AlertTip") {
$.formValidator.setTipState(this, "onFocus", setting.onFocus)
};
},
//失去焦点
blur: function(){
if(this.validValueOld==undefined || this.validValueOld==jqobj.val()){$(this).trigger("change")}
},
//选择项目后触发
change: function(){
var returnObj = $.formValidator.oneIsValid(id);
if(returnObj==null){return;}
if ( returnObj.ajax >= 0){
$.formValidator.showAjaxMessage(returnObj);
}else{
$.formValidator.showMessage(returnObj);
}
}
});
}
});
};
$.fn.inputValidator = function(controlOptions)
{
var settings = {};
$.extend(true, settings, inputValidator_setting, controlOptions || {});
return this.each(function(){
$.formValidator.appendValid(this.id,settings);
});
};
$.fn.compareValidator = function(controlOptions)
{
var settings = {};
$.extend(true, settings, compareValidator_setting, controlOptions || {});
return this.each(function(){
$.formValidator.appendValid(this.id,settings);
});
};
$.fn.regexValidator = function(controlOptions)
{
var settings = {};
$.extend(true, settings, regexValidator_setting, controlOptions || {});
return this.each(function(){
$.formValidator.appendValid(this.id,settings);
});
};
$.fn.functionValidator = function(controlOptions)
{
var settings = {};
$.extend(true, settings, functionValidator_setting, controlOptions || {});
return this.each(function(){
$.formValidator.appendValid(this.id,settings);
});
};
$.fn.ajaxValidator = function(controlOptions)
{
var settings = {};
$.extend(true, settings, ajaxValidator_setting, controlOptions || {});
return this.each(function()
{
var initConfig = $.formValidator.getInitConfig(this.validatorGroup);
var ajax = initConfig.ajaxObjects;
if((ajax+",").indexOf("#"+this.id+",") == -1)
{
initConfig.ajaxObjects = ajax + (ajax != "" ? ",#" : "#") + this.id;
}
this.validatorAjaxIndex = $.formValidator.appendValid(this.id,settings);
});
};
$.fn.passwordValidator = function(controlOptions)
{
//默认配置
var settings = {};
$.extend(true, settings, passwordValidator_setting, controlOptions || {});
return this.each(function()
{
this.validatorPasswordIndex = $.formValidator.appendValid(this.id,settings);
});
};
//指定控件显示通过或不通过样式
$.fn.defaultPassed = function(onShow)
{
return this.each(function()
{
var settings = this.settings;
settings[0].defaultPassed = true;
this.onceValided = true;
for ( var i = 1 ; i < settings.length ; i ++ )
{
settings[i].isValid = true;
if(!$.formValidator.getInitConfig(settings[0].validatorGroup).mode == "AlertTip"){
var ls_style = onShow ? "onShow" : "onCorrect";
$.formValidator.setTipState(this,ls_style,settings[0].onCorrect);
}
}
});
};
//指定控件不参加校验
$.fn.unFormValidator = function(unbind)
{
return this.each(function()
{
if(this.settings)
{
this.settings[0].bind = !unbind;
if(unbind){
$("#"+this.settings[0].tipID).hide();
}else{
$("#"+this.settings[0].tipID).show();
}
}
});
};
//显示漂浮显示层
$.fn.showTooltips = function()
{
if($("body [id=fvtt]").length==0){
fvtt = $("<div id='fvtt' style='position:absolute;z-index:56002'></div>");
$("body").append(fvtt);
fvtt.before("<iframe index=0 src='about:blank' class='fv_iframe' scrolling='no' frameborder='0'></iframe>");
}
return this.each(function()
{
jqobj = $(this);
s = $("<span class='top' id=fv_content style='display:block'></span>");
b = $("<b class='bottom' style='display:block' />");
this.tooltip = $("<span class='fv_tooltip' style='display:block'></span>").append(s).append(b).css({"filter":"alpha(opacity:95)","KHTMLOpacity":"0.95","MozOpacity":"0.95","opacity":"0.95"});
//注册事件
jqobj.bind({
mouseover : function(e){
$("#fvtt").empty().append(this.tooltip).show();
$("#fv_content").html(this.Tooltip);
$.formValidator.localTooltip(e);
},
mouseout : function(){
$("#fvtt").hide();
},
mousemove: function(e){
$.formValidator.localTooltip(e);
}
});
});
}
})(jQuery);
var initConfig_setting =
{
theme:"Default",
validatorGroup : "1", //分组号
formID:"", //表单ID
submitOnce:false, //页面是否提交一次,不会停留
ajaxForm : null, //如果不为null,表示整个表单ajax提交
mode : "FixTip", //显示模式
errorFocus:true, //第一个错误的控件获得焦点
wideWord:true, //一个汉字当做2个长
forceValid:false, //控件输入正确之后,才允许失去焦
debug:false, //调试模式点
inIframe:false,
onSuccess: function() {return true;}, //提交成功后的回调函数
onError: $.noop, //提交失败的回调函数度
status:"", //提交的状态:submited、sumbiting、sumbitingWithAjax
ajaxPrompt : "当前有数据正在进行服务器端校验,请稍候", //控件失去焦点后,触发ajax校验,没有返回结果前的错误提示
validCount:0, //含ajaxValidator的控件个数
ajaxCountSubmit:0, //提交的时候触发的ajax验证个数
ajaxCountValid:0, //失去焦点时候触发的ajax验证个数
validObjects:[], //参加校验的控件集合
ajaxObjects:"", //传到服务器的控件列表
showTextObjects:"",
validateType : "initConfig"
};
var formValidator_setting =
{
validatorGroup : "1",
onShowText : "",
onShowTextColor:{mouseOnColor:"#000000",mouseOutColor:"#999999"},
onShowFixText:"",
onShow :"请输入内容",
onFocus: "请输入内容",
onCorrect: "输入正确",
onEmpty: "输入内容为空",
empty :false,
autoModify : false,
defaultValue : null,
bind : true,
ajax : false,
validateType : "formValidator",
tipCss :
{
left:10,
top:-4,
height:20,
width:280
},
triggerEvent:"blur",
forceValid : false,
tipID : null,
pwdTipID : null,
fixTipID : null,
relativeID : null,
index : 0,
leftTrim : false,
rightTrim : false
};
var inputValidator_setting =
{
isValid : false,
type : "size",
min : 0,
max : 99999,
onError:"输入错误",
validateType:"inputValidator",
empty:{leftEmpty:true,rightEmpty:true,leftEmptyError:null,rightEmptyError:null}
};
var compareValidator_setting =
{
isValid : false,
desID : "",
operateor :"=",
onError:"输入错误",
validateType:"compareValidator"
};
var regexValidator_setting =
{
isValid : false,
regExp : "",
param : "i",
dataType : "string",
compareType : "||",
onError:"输入的格式不正确",
validateType:"regexValidator"
};
var ajaxForm_setting =
{
type : "GET",
url : window.location.href,
dataType : "html",
timeout : 100000,
data : null,
async : true,
cache : false,
buttons : null,
beforeSend : function(){return true;},
success : function(){return true;},
complete : $.noop,
processData : true,
error : $.noop
};
var ajaxValidator_setting =
{
isValid : false,
lastValid : "",
oneceValid : false,
randNumberName : "rand",
onError:"服务器校验没有通过",
onWait:"正在等待服务器返回数据",
validateType:"ajaxValidator"
};
$.extend(true,ajaxValidator_setting,ajaxForm_setting);
var functionValidator_setting =
{
isValid : true,
fun : function(){this.isValid = true;},
validateType:"functionValidator",
onError:"输入错误"
};
var passwordValidator_setting = {
isValid : true,
compareID : "",
validateType:"passwordValidator",
onErrorContinueChar:"密码字符为连续字符不被允许",
onErrorSameChar:"密码字符都相同不被允许",
onErrorCompareSame:"密码于用户名相同不被允许"
};
var validatorGroup_setting = [];
var fv_scriptSrc = document.getElementsByTagName('script')[document.getElementsByTagName('script').length - 1].src;
|
JavaScript
|
/*
EASY TABS 1.2 Produced and Copyright by Koller Juergen
www.kollermedia.at | www.austria-media.at
Need Help? http:/www.kollermedia.at/archive/2007/07/10/easy-tabs-12-now-with-autochange
You can use this Script for private and commercial Projects, but just leave the two credit lines, thank you.
*/
//EASY TABS 1.2 - MENU SETTINGS
//Set the id names of your tablink (without a number at the end)
var tablink_idname = new Array("tablink")
//Set the id name of your tabcontentarea (without a number at the end)
var tabcontent_idname = new Array("tabcontent")
//Set the number of your tabs
var tabcount = new Array("4")
//Set the Tab wich should load at start (In this Example:Tab 2 visible on load)
var loadtabs = new Array("2")
//Set the Number of the Menu which should autochange (if you dont't want to have a change menu set it to 0)
var autochangemenu = 1;
//the speed in seconds when the tabs should change
var changespeed = 3;
//should the autochange stop if the user hover over a tab from the autochangemenu? 0=no 1=yes
var stoponhover = 0;
//END MENU SETTINGS
/*Swich EasyTabs Functions - no need to edit something here*/
function easytabs(menunr, active) { if (menunr == autochangemenu){currenttab=active;}if ((menunr == autochangemenu)&&(stoponhover==1)) {stop_autochange()} else if ((menunr == autochangemenu)&&(stoponhover==0)) {counter=0;}menunr = menunr-1;for (i=1; i <= tabcount[menunr]; i++){document.getElementById(tablink_idname[menunr]+i).className='tab'+i;document.getElementById(tabcontent_idname[menunr]+i).style.display = 'none';}document.getElementById(tablink_idname[menunr]+active).className='tab'+active+' tabactive';document.getElementById(tabcontent_idname[menunr]+active).style.display = 'block';}var timer; counter=0; var totaltabs=tabcount[autochangemenu-1];var currenttab=loadtabs[autochangemenu-1];function start_autochange(){counter=counter+1;timer=setTimeout("start_autochange()",1000);if (counter == changespeed+1) {currenttab++;if (currenttab>totaltabs) {currenttab=1}easytabs(autochangemenu,currenttab);restart_autochange();}}function restart_autochange(){clearTimeout(timer);counter=0;start_autochange();}function stop_autochange(){clearTimeout(timer);counter=0;}
window.onload=function(){
var menucount=loadtabs.length; var a = 0; var b = 1; do {easytabs(b, loadtabs[a]); a++; b++;}while (b<=menucount);
if (autochangemenu!=0){start_autochange();}
}
|
JavaScript
|
var onShowHtml = "<div class='$class$'>$data$</div>";
var onFocusHtml = "<div class='$class$'>$data$</div>";
var onErrorHtml = "<div class='$class$'>$data$</div>";
var onCorrectHtml = "<div class='$class$'>$data$</div>";
var onShowClass = "";
var onFocusClass = "";
var onErrorClass = "";
var onCorrectClass = "";
|
JavaScript
|
//提示层的HTML
var onShowHtml = '';
var onFocusHtml = '';
var onErrorHtml = '<P class="noticeWrap"><B class="ico-warning"></B><SPAN class=txt-err>$data$</SPAN></P>';
var onCorrectHtml = '<P class="noticeWrap"><B class="ico-succ"></B><SPAN class=txt-succ>$data$</SPAN></P>';
var onShowHtml = '';
//文本框的样式
var onShowClass = "g-ipt";
var onFocusClass = "g-ipt-active";
var onErrorClass = "g-ipt-err";
var onCorrectClass = "g-ipt";
//固定提示层的HTML
var onMouseOnFixTextHtml = '<DIV class="txt-info-mouseon">$data$</DIV>';
var onMouseOutFixTextHtml = '<DIV class="txt-info-mouseout">$data$</DIV>';
//初始状态,加其它几种状态
var passwordStrengthStatusHtml = [
'<P id=passStrong class="pswState">强度:<EM class=st1>弱</EM><B class="progressImage prog0"></B><EM class=st2>强</EM></P>',
'<P id=passStrong class="pswState">强度:<EM class=st1>弱</EM><B class="progressImage prog1"></B><EM class=st2>强</EM></P>',
'<P id=passStrong class="pswState">强度:<EM class=st1>弱</EM><B class="progressImage prog2"></B><EM class=st2>强</EM></P>',
'<P id=passStrong class="pswState">强度:<EM class=st1>弱</EM><B class="progressImage prog3"></B><EM class=st2>强</EM></P>'
];
var passwordStrengthText = ['密码强度:弱','密码强度:中','密码强度:强']
//密码强度校验规则(flag=1(数字)+2(小写)+4(大写)+8(特殊字符)的组合,value里的0表示跟密码一样长,1表示起码1个长度)
var passwordStrengthRule = [
{level:1,rule:[
{flag:1,value:[0]}, //数字
{flag:2,value:[0]}, //小写字符
{flag:4,value:[0]} //大写字符
]
},
{level:2,rule:[
{flag:8,value:[0]}, //特符
{flag:9,value:[1,1]}, //数字(>=1)+特符>=1)
{flag:10,value:[1,1]}, //小写(>=1)+特符>=1)
{flag:12,value:[1,1]}, //大写(>=1)+特符>=1)
{flag:3,value:[1,1]}, //数字(>=1)+小写(>=1)
{flag:5,value:[1,1]}, //数字(>=1)+大写(>=1)
{flag:6,value:[1,1]} //小写(>=1)+大写(>=1)
]
},
{level:3,rule:[
{flag:11,value:[1,1,1]}, //数字(>=1)+小写(>=1)+特符(>=1)
{flag:13,value:[1,1,1]}, //数字(>=1)+大写(>=1)+特符(>=1)
{flag:14,value:[1,1,1]}, //小写(>=1)+大写(>=1)+特符(>=1)
{flag:7,value:[1,1,1]} //数字(>=1)+小写(>=1)+大写(>=1)
]
}
];
|
JavaScript
|
var onShowHtml = "<div class='$class$'>$data$</div>";
var onFocusHtml = "<div class='$class$'>$data$</div>";
var onErrorHtml = "<div class='$class$'>$data$</div>";
var onCorrectHtml = "<div class='$class$'>$data$</div>";
var onShowClass = "input_show";
var onFocusClass = "input_focus";
var onErrorClass = "input_error";
var onCorrectClass = "input_correct";
|
JavaScript
|
var onShowHtml = "";
var onFocusHtml = "<span class='$class$'><span class='$class$_top'>$data$</span><span class='$class$_bot'></span></span>";
var onErrorHtml = "<span class='$class$'><span class='$class$_top'>$data$</span><span class='$class$_bot'></span></span>";
var onCorrectHtml = "<span class='$class$'></span>";
var onShowClass = "input_public";
var onFocusClass = "input_public input_focus";
var onErrorClass = "input_public input_error";
var onCorrectClass = "input_public input_correct";
|
JavaScript
|
$(function () {
$(".msgtable tr:nth-child(odd)").addClass("tr_bg"); //隔行变色
$(".msgtable tr").hover(
function () {
$(this).addClass("tr_hover_col");
},
function () {
$(this).removeClass("tr_hover_col");
}
);
$("input[type='text'].input").focus(function () {
if (!$(this).hasClass("tcal")) {
$(this).addClass("focus");
}
}).blur(function () {
$(this).removeClass("focus");
});
});
//设置为自动高
function SetWinHeight(obj) {
var win = obj;
if (document.getElementById) {
if (win && !window.opera) {
if (win.contentDocument && win.contentDocument.body.offsetHeight)
win.height = win.contentDocument.body.offsetHeight + 100;
else if (win.Document && win.Document.body.scrollHeight)
win.height = win.Document.body.scrollHeight + 100;
}
}
}
//全选取消按钮函数,调用样式如:
function checkAll(chkobj) {
if ($(chkobj).text() == "全选") {
$(chkobj).text("取消");
$(".checkall").each(function () {
if ($(this).attr("disabled") != 'disabled') {
$(this).find("input").attr("checked", true);
}
});
} else {
$(chkobj).text("全选");
$(".checkall input").attr("checked", false);
}
}
//遮罩提示窗口
function jsmsg(w, h, msgtitle, msgbox, url, msgcss) {
$("#msgdialog").remove();
var cssname = "";
switch (msgcss) {
case "Success":
cssname = "icon-01";
break;
case "Error":
cssname = "icon-02";
break;
default:
cssname = "icon-03";
break;
}
var str = "<div id='msgdialog' title='" + msgtitle + "'><p class='" + cssname + "'>" + msgbox + "</p></div>";
$("body").append(str);
$("#msgdialog").dialog({
//title: null,
//show: null,
bgiframe: true,
autoOpen: false,
width: w,
//height: h,
resizable: false,
closeOnEscape: true,
buttons: { "确定": function () { $(this).dialog("close"); } },
modal: true
});
$("#msgdialog").dialog("open");
if (url == "back") {
mainFrame.history.back(-1);
} else if (url != "") {
mainFrame.location.href = url;
}
}
function jsmsgCurPage(w, h, msgtitle, msgbox, url, msgcss) {
$("#msgdialog").remove();
var cssname = "";
switch (msgcss) {
case "Success":
cssname = "icon-01";
break;
case "Error":
cssname = "icon-02";
break;
default:
cssname = "icon-03";
break;
}
var str = "<div id='msgdialog' title='" + msgtitle + "'><p class='" + cssname + "'>" + msgbox + "</p></div>";
$("body").append(str);
$("#msgdialog").dialog({
//title: null,
//show: null,
bgiframe: true,
autoOpen: false,
width: w,
height: h,
resizable: false,
closeOnEscape: true,
buttons: { "确定": function () { $(this).dialog("close"); } },
modal: true
});
$("#msgdialog").dialog("open");
}
//可以自动关闭的提示
function jsprint(msgtitle, url, msgcss) {
$("#msgprint").remove();
var cssname = "";
switch (msgcss) {
case "Success":
cssname = "pcent correct";
break;
case "Error":
cssname = "pcent disable";
break;
default:
cssname = "pcent warning";
break;
}
var str = "<div id=\"msgprint\" class=\"" + cssname + "\">" + msgtitle + "</div>";
$("body").append(str);
$("#msgprint").show();
if (url == "back") {
mainFrame.history.back(-1);
} else if (url != "") {
mainFrame.location.href = url;
}
//3秒后清除提示
setTimeout(function () {
$("#msgprint").fadeOut(500);
//如果动画结束则删除节点
if (!$("#msgprint").is(":animated")) {
$("#msgprint").remove();
}
}, 3000);
}
//可以自动关闭的提示
function jsprintCurPage(msgtitle, url, msgcss) {
$("#msgprint").remove();
var cssname = "";
switch (msgcss) {
case "Success":
cssname = "pcent correct";
break;
case "Error":
cssname = "pcent disable";
break;
default:
cssname = "pcent warning";
break;
}
var str = "<div id=\"msgprint\" class=\"" + cssname + "\">" + msgtitle + "</div>";
$("body").append(str);
$("#msgprint").show();
var outT = 900;
var outT2 = 3000;
if (url == "thickbox") {
outT = 500;
outT2 = 1500;
}
//3秒后清除提示
setTimeout(function () {
$("#msgprint").fadeOut(outT);
//如果动画结束则删除节点
if (!$("#msgprint").is(":animated")) {
$("#msgprint").remove();
}
if (url == "back") {
this.history.back(-1);
} else if (url == "#") {
return;
} else if (url == "thickbox") {
TB_iframeContent.location.href = $("#TB_iframeContent").attr("src");
} else if (url != "") {
this.location.href = url;
}
}, outT2);
}
function SetPermission() {
$("#SetPermission").remove();
var str = "<div id='SetPermission' style='width:100%; position:fixed; z-index:99999999; background:#000; left:0px; top:0px; bottom:0px; right:0px; display:none;'></div>";
$("body").append(str);
$("#SetPermission").css("display", "block").animate({ opacity: 0.1 });
}
|
JavaScript
|
/*
EASY TABS 1.2 Produced and Copyright by Koller Juergen
www.kollermedia.at | www.austria-media.at
Need Help? http:/www.kollermedia.at/archive/2007/07/10/easy-tabs-12-now-with-autochange
You can use this Script for private and commercial Projects, but just leave the two credit lines, thank you.
*/
//EASY TABS 1.2 - MENU SETTINGS
//Set the id names of your tablink (without a number at the end)
var tablink_idname = new Array("tablink")
//Set the id name of your tabcontentarea (without a number at the end)
var tabcontent_idname = new Array("tabcontent")
//Set the number of your tabs
var tabcount = new Array("4")
//Set the Tab wich should load at start (In this Example:Tab 2 visible on load)
var loadtabs = new Array("2")
//Set the Number of the Menu which should autochange (if you dont't want to have a change menu set it to 0)
var autochangemenu = 1;
//the speed in seconds when the tabs should change
var changespeed = 3;
//should the autochange stop if the user hover over a tab from the autochangemenu? 0=no 1=yes
var stoponhover = 0;
//END MENU SETTINGS
/*Swich EasyTabs Functions - no need to edit something here*/
function easytabs(menunr, active) { if (menunr == autochangemenu){currenttab=active;}if ((menunr == autochangemenu)&&(stoponhover==1)) {stop_autochange()} else if ((menunr == autochangemenu)&&(stoponhover==0)) {counter=0;}menunr = menunr-1;for (i=1; i <= tabcount[menunr]; i++){document.getElementById(tablink_idname[menunr]+i).className='tab'+i;document.getElementById(tabcontent_idname[menunr]+i).style.display = 'none';}document.getElementById(tablink_idname[menunr]+active).className='tab'+active+' tabactive';document.getElementById(tabcontent_idname[menunr]+active).style.display = 'block';}var timer; counter=0; var totaltabs=tabcount[autochangemenu-1];var currenttab=loadtabs[autochangemenu-1];function start_autochange(){counter=counter+1;timer=setTimeout("start_autochange()",1000);if (counter == changespeed+1) {currenttab++;if (currenttab>totaltabs) {currenttab=1}easytabs(autochangemenu,currenttab);restart_autochange();}}function restart_autochange(){clearTimeout(timer);counter=0;start_autochange();}function stop_autochange(){clearTimeout(timer);counter=0;}
window.onload=function(){
var menucount=loadtabs.length; var a = 0; var b = 1; do {easytabs(b, loadtabs[a]); a++; b++;}while (b<=menucount);
if (autochangemenu!=0){start_autochange();}
}
|
JavaScript
|
/** @license Hyphenator X.Y.Z - client side hyphenation for webbrowsers
* Copyright (C) 2012 Mathias Nater, Zürich (mathias at mnn dot ch)
* Project and Source hosted on http://code.google.com/p/hyphenator/
*
* This JavaScript code is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser
* General Public License (GNU LGPL) as published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. The code is distributed WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
*
* As additional permission under GNU GPL version 3 section 7, you
* may distribute non-source (e.g., minimized or compacted) forms of
* that code without the copy of the GNU GPL normally required by
* section 4, provided you include this license notice and a URL
* through which recipients can access the Corresponding Source.
*
*
* Hyphenator.js contains code from Bram Steins hypher.js-Project:
* https://github.com/bramstein/Hypher
*
* Code from this project is marked in the source and belongs
* to the following license:
*
* Copyright (c) 2011, Bram Stein
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/*
* Comments are jsdoctoolkit formatted. See http://code.google.com/p/jsdoc-toolkit/
*/
/* The following comment is for JSLint: */
/*global window */
/*jslint browser: true */
/**
* @constructor
* @description Provides all functionality to do hyphenation, except the patterns that are loaded
* externally.
* @author Mathias Nater, <a href = "mailto:mathias@mnn.ch">mathias@mnn.ch</a>
* @version X.Y.Z
* @namespace Holds all methods and properties
* @example
* <script src = "Hyphenator.js" type = "text/javascript"></script>
* <script type = "text/javascript">
* Hyphenator.run();
* </script>
*/
var Hyphenator = (function (window) {
'use strict';
/**
* @name Hyphenator-contextWindow
* @private
* @description
* contextWindow stores the window for the document to be hyphenated.
* If there are frames this will change.
* So use contextWindow instead of window!
*/
var contextWindow = window,
/**
* @name Hyphenator-supportedLangs
* @description
* A key-value object that stores supported languages and meta data.
* The key is the bcp47 code of the language and the value
* is an object containing following informations about the language:
* file: filename of the pattern file,
* script: script type of the language (e.g. 'latin' for english), this type is abbreviated by an id,
* prompt: the sentence prompted to the user, if Hyphenator.js doesn't find a language hint.
* @type {Object.<string>, Object>}
* @private
* @example
* Check if language lang is supported:
* if (supportedLangs.hasOwnProperty(lang))
*/
supportedLangs = (function () {
var r = {},
o = function (code, file, script, prompt) {
r[code] = {'file': file, 'script': script, 'prompt': prompt};
};
//latin:0, cyrillic: 1, arabic: 2, armenian:3, bengali: 4, devangari: 5, greek: 6
//gujarati: 7, kannada: 8, lao: 9, malayalam: 10, oriya: 11, persian: 12, punjabi: 13, tamil: 14, telugu: 15
//
//(language code, file name, script, prompt)
o('be', 'be.js', 1, 'Мова гэтага сайта не можа быць вызначаны аўтаматычна. Калі ласка пакажыце мову:');
o('ca', 'ca.js', 0, '');
o('cs', 'cs.js', 0, 'Jazyk této internetové stránky nebyl automaticky rozpoznán. Určete prosím její jazyk:');
o('da', 'da.js', 0, 'Denne websides sprog kunne ikke bestemmes. Angiv venligst sprog:');
o('bn', 'bn.js', 4, '');
o('de', 'de.js', 0, 'Die Sprache dieser Webseite konnte nicht automatisch bestimmt werden. Bitte Sprache angeben:');
o('el', 'el-monoton.js', 6, '');
o('el-monoton', 'el-monoton.js', 6, '');
o('el-polyton', 'el-polyton.js', 6, '');
o('en', 'en-us.js', 0, 'The language of this website could not be determined automatically. Please indicate the main language:');
o('en-gb', 'en-gb.js', 0, 'The language of this website could not be determined automatically. Please indicate the main language:');
o('en-us', 'en-us.js', 0, 'The language of this website could not be determined automatically. Please indicate the main language:');
o('eo', 'eo.js', 0, 'La lingvo de ĉi tiu retpaĝo ne rekoneblas aŭtomate. Bonvolu indiki ĝian ĉeflingvon:');
o('es', 'es.js', 0, 'El idioma del sitio no pudo determinarse autom%E1ticamente. Por favor, indique el idioma principal:');
o('et', 'et.js', 0, 'Veebilehe keele tuvastamine ebaõnnestus, palun valige kasutatud keel:');
o('fi', 'fi.js', 0, 'Sivun kielt%E4 ei tunnistettu automaattisesti. M%E4%E4rit%E4 sivun p%E4%E4kieli:');
o('fr', 'fr.js', 0, 'La langue de ce site n%u2019a pas pu %EAtre d%E9termin%E9e automatiquement. Veuillez indiquer une langue, s.v.p.%A0:');
o('grc', 'grc.js', 6, '');
o('gu', 'gu.js', 7, '');
o('hi', 'hi.js', 5, '');
o('hu', 'hu.js', 0, 'A weboldal nyelvét nem sikerült automatikusan megállapítani. Kérem adja meg a nyelvet:');
o('hy', 'hy.js', 3, 'Չհաջողվեց հայտնաբերել այս կայքի լեզուն։ Խնդրում ենք նշեք հիմնական լեզուն՝');
o('it', 'it.js', 0, 'Lingua del sito sconosciuta. Indicare una lingua, per favore:');
o('kn', 'kn.js', 8, 'ಜಾಲ ತಾಣದ ಭಾಷೆಯನ್ನು ನಿರ್ಧರಿಸಲು ಸಾಧ್ಯವಾಗುತ್ತಿಲ್ಲ. ದಯವಿಟ್ಟು ಮುಖ್ಯ ಭಾಷೆಯನ್ನು ಸೂಚಿಸಿ:');
o('la', 'la.js', 0, '');
o('lt', 'lt.js', 0, 'Nepavyko automatiškai nustatyti šios svetainės kalbos. Prašome įvesti kalbą:');
o('lv', 'lv.js', 0, 'Šīs lapas valodu nevarēja noteikt automātiski. Lūdzu norādiet pamata valodu:');
o('ml', 'ml.js', 10, 'ഈ വെ%u0D2C%u0D4D%u200Cസൈറ്റിന്റെ ഭാഷ കണ്ടുപിടിയ്ക്കാ%u0D28%u0D4D%u200D കഴിഞ്ഞില്ല. ഭാഷ ഏതാണെന്നു തിരഞ്ഞെടുക്കുക:');
o('nb', 'nb-no.js', 0, 'Nettstedets språk kunne ikke finnes automatisk. Vennligst oppgi språk:');
o('no', 'nb-no.js', 0, 'Nettstedets språk kunne ikke finnes automatisk. Vennligst oppgi språk:');
o('nb-no', 'nb-no.js', 0, 'Nettstedets språk kunne ikke finnes automatisk. Vennligst oppgi språk:');
o('nl', 'nl.js', 0, 'De taal van deze website kan niet automatisch worden bepaald. Geef de hoofdtaal op:');
o('or', 'or.js', 11, '');
o('pa', 'pa.js', 13, '');
o('pl', 'pl.js', 0, 'Języka tej strony nie można ustalić automatycznie. Proszę wskazać język:');
o('pt', 'pt.js', 0, 'A língua deste site não pôde ser determinada automaticamente. Por favor indique a língua principal:');
o('ru', 'ru.js', 1, 'Язык этого сайта не может быть определен автоматически. Пожалуйста укажите язык:');
o('sk', 'sk.js', 0, '');
o('sl', 'sl.js', 0, 'Jezika te spletne strani ni bilo mogoče samodejno določiti. Prosim navedite jezik:');
o('sr-latn', 'sr-latn.js', 0, 'Jezika te spletne strani ni bilo mogoče samodejno določiti. Prosim navedite jezik:');
o('sv', 'sv.js', 0, 'Spr%E5ket p%E5 den h%E4r webbplatsen kunde inte avg%F6ras automatiskt. V%E4nligen ange:');
o('ta', 'ta.js', 14, '');
o('te', 'te.js', 15, '');
o('tr', 'tr.js', 0, 'Bu web sitesinin dili otomatik olarak tespit edilememiştir. Lütfen dökümanın dilini seçiniz%A0:');
o('uk', 'uk.js', 1, 'Мова цього веб-сайту не може бути визначена автоматично. Будь ласка, вкажіть головну мову:');
o('ro', 'ro.js', 0, 'Limba acestui sit nu a putut fi determinată automat. Alege limba principală:');
return r;
}()),
/**
* @name Hyphenator-basePath
* @description
* A string storing the basepath from where Hyphenator.js was loaded.
* This is used to load the patternfiles.
* The basepath is determined dynamically by searching all script-tags for Hyphenator.js
* If the path cannot be determined http://hyphenator.googlecode.com/svn/trunk/ is used as fallback.
* @type {string}
* @private
* @see Hyphenator-loadPatterns
*/
basePath = (function () {
var s = contextWindow.document.getElementsByTagName('script'), i = 0, p, src, t = s[i], r = '';
while (!!t) {
if (!!t.src) {
src = t.src;
p = src.indexOf('Hyphenator.js');
if (p !== -1) {
r = src.substring(0, p);
}
}
i += 1;
t = s[i];
}
return !!r ? r : 'http://hyphenator.googlecode.com/svn/trunk/';
}()),
/**
* @name Hyphenator-isLocal
* @private
* @description
* isLocal is true, if Hyphenator is loaded from the same domain, as the webpage, but false, if
* it's loaded from an external source (i.e. directly from google.code)
*/
isLocal = (function () {
var re = false;
if (window.location.href.indexOf(basePath) !== -1) {
re = true;
}
return re;
}()),
/**
* @name Hyphenator-documentLoaded
* @private
* @description
* documentLoaded is true, when the DOM has been loaded. This is set by runOnContentLoaded
*/
documentLoaded = false,
/**
* @name Hyphenator-persistentConfig
* @private
* @description
* if persistentConfig is set to true (defaults to false), config options and the state of the
* toggleBox are stored in DOM-storage (according to the storage-setting). So they haven't to be
* set for each page.
*/
persistentConfig = false,
/**
* @name Hyphenator-doFrames
* @private
* @description
* switch to control if frames/iframes should be hyphenated, too
* defaults to false (frames are a bag of hurt!)
*/
doFrames = false,
/**
* @name Hyphenator-dontHyphenate
* @description
* A key-value object containing all html-tags whose content should not be hyphenated
* @type {Object.<string,boolean>}
* @private
* @see Hyphenator-hyphenateElement
*/
dontHyphenate = {'script': true, 'code': true, 'pre': true, 'img': true, 'br': true, 'samp': true, 'kbd': true, 'var': true, 'abbr': true, 'acronym': true, 'sub': true, 'sup': true, 'button': true, 'option': true, 'label': true, 'textarea': true, 'input': true, 'math': true, 'svg': true, 'style': true},
/**
* @name Hyphenator-enableCache
* @description
* A variable to set if caching is enabled or not
* @type boolean
* @default true
* @private
* @see Hyphenator.config
* @see hyphenateWord
*/
enableCache = true,
/**
* @name Hyphenator-storageType
* @description
* A variable to define what html5-DOM-Storage-Method is used ('none', 'local' or 'session')
* @type {string}
* @default 'local'
* @private
* @see Hyphenator.config
*/
storageType = 'local',
/**
* @name Hyphenator-storage
* @description
* An alias to the storage-Method defined in storageType.
* Set by Hyphenator.run()
* @type {Object|undefined}
* @default null
* @private
* @see Hyphenator.run
*/
storage,
/**
* @name Hyphenator-enableReducedPatternSet
* @description
* A variable to set if storing the used patterns is set
* @type boolean
* @default false
* @private
* @see Hyphenator.config
* @see hyphenateWord
* @see Hyphenator.getRedPatternSet
*/
enableReducedPatternSet = false,
/**
* @name Hyphenator-enableRemoteLoading
* @description
* A variable to set if pattern files should be loaded remotely or not
* @type boolean
* @default true
* @private
* @see Hyphenator.config
* @see Hyphenator-loadPatterns
*/
enableRemoteLoading = true,
/**
* @name Hyphenator-displayToggleBox
* @description
* A variable to set if the togglebox should be displayed or not
* @type boolean
* @default false
* @private
* @see Hyphenator.config
* @see Hyphenator-toggleBox
*/
displayToggleBox = false,
/**
* @name Hyphenator-onError
* @description
* A function that can be called upon an error.
* @see Hyphenator.config
* @type {function(Object)}
* @private
*/
onError = function (e) {
window.alert("Hyphenator.js says:\n\nAn Error occurred:\n" + e.message);
},
/**
* @name Hyphenator-createElem
* @description
* A function alias to document.createElementNS or document.createElement
* @type {function(string, Object)}
* @private
*/
createElem = function (tagname, context) {
context = context || contextWindow;
var el;
if (window.document.createElementNS) {
el = context.document.createElementNS('http://www.w3.org/1999/xhtml', tagname);
} else if (window.document.createElement) {
el = context.document.createElement(tagname);
}
return el;
},
/**
* @name Hyphenator-css3
* @description
* A variable to set if css3 hyphenation should be used
* @type boolean
* @default false
* @private
* @see Hyphenator.config
*/
css3 = false,
/**
* @name Hyphenator-css3_hsupport
* @description
* A generated object containing information for CSS3-hyphenation support
* {
* support: boolean,
* property: <the property name to access hyphen-settings>,
* languages: <an object containing supported languages>
* }
* @type object
* @default undefined
* @private
* @see Hyphenator-css3_gethsupport
*/
css3_h9n,
/**
* @name Hyphenator-css3_gethsupport
* @description
* This function sets Hyphenator-css3_h9n for the current UA
* @type function
* @private
* @see Hyphenator-css3_h9n
*/
css3_gethsupport = function () {
var s,
createLangSupportChecker = function (prefix) {
var testStrings = [
//latin: 0
'aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz',
//cyrillic: 1
'абвгдеёжзийклмнопрстуфхцчшщъыьэюя',
//arabic: 2
'أبتثجحخدذرزسشصضطظعغفقكلمنهوي',
//armenian: 3
'աբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆ',
//bengali: 4
'ঁংঃঅআইঈউঊঋঌএঐওঔকখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহ়ঽািীুূৃৄেৈোৌ্ৎৗড়ঢ়য়ৠৡৢৣ',
//devangari: 5
'ँंःअआइईउऊऋऌएऐओऔकखगघङचछजझञटठडढणतथदधनपफबभमयरलळवशषसहऽािीुूृॄेैोौ्॒॑ॠॡॢॣ',
//greek: 6
'αβγδεζηθικλμνξοπρσςτυφχψω',
//gujarati: 7
'બહઅઆઇઈઉઊઋૠએઐઓઔાિીુૂૃૄૢૣેૈોૌકખગઘઙચછજઝઞટઠડઢણતથદધનપફસભમયરલળવશષ',
//kannada: 8
'ಂಃಅಆಇಈಉಊಋಌಎಏಐಒಓಔಕಖಗಘಙಚಛಜಝಞಟಠಡಢಣತಥದಧನಪಫಬಭಮಯರಱಲಳವಶಷಸಹಽಾಿೀುೂೃೄೆೇೈೊೋೌ್ೕೖೞೠೡ',
//lao: 9
'ກຂຄງຈຊຍດຕຖທນບປຜຝພຟມຢຣລວສຫອຮະັາິີຶືຸູົຼເແໂໃໄ່້໊໋ໜໝ',
//malayalam: 10
'ംഃഅആഇഈഉഊഋഌഎഏഐഒഓഔകഖഗഘങചഛജഝഞടഠഡഢണതഥദധനപഫബഭമയരറലളഴവശഷസഹാിീുൂൃെേൈൊോൌ്ൗൠൡൺൻർൽൾൿ',
//oriya: 11
'ଁଂଃଅଆଇଈଉଊଋଌଏଐଓଔକଖଗଘଙଚଛଜଝଞଟଠଡଢଣତଥଦଧନପଫବଭମଯରଲଳଵଶଷସହାିୀୁୂୃେୈୋୌ୍ୗୠୡ',
//persian: 12
'أبتثجحخدذرزسشصضطظعغفقكلمنهوي',
//punjabi: 13
'ਁਂਃਅਆਇਈਉਊਏਐਓਔਕਖਗਘਙਚਛਜਝਞਟਠਡਢਣਤਥਦਧਨਪਫਬਭਮਯਰਲਲ਼ਵਸ਼ਸਹਾਿੀੁੂੇੈੋੌ੍ੰੱ',
//tamil: 14
'ஃஅஆஇஈஉஊஎஏஐஒஓஔகஙசஜஞடணதநனபமயரறலளழவஷஸஹாிீுூெேைொோௌ்ௗ',
//telugu: 15
'ఁంఃఅఆఇఈఉఊఋఌఎఏఐఒఓఔకఖగఘఙచఛజఝఞటఠడఢణతథదధనపఫబభమయరఱలళవశషసహాిీుూృౄెేైొోౌ్ౕౖౠౡ'
],
f = function (lang) {
var shadow,
computedHeight,
bdy = window.document.getElementsByTagName('body')[0],
r = false;
if (supportedLangs.hasOwnProperty(lang)) {
//create and append shadow-test-element
shadow = createElem('div', window);
shadow.id = 'Hyphenator_LanguageChecker';
shadow.style.width = '5em';
shadow.style[prefix] = 'auto';
shadow.style.hyphens = 'auto';
shadow.style.fontSize = '12px';
shadow.style.lineHeight = '12px';
shadow.style.visibility = 'hidden';
shadow.lang = lang;
shadow.style['-webkit-locale'] = "'" + lang + "'";
shadow.innerHTML = testStrings[supportedLangs[lang].script];
bdy.appendChild(shadow);
//measure its height
computedHeight = shadow.offsetHeight;
//remove shadow element
bdy.removeChild(shadow);
r = (computedHeight > 12) ? true : false;
} else {
r = false;
}
return r;
};
return f;
},
r = {
support: false,
property: '',
checkLangSupport: function () {}
};
if (window.getComputedStyle) {
s = contextWindow.getComputedStyle(contextWindow.document.getElementsByTagName('body')[0], null);
} else {
//ancient Browsers don't support CSS3 anyway
css3_h9n = r;
return;
}
if (s['-webkit-hyphens'] !== undefined) {
r.support = true;
r.property = '-webkit-hyphens';
r.checkLangSupport = createLangSupportChecker('-webkit-hyphens');
} else if (s.MozHyphens !== undefined) {
r.support = true;
r.property = '-moz-hyphens';
r.checkLangSupport = createLangSupportChecker('MozHyphens');
} else if (s['-ms-hyphens'] !== undefined) {
r.support = true;
r.property = '-ms-hyphens';
r.checkLangSupport = createLangSupportChecker('-ms-hyphens');
}
css3_h9n = r;
},
/**
* @name Hyphenator-hyphenateClass
* @description
* A string containing the css-class-name for the hyphenate class
* @type {string}
* @default 'hyphenate'
* @private
* @example
* <p class = "hyphenate">Text</p>
* @see Hyphenator.config
*/
hyphenateClass = 'hyphenate',
/**
* @name Hyphenator-classPrefix
* @description
* A string containing a unique className prefix to be used
* whenever Hyphenator sets a CSS-class
* @type {string}
* @private
*/
classPrefix = 'Hyphenator' + Math.round(Math.random() * 1000),
/**
* @name Hyphenator-hideClass
* @description
* The name of the class that hides elements
* @type {string}
* @private
*/
hideClass = classPrefix + 'hide',
/**
* @name Hyphenator-hideClassRegExp
* @description
* RegExp to remove hideClass from a list of classes
* @type {RegExp}
* @private
*/
hideClassRegExp = new RegExp("\\s?\\b" + hideClass + "\\b", "g"),
/**
* @name Hyphenator-hideClass
* @description
* The name of the class that unhides elements
* @type {string}
* @private
*/
unhideClass = classPrefix + 'unhide',
/**
* @name Hyphenator-hideClassRegExp
* @description
* RegExp to remove unhideClass from a list of classes
* @type {RegExp}
* @private
*/
unhideClassRegExp = new RegExp("\\s?\\b" + unhideClass + "\\b", "g"),
/**
* @name Hyphenator-css3hyphenateClass
* @description
* The name of the class that hyphenates elements with css3
* @type {string}
* @private
*/
css3hyphenateClass = classPrefix + 'css3hyphenate',
/**
* @name Hyphenator-css3hyphenateClass
* @description
* The var where CSSEdit class is stored
* @type {Object}
* @private
*/
css3hyphenateClassHandle,
/**
* @name Hyphenator-dontHyphenateClass
* @description
* A string containing the css-class-name for elements that should not be hyphenated
* @type {string}
* @default 'donthyphenate'
* @private
* @example
* <p class = "donthyphenate">Text</p>
* @see Hyphenator.config
*/
dontHyphenateClass = 'donthyphenate',
/**
* @name Hyphenator-min
* @description
* A number wich indicates the minimal length of words to hyphenate.
* @type {number}
* @default 6
* @private
* @see Hyphenator.config
*/
min = 6,
/**
* @name Hyphenator-orphanControl
* @description
* Control how the last words of a line are handled:
* level 1 (default): last word is hyphenated
* level 2: last word is not hyphenated
* level 3: last word is not hyphenated and last space is non breaking
* @type {number}
* @default 1
* @private
*/
orphanControl = 1,
/**
* @name Hyphenator-isBookmarklet
* @description
* Indicates if Hyphanetor runs as bookmarklet or not.
* @type boolean
* @default false
* @private
*/
isBookmarklet = (function () {
var loc = null,
re = false,
scripts = contextWindow.document.getElementsByTagName('script'),
i = 0,
l = scripts.length;
while (!re && i < l) {
loc = scripts[i].getAttribute('src');
if (!!loc && loc.indexOf('Hyphenator.js?bm=true') !== -1) {
re = true;
}
i += 1;
}
return re;
}()),
/**
* @name Hyphenator-mainLanguage
* @description
* The general language of the document. In contrast to {@link Hyphenator-defaultLanguage},
* mainLanguage is defined by the client (i.e. by the html or by a prompt).
* @type {string|null}
* @private
* @see Hyphenator-autoSetMainLanguage
*/
mainLanguage = null,
/**
* @name Hyphenator-defaultLanguage
* @description
* The language defined by the developper. This language setting is defined by a config option.
* It is overwritten by any html-lang-attribute and only taken in count, when no such attribute can
* be found (i.e. just before the prompt).
* @type {string|null}
* @private
* @see Hyphenator-autoSetMainLanguage
*/
defaultLanguage = '',
/**
* @name Hyphenator-elements
* @description
* An object holding all elements that have to be hyphenated. This var is filled by
* {@link Hyphenator-gatherDocumentInfos}
* @type {Array}
* @private
*/
elements = (function () {
var Element = function (element) {
this.element = element;
this.hyphenated = false;
this.treated = false; //collected but not hyphenated (dohyphenation is off)
},
ElementCollection = function () {
this.count = 0;
this.hyCount = 0;
this.list = {};
};
ElementCollection.prototype = {
add: function (el, lang) {
if (!this.list.hasOwnProperty(lang)) {
this.list[lang] = [];
}
this.list[lang].push(new Element(el));
this.count += 1;
},
each: function (fn) {
var k;
for (k in this.list) {
if (this.list.hasOwnProperty(k)) {
if (fn.length === 2) {
fn(k, this.list[k]);
} else {
fn(this.list[k]);
}
}
}
}
};
return new ElementCollection();
}()),
/**
* @name Hyphenator-exceptions
* @description
* An object containing exceptions as comma separated strings for each language.
* When the language-objects are loaded, their exceptions are processed, copied here and then deleted.
* @see Hyphenator-prepareLanguagesObj
* @type {Object}
* @private
*/
exceptions = {},
/**
* @name Hyphenator-docLanguages
* @description
* An object holding all languages used in the document. This is filled by
* {@link Hyphenator-gatherDocumentInfos}
* @type {Object}
* @private
*/
docLanguages = {},
/**
* @name Hyphenator-state
* @description
* A number that inidcates the current state of the script
* 0: not initialized
* 1: loading patterns
* 2: ready
* 3: hyphenation done
* 4: hyphenation removed
* @type {number}
* @private
*/
state = 0,
/**
* @name Hyphenator-url
* @description
* A string containing a RegularExpression to match URL's
* @type {string}
* @private
*/
url = '(\\w*:\/\/)?((\\w*:)?(\\w*)@)?((([\\d]{1,3}\\.){3}([\\d]{1,3}))|((www\\.|[a-zA-Z]\\.)?[a-zA-Z0-9\\-\\.]+\\.([a-z]{2,4})))(:\\d*)?(\/[\\w#!:\\.?\\+=&%@!\\-]*)*',
// protocoll usr pwd ip or host tld port path
/**
* @name Hyphenator-mail
* @description
* A string containing a RegularExpression to match mail-adresses
* @type {string}
* @private
*/
mail = '[\\w-\\.]+@[\\w\\.]+',
/**
* @name Hyphenator-urlRE
* @description
* A RegularExpressions-Object for url- and mail adress matching
* @type {RegExp}
* @private
*/
urlOrMailRE = new RegExp('(' + url + ')|(' + mail + ')', 'i'),
/**
* @name Hyphenator-zeroWidthSpace
* @description
* A string that holds a char.
* Depending on the browser, this is the zero with space or an empty string.
* zeroWidthSpace is used to break URLs
* @type {string}
* @private
*/
zeroWidthSpace = (function () {
var zws, ua = window.navigator.userAgent.toLowerCase();
zws = String.fromCharCode(8203); //Unicode zero width space
if (ua.indexOf('msie 6') !== -1) {
zws = ''; //IE6 doesn't support zws
}
if (ua.indexOf('opera') !== -1 && ua.indexOf('version/10.00') !== -1) {
zws = ''; //opera 10 on XP doesn't support zws
}
return zws;
}()),
/**
* @name Hyphenator-onBeforeWordHyphenation
* @description
* A method to be called for each word to be hyphenated before it is hyphenated.
* Takes the word as a first parameter and its language as a second parameter.
* Returns a string that will replace the word to be hyphenated.
* @see Hyphenator.config
* @type {function()}
* @private
*/
onBeforeWordHyphenation = function (word) {
return word;
},
/**
* @name Hyphenator-onAfterWordHyphenation
* @description
* A method to be called for each word to be hyphenated after it is hyphenated.
* Takes the word as a first parameter and its language as a second parameter.
* Returns a string that will replace the word that has been hyphenated.
* @see Hyphenator.config
* @type {function()}
* @private
*/
onAfterWordHyphenation = function (word) {
return word;
},
/**
* @name Hyphenator-onHyphenationDone
* @description
* A method to be called, when the last element has been hyphenated
* @see Hyphenator.config
* @type {function()}
* @private
*/
onHyphenationDone = function () {},
/**
* @name Hyphenator-selectorFunction
* @description
* A function set by the user that has to return a HTMLNodeList or array of Elements to be hyphenated.
* By default this is set to false so we can check if a selectorFunction is set…
* @see Hyphenator.config
* @type {function()}
* @private
*/
selectorFunction = false,
/**
* @name Hyphenator-mySelectorFunction
* @description
* A function that has to return a HTMLNodeList or array of Elements to be hyphenated.
* By default it uses the classname ('hyphenate') to select the elements.
* @type {function()}
* @private
*/
mySelectorFunction = function (hyphenateClass) {
var tmp, el = [], i, l;
if (window.document.getElementsByClassName) {
el = contextWindow.document.getElementsByClassName(hyphenateClass);
} else if (window.document.querySelectorAll) {
el = contextWindow.document.querySelectorAll('.' + hyphenateClass);
} else {
tmp = contextWindow.document.getElementsByTagName('*');
l = tmp.length;
for (i = 0; i < l; i += 1) {
if (tmp[i].className.indexOf(hyphenateClass) !== -1 && tmp[i].className.indexOf(dontHyphenateClass) === -1) {
el.push(tmp[i]);
}
}
}
return el;
},
/**
* @name Hyphenator-selectElements
* @description
* A function that has to return a HTMLNodeList or array of Elements to be hyphenated.
* It uses either selectorFunction set by the user (and adds a unique class to each element)
* or the default mySelectorFunction.
* @type {function()}
* @private
*/
selectElements = function () {
var elements;
if (selectorFunction) {
elements = selectorFunction();
} else {
elements = mySelectorFunction(hyphenateClass);
}
return elements;
},
/**
* @name Hyphenator-intermediateState
* @description
* The value of style.visibility of the text while it is hyphenated.
* @see Hyphenator.config
* @type {string}
* @private
*/
intermediateState = 'hidden',
/**
* @name Hyphenator-unhide
* @description
* How hidden elements unhide: either simultaneous (default: 'wait') or progressively.
* 'wait' makes Hyphenator.js to wait until all elements are hyphenated (one redraw)
* With 'progressive' Hyphenator.js unhides elements as soon as they are hyphenated.
* @see Hyphenator.config
* @type {string}
* @private
*/
unhide = 'wait',
/**
* @name Hyphenator-CSSEditors
* @description A container array that holds CSSEdit classes
* For each window object one CSSEdit class is inserted
* @see Hyphenator-CSSEdit
* @type {array}
* @private
*/
CSSEditors = [],
/**
* @name Hyphenator-CSSEditors
* @description A custom class with two public methods: setRule() and clearChanges()
* Rather sets style for CSS-classes then for single elements
* This is used to hide/unhide elements when they are hyphenated.
* @see Hyphenator-gatherDocumentInfos
* @type {function ()}
* @private
*/
CSSEdit = function (w) {
w = w || window;
var doc = w.document,
//find/create an accessible StyleSheet
sheet = (function () {
var i,
l = doc.styleSheets.length,
sheet,
element,
r = false;
for (i = 0; i < l; i += 1) {
sheet = doc.styleSheets[i];
try {
if (!!sheet.cssRules) {
r = sheet;
break;
}
} catch (e) {}
}
if (r === false) {
element = doc.createElement('style');
element.type = 'text/css';
doc.getElementsByTagName('head')[0].appendChild(element);
r = doc.styleSheets[doc.styleSheets.length - 1];
}
return r;
}()),
changes = [],
findRule = function (sel) {
var sheet, rule, sheets = w.document.styleSheets, rules, i, j, r = false;
for (i = 0; i < sheets.length; i += 1) {
sheet = sheets[i];
try { //FF has issues here with external CSS (s.o.p)
if (!!sheet.cssRules) {
rules = sheet.cssRules;
} else if (!!sheet.rules) {
// IE < 9
rules = sheet.rules;
}
} catch (e) {
//do nothing
//console.log(e);
}
if (!!rules && !!rules.length) {
for (j = 0; j < rules.length; j += 1) {
rule = rules[j];
if (rule.selectorText === sel) {
r = {
index: j,
rule: rule
};
}
}
}
}
return r;
},
addRule = function (sel, rulesStr) {
var i, r;
if (!!sheet.insertRule) {
if (!!sheet.cssRules) {
i = sheet.cssRules.length;
} else {
i = 0;
}
r = sheet.insertRule(sel + '{' + rulesStr + '}', i);
} else if (!!sheet.addRule) {
// IE < 9
if (!!sheet.rules) {
i = sheet.rules.length;
} else {
i = 0;
}
sheet.addRule(sel, rulesStr, i);
r = i;
}
return r;
},
removeRule = function (sheet, index) {
if (sheet.deleteRule) {
sheet.deleteRule(index);
} else {
// IE < 9
sheet.removeRule(index);
}
};
return {
setRule: function (sel, rulesString) {
var i, existingRule, cssText;
existingRule = findRule(sel);
if (!!existingRule) {
if (!!existingRule.rule.cssText) {
cssText = existingRule.rule.cssText;
} else {
// IE < 9
cssText = existingRule.rule.style.cssText.toLowerCase();
}
if (cssText === '.' + hyphenateClass + ' { visibility: hidden; }') {
//browsers w/o IE < 9 and no additional style defs:
//add to [changes] for later removal
changes.push({sheet: existingRule.rule.parentStyleSheet, index: existingRule.index});
} else if (cssText.indexOf('visibility: hidden') !== -1) {
// IE < 9 or additional style defs:
// add new rule
i = addRule(sel, rulesString);
//add to [changes] for later removal
changes.push({sheet: sheet, index: i});
// clear existing def
existingRule.rule.style.visibility = '';
} else {
addRule(sel, rulesString);
}
} else {
i = addRule(sel, rulesString);
changes.push({sheet: sheet, index: i});
}
},
clearChanges: function () {
var change = changes.pop();
while (!!change) {
removeRule(change.sheet, change.index);
change = changes.pop();
}
}
};
},
/**
* @name Hyphenator-hyphen
* @description
* A string containing the character for in-word-hyphenation
* @type {string}
* @default the soft hyphen
* @private
* @see Hyphenator.config
*/
hyphen = String.fromCharCode(173),
/**
* @name Hyphenator-urlhyphen
* @description
* A string containing the character for url/mail-hyphenation
* @type {string}
* @default the zero width space
* @private
* @see Hyphenator.config
* @see Hyphenator-zeroWidthSpace
*/
urlhyphen = zeroWidthSpace,
/**
* @name Hyphenator-safeCopy
* @description
* Defines wether work-around for copy issues is active or not
* Not supported by Opera (no onCopy handler)
* @type boolean
* @default true
* @private
* @see Hyphenator.config
* @see Hyphenator-registerOnCopy
*/
safeCopy = true,
/*
* runWhenLoaded is based od jQuery.bindReady()
* see
* jQuery JavaScript Library v1.3.2
* http://jquery.com/
*
* Copyright (c) 2009 John Resig
* Dual licensed under the MIT and GPL licenses.
* http://docs.jquery.com/License
*
* Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
* Revision: 6246
*/
/**
* @name Hyphenator-runWhenLoaded
* @description
* A crossbrowser solution for the DOMContentLoaded-Event based on jQuery
* <a href = "http://jquery.com/</a>
* I added some functionality: e.g. support for frames and iframes…
* @param {Object} w the window-object
* @param {function()} f the function to call onDOMContentLoaded
* @private
*/
runWhenLoaded = function (w, f) {
var
toplevel, hyphRunForThis = {},
add = window.document.addEventListener ? 'addEventListener' : 'attachEvent',
rem = window.document.addEventListener ? 'removeEventListener' : 'detachEvent',
pre = window.document.addEventListener ? '' : 'on',
init = function (context) {
if (!hyphRunForThis[context.location.href]) {
contextWindow = context || window;
f();
hyphRunForThis[contextWindow.location.href] = true;
}
},
doScrollCheck = function () {
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
w.document.documentElement.doScroll("left");
} catch (error) {
window.setTimeout(doScrollCheck, 1);
return;
}
// and execute any waiting functions
documentLoaded = true;
init(w);
},
doOnEvent = function (e) {
var i, fl, haveAccess;
if (!!e && e.type === 'readystatechange' && w.document.readyState !== 'interactive' && w.document.readyState !== 'complete') {
return;
}
//DOM is ready/interactive, but frames may not be loaded yet!
//cleanup events
w.document[rem](pre + 'DOMContentLoaded', doOnEvent, false);
w.document[rem](pre + 'readystatechange', doOnEvent, false);
//check frames
fl = w.frames.length;
if (fl === 0) {
//there are no frames!
//cleanup events
w[rem](pre + 'load', doOnEvent, false);
documentLoaded = true;
} else if (doFrames && fl > 0) {
//we have frames, so wait for onload and then initiate runWhenLoaded recursevly for each frame:
if (!!e && e.type === 'load') {
//cleanup events
w[rem](pre + 'load', doOnEvent, false);
for (i = 0; i < fl; i += 1) {
haveAccess = undefined;
//try catch isn't enough for webkit
try {
//opera throws only on document.toString-access
haveAccess = window.frames[i].document.toString();
} catch (err) {
haveAccess = undefined;
}
if (!!haveAccess) {
runWhenLoaded(w.frames[i], f);
}
}
}
}
init(w);
};
if (documentLoaded || w.document.readyState === 'complete') {
//Hyphenator has run already (documentLoaded is true) or
//it has been loaded after onLoad
documentLoaded = true;
doOnEvent({type: 'load'});
} else {
//register events
w.document[add](pre + 'DOMContentLoaded', doOnEvent, false);
w.document[add](pre + 'readystatechange', doOnEvent, false);
w[add](pre + 'load', doOnEvent, false);
toplevel = false;
try {
toplevel = !window.frameElement;
} catch (e) {}
if (toplevel && w.document.documentElement.doScroll) {
doScrollCheck(); //calls init()
}
}
},
/**
* @name Hyphenator-getLang
* @description
* Gets the language of an element. If no language is set, it may use the {@link Hyphenator-mainLanguage}.
* @param {Object} el The first parameter is an DOM-Element-Object
* @param {boolean} fallback The second parameter is a boolean to tell if the function should return the {@link Hyphenator-mainLanguage}
* if there's no language found for the element.
* @private
*/
getLang = function (el, fallback) {
try {
return !!el.getAttribute('lang') ? el.getAttribute('lang').toLowerCase() :
!!el.getAttribute('xml:lang') ? el.getAttribute('xml:lang').toLowerCase() :
el.tagName.toLowerCase() !== 'html' ? getLang(el.parentNode, fallback) :
fallback ? mainLanguage :
null;
} catch (e) {}
},
/**
* @name Hyphenator-autoSetMainLanguage
* @description
* Retrieves the language of the document from the DOM.
* The function looks in the following places:
* <ul>
* <li>lang-attribute in the html-tag</li>
* <li><meta http-equiv = "content-language" content = "xy" /></li>
* <li><meta name = "DC.Language" content = "xy" /></li>
* <li><meta name = "language" content = "xy" /></li>
* </li>
* If nothing can be found a prompt using {@link Hyphenator-languageHint} and a prompt-string is displayed.
* If the retrieved language is in the object {@link Hyphenator-supportedLangs} it is copied to {@link Hyphenator-mainLanguage}
* @private
*/
autoSetMainLanguage = function (w) {
w = w || contextWindow;
var el = w.document.getElementsByTagName('html')[0],
m = w.document.getElementsByTagName('meta'),
i,
getLangFromUser = function () {
var mainLanguage,
text = '',
dH = 300,
dW = 450,
dX = Math.floor((w.outerWidth - dW) / 2) + window.screenX,
dY = Math.floor((w.outerHeight - dH) / 2) + window.screenY,
ul = '',
languageHint;
if (!!window.showModalDialog) {
mainLanguage = window.showModalDialog(basePath + 'modalLangDialog.html', supportedLangs, "dialogWidth: " + dW + "px; dialogHeight: " + dH + "px; dialogtop: " + dY + "; dialogleft: " + dX + "; center: on; resizable: off; scroll: off;");
} else {
languageHint = (function () {
var k, r = '';
for (k in supportedLangs) {
if (supportedLangs.hasOwnProperty(k)) {
r += k + ', ';
}
}
r = r.substring(0, r.length - 2);
return r;
}());
ul = window.navigator.language || window.navigator.userLanguage;
ul = ul.substring(0, 2);
if (!!supportedLangs[ul] && supportedLangs[ul].prompt !== '') {
text = supportedLangs[ul].prompt;
} else {
text = supportedLangs.en.prompt;
}
text += ' (ISO 639-1)\n\n' + languageHint;
mainLanguage = window.prompt(window.unescape(text), ul).toLowerCase();
}
return mainLanguage;
};
mainLanguage = getLang(el, false);
if (!mainLanguage) {
for (i = 0; i < m.length; i += 1) {
//<meta http-equiv = "content-language" content="xy">
if (!!m[i].getAttribute('http-equiv') && (m[i].getAttribute('http-equiv').toLowerCase() === 'content-language')) {
mainLanguage = m[i].getAttribute('content').toLowerCase();
}
//<meta name = "DC.Language" content="xy">
if (!!m[i].getAttribute('name') && (m[i].getAttribute('name').toLowerCase() === 'dc.language')) {
mainLanguage = m[i].getAttribute('content').toLowerCase();
}
//<meta name = "language" content = "xy">
if (!!m[i].getAttribute('name') && (m[i].getAttribute('name').toLowerCase() === 'language')) {
mainLanguage = m[i].getAttribute('content').toLowerCase();
}
}
}
//get lang for frame from enclosing document
if (!mainLanguage && doFrames && (!!contextWindow.frameElement)) {
autoSetMainLanguage(window.parent);
}
//fallback to defaultLang if set
if (!mainLanguage && defaultLanguage !== '') {
mainLanguage = defaultLanguage;
}
//ask user for lang
if (!mainLanguage) {
mainLanguage = getLangFromUser();
}
el.lang = mainLanguage;
},
/**
* @name Hyphenator-gatherDocumentInfos
* @description
* This method runs through the DOM and executes the process()-function on:
* - every node returned by the {@link Hyphenator-selectorFunction}.
* The process()-function copies the element to the elements-variable, sets its visibility
* to intermediateState, retrieves its language and recursivly descends the DOM-tree until
* the child-Nodes aren't of type 1
* @private
*/
gatherDocumentInfos = function () {
var elToProcess, tmp, i = 0,
process = function (el, lang) {
var n, i = 0, hyphenate = true;
if (el.lang && typeof (el.lang) === 'string') {
lang = el.lang.toLowerCase(); //copy attribute-lang to internal lang
} else if (lang) {
lang = lang.toLowerCase();
} else {
lang = getLang(el, true);
}
//if css3-hyphenation is supported: use it!
if (css3 && css3_h9n.support && !!css3_h9n.checkLangSupport(lang)) {
css3hyphenateClassHandle = new CSSEdit(contextWindow);
css3hyphenateClassHandle.setRule('.' + css3hyphenateClass, css3_h9n.property + ': auto;');
css3hyphenateClassHandle.setRule('.' + dontHyphenateClass, css3_h9n.property + ': none;');
css3hyphenateClassHandle.setRule('.' + css3hyphenateClass, '-webkit-locale : ' + lang + ';');
el.className = el.className + ' ' + css3hyphenateClass;
} else {
if (supportedLangs.hasOwnProperty(lang)) {
docLanguages[lang] = true;
} else {
if (supportedLangs.hasOwnProperty(lang.split('-')[0])) { //try subtag
lang = lang.split('-')[0];
docLanguages[lang] = true;
} else if (!isBookmarklet) {
hyphenate = false;
onError(new Error('Language "' + lang + '" is not yet supported.'));
}
}
if (hyphenate) {
if (intermediateState === 'hidden') {
el.className = el.className + ' ' + hideClass;
}
elements.add(el, lang);
}
}
n = el.childNodes[i];
while (!!n) {
if (n.nodeType === 1 && !dontHyphenate[n.nodeName.toLowerCase()] &&
n.className.indexOf(dontHyphenateClass) === -1 && !elToProcess[n]) {
process(n, lang);
}
i += 1;
n = el.childNodes[i];
}
};
if (css3) {
css3_gethsupport();
}
if (isBookmarklet) {
elToProcess = contextWindow.document.getElementsByTagName('body')[0];
process(elToProcess, mainLanguage);
} else {
if (!css3 && intermediateState === 'hidden') {
CSSEditors.push(new CSSEdit(contextWindow));
CSSEditors[CSSEditors.length - 1].setRule('.' + hyphenateClass, 'visibility: hidden;');
CSSEditors[CSSEditors.length - 1].setRule('.' + hideClass, 'visibility: hidden;');
CSSEditors[CSSEditors.length - 1].setRule('.' + unhideClass, 'visibility: visible;');
}
elToProcess = selectElements();
tmp = elToProcess[i];
while (!!tmp) {
process(tmp, '');
i += 1;
tmp = elToProcess[i];
}
}
if (elements.count === 0) {
//nothing to hyphenate or all hyphenated by css3
for (i = 0; i < CSSEditors.length; i += 1) {
CSSEditors[i].clearChanges();
}
state = 3;
onHyphenationDone();
}
},
/**
* @name Hyphenator-createTrie
* @description
* converts patterns of the given language in a trie
* @private
* @param {string} lang the language whose patterns shall be converted
*/
convertPatterns = function (lang) {
/** @license BSD licenced code
* The following code is based on code from hypher.js and adapted for Hyphenator.js
* Copyright (c) 2011, Bram Stein
*/
var size = 0,
tree = {
tpoints: []
},
patterns,
pattern,
i,
j,
k,
patternObject = Hyphenator.languages[lang].patterns,
c,
chars,
points,
t,
p,
codePoint,
test = 'in3se',
rf,
getPoints = (function () {
//IE<9 doesn't act like other browsers: doesn't preserve the separators
if (test.split(/\D/).length === 1) {
rf = function (pattern) {
pattern = pattern.replace(/\D/gi, ' ');
return pattern.split(' ');
};
} else {
rf = function (pattern) {
return pattern.split(/\D/);
};
}
return rf;
}());
for (size in patternObject) {
if (patternObject.hasOwnProperty(size)) {
patterns = patternObject[size].match(new RegExp('.{1,' + (+size) + '}', 'g'));
i = 0;
pattern = patterns[i];
while (!!pattern) {
chars = pattern.replace(/[\d]/g, '').split('');
points = getPoints(pattern);
t = tree;
j = 0;
c = chars[j];
while (!!c) {
codePoint = c.charCodeAt(0);
if (!t[codePoint]) {
t[codePoint] = {};
}
t = t[codePoint];
j += 1;
c = chars[j];
}
t.tpoints = [];
for (k = 0; k < points.length; k += 1) {
p = points[k];
t.tpoints.push((p === "") ? 0 : p);
}
i += 1;
pattern = patterns[i];
}
}
}
Hyphenator.languages[lang].patterns = tree;
/**
* end of BSD licenced code from hypher.js
*/
},
/**
* @name Hyphenator-recreatePattern
* @description
* Recreates the pattern for the reducedPatternSet
* @private
*/
recreatePattern = function (pattern, nodePoints) {
var r = [], c = pattern.split(''), i;
for (i = 0; i < nodePoints.length; i += 1) {
if (nodePoints[i] !== 0) {
r.push(nodePoints[i]);
}
if (c[i]) {
r.push(c[i]);
}
}
return r.join('');
},
/**
* @name Hyphenator-convertExceptionsToObject
* @description
* Converts a list of comma seprated exceptions to an object:
* 'Fortran,Hy-phen-a-tion' -> {'Fortran':'Fortran','Hyphenation':'Hy-phen-a-tion'}
* @private
* @param {string} exc a comma separated string of exceptions (without spaces)
*/
convertExceptionsToObject = function (exc) {
var w = exc.split(', '),
r = {},
i,
l,
key;
for (i = 0, l = w.length; i < l; i += 1) {
key = w[i].replace(/-/g, '');
if (!r.hasOwnProperty(key)) {
r[key] = w[i];
}
}
return r;
},
/**
* @name Hyphenator-loadPatterns
* @description
* Checks if the requested file is available in the network.
* Adds a <script>-Tag to the DOM to load an externeal .js-file containing patterns and settings for the given language.
* If the given language is not in the {@link Hyphenator-supportedLangs}-Object it returns.
* One may ask why we are not using AJAX to load the patterns. The XMLHttpRequest-Object
* has a same-origin-policy. This makes the Bookmarklet impossible.
* @param {string} lang The language to load the patterns for
* @private
* @see Hyphenator-basePath
*/
loadPatterns = function (lang) {
var url, xhr, head, script;
if (supportedLangs.hasOwnProperty(lang) && !Hyphenator.languages[lang]) {
url = basePath + 'patterns/' + supportedLangs[lang].file;
} else {
return;
}
if (isLocal && !isBookmarklet) {
//check if 'url' is available:
xhr = null;
try {
// Mozilla, Opera, Safari and Internet Explorer (ab v7)
xhr = new window.XMLHttpRequest();
} catch (e) {
try {
//IE>=6
xhr = new window.ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
try {
//IE>=5
xhr = new window.ActiveXObject("Msxml2.XMLHTTP");
} catch (e3) {
xhr = null;
}
}
}
if (xhr) {
xhr.open('HEAD', url, true);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 404) {
onError(new Error('Could not load\n' + url));
delete docLanguages[lang];
return;
}
}
};
xhr.send(null);
}
}
if (createElem) {
head = window.document.getElementsByTagName('head').item(0);
script = createElem('script', window);
script.src = url;
script.type = 'text/javascript';
head.appendChild(script);
}
},
/**
* @name Hyphenator-prepareLanguagesObj
* @description
* Adds a cache to each language and converts the exceptions-list to an object.
* If storage is active the object is stored there.
* @private
* @param {string} lang the language ob the lang-obj
*/
prepareLanguagesObj = function (lang) {
var lo = Hyphenator.languages[lang], wrd;
if (!lo.prepared) {
if (enableCache) {
lo.cache = {};
//Export
//lo['cache'] = lo.cache;
}
if (enableReducedPatternSet) {
lo.redPatSet = {};
}
//add exceptions from the pattern file to the local 'exceptions'-obj
if (lo.hasOwnProperty('exceptions')) {
Hyphenator.addExceptions(lang, lo.exceptions);
delete lo.exceptions;
}
//copy global exceptions to the language specific exceptions
if (exceptions.hasOwnProperty('global')) {
if (exceptions.hasOwnProperty(lang)) {
exceptions[lang] += ', ' + exceptions.global;
} else {
exceptions[lang] = exceptions.global;
}
}
//move exceptions from the the local 'exceptions'-obj to the 'language'-object
if (exceptions.hasOwnProperty(lang)) {
lo.exceptions = convertExceptionsToObject(exceptions[lang]);
delete exceptions[lang];
} else {
lo.exceptions = {};
}
convertPatterns(lang);
wrd = '[\\w' + lo.specialChars + '@' + String.fromCharCode(173) + String.fromCharCode(8204) + '-]{' + min + ',}';
lo.genRegExp = new RegExp('(' + url + ')|(' + mail + ')|(' + wrd + ')', 'gi');
lo.prepared = true;
}
if (!!storage) {
try {
storage.setItem(lang, window.JSON.stringify(lo));
} catch (e) {
onError(e);
}
}
},
/**
* @name Hyphenator-prepare
* @description
* This funtion prepares the Hyphenator-Object: If RemoteLoading is turned off, it assumes
* that the patternfiles are loaded, all conversions are made and the callback is called.
* If storage is active the object is retrieved there.
* If RemoteLoading is on (default), it loads the pattern files and waits until they are loaded,
* by repeatedly checking Hyphenator.languages. If a patterfile is loaded the patterns are
* converted to their object style and the lang-object extended.
* Finally the callback is called.
* @private
*/
prepare = function (callback) {
var lang, interval, tmp1, tmp2;
if (!enableRemoteLoading) {
for (lang in Hyphenator.languages) {
if (Hyphenator.languages.hasOwnProperty(lang)) {
prepareLanguagesObj(lang);
}
}
state = 2;
callback('*');
return;
}
// get all languages that are used and preload the patterns
for (lang in docLanguages) {
if (docLanguages.hasOwnProperty(lang)) {
if (!!storage && storage.test(lang)) {
Hyphenator.languages[lang] = window.JSON.parse(storage.getItem(lang));
if (exceptions.hasOwnProperty('global')) {
tmp1 = convertExceptionsToObject(exceptions.global);
for (tmp2 in tmp1) {
if (tmp1.hasOwnProperty(tmp2)) {
Hyphenator.languages[lang].exceptions[tmp2] = tmp1[tmp2];
}
}
}
//Replace exceptions since they may have been changed:
if (exceptions.hasOwnProperty(lang)) {
tmp1 = convertExceptionsToObject(exceptions[lang]);
for (tmp2 in tmp1) {
if (tmp1.hasOwnProperty(tmp2)) {
Hyphenator.languages[lang].exceptions[tmp2] = tmp1[tmp2];
}
}
delete exceptions[lang];
}
//Replace genRegExp since it may have been changed:
tmp1 = '[\\w' + Hyphenator.languages[lang].specialChars + '@' + String.fromCharCode(173) + String.fromCharCode(8204) + '-]{' + min + ',}';
Hyphenator.languages[lang].genRegExp = new RegExp('(' + url + ')|(' + mail + ')|(' + tmp1 + ')', 'gi');
delete docLanguages[lang];
callback(lang);
} else {
loadPatterns(lang);
}
}
}
// else async wait until patterns are loaded, then hyphenate
interval = window.setInterval(function () {
var finishedLoading = true, lang;
for (lang in docLanguages) {
if (docLanguages.hasOwnProperty(lang)) {
finishedLoading = false;
if (!!Hyphenator.languages[lang]) {
delete docLanguages[lang];
//do conversion while other patterns are loading:
prepareLanguagesObj(lang);
callback(lang);
}
}
}
if (finishedLoading) {
window.clearInterval(interval);
state = 2;
}
}, 100);
},
/**
* @name Hyphenator-switchToggleBox
* @description
* Creates or hides the toggleBox: a small button to turn off/on hyphenation on a page.
* @see Hyphenator.config
* @private
*/
toggleBox = function () {
var bdy, myTextNode,
text = (Hyphenator.doHyphenation ? 'Hy-phen-a-tion' : 'Hyphenation'),
myBox = contextWindow.document.getElementById('HyphenatorToggleBox');
if (!!myBox) {
myBox.firstChild.data = text;
} else {
bdy = contextWindow.document.getElementsByTagName('body')[0];
myBox = createElem('div', contextWindow);
myBox.setAttribute('id', 'HyphenatorToggleBox');
myBox.setAttribute('class', dontHyphenateClass);
myTextNode = contextWindow.document.createTextNode(text);
myBox.appendChild(myTextNode);
myBox.onclick = Hyphenator.toggleHyphenation;
myBox.style.position = 'absolute';
myBox.style.top = '0px';
myBox.style.right = '0px';
myBox.style.margin = '0';
myBox.style.backgroundColor = '#AAAAAA';
myBox.style.color = '#FFFFFF';
myBox.style.font = '6pt Arial';
myBox.style.letterSpacing = '0.2em';
myBox.style.padding = '3px';
myBox.style.cursor = 'pointer';
myBox.style.WebkitBorderBottomLeftRadius = '4px';
myBox.style.MozBorderRadiusBottomleft = '4px';
myBox.style.borderBottomLeftRadius = '4px';
bdy.appendChild(myBox);
}
},
/**
* @name Hyphenator-hyphenateWord
* @description
* This function is the heart of Hyphenator.js. It returns a hyphenated word.
*
* If there's already a {@link Hyphenator-hypen} in the word, the word is returned as it is.
* If the word is in the exceptions list or in the cache, it is retrieved from it.
* If there's a '-' put a zeroWidthSpace after the '-' and hyphenate the parts.
* @param {string} lang The language of the word
* @param {string} word The word
* @returns string The hyphenated word
* @public
*/
hyphenateWord = function (lang, word) {
var lo = Hyphenator.languages[lang], parts, l, subst,
w, characters, origWord, originalCharacters, wordLength, i, j, k, node, points = [],
characterPoints = [], nodePoints, nodePointsLength, m = Math.max, trie,
result = [''], pattern, r;
word = onBeforeWordHyphenation(word, lang);
if (word === '') {
r = '';
} else if (enableCache && lo.cache.hasOwnProperty(word)) { //the word is in the cache
r = lo.cache[word];
} else if (word.indexOf(hyphen) !== -1) {
//word already contains shy; -> leave at it is!
r = word;
} else if (lo.exceptions.hasOwnProperty(word)) { //the word is in the exceptions list
r = lo.exceptions[word].replace(/-/g, hyphen);
} else if (word.indexOf('-') !== -1) {
//word contains '-' -> hyphenate the parts separated with '-'
parts = word.split('-');
for (i = 0, l = parts.length; i < l; i += 1) {
parts[i] = hyphenateWord(lang, parts[i]);
}
r = parts.join('-');
} else {
origWord = word;
w = word = '_' + word + '_';
if (!!lo.charSubstitution) {
for (subst in lo.charSubstitution) {
if (lo.charSubstitution.hasOwnProperty(subst)) {
w = w.replace(new RegExp(subst, 'g'), lo.charSubstitution[subst]);
}
}
}
if (origWord.indexOf("'") !== -1) {
w = w.replace("'", "’"); //replace APOSTROPHE with RIGHT SINGLE QUOTATION MARK (since the latter is used in the patterns)
}
/** @license BSD licenced code
* The following code is based on code from hypher.js
* Copyright (c) 2011, Bram Stein
*/
characters = w.toLowerCase().split('');
originalCharacters = word.split('');
wordLength = characters.length;
trie = lo.patterns;
for (i = 0; i < wordLength; i += 1) {
points[i] = 0;
characterPoints[i] = characters[i].charCodeAt(0);
}
for (i = 0; i < wordLength; i += 1) {
pattern = '';
node = trie;
for (j = i; j < wordLength; j += 1) {
node = node[characterPoints[j]];
if (node) {
if (enableReducedPatternSet) {
pattern += String.fromCharCode(characterPoints[j]);
}
nodePoints = node.tpoints;
if (nodePoints) {
if (enableReducedPatternSet) {
if (!lo.redPatSet) {
lo.redPatSet = {};
}
lo.redPatSet[pattern] = recreatePattern(pattern, nodePoints);
}
for (k = 0, nodePointsLength = nodePoints.length; k < nodePointsLength; k += 1) {
points[i + k] = m(points[i + k], nodePoints[k]);
}
}
} else {
break;
}
}
}
for (i = 1; i < wordLength - 1; i += 1) {
if (i > lo.leftmin && i < (wordLength - lo.rightmin) && points[i] % 2) {
result.push(originalCharacters[i]);
} else {
result[result.length - 1] += originalCharacters[i];
}
}
r = result.join(hyphen);
/**
* end of BSD licenced code from hypher.js
*/
}
r = onAfterWordHyphenation(r, lang);
if (enableCache) { //put the word in the cache
lo.cache[origWord] = r;
}
return r;
},
/**
* @name Hyphenator-hyphenateURL
* @description
* Puts {@link Hyphenator-urlhyphen} after each no-alphanumeric char that my be in a URL.
* @param {string} url to hyphenate
* @returns string the hyphenated URL
* @public
*/
hyphenateURL = function (url) {
return url.replace(/([:\/\.\?#&_,;!@]+)/gi, '$&' + urlhyphen);
},
/**
* @name Hyphenator-removeHyphenationFromElement
* @description
* Removes all hyphens from the element. If there are other elements, the function is
* called recursively.
* Removing hyphens is usefull if you like to copy text. Some browsers are buggy when the copy hyphenated texts.
* @param {Object} el The element where to remove hyphenation.
* @public
*/
removeHyphenationFromElement = function (el) {
var h, i = 0, n;
switch (hyphen) {
case '|':
h = '\\|';
break;
case '+':
h = '\\+';
break;
case '*':
h = '\\*';
break;
default:
h = hyphen;
}
n = el.childNodes[i];
while (!!n) {
if (n.nodeType === 3) {
n.data = n.data.replace(new RegExp(h, 'g'), '');
n.data = n.data.replace(new RegExp(zeroWidthSpace, 'g'), '');
} else if (n.nodeType === 1) {
removeHyphenationFromElement(n);
}
i += 1;
n = el.childNodes[i];
}
},
/**
* @name Hyphenator-oncopyHandler
* @description
* The function called by registerOnCopy
* @private
*/
oncopyHandler,
/**
* @name Hyphenator-removeOnCopy
* @description
* Method to remove copy event handler from the given element
* @param object a html object from witch we remove the event
* @private
*/
removeOnCopy = function (el) {
var body = el.ownerDocument.getElementsByTagName('body')[0];
if (!body) {
return;
}
el = el || body;
if (window.removeEventListener) {
el.removeEventListener("copy", oncopyHandler, true);
} else {
el.detachEvent("oncopy", oncopyHandler);
}
},
/**
* @name Hyphenator-registerOnCopy
* @description
* Huge work-around for browser-inconsistency when it comes to
* copying of hyphenated text.
* The idea behind this code has been provided by http://github.com/aristus/sweet-justice
* sweet-justice is under BSD-License
* @param object an HTML element where the copy event will be registered to
* @private
*/
registerOnCopy = function (el) {
var body = el.ownerDocument.getElementsByTagName('body')[0],
shadow,
selection,
range,
rangeShadow,
restore;
oncopyHandler = function (e) {
e = e || window.event;
var target = e.target || e.srcElement,
currDoc = target.ownerDocument,
body = currDoc.getElementsByTagName('body')[0],
targetWindow = currDoc.defaultView || currDoc.parentWindow;
if (target.tagName && dontHyphenate[target.tagName.toLowerCase()]) {
//Safari needs this
return;
}
//create a hidden shadow element
shadow = currDoc.createElement('div');
//Moving the element out of the screen doesn't work for IE9 (https://connect.microsoft.com/IE/feedback/details/663981/)
//shadow.style.overflow = 'hidden';
//shadow.style.position = 'absolute';
//shadow.style.top = '-5000px';
//shadow.style.height = '1px';
//doing this instead:
shadow.style.color = window.getComputedStyle ? targetWindow.getComputedStyle(body, null).backgroundColor : '#FFFFFF';
shadow.style.fontSize = '0px';
body.appendChild(shadow);
if (!!window.getSelection) {
//FF3, Webkit, IE9
e.stopPropagation();
selection = targetWindow.getSelection();
range = selection.getRangeAt(0);
shadow.appendChild(range.cloneContents());
removeHyphenationFromElement(shadow);
selection.selectAllChildren(shadow);
restore = function () {
shadow.parentNode.removeChild(shadow);
selection.removeAllRanges(); //IE9 needs that
selection.addRange(range);
};
} else {
// IE<9
e.cancelBubble = true;
selection = targetWindow.document.selection;
range = selection.createRange();
shadow.innerHTML = range.htmlText;
removeHyphenationFromElement(shadow);
rangeShadow = body.createTextRange();
rangeShadow.moveToElementText(shadow);
rangeShadow.select();
restore = function () {
shadow.parentNode.removeChild(shadow);
if (range.text !== "") {
range.select();
}
};
}
window.setTimeout(restore, 0);
};
if (!body) {
return;
}
el = el || body;
if (window.addEventListener) {
el.addEventListener("copy", oncopyHandler, true);
} else {
el.attachEvent("oncopy", oncopyHandler);
}
},
/**
* @name Hyphenator-checkIfAllDone
* @description
* Checks if all Elements are hyphenated, unhides them and fires onHyphenationDone()
* @private
*/
checkIfAllDone = function () {
var allDone = true, i;
elements.each(function (ellist) {
var i, l = ellist.length;
for (i = 0; i < l; i += 1) {
allDone = allDone && ellist[i].hyphenated;
}
});
if (allDone) {
if (intermediateState === 'hidden' && unhide === 'progressive') {
elements.each(function (ellist) {
var i, l = ellist.length, el;
for (i = 0; i < l; i += 1) {
el = ellist[i].element;
el.className = el.className.replace(unhideClassRegExp, '');
if (el.className === '') {
el.removeAttribute('class');
}
}
});
}
for (i = 0; i < CSSEditors.length; i += 1) {
CSSEditors[i].clearChanges();
}
state = 3;
onHyphenationDone();
}
},
/**
* @name Hyphenator-hyphenateElement
* @description
* Takes the content of the given element and - if there's text - replaces the words
* by hyphenated words. If there's another element, the function is called recursively.
* When all words are hyphenated, the visibility of the element is set to 'visible'.
* @param {Object} el The element to hyphenate
* @private
*/
hyphenateElement = function (lang, elo) {
var el = elo.element,
hyphenate,
n,
i,
r,
controlOrphans = function (part) {
var h, r;
switch (hyphen) {
case '|':
h = '\\|';
break;
case '+':
h = '\\+';
break;
case '*':
h = '\\*';
break;
default:
h = hyphen;
}
if (orphanControl >= 2) {
//remove hyphen points from last word
r = part.split(' ');
r[1] = r[1].replace(new RegExp(h, 'g'), '');
r[1] = r[1].replace(new RegExp(zeroWidthSpace, 'g'), '');
r = r.join(' ');
}
if (orphanControl === 3) {
//replace spaces by non breaking spaces
r = r.replace(/[ ]+/g, String.fromCharCode(160));
}
return r;
};
if (Hyphenator.languages.hasOwnProperty(lang)) {
hyphenate = function (word) {
if (!Hyphenator.doHyphenation) {
r = word;
} else if (urlOrMailRE.test(word)) {
r = hyphenateURL(word);
} else {
r = hyphenateWord(lang, word);
}
return r;
};
if (safeCopy && (el.tagName.toLowerCase() !== 'body')) {
registerOnCopy(el);
}
i = 0;
n = el.childNodes[i];
while (!!n) {
if (n.nodeType === 3 && n.data.length >= min) { //type 3 = #text -> hyphenate!
n.data = n.data.replace(Hyphenator.languages[lang].genRegExp, hyphenate);
if (orphanControl !== 1) {
n.data = n.data.replace(/[\S]+ [\S]+$/, controlOrphans);
}
}
i += 1;
n = el.childNodes[i];
}
}
if (intermediateState === 'hidden' && unhide === 'wait') {
el.className = el.className.replace(hideClassRegExp, '');
if (el.className === '') {
el.removeAttribute('class');
}
}
if (intermediateState === 'hidden' && unhide === 'progressive') {
el.className = el.className.replace(hideClassRegExp, ' ' + unhideClass);
}
elo.hyphenated = true;
elements.hyCount += 1;
if (elements.count <= elements.hyCount) {
checkIfAllDone();
}
},
/**
* @name Hyphenator-hyphenateLanguageElements
* @description
* Calls hyphenateElement() for all elements of the specified language.
* If the language is '*' then all elements are hyphenated.
* This is done with a setTimout
* to prevent a "long running Script"-alert when hyphenating large pages.
* Therefore a tricky bind()-function was necessary.
* @private
*/
hyphenateLanguageElements = function (lang) {
function bind(fun, arg1, arg2) {
return function () {
return fun(arg1, arg2);
};
}
var i, l;
if (lang === '*') {
elements.each(function (lang, ellist) {
var i, l = ellist.length;
for (i = 0; i < l; i += 1) {
window.setTimeout(bind(hyphenateElement, lang, ellist[i]), 0);
}
});
} else {
if (elements.list.hasOwnProperty(lang)) {
l = elements.list[lang].length;
for (i = 0; i < l; i += 1) {
window.setTimeout(bind(hyphenateElement, lang, elements.list[lang][i]), 0);
}
}
}
},
/**
* @name Hyphenator-removeHyphenationFromDocument
* @description
* Does what it says ;-)
* @private
*/
removeHyphenationFromDocument = function () {
elements.each(function (ellist) {
var i, l = ellist.length;
for (i = 0; i < l; i += 1) {
removeHyphenationFromElement(ellist[i].element);
if (safeCopy) {
removeOnCopy(ellist[i].element);
}
ellist[i].hyphenated = false;
}
});
state = 4;
},
/**
* @name Hyphenator-createStorage
* @description
* inits the private var storage depending of the setting in storageType
* and the supported features of the system.
* @private
*/
createStorage = function () {
var s;
try {
if (storageType !== 'none' &&
window.localStorage !== undefined &&
window.sessionStorage !== undefined &&
window.JSON.stringify !== undefined &&
window.JSON.parse !== undefined) {
switch (storageType) {
case 'session':
s = window.sessionStorage;
break;
case 'local':
s = window.localStorage;
break;
default:
s = undefined;
break;
}
}
} catch (f) {
//FF throws an error if DOM.storage.enabled is set to false
}
if (s) {
storage = {
prefix: 'Hyphenator_' + Hyphenator.version + '_',
store: s,
test: function (name) {
var val = this.store.getItem(this.prefix + name);
return (!!val) ? true : false;
},
getItem: function (name) {
return this.store.getItem(this.prefix + name);
},
setItem: function (name, value) {
this.store.setItem(this.prefix + name, value);
}
};
} else {
storage = undefined;
}
},
/**
* @name Hyphenator-storeConfiguration
* @description
* Stores the current config-options in DOM-Storage
* @private
*/
storeConfiguration = function () {
if (!storage) {
return;
}
var settings = {
'STORED': true,
'classname': hyphenateClass,
'donthyphenateclassname': dontHyphenateClass,
'minwordlength': min,
'hyphenchar': hyphen,
'urlhyphenchar': urlhyphen,
'togglebox': toggleBox,
'displaytogglebox': displayToggleBox,
'remoteloading': enableRemoteLoading,
'enablecache': enableCache,
'onhyphenationdonecallback': onHyphenationDone,
'onerrorhandler': onError,
'intermediatestate': intermediateState,
'selectorfunction': selectorFunction || mySelectorFunction,
'safecopy': safeCopy,
'doframes': doFrames,
'storagetype': storageType,
'orphancontrol': orphanControl,
'dohyphenation': Hyphenator.doHyphenation,
'persistentconfig': persistentConfig,
'defaultlanguage': defaultLanguage,
'useCSS3hyphenation': css3,
'unhide': unhide,
'onbeforewordhyphenation': onBeforeWordHyphenation,
'onafterwordhyphenation': onAfterWordHyphenation
};
storage.setItem('config', window.JSON.stringify(settings));
},
/**
* @name Hyphenator-restoreConfiguration
* @description
* Retrieves config-options from DOM-Storage and does configuration accordingly
* @private
*/
restoreConfiguration = function () {
var settings;
if (storage.test('config')) {
settings = window.JSON.parse(storage.getItem('config'));
Hyphenator.config(settings);
}
};
return {
/**
* @name Hyphenator.version
* @memberOf Hyphenator
* @description
* String containing the actual version of Hyphenator.js
* [major release].[minor releas].[bugfix release]
* major release: new API, new Features, big changes
* minor release: new languages, improvements
* @public
*/
version: 'X.Y.Z',
/**
* @name Hyphenator.doHyphenation
* @description
* If doHyphenation is set to false (defaults to true), hyphenateDocument() isn't called.
* All other actions are performed.
*/
doHyphenation: true,
/**
* @name Hyphenator.languages
* @memberOf Hyphenator
* @description
* Objects that holds key-value pairs, where key is the language and the value is the
* language-object loaded from (and set by) the pattern file.
* The language object holds the following members:
* <table>
* <tr><th>key</th><th>desc></th></tr>
* <tr><td>leftmin</td><td>The minimum of chars to remain on the old line</td></tr>
* <tr><td>rightmin</td><td>The minimum of chars to go on the new line</td></tr>
* <tr><td>shortestPattern</td><td>The shortes pattern (numbers don't count!)</td></tr>
* <tr><td>longestPattern</td><td>The longest pattern (numbers don't count!)</td></tr>
* <tr><td>specialChars</td><td>Non-ASCII chars in the alphabet.</td></tr>
* <tr><td>patterns</td><td>the patterns</td></tr>
* </table>
* And optionally (or after prepareLanguagesObj() has been called):
* <table>
* <tr><td>exceptions</td><td>Excpetions for the secified language</td></tr>
* </table>
* @public
*/
languages: {},
/**
* @name Hyphenator.config
* @description
* Config function that takes an object as an argument. The object contains key-value-pairs
* containig Hyphenator-settings. This is a shortcut for calling Hyphenator.set...-Methods.
* @param {Object} obj <table>
* <tr><th>key</th><th>values</th><th>default</th></tr>
* <tr><td>classname</td><td>string</td><td>'hyphenate'</td></tr>
* <tr><td>donthyphenateclassname</td><td>string</td><td>''</td></tr>
* <tr><td>minwordlength</td><td>integer</td><td>6</td></tr>
* <tr><td>hyphenchar</td><td>string</td><td>'&shy;'</td></tr>
* <tr><td>urlhyphenchar</td><td>string</td><td>'zero with space'</td></tr>
* <tr><td>togglebox</td><td>function</td><td>see code</td></tr>
* <tr><td>displaytogglebox</td><td>boolean</td><td>false</td></tr>
* <tr><td>remoteloading</td><td>boolean</td><td>true</td></tr>
* <tr><td>enablecache</td><td>boolean</td><td>true</td></tr>
* <tr><td>enablereducedpatternset</td><td>boolean</td><td>false</td></tr>
* <tr><td>onhyphenationdonecallback</td><td>function</td><td>empty function</td></tr>
* <tr><td>onerrorhandler</td><td>function</td><td>alert(onError)</td></tr>
* <tr><td>intermediatestate</td><td>string</td><td>'hidden'</td></tr>
* <tr><td>selectorfunction</td><td>function</td><td>[…]</td></tr>
* <tr><td>safecopy</td><td>boolean</td><td>true</td></tr>
* <tr><td>doframes</td><td>boolean</td><td>false</td></tr>
* <tr><td>storagetype</td><td>string</td><td>'none'</td></tr>
* </table>
* @public
* @example <script src = "Hyphenator.js" type = "text/javascript"></script>
* <script type = "text/javascript">
* Hyphenator.config({'minwordlength':4,'hyphenchar':'|'});
* Hyphenator.run();
* </script>
*/
config: function (obj) {
var assert = function (name, type) {
var r, t;
t = typeof obj[name];
if (t === type) {
r = true;
} else {
onError(new Error('Config onError: ' + name + ' must be of type ' + type));
r = false;
}
return r;
},
key;
if (obj.hasOwnProperty('storagetype')) {
if (assert('storagetype', 'string')) {
storageType = obj.storagetype;
}
if (!storage) {
createStorage();
}
}
if (!obj.hasOwnProperty('STORED') && storage && obj.hasOwnProperty('persistentconfig') && obj.persistentconfig === true) {
restoreConfiguration();
}
for (key in obj) {
if (obj.hasOwnProperty(key)) {
switch (key) {
case 'STORED':
break;
case 'classname':
if (assert('classname', 'string')) {
hyphenateClass = obj[key];
}
break;
case 'donthyphenateclassname':
if (assert('donthyphenateclassname', 'string')) {
dontHyphenateClass = obj[key];
}
break;
case 'minwordlength':
if (assert('minwordlength', 'number')) {
min = obj[key];
}
break;
case 'hyphenchar':
if (assert('hyphenchar', 'string')) {
if (obj.hyphenchar === '­') {
obj.hyphenchar = String.fromCharCode(173);
}
hyphen = obj[key];
}
break;
case 'urlhyphenchar':
if (obj.hasOwnProperty('urlhyphenchar')) {
if (assert('urlhyphenchar', 'string')) {
urlhyphen = obj[key];
}
}
break;
case 'togglebox':
if (assert('togglebox', 'function')) {
toggleBox = obj[key];
}
break;
case 'displaytogglebox':
if (assert('displaytogglebox', 'boolean')) {
displayToggleBox = obj[key];
}
break;
case 'remoteloading':
if (assert('remoteloading', 'boolean')) {
enableRemoteLoading = obj[key];
}
break;
case 'enablecache':
if (assert('enablecache', 'boolean')) {
enableCache = obj[key];
}
break;
case 'enablereducedpatternset':
if (assert('enablereducedpatternset', 'boolean')) {
enableReducedPatternSet = obj[key];
}
break;
case 'onhyphenationdonecallback':
if (assert('onhyphenationdonecallback', 'function')) {
onHyphenationDone = obj[key];
}
break;
case 'onerrorhandler':
if (assert('onerrorhandler', 'function')) {
onError = obj[key];
}
break;
case 'intermediatestate':
if (assert('intermediatestate', 'string')) {
intermediateState = obj[key];
}
break;
case 'selectorfunction':
if (assert('selectorfunction', 'function')) {
selectorFunction = obj[key];
}
break;
case 'safecopy':
if (assert('safecopy', 'boolean')) {
safeCopy = obj[key];
}
break;
case 'doframes':
if (assert('doframes', 'boolean')) {
doFrames = obj[key];
}
break;
case 'storagetype':
if (assert('storagetype', 'string')) {
storageType = obj[key];
}
break;
case 'orphancontrol':
if (assert('orphancontrol', 'number')) {
orphanControl = obj[key];
}
break;
case 'dohyphenation':
if (assert('dohyphenation', 'boolean')) {
Hyphenator.doHyphenation = obj[key];
}
break;
case 'persistentconfig':
if (assert('persistentconfig', 'boolean')) {
persistentConfig = obj[key];
}
break;
case 'defaultlanguage':
if (assert('defaultlanguage', 'string')) {
defaultLanguage = obj[key];
}
break;
case 'useCSS3hyphenation':
if (assert('useCSS3hyphenation', 'boolean')) {
css3 = obj[key];
}
break;
case 'unhide':
if (assert('unhide', 'string')) {
unhide = obj[key];
}
break;
case 'onbeforewordhyphenation':
if (assert('onbeforewordhyphenation', 'function')) {
onBeforeWordHyphenation = obj[key];
}
break;
case 'onafterwordhyphenation':
if (assert('onafterwordhyphenation', 'function')) {
onAfterWordHyphenation = obj[key];
}
break;
default:
onError(new Error('Hyphenator.config: property ' + key + ' not known.'));
}
}
}
if (storage && persistentConfig) {
storeConfiguration();
}
},
/**
* @name Hyphenator.run
* @description
* Bootstrap function that starts all hyphenation processes when called.
* @public
* @example <script src = "Hyphenator.js" type = "text/javascript"></script>
* <script type = "text/javascript">
* Hyphenator.run();
* </script>
*/
run: function () {
var process = function () {
try {
if (contextWindow.document.getElementsByTagName('frameset').length > 0) {
return; //we are in a frameset
}
autoSetMainLanguage(undefined);
gatherDocumentInfos();
prepare(hyphenateLanguageElements);
if (displayToggleBox) {
toggleBox();
}
} catch (e) {
onError(e);
}
};
if (!storage) {
createStorage();
}
runWhenLoaded(window, process);
},
/**
* @name Hyphenator.addExceptions
* @description
* Adds the exceptions from the string to the appropriate language in the
* {@link Hyphenator-languages}-object
* @param {string} lang The language
* @param {string} words A comma separated string of hyphenated words WITH spaces.
* @public
* @example <script src = "Hyphenator.js" type = "text/javascript"></script>
* <script type = "text/javascript">
* Hyphenator.addExceptions('de','ziem-lich, Wach-stube');
* Hyphenator.run();
* </script>
*/
addExceptions: function (lang, words) {
if (lang === '') {
lang = 'global';
}
if (exceptions.hasOwnProperty(lang)) {
exceptions[lang] += ", " + words;
} else {
exceptions[lang] = words;
}
},
/**
* @name Hyphenator.hyphenate
* @public
* @description
* Hyphenates the target. The language patterns must be loaded.
* If the target is a string, the hyphenated string is returned,
* if it's an object, the values are hyphenated directly.
* @param {string|Object} target the target to be hyphenated
* @param {string} lang the language of the target
* @returns string
* @example <script src = "Hyphenator.js" type = "text/javascript"></script>
* <script src = "patterns/en.js" type = "text/javascript"></script>
* <script type = "text/javascript">
* var t = Hyphenator.hyphenate('Hyphenation', 'en'); //Hy|phen|ation
* </script>
*/
hyphenate: function (target, lang) {
var hyphenate, n, i;
if (Hyphenator.languages.hasOwnProperty(lang)) {
if (!Hyphenator.languages[lang].prepared) {
prepareLanguagesObj(lang);
}
hyphenate = function (word) {
var r;
if (urlOrMailRE.test(word)) {
r = hyphenateURL(word);
} else {
r = hyphenateWord(lang, word);
}
return r;
};
if (typeof target === 'object' && !(typeof target === 'string' || target.constructor === String)) {
i = 0;
n = target.childNodes[i];
while (!!n) {
if (n.nodeType === 3 && n.data.length >= min) { //type 3 = #text -> hyphenate!
n.data = n.data.replace(Hyphenator.languages[lang].genRegExp, hyphenate);
} else if (n.nodeType === 1) {
if (n.lang !== '') {
Hyphenator.hyphenate(n, n.lang);
} else {
Hyphenator.hyphenate(n, lang);
}
}
i += 1;
n = target.childNodes[i];
}
} else if (typeof target === 'string' || target.constructor === String) {
return target.replace(Hyphenator.languages[lang].genRegExp, hyphenate);
}
} else {
onError(new Error('Language "' + lang + '" is not loaded.'));
}
},
/**
* @name Hyphenator.getRedPatternSet
* @description
* Returns {@link Hyphenator-isBookmarklet}.
* @param {string} lang the language patterns are stored for
* @returns object {'patk': pat}
* @public
*/
getRedPatternSet: function (lang) {
return Hyphenator.languages[lang].redPatSet;
},
/**
* @name Hyphenator.isBookmarklet
* @description
* Returns {@link Hyphenator-isBookmarklet}.
* @returns boolean
* @public
*/
isBookmarklet: function () {
return isBookmarklet;
},
getConfigFromURI: function () {
/*jslint evil: true*/
var loc = null, re = {}, jsArray = contextWindow.document.getElementsByTagName('script'), i, j, l, s, gp, option;
for (i = 0, l = jsArray.length; i < l; i += 1) {
if (!!jsArray[i].getAttribute('src')) {
loc = jsArray[i].getAttribute('src');
}
if (loc && (loc.indexOf('Hyphenator.js?') !== -1)) {
s = loc.indexOf('Hyphenator.js?');
gp = loc.substring(s + 14).split('&');
for (j = 0; j < gp.length; j += 1) {
option = gp[j].split('=');
if (option[0] !== 'bm') {
if (option[1] === 'true') {
option[1] = true;
} else if (option[1] === 'false') {
option[1] = false;
} else if (isFinite(option[1])) {
option[1] = parseInt(option[1], 10);
}
if (option[0] === 'onhyphenationdonecallback') {
option[1] = new Function('', option[1]);
}
re[option[0]] = option[1];
}
}
break;
}
}
return re;
},
/**
* @name Hyphenator.toggleHyphenation
* @description
* Checks the current state of the ToggleBox and removes or does hyphenation.
* @public
*/
toggleHyphenation: function () {
if (Hyphenator.doHyphenation) {
if (!!css3hyphenateClassHandle) {
css3hyphenateClassHandle.setRule('.' + css3hyphenateClass, css3_h9n.property + ': none;');
}
removeHyphenationFromDocument();
Hyphenator.doHyphenation = false;
storeConfiguration();
toggleBox();
} else {
if (!!css3hyphenateClassHandle) {
css3hyphenateClassHandle.setRule('.' + css3hyphenateClass, css3_h9n.property + ': auto;');
}
hyphenateLanguageElements('*');
Hyphenator.doHyphenation = true;
storeConfiguration();
toggleBox();
}
}
};
}(window));
//Export properties/methods (for google closure compiler)
/* to be moved to external file
Hyphenator['languages'] = Hyphenator.languages;
Hyphenator['config'] = Hyphenator.config;
Hyphenator['run'] = Hyphenator.run;
Hyphenator['addExceptions'] = Hyphenator.addExceptions;
Hyphenator['hyphenate'] = Hyphenator.hyphenate;
Hyphenator['getRedPatternSet'] = Hyphenator.getRedPatternSet;
Hyphenator['isBookmarklet'] = Hyphenator.isBookmarklet;
Hyphenator['getConfigFromURI'] = Hyphenator.getConfigFromURI;
Hyphenator['toggleHyphenation'] = Hyphenator.toggleHyphenation;
window['Hyphenator'] = Hyphenator;
*/
if (Hyphenator.isBookmarklet()) {
Hyphenator.config({displaytogglebox: true, intermediatestate: 'visible', doframes: true, useCSS3hyphenation: true});
Hyphenator.config(Hyphenator.getConfigFromURI());
Hyphenator.run();
}
|
JavaScript
|
Hyphenator.languages['it'] = {
leftmin : 2,
rightmin : 2,
specialChars : "àéèìòù’'",
// The italian hyphenation patterns are retrieved from
// http://www.ctan.org/tex-archive/language/hyphenation/ithyph.tex
patterns : {
2 : "1b1c1d1f1g1h1j1k1l1m1n1p1q1r1t1v1w1x1z",
3 : "2’2e2w2bb2bc2bd2bf2bm2bn2bp2bs2bt2bvb2lb2r2b_2b’2cb2cc2cd2cf2ck2cm2cn2cq2cs2ct2czc2hc2lc2r2c_2c’_c22db2dd2dg2dl2dm2dn2dpd2r2ds2dt2dv2dw2d_2d’_d22fb2fg2ff2fnf2lf2r2fs2ft2f_2f’2gb2gd2gf2ggg2hg2l2gmg2n2gpg2r2gs2gt2gv2gw2gz2g_2g’2hb2hd2hhh2l2hm2hn2hr2hv2h_2h’2j_2j’2kg2kfk2h2kkk2l2kmk2r2ks2kt2k_2k’2lb2lc2ld2lgl2h2lk2ll2lm2ln2lp2lq2lr2ls2lt2lv2lw2lz2l_2mb2mc2mf2ml2mm2mn2mp2mq2mr2ms2mt2mv2mw2m_2m’2nb2nc2nd2nf2ng2nk2nl2nm2nn2np2nq2nr2ns2nt2nv2nz2n_2n’2pdp2hp2l2pn2ppp2r2ps2pt2pz2p_2p’2qq2q_2q’2rb2rc2rd2rfr2h2rg2rk2rl2rm2rn2rp2rq2rr2rs2rt2rv2rx2rw2rz2r_2r’1s22sz4s_2tb2tc2td2tf2tgt2ht2l2tm2tn2tpt2rt2s2tt2tv2twt2z2t_2vcv2lv2r2vv2v_w2h2w_2w’2xb2xc2xf2xh2xm2xp2xt2xw2x_2x’y1i2zb2zd2zl2zn2zp2zt2zs2zv2zz2z_",
4 : "_p2sa1iaa1iea1ioa1iua1uoa1ya2at_e1iuo1iao1ieo1ioo1iu2chh2chbch2r2chn2l’_2l’’2shm2sh_2sh’2s3s2stb2stc2std2stf2stg2stm2stn2stp2sts2stt2stv4s’_4s’’2tzktz2s2t’_2t’’2v’_2v’’wa2r2w1yy1ou2z’_2z’’_z2",
5 : "_bio1_pre12gh2t2l3f2n2g3n3p2nes4s3mt2t3s",
6 : "_a3p2n_anti1_free3_opto1_para1hi3p2n2nheit3p2sicr2t2s32s3p2n3t2sch",
7 : "_ca4p3s_e2x1eu_narco1_su2b3r_wa2g3n_wel2t1n2s3fer",
8 : "_contro1_fran2k3_li3p2sa_orto3p2_poli3p2_sha2re3_su2b3lu",
9 : "_anti3m2n_circu2m1_re1i2scr_tran2s3c_tran2s3d_tran2s3l_tran2s3n_tran2s3p_tran2s3r_tran2s3t",
10 : "_di2s3cine"
}
};
|
JavaScript
|
// For questions about the Oriya hyphenation patterns
// ask Santhosh Thottingal (santhosh dot thottingal at gmail dot com)
Hyphenator.languages['or'] = {
leftmin : 2,
rightmin : 2,
specialChars : unescape("ଆଅଇଈଉଊଋଏଐଔକଗଖଘଙଚଛଜଝଞଟଠଡଢଣତଥଦଧନପଫବଭମଯରଲଵଶଷସହଳିୀାୁୂୃୋୋୈୌୗ୍ଃଂ%u200D"),
patterns : {
2 : "ଅ1ଆ1ଇ1ଈ1ଉ1ଊ1ଋ1ଏ1ଐ1ଔ1ି1ା1ୀ1ୁ1ୂ1ୃ1େ1ୋ1ୌ1ୗ1୍2ଃ1ଂ11କ1ଖ1ଘ1ଙ1ଚ1ଛ1ଜ1ଝ1ଞ1ଟ1ଠ1ଡ1ଢ1ଣ1ତ1ଥ1ଦ1ଧ1ନ1ପ1ଫ1ବ1ଭ1ମ1ଯ1ର1ଲ1ଵ1ଶ1ଷ1ସ1ହ1ଳ",
3 : "1ଗ1",
4 : unescape("2ନ୍%u200D2ର୍%u200D2ଲ୍%u200D2ଳ୍%u200D2ଣ୍%u200D")
}
};
|
JavaScript
|
// For questions about the Kannada hyphenation patterns
// ask Santhosh Thottingal (santhosh dot thottingal at gmail dot com)
Hyphenator.languages['kn'] = {
leftmin : 2,
rightmin : 2,
specialChars : "ಆಅಇಈಉಊಋಎಏಐಒಔಕಗಖಘಙಚಛಜಝಞಟಠಡಢಣತಥದಧನಪಫಬಭಮಯರಲವಶಷಸಹಳಱಿೀಾುೂೃೆೇೊಾೋೈೌ್ಃಂ",
patterns : {
2 : "ಅ1ಆ1ಇ1ಈ1ಉ1ಊ1ಋ1ಎ1ಏ1ಐ1ಒ1ಔ1ೀ1ು1ೂ1ೃ1ೆ1ೇ1ೊ1ೋ1ೌ1್2ಃ1ಂ11ಕ1ಗ1ಖ1ಘ1ಙ1ಚ1ಛ1ಜ1ಝ1ಞ1ಟ1ಠ1ಡ1ಢ1ಣ1ತ1ಥ1ದ1ಧ1ನ1ಪ1ಫ1ಬ1ಭ1ಮ1ಯ1ರ1ಲ1ವ1ಶ1ಷ1ಸ1ಹ1ಳ1ಱ",
3 : "2ಃ12ಂ1"
}
};
|
JavaScript
|
// For questions about the Panjabi hyphenation patterns
// ask Santhosh Thottingal (santhosh dot thottingal at gmail dot com)
Hyphenator.languages['pa'] = {
leftmin : 2,
rightmin : 2,
specialChars : unescape("ਆਅਇਈਉਊਏਐਔਕਗਖਘਙਚਛਜਝਞਟਠਡਢਣਤਥਦਧਨਪਫਬਭਮਯਰਲਵਸ਼ਸਹਲ਼ਿੀਾੁੂੇਾੋੈੌ੍ਃ%u0A02%u200D"),
patterns : {
2 : unescape("ਅ1ਆ1ਇ1ਈ1ਉ1ਊ1ਏ1ਐ1ਔ1ਿ1ਾ1ੀ1ੁ1ੂ1ੇ1ੋ1ੌ1੍2ਃ1%u0A0211ਕ1ਗ1ਖ1ਘ1ਙ1ਚ1ਛ1ਜ1ਝ1ਞ1ਟ1ਠ1ਡ1ਢ1ਣ1ਤ1ਥ1ਦ1ਧ1ਨ1ਪ1ਫ1ਬ1ਭ1ਮ1ਯ1ਰ1ਲ1ਵ1ਸ਼1ਸ1ਹ1ਲ਼")
}
};
|
JavaScript
|
// For questions about the Malayalam hyphenation patterns
// ask Santhosh Thottingal (santhosh dot thottingal at gmail dot com)
Hyphenator.languages['ml'] = {
leftmin : 2,
rightmin : 2,
specialChars : unescape("അആഇഈഉഊഋൠഌൡഎഏഐഒഓഔാിീുൂൃെേൈൊോൌൗകഖഗഘങചഛജഝഞടഠഡഢണതഥദധനപഫബഭമയരറലളഴവശഷസഹഃം്ൺൻർൽൾൿ%u200D"),
patterns : {
2 : "ാ1ി1ീ1ു1ൂ1ൃ1െ1േ1ൈ1ൊ1ോ1ൌ1ൗ11ക1ഖ1ഗ1ഘ1ങ1ച1ഛ1ജ1ഝ1ഞ1ട1ഠ1ഡ1ഢ1ണ1ത1ഥ1ദ1ധ1ന1പ1ഫ1ബ1ഭ1മ1യ1ര1റ1ല1ള1ഴ1വ1ശ1ഷ1സ1ഹ2ൺ2ൻ2ർ2ൽ2ൾ2ൿ",
3 : "1അ11ആ11ഇ11ഈ11ഉ11ഊ11ഋ11ൠ11ഌ11ൡ11എ11ഏ11ഐ11ഒ11ഓ11ഔ12ഃ12ം12്2ന്2ര്2ള്2ല്2ക്2ണ്2",
4 : unescape("2ന്%u200D2ര്%u200D2ല്%u200D2ള്%u200D2ണ്%u200D2ക്%u200D")
}
};
|
JavaScript
|
// For questions about the Telugu hyphenation patterns
// ask Santhosh Thottingal (santhosh dot thottingal at gmail dot com)
Hyphenator.languages['te'] = {
leftmin : 2,
rightmin : 2,
specialChars : "ఆఅఇఈఉఊఋఎఏఐఒఔకగఖఘఙచఛజఝఞటఠడఢణతథదధనపఫబభమయరలవశషసహళఱిీాుూృెేొాోైౌ్ఃం",
patterns : {
2 : "అ1ఆ1ఇ1ఈ1ఉ1ఊ1ఋ1ఎ1ఏ1ఐ1ఒ1ఔ1ి1ా1ీ1ు1ూ1ృ1ె1ే1ొ1ో1ౌ1్2ః1ం11క1గ1ఖ1ఘ1ఙ1చ1ఛ1జ1ఝ1ఞ1ట1ఠ1డ1ఢ1ణ1త1థ1ద1ధ1న1ప1ఫ1బ1భ1మ1య1ర1ల1వ1శ1ష1స1హ1ళ1ఱ"
}
};
|
JavaScript
|
// For questions about the Bengali hyphenation patterns
// ask Santhosh Thottingal (santhosh dot thottingal at gmail dot com)
Hyphenator.languages['bn'] = {
leftmin : 2,
rightmin : 2,
specialChars : unescape("আঅইঈউঊঋএঐঔকগখঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহিীাুূৃোোৈৌৗ্ঃং%u200D"),
patterns : {
2 : "অ1আ1ই1ঈ1উ1ঊ1ঋ1এ1ঐ1ঔ1ি1া1ী1ু1ৃ1ে1ো1ৌ1ৗ1্2ঃ1ং11ক1গ1খ1ঘ1ঙ1চ1ছ1জ1ঝ1ঞ1ট1ঠ1ড1ঢ1ণ1ত1থ1দ1ধ1ন1প1ফ1ব1ভ1ম1য1র1ল1শ1ষ1স1হ",
3 : "2ঃ12ং1"
}
};
|
JavaScript
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.