code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/*!
* jQuery JavaScript Library v1.6.1
* http://jquery.com/
*
* Copyright 2011, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Thu May 12 15:04:36 2011 -0400
*/
(function( window, undefined ) {
// Use the correct document accordingly with window argument (sandbox)
var document = window.document,
navigator = window.navigator,
location = window.location;
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// (both of which we optimize for)
quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
// Check for digits
rdigit = /\d/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
// Useragent RegExp
rwebkit = /(webkit)[ \/]([\w.]+)/,
ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
rmsie = /(msie) ([\w.]+)/,
rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
// Keep a UserAgent string for use with jQuery.browser
userAgent = navigator.userAgent,
// For matching the engine and version of the browser
browserMatch,
// The deferred used on DOM ready
readyList,
// The ready event handler
DOMContentLoaded,
// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = quickExpr.exec( selector );
}
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = (context ? context.ownerDocument || context : document);
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
}
return jQuery.merge( this, selector );
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return (context || rootjQuery).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if (selector.selector !== undefined) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.6.1",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return slice.call( this, 0 );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = this.constructor();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
} else {
jQuery.merge( ret, elems );
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + (this.selector ? " " : "") + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// Add the callback
readyList.done( fn );
return this;
},
eq: function( i ) {
return i === -1 ?
this.slice( i ) :
this.slice( i, +i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ),
"slice", slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Either a released hold or an DOMready/load event and not yet ready
if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).unbind( "ready" );
}
}
},
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery._Deferred();
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
// A crude way of determining if an object is a window
isWindow: function( obj ) {
return obj && typeof obj === "object" && "setInterval" in obj;
},
isNaN: function( obj ) {
return obj == null || !rdigit.test( obj ) || isNaN( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw msg;
},
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return (new Function( "return " + data ))();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
// (xml & tmp used internally)
parseXML: function( data , xml , tmp ) {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
tmp = xml.documentElement;
if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction( object );
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
break;
}
}
}
}
return object;
},
// Use native String.trim function wherever possible
trim: trim ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
},
// results is for internal usage only
makeArray: function( array, results ) {
var ret = results || [];
if ( array != null ) {
// The window, strings (and functions) also have 'length'
// The extra typeof function check is to prevent crashes
// in Safari 2 (See: #3039)
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
var type = jQuery.type( array );
if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
push.call( ret, array );
} else {
jQuery.merge( ret, array );
}
}
return ret;
},
inArray: function( elem, array ) {
if ( indexOf ) {
return indexOf.call( array, elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
},
merge: function( first, second ) {
var i = first.length,
j = 0;
if ( typeof second.length === "number" ) {
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var ret = [], retVal;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key, ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
if ( typeof context === "string" ) {
var tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
var args = slice.call( arguments, 2 ),
proxy = function() {
return fn.apply( context, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
return proxy;
},
// Mutifunctional method to get and set values to a collection
// The value/s can be optionally by executed if its a function
access: function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
// Setting many attributes
if ( typeof key === "object" ) {
for ( var k in key ) {
jQuery.access( elems, k, key[k], exec, fn, value );
}
return elems;
}
// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
for ( var i = 0; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
return elems;
}
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
},
now: function() {
return (new Date()).getTime();
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
},
sub: function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
},
browser: {}
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
jQuery.browser[ browserMatch.browser ] = true;
jQuery.browser.version = browserMatch.version;
}
// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
jQuery.browser.safari = true;
}
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
};
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
// Expose jQuery to the global object
return jQuery;
})();
var // Promise methods
promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ),
// Static reference to slice
sliceDeferred = [].slice;
jQuery.extend({
// Create a simple deferred (one callbacks list)
_Deferred: function() {
var // callbacks list
callbacks = [],
// stored [ context , args ]
fired,
// to avoid firing when already doing so
firing,
// flag to know if the deferred has been cancelled
cancelled,
// the deferred itself
deferred = {
// done( f1, f2, ...)
done: function() {
if ( !cancelled ) {
var args = arguments,
i,
length,
elem,
type,
_fired;
if ( fired ) {
_fired = fired;
fired = 0;
}
for ( i = 0, length = args.length; i < length; i++ ) {
elem = args[ i ];
type = jQuery.type( elem );
if ( type === "array" ) {
deferred.done.apply( deferred, elem );
} else if ( type === "function" ) {
callbacks.push( elem );
}
}
if ( _fired ) {
deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
}
}
return this;
},
// resolve with given context and args
resolveWith: function( context, args ) {
if ( !cancelled && !fired && !firing ) {
// make sure args are available (#8421)
args = args || [];
firing = 1;
try {
while( callbacks[ 0 ] ) {
callbacks.shift().apply( context, args );
}
}
finally {
fired = [ context, args ];
firing = 0;
}
}
return this;
},
// resolve with this as context and given arguments
resolve: function() {
deferred.resolveWith( this, arguments );
return this;
},
// Has this deferred been resolved?
isResolved: function() {
return !!( firing || fired );
},
// Cancel
cancel: function() {
cancelled = 1;
callbacks = [];
return this;
}
};
return deferred;
},
// Full fledged deferred (two callbacks list)
Deferred: function( func ) {
var deferred = jQuery._Deferred(),
failDeferred = jQuery._Deferred(),
promise;
// Add errorDeferred methods, then and promise
jQuery.extend( deferred, {
then: function( doneCallbacks, failCallbacks ) {
deferred.done( doneCallbacks ).fail( failCallbacks );
return this;
},
always: function() {
return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments );
},
fail: failDeferred.done,
rejectWith: failDeferred.resolveWith,
reject: failDeferred.resolve,
isRejected: failDeferred.isResolved,
pipe: function( fnDone, fnFail ) {
return jQuery.Deferred(function( newDefer ) {
jQuery.each( {
done: [ fnDone, "resolve" ],
fail: [ fnFail, "reject" ]
}, function( handler, data ) {
var fn = data[ 0 ],
action = data[ 1 ],
returned;
if ( jQuery.isFunction( fn ) ) {
deferred[ handler ](function() {
returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise().then( newDefer.resolve, newDefer.reject );
} else {
newDefer[ action ]( returned );
}
});
} else {
deferred[ handler ]( newDefer[ action ] );
}
});
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
if ( obj == null ) {
if ( promise ) {
return promise;
}
promise = obj = {};
}
var i = promiseMethods.length;
while( i-- ) {
obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ];
}
return obj;
}
});
// Make sure only one callback list will be used
deferred.done( failDeferred.cancel ).fail( deferred.cancel );
// Unexpose cancel
delete deferred.cancel;
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
return deferred;
},
// Deferred helper
when: function( firstParam ) {
var args = arguments,
i = 0,
length = args.length,
count = length,
deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
firstParam :
jQuery.Deferred();
function resolveFunc( i ) {
return function( value ) {
args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
if ( !( --count ) ) {
// Strange bug in FF4:
// Values changed onto the arguments object sometimes end up as undefined values
// outside the $.when method. Cloning the object into a fresh array solves the issue
deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) );
}
};
}
if ( length > 1 ) {
for( ; i < length; i++ ) {
if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) {
args[ i ].promise().then( resolveFunc(i), deferred.reject );
} else {
--count;
}
}
if ( !count ) {
deferred.resolveWith( deferred, args );
}
} else if ( deferred !== firstParam ) {
deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var div = document.createElement( "div" ),
documentElement = document.documentElement,
all,
a,
select,
opt,
input,
marginDiv,
support,
fragment,
body,
bodyStyle,
tds,
events,
eventName,
i,
isSupported;
// Preliminary tests
div.setAttribute("className", "t");
div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
all = div.getElementsByTagName( "*" );
a = div.getElementsByTagName( "a" )[ 0 ];
// Can't get basic test support
if ( !all || !all.length || !a ) {
return {};
}
// First batch of supports tests
select = document.createElement( "select" );
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName( "input" )[ 0 ];
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName( "tbody" ).length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName( "link" ).length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute( "href" ) === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.55$/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", function click() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
div.detachEvent( "onclick", click );
});
div.cloneNode( true ).fireEvent( "onclick" );
}
// Check if a radio maintains it's value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute("type", "radio");
support.radioValue = input.value === "t";
input.setAttribute("checked", "checked");
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.firstChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
div.innerHTML = "";
// Figure out if the W3C box model works as expected
div.style.width = div.style.paddingLeft = "1px";
// We use our own, invisible, body
body = document.createElement( "body" );
bodyStyle = {
visibility: "hidden",
width: 0,
height: 0,
border: 0,
margin: 0,
// Set background to avoid IE crashes when removing (#9028)
background: "none"
};
for ( i in bodyStyle ) {
body.style[ i ] = bodyStyle[ i ];
}
body.appendChild( div );
documentElement.insertBefore( body, documentElement.firstChild );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
support.boxModel = div.offsetWidth === 2;
if ( "zoom" in div.style ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.style.display = "inline";
div.style.zoom = 1;
support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "";
div.innerHTML = "<div style='width:4px;'></div>";
support.shrinkWrapBlocks = ( div.offsetWidth !== 2 );
}
div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";
tds = div.getElementsByTagName( "td" );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE < 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
div.innerHTML = "";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
if ( document.defaultView && document.defaultView.getComputedStyle ) {
marginDiv = document.createElement( "div" );
marginDiv.style.width = "0";
marginDiv.style.marginRight = "0";
div.appendChild( marginDiv );
support.reliableMarginRight =
( parseInt( ( document.defaultView.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
}
// Remove the body element we added
body.innerHTML = "";
documentElement.removeChild( body );
// Technique from Juriy Zaytsev
// http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for( i in {
submit: 1,
change: 1,
focusin: 1
} ) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
return support;
})();
// Keep track of boxModel
jQuery.boxModel = jQuery.support.boxModel;
var rbrace = /^(?:\{.*\}|\[.*\])$/,
rmultiDash = /([a-z])([A-Z])/g;
jQuery.extend({
cache: {},
// Please use with caution
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ jQuery.expando ] = id = ++jQuery.uuid;
} else {
id = jQuery.expando;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
// metadata on plain JS objects when the object is serialized using
// JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name);
} else {
cache[ id ] = jQuery.extend(cache[ id ], name);
}
}
thisCache = cache[ id ];
// Internal jQuery data is stored in a separate object inside the object's data
// cache in order to avoid key collisions between internal data and user-defined
// data
if ( pvt ) {
if ( !thisCache[ internalKey ] ) {
thisCache[ internalKey ] = {};
}
thisCache = thisCache[ internalKey ];
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should
// not attempt to inspect the internal events object using jQuery.data, as this
// internal data object is undocumented and subject to change.
if ( name === "events" && !thisCache[name] ) {
return thisCache[ internalKey ] && thisCache[ internalKey ].events;
}
return getByName ? thisCache[ jQuery.camelCase( name ) ] : thisCache;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var internalKey = jQuery.expando, isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
// See jQuery.data for more information
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ];
if ( thisCache ) {
delete thisCache[ name ];
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !isEmptyDataObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( pvt ) {
delete cache[ id ][ internalKey ];
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject(cache[ id ]) ) {
return;
}
}
var internalCache = cache[ id ][ internalKey ];
// Browsers that fail expando deletion also refuse to delete expandos on
// the window, but it will allow it on all other JS objects; other browsers
// don't care
if ( jQuery.support.deleteExpando || cache != window ) {
delete cache[ id ];
} else {
cache[ id ] = null;
}
// We destroyed the entire user cache at once because it's faster than
// iterating through each key, but we need to continue to persist internal
// data if it existed
if ( internalCache ) {
cache[ id ] = {};
// TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
// metadata on plain JS objects when the object is serialized using
// JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
cache[ id ][ internalKey ] = internalCache;
// Otherwise, we need to eliminate the expando on the node to avoid
// false lookups in the cache for entries that no longer exist
} else if ( isNode ) {
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( jQuery.support.deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
} else {
elem[ jQuery.expando ] = null;
}
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
if ( elem.nodeName ) {
var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
if ( match ) {
return !(match === true || elem.getAttribute("classid") !== match);
}
}
return true;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var data = null;
if ( typeof key === "undefined" ) {
if ( this.length ) {
data = jQuery.data( this[0] );
if ( this[0].nodeType === 1 ) {
var attr = this[0].attributes, name;
for ( var i = 0, l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( this[0], name, data[ name ] );
}
}
}
}
return data;
} else if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
var parts = key.split(".");
parts[1] = parts[1] ? "." + parts[1] : "";
if ( value === undefined ) {
data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
// Try to fetch any internally stored data first
if ( data === undefined && this.length ) {
data = jQuery.data( this[0], key );
data = dataAttr( this[0], key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
} else {
return this.each(function() {
var $this = jQuery( this ),
args = [ parts[0], value ];
$this.triggerHandler( "setData" + parts[1] + "!", args );
jQuery.data( this, key, value );
$this.triggerHandler( "changeData" + parts[1] + "!", args );
});
}
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "$1-$2" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
!jQuery.isNaN( data ) ? parseFloat( data ) :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON
// property to be considered empty objects; this property always exists in
// order to make sure JSON.stringify does not expose internal metadata
function isEmptyDataObject( obj ) {
for ( var name in obj ) {
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function handleQueueMarkDefer( elem, type, src ) {
var deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
defer = jQuery.data( elem, deferDataKey, undefined, true );
if ( defer &&
( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) &&
( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) {
// Give room for hard-coded callbacks to fire first
// and eventually mark/queue something else on the element
setTimeout( function() {
if ( !jQuery.data( elem, queueDataKey, undefined, true ) &&
!jQuery.data( elem, markDataKey, undefined, true ) ) {
jQuery.removeData( elem, deferDataKey, true );
defer.resolve();
}
}, 0 );
}
}
jQuery.extend({
_mark: function( elem, type ) {
if ( elem ) {
type = (type || "fx") + "mark";
jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true );
}
},
_unmark: function( force, elem, type ) {
if ( force !== true ) {
type = elem;
elem = force;
force = false;
}
if ( elem ) {
type = type || "fx";
var key = type + "mark",
count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 );
if ( count ) {
jQuery.data( elem, key, count, true );
} else {
jQuery.removeData( elem, key, true );
handleQueueMarkDefer( elem, type, "mark" );
}
}
},
queue: function( elem, type, data ) {
if ( elem ) {
type = (type || "fx") + "queue";
var q = jQuery.data( elem, type, undefined, true );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !q || jQuery.isArray(data) ) {
q = jQuery.data( elem, type, jQuery.makeArray(data), true );
} else {
q.push( data );
}
}
return q || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
fn = queue.shift(),
defer;
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift("inprogress");
}
fn.call(elem, function() {
jQuery.dequeue(elem, type);
});
}
if ( !queue.length ) {
jQuery.removeData( elem, type + "queue", true );
handleQueueMarkDefer( elem, type, "queue" );
}
}
});
jQuery.fn.extend({
queue: function( type, data ) {
if ( typeof type !== "string" ) {
data = type;
type = "fx";
}
if ( data === undefined ) {
return jQuery.queue( this[0], type );
}
return this.each(function() {
var queue = jQuery.queue( this, type, data );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
type = type || "fx";
return this.queue( type, function() {
var elem = this;
setTimeout(function() {
jQuery.dequeue( elem, type );
}, time );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, object ) {
if ( typeof type !== "string" ) {
object = type;
type = undefined;
}
type = type || "fx";
var defer = jQuery.Deferred(),
elements = this,
i = elements.length,
count = 1,
deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
tmp;
function resolve() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
}
while( i-- ) {
if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) {
count++;
tmp.done( resolve );
}
}
resolve();
return defer.promise();
}
});
var rclass = /[\n\t\r]/g,
rspace = /\s+/,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea)?$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
rinvalidChar = /\:/,
formHook, boolHook;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.attr );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.prop );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this);
self.addClass( value.call(this, i, self.attr("class") || "") );
});
}
if ( value && typeof value === "string" ) {
var classNames = (value || "").split( rspace );
for ( var i = 0, l = this.length; i < l; i++ ) {
var elem = this[i];
if ( elem.nodeType === 1 ) {
if ( !elem.className ) {
elem.className = value;
} else {
var className = " " + elem.className + " ",
setClass = elem.className;
for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
setClass += " " + classNames[c];
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
self.removeClass( value.call(this, i, self.attr("class")) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
var classNames = (value || "").split( rspace );
for ( var i = 0, l = this.length; i < l; i++ ) {
var elem = this[i];
if ( elem.nodeType === 1 && elem.className ) {
if ( value ) {
var className = (" " + elem.className + " ").replace(rclass, " ");
for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[c] + " ", " ");
}
elem.className = jQuery.trim( className );
} else {
elem.className = "";
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this);
self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space seperated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ";
for ( var i = 0, l = this.length; i < l; i++ ) {
if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
return (elem.value || "").replace(rreturn, "");
}
return undefined;
}
var isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var self = jQuery(this), val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value,
index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if ( index < 0 ) {
return null;
}
// Loop through all the selected options
for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
var option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
if ( one && !values.length && options.length ) {
return jQuery( options[ index ] ).val();
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attrFn: {
val: true,
css: true,
html: true,
text: true,
data: true,
width: true,
height: true,
offset: true
},
attrFix: {
// Always normalize to ensure hook usage
tabindex: "tabIndex"
},
attr: function( elem, name, value, pass ) {
var nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return undefined;
}
if ( pass && name in jQuery.attrFn ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( !("getAttribute" in elem) ) {
return jQuery.prop( elem, name, value );
}
var ret, hooks,
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// Normalize the name if needed
name = notxml && jQuery.attrFix[ name ] || name;
hooks = jQuery.attrHooks[ name ];
if ( !hooks ) {
// Use boolHook for boolean attributes
if ( rboolean.test( name ) &&
(typeof value === "boolean" || value === undefined || value.toLowerCase() === name.toLowerCase()) ) {
hooks = boolHook;
// Use formHook for forms and if the name contains certain characters
} else if ( formHook && (jQuery.nodeName( elem, "form" ) || rinvalidChar.test( name )) ) {
hooks = formHook;
}
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return undefined;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, "" + value );
return value;
}
} else if ( hooks && "get" in hooks && notxml ) {
return hooks.get( elem, name );
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, name ) {
var propName;
if ( elem.nodeType === 1 ) {
name = jQuery.attrFix[ name ] || name;
if ( jQuery.support.getSetAttribute ) {
// Use removeAttribute in browsers that support it
elem.removeAttribute( name );
} else {
jQuery.attr( elem, name, "" );
elem.removeAttributeNode( elem.getAttributeNode( name ) );
}
// Set corresponding property to false for boolean attributes
if ( rboolean.test( name ) && (propName = jQuery.propFix[ name ] || name) in elem ) {
elem[ propName ] = false;
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabIndex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return undefined;
}
var ret, hooks,
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// Try to normalize/fix the name
name = notxml && jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return (elem[ name ] = value);
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== undefined ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
return elem[ jQuery.propFix[ name ] || name ] ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = value;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// Use the value property for back compat
// Use the formHook for button elements in IE6/7 (#1954)
jQuery.attrHooks.value = {
get: function( elem, name ) {
if ( formHook && jQuery.nodeName( elem, "button" ) ) {
return formHook.get( elem, name );
}
return elem.value;
},
set: function( elem, value, name ) {
if ( formHook && jQuery.nodeName( elem, "button" ) ) {
return formHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !jQuery.support.getSetAttribute ) {
// propFix is more comprehensive and contains all fixes
jQuery.attrFix = jQuery.propFix;
// Use this for any attribute on a form in IE6/7
formHook = jQuery.attrHooks.name = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
// Return undefined if nodeValue is empty string
return ret && ret.nodeValue !== "" ?
ret.nodeValue :
undefined;
},
set: function( elem, value, name ) {
// Check form objects in IE (multiple bugs related)
// Only use nodeValue if the attribute node exists on the form
var ret = elem.getAttributeNode( name );
if ( ret ) {
ret.nodeValue = value;
return value;
}
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return (elem.style.cssText = "" + value);
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
}
});
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return (elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0);
}
}
});
});
var hasOwn = Object.prototype.hasOwnProperty,
rnamespaces = /\.(.*)$/,
rformElems = /^(?:textarea|input|select)$/i,
rperiod = /\./g,
rspaces = / /g,
rescape = /[^\w\s.|`]/g,
fcleanup = function( nm ) {
return nm.replace(rescape, "\\$&");
};
/*
* A number of helper functions used for managing events.
* Many of the ideas behind this code originated from
* Dean Edwards' addEvent library.
*/
jQuery.event = {
// Bind an event to an element
// Original by Dean Edwards
add: function( elem, types, handler, data ) {
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
if ( handler === false ) {
handler = returnFalse;
} else if ( !handler ) {
// Fixes bug #7229. Fix recommended by jdalton
return;
}
var handleObjIn, handleObj;
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
}
// Make sure that the function being executed has a unique ID
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure
var elemData = jQuery._data( elem );
// If no elemData is found then we must be trying to bind to one of the
// banned noData elements
if ( !elemData ) {
return;
}
var events = elemData.events,
eventHandle = elemData.handle;
if ( !events ) {
elemData.events = events = {};
}
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.handle.apply( eventHandle.elem, arguments ) :
undefined;
};
}
// Add elem as a property of the handle function
// This is to prevent a memory leak with non-native events in IE.
eventHandle.elem = elem;
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = types.split(" ");
var type, i = 0, namespaces;
while ( (type = types[ i++ ]) ) {
handleObj = handleObjIn ?
jQuery.extend({}, handleObjIn) :
{ handler: handler, data: data };
// Namespaced event handlers
if ( type.indexOf(".") > -1 ) {
namespaces = type.split(".");
type = namespaces.shift();
handleObj.namespace = namespaces.slice(0).sort().join(".");
} else {
namespaces = [];
handleObj.namespace = "";
}
handleObj.type = type;
if ( !handleObj.guid ) {
handleObj.guid = handler.guid;
}
// Get the current list of functions bound to this event
var handlers = events[ type ],
special = jQuery.event.special[ type ] || {};
// Init the event handler queue
if ( !handlers ) {
handlers = events[ type ] = [];
// Check for a special event handler
// Only use addEventListener/attachEvent if the special
// events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add the function to the element's handler list
handlers.push( handleObj );
// Keep track of which events have been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, pos ) {
// don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
if ( handler === false ) {
handler = returnFalse;
}
var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
events = elemData && elemData.events;
if ( !elemData || !events ) {
return;
}
// types is actually an event object here
if ( types && types.type ) {
handler = types.handler;
types = types.type;
}
// Unbind all events for the element
if ( !types || typeof types === "string" && types.charAt(0) === "." ) {
types = types || "";
for ( type in events ) {
jQuery.event.remove( elem, type + types );
}
return;
}
// Handle multiple events separated by a space
// jQuery(...).unbind("mouseover mouseout", fn);
types = types.split(" ");
while ( (type = types[ i++ ]) ) {
origType = type;
handleObj = null;
all = type.indexOf(".") < 0;
namespaces = [];
if ( !all ) {
// Namespaced event handlers
namespaces = type.split(".");
type = namespaces.shift();
namespace = new RegExp("(^|\\.)" +
jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
}
eventType = events[ type ];
if ( !eventType ) {
continue;
}
if ( !handler ) {
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( all || namespace.test( handleObj.namespace ) ) {
jQuery.event.remove( elem, origType, handleObj.handler, j );
eventType.splice( j--, 1 );
}
}
continue;
}
special = jQuery.event.special[ type ] || {};
for ( j = pos || 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( handler.guid === handleObj.guid ) {
// remove the given handler for the given type
if ( all || namespace.test( handleObj.namespace ) ) {
if ( pos == null ) {
eventType.splice( j--, 1 );
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
if ( pos != null ) {
break;
}
}
}
// remove generic event handler if no more handlers exist
if ( eventType.length === 0 || pos != null && eventType.length === 1 ) {
if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
ret = null;
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
var handle = elemData.handle;
if ( handle ) {
handle.elem = null;
}
delete elemData.events;
delete elemData.handle;
if ( jQuery.isEmptyObject( elemData ) ) {
jQuery.removeData( elem, undefined, true );
}
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Event object or event type
var type = event.type || event,
namespaces = [],
exclusive;
if ( type.indexOf("!") >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.exclusive = exclusive;
event.namespace = namespaces.join(".");
event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)");
// triggerHandler() and global events don't bubble or run the default action
if ( onlyHandlers || !elem ) {
event.preventDefault();
event.stopPropagation();
}
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
jQuery.each( jQuery.cache, function() {
// internalKey variable is just used to make it easier to find
// and potentially change this stuff later; currently it just
// points to jQuery.expando
var internalKey = jQuery.expando,
internalCache = this[ internalKey ];
if ( internalCache && internalCache.events && internalCache.events[ type ] ) {
jQuery.event.trigger( event, data, internalCache.handle.elem );
}
});
return;
}
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
event.target = elem;
// Clone any incoming data and prepend the event, creating the handler arg list
data = data ? jQuery.makeArray( data ) : [];
data.unshift( event );
var cur = elem,
// IE doesn't like method names with a colon (#3533, #8272)
ontype = type.indexOf(":") < 0 ? "on" + type : "";
// Fire event on the current element, then bubble up the DOM tree
do {
var handle = jQuery._data( cur, "handle" );
event.currentTarget = cur;
if ( handle ) {
handle.apply( cur, data );
}
// Trigger an inline bound script
if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) {
event.result = false;
event.preventDefault();
}
// Bubble up to document, then to window
cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window;
} while ( cur && !event.isPropagationStopped() );
// If nobody prevented the default action, do it now
if ( !event.isDefaultPrevented() ) {
var old,
special = jQuery.event.special[ type ] || {};
if ( (!special._default || special._default.call( elem.ownerDocument, event ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction)() check here because IE6/7 fails that test.
// IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch.
try {
if ( ontype && elem[ type ] ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
jQuery.event.triggered = type;
elem[ type ]();
}
} catch ( ieError ) {}
if ( old ) {
elem[ ontype ] = old;
}
jQuery.event.triggered = undefined;
}
}
return event.result;
},
handle: function( event ) {
event = jQuery.event.fix( event || window.event );
// Snapshot the handlers list since a called handler may add/remove events.
var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0),
run_all = !event.exclusive && !event.namespace,
args = Array.prototype.slice.call( arguments, 0 );
// Use the fix-ed Event rather than the (read-only) native event
args[0] = event;
event.currentTarget = this;
for ( var j = 0, l = handlers.length; j < l; j++ ) {
var handleObj = handlers[ j ];
// Triggered event must 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event.
if ( run_all || event.namespace_re.test( handleObj.namespace ) ) {
// Pass in a reference to the handler function itself
// So that we can later remove it
event.handler = handleObj.handler;
event.data = handleObj.data;
event.handleObj = handleObj;
var ret = handleObj.handler.apply( this, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
if ( event.isImmediatePropagationStopped() ) {
break;
}
}
}
return event.result;
},
props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// store a copy of the original event object
// and "clone" to set read-only properties
var originalEvent = event;
event = jQuery.Event( originalEvent );
for ( var i = this.props.length, prop; i; ) {
prop = this.props[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary
if ( !event.target ) {
// Fixes #1925 where srcElement might not be defined either
event.target = event.srcElement || document;
}
// check if target is a textnode (safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && event.fromElement ) {
event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
}
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && event.clientX != null ) {
var eventDocument = event.target.ownerDocument || document,
doc = eventDocument.documentElement,
body = eventDocument.body;
event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
}
// Add which for key events
if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
event.which = event.charCode != null ? event.charCode : event.keyCode;
}
// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
if ( !event.metaKey && event.ctrlKey ) {
event.metaKey = event.ctrlKey;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button !== undefined ) {
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
}
return event;
},
// Deprecated, use jQuery.guid instead
guid: 1E8,
// Deprecated, use jQuery.proxy instead
proxy: jQuery.proxy,
special: {
ready: {
// Make sure the ready event is setup
setup: jQuery.bindReady,
teardown: jQuery.noop
},
live: {
add: function( handleObj ) {
jQuery.event.add( this,
liveConvert( handleObj.origType, handleObj.selector ),
jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) );
},
remove: function( handleObj ) {
jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj );
}
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !this.preventDefault ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// timeStamp is buggy for some events on Firefox(#3843)
// So we won't rely on the native value
this.timeStamp = jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function( event ) {
// Check if mouse(over|out) are still within the same parent element
var parent = event.relatedTarget;
// set the correct event type
event.type = event.data;
// Firefox sometimes assigns relatedTarget a XUL element
// which we cannot access the parentNode property of
try {
// Chrome does something similar, the parentNode property
// can be accessed but is null.
if ( parent && parent !== document && !parent.parentNode ) {
return;
}
// Traverse up the tree
while ( parent && parent !== this ) {
parent = parent.parentNode;
}
if ( parent !== this ) {
// handle event if we actually just moused on to a non sub-element
jQuery.event.handle.apply( this, arguments );
}
// assuming we've left the element since we most likely mousedover a xul element
} catch(e) { }
},
// In case of event delegation, we only need to rename the event.type,
// liveHandler will take care of the rest.
delegate = function( event ) {
event.type = event.data;
jQuery.event.handle.apply( this, arguments );
};
// Create mouseenter and mouseleave events
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
setup: function( data ) {
jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig );
},
teardown: function( data ) {
jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement );
}
};
});
// submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function( data, namespaces ) {
if ( !jQuery.nodeName( this, "form" ) ) {
jQuery.event.add(this, "click.specialSubmit", function( e ) {
var elem = e.target,
type = elem.type;
if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
trigger( "submit", this, arguments );
}
});
jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
var elem = e.target,
type = elem.type;
if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
trigger( "submit", this, arguments );
}
});
} else {
return false;
}
},
teardown: function( namespaces ) {
jQuery.event.remove( this, ".specialSubmit" );
}
};
}
// change delegation, happens here so we have bind.
if ( !jQuery.support.changeBubbles ) {
var changeFilters,
getVal = function( elem ) {
var type = elem.type, val = elem.value;
if ( type === "radio" || type === "checkbox" ) {
val = elem.checked;
} else if ( type === "select-multiple" ) {
val = elem.selectedIndex > -1 ?
jQuery.map( elem.options, function( elem ) {
return elem.selected;
}).join("-") :
"";
} else if ( jQuery.nodeName( elem, "select" ) ) {
val = elem.selectedIndex;
}
return val;
},
testChange = function testChange( e ) {
var elem = e.target, data, val;
if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) {
return;
}
data = jQuery._data( elem, "_change_data" );
val = getVal(elem);
// the current data will be also retrieved by beforeactivate
if ( e.type !== "focusout" || elem.type !== "radio" ) {
jQuery._data( elem, "_change_data", val );
}
if ( data === undefined || val === data ) {
return;
}
if ( data != null || val ) {
e.type = "change";
e.liveFired = undefined;
jQuery.event.trigger( e, arguments[1], elem );
}
};
jQuery.event.special.change = {
filters: {
focusout: testChange,
beforedeactivate: testChange,
click: function( e ) {
var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) {
testChange.call( this, e );
}
},
// Change has to be called before submit
// Keydown will be called before keypress, which is used in submit-event delegation
keydown: function( e ) {
var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) ||
(e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
type === "select-multiple" ) {
testChange.call( this, e );
}
},
// Beforeactivate happens also before the previous element is blurred
// with this event you can't trigger a change event, but you can store
// information
beforeactivate: function( e ) {
var elem = e.target;
jQuery._data( elem, "_change_data", getVal(elem) );
}
},
setup: function( data, namespaces ) {
if ( this.type === "file" ) {
return false;
}
for ( var type in changeFilters ) {
jQuery.event.add( this, type + ".specialChange", changeFilters[type] );
}
return rformElems.test( this.nodeName );
},
teardown: function( namespaces ) {
jQuery.event.remove( this, ".specialChange" );
return rformElems.test( this.nodeName );
}
};
changeFilters = jQuery.event.special.change.filters;
// Handle when the input is .focus()'d
changeFilters.focus = changeFilters.beforeactivate;
}
function trigger( type, elem, args ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
// Don't pass args or remember liveFired; they apply to the donor event.
var event = jQuery.extend( {}, args[ 0 ] );
event.type = type;
event.originalEvent = {};
event.liveFired = undefined;
jQuery.event.handle.call( elem, event );
if ( event.isDefaultPrevented() ) {
args[ 0 ].preventDefault();
}
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0;
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
function handler( donor ) {
// Donor event is always a native one; fix it and switch its type.
// Let focusin/out handler cancel the donor focus/blur event.
var e = jQuery.event.fix( donor );
e.type = fix;
e.originalEvent = {};
jQuery.event.trigger( e, null, e.target );
if ( e.isDefaultPrevented() ) {
donor.preventDefault();
}
}
});
}
jQuery.each(["bind", "one"], function( i, name ) {
jQuery.fn[ name ] = function( type, data, fn ) {
var handler;
// Handle object literals
if ( typeof type === "object" ) {
for ( var key in type ) {
this[ name ](key, data, type[key], fn);
}
return this;
}
if ( arguments.length === 2 || data === false ) {
fn = data;
data = undefined;
}
if ( name === "one" ) {
handler = function( event ) {
jQuery( this ).unbind( event, handler );
return fn.apply( this, arguments );
};
handler.guid = fn.guid || jQuery.guid++;
} else {
handler = fn;
}
if ( type === "unload" && name !== "one" ) {
this.one( type, data, fn );
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.add( this[i], type, handler, data );
}
}
return this;
};
});
jQuery.fn.extend({
unbind: function( type, fn ) {
// Handle object literals
if ( typeof type === "object" && !type.preventDefault ) {
for ( var key in type ) {
this.unbind(key, type[key]);
}
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.remove( this[i], type, fn );
}
}
return this;
},
delegate: function( selector, types, data, fn ) {
return this.live( types, data, fn, selector );
},
undelegate: function( selector, types, fn ) {
if ( arguments.length === 0 ) {
return this.unbind( "live" );
} else {
return this.die( types, null, fn, selector );
}
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
var liveMap = {
focus: "focusin",
blur: "focusout",
mouseenter: "mouseover",
mouseleave: "mouseout"
};
jQuery.each(["live", "die"], function( i, name ) {
jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) {
var type, i = 0, match, namespaces, preType,
selector = origSelector || this.selector,
context = origSelector ? this : jQuery( this.context );
if ( typeof types === "object" && !types.preventDefault ) {
for ( var key in types ) {
context[ name ]( key, data, types[key], selector );
}
return this;
}
if ( name === "die" && !types &&
origSelector && origSelector.charAt(0) === "." ) {
context.unbind( origSelector );
return this;
}
if ( data === false || jQuery.isFunction( data ) ) {
fn = data || returnFalse;
data = undefined;
}
types = (types || "").split(" ");
while ( (type = types[ i++ ]) != null ) {
match = rnamespaces.exec( type );
namespaces = "";
if ( match ) {
namespaces = match[0];
type = type.replace( rnamespaces, "" );
}
if ( type === "hover" ) {
types.push( "mouseenter" + namespaces, "mouseleave" + namespaces );
continue;
}
preType = type;
if ( liveMap[ type ] ) {
types.push( liveMap[ type ] + namespaces );
type = type + namespaces;
} else {
type = (liveMap[ type ] || type) + namespaces;
}
if ( name === "live" ) {
// bind live handler
for ( var j = 0, l = context.length; j < l; j++ ) {
jQuery.event.add( context[j], "live." + liveConvert( type, selector ),
{ data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } );
}
} else {
// unbind live handler
context.unbind( "live." + liveConvert( type, selector ), fn );
}
}
return this;
};
});
function liveHandler( event ) {
var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
elems = [],
selectors = [],
events = jQuery._data( this, "events" );
// Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911)
if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) {
return;
}
if ( event.namespace ) {
namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
}
event.liveFired = this;
var live = events.live.slice(0);
for ( j = 0; j < live.length; j++ ) {
handleObj = live[j];
if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) {
selectors.push( handleObj.selector );
} else {
live.splice( j--, 1 );
}
}
match = jQuery( event.target ).closest( selectors, event.currentTarget );
for ( i = 0, l = match.length; i < l; i++ ) {
close = match[i];
for ( j = 0; j < live.length; j++ ) {
handleObj = live[j];
if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) {
elem = close.elem;
related = null;
// Those two events require additional checking
if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) {
event.type = handleObj.preType;
related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0];
// Make sure not to accidentally match a child element with the same selector
if ( related && jQuery.contains( elem, related ) ) {
related = elem;
}
}
if ( !related || related !== elem ) {
elems.push({ elem: elem, handleObj: handleObj, level: close.level });
}
}
}
}
for ( i = 0, l = elems.length; i < l; i++ ) {
match = elems[i];
if ( maxLevel && match.level > maxLevel ) {
break;
}
event.currentTarget = match.elem;
event.data = match.handleObj.data;
event.handleObj = match.handleObj;
ret = match.handleObj.origHandler.apply( match.elem, arguments );
if ( ret === false || event.isPropagationStopped() ) {
maxLevel = match.level;
if ( ret === false ) {
stop = false;
}
if ( event.isImmediatePropagationStopped() ) {
break;
}
}
}
return stop;
}
function liveConvert( type, selector ) {
return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&");
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
if ( jQuery.attrFn ) {
jQuery.attrFn[ name ] = true;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true,
rBackslash = /\\/g,
rNonWord = /\W/;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
var Sizzle = function( selector, context, results, seed ) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var m, set, checkSet, extra, ret, cur, pop, i,
prune = true,
contextXML = Sizzle.isXML( context ),
parts = [],
soFar = selector;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec( "" );
m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ?
Sizzle.filter( ret.expr, ret.set )[0] :
ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ?
Sizzle.filter( ret.expr, ret.set ) :
ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray( set );
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function( results ) {
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
Sizzle.matches = function( expr, set ) {
return Sizzle( expr, null, null, set );
};
Sizzle.matchesSelector = function( node, expr ) {
return Sizzle( expr, null, null, [node] ).length > 0;
};
Sizzle.find = function( expr, context, isXML ) {
var set;
if ( !expr ) {
return [];
}
for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
var match,
type = Expr.order[i];
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
var left = match[1];
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace( rBackslash, "" );
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( "*" ) :
[];
}
return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
while ( expr && set.length ) {
for ( var type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
var found, item,
filter = Expr.filter[ type ],
left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
var pass = not ^ !!found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw "Syntax error, unrecognized expression: " + msg;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function( elem ) {
return elem.getAttribute( "href" );
},
type: function( elem ) {
return elem.getAttribute( "type" );
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !rNonWord.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function( checkSet, part ) {
var elem,
isPartStr = typeof part === "string",
i = 0,
l = checkSet.length;
if ( isPartStr && !rNonWord.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
},
"~": function( checkSet, part, isXML ) {
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
}
},
find: {
ID: function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function( match, context ) {
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [],
results = context.getElementsByName( match[1] );
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function( match, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( match[1] );
}
}
},
preFilter: {
CLASS: function( match, curLoop, inplace, result, not, isXML ) {
match = " " + match[1].replace( rBackslash, "" ) + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function( match ) {
return match[1].replace( rBackslash, "" );
},
TAG: function( match, curLoop ) {
return match[1].replace( rBackslash, "" ).toLowerCase();
},
CHILD: function( match ) {
if ( match[1] === "nth" ) {
if ( !match[2] ) {
Sizzle.error( match[0] );
}
match[2] = match[2].replace(/^\+|\s*/g, '');
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
else if ( match[2] ) {
Sizzle.error( match[0] );
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
var name = match[1] = match[1].replace( rBackslash, "" );
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
// Handle if an un-quoted value was used
match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function( match, curLoop, inplace, result, not ) {
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function( match ) {
match.unshift( true );
return match;
}
},
filters: {
enabled: function( elem ) {
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function( elem ) {
return elem.disabled === true;
},
checked: function( elem ) {
return elem.checked === true;
},
selected: function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
parent: function( elem ) {
return !!elem.firstChild;
},
empty: function( elem ) {
return !elem.firstChild;
},
has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
},
header: function( elem ) {
return (/h\d/i).test( elem.nodeName );
},
text: function( elem ) {
var attr = elem.getAttribute( "type" ), type = elem.type;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
},
radio: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
},
checkbox: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
},
file: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
},
password: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
},
submit: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "submit" === elem.type;
},
image: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
},
reset: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "reset" === elem.type;
},
button: function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && "button" === elem.type || name === "button";
},
input: function( elem ) {
return (/input|select|textarea|button/i).test( elem.nodeName );
},
focus: function( elem ) {
return elem === elem.ownerDocument.activeElement;
}
},
setFilters: {
first: function( elem, i ) {
return i === 0;
},
last: function( elem, i, match, array ) {
return i === array.length - 1;
},
even: function( elem, i ) {
return i % 2 === 0;
},
odd: function( elem, i ) {
return i % 2 === 1;
},
lt: function( elem, i, match ) {
return i < match[3] - 0;
},
gt: function( elem, i, match ) {
return i > match[3] - 0;
},
nth: function( elem, i, match ) {
return match[3] - 0 === i;
},
eq: function( elem, i, match ) {
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function( elem, match, i, array ) {
var name = match[1],
filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( name );
}
},
CHILD: function( elem, match ) {
var type = match[1],
node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case "nth":
var first = match[2],
last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
var doneName = match[0],
parent = elem.parentNode;
if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
var count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent.sizcache = doneName;
}
var diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function( elem, match ) {
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function( elem, match ) {
return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
},
CLASS: function( elem, match ) {
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function( elem, match ) {
var name = match[1],
result = Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function( elem, match, i, array ) {
var name = match[2],
filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS,
fescape = function(all, num){
return "\\" + (num - 0 + 1);
};
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
var makeArray = function( array, results ) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch( e ) {
makeArray = function( array, results ) {
var i = 0,
ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Utility function for retreiving the text value of an array of DOM nodes
Sizzle.getText = function( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += Sizzle.getText( elem.childNodes );
}
}
return ret;
};
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("div"),
id = "script" + (new Date()).getTime(),
root = document.documentElement;
form.innerHTML = "<a name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( document.getElementById( id ) ) {
Expr.find.ID = function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ?
m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
[m] :
undefined :
[];
}
};
Expr.filter.ID = function( elem, match ) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
// release memory in IE
root = form = null;
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function( match, context ) {
var results = context.getElementsByTagName( match[1] );
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function( elem ) {
return elem.getAttribute( "href", 2 );
};
}
// release memory in IE
div = null;
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle,
div = document.createElement("div"),
id = "__sizzle__";
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function( query, context, extra, seed ) {
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
// See if we find a selector to speed up
var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
// Speed-up: Sizzle("TAG")
if ( match[1] ) {
return makeArray( context.getElementsByTagName( query ), extra );
// Speed-up: Sizzle(".CLASS")
} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
return makeArray( context.getElementsByClassName( match[2] ), extra );
}
}
if ( context.nodeType === 9 ) {
// Speed-up: Sizzle("body")
// The body element only exists once, optimize finding it
if ( query === "body" && context.body ) {
return makeArray( [ context.body ], extra );
// Speed-up: Sizzle("#ID")
} else if ( match && match[3] ) {
var elem = context.getElementById( match[3] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id === match[3] ) {
return makeArray( [ elem ], extra );
}
} else {
return makeArray( [], extra );
}
}
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var oldContext = context,
old = context.getAttribute( "id" ),
nid = old || id,
hasParent = context.parentNode,
relativeHierarchySelector = /^\s*[+~]/.test( query );
if ( !old ) {
context.setAttribute( "id", nid );
} else {
nid = nid.replace( /'/g, "\\$&" );
}
if ( relativeHierarchySelector && hasParent ) {
context = context.parentNode;
}
try {
if ( !relativeHierarchySelector || hasParent ) {
return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
}
} catch(pseudoError) {
} finally {
if ( !old ) {
oldContext.removeAttribute( "id" );
}
}
}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
// release memory in IE
div = null;
})();
}
(function(){
var html = document.documentElement,
matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
if ( matches ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9 fails this)
var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
pseudoWorks = false;
try {
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( document.documentElement, "[test!='']:sizzle" );
} catch( pseudoError ) {
pseudoWorks = true;
}
Sizzle.matchesSelector = function( node, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
if ( !Sizzle.isXML( node ) ) {
try {
if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
var ret = matches.call( node, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || !disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9, so check for that
node.document && node.document.nodeType !== 11 ) {
return ret;
}
}
} catch(e) {}
}
return Sizzle(expr, null, null, [node]).length > 0;
};
}
})();
(function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function( match, context, isXML ) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
// release memory in IE
div = null;
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem.sizcache = doneName;
elem.sizset = i;
}
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem.sizcache = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
if ( document.documentElement.contains ) {
Sizzle.contains = function( a, b ) {
return a !== b && (a.contains ? a.contains(b) : true);
};
} else if ( document.documentElement.compareDocumentPosition ) {
Sizzle.contains = function( a, b ) {
return !!(a.compareDocumentPosition(b) & 16);
};
} else {
Sizzle.contains = function() {
return false;
};
}
Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function( selector, context ) {
var match,
tmpSet = [],
later = "",
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})();
var runtil = /Until$/,
rparentsprev = /^(?:parents|prevUntil|prevAll)/,
// Note: This RegExp should be improved, or likely pulled from Sizzle
rmultiselector = /,/,
isSimple = /^.[^:#\[\.,]*$/,
slice = Array.prototype.slice,
POS = jQuery.expr.match.POS,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var self = this,
i, l;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
var ret = this.pushStack( "", "find", selector ),
length, n, r;
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var targets = jQuery( target );
return this.filter(function() {
for ( var i = 0, l = targets.length; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && ( typeof selector === "string" ?
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var ret = [], i, l, cur = this[0];
// Array
if ( jQuery.isArray( selectors ) ) {
var match, selector,
matches = {},
level = 1;
if ( cur && selectors.length ) {
for ( i = 0, l = selectors.length; i < l; i++ ) {
selector = selectors[i];
if ( !matches[ selector ] ) {
matches[ selector ] = POS.test( selector ) ?
jQuery( selector, context || this.context ) :
selector;
}
}
while ( cur && cur.ownerDocument && cur !== context ) {
for ( selector in matches ) {
match = matches[ selector ];
if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) {
ret.push({ selector: selector, elem: cur, level: level });
}
}
cur = cur.parentNode;
level++;
}
}
return ret;
}
// String
var pos = POS.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i];
while ( cur ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
} else {
cur = cur.parentNode;
if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
break;
}
}
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
if ( !elem || typeof elem === "string" ) {
return jQuery.inArray( this[0],
// If it receives a string, the selector is used
// If it receives nothing, the siblings are used
elem ? jQuery( elem ) : this.parent().children() );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
andSelf: function() {
return this.add( this.prevObject );
}
});
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return jQuery.nth( elem, 2, "nextSibling" );
},
prev: function( elem ) {
return jQuery.nth( elem, 2, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( elem.parentNode.firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.makeArray( elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until ),
// The variable 'args' was introduced in
// https://github.com/jquery/jquery/commit/52a0238
// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
// http://code.google.com/p/v8/issues/detail?id=1050
args = slice.call(arguments);
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, args.join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
nth: function( cur, result, dir, elem ) {
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] ) {
if ( cur.nodeType === 1 && ++num === result ) {
break;
}
}
return cur;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return (elem === qualifier) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return (jQuery.inArray( elem, qualifier ) >= 0) === keep;
});
}
var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnocache = /<(?:script|object|embed|option|style)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
};
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "div<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( text ) {
if ( jQuery.isFunction(text) ) {
return this.each(function(i) {
var self = jQuery( this );
self.text( text.call(this, i, self.text()) );
});
}
if ( typeof text !== "object" && text !== undefined ) {
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
}
return jQuery.text( this );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
return this.each(function() {
jQuery( this ).wrapAll( html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
} else if ( arguments.length ) {
var set = jQuery(arguments[0]);
set.push.apply( set, this.toArray() );
return this.pushStack( set, "before", arguments );
}
},
after: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
} else if ( arguments.length ) {
var set = this.pushStack( this, "after", arguments );
set.push.apply( set, jQuery(arguments[0]).toArray() );
return set;
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
if ( value === undefined ) {
return this[0] && this[0].nodeType === 1 ?
this[0].innerHTML.replace(rinlinejQuery, "") :
null;
// See if we can take a shortcut and just use innerHTML
} else if ( typeof value === "string" && !rnocache.test( value ) &&
(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
value = value.replace(rxhtmlTag, "<$1></$2>");
try {
for ( var i = 0, l = this.length; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
if ( this[i].nodeType === 1 ) {
jQuery.cleanData( this[i].getElementsByTagName("*") );
this[i].innerHTML = value;
}
}
// If using innerHTML throws an exception, use the fallback method
} catch(e) {
this.empty().append( value );
}
} else if ( jQuery.isFunction( value ) ) {
this.each(function(i){
var self = jQuery( this );
self.html( value.call(this, i, self.html()) );
});
} else {
this.empty().append( value );
}
return this;
},
replaceWith: function( value ) {
if ( this[0] && this[0].parentNode ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
} else {
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
}
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
var results, first, fragment, parent,
value = args[0],
scripts = [];
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback, true );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call(this, i, table ? self.html() : undefined);
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
parent = value && value.parentNode;
// If we're in a fragment, just use that instead of building a new one
if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
results = { fragment: parent };
} else {
results = jQuery.buildFragment( args, this, scripts );
}
fragment = results.fragment;
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
first = fragment.firstChild;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
// Make sure that we do not leak memory by inadvertently discarding
// the original fragment (which might have attached data) instead of
// using it; in addition, use the original fragment object for the last
// item instead of first because it can end up being emptied incorrectly
// in certain situations (Bug #8070).
// Fragments from the fragment cache must always be cloned and never used
// in place.
results.cacheable || (l > 1 && i < lastIndex) ?
jQuery.clone( fragment, true, true ) :
fragment
);
}
}
if ( scripts.length ) {
jQuery.each( scripts, evalScript );
}
}
return this;
}
});
function root( elem, cur ) {
return jQuery.nodeName(elem, "table") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var internalKey = jQuery.expando,
oldData = jQuery.data( src ),
curData = jQuery.data( dest, oldData );
// Switch to use the internal data object, if it exists, for the next
// stage of data copying
if ( (oldData = oldData[ internalKey ]) ) {
var events = oldData.events;
curData = curData[ internalKey ] = jQuery.extend({}, oldData);
if ( events ) {
delete curData.handle;
curData.events = {};
for ( var type in events ) {
for ( var i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data );
}
}
}
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 fail to clone children inside object elements that use
// the proprietary classid attribute value (rather than the type
// attribute) to identify the type of content to display
if ( nodeName === "object" ) {
dest.outerHTML = src.outerHTML;
} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
if ( src.checked ) {
dest.defaultChecked = dest.checked = src.checked;
}
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults,
doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ args[0] ];
if ( cacheresults && cacheresults !== 1 ) {
fragment = cacheresults;
}
}
if ( !fragment ) {
fragment = doc.createDocumentFragment();
jQuery.clean( args, doc, fragment, scripts );
}
if ( cacheable ) {
jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( "getElementsByTagName" in elem ) {
return elem.getElementsByTagName( "*" );
} else if ( "querySelectorAll" in elem ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( elem.type === "checkbox" || elem.type === "radio" ) {
elem.defaultChecked = elem.checked;
}
}
// Finds all inputs and passes them to fixDefaultChecked
function findInputs( elem ) {
if ( jQuery.nodeName( elem, "input" ) ) {
fixDefaultChecked( elem );
} else if ( elem.getElementsByTagName ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var clone = elem.cloneNode(true),
srcElements,
destElements,
i;
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName
// instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var checkScriptType;
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if ( typeof context.createElement === "undefined" ) {
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
}
var ret = [], j;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Trim whitespace, otherwise indexOf won't work as expected
var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
wrap = wrapMap[ tag ] || wrapMap._default,
depth = wrap[0],
div = context.createElement("div");
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
var hasBody = rtbody.test(elem),
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
}
}
// Resets defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
var len;
if ( !jQuery.support.appendChecked ) {
if ( elem[0] && typeof (len = elem.length) === "number" ) {
for ( j = 0; j < len; j++ ) {
findInputs( elem[j] );
}
} else {
findInputs( elem );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
ret = jQuery.merge( ret, elem );
}
}
if ( fragment ) {
checkScriptType = function( elem ) {
return !elem.type || rscriptType.test( elem.type );
};
for ( i = 0; ret[i]; i++ ) {
if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
} else {
if ( ret[i].nodeType === 1 ) {
var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType );
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
}
fragment.appendChild( ret[i] );
}
}
}
return ret;
},
cleanData: function( elems ) {
var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
continue;
}
id = elem[ jQuery.expando ];
if ( id ) {
data = cache[ id ] && cache[ id ][ internalKey ];
if ( data && data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
// Null the DOM reference to avoid IE6/7/8 leak (#7054)
if ( data.handle ) {
data.handle.elem = null;
}
}
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
delete cache[ id ];
}
}
}
});
function evalScript( i, elem ) {
if ( elem.src ) {
jQuery.ajax({
url: elem.src,
async: false,
dataType: "script"
});
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
var ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
rdashAlpha = /-([a-z])/ig,
// fixed for IE9, see #8346
rupper = /([A-Z]|^ms)/g,
rnumpx = /^-?\d+(?:px)?$/i,
rnum = /^-?\d/,
rrelNum = /^[+\-]=/,
rrelNumFilter = /[^+\-\.\de]+/g,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssWidth = [ "Left", "Right" ],
cssHeight = [ "Top", "Bottom" ],
curCSS,
getComputedStyle,
currentStyle,
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn.css = function( name, value ) {
// Setting 'undefined' is a no-op
if ( arguments.length === 2 && value === undefined ) {
return this;
}
return jQuery.access( this, name, value, true, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
});
};
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity", "opacity" );
return ret === "" ? "1" : ret;
} else {
return elem.style.opacity;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"zIndex": true,
"fontWeight": true,
"opacity": true,
"zoom": true,
"lineHeight": true,
"widows": true,
"orphans": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, origName = jQuery.camelCase( name ),
style = elem.style, hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// Make sure that NaN and null values aren't set. See: #7116
if ( type === "number" && isNaN( value ) || value == null ) {
return;
}
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && rrelNum.test( value ) ) {
value = +value.replace( rrelNumFilter, "" ) + parseFloat( jQuery.css( elem, name ) );
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra ) {
var ret, hooks;
// Make sure that we're working with the right name
name = jQuery.camelCase( name );
hooks = jQuery.cssHooks[ name ];
name = jQuery.cssProps[ name ] || name;
// cssFloat needs a special treatment
if ( name === "cssFloat" ) {
name = "float";
}
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
return ret;
// Otherwise, if a way to get the computed value exists, use that
} else if ( curCSS ) {
return curCSS( elem, name );
}
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var old = {};
// Remember the old values, and insert the new ones
for ( var name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
},
camelCase: function( string ) {
return string.replace( rdashAlpha, fcamelCase );
}
});
// DEPRECATED, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;
jQuery.each(["height", "width"], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
var val;
if ( computed ) {
if ( elem.offsetWidth !== 0 ) {
val = getWH( elem, name, extra );
} else {
jQuery.swap( elem, cssShow, function() {
val = getWH( elem, name, extra );
});
}
if ( val <= 0 ) {
val = curCSS( elem, name, name );
if ( val === "0px" && currentStyle ) {
val = currentStyle( elem, name, name );
}
if ( val != null ) {
// Should return "auto" instead of 0, use 0 for
// temporary backwards-compat
return val === "" || val === "auto" ? "0px" : val;
}
}
if ( val < 0 || val == null ) {
val = elem.style[ name ];
// Should return "auto" instead of 0, use 0 for
// temporary backwards-compat
return val === "" || val === "auto" ? "0px" : val;
}
return typeof val === "string" ? val : val + "px";
}
},
set: function( elem, value ) {
if ( rnumpx.test( value ) ) {
// ignore negative width and height values #1599
value = parseFloat(value);
if ( value >= 0 ) {
return value + "px";
}
} else {
return value;
}
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( parseFloat( RegExp.$1 ) / 100 ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle;
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// Set the alpha filter to set the opacity
var opacity = jQuery.isNaN( value ) ?
"" :
"alpha(opacity=" + value * 100 + ")",
filter = currentStyle && currentStyle.filter || style.filter || "";
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery(function() {
// This hook cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
var ret;
jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
ret = curCSS( elem, "margin-right", "marginRight" );
} else {
ret = elem.style.marginRight;
}
});
return ret;
}
};
}
});
if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, name ) {
var ret, defaultView, computedStyle;
name = name.replace( rupper, "-$1" ).toLowerCase();
if ( !(defaultView = elem.ownerDocument.defaultView) ) {
return undefined;
}
if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) {
ret = computedStyle.getPropertyValue( name );
if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
ret = jQuery.style( elem, name );
}
}
return ret;
};
}
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
var left,
ret = elem.currentStyle && elem.currentStyle[ name ],
rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ],
style = elem.style;
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
// Remember the original values
left = style.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : (ret || 0);
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
curCSS = getComputedStyle || currentStyle;
function getWH( elem, name, extra ) {
var which = name === "width" ? cssWidth : cssHeight,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight;
if ( extra === "border" ) {
return val;
}
jQuery.each( which, function() {
if ( !extra ) {
val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0;
}
if ( extra === "margin" ) {
val += parseFloat(jQuery.css( elem, "margin" + this )) || 0;
} else {
val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0;
}
});
return val;
}
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
var width = elem.offsetWidth,
height = elem.offsetHeight;
return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rselectTextarea = /^(?:select|textarea)/i,
rspacesAjax = /\s+/,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Document location
ajaxLocation,
// Document location segments
ajaxLocParts;
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
if ( jQuery.isFunction( func ) ) {
var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
i = 0,
length = dataTypes.length,
dataType,
list,
placeBefore;
// For each dataType in the dataTypeExpression
for(; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters ),
selection;
for(; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
jQuery.fn.extend({
load: function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf( " " );
if ( off >= 0 ) {
var selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
// Complete callback (responseText is used internally)
complete: function( jqXHR, status, responseText ) {
// Store the response as specified by the jqXHR object
responseText = jqXHR.responseText;
// If successful, inject the HTML into all the matched elements
if ( jqXHR.isResolved() ) {
// #4825: Get the actual response in case
// a dataFilter is present in ajaxSettings
jqXHR.done(function( r ) {
responseText = r;
});
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
responseText );
}
if ( callback ) {
self.each( callback, [ responseText, status, jqXHR ] );
}
}
});
return this;
},
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.bind( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function ( target, settings ) {
if ( !settings ) {
// Only one parameter, we extend ajaxSettings
settings = target;
target = jQuery.extend( true, jQuery.ajaxSettings, settings );
} else {
// target was provided, we extend into it
jQuery.extend( true, target, jQuery.ajaxSettings, settings );
}
// Flatten fields we don't want deep extended
for( var field in { context: 1, url: 1 } ) {
if ( field in settings ) {
target[ field ] = settings[ field ];
} else if( field in jQuery.ajaxSettings ) {
target[ field ] = jQuery.ajaxSettings[ field ];
}
}
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": "*/*"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery._Deferred(),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// ifModified key
ifModifiedKey,
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// The jqXHR state
state = 0,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || "abort";
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, statusText, responses, headers ) {
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status ? 4 : 0;
var isSuccess,
success,
error,
response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
lastModified,
etag;
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
jQuery.lastModified[ ifModifiedKey ] = lastModified;
}
if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
jQuery.etag[ ifModifiedKey ] = etag;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
try {
success = ajaxConvert( s, response );
statusText = "success";
isSuccess = true;
} catch(e) {
// We have a parsererror
statusText = "parsererror";
error = e;
}
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = statusText;
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.done;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.then( tmp, tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
// Determine if a cross-domain request is in order
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefiler, stop there
if ( state === 2 ) {
return false;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already
jqXHR.abort();
return false;
}
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( status < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
jQuery.error( e );
}
}
}
return jqXHR;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : value;
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
}
});
function buildParams( prefix, obj, traditional, add ) {
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && obj != null && typeof obj === "object" ) {
// Serialize object item.
for ( var name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields,
ct,
type,
finalDataType,
firstDataType;
// Fill responseXXX fields
for( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
var dataTypes = s.dataTypes,
converters = {},
i,
key,
length = dataTypes.length,
tmp,
// Current and previous dataTypes
current = dataTypes[ 0 ],
prev,
// Conversion expression
conversion,
// Conversion function
conv,
// Conversion functions (transitive conversion)
conv1,
conv2;
// For each dataType in the chain
for( i = 1; i < length; i++ ) {
// Create converters map
// with lowercased keys
if ( i === 1 ) {
for( key in s.converters ) {
if( typeof key === "string" ) {
converters[ key.toLowerCase() ] = s.converters[ key ];
}
}
}
// Get the dataTypes
prev = current;
current = dataTypes[ i ];
// If current is auto dataType, update it to prev
if( current === "*" ) {
current = prev;
// If no auto and dataTypes are actually different
} else if ( prev !== "*" && prev !== current ) {
// Get the converter
conversion = prev + " " + current;
conv = converters[ conversion ] || converters[ "* " + current ];
// If there is no direct converter, search transitively
if ( !conv ) {
conv2 = undefined;
for( conv1 in converters ) {
tmp = conv1.split( " " );
if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
conv2 = converters[ tmp[1] + " " + current ];
if ( conv2 ) {
conv1 = converters[ conv1 ];
if ( conv1 === true ) {
conv = conv2;
} else if ( conv2 === true ) {
conv = conv1;
}
break;
}
}
}
}
// If we found no converter, dispatch an error
if ( !( conv || conv2 ) ) {
jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
}
// If found converter is not an equivalence
if ( conv !== true ) {
// Convert with 1 or 2 converters accordingly
response = conv ? conv( response ) : conv2( conv1(response) );
}
}
}
return response;
}
var jsc = jQuery.now(),
jsre = /(\=)\?(&|$)|\?\?/i;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
return jQuery.expando + "_" + ( jsc++ );
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var inspectData = s.contentType === "application/x-www-form-urlencoded" &&
( typeof s.data === "string" );
if ( s.dataTypes[ 0 ] === "jsonp" ||
s.jsonp !== false && ( jsre.test( s.url ) ||
inspectData && jsre.test( s.data ) ) ) {
var responseContainer,
jsonpCallback = s.jsonpCallback =
jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
previous = window[ jsonpCallback ],
url = s.url,
data = s.data,
replace = "$1" + jsonpCallback + "$2";
if ( s.jsonp !== false ) {
url = url.replace( jsre, replace );
if ( s.url === url ) {
if ( inspectData ) {
data = data.replace( jsre, replace );
}
if ( s.data === data ) {
// Add callback manually
url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
}
}
}
s.url = url;
s.data = data;
// Install callback
window[ jsonpCallback ] = function( response ) {
responseContainer = [ response ];
};
// Clean-up function
jqXHR.always(function() {
// Set callback back to previous value
window[ jsonpCallback ] = previous;
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( previous ) ) {
window[ jsonpCallback ]( responseContainer[ 0 ] );
}
});
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( jsonpCallback + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var // #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0,
xhrCallbacks;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var xhr = s.xhr(),
handle,
i;
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occured
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
responses.text = xhr.responseText;
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
// if we're in sync mode or it's in cache
// and has been retrieved directly (IE6 & IE7)
// we need to manually fire the callback
if ( !s.async || xhr.readyState === 4 ) {
callback();
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var elemdisplay = {},
iframe, iframeDoc,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
],
fxNow,
requestAnimationFrame = window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame;
jQuery.fn.extend({
show: function( speed, easing, callback ) {
var elem, display;
if ( speed || speed === 0 ) {
return this.animate( genFx("show", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = elem.style.display;
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
display = elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( display === "" && jQuery.css( elem, "display" ) === "none" ) {
jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName));
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = elem.style.display;
if ( display === "" || display === "none" ) {
elem.style.display = jQuery._data(elem, "olddisplay") || "";
}
}
}
return this;
}
},
hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
if ( this[i].style ) {
var display = jQuery.css( this[i], "display" );
if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) {
jQuery._data( this[i], "olddisplay", display );
}
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
if ( this[i].style ) {
this[i].style.display = "none";
}
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2, callback ) {
var bool = typeof fn === "boolean";
if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
this._toggle.apply( this, arguments );
} else if ( fn == null || bool ) {
this.each(function() {
var state = bool ? fn : jQuery(this).is(":hidden");
jQuery(this)[ state ? "show" : "hide" ]();
});
} else {
this.animate(genFx("toggle", 3), fn, fn2, callback);
}
return this;
},
fadeTo: function( speed, to, easing, callback ) {
return this.filter(":hidden").css("opacity", 0).show().end()
.animate({opacity: to}, speed, easing, callback);
},
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed(speed, easing, callback);
if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete, [ false ] );
}
// Do not change referenced properties as per-property easing will be lost
prop = jQuery.extend( {}, prop );
return this[ optall.queue === false ? "each" : "queue" ](function() {
// XXX 'this' does not always have a nodeName when running the
// test suite
if ( optall.queue === false ) {
jQuery._mark( this );
}
var opt = jQuery.extend( {}, optall ),
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
name, val, p,
display, e,
parts, start, end, unit;
// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties = {};
for ( p in prop ) {
// property name normalization
name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
}
val = prop[ name ];
// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
if ( jQuery.isArray( val ) ) {
opt.animatedProperties[ name ] = val[ 1 ];
val = prop[ name ] = val[ 0 ];
} else {
opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
}
if ( val === "hide" && hidden || val === "show" && !hidden ) {
return opt.complete.call( this );
}
if ( isElement && ( name === "height" || name === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height
// animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
if ( !jQuery.support.inlineBlockNeedsLayout ) {
this.style.display = "inline-block";
} else {
display = defaultDisplay( this.nodeName );
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( display === "inline" ) {
this.style.display = "inline-block";
} else {
this.style.display = "inline";
this.style.zoom = 1;
}
}
}
}
}
if ( opt.overflow != null ) {
this.style.overflow = "hidden";
}
for ( p in prop ) {
e = new jQuery.fx( this, opt, p );
val = prop[ p ];
if ( rfxtypes.test(val) ) {
e[ val === "toggle" ? hidden ? "show" : "hide" : val ]();
} else {
parts = rfxnum.exec( val );
start = e.cur();
if ( parts ) {
end = parseFloat( parts[2] );
unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( this, p, (end || 1) + unit);
start = ((end || 1) / e.cur()) * start;
jQuery.style( this, p, start + unit);
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) {
end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
}
e.custom( start, end, unit );
} else {
e.custom( start, val, "" );
}
}
}
// For JS strict compliance
return true;
});
},
stop: function( clearQueue, gotoEnd ) {
if ( clearQueue ) {
this.queue([]);
}
this.each(function() {
var timers = jQuery.timers,
i = timers.length;
// clear marker counters if we know they won't be
if ( !gotoEnd ) {
jQuery._unmark( true, this );
}
while ( i-- ) {
if ( timers[i].elem === this ) {
if (gotoEnd) {
// force the next step to be the last
timers[i](true);
}
timers.splice(i, 1);
}
}
});
// start the next in the queue if the last step wasn't forced
if ( !gotoEnd ) {
this.dequeue();
}
return this;
}
});
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout( clearFxNow, 0 );
return ( fxNow = jQuery.now() );
}
function clearFxNow() {
fxNow = undefined;
}
// Generate parameters to create a standard animation
function genFx( type, num ) {
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() {
obj[ this ] = type;
});
return obj;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show", 1),
slideUp: genFx("hide", 1),
slideToggle: genFx("toggle", 1),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.extend({
speed: function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default;
// Queueing
opt.old = opt.complete;
opt.complete = function( noUnmark ) {
if ( opt.queue !== false ) {
jQuery.dequeue( this );
} else if ( noUnmark !== false ) {
jQuery._unmark( this );
}
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
};
return opt;
},
easing: {
linear: function( p, n, firstNum, diff ) {
return firstNum + diff * p;
},
swing: function( p, n, firstNum, diff ) {
return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
}
},
timers: [],
fx: function( elem, options, prop ) {
this.options = options;
this.elem = elem;
this.prop = prop;
options.orig = options.orig || {};
}
});
jQuery.fx.prototype = {
// Simple function for setting a style value
update: function() {
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
(jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
},
// Get the current size
cur: function() {
if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
return this.elem[ this.prop ];
}
var parsed,
r = jQuery.css( this.elem, this.prop );
// Empty strings, null, undefined and "auto" are converted to 0,
// complex values such as "rotate(1rad)" are returned as is,
// simple values such as "10px" are parsed to Float.
return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
},
// Start an animation from one number to another
custom: function( from, to, unit ) {
var self = this,
fx = jQuery.fx,
raf;
this.startTime = fxNow || createFxNow();
this.start = from;
this.end = to;
this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
this.now = this.start;
this.pos = this.state = 0;
function t( gotoEnd ) {
return self.step(gotoEnd);
}
t.elem = this.elem;
if ( t() && jQuery.timers.push(t) && !timerId ) {
// Use requestAnimationFrame instead of setInterval if available
if ( requestAnimationFrame ) {
timerId = 1;
raf = function() {
// When timerId gets set to null at any point, this stops
if ( timerId ) {
requestAnimationFrame( raf );
fx.tick();
}
};
requestAnimationFrame( raf );
} else {
timerId = setInterval( fx.tick, fx.interval );
}
}
},
// Simple 'show' function
show: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
this.options.show = true;
// Begin the animation
// Make sure that we start at a small width/height to avoid any
// flash of content
this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur());
// Start by showing the element
jQuery( this.elem ).show();
},
// Simple 'hide' function
hide: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
this.options.hide = true;
// Begin the animation
this.custom(this.cur(), 0);
},
// Each step of an animation
step: function( gotoEnd ) {
var t = fxNow || createFxNow(),
done = true,
elem = this.elem,
options = this.options,
i, n;
if ( gotoEnd || t >= options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
options.animatedProperties[ this.prop ] = true;
for ( i in options.animatedProperties ) {
if ( options.animatedProperties[i] !== true ) {
done = false;
}
}
if ( done ) {
// Reset the overflow
if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
jQuery.each( [ "", "X", "Y" ], function (index, value) {
elem.style[ "overflow" + value ] = options.overflow[index];
});
}
// Hide the element if the "hide" operation was done
if ( options.hide ) {
jQuery(elem).hide();
}
// Reset the properties, if the item has been hidden or shown
if ( options.hide || options.show ) {
for ( var p in options.animatedProperties ) {
jQuery.style( elem, p, options.orig[p] );
}
}
// Execute the complete function
options.complete.call( elem );
}
return false;
} else {
// classical easing cannot be used with an Infinity duration
if ( options.duration == Infinity ) {
this.now = t;
} else {
n = t - this.startTime;
this.state = n / options.duration;
// Perform the easing function, defaults to swing
this.pos = jQuery.easing[ options.animatedProperties[ this.prop ] ]( this.state, n, 0, 1, options.duration );
this.now = this.start + ((this.end - this.start) * this.pos);
}
// Perform the next step of the animation
this.update();
}
return true;
}
};
jQuery.extend( jQuery.fx, {
tick: function() {
for ( var timers = jQuery.timers, i = 0 ; i < timers.length ; ++i ) {
if ( !timers[i]() ) {
timers.splice(i--, 1);
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
},
interval: 13,
stop: function() {
clearInterval( timerId );
timerId = null;
},
speeds: {
slow: 600,
fast: 200,
// Default speed
_default: 400
},
step: {
opacity: function( fx ) {
jQuery.style( fx.elem, "opacity", fx.now );
},
_default: function( fx ) {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit;
} else {
fx.elem[ fx.prop ] = fx.now;
}
}
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
// Try to restore the default display value of an element
function defaultDisplay( nodeName ) {
if ( !elemdisplay[ nodeName ] ) {
var elem = jQuery( "<" + nodeName + ">" ).appendTo( "body" ),
display = elem.css( "display" );
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// No iframe to use yet, so create it
if ( !iframe ) {
iframe = document.createElement( "iframe" );
iframe.frameBorder = iframe.width = iframe.height = 0;
}
document.body.appendChild( iframe );
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake html
// document to it, Webkit & Firefox won't allow reusing the iframe document
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write( "<!doctype><html><body></body></html>" );
}
elem = iframeDoc.createElement( nodeName );
iframeDoc.body.appendChild( elem );
display = jQuery.css( elem, "display" );
document.body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return elemdisplay[ nodeName ];
}
var rtable = /^t(?:able|d|h)$/i,
rroot = /^(?:body|html)$/i;
if ( "getBoundingClientRect" in document.documentElement ) {
jQuery.fn.offset = function( options ) {
var elem = this[0], box;
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
try {
box = elem.getBoundingClientRect();
} catch(e) {}
var doc = elem.ownerDocument,
docElem = doc.documentElement;
// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
}
var body = doc.body,
win = getWindow(doc),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: top, left: left };
};
} else {
jQuery.fn.offset = function( options ) {
var elem = this[0];
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
jQuery.offset.initialize();
var computedStyle,
offsetParent = elem.offsetParent,
prevOffsetParent = elem,
doc = elem.ownerDocument,
docElem = doc.documentElement,
body = doc.body,
defaultView = doc.defaultView,
prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
top = elem.offsetTop,
left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
break;
}
computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
top -= elem.scrollTop;
left -= elem.scrollLeft;
if ( elem === offsetParent ) {
top += elem.offsetTop;
left += elem.offsetLeft;
if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevOffsetParent = offsetParent;
offsetParent = elem.offsetParent;
}
if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevComputedStyle = computedStyle;
}
if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
top += body.offsetTop;
left += body.offsetLeft;
}
if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
top += Math.max( docElem.scrollTop, body.scrollTop );
left += Math.max( docElem.scrollLeft, body.scrollLeft );
}
return { top: top, left: left };
};
}
jQuery.offset = {
initialize: function() {
var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0,
html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } );
container.innerHTML = html;
body.insertBefore( container, body.firstChild );
innerDiv = container.firstChild;
checkDiv = innerDiv.firstChild;
td = innerDiv.nextSibling.firstChild.firstChild;
this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
this.doesAddBorderForTableAndCells = (td.offsetTop === 5);
checkDiv.style.position = "fixed";
checkDiv.style.top = "20px";
// safari subtracts parent border width here which is 5px
this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15);
checkDiv.style.position = checkDiv.style.top = "";
innerDiv.style.overflow = "hidden";
innerDiv.style.position = "relative";
this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);
this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop);
body.removeChild( container );
jQuery.offset.initialize = jQuery.noop;
},
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
jQuery.offset.initialize();
if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = (position === "absolute" || position === "fixed") && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if (options.top != null) {
props.top = (options.top - curOffset.top) + curTop;
}
if (options.left != null) {
props.left = (options.left - curOffset.left) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return null;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( ["Left", "Top"], function( i, name ) {
var method = "scroll" + name;
jQuery.fn[ method ] = function( val ) {
var elem, win;
if ( val === undefined ) {
elem = this[ 0 ];
if ( !elem ) {
return null;
}
win = getWindow( elem );
// Return the scroll offset
return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ method ] :
elem[ method ];
}
// Set the scroll offset
return this.each(function() {
win = getWindow( this );
if ( win ) {
win.scrollTo(
!i ? val : jQuery( win ).scrollLeft(),
i ? val : jQuery( win ).scrollTop()
);
} else {
this[ method ] = val;
}
});
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function( i, name ) {
var type = name.toLowerCase();
// innerHeight and innerWidth
jQuery.fn["inner" + name] = function() {
return this[0] ?
parseFloat( jQuery.css( this[0], type, "padding" ) ) :
null;
};
// outerHeight and outerWidth
jQuery.fn["outer" + name] = function( margin ) {
return this[0] ?
parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) :
null;
};
jQuery.fn[ type ] = function( size ) {
// Get window width or height
var elem = this[0];
if ( !elem ) {
return size == null ? null : this;
}
if ( jQuery.isFunction( size ) ) {
return this.each(function( i ) {
var self = jQuery( this );
self[ type ]( size.call( this, i, self[ type ]() ) );
});
}
if ( jQuery.isWindow( elem ) ) {
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
var docElemProp = elem.document.documentElement[ "client" + name ];
return elem.document.compatMode === "CSS1Compat" && docElemProp ||
elem.document.body[ "client" + name ] || docElemProp;
// Get document width or height
} else if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
return Math.max(
elem.documentElement["client" + name],
elem.body["scroll" + name], elem.documentElement["scroll" + name],
elem.body["offset" + name], elem.documentElement["offset" + name]
);
// Get or set width or height on the element
} else if ( size === undefined ) {
var orig = jQuery.css( elem, type ),
ret = parseFloat( orig );
return jQuery.isNaN( ret ) ? orig : ret;
// Set the width or height on the element (default to pixels if value is unitless)
} else {
return this.css( type, typeof size === "string" ? size : size + "px" );
}
};
});
window.jQuery = window.$ = jQuery;
})(window); | JavaScript |
<!--
/*
Screw - A jQuery plugin
==================================================================
©2010-2011 JasonLau.biz - Version 1.0.1
==================================================================
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
(function($){
$.fn.extend({
screw: function(options) {
var defaults = {
loadingHTML : 'Loading ... '
}
var option = $.extend(defaults, options);
var obj = $(this);
return this.each(function() {
$(window).scroll(function() {
screwIt($(this));
});
var screwIt = function(it){
var h = $(window).height(), st = it.scrollTop(), t = h+st;
$(".screw-image").each(function(){
var pos = $(this).offset(), rand = Math.round(Math.random()*1000);
if(t >= pos.top){
if(!$(this).hasClass('screw-loaded')){
$(this).html('<div id="screw-loading-' + rand + '">' + option.loadingHTML + '</div>');
// Stop cache
var url = $(this).attr('rel'), patt = /&/g;
if(patt.test(url)){
url += '&screw_rand=' + rand;
} else {
url += '?screw_rand=' + rand;
}
// Preload image
objImage = new Image();
objImage.src = url;
var o = $(this);
objImage.onload = function(){
o.append('<img style="display:none" id="screw-content-' + rand + '" class="screw-content" src="' + url + '" />');
$('#screw-loading-' + rand).fadeOut('slow', function(){
$('#screw-content-' + rand).fadeIn('slow');
o.addClass('screw-loaded');
});
};
}
}
});
$(".screw").each(function(){
var pos = $(this).offset(), rand = Math.round(Math.random()*1000);
if(t >= pos.top){
if(!$(this).hasClass('screw-loaded') || $(this).hasClass('screw-repeat')){
var o = $(this);
if(option.loadingHTML){
o.html('<div id="screw-loading-' + rand + '">' + option.loadingHTML + '</div>');
}
if(o.hasClass('screw-append')){
if($(this).attr('rel')){
$.get($(this).attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) {
o.append('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + data + '</div>');
showContent(rand);
});
} else if($(this).attr('rev')){
o.append('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + $(this).attr('rev') + '</div>');
showContent(rand);
}
} else if(o.hasClass('screw-prepend')){
if($(this).attr('rel')){
$.get($(this).attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) {
o.prepend('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + data + '</div>');
showContent(rand);
});
} else if($(this).attr('rev')){
o.prepend('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + $(this).attr('rev') + '</div>');
showContent(rand);
}
} else if(o.hasClass('screw-before')){
if($(this).attr('rel')){
$.get($(this).attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) {
o.before('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + data + '</div>');
showContent(rand);
});
} else if($(this).attr('rev')){
o.before('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + $(this).attr('rev') + '</div>');
showContent(rand);
}
if(o.hasClass('screw-repeat') && pos.top < $(window).height()){
if($(this).attr('rel')){
$.get($(this).attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) {
o.before('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + data + '</div>');
showContent(rand);
});
} else if($(this).attr('rev')){
o.before('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + $(this).attr('rev') + '</div>');
showContent(rand);
}
}
} else if(o.hasClass('screw-after')){
if($(this).attr('rel')){
$.get($(this).attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) {
o.after('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + data + '</div>');
showContent(rand);
});
} else if($(this).attr('rev')){
o.after('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + $(this).attr('rev') + '</div>');
showContent(rand);
}
} else {
if($(this).attr('rel')){
$.get($(this).attr('rel'), { screwrand : Math.round(Math.random()*1000) }, function(data) {
o.append('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + data + '</div>');
showContent(rand);
});
} else if($(this).attr('rev')){
o.append('<div style="display:none" id="screw-content-' + rand + '" class="screw-content">' + $(this).attr('rev') + '</div>');
showContent(rand);
}
}
o.addClass('screw-loaded');
}
}
});
};
var showContent = function(rand){
if(option.loadingHTML){
$('#screw-loading-' + rand).fadeOut('slow', function(){
$('#screw-content-' + rand).fadeIn('slow');
});
} else {
$('#screw-content-' + rand).fadeIn('slow');
}
};
screwIt($(window));
});
}
});
})(jQuery);
--> | JavaScript |
jQuery(document).ready(function($){
function evaluate(){
var item = $(this);
var relatedItem = $('.checktoshow');
if(item.is(":checked")){
relatedItem.fadeIn();
}else{
relatedItem.fadeOut();
}
}
$('#wp_ulike_style').click(evaluate).each(evaluate);
$('.my-color-field').wpColorPicker();
}); | JavaScript |
//socket javascript
// jQuery(document).ready(function()
// {
// jQuery(".count-box").click(function()
// {
// jQuery("#liked_users").stop().slideToggle(500);
// });
// });
function likeThis(e, l, s) {
"" != e && (jQuery("#wp-ulike-" + e + " .counter").html('<a class="loading"></a><span class="count-box">...</span>'), jQuery.ajax({
type: "POST",
url: ulike_obj.ajaxurl,
data: {
action: "ulikeprocess",
id: e
},
success: function(a) {
l + s == 1 ? jQuery("#wp-ulike-" + e + " .counter").html("<a id='like_button' onclick='likeThis(" + e + ",1,1)' class='text'>" + ulike_obj.likeText + "</a><span class='count-box'>" + a + "</span>") : l + s == 2 ? jQuery("#wp-ulike-" + e + " .counter").html("<a onclick='likeThis(" + e + ",1,0)' class='text'>" + ulike_obj.disLikeText + "</a><span class='count-box'>" + a + "</span>") : l + s == 3 && jQuery("#wp-ulike-" + e + " .counter").html("<a class='text user-tooltip' title='Already Voted'>" + ulike_obj.likeText + "</a><span class='count-box'>" + a + "</span>")
}
}));
var actor_id =ulike_obj.current_user_id;
jQuery.ajax({
type: "POST",
url: ulike_obj.ajaxurl,
data: {
action: "like_clicked",
actor_id: actor_id,
image_id:e,
notification_type:"like",
like_status:s
},
success: function(data) {
var json = JSON.parse(data);
// var myWindow = window.open("", "MsgWindow", "width=1000, height=1000");
// myWindow.document.write(json.receiver_id);
if(ulike_obj.current_user_id==json.receiver_id) return;//neu nguoi kich hoat la nguoi nhan thi thoat
var msg = {
receiver_id: json.receiver_id,
type:'like'
}
wsocket.send(JSON.stringify(msg));
}
});
//gui thong tin di
}
if (! function(t) {
"use strict";
var e = function(t, e) {
this.init("tooltip", t, e)
};
e.prototype = {
constructor: e,
init: function(e, i, n) {
var o, s, r, a, l;
for (this.type = e, this.$element = t(i), this.options = this.getOptions(n), this.enabled = !0, r = this.options.trigger.split(" "), l = r.length; l--;) a = r[l], "click" == a ? this.$element.on("click." + this.type, this.options.selector, t.proxy(this.toggle, this)) : "manual" != a && (o = "hover" == a ? "mouseenter" : "focus", s = "hover" == a ? "mouseleave" : "blur", this.$element.on(o + "." + this.type, this.options.selector, t.proxy(this.enter, this)), this.$element.on(s + "." + this.type, this.options.selector, t.proxy(this.leave, this)));
this.options.selector ? this._options = t.extend({}, this.options, {
trigger: "manual",
selector: ""
}) : this.fixTitle()
},
getOptions: function(e) {
return e = t.extend({}, t.fn[this.type].defaults, this.$element.data(), e), e.delay && "number" == typeof e.delay && (e.delay = {
show: e.delay,
hide: e.delay
}), e
},
enter: function(e) {
var i, n = t.fn[this.type].defaults,
o = {};
return this._options && t.each(this._options, function(t, e) {
n[t] != e && (o[t] = e)
}, this), i = t(e.currentTarget)[this.type](o).data(this.type), i.options.delay && i.options.delay.show ? (clearTimeout(this.timeout), i.hoverState = "in", void(this.timeout = setTimeout(function() {
"in" == i.hoverState && i.show()
}, i.options.delay.show))) : i.show()
},
leave: function(e) {
var i = t(e.currentTarget)[this.type](this._options).data(this.type);
return this.timeout && clearTimeout(this.timeout), i.options.delay && i.options.delay.hide ? (i.hoverState = "out", void(this.timeout = setTimeout(function() {
"out" == i.hoverState && i.hide()
}, i.options.delay.hide))) : i.hide()
},
show: function() {
var e, i, n, o, s, r, a = t.Event("show");
if (this.hasContent() && this.enabled) {
if (this.$element.trigger(a), a.isDefaultPrevented()) return;
switch (e = this.tip(), this.setContent(), this.options.animation && e.addClass("fade"), s = "function" == typeof this.options.placement ? this.options.placement.call(this, e[0], this.$element[0]) : this.options.placement, e.detach().css({
top: 0,
left: 0,
display: "block"
}), this.options.container ? e.appendTo(this.options.container) : e.insertAfter(this.$element), i = this.getPosition(), n = e[0].offsetWidth, o = e[0].offsetHeight, s) {
case "bottom":
r = {
top: i.top + i.height,
left: i.left + i.width / 2 - n / 2
};
break;
case "top":
r = {
top: i.top - o,
left: i.left + i.width / 2 - n / 2
};
break;
case "left":
r = {
top: i.top + i.height / 2 - o / 2,
left: i.left - n
};
break;
case "right":
r = {
top: i.top + i.height / 2 - o / 2,
left: i.left + i.width
}
}
this.applyPlacement(r, s), this.$element.trigger("shown")
}
},
applyPlacement: function(t, e) {
var i, n, o, s, r = this.tip(),
a = r[0].offsetWidth,
l = r[0].offsetHeight;
r.offset(t).addClass(e).addClass("in"), i = r[0].offsetWidth, n = r[0].offsetHeight, "top" == e && n != l && (t.top = t.top + l - n, s = !0), "bottom" == e || "top" == e ? (o = 0, t.left < 0 && (o = -2 * t.left, t.left = 0, r.offset(t), i = r[0].offsetWidth, n = r[0].offsetHeight), this.replaceArrow(o - a + i, i, "left")) : this.replaceArrow(n - l, n, "top"), s && r.offset(t)
},
replaceArrow: function(t, e, i) {
this.arrow().css(i, t ? 50 * (1 - t / e) + "%" : "")
},
setContent: function() {
var t = this.tip(),
e = this.getTitle();
t.find(".tooltip-inner")[this.options.html ? "html" : "text"](e), t.removeClass("fade in top bottom left right")
},
hide: function() {
function e() {
var e = setTimeout(function() {
i.off(t.support.transition.end).detach()
}, 500);
i.one(t.support.transition.end, function() {
clearTimeout(e), i.detach()
})
}
var i = this.tip(),
n = t.Event("hide");
return this.$element.trigger(n), n.isDefaultPrevented() ? void 0 : (i.removeClass("in"), t.support.transition && this.$tip.hasClass("fade") ? e() : i.detach(), this.$element.trigger("hidden"), this)
},
fixTitle: function() {
var t = this.$element;
(t.attr("title") || "string" != typeof t.attr("data-original-title")) && t.attr("data-original-title", t.attr("title") || "").attr("title", "")
},
hasContent: function() {
return this.getTitle()
},
getPosition: function() {
var e = this.$element[0];
return t.extend({}, "function" == typeof e.getBoundingClientRect ? e.getBoundingClientRect() : {
width: e.offsetWidth,
height: e.offsetHeight
}, this.$element.offset())
},
getTitle: function() {
var t, e = this.$element,
i = this.options;
return t = e.attr("data-original-title") || ("function" == typeof i.title ? i.title.call(e[0]) : i.title)
},
tip: function() {
return this.$tip = this.$tip || t(this.options.template)
},
arrow: function() {
return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow")
},
validate: function() {
this.$element[0].parentNode || (this.hide(), this.$element = null, this.options = null)
},
enable: function() {
this.enabled = !0
},
disable: function() {
this.enabled = !1
},
toggleEnabled: function() {
this.enabled = !this.enabled
},
toggle: function(e) {
var i = e ? t(e.currentTarget)[this.type](this._options).data(this.type) : this;
i.tip().hasClass("in") ? i.hide() : i.show()
},
destroy: function() {
this.hide().$element.off("." + this.type).removeData(this.type)
}
};
var i = t.fn.tooltip;
t.fn.tooltip = function(i) {
return this.each(function() {
var n = t(this),
o = n.data("tooltip"),
s = "object" == typeof i && i;
o || n.data("tooltip", o = new e(this, s)), "string" == typeof i && o[i]()
})
}, t.fn.tooltip.Constructor = e, t.fn.tooltip.defaults = {
animation: !0,
placement: "top",
selector: !1,
template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: "hover focus",
title: "",
delay: 0,
html: !1,
container: !1
}, t.fn.tooltip.noConflict = function() {
return t.fn.tooltip = i, this
}
}(window.jQuery), "undefined" == typeof jQuery) throw new Error("WP Ulike's JavaScript requires jQuery");
if (+ function(t) {
"use strict";
function e() {
var t = document.createElement("bootstrap"),
e = {
WebkitTransition: "webkitTransitionEnd",
MozTransition: "transitionend",
OTransition: "oTransitionEnd otransitionend",
transition: "transitionend"
};
for (var i in e)
if (void 0 !== t.style[i]) return {
end: e[i]
};
return !1
}
t.fn.emulateTransitionEnd = function(e) {
var i = !1,
n = this;
t(this).one("bsTransitionEnd", function() {
i = !0
});
var o = function() {
i || t(n).trigger(t.support.transition.end)
};
return setTimeout(o, e), this
}, t(function() {
t.support.transition = e(), t.support.transition && (t.event.special.bsTransitionEnd = {
bindType: t.support.transition.end,
delegateType: t.support.transition.end,
handle: function(e) {
return t(e.target).is(this) ? e.handleObj.handler.apply(this, arguments) : void 0
}
})
})
}(jQuery), "undefined" == typeof jQuery) throw new Error("WP Ulike's JavaScript requires jQuery"); + function(t) {
"use strict";
function e(e) {
return this.each(function() {
var i = t(this),
o = i.data("bs.alert");
o || i.data("bs.alert", o = new n(this)), "string" == typeof e && o[e].call(i)
})
}
var i = '[data-dismiss="alert"]',
n = function(e) {
t(e).on("click", i, this.close)
};
n.VERSION = "3.2.0", n.prototype.close = function(e) {
function i() {
s.detach().trigger("closed.bs.alert").remove()
}
var n = t(this),
o = n.attr("data-target");
o || (o = n.attr("href"), o = o && o.replace(/.*(?=#[^\s]*$)/, ""));
var s = t(o);
e && e.preventDefault(), s.length || (s = n.hasClass("alert") ? n : n.parent()), s.trigger(e = t.Event("close.bs.alert")), e.isDefaultPrevented() || (s.removeClass("in"), t.support.transition && s.hasClass("fade") ? s.one("bsTransitionEnd", i).emulateTransitionEnd(150) : i())
};
var o = t.fn.alert;
t.fn.alert = e, t.fn.alert.Constructor = n, t.fn.alert.noConflict = function() {
return t.fn.alert = o, this
}, t(document).on("click.bs.alert.data-api", i, n.prototype.close)
}(jQuery), jQuery(document).ready(function(t) {
t(".user-tooltip").tooltip()
});
| JavaScript |
function wppb_insertAtCursor(myField,value) {
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = value;
}
//MOZILLA/NETSCAPE support
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ value
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += value;
}
}
function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
function wppb_replaceSelection (input, replaceString) {
if (input.setSelectionRange) {
var selectionStart = input.selectionStart;
var selectionEnd = input.selectionEnd;
input.value = input.value.substring(0, selectionStart)+ replaceString + input.value.substring(selectionEnd);
if (selectionStart != selectionEnd){
setSelectionRange(input, selectionStart, selectionStart + replaceString.length);
}else{
setSelectionRange(input, selectionStart + replaceString.length, selectionStart + replaceString.length);
}
}else if (document.selection) {
var range = document.selection.createRange();
if (range.parentElement() == input) {
var isCollapsed = range.text == '';
range.text = replaceString;
if (!isCollapsed) {
range.moveStart('character', -replaceString.length);
range.select();
}
}
}
}
// We are going to catch the TAB key so that we can use it, Hooray!
function wppb_catchTab(item,e){
if(navigator.userAgent.match("Gecko")){
c=e.which;
}else{
c=e.keyCode;
}
if(c==9){
wppb_replaceSelection(item,String.fromCharCode(9));
setTimeout("document.getElementById('"+item.id+"').focus();",0);
return false;
}
} | JavaScript |
/*
Original Plugin Name: OptionTree
Original Plugin URI: http://wp.envato.com
Original Author: Derek Herman
Original Author URI: http://valendesigns.com
*/
/**
* TableDnD plug-in for JQuery, allows you to drag and drop table rows
* You can set up various options to control how the system will work
* Copyright (c) Denis Howlett <denish@isocra.com>
* Licensed like jQuery, see http://docs.jquery.com/License.
*
* Configuration options:
*
* onDragStyle
* This is the style that is assigned to the row during drag. There are limitations to the styles that can be
* associated with a row (such as you can't assign a border--well you can, but it won't be
* displayed). (So instead consider using onDragClass.) The CSS style to apply is specified as
* a map (as used in the jQuery css(...) function).
* onDropStyle
* This is the style that is assigned to the row when it is dropped. As for onDragStyle, there are limitations
* to what you can do. Also this replaces the original style, so again consider using onDragClass which
* is simply added and then removed on drop.
* onDragClass
* This class is added for the duration of the drag and then removed when the row is dropped. It is more
* flexible than using onDragStyle since it can be inherited by the row cells and other content. The default
* is class is tDnD_whileDrag. So to use the default, simply customise this CSS class in your
* stylesheet.
* onDrop
* Pass a function that will be called when the row is dropped. The function takes 2 parameters: the table
* and the row that was dropped. You can work out the new order of the rows by using
* table.rows.
* onDragStart
* Pass a function that will be called when the user starts dragging. The function takes 2 parameters: the
* table and the row which the user has started to drag.
* onAllowDrop
* Pass a function that will be called as a row is over another row. If the function returns true, allow
* dropping on that row, otherwise not. The function takes 2 parameters: the dragged row and the row under
* the cursor. It returns a boolean: true allows the drop, false doesn't allow it.
* scrollAmount
* This is the number of pixels to scroll if the user moves the mouse cursor to the top or bottom of the
* window. The page should automatically scroll up or down as appropriate (tested in IE6, IE7, Safari, FF2,
* FF3 beta
* dragHandle
* This is the name of a class that you assign to one or more cells in each row that is draggable. If you
* specify this class, then you are responsible for setting cursor: move in the CSS and only these cells
* will have the drag behaviour. If you do not specify a dragHandle, then you get the old behaviour where
* the whole row is draggable.
*
* Other ways to control behaviour:
*
* Add class="nodrop" to any rows for which you don't want to allow dropping, and class="nodrag" to any rows
* that you don't want to be draggable.
*
* Inside the onDrop method you can also call $.tableDnD.serialize() this returns a string of the form
* <tableID>[]=<rowID1>&<tableID>[]=<rowID2> so that you can send this back to the server. The table must have
* an ID as must all the rows.
*
* Other methods:
*
* $("...").tableDnDUpdate()
* Will update all the matching tables, that is it will reapply the mousedown method to the rows (or handle cells).
* This is useful if you have updated the table rows using Ajax and you want to make the table draggable again.
* The table maintains the original configuration (so you don't have to specify it again).
*
* $("...").tableDnDSerialize()
* Will serialize and return the serialized string as above, but for each of the matching tables--so it can be
* called from anywhere and isn't dependent on the currentTable being set up correctly before calling
*
* Known problems:
* - Auto-scoll has some problems with IE7 (it scrolls even when it shouldn't), work-around: set scrollAmount to 0
*
* Version 0.2: 2008-02-20 First public version
* Version 0.3: 2008-02-07 Added onDragStart option
* Made the scroll amount configurable (default is 5 as before)
* Version 0.4: 2008-03-15 Changed the noDrag/noDrop attributes to nodrag/nodrop classes
* Added onAllowDrop to control dropping
* Fixed a bug which meant that you couldn't set the scroll amount in both directions
* Added serialize method
* Version 0.5: 2008-05-16 Changed so that if you specify a dragHandle class it doesn't make the whole row
* draggable
* Improved the serialize method to use a default (and settable) regular expression.
* Added tableDnDupate() and tableDnDSerialize() to be called when you are outside the table
*/
jQuery.tableDnD = {
/** Keep hold of the current table being dragged */
currentTable : null,
/** Keep hold of the current drag object if any */
dragObject: null,
/** The current mouse offset */
mouseOffset: null,
/** Remember the old value of Y so that we don't do too much processing */
oldY: 0,
/** Actually build the structure */
build: function(options) {
// Set up the defaults if any
this.each(function() {
// This is bound to each matching table, set up the defaults and override with user options
this.tableDnDConfig = jQuery.extend({
onDragStyle: null,
onDropStyle: null,
// Add in the default class for whileDragging
onDragClass: "tDnD_whileDrag",
onDrop: null,
onDragStart: null,
scrollAmount: 5,
serializeRegexp: /[^\-]*$/, // The regular expression to use to trim row IDs
serializeParamName: null, // If you want to specify another parameter name instead of the table ID
dragHandle: null // If you give the name of a class here, then only Cells with this class will be draggable
}, options || {});
// Now make the rows draggable
jQuery.tableDnD.makeDraggable(this);
});
// Now we need to capture the mouse up and mouse move event
// We can use bind so that we don't interfere with other event handlers
jQuery(document)
.bind('mousemove', jQuery.tableDnD.mousemove)
.bind('mouseup', jQuery.tableDnD.mouseup);
// Don't break the chain
return this;
},
/** This function makes all the rows on the table draggable apart from those marked as "NoDrag" */
makeDraggable: function(table) {
var config = table.tableDnDConfig;
if (table.tableDnDConfig.dragHandle) {
// We only need to add the event to the specified cells
var cells = jQuery("td."+table.tableDnDConfig.dragHandle, table);
cells.each(function() {
// The cell is bound to "this"
jQuery(this).mousedown(function(ev) {
jQuery.tableDnD.dragObject = this.parentNode;
jQuery.tableDnD.currentTable = table;
jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
if (config.onDragStart) {
// Call the onDrop method if there is one
config.onDragStart(table, this);
}
return false;
});
})
} else {
// For backwards compatibility, we add the event to the whole row
var rows = jQuery("tr", table); // get all the rows as a wrapped set
rows.each(function() {
// Iterate through each row, the row is bound to "this"
var row = jQuery(this);
if (! row.hasClass("nodrag")) {
row.mousedown(function(ev) {
if (ev.target.tagName == "TD") {
jQuery.tableDnD.dragObject = this;
jQuery.tableDnD.currentTable = table;
jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
if (config.onDragStart) {
// Call the onDrop method if there is one
config.onDragStart(table, this);
}
return false;
}
}).css("cursor", "move"); // Store the tableDnD object
}
});
}
},
updateTables: function() {
this.each(function() {
// this is now bound to each matching table
if (this.tableDnDConfig) {
jQuery.tableDnD.makeDraggable(this);
}
})
},
/** Get the mouse coordinates from the event (allowing for browser differences) */
mouseCoords: function(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
},
/** Given a target element and a mouse event, get the mouse offset from that element.
To do this we need the element's position and the mouse position */
getMouseOffset: function(target, ev) {
ev = ev || window.event;
var docPos = this.getPosition(target);
var mousePos = this.mouseCoords(ev);
return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
},
/** Get the position of an element by going up the DOM tree and adding up all the offsets */
getPosition: function(e){
var left = 0;
var top = 0;
/** Safari fix -- thanks to Luis Chato for this! */
if (e.offsetHeight == 0) {
/** Safari 2 doesn't correctly grab the offsetTop of a table row
this is detailed here:
http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/
the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild.
note that firefox will return a text node as a first child, so designing a more thorough
solution may need to take that into account, for now this seems to work in firefox, safari, ie */
e = e.firstChild; // a table cell
}
while (e.offsetParent){
left += e.offsetLeft;
top += e.offsetTop;
e = e.offsetParent;
}
left += e.offsetLeft;
top += e.offsetTop;
return {x:left, y:top};
},
mousemove: function(ev) {
if (jQuery.tableDnD.dragObject == null) {
return;
}
var dragObj = jQuery(jQuery.tableDnD.dragObject);
var config = jQuery.tableDnD.currentTable.tableDnDConfig;
var mousePos = jQuery.tableDnD.mouseCoords(ev);
var y = mousePos.y - jQuery.tableDnD.mouseOffset.y;
//auto scroll the window
var yOffset = window.pageYOffset;
if (document.all) {
// Windows version
//yOffset=document.body.scrollTop;
if (typeof document.compatMode != 'undefined' &&
document.compatMode != 'BackCompat') {
yOffset = document.documentElement.scrollTop;
}
else if (typeof document.body != 'undefined') {
yOffset=document.body.scrollTop;
}
}
if (mousePos.y-yOffset < config.scrollAmount) {
window.scrollBy(0, -config.scrollAmount);
} else {
var windowHeight = window.innerHeight ? window.innerHeight
: document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
if (windowHeight-(mousePos.y-yOffset) < config.scrollAmount) {
window.scrollBy(0, config.scrollAmount);
}
}
if (y != jQuery.tableDnD.oldY) {
// work out if we're going up or down...
var movingDown = y > jQuery.tableDnD.oldY;
// update the old value
jQuery.tableDnD.oldY = y;
// update the style to show we're dragging
if (config.onDragClass) {
dragObj.addClass(config.onDragClass);
} else {
dragObj.css(config.onDragStyle);
}
// If we're over a row then move the dragged row to there so that the user sees the
// effect dynamically
var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y);
if (currentRow) {
// TODO worry about what happens when there are multiple TBODIES
if (movingDown && jQuery.tableDnD.dragObject != currentRow) {
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling);
} else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) {
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow);
}
}
}
return false;
},
/** We're only worried about the y position really, because we can only move rows up and down */
findDropTargetRow: function(draggedRow, y) {
var rows = jQuery.tableDnD.currentTable.rows;
for (var i=0; i<rows.length; i++) {
var row = rows[i];
var rowY = this.getPosition(row).y;
var rowHeight = parseInt(row.offsetHeight)/2;
if (row.offsetHeight == 0) {
rowY = this.getPosition(row.firstChild).y;
rowHeight = parseInt(row.firstChild.offsetHeight)/2;
}
// Because we always have to insert before, we need to offset the height a bit
if ((y > rowY - rowHeight) && (y < (rowY + rowHeight + rowHeight))) {
// that's the row we're over
// If it's the same as the current row, ignore it
if (row == draggedRow) {return null;}
var config = jQuery.tableDnD.currentTable.tableDnDConfig;
if (config.onAllowDrop) {
if (config.onAllowDrop(draggedRow, row)) {
return row;
} else {
return null;
}
} else {
// If a row has nodrop class, then don't allow dropping (inspired by John Tarr and Famic)
var nodrop = jQuery(row).hasClass("nodrop");
if (! nodrop) {
return row;
} else {
return null;
}
}
return row;
}
}
return null;
},
mouseup: function(e) {
if (jQuery.tableDnD.currentTable && jQuery.tableDnD.dragObject) {
var droppedRow = jQuery.tableDnD.dragObject;
var config = jQuery.tableDnD.currentTable.tableDnDConfig;
// If we have a dragObject, then we need to release it,
// The row will already have been moved to the right place so we just reset stuff
if (config.onDragClass) {
jQuery(droppedRow).removeClass(config.onDragClass);
} else {
jQuery(droppedRow).css(config.onDropStyle);
}
jQuery.tableDnD.dragObject = null;
if (config.onDrop) {
// Call the onDrop method if there is one
config.onDrop(jQuery.tableDnD.currentTable, droppedRow);
}
jQuery.tableDnD.currentTable = null; // let go of the table too
}
},
serialize: function() {
if (jQuery.tableDnD.currentTable) {
return jQuery.tableDnD.serializeTable(jQuery.tableDnD.currentTable);
} else {
return "Error: No Table id set, you need to set an id on your table and every row";
}
},
serializeTable: function(table) {
var result = "";
var tableId = table.id;
var rows = table.rows;
for (var i=0; i<rows.length; i++) {
if (result.length > 0) result += "&";
var rowId = rows[i].id;
if (rowId && rowId && table.tableDnDConfig && table.tableDnDConfig.serializeRegexp) {
rowId = rowId.match(table.tableDnDConfig.serializeRegexp)[0];
}
result += tableId + '[]=' + rowId;
}
return result;
},
serializeTables: function() {
var result = "";
this.each(function() {
// this is now bound to each matching table
result += jQuery.tableDnD.serializeTable(this);
});
return result;
}
}
jQuery.fn.extend(
{
tableDnD : jQuery.tableDnD.build,
tableDnDUpdate : jQuery.tableDnD.updateTables,
tableDnDSerialize: jQuery.tableDnD.serializeTables
}
); | JavaScript |
jQuery(function(){
//hover states on the static widgets
jQuery('#dialog_link, ul#icons li').hover(
function() { jQuery(this).addClass('ui-state-hover'); },
function() { jQuery(this).removeClass('ui-state-hover'); }
);
});
/* initialize datepicker */
jQuery(function(){
// Datepicker
jQuery('.wppb_datepicker').datepicker({
inline: true,
changeMonth: true,
changeYear: true
});
}); | JavaScript |
/**
*
* Delay
*
* Creates a way to delay events
* Dependencies: jQuery
*
*/
/*
Original Plugin Name: OptionTree
Original Plugin URI: http://wp.envato.com
Original Author: Derek Herman
Original Author URI: http://valendesigns.com
*/
(function ($) {
$.fn.delay = function(time,func){
return this.each(function(){
setTimeout(func,time);
});
};
})(jQuery);
/**
*
* Center AJAX
*
* Creates a way to center the AJAX message
* Dependencies: jQuery
*
*/
(function ($) {
$.fn.ajaxMessage = function(html){
if (html) {
return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').html(html).delay(3000, function(){$('.ajax-message').fadeOut()});
} else {
return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').delay(3000, function(){$('.ajax-message').fadeOut()});
}
};
})(jQuery);
/**
*
* Style File
*
* Creates a way to cover file input with a better styled version
* Dependencies: jQuery
*
*/
(function ($) {
styleFile = {
init: function () {
$('input.file').each(function(){
var uploadbutton = '<input class="upload_file_button" type="button" value="Upload" />';
$(this).wrap('<div class="file_wrap" />');
$(this).addClass('file').css('opacity', 0); //set to invisible
$(this).parent().append($('<div class="fake_file" />').append($('<input type="text" class="upload" />').attr('id',$(this).attr('id')+'_file')).append(uploadbutton));
$(this).bind('change', function() {
$('#'+$(this).attr('id')+'_file').val($(this).val());;
});
$(this).bind('mouseout', function() {
$('#'+$(this).attr('id')+'_file').val($(this).val());;
});
});
}
};
$(document).ready(function () {
styleFile.init()
})
})(jQuery);
/**
*
* Style Select
*
* Replace Select text
* Dependencies: jQuery
*
*/
(function ($) {
styleSelect = {
init: function () {
$('.select_wrapper').each(function () {
$(this).prepend('<span>' + $(this).find('.select option:selected').text() + '</span>');
});
$('.select').live('change', function () {
$(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>');
});
$('.select').bind($.browser.msie ? 'click' : 'change', function(event) {
$(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>');
});
}
};
$(document).ready(function () {
styleSelect.init()
})
})(jQuery);
/**
*
* Activate Tabs
*
* Tab style UI toggle
* Dependencies: jQuery, jQuery UI Core, jQuery UI Tabs
*
*/
(function ($) {
activateTabs = {
init: function () {
// Activate
$("#options_tabs").tabs();
// Append Toggle Button
$('.top-info').append('<a href="" class="toggle_tabs">Tabs</a>');
// Toggle Tabs
$('.toggle_tabs').toggle(function() {
$("#options_tabs").tabs('destroy');
$(this).addClass('off');
}, function() {
$("#options_tabs").tabs();
$(this).removeClass('off');
});
}
};
$(document).ready(function () {
activateTabs.init()
})
})(jQuery);
/**
*
* Upload Option
*
* Allows window.send_to_editor to function properly using a private post_id
* Dependencies: jQuery, Media Upload, Thickbox
*
*/
(function ($) {
uploadOption = {
init: function () {
var formfield,
formID,
btnContent = true;
// On Click
$('.upload_button').live("click", function () {
formfield = $(this).prev('input').attr('name');
formID = $(this).attr('rel');
tb_show('', 'media-upload.php?post_id='+formID+'&type=image&TB_iframe=1');
return false;
});
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function(html) {
if (formfield) {
itemurl = $(html).attr('href');
var image = /(^.*\.jpg|jpeg|png|gif|ico*)/gi;
var document = /(^.*\.pdf|doc|docx|ppt|pptx|odt*)/gi;
var audio = /(^.*\.mp3|m4a|ogg|wav*)/gi;
var video = /(^.*\.mp4|m4v|mov|wmv|avi|mpg|ogv|3gp|3g2*)/gi;
if (itemurl.match(image)) {
btnContent = '<img src="'+itemurl+'" alt="" /><a href="" class="remove">Remove Image</a>';
} else {
btnContent = '<div class="no_image">'+html+'<a href="" class="remove">Remove</a></div>';
}
$('#' + formfield).val(itemurl);
$('#' + formfield).next().next('div').slideDown().html(btnContent);
tb_remove();
} else {
window.original_send_to_editor(html);
}
}
}
};
$(document).ready(function () {
uploadOption.init()
})
})(jQuery);
/**
*
* Inline Edit Options
*
* Creates & Updates Options via Ajax
* Dependencies: jQuery
*
*/
(function ($) {
inlineEditOption = {
init: function () {
var c = this,
d = $("tr.inline-edit-option");
$('.save-options', '#the-theme-options').live("click", function () {
inlineEditOption.save_options(this);
return false;
});
$("a.edit-inline").live("click", function (event) {
if ($("a.edit-inline").hasClass('disable')) {
event.preventDefault();
return false;
} else {
inlineEditOption.edit(this);
return false;
}
});
$("a.save").live("click", function () {
if ($("a.save").hasClass('add-save')) {
inlineEditOption.addSave(this);
return false;
} else {
inlineEditOption.editSave(this);
return false;
}
});
$("a.cancel").live("click", function () {
if ($("a.cancel").hasClass('undo-add')) {
inlineEditOption.undoAdd();
return false;
} else {
inlineEditOption.revert();
return false;
}
});
$("a.add-option").live("click", function (event) {
if (1) {
event.preventDefault();
return false;
} else {
$.post(
ajaxurl,
{ action:'profile_builder_next_id', _ajax_nonce: $("#_ajax_nonce").val() },
function (response) {
c = parseInt(response) + 1;
inlineEditOption.add(c);
}
);
return false;
}
});
$('#framework-settings').tableDnD({
onDragClass: "dragging",
onDrop: function(table, row) {
d = {
action: "profile_builder_sort",
id: $.tableDnD.serialize(),
_ajax_nonce: $("#_ajax_nonce").val()
};
$.post(ajaxurl, d, function (response) {
}, "html");
}
});
$('.delete-inline').live("click", function (event) {
if ($("a.delete-inline").hasClass('disable')) {
event.preventDefault();
return false;
} else {
var agree = confirm("Are you sure you want to delete this input?");
if (agree) {
inlineEditOption.remove(this);
return false;
} else {
return false;
}
}
});
// Fade out message div
if ($('.ajax-message').hasClass('show')) {
$('.ajax-message').ajaxMessage();
}
// Remove Uploaded Image
$('.remove').live('click', function(event) {
$(this).hide();
$(this).parents().prev().prev('.upload').attr('value', '');
$(this).parents('.screenshot').slideUp();
});
},
save_options: function (e) {
var d = {
action: "profile_builder_array_save"
};
b = $(':input', '#the-theme-options').serialize();
d = b + "&" + $.param(d);
$.post(ajaxurl, d, function (r) {
if (r != -1) {
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Theme Options were saved</div>');
$(".option-tree-slider-body").hide();
$('.option-tree-slider .edit').removeClass('down');
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>Theme Options could not be saved</div>');
}
});
return false;
},
remove: function (b) {
var c = true;
// Set ID
c = $(b).parents("tr:first").attr('id');
c = c.substr(c.lastIndexOf("-") + 1);
d = {
action: "profile_builder_delete",
id: c,
_ajax_nonce: $("#_ajax_nonce").val()
};
$.post(ajaxurl, d, function (r) {
if (r) {
r=$.trim(r);
if (r == 'removed') {
$("#option-" + c).remove();
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Input deleted.</div>');
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
});
return false;
},
add: function (c) {
var e = this,
addRow, editRow = true, temp_select;
e.revert();
// Clone the blank main row
addRow = $('#inline-add').clone(true);
addRow = $(addRow).attr('id', 'option-'+c);
// Clone the blank edit row
editRow = $('#inline-edit').clone(true);
$('a.cancel', editRow).addClass('undo-add');
$('a.save', editRow).addClass('add-save');
$('a.edit-inline').addClass('disable');
$('a.delete-inline').addClass('disable');
$('a.add-option').addClass('disable');
// Set Colspan to 6
$('td', editRow).attr('colspan', 6);
// Add Row
$("#framework-settings tr:last").after(addRow);
// Add Row and hide
$(addRow).hide().after(editRow);
$('.item-data', addRow).attr('id', 'inline_'+c);
// Show The Editor
$(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show();
$('.item_title', '#edit-'+c).focus();
// Item MetaKey
$('.item_metaName', editRow).attr('value', 'custom_field_'+c);
//internal id
$('.internal_id', editRow).attr('value', c);
$('.select').each(function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.alternative3').hide();
$('.option-desc', '#edit-'+c).hide();
$('.option-options', '#edit-'+c).hide();
$('.option-required', '#edit-'+c).hide();
}
});
$('.select').live('change', function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.alternative3').hide();
$('.option-desc', '#edit-'+c).hide();
$('.option-options', '#edit-'+c).hide();
$('.option-required', '#edit-'+c).hide();
} else if (
temp_select == 'Checkbox' ||
temp_select == 'Radio' ||
temp_select == 'Select'
) {
$('.alternative3').hide();
$('.alternative').hide();
$('.regular').show();
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).show();
$('.option-required', '#edit-'+c).show();
/* input */
}else if (temp_select == 'Input'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Maximum Character Length:</strong> Enter a value for the maxlength attribute(optional).');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-required', editRow).show();
/* end input */
/* avatar */
}else if (temp_select == 'Avatar'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-required', editRow).show();
/* end avatar */
/*upload */
} else if (temp_select == 'Upload'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Allowed Extensions:</strong> Specify the extension(s) you want to limit for upload(optional).<br/>Example: .ext1,.ext2,.ext3');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* end upload */
/* agree to terms */
}else if (temp_select == 'Checkbox ("I agree to terms and conditions")'){
$('.alternative3').show();
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
/* agree to terms end */
}
/* hidden input*/
else if (temp_select == 'Input (Hidden)'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Value:</strong> Enter the value for the hidden input field. This can be overwritten for each user individually by a user with administrator rights.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-required', editRow).hide();
/* end hidden input */
} else {
if (temp_select == 'Textarea') {
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.');
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).show();
$('.option-required', '#edit-'+c).show();
} else if (
temp_select == 'Custom Post' ||
temp_select == 'Custom Posts'
) {
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.');
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).show();
} else {
$('.alternative3').hide();
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).hide();
$('.option-required', '#edit-'+c).show();
}
}
});
// Scroll
$('html, body').animate({ scrollTop: 2000 }, 500);
return false;
},
undoAdd: function (b) {
var e = this,
c = true;
e.revert();
c = $("#framework-settings tr:last").attr('id');
c = c.substr(c.lastIndexOf("-") + 1);
$("a.edit-inline").removeClass('disable');
$("a.delete-inline").removeClass('disable');
$("a.add-option").removeClass('disable');
$("#option-" + c).remove();
return false;
},
addSave: function (e) {
var d, b, c, f, g, itemMN;
e = $("tr.inline-editor").attr("id");
e = e.substr(e.lastIndexOf("-") + 1);
f = $("#edit-" + e);
g = $("#inline_" + e);
itemMN = $.trim($("input.item_metaName", f).val().toLowerCase()).replace(/(\s+)/g,'_');
if (!itemMN) {
itemMN = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_');
}
d = {
action: "profile_builder_add",
id: e,
item_metaName: itemMN,
item_title: $("input.item_title", f).val(),
item_desc: $("textarea.item_desc", f).val(),
item_type: $("select.item_type", f).val(),
item_options: $("input.item_options", f).val()
};
b = $("#edit-" + e + " :input").serialize();
d = b + "&" + $.param(d);
$.post(ajaxurl, d, function (r) {
if (r) {
if (jQuery.trim(r) == 'updated') {
inlineEditOption.afterSave(e);
$("#edit-" + e).remove();
$("#option-" + e).show();
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Input added.</div>');
$('#framework-settings').tableDnD({
onDragClass: "dragging",
onDrop: function(table, row) {
d = {
action: "profile_builder_sort",
id: $.tableDnD.serialize(),
_ajax_nonce: $("#_ajax_nonce").val()
};
$.post(ajaxurl, d, function (response) {
}, "html");
}
});
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
});
return false;
},
edit: function (b) {
var e = this,
c, editRow, rowData, item_title, itemMN, item_type, item_desc, item_options = true, temp_select, item_required;
e.revert();
c = $(b).parents("tr:first").attr('id');
c = c.substr(c.lastIndexOf("-") + 1);
// Clone the blank row
editRow = $('#inline-edit').clone(true);
$('td', editRow).attr('colspan', 6);
$("#option-" + c).hide().after(editRow);
// First Option Settings
if ("#option-" + c == '#option-1') {
$('.option').hide();
$('.option-title').show().css({"paddingBottom":"1px"});
//$('.option-title', editRow).html('<strong>Title:</strong> The title of the item.<br/>First item must be a heading.');
$('.option-internal_id', editRow).show();
}
// Populate the option data
rowData = $('#inline_' + c);
// Item Title
item_title = $('.item_title', rowData).text();
$('.item_title', editRow).attr('value', item_title);
// Item MetaKey
item_metaName = $('.item_metaName', rowData).text();
$('.item_metaName', editRow).attr('value', 'custom_field_'+c);
// Item MetaNames
itemMN = $('.item_metaName', rowData).text();
$('.item_metaName', editRow).attr('value', itemMN);
// Internal ID
internal_id = $('.internal_id', rowData).text();
$('.internal_id', editRow).attr('value', c);
// Item Type
item_type = $('.item_type', rowData).text();
$('select[name=item_type] option[value='+item_type+']', editRow).attr('selected', true);
var temp_item_type = $('select[name=item_type] option[value='+item_type+']', editRow).text();
$('.select_wrapper span', editRow).text(temp_item_type);
// Item Description
item_desc = $('.item_desc', rowData).text();
$('.item_desc', editRow).attr('value', item_desc);
// Avatar size
item_avatar = $('.item_avatar', rowData).text();
$('.item_avatar', editRow).attr('value', item_avatar);
// Hidden field value
item_hiddenField = $('.item_hiddenField', rowData).text();
$('.item_hiddenField', editRow).attr('value', item_hiddenField);
// Item Options
item_options = $('.item_options', rowData).text();
$('.item_options', editRow).attr('value', item_options);
//Item Required checkbox
item_required = $('.item_required', rowData).text();
if(item_required == "yes") {
$('.item_required', editRow).attr('checked', 'checked');
}
$('.select', editRow).each(function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.alternative3').hide();
$('.option-desc', editRow).hide();
$('.option-options', editRow).hide();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).hide();
} else if (
temp_select == 'Checkbox' ||
temp_select == 'Radio' ||
temp_select == 'Select'
) {
$('.alternative3').hide();
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* input */
}else if (temp_select == 'Input'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Maximum Character Length:</strong> Enter a value for the maxlength attribute(optional).');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-required', editRow).show();
/* end input */
/*avatar */
} else if (temp_select == 'Avatar'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* end avatar */
/*upload */
} else if (temp_select == 'Upload'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Allowed Extensions:</strong> Specify the extension(s) you want to limit for upload(optional).<br/>Example: .ext1,.ext2,.ext3');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* end upload */
/* agree to terms */
}else if (temp_select == 'Checkbox ("I agree to terms and conditions")'){
$('.alternative3').show();
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
/* agree to terms end */
}
/* hidden input*/
else if (temp_select == 'Input (Hidden)'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Value:</strong> Enter the value for the hidden input field. This can be overwritten for each user individually by a user with administrator rights.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).hide();
/* end hidden input */
} else {
if (temp_select == 'Textarea') {
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
} else if (
temp_select == 'Custom Post' ||
temp_select == 'Custom Posts'
) {
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
} else {
$('.alternative3').hide();
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
}
}
});
$('.select').live('change', function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.alternative3').hide();
$('.option-desc', editRow).hide();
$('.option-options', editRow).hide();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).hide();
} else if (
temp_select == 'Checkbox' ||
temp_select == 'Radio' ||
temp_select == 'Select'
) {
$('.alternative').hide();
$('.alternative3').hide();
$('.regular').show();
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* input */
}else if (temp_select == 'Input'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Maximum Character Length:</strong> Enter a value for the maxlength attribute(optional).');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-required', editRow).show();
/* end input */
/*avatar */
} else if (temp_select == 'Avatar'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* end avatar */
/*upload */
} else if (temp_select == 'Upload'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Allowed Extensions:</strong> Specify the extension(s) you want to limit for upload(optional).<br/>Example: .ext1,.ext2,.ext3');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* end upload */
/* agree to terms */
}else if (temp_select == 'Checkbox ("I agree to terms and conditions")'){
$('.alternative3').show();
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
/* agree to terms end */
}
/* hidden input*/
else if (temp_select == 'Input (Hidden)'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Value:</strong> Enter the value for the hidden input field. This can be overwritten for each user individually by a user with administrator rights.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).hide();
/* end hidden input */
} else {
if (temp_select == 'Textarea') {
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
} else if (
temp_select == 'Custom Post' ||
temp_select == 'Custom Posts'
) {
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
} else {
$('.alternative3').hide();
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
}
}
});
// Show The Editor
$(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show();
// Scroll
var target = $('#edit-'+c);
if (c > 1) {
var top = target.offset().top;
$('html,body').animate({scrollTop: top}, 500);
return false;
}
return false;
},
editSave: function (e) {
var d, b, c, f, g, itemMN;
e = $("tr.inline-editor").attr("id");
e = e.substr(e.lastIndexOf("-") + 1);
f = $("#edit-" + e);
g = $("#inline_" + e);
itemMN = $.trim($("input.item_metaName", f).val().toLowerCase()).replace(/(\s+)/g,'_');
if (!itemMN) {
itemMN = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_');
}
d = {
action: "profile_builder_edit",
id: e,
item_metaName: itemMN,
item_title: $("input.item_title", f).val(),
item_desc: $("textarea.item_desc", f).val(),
item_type: $("select.item_type", f).val(),
item_options: $("input.item_options", f).val()
};
b = $("#edit-" + e + " :input").serialize();
d = b + "&" + $.param(d);
$.post(ajaxurl, d, function (r) {
if (r) {
if (jQuery.trim(r) == 'updated') {
inlineEditOption.afterSave(e);
$("#edit-" + e).remove();
$("#option-" + e).show();
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Input Saved.</div>');
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
});
return false;
},
afterSave: function (e) {
var x, y, z,
n, m, o, p, q, r = true, t, itemMN;
x = $("#edit-" + e);
y = $("#option-" + e);
z = $("#inline_" + e);
$('.option').show();
$('a.cancel', x).removeClass('undo-add');
$('a.save', x).removeClass('add-save');
$("a.add-option").removeClass('disable');
$('a.edit-inline').removeClass('disable');
$('a.delete-inline').removeClass('disable');
if (n = $("input.item_title", x).val()) {
if ($("select.item_type", x).val() != 'heading') {
$(y).removeClass('col-heading');
$('.col-title', y).attr('colspan', 1);
$(".col-type", y).show();
$(".col-metaName", y).show();
itemMN = $("input.item_metaName", x).val();
if (itemMN == '')
itemMN = n;
itemMN = itemMN.replace(" ","_");
$(".col-metaName", y).text(itemMN);
$(".col-internal_id", y).show();
$(".col-internal_id", y).text(e);
$(".col-item_required", y).show();
t = $("input.item_required", x).attr('checked');
if (t == 'checked'){
$(".col-item_required", y).text('Yes');
$('.item_required', z).text('yes');
}
else{
$(".col-item_required", y).text('No');
$('.item_required', z).text('no');
}
$(".col-title", y).text('- ' + n);
} else {
$(y).addClass('col-heading');
$('.col-title', y).attr('colspan', 5);
$(".col-internal_id", y).hide();
$(".col-type", y).hide();
$(".col-metaName", y).hide();
$(".col-item_required", y).hide();
$(".col-title", y).text(n);
}
$(".item_title", z).text(n);
}
if (m = $.trim($("input.item_metaName", x).val().toLowerCase()).replace(/(\s+)/g,'_')) {
$(".col-key", y).text(m);
$(".item_metaName", z).text(m);
} else {
m = $.trim($("input.item_title", x).val().toLowerCase()).replace(/(\s+)/g,'_');
$(".col-key", y).text(m);
$(".item_metaName", z).text(m);
}
if (o = $("select.item_type option:selected", x).val()) {
$(".col-type", y).text(o);
$(".item_type", z).text(o);
}
if (p = $("textarea.item_desc", x).val()) {
$(".item_desc", z).text(p);
}
if (r = $("input.item_options", x).val()) {
$(".item_options", z).text(r);
}
},
revert: function () {
var b,
n, m, o, p, q, r = true;
if (b = $(".inline-editor").attr("id")) {
$('#'+ b).remove();
b = b.substr(b.lastIndexOf("-") + 1);
$('.option').show();
$("#option-" + b).show();
}
return false;
}
};
$(document).ready(function () {
inlineEditOption.init();
})
})(jQuery); | JavaScript |
/**
*
* Delay
*
* Creates a way to delay events
* Dependencies: jQuery
*
*/
/*
Original Plugin Name: OptionTree
Original Plugin URI: http://wp.envato.com
Original Author: Derek Herman
Original Author URI: http://valendesigns.com
*/
(function ($) {
$.fn.delay = function(time,func){
return this.each(function(){
setTimeout(func,time);
});
};
})(jQuery);
/**
*
* Center AJAX
*
* Creates a way to center the AJAX message
* Dependencies: jQuery
*
*/
(function ($) {
$.fn.ajaxMessage = function(html){
if (html) {
return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').html(html).delay(3000, function(){$('.ajax-message').fadeOut()});
} else {
return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').delay(3000, function(){$('.ajax-message').fadeOut()});
}
};
})(jQuery);
/**
*
* Style File
*
* Creates a way to cover file input with a better styled version
* Dependencies: jQuery
*
*/
(function ($) {
styleFile = {
init: function () {
$('input.file').each(function(){
var uploadbutton = '<input class="upload_file_button" type="button" value="Upload" />';
$(this).wrap('<div class="file_wrap" />');
$(this).addClass('file').css('opacity', 0); //set to invisible
$(this).parent().append($('<div class="fake_file" />').append($('<input type="text" class="upload" />').attr('id',$(this).attr('id')+'_file')).append(uploadbutton));
$(this).bind('change', function() {
$('#'+$(this).attr('id')+'_file').val($(this).val());;
});
$(this).bind('mouseout', function() {
$('#'+$(this).attr('id')+'_file').val($(this).val());;
});
});
}
};
$(document).ready(function () {
styleFile.init()
})
})(jQuery);
/**
*
* Style Select
*
* Replace Select text
* Dependencies: jQuery
*
*/
(function ($) {
styleSelect = {
init: function () {
$('.select_wrapper').each(function () {
$(this).prepend('<span>' + $(this).find('.select option:selected').text() + '</span>');
});
$('.select').live('change', function () {
$(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>');
});
$('.select').bind($.browser.msie ? 'click' : 'change', function(event) {
$(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>');
});
}
};
$(document).ready(function () {
styleSelect.init()
})
})(jQuery);
/**
*
* Activate Tabs
*
* Tab style UI toggle
* Dependencies: jQuery, jQuery UI Core, jQuery UI Tabs
*
*/
(function ($) {
activateTabs = {
init: function () {
// Activate
$("#options_tabs").tabs();
// Append Toggle Button
$('.top-info').append('<a href="" class="toggle_tabs">Tabs</a>');
// Toggle Tabs
$('.toggle_tabs').toggle(function() {
$("#options_tabs").tabs('destroy');
$(this).addClass('off');
}, function() {
$("#options_tabs").tabs();
$(this).removeClass('off');
});
}
};
$(document).ready(function () {
activateTabs.init()
})
})(jQuery);
/**
*
* Upload Option
*
* Allows window.send_to_editor to function properly using a private post_id
* Dependencies: jQuery, Media Upload, Thickbox
*
*/
(function ($) {
uploadOption = {
init: function () {
var formfield,
formID,
btnContent = true;
// On Click
$('.upload_button').live("click", function () {
formfield = $(this).prev('input').attr('name');
formID = $(this).attr('rel');
tb_show('', 'media-upload.php?post_id='+formID+'&type=image&TB_iframe=1');
return false;
});
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function(html) {
if (formfield) {
itemurl = $(html).attr('href');
var image = /(^.*\.jpg|jpeg|png|gif|ico*)/gi;
var document = /(^.*\.pdf|doc|docx|ppt|pptx|odt*)/gi;
var audio = /(^.*\.mp3|m4a|ogg|wav*)/gi;
var video = /(^.*\.mp4|m4v|mov|wmv|avi|mpg|ogv|3gp|3g2*)/gi;
if (itemurl.match(image)) {
btnContent = '<img src="'+itemurl+'" alt="" /><a href="" class="remove">Remove Image</a>';
} else {
btnContent = '<div class="no_image">'+html+'<a href="" class="remove">Remove</a></div>';
}
$('#' + formfield).val(itemurl);
$('#' + formfield).next().next('div').slideDown().html(btnContent);
tb_remove();
} else {
window.original_send_to_editor(html);
}
}
}
};
$(document).ready(function () {
uploadOption.init()
})
})(jQuery);
/**
*
* Inline Edit Options
*
* Creates & Updates Options via Ajax
* Dependencies: jQuery
*
*/
(function ($) {
inlineEditOption = {
init: function () {
var c = this,
d = $("tr.inline-edit-option");
$('.save-options', '#the-theme-options').live("click", function () {
inlineEditOption.save_options(this);
return false;
});
$("a.edit-inline").live("click", function (event) {
if ($("a.edit-inline").hasClass('disable')) {
event.preventDefault();
return false;
} else {
inlineEditOption.edit(this);
return false;
}
});
$("a.save").live("click", function () {
if ($("a.save").hasClass('add-save')) {
inlineEditOption.addSave(this);
return false;
} else {
inlineEditOption.editSave(this);
return false;
}
});
$("a.cancel").live("click", function () {
if ($("a.cancel").hasClass('undo-add')) {
inlineEditOption.undoAdd();
return false;
} else {
inlineEditOption.revert();
return false;
}
});
$("a.add-option").live("click", function (event) {
if ($(this).hasClass('disable')) {
event.preventDefault();
return false;
} else {
$.post(
ajaxurl,
{ action:'profile_builder_next_id', _ajax_nonce: $("#_ajax_nonce").val() },
function (response) {
c = parseInt(response) + 1;
inlineEditOption.add(c);
}
);
return false;
}
});
$('.delete-inline').live("click", function (event) {
if ($("a.delete-inline").hasClass('disable')) {
event.preventDefault();
return false;
} else {
var agree = confirm("Are you sure you want to delete this input?");
if (agree) {
inlineEditOption.remove(this);
return false;
} else {
return false;
}
}
});
// Fade out message div
if ($('.ajax-message').hasClass('show')) {
$('.ajax-message').ajaxMessage();
}
// Remove Uploaded Image
$('.remove').live('click', function(event) {
$(this).hide();
$(this).parents().prev().prev('.upload').attr('value', '');
$(this).parents('.screenshot').slideUp();
});
},
save_options: function (e) {
var d = {
action: "profile_builder_array_save"
};
b = $(':input', '#the-theme-options').serialize();
d = b + "&" + $.param(d);
$.post(ajaxurl, d, function (r) {
if (r != -1) {
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Theme Options were saved</div>');
$(".option-tree-slider-body").hide();
$('.option-tree-slider .edit').removeClass('down');
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>Theme Options could not be saved</div>');
}
});
return false;
},
remove: function (b) {
var c = true;
// Set ID
c = $(b).parents("tr:first").attr('id');
c = c.substr(c.lastIndexOf("-") + 1);
d = {
action: "profile_builder_delete",
id: c,
_ajax_nonce: $("#_ajax_nonce").val()
};
$.post(ajaxurl, d, function (r) {
if (r) {
if (r == 'removed') {
$("#option-" + c).remove();
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Input deleted.</div>');
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
});
return false;
},
add: function (c) {
var e = this,
addRow, editRow = true, temp_select;
e.revert();
// Clone the blank main row
addRow = $('#inline-add').clone(true);
addRow = $(addRow).attr('id', 'option-'+c);
// Clone the blank edit row
editRow = $('#inline-edit').clone(true);
$('a.cancel', editRow).addClass('undo-add');
$('a.save', editRow).addClass('add-save');
$('a.edit-inline').addClass('disable');
$('a.delete-inline').addClass('disable');
$('a.add-option').addClass('disable');
// Set Colspan to 5
$('td', editRow).attr('colspan', 5);
// Add Row
$("#framework-settings tr:last").after(addRow);
// Add Row and hide
$(addRow).hide().after(editRow);
$('.item-data', addRow).attr('id', 'inline_'+c);
// Show The Editor
$(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show();
$('.item_title', '#edit-'+c).focus();
$('.select').each(function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.option-desc', '#edit-'+c).hide();
$('.option-options', '#edit-'+c).hide();
}
});
$('.select').live('change', function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.option-desc', '#edit-'+c).hide();
$('.option-options', '#edit-'+c).hide();
} else if (
temp_select == 'Checkbox' ||
temp_select == 'Radio' ||
temp_select == 'Select'
) {
$('.alternative').hide();
$('.regular').show();
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).show();
/* avatar */
}else if (temp_select == 'Avatar'){
$('.regular').hide();
$('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
/* end avatar */
} else {
if (temp_select == 'Textarea') {
$('.regular').hide();
$('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.');
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).show();
} else if (
temp_select == 'Custom Post' ||
temp_select == 'Custom Posts'
) {
$('.regular').hide();
$('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.');
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).show();
} else {
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).hide();
}
}
});
// Scroll
$('html, body').animate({ scrollTop: 2000 }, 500);
return false;
},
undoAdd: function (b) {
var e = this,
c = true;
e.revert();
c = $("#framework-settings tr:last").attr('id');
c = c.substr(c.lastIndexOf("-") + 1);
$("a.edit-inline").removeClass('disable');
$("a.delete-inline").removeClass('disable');
$("a.add-option").removeClass('disable');
$("#option-" + c).remove();
return false;
},
addSave: function (e) {
var d, b, c, f, g, itemId;
e = $("tr.inline-editor").attr("id");
e = e.substr(e.lastIndexOf("-") + 1);
f = $("#edit-" + e);
g = $("#inline_" + e);
itemId = $.trim($("input.item_id", f).val().toLowerCase()).replace(/(\s+)/g,'_');
if (!itemId) {
itemId = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_');
}
d = {
action: "profile_builder_add",
id: e,
item_id: itemId,
item_title: $("input.item_title", f).val(),
item_desc: $("textarea.item_desc", f).val(),
item_type: $("select.item_type", f).val(),
item_options: $("input.item_options", f).val()
};
b = $("#edit-" + e + " :input").serialize();
d = b + "&" + $.param(d);
$.post(ajaxurl, d, function (r) {
if (r) {
if (r == 'updated') {
inlineEditOption.afterSave(e);
$("#edit-" + e).remove();
$("#option-" + e).show();
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Input added.</div>');
$('#framework-settings').tableDnD({
onDragClass: "dragging",
onDrop: function(table, row) {
d = {
action: "profile_builder_sort",
id: $.tableDnD.serialize(),
_ajax_nonce: $("#_ajax_nonce").val()
};
$.post(ajaxurl, d, function (response) {
}, "html");
}
});
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
});
return false;
},
edit: function (b) {
var e = this,
c, editRow, rowData, item_title, item_id, item_type, item_desc, item_options = true, temp_select;
e.revert();
c = $(b).parents("tr:first").attr('id');
c = c.substr(c.lastIndexOf("-") + 1);
// Clone the blank row
editRow = $('#inline-edit').clone(true);
$('td', editRow).attr('colspan', 5);
$("#option-" + c).hide().after(editRow);
// First Option Settings
if ("#option-" + c == '#option-1') {
$('.option').hide();
$('.option-title').show().css({"paddingBottom":"1px"});
$('.description', editRow).html('First item must be a heading.');
}
// Populate the option data
rowData = $('#inline_' + c);
// Item Title
item_title = $('.item_title', rowData).text();
$('.item_title', editRow).attr('value', item_title);
// Item ID
item_id = $('.item_id', rowData).text();
$('.item_id', editRow).attr('value', item_id);
// Item Type
item_type = $('.item_type', rowData).text();
$('select[name=item_type] option[value='+item_type+']', editRow).attr('selected', true);
var temp_item_type = $('select[name=item_type] option[value='+item_type+']', editRow).text();
$('.select_wrapper span', editRow).text(temp_item_type);
// Item Description
item_desc = $('.item_desc', rowData).text();
$('.item_desc', editRow).attr('value', item_desc);
// Avatar size
item_avatar = $('.item_avatar', rowData).text();
$('.item_avatar', editRow).attr('value', item_avatar);
// Item Options
item_options = $('.item_options', rowData).text();
$('.item_options', editRow).attr('value', item_options);
$('.select', editRow).each(function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.option-desc', editRow).hide();
$('.option-options', editRow).hide();
} else if (
temp_select == 'Checkbox' ||
temp_select == 'Radio' ||
temp_select == 'Select'
) {
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
/*avatar */
} else if (temp_select == 'Avatar'){
$('.regular').hide();
$('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
/* end avatar */
} else {
if (temp_select == 'Textarea') {
$('.regular').hide();
$('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
} else if (
temp_select == 'Custom Post' ||
temp_select == 'Custom Posts'
) {
$('.regular').hide();
$('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
} else {
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
}
}
});
$('.select').live('change', function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.option-desc', editRow).hide();
$('.option-options', editRow).hide();
} else if (
temp_select == 'Checkbox' ||
temp_select == 'Radio' ||
temp_select == 'Select'
) {
$('.alternative').hide();
$('.regular').show();
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
/*avatar */
} else if (temp_select == 'Avatar'){
$('.regular').hide();
$('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
/* end avatar */
} else {
if (temp_select == 'Textarea') {
$('.regular').hide();
$('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
} else if (
temp_select == 'Custom Post' ||
temp_select == 'Custom Posts'
) {
$('.regular').hide();
$('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
} else {
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
}
}
});
// Show The Editor
$(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show();
// Scroll
var target = $('#edit-'+c);
if (c > 1) {
var top = target.offset().top;
$('html,body').animate({scrollTop: top}, 500);
return false;
}
return false;
},
editSave: function (e) {
var d, b, c, f, g, itemId;
e = $("tr.inline-editor").attr("id");
e = e.substr(e.lastIndexOf("-") + 1);
f = $("#edit-" + e);
g = $("#inline_" + e);
itemId = $.trim($("input.item_id", f).val().toLowerCase()).replace(/(\s+)/g,'_');
if (!itemId) {
itemId = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_');
}
d = {
action: "profile_builder_edit",
id: e,
item_id: itemId,
item_title: $("input.item_title", f).val(),
item_desc: $("textarea.item_desc", f).val(),
item_type: $("select.item_type", f).val(),
item_options: $("input.item_options", f).val()
};
b = $("#edit-" + e + " :input").serialize();
d = b + "&" + $.param(d);
$.post(ajaxurl, d, function (r) {
if (r) {
if (r == 'updated') {
inlineEditOption.afterSave(e);
$("#edit-" + e).remove();
$("#option-" + e).show();
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Option Saved.</div>');
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
});
return false;
},
afterSave: function (e) {
var x, y, z,
n, m, o, p, q, r = true;
x = $("#edit-" + e);
y = $("#option-" + e);
z = $("#inline_" + e);
$('.option').show();
$('a.cancel', x).removeClass('undo-add');
$('a.save', x).removeClass('add-save');
$("a.add-option").removeClass('disable');
$('a.edit-inline').removeClass('disable');
$('a.delete-inline').removeClass('disable');
if (n = $("input.item_title", x).val()) {
if ($("select.item_type", x).val() != 'heading') {
$(y).removeClass('col-heading');
$('.col-title', y).attr('colspan', 1);
$(".col-key", y).show();
$(".col-type", y).show();
$(".col-title", y).text('- ' + n);
} else {
$(y).addClass('col-heading');
$('.col-title', y).attr('colspan', 3);
$(".col-key", y).hide();
$(".col-type", y).hide();
$(".col-title", y).text(n);
}
$(".item_title", z).text(n);
}
if (m = $.trim($("input.item_id", x).val().toLowerCase()).replace(/(\s+)/g,'_')) {
$(".col-key", y).text(m);
$(".item_id", z).text(m);
} else {
m = $.trim($("input.item_title", x).val().toLowerCase()).replace(/(\s+)/g,'_');
$(".col-key", y).text(m);
$(".item_id", z).text(m);
}
if (o = $("select.item_type option:selected", x).val()) {
$(".col-type", y).text(o);
$(".item_type", z).text(o);
}
if (p = $("textarea.item_desc", x).val()) {
$(".item_desc", z).text(p);
}
if (r = $("input.item_options", x).val()) {
$(".item_options", z).text(r);
}
},
revert: function () {
var b,
n, m, o, p, q, r = true;
if (b = $(".inline-editor").attr("id")) {
$('#'+ b).remove();
b = b.substr(b.lastIndexOf("-") + 1);
$('.option').show();
$("#option-" + b).show();
}
return false;
}
};
$(document).ready(function () {
inlineEditOption.init();
})
})(jQuery); | JavaScript |
function wppb_insertAtCursor(myField,value) {
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = value;
}
//MOZILLA/NETSCAPE support
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ value
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += value;
}
}
function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
function wppb_replaceSelection (input, replaceString) {
if (input.setSelectionRange) {
var selectionStart = input.selectionStart;
var selectionEnd = input.selectionEnd;
input.value = input.value.substring(0, selectionStart)+ replaceString + input.value.substring(selectionEnd);
if (selectionStart != selectionEnd){
setSelectionRange(input, selectionStart, selectionStart + replaceString.length);
}else{
setSelectionRange(input, selectionStart + replaceString.length, selectionStart + replaceString.length);
}
}else if (document.selection) {
var range = document.selection.createRange();
if (range.parentElement() == input) {
var isCollapsed = range.text == '';
range.text = replaceString;
if (!isCollapsed) {
range.moveStart('character', -replaceString.length);
range.select();
}
}
}
}
// We are going to catch the TAB key so that we can use it, Hooray!
function wppb_catchTab(item,e){
if(navigator.userAgent.match("Gecko")){
c=e.which;
}else{
c=e.keyCode;
}
if(c==9){
wppb_replaceSelection(item,String.fromCharCode(9));
setTimeout("document.getElementById('"+item.id+"').focus();",0);
return false;
}
} | JavaScript |
/*
Original Plugin Name: OptionTree
Original Plugin URI: http://wp.envato.com
Original Author: Derek Herman
Original Author URI: http://valendesigns.com
*/
/**
* TableDnD plug-in for JQuery, allows you to drag and drop table rows
* You can set up various options to control how the system will work
* Copyright (c) Denis Howlett <denish@isocra.com>
* Licensed like jQuery, see http://docs.jquery.com/License.
*
* Configuration options:
*
* onDragStyle
* This is the style that is assigned to the row during drag. There are limitations to the styles that can be
* associated with a row (such as you can't assign a border--well you can, but it won't be
* displayed). (So instead consider using onDragClass.) The CSS style to apply is specified as
* a map (as used in the jQuery css(...) function).
* onDropStyle
* This is the style that is assigned to the row when it is dropped. As for onDragStyle, there are limitations
* to what you can do. Also this replaces the original style, so again consider using onDragClass which
* is simply added and then removed on drop.
* onDragClass
* This class is added for the duration of the drag and then removed when the row is dropped. It is more
* flexible than using onDragStyle since it can be inherited by the row cells and other content. The default
* is class is tDnD_whileDrag. So to use the default, simply customise this CSS class in your
* stylesheet.
* onDrop
* Pass a function that will be called when the row is dropped. The function takes 2 parameters: the table
* and the row that was dropped. You can work out the new order of the rows by using
* table.rows.
* onDragStart
* Pass a function that will be called when the user starts dragging. The function takes 2 parameters: the
* table and the row which the user has started to drag.
* onAllowDrop
* Pass a function that will be called as a row is over another row. If the function returns true, allow
* dropping on that row, otherwise not. The function takes 2 parameters: the dragged row and the row under
* the cursor. It returns a boolean: true allows the drop, false doesn't allow it.
* scrollAmount
* This is the number of pixels to scroll if the user moves the mouse cursor to the top or bottom of the
* window. The page should automatically scroll up or down as appropriate (tested in IE6, IE7, Safari, FF2,
* FF3 beta
* dragHandle
* This is the name of a class that you assign to one or more cells in each row that is draggable. If you
* specify this class, then you are responsible for setting cursor: move in the CSS and only these cells
* will have the drag behaviour. If you do not specify a dragHandle, then you get the old behaviour where
* the whole row is draggable.
*
* Other ways to control behaviour:
*
* Add class="nodrop" to any rows for which you don't want to allow dropping, and class="nodrag" to any rows
* that you don't want to be draggable.
*
* Inside the onDrop method you can also call $.tableDnD.serialize() this returns a string of the form
* <tableID>[]=<rowID1>&<tableID>[]=<rowID2> so that you can send this back to the server. The table must have
* an ID as must all the rows.
*
* Other methods:
*
* $("...").tableDnDUpdate()
* Will update all the matching tables, that is it will reapply the mousedown method to the rows (or handle cells).
* This is useful if you have updated the table rows using Ajax and you want to make the table draggable again.
* The table maintains the original configuration (so you don't have to specify it again).
*
* $("...").tableDnDSerialize()
* Will serialize and return the serialized string as above, but for each of the matching tables--so it can be
* called from anywhere and isn't dependent on the currentTable being set up correctly before calling
*
* Known problems:
* - Auto-scoll has some problems with IE7 (it scrolls even when it shouldn't), work-around: set scrollAmount to 0
*
* Version 0.2: 2008-02-20 First public version
* Version 0.3: 2008-02-07 Added onDragStart option
* Made the scroll amount configurable (default is 5 as before)
* Version 0.4: 2008-03-15 Changed the noDrag/noDrop attributes to nodrag/nodrop classes
* Added onAllowDrop to control dropping
* Fixed a bug which meant that you couldn't set the scroll amount in both directions
* Added serialize method
* Version 0.5: 2008-05-16 Changed so that if you specify a dragHandle class it doesn't make the whole row
* draggable
* Improved the serialize method to use a default (and settable) regular expression.
* Added tableDnDupate() and tableDnDSerialize() to be called when you are outside the table
*/
jQuery.tableDnD = {
/** Keep hold of the current table being dragged */
currentTable : null,
/** Keep hold of the current drag object if any */
dragObject: null,
/** The current mouse offset */
mouseOffset: null,
/** Remember the old value of Y so that we don't do too much processing */
oldY: 0,
/** Actually build the structure */
build: function(options) {
// Set up the defaults if any
this.each(function() {
// This is bound to each matching table, set up the defaults and override with user options
this.tableDnDConfig = jQuery.extend({
onDragStyle: null,
onDropStyle: null,
// Add in the default class for whileDragging
onDragClass: "tDnD_whileDrag",
onDrop: null,
onDragStart: null,
scrollAmount: 5,
serializeRegexp: /[^\-]*$/, // The regular expression to use to trim row IDs
serializeParamName: null, // If you want to specify another parameter name instead of the table ID
dragHandle: null // If you give the name of a class here, then only Cells with this class will be draggable
}, options || {});
// Now make the rows draggable
jQuery.tableDnD.makeDraggable(this);
});
// Now we need to capture the mouse up and mouse move event
// We can use bind so that we don't interfere with other event handlers
jQuery(document)
.bind('mousemove', jQuery.tableDnD.mousemove)
.bind('mouseup', jQuery.tableDnD.mouseup);
// Don't break the chain
return this;
},
/** This function makes all the rows on the table draggable apart from those marked as "NoDrag" */
makeDraggable: function(table) {
var config = table.tableDnDConfig;
if (table.tableDnDConfig.dragHandle) {
// We only need to add the event to the specified cells
var cells = jQuery("td."+table.tableDnDConfig.dragHandle, table);
cells.each(function() {
// The cell is bound to "this"
jQuery(this).mousedown(function(ev) {
jQuery.tableDnD.dragObject = this.parentNode;
jQuery.tableDnD.currentTable = table;
jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
if (config.onDragStart) {
// Call the onDrop method if there is one
config.onDragStart(table, this);
}
return false;
});
})
} else {
// For backwards compatibility, we add the event to the whole row
var rows = jQuery("tr", table); // get all the rows as a wrapped set
rows.each(function() {
// Iterate through each row, the row is bound to "this"
var row = jQuery(this);
if (! row.hasClass("nodrag")) {
row.mousedown(function(ev) {
if (ev.target.tagName == "TD") {
jQuery.tableDnD.dragObject = this;
jQuery.tableDnD.currentTable = table;
jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
if (config.onDragStart) {
// Call the onDrop method if there is one
config.onDragStart(table, this);
}
return false;
}
}).css("cursor", "move"); // Store the tableDnD object
}
});
}
},
updateTables: function() {
this.each(function() {
// this is now bound to each matching table
if (this.tableDnDConfig) {
jQuery.tableDnD.makeDraggable(this);
}
})
},
/** Get the mouse coordinates from the event (allowing for browser differences) */
mouseCoords: function(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
},
/** Given a target element and a mouse event, get the mouse offset from that element.
To do this we need the element's position and the mouse position */
getMouseOffset: function(target, ev) {
ev = ev || window.event;
var docPos = this.getPosition(target);
var mousePos = this.mouseCoords(ev);
return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
},
/** Get the position of an element by going up the DOM tree and adding up all the offsets */
getPosition: function(e){
var left = 0;
var top = 0;
/** Safari fix -- thanks to Luis Chato for this! */
if (e.offsetHeight == 0) {
/** Safari 2 doesn't correctly grab the offsetTop of a table row
this is detailed here:
http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/
the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild.
note that firefox will return a text node as a first child, so designing a more thorough
solution may need to take that into account, for now this seems to work in firefox, safari, ie */
e = e.firstChild; // a table cell
}
while (e.offsetParent){
left += e.offsetLeft;
top += e.offsetTop;
e = e.offsetParent;
}
left += e.offsetLeft;
top += e.offsetTop;
return {x:left, y:top};
},
mousemove: function(ev) {
if (jQuery.tableDnD.dragObject == null) {
return;
}
var dragObj = jQuery(jQuery.tableDnD.dragObject);
var config = jQuery.tableDnD.currentTable.tableDnDConfig;
var mousePos = jQuery.tableDnD.mouseCoords(ev);
var y = mousePos.y - jQuery.tableDnD.mouseOffset.y;
//auto scroll the window
var yOffset = window.pageYOffset;
if (document.all) {
// Windows version
//yOffset=document.body.scrollTop;
if (typeof document.compatMode != 'undefined' &&
document.compatMode != 'BackCompat') {
yOffset = document.documentElement.scrollTop;
}
else if (typeof document.body != 'undefined') {
yOffset=document.body.scrollTop;
}
}
if (mousePos.y-yOffset < config.scrollAmount) {
window.scrollBy(0, -config.scrollAmount);
} else {
var windowHeight = window.innerHeight ? window.innerHeight
: document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
if (windowHeight-(mousePos.y-yOffset) < config.scrollAmount) {
window.scrollBy(0, config.scrollAmount);
}
}
if (y != jQuery.tableDnD.oldY) {
// work out if we're going up or down...
var movingDown = y > jQuery.tableDnD.oldY;
// update the old value
jQuery.tableDnD.oldY = y;
// update the style to show we're dragging
if (config.onDragClass) {
dragObj.addClass(config.onDragClass);
} else {
dragObj.css(config.onDragStyle);
}
// If we're over a row then move the dragged row to there so that the user sees the
// effect dynamically
var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y);
if (currentRow) {
// TODO worry about what happens when there are multiple TBODIES
if (movingDown && jQuery.tableDnD.dragObject != currentRow) {
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling);
} else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) {
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow);
}
}
}
return false;
},
/** We're only worried about the y position really, because we can only move rows up and down */
findDropTargetRow: function(draggedRow, y) {
var rows = jQuery.tableDnD.currentTable.rows;
for (var i=0; i<rows.length; i++) {
var row = rows[i];
var rowY = this.getPosition(row).y;
var rowHeight = parseInt(row.offsetHeight)/2;
if (row.offsetHeight == 0) {
rowY = this.getPosition(row.firstChild).y;
rowHeight = parseInt(row.firstChild.offsetHeight)/2;
}
// Because we always have to insert before, we need to offset the height a bit
if ((y > rowY - rowHeight) && (y < (rowY + rowHeight + rowHeight))) {
// that's the row we're over
// If it's the same as the current row, ignore it
if (row == draggedRow) {return null;}
var config = jQuery.tableDnD.currentTable.tableDnDConfig;
if (config.onAllowDrop) {
if (config.onAllowDrop(draggedRow, row)) {
return row;
} else {
return null;
}
} else {
// If a row has nodrop class, then don't allow dropping (inspired by John Tarr and Famic)
var nodrop = jQuery(row).hasClass("nodrop");
if (! nodrop) {
return row;
} else {
return null;
}
}
return row;
}
}
return null;
},
mouseup: function(e) {
if (jQuery.tableDnD.currentTable && jQuery.tableDnD.dragObject) {
var droppedRow = jQuery.tableDnD.dragObject;
var config = jQuery.tableDnD.currentTable.tableDnDConfig;
// If we have a dragObject, then we need to release it,
// The row will already have been moved to the right place so we just reset stuff
if (config.onDragClass) {
jQuery(droppedRow).removeClass(config.onDragClass);
} else {
jQuery(droppedRow).css(config.onDropStyle);
}
jQuery.tableDnD.dragObject = null;
if (config.onDrop) {
// Call the onDrop method if there is one
config.onDrop(jQuery.tableDnD.currentTable, droppedRow);
}
jQuery.tableDnD.currentTable = null; // let go of the table too
}
},
serialize: function() {
if (jQuery.tableDnD.currentTable) {
return jQuery.tableDnD.serializeTable(jQuery.tableDnD.currentTable);
} else {
return "Error: No Table id set, you need to set an id on your table and every row";
}
},
serializeTable: function(table) {
var result = "";
var tableId = table.id;
var rows = table.rows;
for (var i=0; i<rows.length; i++) {
if (result.length > 0) result += "&";
var rowId = rows[i].id;
if (rowId && rowId && table.tableDnDConfig && table.tableDnDConfig.serializeRegexp) {
rowId = rowId.match(table.tableDnDConfig.serializeRegexp)[0];
}
result += tableId + '[]=' + rowId;
}
return result;
},
serializeTables: function() {
var result = "";
this.each(function() {
// this is now bound to each matching table
result += jQuery.tableDnD.serializeTable(this);
});
return result;
}
}
jQuery.fn.extend(
{
tableDnD : jQuery.tableDnD.build,
tableDnDUpdate : jQuery.tableDnD.updateTables,
tableDnDSerialize: jQuery.tableDnD.serializeTables
}
); | JavaScript |
jQuery(function(){
//hover states on the static widgets
jQuery('#dialog_link, ul#icons li').hover(
function() { jQuery(this).addClass('ui-state-hover'); },
function() { jQuery(this).removeClass('ui-state-hover'); }
);
});
/* initialize datepicker */
jQuery(function(){
// Datepicker
jQuery('.wppb_datepicker').datepicker({
inline: true,
changeMonth: true,
changeYear: true
});
}); | JavaScript |
/**
*
* Delay
*
* Creates a way to delay events
* Dependencies: jQuery
*
*/
/*
Original Plugin Name: OptionTree
Original Plugin URI: http://wp.envato.com
Original Author: Derek Herman
Original Author URI: http://valendesigns.com
*/
(function ($) {
$.fn.delay = function(time,func){
return this.each(function(){
setTimeout(func,time);
});
};
})(jQuery);
/**
*
* Center AJAX
*
* Creates a way to center the AJAX message
* Dependencies: jQuery
*
*/
(function ($) {
$.fn.ajaxMessage = function(html){
if (html) {
return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').html(html).delay(3000, function(){$('.ajax-message').fadeOut()});
} else {
return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').delay(3000, function(){$('.ajax-message').fadeOut()});
}
};
})(jQuery);
/**
*
* Style File
*
* Creates a way to cover file input with a better styled version
* Dependencies: jQuery
*
*/
(function ($) {
styleFile = {
init: function () {
$('input.file').each(function(){
var uploadbutton = '<input class="upload_file_button" type="button" value="Upload" />';
$(this).wrap('<div class="file_wrap" />');
$(this).addClass('file').css('opacity', 0); //set to invisible
$(this).parent().append($('<div class="fake_file" />').append($('<input type="text" class="upload" />').attr('id',$(this).attr('id')+'_file')).append(uploadbutton));
$(this).bind('change', function() {
$('#'+$(this).attr('id')+'_file').val($(this).val());;
});
$(this).bind('mouseout', function() {
$('#'+$(this).attr('id')+'_file').val($(this).val());;
});
});
}
};
$(document).ready(function () {
styleFile.init()
})
})(jQuery);
/**
*
* Style Select
*
* Replace Select text
* Dependencies: jQuery
*
*/
(function ($) {
styleSelect = {
init: function () {
$('.select_wrapper').each(function () {
$(this).prepend('<span>' + $(this).find('.select option:selected').text() + '</span>');
});
$('.select').live('change', function () {
$(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>');
});
$('.select').bind($.browser.msie ? 'click' : 'change', function(event) {
$(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>');
});
}
};
$(document).ready(function () {
styleSelect.init()
})
})(jQuery);
/**
*
* Activate Tabs
*
* Tab style UI toggle
* Dependencies: jQuery, jQuery UI Core, jQuery UI Tabs
*
*/
(function ($) {
activateTabs = {
init: function () {
// Activate
$("#options_tabs").tabs();
// Append Toggle Button
$('.top-info').append('<a href="" class="toggle_tabs">Tabs</a>');
// Toggle Tabs
$('.toggle_tabs').toggle(function() {
$("#options_tabs").tabs('destroy');
$(this).addClass('off');
}, function() {
$("#options_tabs").tabs();
$(this).removeClass('off');
});
}
};
$(document).ready(function () {
activateTabs.init()
})
})(jQuery);
/**
*
* Upload Option
*
* Allows window.send_to_editor to function properly using a private post_id
* Dependencies: jQuery, Media Upload, Thickbox
*
*/
(function ($) {
uploadOption = {
init: function () {
var formfield,
formID,
btnContent = true;
// On Click
$('.upload_button').live("click", function () {
formfield = $(this).prev('input').attr('name');
formID = $(this).attr('rel');
tb_show('', 'media-upload.php?post_id='+formID+'&type=image&TB_iframe=1');
return false;
});
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function(html) {
if (formfield) {
itemurl = $(html).attr('href');
var image = /(^.*\.jpg|jpeg|png|gif|ico*)/gi;
var document = /(^.*\.pdf|doc|docx|ppt|pptx|odt*)/gi;
var audio = /(^.*\.mp3|m4a|ogg|wav*)/gi;
var video = /(^.*\.mp4|m4v|mov|wmv|avi|mpg|ogv|3gp|3g2*)/gi;
if (itemurl.match(image)) {
btnContent = '<img src="'+itemurl+'" alt="" /><a href="" class="remove">Remove Image</a>';
} else {
btnContent = '<div class="no_image">'+html+'<a href="" class="remove">Remove</a></div>';
}
$('#' + formfield).val(itemurl);
$('#' + formfield).next().next('div').slideDown().html(btnContent);
tb_remove();
} else {
window.original_send_to_editor(html);
}
}
}
};
$(document).ready(function () {
uploadOption.init()
})
})(jQuery);
/**
*
* Inline Edit Options
*
* Creates & Updates Options via Ajax
* Dependencies: jQuery
*
*/
(function ($) {
inlineEditOption = {
init: function () {
var c = this,
d = $("tr.inline-edit-option");
$('.save-options', '#the-theme-options').live("click", function () {
inlineEditOption.save_options(this);
return false;
});
$("a.edit-inline").live("click", function (event) {
if ($("a.edit-inline").hasClass('disable')) {
event.preventDefault();
return false;
} else {
inlineEditOption.edit(this);
return false;
}
});
$("a.save").live("click", function () {
if ($("a.save").hasClass('add-save')) {
inlineEditOption.addSave(this);
return false;
} else {
inlineEditOption.editSave(this);
return false;
}
});
$("a.cancel").live("click", function () {
if ($("a.cancel").hasClass('undo-add')) {
inlineEditOption.undoAdd();
return false;
} else {
inlineEditOption.revert();
return false;
}
});
$("a.add-option").live("click", function (event) {
if ($(this).hasClass('disable')) {
event.preventDefault();
return false;
} else {
$.post(
ajaxurl,
{ action:'profile_builder_next_id', _ajax_nonce: $("#_ajax_nonce").val() },
function (response) {
c = parseInt(response) + 1;
inlineEditOption.add(c);
}
);
return false;
}
});
$('#framework-settings').tableDnD({
onDragClass: "dragging",
onDrop: function(table, row) {
d = {
action: "profile_builder_sort",
id: $.tableDnD.serialize(),
_ajax_nonce: $("#_ajax_nonce").val()
};
$.post(ajaxurl, d, function (response) {
}, "html");
}
});
$('.delete-inline').live("click", function (event) {
if ($("a.delete-inline").hasClass('disable')) {
event.preventDefault();
return false;
} else {
var agree = confirm("Are you sure you want to delete this input?");
if (agree) {
inlineEditOption.remove(this);
return false;
} else {
return false;
}
}
});
// Fade out message div
if ($('.ajax-message').hasClass('show')) {
$('.ajax-message').ajaxMessage();
}
// Remove Uploaded Image
$('.remove').live('click', function(event) {
$(this).hide();
$(this).parents().prev().prev('.upload').attr('value', '');
$(this).parents('.screenshot').slideUp();
});
},
save_options: function (e) {
var d = {
action: "profile_builder_array_save"
};
b = $(':input', '#the-theme-options').serialize();
d = b + "&" + $.param(d);
$.post(ajaxurl, d, function (r) {
if (r != -1) {
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Theme Options were saved</div>');
$(".option-tree-slider-body").hide();
$('.option-tree-slider .edit').removeClass('down');
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>Theme Options could not be saved</div>');
}
});
return false;
},
remove: function (b) {
var c = true;
// Set ID
c = $(b).parents("tr:first").attr('id');
c = c.substr(c.lastIndexOf("-") + 1);
d = {
action: "profile_builder_delete",
id: c,
_ajax_nonce: $("#_ajax_nonce").val()
};
$.post(ajaxurl, d, function (r) {
if (r) {
r=$.trim(r);
if (r == 'removed') {
$("#option-" + c).remove();
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Input deleted.</div>');
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
});
return false;
},
add: function (c) {
var e = this,
addRow, editRow = true, temp_select;
e.revert();
// Clone the blank main row
addRow = $('#inline-add').clone(true);
addRow = $(addRow).attr('id', 'option-'+c);
// Clone the blank edit row
editRow = $('#inline-edit').clone(true);
$('a.cancel', editRow).addClass('undo-add');
$('a.save', editRow).addClass('add-save');
$('a.edit-inline').addClass('disable');
$('a.delete-inline').addClass('disable');
$('a.add-option').addClass('disable');
// Set Colspan to 6
$('td', editRow).attr('colspan', 6);
// Add Row
$("#framework-settings tr:last").after(addRow);
// Add Row and hide
$(addRow).hide().after(editRow);
$('.item-data', addRow).attr('id', 'inline_'+c);
// Show The Editor
$(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show();
$('.item_title', '#edit-'+c).focus();
// Item MetaKey
$('.item_metaName', editRow).attr('value', 'custom_field_'+c);
//internal id
$('.internal_id', editRow).attr('value', c);
$('.select').each(function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.alternative3').hide();
$('.option-desc', '#edit-'+c).hide();
$('.option-options', '#edit-'+c).hide();
$('.option-required', '#edit-'+c).hide();
}
});
$('.select').live('change', function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.alternative3').hide();
$('.option-desc', '#edit-'+c).hide();
$('.option-options', '#edit-'+c).hide();
$('.option-required', '#edit-'+c).hide();
} else if (
temp_select == 'Checkbox' ||
temp_select == 'Radio' ||
temp_select == 'Select'
) {
$('.alternative3').hide();
$('.alternative').hide();
$('.regular').show();
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).show();
$('.option-required', '#edit-'+c).show();
/* input */
}else if (temp_select == 'Input'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Maximum Character Length:</strong> Enter a value for the maxlength attribute(optional).');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-required', editRow).show();
/* end input */
/* avatar */
}else if (temp_select == 'Avatar'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-required', editRow).show();
/* end avatar */
/*upload */
} else if (temp_select == 'Upload'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Allowed Extensions:</strong> Specify the extension(s) you want to limit for upload(optional).<br/>Example: .ext1,.ext2,.ext3');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* end upload */
/* agree to terms */
}else if (temp_select == 'Checkbox ("I agree to terms and conditions")'){
$('.alternative3').show();
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
/* agree to terms end */
}
/* hidden input*/
else if (temp_select == 'Input (Hidden)'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Value:</strong> Enter the value for the hidden input field. This can be overwritten for each user individually by a user with administrator rights.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-required', editRow).hide();
/* end hidden input */
} else {
if (temp_select == 'Textarea') {
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.');
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).show();
$('.option-required', '#edit-'+c).show();
} else if (
temp_select == 'Custom Post' ||
temp_select == 'Custom Posts'
) {
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.');
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).show();
} else {
$('.alternative3').hide();
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).hide();
$('.option-required', '#edit-'+c).show();
}
}
});
// Scroll
$('html, body').animate({ scrollTop: 2000 }, 500);
return false;
},
undoAdd: function (b) {
var e = this,
c = true;
e.revert();
c = $("#framework-settings tr:last").attr('id');
c = c.substr(c.lastIndexOf("-") + 1);
$("a.edit-inline").removeClass('disable');
$("a.delete-inline").removeClass('disable');
$("a.add-option").removeClass('disable');
$("#option-" + c).remove();
return false;
},
addSave: function (e) {
var d, b, c, f, g, itemMN;
e = $("tr.inline-editor").attr("id");
e = e.substr(e.lastIndexOf("-") + 1);
f = $("#edit-" + e);
g = $("#inline_" + e);
itemMN = $.trim($("input.item_metaName", f).val().toLowerCase()).replace(/(\s+)/g,'_');
if (!itemMN) {
itemMN = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_');
}
d = {
action: "profile_builder_add",
id: e,
item_metaName: itemMN,
item_title: $("input.item_title", f).val(),
item_desc: $("textarea.item_desc", f).val(),
item_type: $("select.item_type", f).val(),
item_options: $("input.item_options", f).val()
};
b = $("#edit-" + e + " :input").serialize();
d = b + "&" + $.param(d);
$.post(ajaxurl, d, function (r) {
if (r) {
if (jQuery.trim(r) == 'updated') {
inlineEditOption.afterSave(e);
$("#edit-" + e).remove();
$("#option-" + e).show();
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Input added.</div>');
$('#framework-settings').tableDnD({
onDragClass: "dragging",
onDrop: function(table, row) {
d = {
action: "profile_builder_sort",
id: $.tableDnD.serialize(),
_ajax_nonce: $("#_ajax_nonce").val()
};
$.post(ajaxurl, d, function (response) {
}, "html");
}
});
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
});
return false;
},
edit: function (b) {
var e = this,
c, editRow, rowData, item_title, itemMN, item_type, item_desc, item_options = true, temp_select, item_required;
e.revert();
c = $(b).parents("tr:first").attr('id');
c = c.substr(c.lastIndexOf("-") + 1);
// Clone the blank row
editRow = $('#inline-edit').clone(true);
$('td', editRow).attr('colspan', 6);
$("#option-" + c).hide().after(editRow);
// First Option Settings
if ("#option-" + c == '#option-1') {
$('.option').hide();
$('.option-title').show().css({"paddingBottom":"1px"});
//$('.option-title', editRow).html('<strong>Title:</strong> The title of the item.<br/>First item must be a heading.');
$('.option-internal_id', editRow).show();
}
// Populate the option data
rowData = $('#inline_' + c);
// Item Title
item_title = $('.item_title', rowData).text();
$('.item_title', editRow).attr('value', item_title);
// Item MetaKey
item_metaName = $('.item_metaName', rowData).text();
$('.item_metaName', editRow).attr('value', 'custom_field_'+c);
// Item MetaNames
itemMN = $('.item_metaName', rowData).text();
$('.item_metaName', editRow).attr('value', itemMN);
// Internal ID
internal_id = $('.internal_id', rowData).text();
$('.internal_id', editRow).attr('value', c);
// Item Type
item_type = $('.item_type', rowData).text();
$('select[name=item_type] option[value='+item_type+']', editRow).attr('selected', true);
var temp_item_type = $('select[name=item_type] option[value='+item_type+']', editRow).text();
$('.select_wrapper span', editRow).text(temp_item_type);
// Item Description
item_desc = $('.item_desc', rowData).text();
$('.item_desc', editRow).attr('value', item_desc);
// Avatar size
item_avatar = $('.item_avatar', rowData).text();
$('.item_avatar', editRow).attr('value', item_avatar);
// Hidden field value
item_hiddenField = $('.item_hiddenField', rowData).text();
$('.item_hiddenField', editRow).attr('value', item_hiddenField);
// Item Options
item_options = $('.item_options', rowData).text();
$('.item_options', editRow).attr('value', item_options);
//Item Required checkbox
item_required = $('.item_required', rowData).text();
if(item_required == "yes") {
$('.item_required', editRow).attr('checked', 'checked');
}
$('.select', editRow).each(function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.alternative3').hide();
$('.option-desc', editRow).hide();
$('.option-options', editRow).hide();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).hide();
} else if (
temp_select == 'Checkbox' ||
temp_select == 'Radio' ||
temp_select == 'Select'
) {
$('.alternative3').hide();
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* input */
}else if (temp_select == 'Input'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Maximum Character Length:</strong> Enter a value for the maxlength attribute(optional).');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-required', editRow).show();
/* end input */
/*avatar */
} else if (temp_select == 'Avatar'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* end avatar */
/*upload */
} else if (temp_select == 'Upload'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Allowed Extensions:</strong> Specify the extension(s) you want to limit for upload(optional).<br/>Example: .ext1,.ext2,.ext3');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* end upload */
/* agree to terms */
}else if (temp_select == 'Checkbox ("I agree to terms and conditions")'){
$('.alternative3').show();
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
/* agree to terms end */
}
/* hidden input*/
else if (temp_select == 'Input (Hidden)'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Value:</strong> Enter the value for the hidden input field. This can be overwritten for each user individually by a user with administrator rights.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).hide();
/* end hidden input */
} else {
if (temp_select == 'Textarea') {
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
} else if (
temp_select == 'Custom Post' ||
temp_select == 'Custom Posts'
) {
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
} else {
$('.alternative3').hide();
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
}
}
});
$('.select').live('change', function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.alternative3').hide();
$('.option-desc', editRow).hide();
$('.option-options', editRow).hide();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).hide();
} else if (
temp_select == 'Checkbox' ||
temp_select == 'Radio' ||
temp_select == 'Select'
) {
$('.alternative').hide();
$('.alternative3').hide();
$('.regular').show();
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* input */
}else if (temp_select == 'Input'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Maximum Character Length:</strong> Enter a value for the maxlength attribute(optional).');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-required', editRow).show();
/* end input */
/*avatar */
} else if (temp_select == 'Avatar'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* end avatar */
/*upload */
} else if (temp_select == 'Upload'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Allowed Extensions:</strong> Specify the extension(s) you want to limit for upload(optional).<br/>Example: .ext1,.ext2,.ext3');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* end upload */
/* agree to terms */
}else if (temp_select == 'Checkbox ("I agree to terms and conditions")'){
$('.alternative3').show();
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
/* agree to terms end */
}
/* hidden input*/
else if (temp_select == 'Input (Hidden)'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Value:</strong> Enter the value for the hidden input field. This can be overwritten for each user individually by a user with administrator rights.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).hide();
/* end hidden input */
} else {
if (temp_select == 'Textarea') {
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
} else if (
temp_select == 'Custom Post' ||
temp_select == 'Custom Posts'
) {
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
} else {
$('.alternative3').hide();
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
}
}
});
// Show The Editor
$(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show();
// Scroll
var target = $('#edit-'+c);
if (c > 1) {
var top = target.offset().top;
$('html,body').animate({scrollTop: top}, 500);
return false;
}
return false;
},
editSave: function (e) {
var d, b, c, f, g, itemMN;
e = $("tr.inline-editor").attr("id");
e = e.substr(e.lastIndexOf("-") + 1);
f = $("#edit-" + e);
g = $("#inline_" + e);
itemMN = $.trim($("input.item_metaName", f).val().toLowerCase()).replace(/(\s+)/g,'_');
if (!itemMN) {
itemMN = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_');
}
d = {
action: "profile_builder_edit",
id: e,
item_metaName: itemMN,
item_title: $("input.item_title", f).val(),
item_desc: $("textarea.item_desc", f).val(),
item_type: $("select.item_type", f).val(),
item_options: $("input.item_options", f).val()
};
b = $("#edit-" + e + " :input").serialize();
d = b + "&" + $.param(d);
$.post(ajaxurl, d, function (r) {
if (r) {
if (jQuery.trim(r) == 'updated') {
inlineEditOption.afterSave(e);
$("#edit-" + e).remove();
$("#option-" + e).show();
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Input Saved.</div>');
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
});
return false;
},
afterSave: function (e) {
var x, y, z,
n, m, o, p, q, r = true, t, itemMN;
x = $("#edit-" + e);
y = $("#option-" + e);
z = $("#inline_" + e);
$('.option').show();
$('a.cancel', x).removeClass('undo-add');
$('a.save', x).removeClass('add-save');
$("a.add-option").removeClass('disable');
$('a.edit-inline').removeClass('disable');
$('a.delete-inline').removeClass('disable');
if (n = $("input.item_title", x).val()) {
if ($("select.item_type", x).val() != 'heading') {
$(y).removeClass('col-heading');
$('.col-title', y).attr('colspan', 1);
$(".col-type", y).show();
$(".col-metaName", y).show();
itemMN = $("input.item_metaName", x).val();
if (itemMN == '')
itemMN = n;
itemMN = itemMN.replace(" ","_");
$(".col-metaName", y).text(itemMN);
$(".col-internal_id", y).show();
$(".col-internal_id", y).text(e);
$(".col-item_required", y).show();
t = $("input.item_required", x).attr('checked');
if (t == 'checked'){
$(".col-item_required", y).text('Yes');
$('.item_required', z).text('yes');
}
else{
$(".col-item_required", y).text('No');
$('.item_required', z).text('no');
}
$(".col-title", y).text('- ' + n);
} else {
$(y).addClass('col-heading');
$('.col-title', y).attr('colspan', 5);
$(".col-internal_id", y).hide();
$(".col-type", y).hide();
$(".col-metaName", y).hide();
$(".col-item_required", y).hide();
$(".col-title", y).text(n);
}
$(".item_title", z).text(n);
}
if (m = $.trim($("input.item_metaName", x).val().toLowerCase()).replace(/(\s+)/g,'_')) {
$(".col-key", y).text(m);
$(".item_metaName", z).text(m);
} else {
m = $.trim($("input.item_title", x).val().toLowerCase()).replace(/(\s+)/g,'_');
$(".col-key", y).text(m);
$(".item_metaName", z).text(m);
}
if (o = $("select.item_type option:selected", x).val()) {
$(".col-type", y).text(o);
$(".item_type", z).text(o);
}
if (p = $("textarea.item_desc", x).val()) {
$(".item_desc", z).text(p);
}
if (r = $("input.item_options", x).val()) {
$(".item_options", z).text(r);
}
},
revert: function () {
var b,
n, m, o, p, q, r = true;
if (b = $(".inline-editor").attr("id")) {
$('#'+ b).remove();
b = b.substr(b.lastIndexOf("-") + 1);
$('.option').show();
$("#option-" + b).show();
}
return false;
}
};
$(document).ready(function () {
inlineEditOption.init();
})
})(jQuery); | JavaScript |
function wppb_insertAtCursor(myField,value) {
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = value;
}
//MOZILLA/NETSCAPE support
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ value
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += value;
}
}
function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
function wppb_replaceSelection (input, replaceString) {
if (input.setSelectionRange) {
var selectionStart = input.selectionStart;
var selectionEnd = input.selectionEnd;
input.value = input.value.substring(0, selectionStart)+ replaceString + input.value.substring(selectionEnd);
if (selectionStart != selectionEnd){
setSelectionRange(input, selectionStart, selectionStart + replaceString.length);
}else{
setSelectionRange(input, selectionStart + replaceString.length, selectionStart + replaceString.length);
}
}else if (document.selection) {
var range = document.selection.createRange();
if (range.parentElement() == input) {
var isCollapsed = range.text == '';
range.text = replaceString;
if (!isCollapsed) {
range.moveStart('character', -replaceString.length);
range.select();
}
}
}
}
// We are going to catch the TAB key so that we can use it, Hooray!
function wppb_catchTab(item,e){
if(navigator.userAgent.match("Gecko")){
c=e.which;
}else{
c=e.keyCode;
}
if(c==9){
wppb_replaceSelection(item,String.fromCharCode(9));
setTimeout("document.getElementById('"+item.id+"').focus();",0);
return false;
}
} | JavaScript |
/*
Original Plugin Name: OptionTree
Original Plugin URI: http://wp.envato.com
Original Author: Derek Herman
Original Author URI: http://valendesigns.com
*/
/**
* TableDnD plug-in for JQuery, allows you to drag and drop table rows
* You can set up various options to control how the system will work
* Copyright (c) Denis Howlett <denish@isocra.com>
* Licensed like jQuery, see http://docs.jquery.com/License.
*
* Configuration options:
*
* onDragStyle
* This is the style that is assigned to the row during drag. There are limitations to the styles that can be
* associated with a row (such as you can't assign a border--well you can, but it won't be
* displayed). (So instead consider using onDragClass.) The CSS style to apply is specified as
* a map (as used in the jQuery css(...) function).
* onDropStyle
* This is the style that is assigned to the row when it is dropped. As for onDragStyle, there are limitations
* to what you can do. Also this replaces the original style, so again consider using onDragClass which
* is simply added and then removed on drop.
* onDragClass
* This class is added for the duration of the drag and then removed when the row is dropped. It is more
* flexible than using onDragStyle since it can be inherited by the row cells and other content. The default
* is class is tDnD_whileDrag. So to use the default, simply customise this CSS class in your
* stylesheet.
* onDrop
* Pass a function that will be called when the row is dropped. The function takes 2 parameters: the table
* and the row that was dropped. You can work out the new order of the rows by using
* table.rows.
* onDragStart
* Pass a function that will be called when the user starts dragging. The function takes 2 parameters: the
* table and the row which the user has started to drag.
* onAllowDrop
* Pass a function that will be called as a row is over another row. If the function returns true, allow
* dropping on that row, otherwise not. The function takes 2 parameters: the dragged row and the row under
* the cursor. It returns a boolean: true allows the drop, false doesn't allow it.
* scrollAmount
* This is the number of pixels to scroll if the user moves the mouse cursor to the top or bottom of the
* window. The page should automatically scroll up or down as appropriate (tested in IE6, IE7, Safari, FF2,
* FF3 beta
* dragHandle
* This is the name of a class that you assign to one or more cells in each row that is draggable. If you
* specify this class, then you are responsible for setting cursor: move in the CSS and only these cells
* will have the drag behaviour. If you do not specify a dragHandle, then you get the old behaviour where
* the whole row is draggable.
*
* Other ways to control behaviour:
*
* Add class="nodrop" to any rows for which you don't want to allow dropping, and class="nodrag" to any rows
* that you don't want to be draggable.
*
* Inside the onDrop method you can also call $.tableDnD.serialize() this returns a string of the form
* <tableID>[]=<rowID1>&<tableID>[]=<rowID2> so that you can send this back to the server. The table must have
* an ID as must all the rows.
*
* Other methods:
*
* $("...").tableDnDUpdate()
* Will update all the matching tables, that is it will reapply the mousedown method to the rows (or handle cells).
* This is useful if you have updated the table rows using Ajax and you want to make the table draggable again.
* The table maintains the original configuration (so you don't have to specify it again).
*
* $("...").tableDnDSerialize()
* Will serialize and return the serialized string as above, but for each of the matching tables--so it can be
* called from anywhere and isn't dependent on the currentTable being set up correctly before calling
*
* Known problems:
* - Auto-scoll has some problems with IE7 (it scrolls even when it shouldn't), work-around: set scrollAmount to 0
*
* Version 0.2: 2008-02-20 First public version
* Version 0.3: 2008-02-07 Added onDragStart option
* Made the scroll amount configurable (default is 5 as before)
* Version 0.4: 2008-03-15 Changed the noDrag/noDrop attributes to nodrag/nodrop classes
* Added onAllowDrop to control dropping
* Fixed a bug which meant that you couldn't set the scroll amount in both directions
* Added serialize method
* Version 0.5: 2008-05-16 Changed so that if you specify a dragHandle class it doesn't make the whole row
* draggable
* Improved the serialize method to use a default (and settable) regular expression.
* Added tableDnDupate() and tableDnDSerialize() to be called when you are outside the table
*/
jQuery.tableDnD = {
/** Keep hold of the current table being dragged */
currentTable : null,
/** Keep hold of the current drag object if any */
dragObject: null,
/** The current mouse offset */
mouseOffset: null,
/** Remember the old value of Y so that we don't do too much processing */
oldY: 0,
/** Actually build the structure */
build: function(options) {
// Set up the defaults if any
this.each(function() {
// This is bound to each matching table, set up the defaults and override with user options
this.tableDnDConfig = jQuery.extend({
onDragStyle: null,
onDropStyle: null,
// Add in the default class for whileDragging
onDragClass: "tDnD_whileDrag",
onDrop: null,
onDragStart: null,
scrollAmount: 5,
serializeRegexp: /[^\-]*$/, // The regular expression to use to trim row IDs
serializeParamName: null, // If you want to specify another parameter name instead of the table ID
dragHandle: null // If you give the name of a class here, then only Cells with this class will be draggable
}, options || {});
// Now make the rows draggable
jQuery.tableDnD.makeDraggable(this);
});
// Now we need to capture the mouse up and mouse move event
// We can use bind so that we don't interfere with other event handlers
jQuery(document)
.bind('mousemove', jQuery.tableDnD.mousemove)
.bind('mouseup', jQuery.tableDnD.mouseup);
// Don't break the chain
return this;
},
/** This function makes all the rows on the table draggable apart from those marked as "NoDrag" */
makeDraggable: function(table) {
var config = table.tableDnDConfig;
if (table.tableDnDConfig.dragHandle) {
// We only need to add the event to the specified cells
var cells = jQuery("td."+table.tableDnDConfig.dragHandle, table);
cells.each(function() {
// The cell is bound to "this"
jQuery(this).mousedown(function(ev) {
jQuery.tableDnD.dragObject = this.parentNode;
jQuery.tableDnD.currentTable = table;
jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
if (config.onDragStart) {
// Call the onDrop method if there is one
config.onDragStart(table, this);
}
return false;
});
})
} else {
// For backwards compatibility, we add the event to the whole row
var rows = jQuery("tr", table); // get all the rows as a wrapped set
rows.each(function() {
// Iterate through each row, the row is bound to "this"
var row = jQuery(this);
if (! row.hasClass("nodrag")) {
row.mousedown(function(ev) {
if (ev.target.tagName == "TD") {
jQuery.tableDnD.dragObject = this;
jQuery.tableDnD.currentTable = table;
jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
if (config.onDragStart) {
// Call the onDrop method if there is one
config.onDragStart(table, this);
}
return false;
}
}).css("cursor", "move"); // Store the tableDnD object
}
});
}
},
updateTables: function() {
this.each(function() {
// this is now bound to each matching table
if (this.tableDnDConfig) {
jQuery.tableDnD.makeDraggable(this);
}
})
},
/** Get the mouse coordinates from the event (allowing for browser differences) */
mouseCoords: function(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
},
/** Given a target element and a mouse event, get the mouse offset from that element.
To do this we need the element's position and the mouse position */
getMouseOffset: function(target, ev) {
ev = ev || window.event;
var docPos = this.getPosition(target);
var mousePos = this.mouseCoords(ev);
return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
},
/** Get the position of an element by going up the DOM tree and adding up all the offsets */
getPosition: function(e){
var left = 0;
var top = 0;
/** Safari fix -- thanks to Luis Chato for this! */
if (e.offsetHeight == 0) {
/** Safari 2 doesn't correctly grab the offsetTop of a table row
this is detailed here:
http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/
the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild.
note that firefox will return a text node as a first child, so designing a more thorough
solution may need to take that into account, for now this seems to work in firefox, safari, ie */
e = e.firstChild; // a table cell
}
while (e.offsetParent){
left += e.offsetLeft;
top += e.offsetTop;
e = e.offsetParent;
}
left += e.offsetLeft;
top += e.offsetTop;
return {x:left, y:top};
},
mousemove: function(ev) {
if (jQuery.tableDnD.dragObject == null) {
return;
}
var dragObj = jQuery(jQuery.tableDnD.dragObject);
var config = jQuery.tableDnD.currentTable.tableDnDConfig;
var mousePos = jQuery.tableDnD.mouseCoords(ev);
var y = mousePos.y - jQuery.tableDnD.mouseOffset.y;
//auto scroll the window
var yOffset = window.pageYOffset;
if (document.all) {
// Windows version
//yOffset=document.body.scrollTop;
if (typeof document.compatMode != 'undefined' &&
document.compatMode != 'BackCompat') {
yOffset = document.documentElement.scrollTop;
}
else if (typeof document.body != 'undefined') {
yOffset=document.body.scrollTop;
}
}
if (mousePos.y-yOffset < config.scrollAmount) {
window.scrollBy(0, -config.scrollAmount);
} else {
var windowHeight = window.innerHeight ? window.innerHeight
: document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
if (windowHeight-(mousePos.y-yOffset) < config.scrollAmount) {
window.scrollBy(0, config.scrollAmount);
}
}
if (y != jQuery.tableDnD.oldY) {
// work out if we're going up or down...
var movingDown = y > jQuery.tableDnD.oldY;
// update the old value
jQuery.tableDnD.oldY = y;
// update the style to show we're dragging
if (config.onDragClass) {
dragObj.addClass(config.onDragClass);
} else {
dragObj.css(config.onDragStyle);
}
// If we're over a row then move the dragged row to there so that the user sees the
// effect dynamically
var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y);
if (currentRow) {
// TODO worry about what happens when there are multiple TBODIES
if (movingDown && jQuery.tableDnD.dragObject != currentRow) {
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling);
} else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) {
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow);
}
}
}
return false;
},
/** We're only worried about the y position really, because we can only move rows up and down */
findDropTargetRow: function(draggedRow, y) {
var rows = jQuery.tableDnD.currentTable.rows;
for (var i=0; i<rows.length; i++) {
var row = rows[i];
var rowY = this.getPosition(row).y;
var rowHeight = parseInt(row.offsetHeight)/2;
if (row.offsetHeight == 0) {
rowY = this.getPosition(row.firstChild).y;
rowHeight = parseInt(row.firstChild.offsetHeight)/2;
}
// Because we always have to insert before, we need to offset the height a bit
if ((y > rowY - rowHeight) && (y < (rowY + rowHeight + rowHeight))) {
// that's the row we're over
// If it's the same as the current row, ignore it
if (row == draggedRow) {return null;}
var config = jQuery.tableDnD.currentTable.tableDnDConfig;
if (config.onAllowDrop) {
if (config.onAllowDrop(draggedRow, row)) {
return row;
} else {
return null;
}
} else {
// If a row has nodrop class, then don't allow dropping (inspired by John Tarr and Famic)
var nodrop = jQuery(row).hasClass("nodrop");
if (! nodrop) {
return row;
} else {
return null;
}
}
return row;
}
}
return null;
},
mouseup: function(e) {
if (jQuery.tableDnD.currentTable && jQuery.tableDnD.dragObject) {
var droppedRow = jQuery.tableDnD.dragObject;
var config = jQuery.tableDnD.currentTable.tableDnDConfig;
// If we have a dragObject, then we need to release it,
// The row will already have been moved to the right place so we just reset stuff
if (config.onDragClass) {
jQuery(droppedRow).removeClass(config.onDragClass);
} else {
jQuery(droppedRow).css(config.onDropStyle);
}
jQuery.tableDnD.dragObject = null;
if (config.onDrop) {
// Call the onDrop method if there is one
config.onDrop(jQuery.tableDnD.currentTable, droppedRow);
}
jQuery.tableDnD.currentTable = null; // let go of the table too
}
},
serialize: function() {
if (jQuery.tableDnD.currentTable) {
return jQuery.tableDnD.serializeTable(jQuery.tableDnD.currentTable);
} else {
return "Error: No Table id set, you need to set an id on your table and every row";
}
},
serializeTable: function(table) {
var result = "";
var tableId = table.id;
var rows = table.rows;
for (var i=0; i<rows.length; i++) {
if (result.length > 0) result += "&";
var rowId = rows[i].id;
if (rowId && rowId && table.tableDnDConfig && table.tableDnDConfig.serializeRegexp) {
rowId = rowId.match(table.tableDnDConfig.serializeRegexp)[0];
}
result += tableId + '[]=' + rowId;
}
return result;
},
serializeTables: function() {
var result = "";
this.each(function() {
// this is now bound to each matching table
result += jQuery.tableDnD.serializeTable(this);
});
return result;
}
}
jQuery.fn.extend(
{
tableDnD : jQuery.tableDnD.build,
tableDnDUpdate : jQuery.tableDnD.updateTables,
tableDnDSerialize: jQuery.tableDnD.serializeTables
}
); | JavaScript |
jQuery(function(){
//hover states on the static widgets
jQuery('#dialog_link, ul#icons li').hover(
function() { jQuery(this).addClass('ui-state-hover'); },
function() { jQuery(this).removeClass('ui-state-hover'); }
);
});
/* initialize datepicker */
jQuery(function(){
// Datepicker
jQuery('.wppb_datepicker').datepicker({
inline: true,
changeMonth: true,
changeYear: true
});
}); | JavaScript |
/**
*
* Delay
*
* Creates a way to delay events
* Dependencies: jQuery
*
*/
/*
Original Plugin Name: OptionTree
Original Plugin URI: http://wp.envato.com
Original Author: Derek Herman
Original Author URI: http://valendesigns.com
*/
(function ($) {
$.fn.delay = function(time,func){
return this.each(function(){
setTimeout(func,time);
});
};
})(jQuery);
/**
*
* Center AJAX
*
* Creates a way to center the AJAX message
* Dependencies: jQuery
*
*/
(function ($) {
$.fn.ajaxMessage = function(html){
if (html) {
return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').html(html).delay(3000, function(){$('.ajax-message').fadeOut()});
} else {
return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').delay(3000, function(){$('.ajax-message').fadeOut()});
}
};
})(jQuery);
/**
*
* Style File
*
* Creates a way to cover file input with a better styled version
* Dependencies: jQuery
*
*/
(function ($) {
styleFile = {
init: function () {
$('input.file').each(function(){
var uploadbutton = '<input class="upload_file_button" type="button" value="Upload" />';
$(this).wrap('<div class="file_wrap" />');
$(this).addClass('file').css('opacity', 0); //set to invisible
$(this).parent().append($('<div class="fake_file" />').append($('<input type="text" class="upload" />').attr('id',$(this).attr('id')+'_file')).append(uploadbutton));
$(this).bind('change', function() {
$('#'+$(this).attr('id')+'_file').val($(this).val());;
});
$(this).bind('mouseout', function() {
$('#'+$(this).attr('id')+'_file').val($(this).val());;
});
});
}
};
$(document).ready(function () {
styleFile.init()
})
})(jQuery);
/**
*
* Style Select
*
* Replace Select text
* Dependencies: jQuery
*
*/
(function ($) {
styleSelect = {
init: function () {
$('.select_wrapper').each(function () {
$(this).prepend('<span>' + $(this).find('.select option:selected').text() + '</span>');
});
$('.select').live('change', function () {
$(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>');
});
$('.select').bind($.browser.msie ? 'click' : 'change', function(event) {
$(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>');
});
}
};
$(document).ready(function () {
styleSelect.init()
})
})(jQuery);
/**
*
* Activate Tabs
*
* Tab style UI toggle
* Dependencies: jQuery, jQuery UI Core, jQuery UI Tabs
*
*/
(function ($) {
activateTabs = {
init: function () {
// Activate
$("#options_tabs").tabs();
// Append Toggle Button
$('.top-info').append('<a href="" class="toggle_tabs">Tabs</a>');
// Toggle Tabs
$('.toggle_tabs').toggle(function() {
$("#options_tabs").tabs('destroy');
$(this).addClass('off');
}, function() {
$("#options_tabs").tabs();
$(this).removeClass('off');
});
}
};
$(document).ready(function () {
activateTabs.init()
})
})(jQuery);
/**
*
* Upload Option
*
* Allows window.send_to_editor to function properly using a private post_id
* Dependencies: jQuery, Media Upload, Thickbox
*
*/
(function ($) {
uploadOption = {
init: function () {
var formfield,
formID,
btnContent = true;
// On Click
$('.upload_button').live("click", function () {
formfield = $(this).prev('input').attr('name');
formID = $(this).attr('rel');
tb_show('', 'media-upload.php?post_id='+formID+'&type=image&TB_iframe=1');
return false;
});
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function(html) {
if (formfield) {
itemurl = $(html).attr('href');
var image = /(^.*\.jpg|jpeg|png|gif|ico*)/gi;
var document = /(^.*\.pdf|doc|docx|ppt|pptx|odt*)/gi;
var audio = /(^.*\.mp3|m4a|ogg|wav*)/gi;
var video = /(^.*\.mp4|m4v|mov|wmv|avi|mpg|ogv|3gp|3g2*)/gi;
if (itemurl.match(image)) {
btnContent = '<img src="'+itemurl+'" alt="" /><a href="" class="remove">Remove Image</a>';
} else {
btnContent = '<div class="no_image">'+html+'<a href="" class="remove">Remove</a></div>';
}
$('#' + formfield).val(itemurl);
$('#' + formfield).next().next('div').slideDown().html(btnContent);
tb_remove();
} else {
window.original_send_to_editor(html);
}
}
}
};
$(document).ready(function () {
uploadOption.init()
})
})(jQuery);
/**
*
* Inline Edit Options
*
* Creates & Updates Options via Ajax
* Dependencies: jQuery
*
*/
(function ($) {
inlineEditOption = {
init: function () {
var c = this,
d = $("tr.inline-edit-option");
$('.save-options', '#the-theme-options').live("click", function () {
inlineEditOption.save_options(this);
return false;
});
$("a.edit-inline").live("click", function (event) {
if ($("a.edit-inline").hasClass('disable')) {
event.preventDefault();
return false;
} else {
inlineEditOption.edit(this);
return false;
}
});
$("a.save").live("click", function () {
if ($("a.save").hasClass('add-save')) {
inlineEditOption.addSave(this);
return false;
} else {
inlineEditOption.editSave(this);
return false;
}
});
$("a.cancel").live("click", function () {
if ($("a.cancel").hasClass('undo-add')) {
inlineEditOption.undoAdd();
return false;
} else {
inlineEditOption.revert();
return false;
}
});
$("a.add-option").live("click", function (event) {
if ($(this).hasClass('disable')) {
event.preventDefault();
return false;
} else {
$.post(
ajaxurl,
{ action:'profile_builder_next_id', _ajax_nonce: $("#_ajax_nonce").val() },
function (response) {
c = parseInt(response) + 1;
inlineEditOption.add(c);
}
);
return false;
}
});
$('#framework-settings').tableDnD({
onDragClass: "dragging",
onDrop: function(table, row) {
d = {
action: "profile_builder_sort",
id: $.tableDnD.serialize(),
_ajax_nonce: $("#_ajax_nonce").val()
};
$.post(ajaxurl, d, function (response) {
}, "html");
}
});
$('.delete-inline').live("click", function (event) {
if ($("a.delete-inline").hasClass('disable')) {
event.preventDefault();
return false;
} else {
var agree = confirm("Are you sure you want to delete this input?");
if (agree) {
inlineEditOption.remove(this);
return false;
} else {
return false;
}
}
});
// Fade out message div
if ($('.ajax-message').hasClass('show')) {
$('.ajax-message').ajaxMessage();
}
// Remove Uploaded Image
$('.remove').live('click', function(event) {
$(this).hide();
$(this).parents().prev().prev('.upload').attr('value', '');
$(this).parents('.screenshot').slideUp();
});
},
save_options: function (e) {
var d = {
action: "profile_builder_array_save"
};
b = $(':input', '#the-theme-options').serialize();
d = b + "&" + $.param(d);
$.post(ajaxurl, d, function (r) {
if (r != -1) {
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Theme Options were saved</div>');
$(".option-tree-slider-body").hide();
$('.option-tree-slider .edit').removeClass('down');
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>Theme Options could not be saved</div>');
}
});
return false;
},
remove: function (b) {
var c = true;
// Set ID
c = $(b).parents("tr:first").attr('id');
c = c.substr(c.lastIndexOf("-") + 1);
d = {
action: "profile_builder_delete",
id: c,
_ajax_nonce: $("#_ajax_nonce").val()
};
$.post(ajaxurl, d, function (r) {
if (r) {
r=$.trim(r);
if (r == 'removed') {
$("#option-" + c).remove();
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Input deleted.</div>');
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
});
return false;
},
add: function (c) {
var e = this,
addRow, editRow = true, temp_select;
e.revert();
// Clone the blank main row
addRow = $('#inline-add').clone(true);
addRow = $(addRow).attr('id', 'option-'+c);
// Clone the blank edit row
editRow = $('#inline-edit').clone(true);
$('a.cancel', editRow).addClass('undo-add');
$('a.save', editRow).addClass('add-save');
$('a.edit-inline').addClass('disable');
$('a.delete-inline').addClass('disable');
$('a.add-option').addClass('disable');
// Set Colspan to 6
$('td', editRow).attr('colspan', 6);
// Add Row
$("#framework-settings tr:last").after(addRow);
// Add Row and hide
$(addRow).hide().after(editRow);
$('.item-data', addRow).attr('id', 'inline_'+c);
// Show The Editor
$(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show();
$('.item_title', '#edit-'+c).focus();
// Item MetaKey
$('.item_metaName', editRow).attr('value', 'custom_field_'+c);
//internal id
$('.internal_id', editRow).attr('value', c);
$('.select').each(function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.alternative3').hide();
$('.option-desc', '#edit-'+c).hide();
$('.option-options', '#edit-'+c).hide();
$('.option-required', '#edit-'+c).hide();
}
});
$('.select').live('change', function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.alternative3').hide();
$('.option-desc', '#edit-'+c).hide();
$('.option-options', '#edit-'+c).hide();
$('.option-required', '#edit-'+c).hide();
} else if (
temp_select == 'Checkbox' ||
temp_select == 'Radio' ||
temp_select == 'Select'
) {
$('.alternative3').hide();
$('.alternative').hide();
$('.regular').show();
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).show();
$('.option-required', '#edit-'+c).show();
/* input */
}else if (temp_select == 'Input'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Maximum Character Length:</strong> Enter a value for the maxlength attribute(optional).');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-required', editRow).show();
/* end input */
/* avatar */
}else if (temp_select == 'Avatar'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-required', editRow).show();
/* end avatar */
/*upload */
} else if (temp_select == 'Upload'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Allowed Extensions:</strong> Specify the extension(s) you want to limit for upload(optional).<br/>Example: .ext1,.ext2,.ext3');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* end upload */
/* agree to terms */
}else if (temp_select == 'Checkbox ("I agree to terms and conditions")'){
$('.alternative3').show();
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
/* agree to terms end */
}
/* hidden input*/
else if (temp_select == 'Input (Hidden)'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Value:</strong> Enter the value for the hidden input field. This can be overwritten for each user individually by a user with administrator rights.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-required', editRow).hide();
/* end hidden input */
} else {
if (temp_select == 'Textarea') {
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.');
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).show();
$('.option-required', '#edit-'+c).show();
} else if (
temp_select == 'Custom Post' ||
temp_select == 'Custom Posts'
) {
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.');
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).show();
} else {
$('.alternative3').hide();
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).hide();
$('.option-required', '#edit-'+c).show();
}
}
});
// Scroll
$('html, body').animate({ scrollTop: 2000 }, 500);
return false;
},
undoAdd: function (b) {
var e = this,
c = true;
e.revert();
c = $("#framework-settings tr:last").attr('id');
c = c.substr(c.lastIndexOf("-") + 1);
$("a.edit-inline").removeClass('disable');
$("a.delete-inline").removeClass('disable');
$("a.add-option").removeClass('disable');
$("#option-" + c).remove();
return false;
},
addSave: function (e) {
var d, b, c, f, g, itemMN;
e = $("tr.inline-editor").attr("id");
e = e.substr(e.lastIndexOf("-") + 1);
f = $("#edit-" + e);
g = $("#inline_" + e);
itemMN = $.trim($("input.item_metaName", f).val().toLowerCase()).replace(/(\s+)/g,'_');
if (!itemMN) {
itemMN = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_');
}
d = {
action: "profile_builder_add",
id: e,
item_metaName: itemMN,
item_title: $("input.item_title", f).val(),
item_desc: $("textarea.item_desc", f).val(),
item_type: $("select.item_type", f).val(),
item_options: $("input.item_options", f).val()
};
b = $("#edit-" + e + " :input").serialize();
d = b + "&" + $.param(d);
$.post(ajaxurl, d, function (r) {
if (r) {
if (jQuery.trim(r) == 'updated') {
inlineEditOption.afterSave(e);
$("#edit-" + e).remove();
$("#option-" + e).show();
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Input added.</div>');
$('#framework-settings').tableDnD({
onDragClass: "dragging",
onDrop: function(table, row) {
d = {
action: "profile_builder_sort",
id: $.tableDnD.serialize(),
_ajax_nonce: $("#_ajax_nonce").val()
};
$.post(ajaxurl, d, function (response) {
}, "html");
}
});
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
});
return false;
},
edit: function (b) {
var e = this,
c, editRow, rowData, item_title, itemMN, item_type, item_desc, item_options = true, temp_select, item_required;
e.revert();
c = $(b).parents("tr:first").attr('id');
c = c.substr(c.lastIndexOf("-") + 1);
// Clone the blank row
editRow = $('#inline-edit').clone(true);
$('td', editRow).attr('colspan', 6);
$("#option-" + c).hide().after(editRow);
// First Option Settings
if ("#option-" + c == '#option-1') {
$('.option').hide();
$('.option-title').show().css({"paddingBottom":"1px"});
//$('.option-title', editRow).html('<strong>Title:</strong> The title of the item.<br/>First item must be a heading.');
$('.option-internal_id', editRow).show();
}
// Populate the option data
rowData = $('#inline_' + c);
// Item Title
item_title = $('.item_title', rowData).text();
$('.item_title', editRow).attr('value', item_title);
// Item MetaKey
item_metaName = $('.item_metaName', rowData).text();
$('.item_metaName', editRow).attr('value', 'custom_field_'+c);
// Item MetaNames
itemMN = $('.item_metaName', rowData).text();
$('.item_metaName', editRow).attr('value', itemMN);
// Internal ID
internal_id = $('.internal_id', rowData).text();
$('.internal_id', editRow).attr('value', c);
// Item Type
item_type = $('.item_type', rowData).text();
$('select[name=item_type] option[value='+item_type+']', editRow).attr('selected', true);
var temp_item_type = $('select[name=item_type] option[value='+item_type+']', editRow).text();
$('.select_wrapper span', editRow).text(temp_item_type);
// Item Description
item_desc = $('.item_desc', rowData).text();
$('.item_desc', editRow).attr('value', item_desc);
// Avatar size
item_avatar = $('.item_avatar', rowData).text();
$('.item_avatar', editRow).attr('value', item_avatar);
// Hidden field value
item_hiddenField = $('.item_hiddenField', rowData).text();
$('.item_hiddenField', editRow).attr('value', item_hiddenField);
// Item Options
item_options = $('.item_options', rowData).text();
$('.item_options', editRow).attr('value', item_options);
//Item Required checkbox
item_required = $('.item_required', rowData).text();
if(item_required == "yes") {
$('.item_required', editRow).attr('checked', 'checked');
}
$('.select', editRow).each(function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.alternative3').hide();
$('.option-desc', editRow).hide();
$('.option-options', editRow).hide();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).hide();
} else if (
temp_select == 'Checkbox' ||
temp_select == 'Radio' ||
temp_select == 'Select'
) {
$('.alternative3').hide();
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* input */
}else if (temp_select == 'Input'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Maximum Character Length:</strong> Enter a value for the maxlength attribute(optional).');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-required', editRow).show();
/* end input */
/*avatar */
} else if (temp_select == 'Avatar'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* end avatar */
/*upload */
} else if (temp_select == 'Upload'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Allowed Extensions:</strong> Specify the extension(s) you want to limit for upload(optional).<br/>Example: .ext1,.ext2,.ext3');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* end upload */
/* agree to terms */
}else if (temp_select == 'Checkbox ("I agree to terms and conditions")'){
$('.alternative3').show();
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
/* agree to terms end */
}
/* hidden input*/
else if (temp_select == 'Input (Hidden)'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Value:</strong> Enter the value for the hidden input field. This can be overwritten for each user individually by a user with administrator rights.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).hide();
/* end hidden input */
} else {
if (temp_select == 'Textarea') {
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
} else if (
temp_select == 'Custom Post' ||
temp_select == 'Custom Posts'
) {
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
} else {
$('.alternative3').hide();
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
}
}
});
$('.select').live('change', function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.alternative3').hide();
$('.option-desc', editRow).hide();
$('.option-options', editRow).hide();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).hide();
} else if (
temp_select == 'Checkbox' ||
temp_select == 'Radio' ||
temp_select == 'Select'
) {
$('.alternative').hide();
$('.alternative3').hide();
$('.regular').show();
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* input */
}else if (temp_select == 'Input'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Maximum Character Length:</strong> Enter a value for the maxlength attribute(optional).');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-required', editRow).show();
/* end input */
/*avatar */
} else if (temp_select == 'Avatar'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* end avatar */
/*upload */
} else if (temp_select == 'Upload'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Allowed Extensions:</strong> Specify the extension(s) you want to limit for upload(optional).<br/>Example: .ext1,.ext2,.ext3');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
/* end upload */
/* agree to terms */
}else if (temp_select == 'Checkbox ("I agree to terms and conditions")'){
$('.alternative3').show();
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
/* agree to terms end */
}
/* hidden input*/
else if (temp_select == 'Input (Hidden)'){
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Value:</strong> Enter the value for the hidden input field. This can be overwritten for each user individually by a user with administrator rights.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).hide();
/* end hidden input */
} else {
if (temp_select == 'Textarea') {
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
} else if (
temp_select == 'Custom Post' ||
temp_select == 'Custom Posts'
) {
$('.alternative3').hide();
$('.regular').hide();
$('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
$('.option-internal_id', editRow).show();
} else {
$('.alternative3').hide();
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
$('.option-internal_id', editRow).show();
$('.option-required', editRow).show();
}
}
});
// Show The Editor
$(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show();
// Scroll
var target = $('#edit-'+c);
if (c > 1) {
var top = target.offset().top;
$('html,body').animate({scrollTop: top}, 500);
return false;
}
return false;
},
editSave: function (e) {
var d, b, c, f, g, itemMN;
e = $("tr.inline-editor").attr("id");
e = e.substr(e.lastIndexOf("-") + 1);
f = $("#edit-" + e);
g = $("#inline_" + e);
itemMN = $.trim($("input.item_metaName", f).val().toLowerCase()).replace(/(\s+)/g,'_');
if (!itemMN) {
itemMN = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_');
}
d = {
action: "profile_builder_edit",
id: e,
item_metaName: itemMN,
item_title: $("input.item_title", f).val(),
item_desc: $("textarea.item_desc", f).val(),
item_type: $("select.item_type", f).val(),
item_options: $("input.item_options", f).val()
};
b = $("#edit-" + e + " :input").serialize();
d = b + "&" + $.param(d);
$.post(ajaxurl, d, function (r) {
if (r) {
if (jQuery.trim(r) == 'updated') {
inlineEditOption.afterSave(e);
$("#edit-" + e).remove();
$("#option-" + e).show();
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Input Saved.</div>');
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
});
return false;
},
afterSave: function (e) {
var x, y, z,
n, m, o, p, q, r = true, t, itemMN;
x = $("#edit-" + e);
y = $("#option-" + e);
z = $("#inline_" + e);
$('.option').show();
$('a.cancel', x).removeClass('undo-add');
$('a.save', x).removeClass('add-save');
$("a.add-option").removeClass('disable');
$('a.edit-inline').removeClass('disable');
$('a.delete-inline').removeClass('disable');
if (n = $("input.item_title", x).val()) {
if ($("select.item_type", x).val() != 'heading') {
$(y).removeClass('col-heading');
$('.col-title', y).attr('colspan', 1);
$(".col-type", y).show();
$(".col-metaName", y).show();
itemMN = $("input.item_metaName", x).val();
if (itemMN == '')
itemMN = n;
itemMN = itemMN.replace(" ","_");
$(".col-metaName", y).text(itemMN);
$(".col-internal_id", y).show();
$(".col-internal_id", y).text(e);
$(".col-item_required", y).show();
t = $("input.item_required", x).attr('checked');
if (t == 'checked'){
$(".col-item_required", y).text('Yes');
$('.item_required', z).text('yes');
}
else{
$(".col-item_required", y).text('No');
$('.item_required', z).text('no');
}
$(".col-title", y).text('- ' + n);
} else {
$(y).addClass('col-heading');
$('.col-title', y).attr('colspan', 5);
$(".col-internal_id", y).hide();
$(".col-type", y).hide();
$(".col-metaName", y).hide();
$(".col-item_required", y).hide();
$(".col-title", y).text(n);
}
$(".item_title", z).text(n);
}
if (m = $.trim($("input.item_metaName", x).val().toLowerCase()).replace(/(\s+)/g,'_')) {
$(".col-key", y).text(m);
$(".item_metaName", z).text(m);
} else {
m = $.trim($("input.item_title", x).val().toLowerCase()).replace(/(\s+)/g,'_');
$(".col-key", y).text(m);
$(".item_metaName", z).text(m);
}
if (o = $("select.item_type option:selected", x).val()) {
$(".col-type", y).text(o);
$(".item_type", z).text(o);
}
if (p = $("textarea.item_desc", x).val()) {
$(".item_desc", z).text(p);
}
if (r = $("input.item_options", x).val()) {
$(".item_options", z).text(r);
}
},
revert: function () {
var b,
n, m, o, p, q, r = true;
if (b = $(".inline-editor").attr("id")) {
$('#'+ b).remove();
b = b.substr(b.lastIndexOf("-") + 1);
$('.option').show();
$("#option-" + b).show();
}
return false;
}
};
$(document).ready(function () {
inlineEditOption.init();
})
})(jQuery); | JavaScript |
/**
*
* Delay
*
* Creates a way to delay events
* Dependencies: jQuery
*
*/
/*
Original Plugin Name: OptionTree
Original Plugin URI: http://wp.envato.com
Original Author: Derek Herman
Original Author URI: http://valendesigns.com
*/
(function ($) {
$.fn.delay = function(time,func){
return this.each(function(){
setTimeout(func,time);
});
};
})(jQuery);
/**
*
* Center AJAX
*
* Creates a way to center the AJAX message
* Dependencies: jQuery
*
*/
(function ($) {
$.fn.ajaxMessage = function(html){
if (html) {
return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').html(html).delay(3000, function(){$('.ajax-message').fadeOut()});
} else {
return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').delay(3000, function(){$('.ajax-message').fadeOut()});
}
};
})(jQuery);
/**
*
* Style File
*
* Creates a way to cover file input with a better styled version
* Dependencies: jQuery
*
*/
(function ($) {
styleFile = {
init: function () {
$('input.file').each(function(){
var uploadbutton = '<input class="upload_file_button" type="button" value="Upload" />';
$(this).wrap('<div class="file_wrap" />');
$(this).addClass('file').css('opacity', 0); //set to invisible
$(this).parent().append($('<div class="fake_file" />').append($('<input type="text" class="upload" />').attr('id',$(this).attr('id')+'_file')).append(uploadbutton));
$(this).bind('change', function() {
$('#'+$(this).attr('id')+'_file').val($(this).val());;
});
$(this).bind('mouseout', function() {
$('#'+$(this).attr('id')+'_file').val($(this).val());;
});
});
}
};
$(document).ready(function () {
styleFile.init()
})
})(jQuery);
/**
*
* Style Select
*
* Replace Select text
* Dependencies: jQuery
*
*/
(function ($) {
styleSelect = {
init: function () {
$('.select_wrapper').each(function () {
$(this).prepend('<span>' + $(this).find('.select option:selected').text() + '</span>');
});
$('.select').live('change', function () {
$(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>');
});
$('.select').bind($.browser.msie ? 'click' : 'change', function(event) {
$(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>');
});
}
};
$(document).ready(function () {
styleSelect.init()
})
})(jQuery);
/**
*
* Activate Tabs
*
* Tab style UI toggle
* Dependencies: jQuery, jQuery UI Core, jQuery UI Tabs
*
*/
(function ($) {
activateTabs = {
init: function () {
// Activate
$("#options_tabs").tabs();
// Append Toggle Button
$('.top-info').append('<a href="" class="toggle_tabs">Tabs</a>');
// Toggle Tabs
$('.toggle_tabs').toggle(function() {
$("#options_tabs").tabs('destroy');
$(this).addClass('off');
}, function() {
$("#options_tabs").tabs();
$(this).removeClass('off');
});
}
};
$(document).ready(function () {
activateTabs.init()
})
})(jQuery);
/**
*
* Upload Option
*
* Allows window.send_to_editor to function properly using a private post_id
* Dependencies: jQuery, Media Upload, Thickbox
*
*/
(function ($) {
uploadOption = {
init: function () {
var formfield,
formID,
btnContent = true;
// On Click
$('.upload_button').live("click", function () {
formfield = $(this).prev('input').attr('name');
formID = $(this).attr('rel');
tb_show('', 'media-upload.php?post_id='+formID+'&type=image&TB_iframe=1');
return false;
});
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function(html) {
if (formfield) {
itemurl = $(html).attr('href');
var image = /(^.*\.jpg|jpeg|png|gif|ico*)/gi;
var document = /(^.*\.pdf|doc|docx|ppt|pptx|odt*)/gi;
var audio = /(^.*\.mp3|m4a|ogg|wav*)/gi;
var video = /(^.*\.mp4|m4v|mov|wmv|avi|mpg|ogv|3gp|3g2*)/gi;
if (itemurl.match(image)) {
btnContent = '<img src="'+itemurl+'" alt="" /><a href="" class="remove">Remove Image</a>';
} else {
btnContent = '<div class="no_image">'+html+'<a href="" class="remove">Remove</a></div>';
}
$('#' + formfield).val(itemurl);
$('#' + formfield).next().next('div').slideDown().html(btnContent);
tb_remove();
} else {
window.original_send_to_editor(html);
}
}
}
};
$(document).ready(function () {
uploadOption.init()
})
})(jQuery);
/**
*
* Inline Edit Options
*
* Creates & Updates Options via Ajax
* Dependencies: jQuery
*
*/
(function ($) {
inlineEditOption = {
init: function () {
var c = this,
d = $("tr.inline-edit-option");
$('.save-options', '#the-theme-options').live("click", function () {
inlineEditOption.save_options(this);
return false;
});
$("a.edit-inline").live("click", function (event) {
if ($("a.edit-inline").hasClass('disable')) {
event.preventDefault();
return false;
} else {
inlineEditOption.edit(this);
return false;
}
});
$("a.save").live("click", function () {
if ($("a.save").hasClass('add-save')) {
inlineEditOption.addSave(this);
return false;
} else {
inlineEditOption.editSave(this);
return false;
}
});
$("a.cancel").live("click", function () {
if ($("a.cancel").hasClass('undo-add')) {
inlineEditOption.undoAdd();
return false;
} else {
inlineEditOption.revert();
return false;
}
});
$("a.add-option").live("click", function (event) {
if ($(this).hasClass('disable')) {
event.preventDefault();
return false;
} else {
$.post(
ajaxurl,
{ action:'profile_builder_next_id', _ajax_nonce: $("#_ajax_nonce").val() },
function (response) {
c = parseInt(response) + 1;
inlineEditOption.add(c);
}
);
return false;
}
});
$('.delete-inline').live("click", function (event) {
if ($("a.delete-inline").hasClass('disable')) {
event.preventDefault();
return false;
} else {
var agree = confirm("Are you sure you want to delete this input?");
if (agree) {
inlineEditOption.remove(this);
return false;
} else {
return false;
}
}
});
// Fade out message div
if ($('.ajax-message').hasClass('show')) {
$('.ajax-message').ajaxMessage();
}
// Remove Uploaded Image
$('.remove').live('click', function(event) {
$(this).hide();
$(this).parents().prev().prev('.upload').attr('value', '');
$(this).parents('.screenshot').slideUp();
});
},
save_options: function (e) {
var d = {
action: "profile_builder_array_save"
};
b = $(':input', '#the-theme-options').serialize();
d = b + "&" + $.param(d);
$.post(ajaxurl, d, function (r) {
if (r != -1) {
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Theme Options were saved</div>');
$(".option-tree-slider-body").hide();
$('.option-tree-slider .edit').removeClass('down');
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>Theme Options could not be saved</div>');
}
});
return false;
},
remove: function (b) {
var c = true;
// Set ID
c = $(b).parents("tr:first").attr('id');
c = c.substr(c.lastIndexOf("-") + 1);
d = {
action: "profile_builder_delete",
id: c,
_ajax_nonce: $("#_ajax_nonce").val()
};
$.post(ajaxurl, d, function (r) {
if (r) {
if (r == 'removed') {
$("#option-" + c).remove();
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Input deleted.</div>');
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
});
return false;
},
add: function (c) {
var e = this,
addRow, editRow = true, temp_select;
e.revert();
// Clone the blank main row
addRow = $('#inline-add').clone(true);
addRow = $(addRow).attr('id', 'option-'+c);
// Clone the blank edit row
editRow = $('#inline-edit').clone(true);
$('a.cancel', editRow).addClass('undo-add');
$('a.save', editRow).addClass('add-save');
$('a.edit-inline').addClass('disable');
$('a.delete-inline').addClass('disable');
$('a.add-option').addClass('disable');
// Set Colspan to 5
$('td', editRow).attr('colspan', 5);
// Add Row
$("#framework-settings tr:last").after(addRow);
// Add Row and hide
$(addRow).hide().after(editRow);
$('.item-data', addRow).attr('id', 'inline_'+c);
// Show The Editor
$(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show();
$('.item_title', '#edit-'+c).focus();
$('.select').each(function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.option-desc', '#edit-'+c).hide();
$('.option-options', '#edit-'+c).hide();
}
});
$('.select').live('change', function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.option-desc', '#edit-'+c).hide();
$('.option-options', '#edit-'+c).hide();
} else if (
temp_select == 'Checkbox' ||
temp_select == 'Radio' ||
temp_select == 'Select'
) {
$('.alternative').hide();
$('.regular').show();
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).show();
/* avatar */
}else if (temp_select == 'Avatar'){
$('.regular').hide();
$('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
/* end avatar */
} else {
if (temp_select == 'Textarea') {
$('.regular').hide();
$('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.');
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).show();
} else if (
temp_select == 'Custom Post' ||
temp_select == 'Custom Posts'
) {
$('.regular').hide();
$('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.');
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).show();
} else {
$('.option-desc', '#edit-'+c).show();
$('.option-options', '#edit-'+c).hide();
}
}
});
// Scroll
$('html, body').animate({ scrollTop: 2000 }, 500);
return false;
},
undoAdd: function (b) {
var e = this,
c = true;
e.revert();
c = $("#framework-settings tr:last").attr('id');
c = c.substr(c.lastIndexOf("-") + 1);
$("a.edit-inline").removeClass('disable');
$("a.delete-inline").removeClass('disable');
$("a.add-option").removeClass('disable');
$("#option-" + c).remove();
return false;
},
addSave: function (e) {
var d, b, c, f, g, itemId;
e = $("tr.inline-editor").attr("id");
e = e.substr(e.lastIndexOf("-") + 1);
f = $("#edit-" + e);
g = $("#inline_" + e);
itemId = $.trim($("input.item_id", f).val().toLowerCase()).replace(/(\s+)/g,'_');
if (!itemId) {
itemId = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_');
}
d = {
action: "profile_builder_add",
id: e,
item_id: itemId,
item_title: $("input.item_title", f).val(),
item_desc: $("textarea.item_desc", f).val(),
item_type: $("select.item_type", f).val(),
item_options: $("input.item_options", f).val()
};
b = $("#edit-" + e + " :input").serialize();
d = b + "&" + $.param(d);
$.post(ajaxurl, d, function (r) {
if (r) {
if (r == 'updated') {
inlineEditOption.afterSave(e);
$("#edit-" + e).remove();
$("#option-" + e).show();
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Input added.</div>');
$('#framework-settings').tableDnD({
onDragClass: "dragging",
onDrop: function(table, row) {
d = {
action: "profile_builder_sort",
id: $.tableDnD.serialize(),
_ajax_nonce: $("#_ajax_nonce").val()
};
$.post(ajaxurl, d, function (response) {
}, "html");
}
});
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
});
return false;
},
edit: function (b) {
var e = this,
c, editRow, rowData, item_title, item_id, item_type, item_desc, item_options = true, temp_select;
e.revert();
c = $(b).parents("tr:first").attr('id');
c = c.substr(c.lastIndexOf("-") + 1);
// Clone the blank row
editRow = $('#inline-edit').clone(true);
$('td', editRow).attr('colspan', 5);
$("#option-" + c).hide().after(editRow);
// First Option Settings
if ("#option-" + c == '#option-1') {
$('.option').hide();
$('.option-title').show().css({"paddingBottom":"1px"});
$('.description', editRow).html('First item must be a heading.');
}
// Populate the option data
rowData = $('#inline_' + c);
// Item Title
item_title = $('.item_title', rowData).text();
$('.item_title', editRow).attr('value', item_title);
// Item ID
item_id = $('.item_id', rowData).text();
$('.item_id', editRow).attr('value', item_id);
// Item Type
item_type = $('.item_type', rowData).text();
$('select[name=item_type] option[value='+item_type+']', editRow).attr('selected', true);
var temp_item_type = $('select[name=item_type] option[value='+item_type+']', editRow).text();
$('.select_wrapper span', editRow).text(temp_item_type);
// Item Description
item_desc = $('.item_desc', rowData).text();
$('.item_desc', editRow).attr('value', item_desc);
// Avatar size
item_avatar = $('.item_avatar', rowData).text();
$('.item_avatar', editRow).attr('value', item_avatar);
// Item Options
item_options = $('.item_options', rowData).text();
$('.item_options', editRow).attr('value', item_options);
$('.select', editRow).each(function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.option-desc', editRow).hide();
$('.option-options', editRow).hide();
} else if (
temp_select == 'Checkbox' ||
temp_select == 'Radio' ||
temp_select == 'Select'
) {
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
/*avatar */
} else if (temp_select == 'Avatar'){
$('.regular').hide();
$('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
/* end avatar */
} else {
if (temp_select == 'Textarea') {
$('.regular').hide();
$('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
} else if (
temp_select == 'Custom Post' ||
temp_select == 'Custom Posts'
) {
$('.regular').hide();
$('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
} else {
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
}
}
});
$('.select').live('change', function () {
temp_select = $(this).prev('span').text();
if (temp_select == 'Heading') {
$('.option-desc', editRow).hide();
$('.option-options', editRow).hide();
} else if (
temp_select == 'Checkbox' ||
temp_select == 'Radio' ||
temp_select == 'Select'
) {
$('.alternative').hide();
$('.regular').show();
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
/*avatar */
} else if (temp_select == 'Avatar'){
$('.regular').hide();
$('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
/* end avatar */
} else {
if (temp_select == 'Textarea') {
$('.regular').hide();
$('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
} else if (
temp_select == 'Custom Post' ||
temp_select == 'Custom Posts'
) {
$('.regular').hide();
$('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.');
$('.option-desc', editRow).show();
$('.option-options', editRow).show();
} else {
$('.option-desc', editRow).show();
$('.option-options', editRow).hide();
}
}
});
// Show The Editor
$(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show();
// Scroll
var target = $('#edit-'+c);
if (c > 1) {
var top = target.offset().top;
$('html,body').animate({scrollTop: top}, 500);
return false;
}
return false;
},
editSave: function (e) {
var d, b, c, f, g, itemId;
e = $("tr.inline-editor").attr("id");
e = e.substr(e.lastIndexOf("-") + 1);
f = $("#edit-" + e);
g = $("#inline_" + e);
itemId = $.trim($("input.item_id", f).val().toLowerCase()).replace(/(\s+)/g,'_');
if (!itemId) {
itemId = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_');
}
d = {
action: "profile_builder_edit",
id: e,
item_id: itemId,
item_title: $("input.item_title", f).val(),
item_desc: $("textarea.item_desc", f).val(),
item_type: $("select.item_type", f).val(),
item_options: $("input.item_options", f).val()
};
b = $("#edit-" + e + " :input").serialize();
d = b + "&" + $.param(d);
$.post(ajaxurl, d, function (r) {
if (r) {
if (r == 'updated') {
inlineEditOption.afterSave(e);
$("#edit-" + e).remove();
$("#option-" + e).show();
$('.ajax-message').ajaxMessage('<div class="message"><span> </span>Option Saved.</div>');
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
} else {
$('.ajax-message').ajaxMessage('<div class="message warning"><span> </span>'+r+'</div>');
}
});
return false;
},
afterSave: function (e) {
var x, y, z,
n, m, o, p, q, r = true;
x = $("#edit-" + e);
y = $("#option-" + e);
z = $("#inline_" + e);
$('.option').show();
$('a.cancel', x).removeClass('undo-add');
$('a.save', x).removeClass('add-save');
$("a.add-option").removeClass('disable');
$('a.edit-inline').removeClass('disable');
$('a.delete-inline').removeClass('disable');
if (n = $("input.item_title", x).val()) {
if ($("select.item_type", x).val() != 'heading') {
$(y).removeClass('col-heading');
$('.col-title', y).attr('colspan', 1);
$(".col-key", y).show();
$(".col-type", y).show();
$(".col-title", y).text('- ' + n);
} else {
$(y).addClass('col-heading');
$('.col-title', y).attr('colspan', 3);
$(".col-key", y).hide();
$(".col-type", y).hide();
$(".col-title", y).text(n);
}
$(".item_title", z).text(n);
}
if (m = $.trim($("input.item_id", x).val().toLowerCase()).replace(/(\s+)/g,'_')) {
$(".col-key", y).text(m);
$(".item_id", z).text(m);
} else {
m = $.trim($("input.item_title", x).val().toLowerCase()).replace(/(\s+)/g,'_');
$(".col-key", y).text(m);
$(".item_id", z).text(m);
}
if (o = $("select.item_type option:selected", x).val()) {
$(".col-type", y).text(o);
$(".item_type", z).text(o);
}
if (p = $("textarea.item_desc", x).val()) {
$(".item_desc", z).text(p);
}
if (r = $("input.item_options", x).val()) {
$(".item_options", z).text(r);
}
},
revert: function () {
var b,
n, m, o, p, q, r = true;
if (b = $(".inline-editor").attr("id")) {
$('#'+ b).remove();
b = b.substr(b.lastIndexOf("-") + 1);
$('.option').show();
$("#option-" + b).show();
}
return false;
}
};
$(document).ready(function () {
inlineEditOption.init();
})
})(jQuery); | JavaScript |
function wppb_display_page_select( value ) {
if ( value == 'yes' )
jQuery ( '#framework_wrap #content #general_settings_registration_page_div' ).show();
else
jQuery ( '#framework_wrap #content #general_settings_registration_page_div' ).hide();
}
jQuery(function() {
if ( ( jQuery( '#framework_wrap #content .wppb_general_settings2' ).val() == 'yes' ) || ( jQuery( '#framework_wrap #content #wppb_general_settings_hidden' ).val() == 'multisite' ) )
jQuery ( '#framework_wrap #content #general_settings_registration_page_div' ).show();
else
jQuery ( '#framework_wrap #content #general_settings_registration_page_div' ).hide();
}); | JavaScript |
/*
* @package WP Admin Bar Removal
* @subpackage External JS Enqueue Script
* @branche 2014
* @build 2014-08-15
* @since 3.7+
* @tested 3.9+
* @version 2014.0816.0392
* @target 2014.1210.0410
* @status STABLE (trunk) release
* @development Code in Becoming!
* @author slangjis
* @license GPLv2 or later
* @indentation GNU style coding standard
*/
/**
* Please contact me @ slangji.wordpress.com/contact/
* to know how to get this file and test new features
* that will be developed offline on github.com/slangji
*/
| JavaScript |
jQuery( document ).ready( function( $ ) {
// Don't ever cache ajax requests
$.ajaxSetup( { 'cache' : false } );
// Remove the loading class when ajax requests complete
$( document ).ajaxComplete( function() {
$( '.hmbkp-ajax-loading' ).removeClass( 'hmbkp-ajax-loading' ).removeAttr( 'disabled' );
} );
$( document ).on( 'click', '.hmbkp-colorbox-close', function() {
$.colorbox.close(); location.reload();
} );
// Setup the tabs
$( '.hmbkp-tabs' ).tabs();
// Set the first tab to be active
if ( ! $( '.subsubsub a.current' ).size() )
$( '.subsubsub li:first a').addClass( 'current' );
// Initialize colorbox
$( '.colorbox' ).colorbox( {
'initialWidth' : '320px',
'initialHeight' : '100px',
'transition' : 'elastic',
'scrolling' : false,
'innerWidth' : '320px',
'maxHeight' : '85%', // 85% Takes into account the WP Admin bar.
'escKey' : false,
'overlayClose' : false,
'onLoad' : function() {
$( '#cboxClose' ).remove();
},
'onComplete' : function() {
$( '.hmbkp-tabs' ).tabs();
if ( $( ".hmbkp-form p.submit:contains('" + hmbkp.update + "')" ).size() ) {
$( '<button type="button" class="button-secondary hmbkp-colorbox-close">' + hmbkp.cancel + '</button>' ).appendTo( '.hmbkp-form p.submit' );
}
$( '.recurring-setting' ).hide();
hmbkpToggleScheduleFields( $('select#hmbkp_schedule_recurrence_type').val() );
$( document ).on( 'change', 'select#hmbkp_schedule_recurrence_type', function() {
hmbkpToggleScheduleFields( $( this ).val() );
} );
$.colorbox.resize();
}
} );
// Resize the colorbox when switching tabs
$( document).on( 'click', '.ui-tabs-anchor', function( e ) {
$.colorbox.resize();
} );
// Show delete confirm message for delete schedule
$( document ).on( 'click', '.hmbkp-schedule-actions .delete-action', function( e ) {
if ( ! confirm( hmbkp.delete_schedule ) )
e.preventDefault();
} );
// Show delete confirm message for delete backup
$( document ).on( 'click', '.hmbkp_manage_backups_row .delete-action', function( e ) {
if ( ! confirm( hmbkp.delete_backup ) )
e.preventDefault();
} );
// Show delete confirm message for remove exclude rule
$( document ).on( 'click', '.hmbkp-edit-schedule-excludes-form .delete-action', function( e ) {
if ( ! confirm( hmbkp.remove_exclude_rule ) )
e.preventDefault();
} );
// Preview exclude rule
$( document ).on( 'click', '.hmbkp_preview_exclude_rule', function() {
if ( ! $( '.hmbkp_add_exclude_rule input' ).val() ) {
$( '.hmbkp_add_exclude_rule ul' ).remove();
$( '.hmbkp_add_exclude_rule p' ).remove();
return;
}
$( this ).addClass( 'hmbkp-ajax-loading' ).attr( 'disabled', 'disabled' );
$.post(
ajaxurl,
{ 'nonce' : hmbkp.nonce, 'action' : 'hmbkp_file_list', 'hmbkp_schedule_excludes' : $( '.hmbkp_add_exclude_rule input' ).val(), 'hmbkp_schedule_id' : $( '[name="hmbkp_schedule_id"]' ).val() },
function( data ) {
$( '.hmbkp_add_exclude_rule ul' ).remove();
$( '.hmbkp_add_exclude_rule p' ).remove();
if ( data.indexOf( 'hmbkp_file_list' ) != -1 )
$( '.hmbkp_add_exclude_rule' ).append( data );
else
$( '.hmbkp_add_exclude_rule' ).append( '<p>There was an error previewing the exclude rule.</p>' );
$( '.hmbkp-edit-schedule-excludes-form' ).addClass( 'hmbkp-exclude-preview-open' );
$.colorbox.resize();
}
)
} );
// Fire the preview button when the enter key is pressed in the preview input
$( document ).on( 'keypress', '.hmbkp_add_exclude_rule input', function( e ) {
if ( ! $( '.hmbkp_add_exclude_rule input' ).val() )
return true;
var code = ( e.keyCode ? e.keyCode : e.which );
if ( code != 13 )
return true;
$( '.hmbkp_preview_exclude_rule' ).click();
e.preventDefault();
} );
// Cancel add exclude rule
$( document ).on( 'click', '.hmbkp_cancel_save_exclude_rule, .hmbkp-edit-schedule-excludes-form .submit button', function() {
$( '.hmbkp_add_exclude_rule ul' ).remove();
$( '.hmbkp_add_exclude_rule p' ).remove();
$( '.hmbkp-edit-schedule-excludes-form' ).removeClass( 'hmbkp-exclude-preview-open' );
$.colorbox.resize();
} );
// Add exclude rule
$( document ).on( 'click', '.hmbkp_save_exclude_rule', function() {
$( this ).addClass( 'hmbkp-ajax-loading' ).attr( 'disabled', 'disabled' );
$.post(
ajaxurl,
{ 'nonce' : hmbkp.nonce, 'action' : 'hmbkp_add_exclude_rule', 'hmbkp_exclude_rule' : $( '.hmbkp_add_exclude_rule input' ).val(), 'hmbkp_schedule_id' : $( '[name="hmbkp_schedule_id"]' ).val() },
function( data ) {
$( '.hmbkp-edit-schedule-excludes-form' ).replaceWith( data );
$( '.hmbkp-edit-schedule-excludes-form' ).show();
$( '.hmbkp-tabs' ).tabs();
$.colorbox.resize();
}
);
} );
// Remove exclude rule
$( document ).on( 'click', '.hmbkp-edit-schedule-excludes-form td a', function( e ) {
$( this ).addClass( 'hmbkp-ajax-loading' ).text( '' ).attr( 'disabled', 'disabled' );
$.colorbox.resize();
e.preventDefault();
$.get(
ajaxurl,
{ 'action' : 'hmbkp_delete_exclude_rule', 'hmbkp_exclude_rule' : $( this ).closest( 'td' ).attr( 'data-hmbkp-exclude-rule' ), 'hmbkp_schedule_id' : $( '[name="hmbkp_schedule_id"]' ).val() },
function( data ) {
$( '.hmbkp-edit-schedule-excludes-form' ).replaceWith( data );
$( '.hmbkp-edit-schedule-excludes-form' ).show();
$( '.hmbkp-tabs' ).tabs();
$.colorbox.resize();
}
);
} );
// Edit schedule form submit
$( document ).on( 'submit', 'form.hmbkp-form', function( e ) {
var $isDestinationSettingsForm = $( this ).find( 'button[type="submit"]' ).hasClass( "dest-settings-save" );
var isNewSchedule = $( this ).closest( 'form' ).attr( 'data-schedule-action' ) == 'add' ? true : false;
var scheduleId = $( this ).closest( 'form' ).find( '[name="hmbkp_schedule_id"]' ).val();
// Only continue if we have a schedule id
if ( typeof( scheduleId ) == 'undefined' )
return;
// Warn that backups will be deleted if max backups has been set to less than the number of backups currently stored
if ( ! isNewSchedule && Number( $( 'input[name="hmbkp_schedule_max_backups"]' ).val() ) < Number( $( '.hmbkp_manage_backups_row' ).size() ) && ! confirm( hmbkp.remove_old_backups ) )
return false;
$( this ).find( 'button[type="submit"]' ).addClass( 'hmbkp-ajax-loading' ).attr( 'disabled', 'disabled' );
$( '.hmbkp-error span' ).remove();
$( '.hmbkp-error' ).removeClass( 'hmbkp-error' );
e.preventDefault();
$.get(
ajaxurl + '?' + $( this ).serialize(),
{ 'action' : 'hmbkp_edit_schedule_submit' },
function( data ) {
if ( ( data.success === true ) && ( $isDestinationSettingsForm === false ) ) {
$.colorbox.close();
// Reload the page so we see changes
if ( isNewSchedule )
location.replace( '//' + location.host + location.pathname + '?page=' + hmbkp.page_slug + '&hmbkp_schedule_id=' + scheduleId );
else
location.reload();
} else if( data.success === true ) {
// nothing for now
} else {
// Get the errors json string
var errors = data.data;
// Loop through the errors
$.each( errors, function( key, value ) {
var selector = key.replace(/(:|\.|\[|\])/g,'\\$1');
// Focus the first field that errored
if ( typeof( hmbkp_focused ) == 'undefined' ) {
$( '#' + selector ).focus();
hmbkp_focused = true;
}
// Add an error class to all fields with errors
$( 'label[for=' + selector + ']' ).addClass( 'hmbkp-error' );
$( '#' + selector ).next( 'span' ).remove();
// Add the error message
$( '#' + selector ).after( '<span class="hmbkp-error">' + value + '</span>' );
} );
}
}
);
} );
// Test the cron response using ajax
$.post( ajaxurl, { 'nonce' : hmbkp.nonce, 'action' : 'hmbkp_cron_test' },
function( data ) {
if ( data != 1 ) {
$( '.wrap > h2' ).after( data );
}
}
);
// Calculate the estimated backup size
if ( $( '.hmbkp-schedule-sentence .calculating' ).size() ) {
$.post( ajaxurl, { 'nonce' : hmbkp.nonce, 'action' : 'hmbkp_calculate', 'hmbkp_schedule_id' : $( '[data-hmbkp-schedule-id]' ).attr( 'data-hmbkp-schedule-id' ) },
function( data ) {
if ( data.indexOf( 'title' ) != -1 )
$( '.hmbkp-schedule-sentence' ).replaceWith( data );
// Fail silently for now
else
$( '.calculating' ).remove();
}
).error( function() {
// Fail silently for now
$( '.calculating' ).remove();
} );
}
if ( $( '.hmbkp-schedule-sentence.hmbkp-running' ).size() )
hmbkpRedirectOnBackupComplete( $( '[data-hmbkp-schedule-id]' ).attr( 'data-hmbkp-schedule-id' ), true );
// Run a backup
$( document ).on( 'click', '.hmbkp-run', function( e ) {
$( this ).closest( '.hmbkp-schedule-sentence' ).addClass( 'hmbkp-running' );
$( '.hmbkp-error' ).removeClass( 'hmbkp-error' );
scheduleId = $( '[data-hmbkp-schedule-id]' ).attr( 'data-hmbkp-schedule-id' );
ajaxRequest = $.post(
ajaxurl,
{ 'nonce' : hmbkp.nonce, 'action' : 'hmbkp_run_schedule', 'hmbkp_schedule_id' : scheduleId }
).done( function( data ) {
hmbkpCatchResponseAndOfferToEmail( data );
// Redirect back on error
} ).fail( function( jqXHR, textStatus ) {
hmbkpCatchResponseAndOfferToEmail( jqXHR.responseText );
} );
setTimeout( function() {
hmbkpRedirectOnBackupComplete( scheduleId, false )
}, 1000 );
e.preventDefault();
} );
} );
function hmbkpToggleScheduleFields( recurrence ){
recurrence = typeof recurrence !== 'undefined' ? recurrence : 'manually';
var settingFields = jQuery( '.recurring-setting');
var scheduleSettingFields = jQuery( '#schedule-start');
var twiceDailyNote = jQuery( 'p.twice-js' );
switch( recurrence ) {
case 'manually':
settingFields.hide();
break;
case 'hmbkp_hourly' : // fall through
case 'hmbkp_daily' :
settingFields.hide();
scheduleSettingFields.show();
twiceDailyNote.hide();
break;
case 'hmbkp_twicedaily' :
settingFields.hide();
scheduleSettingFields.show();
twiceDailyNote.show();
break;
case 'hmbkp_weekly' : // fall through
case 'hmbkp_fortnightly' :
settingFields.hide();
jQuery( '#start-day' ).show();
scheduleSettingFields.show();
twiceDailyNote.hide();
break;
case 'hmbkp_monthly' :
settingFields.hide();
scheduleSettingFields.show();
jQuery( '#start-date' ).show();
twiceDailyNote.hide();
break;
}
jQuery.colorbox.resize();
}
function hmbkpCatchResponseAndOfferToEmail( data ) {
// Backup Succeeded
if ( ! data || data == 0 )
location.reload( true );
// The backup failed, show the error and offer to have it emailed back
else {
jQuery( '.hmbkp-schedule-sentence.hmbkp-running' ).removeClass( 'hmbkp-running' ).addClass( 'hmbkp-error' );
jQuery.post(
ajaxurl,
{ 'nonce' : hmbkp.nonce, 'action' : 'hmbkp_backup_error', 'hmbkp_error' : data },
function( data ) {
if ( ! data || data == 0 )
return;
jQuery.colorbox( {
'innerWidth' : "320px",
'maxHeight' : "100%",
'html' : data,
'overlayClose' : false,
'escKey' : false,
'onLoad' : function() {
jQuery( '#cboxClose' ).remove();
jQuery.colorbox.resize();
}
} );
}
);
}
jQuery( document ).one( 'click', '.hmbkp_send_error_via_email', function( e ) {
e.preventDefault();
jQuery( this ).addClass( 'hmbkp-ajax-loading' ).attr( 'disabled', 'disabled' );
jQuery.post(
ajaxurl,
{ 'nonce' : hmbkp.nonce, 'action' : 'hmbkp_email_error', 'hmbkp_error' : data },
function( data ) {
jQuery.colorbox.close();
}
)
} );
}
function hmbkpRedirectOnBackupComplete( schedule_id, redirect ) {
jQuery.post(
ajaxurl,
{ 'nonce':hmbkp.nonce, 'action' : 'hmbkp_is_in_progress', 'hmbkp_schedule_id' : jQuery( '[data-hmbkp-schedule-id]' ).attr( 'data-hmbkp-schedule-id' ) },
function( data ) {
if ( data == 0 && redirect === true && ! jQuery( '.hmbkp-error' ).size() ) {
location.reload( true );
} else {
if ( data != 0 ) {
redirect = true;
jQuery( '.hmbkp-status' ).remove();
jQuery( '.hmbkp-schedule-actions' ).replaceWith( data );
}
setTimeout( function() {
hmbkpRedirectOnBackupComplete( schedule_id, redirect );
}, 5000 );
}
}
);
}
| JavaScript |
jQuery( function ( $ ) {
$( 'a.activate-option' ).click( function(){
var link = $( this );
if ( link.hasClass( 'clicked' ) ) {
link.removeClass( 'clicked' );
}
else {
link.addClass( 'clicked' );
}
$( '.toggle-have-key' ).slideToggle( 'slow', function() {});
return false;
});
$('.akismet-status').each(function () {
var thisId = $(this).attr('commentid');
$(this).prependTo('#comment-' + thisId + ' .column-comment');
});
$('.akismet-user-comment-count').each(function () {
var thisId = $(this).attr('commentid');
$(this).insertAfter('#comment-' + thisId + ' .author strong:first').show();
});
$('#the-comment-list').find('tr.comment, tr[id ^= "comment-"]').find('.column-author a[title ^= "http://"]').each(function () {
var thisTitle = $(this).attr('title');
thisCommentId = $(this).parents('tr:first').attr('id').split("-");
$(this).attr("id", "author_comment_url_"+ thisCommentId[1]);
if (thisTitle) {
$(this).after(
$( '<a href="#" class="remove_url">x</a>' )
.attr( 'commentid', thisCommentId[1] )
.attr( 'title', WPAkismet.strings['Remove this URL'] )
);
}
});
$('.remove_url').live('click', function () {
var thisId = $(this).attr('commentid');
var data = {
action: 'comment_author_deurl',
_wpnonce: WPAkismet.comment_author_url_nonce,
id: thisId
};
$.ajax({
url: ajaxurl,
type: 'POST',
data: data,
beforeSend: function () {
// Removes "x" link
$("a[commentid='"+ thisId +"']").hide();
// Show temp status
$("#author_comment_url_"+ thisId).html( $( '<span/>' ).text( WPAkismet.strings['Removing...'] ) );
},
success: function (response) {
if (response) {
// Show status/undo link
$("#author_comment_url_"+ thisId)
.attr('cid', thisId)
.addClass('akismet_undo_link_removal')
.html(
$( '<span/>' ).text( WPAkismet.strings['URL removed'] )
)
.append( ' ' )
.append(
$( '<span/>' )
.text( WPAkismet.strings['(undo)'] )
.addClass( 'akismet-span-link' )
);
}
}
});
return false;
});
$('.akismet_undo_link_removal').live('click', function () {
var thisId = $(this).attr('cid');
var thisUrl = $(this).attr('href').replace("http://www.", "").replace("http://", "");
var data = {
action: 'comment_author_reurl',
_wpnonce: WPAkismet.comment_author_url_nonce,
id: thisId,
url: thisUrl
};
$.ajax({
url: ajaxurl,
type: 'POST',
data: data,
beforeSend: function () {
// Show temp status
$("#author_comment_url_"+ thisId).html( $( '<span/>' ).text( WPAkismet.strings['Re-adding...'] ) );
},
success: function (response) {
if (response) {
// Add "x" link
$("a[commentid='"+ thisId +"']").show();
// Show link
$("#author_comment_url_"+ thisId).removeClass('akismet_undo_link_removal').html(thisUrl);
}
}
});
return false;
});
$('a[id^="author_comment_url"], tr.pingback td.column-author a:first-of-type').mouseover(function () {
var wpcomProtocol = ( 'https:' === location.protocol ) ? 'https://' : 'http://';
// Need to determine size of author column
var thisParentWidth = $(this).parent().width();
// It changes based on if there is a gravatar present
thisParentWidth = ($(this).parent().find('.grav-hijack').length) ? thisParentWidth - 42 + 'px' : thisParentWidth + 'px';
if ($(this).find('.mShot').length == 0 && !$(this).hasClass('akismet_undo_link_removal')) {
var self = $( this );
$('.widefat td').css('overflow', 'visible');
$(this).css('position', 'relative');
var thisHref = $.URLEncode( $(this).attr('href') );
$(this).append('<div class="mShot mshot-container" style="left: '+thisParentWidth+'"><div class="mshot-arrow"></div><img src="//s0.wordpress.com/mshots/v1/'+thisHref+'?w=450" width="450" class="mshot-image" style="margin: 0;" /></div>');
setTimeout(function () {
self.find( '.mshot-image' ).attr('src', '//s0.wordpress.com/mshots/v1/'+thisHref+'?w=450&r=2');
}, 6000);
setTimeout(function () {
self.find( '.mshot-image' ).attr('src', '//s0.wordpress.com/mshots/v1/'+thisHref+'?w=450&r=3');
}, 12000);
} else {
$(this).find('.mShot').css('left', thisParentWidth).show();
}
}).mouseout(function () {
$(this).find('.mShot').hide();
});
$('.checkforspam:not(.button-disabled)').click( function(e) {
$('.checkforspam:not(.button-disabled)').addClass('button-disabled');
$('.checkforspam-spinner').addClass( 'spinner' );
akismet_check_for_spam(0, 100);
e.preventDefault();
});
function akismet_check_for_spam(offset, limit) {
$.post(
ajaxurl,
{
'action': 'akismet_recheck_queue',
'offset': offset,
'limit': limit
},
function(result) {
if (result.processed < limit) {
window.location.reload();
}
else {
akismet_check_for_spam(offset + limit, limit);
}
}
);
}
});
// URL encode plugin
jQuery.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
while(x<c.length){var m=r.exec(c.substr(x));
if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
}else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;}
});
| JavaScript |
var ak_js = document.getElementById( "ak_js" );
if ( ! ak_js ) {
ak_js = document.createElement( 'input' );
ak_js.setAttribute( 'id', 'ak_js' );
ak_js.setAttribute( 'name', 'ak_js' );
ak_js.setAttribute( 'type', 'hidden' );
}
else {
ak_js.parentNode.removeChild( ak_js );
}
ak_js.setAttribute( 'value', ( new Date() ).getTime() );
var commentForm = document.getElementById( 'commentform' );
if ( commentForm ) {
commentForm.appendChild( ak_js );
}
else {
var replyRowContainer = document.getElementById( 'replyrow' );
if ( replyRowContainer ) {
var children = replyRowContainer.getElementsByTagName( 'td' );
if ( children.length > 0 ) {
children[0].appendChild( ak_js );
}
}
} | JavaScript |
jQuery(document).ready(function()
{
jQuery(".follow-button").click(function()
{
var author_id=jQuery(this).attr('data-author-id');
jQuery.ajax({
type:'POST',
url:ajax_object.ajaxurl,
data:
{
action:'follow',
author_id:author_id
},
success:function(data)
{
jQuery('#follow_status_'+author_id).html(data);
}
});
});
});
function bwg_sliceV(current_image_class, next_image_class, direction) {
if (direction == 'right') {
var translateY = 'min-auto';
}
else if (direction == 'left') {
var translateY = 'auto';
}
bwg_grid(10, 1, 0, 0, translateY, 1, 0, current_image_class, next_image_class, direction);
}
function bwg_grid(cols, rows, ro, tx, ty, sc, op, current_image_class, next_image_class, direction) {
/* If browser does not support CSS transitions.*/
var bwg_trans_in_progress = true;
var bwg_transition_duration=2;
/* Set active thumbnail.*/
jQuery(".bwg_filmstrip_thumbnail").removeClass("bwg_thumb_active").addClass("bwg_thumb_deactive");
jQuery("#bwg_filmstrip_thumbnail_" + bwg_current_key).removeClass("bwg_thumb_deactive").addClass("bwg_thumb_active");
/* The time (in ms) added to/subtracted from the delay total for each new gridlet.*/
var count = (bwg_transition_duration) / (cols + rows);
/* Gridlet creator (divisions of the image grid, positioned with background-images to replicate the look of an entire slide image when assembled)*/
function bwg_gridlet(width, height, top, img_top, left, img_left, src, imgWidth, imgHeight, c, r) {
var delay = (c + r) * count;
/* Return a gridlet elem with styles for specific transition.*/
return jQuery('<div class="bwg_gridlet" />').css({
width : width,
height : height,
top : top,
left : left,
backgroundImage : 'url("' + src + '")',
backgroundColor: jQuery(".spider_popup_wrap").css("background-color"),
/*backgroundColor: 'rgba(0, 0, 0, 0)',*/
backgroundRepeat: 'no-repeat',
backgroundPosition : img_left + 'px ' + img_top + 'px',
backgroundSize : imgWidth + 'px ' + imgHeight + 'px',
transition : 'all ' + bwg_transition_duration + 'ms ease-in-out ' + delay + 'ms',
transform : 'none'
});
}
/* Get the current slide's image.*/
var cur_img = jQuery(current_image_class).find('img');
/* Create a grid to hold the gridlets.*/
var grid = jQuery('<div />').addClass('bwg_grid');
/* Prepend the grid to the next slide (i.e. so it's above the slide image).*/
jQuery(current_image_class).prepend(grid);
/* Vars to calculate positioning/size of gridlets.*/
var cont = jQuery(".bwg_slide_bg");
var imgWidth = cur_img.width();
var imgHeight = cur_img.height();
var contWidth = cont.width(),
contHeight = cont.height(),
imgSrc = cur_img.attr('src'),/*.replace('/thumb', ''),*/
colWidth = Math.floor(contWidth / cols),
rowHeight = Math.floor(contHeight / rows),
colRemainder = contWidth - (cols * colWidth),
colAdd = Math.ceil(colRemainder / cols),
rowRemainder = contHeight - (rows * rowHeight),
rowAdd = Math.ceil(rowRemainder / rows),
leftDist = 0,
img_leftDist = Math.ceil((jQuery(".bwg_slide_bg").width() - cur_img.width()) / 2);
/* tx/ty args can be passed as 'auto'/'min-auto' (meaning use slide width/height or negative slide width/height).*/
tx = tx === 'auto' ? contWidth : tx;
tx = tx === 'min-auto' ? - contWidth : tx;
ty = ty === 'auto' ? contHeight : ty;
ty = ty === 'min-auto' ? - contHeight : ty;
/* Loop through cols.*/
for (var i = 0; i < cols; i++) {
var topDist = 0,
img_topDst = Math.floor((jQuery(".bwg_slide_bg").height() - cur_img.height()) / 2),
newColWidth = colWidth;
/* If imgWidth (px) does not divide cleanly into the specified number of cols, adjust individual col widths to create correct total.*/
if (colRemainder > 0) {
var add = colRemainder >= colAdd ? colAdd : colRemainder;
newColWidth += add;
colRemainder -= add;
}
/* Nested loop to create row gridlets for each col.*/
for (var j = 0; j < rows; j++) {
var newRowHeight = rowHeight,
newRowRemainder = rowRemainder;
/* If contHeight (px) does not divide cleanly into the specified number of rows, adjust individual row heights to create correct total.*/
if (newRowRemainder > 0) {
add = newRowRemainder >= rowAdd ? rowAdd : rowRemainder;
newRowHeight += add;
newRowRemainder -= add;
}
/* Create & append gridlet to grid.*/
grid.append(bwg_gridlet(newColWidth, newRowHeight, topDist, img_topDst, leftDist, img_leftDist, imgSrc, imgWidth, imgHeight, i, j));
topDist += newRowHeight;
img_topDst -= newRowHeight;
}
img_leftDist -= newColWidth;
leftDist += newColWidth;
}
/* Set event listener on last gridlet to finish transitioning.*/
var last_gridlet = grid.children().last();
/* Show grid & hide the image it replaces.*/
grid.show();
cur_img.css('opacity', 0);
/* Add identifying classes to corner gridlets (useful if applying border radius).*/
grid.children().first().addClass('rs-top-left');
grid.children().last().addClass('rs-bottom-right');
grid.children().eq(rows - 1).addClass('rs-bottom-left');
grid.children().eq(- rows).addClass('rs-top-right');
/* Execution steps.*/
setTimeout(function () {
grid.children().css({
opacity: op,
transform: 'rotate('+ ro +'deg) translateX('+ tx +'px) translateY('+ ty +'px) scale('+ sc +')'
});
}, 1);
jQuery(next_image_class).css('opacity', 1);
/* After transition.*/
jQuery(last_gridlet).one('webkitTransitionEnd transitionend otransitionend oTransitionEnd mstransitionend', jQuery.proxy(bwg_after_trans));
function bwg_after_trans() {
jQuery(current_image_class).css({'opacity' : 0, 'z-index': 1});
jQuery(next_image_class).css({'opacity' : 1, 'z-index' : 2});
cur_img.css('opacity', 1);
grid.remove();
bwg_trans_in_progress = false;
if (typeof event_stack !== 'undefined' && event_stack.length > 0) {
key = event_stack[0].split("-");
event_stack.shift();
bwg_change_image(key[0], key[1], data, true);
}
bwg_change_watermark_container();
}
} | JavaScript |
jQuery(document).ready(function(){
wsocket.onmessage = function(ev) {
var msg = JSON.parse(ev.data); //chuyen chuoi JSON thanh doi tuong JSON
var type = msg.type; //kieu message
var user_id =msg.receiver_id;
if (user_id== notify_obj.current_user) //neu la message cua user
{
jQuery.ajax({
type: "POST",
url: notify_obj.ajaxurl,
data: {
action: "get_counter",
receiver_id: user_id,
notification_type:type,
},
success: function(data) {
var json = JSON.parse(data);
var counter=json.counter;
if(type == 'like')
{
jQuery('.like_counter').css({opacity: 0});
jQuery('.like_counter').text(counter);
jQuery('.like_counter').css({top: '-10px'});
jQuery('.like_counter').animate({top: '-2px', opacity: 1});
//hieu ung am thanh
playNotificationSound();
}
else if(type == 'comment') //neu la message cua he thong
{
jQuery('.comment_counter').css({opacity: 0});
jQuery('.comment_counter').text(counter);
jQuery('.comment_counter').css({top: '-10px'});
jQuery('.comment_counter').animate({top: '-2px', opacity: 1});
}
else if(type == 'image') //neu la message cua he thong
{
jQuery('.image_counter').css({opacity: 0});
jQuery('.image_counter').text(counter);
jQuery('.image_counter').css({top: '-10px'});
jQuery('.image_counter').animate({top: '-2px', opacity: 1});
}
else if(type == 'message') //neu la message cua he thong
{
jQuery('.image_counter').css({opacity: 0});
jQuery('.image_counter').text(counter);
jQuery('.image_counter').css({top: '-10px'});
jQuery('.image_counter').animate({top: '-2px', opacity: 1});
}
}
});
}
};
jQuery("#btn_like").hover(function()
{
jQuery.ajax({
type: "POST",
url: notify_obj.ajaxurl,
data: {
action: "get_liked_list",
},
success: function(data) {
// var myWindow = window.open("", "MsgWindow", "width=1000, height=1000");
// myWindow.document.write(data);
jQuery("#liked_list").html(data);
jQuery("#liked_list a").addClass("liked_list_add");
jQuery("#liked_list li").addClass("liked_list_li_add");
jQuery('.like_counter').css({opacity: 0});
}
});
});
jQuery("#btn_comment").hover(function()
{
jQuery.ajax({
type: "POST",
url: notify_obj.ajaxurl,
data: {
action: "get_commented_list",
},
success: function(data) {
// var myWindow = window.open("", "MsgWindow", "width=1000, height=1000");
// myWindow.document.write(data);
jQuery("#commented_list").html(data);
jQuery("#commented_list a").addClass("liked_list_add");
jQuery("#commented_list li").addClass("liked_list_li_add");
jQuery('.comment_counter').css({opacity: 0});
}
});
});
});
function playNotificationSound()
{
var audio = {};
audio["walk"] = new Audio();
audio["walk"].src = notify_obj.current_url;
audio["walk"].addEventListener('load', function () {
audio["walk"].play();
});
}
| JavaScript |
var map;
var markers = [];
var infowindow = new google.maps.InfoWindow();
var current_latLng;
var current_address;
function initialize() {
var map_lat = 1;
var map_lng=1;
var image_latLgns_array = map_object.image_latLgns.split(';');
for(var i=0;i<image_latLgns_array.length-1;i++)
{
var latLng_array=image_latLgns_array[i].split(',');
map_lat=latLng_array[0];
map_lng=latLng_array[1];
var latLng_set=new google.maps.LatLng(latLng_array[0], latLng_array[1]);
add_Exist_Marker(latLng_set);
}
var mapOptions = {
center: new google.maps.LatLng(map_lat,map_lng),
zoom: 13
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Create the search box and link it to the UI element.
var input = /** @type {HTMLInputElement} */(
document.getElementById('pac-input'));
var types = document.getElementById('save-location');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
var searchBox = new google.maps.places.SearchBox(
/** @type {HTMLInputElement} */(input));
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
if(map_object.viewmode!='yes')
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
// Bias the SearchBox results towards places that are within the bounds of the
// current map's viewport.
if(map_object.viewmode!='yes')
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
if(map_object.viewmode!='yes')
google.maps.event.addListener(map, 'click', function(event) {
deleteMarkers();
addMarker(event.latLng);
});
//them cac marker cho cac vi tri anh dc chon
}
function addMarker(location) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': location}, function(results, status) {
var marker = new google.maps.Marker({
position: location,
map: map
});
current_address=results[1].formatted_address;
current_latLng=location.lat()+','+location.lng();
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
markers.push(marker);
});
}
function add_Exist_Marker(location) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': location}, function() {
var marker = new google.maps.Marker({
position: location,
map: map
});
markers.push(marker);
});
}
function clearMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
function deleteMarkers() {
clearMarkers();
markers = [];
}
google.maps.event.addDomListener(window, 'load', initialize);
jQuery(document).ready(function()
{
jQuery("#save-location").click(function()
{
jQuery.ajax({
type:'POST',
url:map_object.ajaxurl,
data:
{
action:'save_location',
image_ids:map_object.image_ids,
address:current_address,
latLng:current_latLng
},
success:function(data)
{
window.close();
//jQuery('#page-content').html(data);
}
});
});
}); | JavaScript |
jQuery( function ($){
if( typeof codepeople_theme_switch != 'undefined' )
{
function getWidth()
{
var myWidth = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
} else if( document.documentElement && document.documentElement.clientWidth ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
} else if( document.body && document.body.clientWidth ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
}
if( typeof window.devicePixelRatio != 'undefined' && window.devicePixelRatio ) myWidth = myWidth/window.devicePixelRatio;
return ( typeof screen != 'undefined' ) ? Math.min( screen.width, myWidth ) : myWidth;
};
var width = getWidth();
if( width < codepeople_theme_switch[ 'width' ] )
{
var selection = window.confirm( codepeople_theme_switch[ 'message' ] );
if( selection )
{
var loc = document.location.href;
loc += ( ( loc.indexOf( '?' ) == -1 ) ? '?' : '&' ) + 'theme_switch_width=' + width;
document.location = loc;
}
else
{
var loc = codepeople_theme_switch[ 'url' ];
loc += ( ( loc.indexOf( '?' ) == -1 ) ? '?' : '&' ) + 'theme_switch_denied=1';
$( 'body' ).append( $( '<img style="width:1px;height:1px;display:none;" src="' + loc + '" />' ) );
}
}
}
}); | JavaScript |
(function ($){
function empty( v )
{
return typeof v != 'undefined' && /^\s*$/.test( v );
};
function clear()
{
// Clear
$( '#cpts_screen_width' ).val( '' );
$( '#cpts_predefined_screen option:first' ).prop( 'selected', true );
};
window[ 'cptsDisplayPreview' ] = function()
{
var t = $( '[name="cpts_theme"]:checked' ),
w = $( '#cpts_screen_width' ).val(),
p = $( '.cp-preview-container' );
if( empty( w ) )
{
alert( 'The screen width is required' );
return;
}
p.show().html( '' );
$( '<iframe width="' + w + '" height="480px" src="' + cptsObj[ 'home' ] + '/?preview=1&preview_iframe=1&template=' + escape( t.attr( 'template' ) ) + '&stylesheet=' + escape( t.attr( 'stylesheet' ) ) + '"></iframe>' ).appendTo( p );
};
window[ 'cptsLoadScreenSizes' ] = function( e )
{
var o = $( e.options[ e.selectedIndex ] );
if( o.attr( 'w' ) )
{
$( '#cpts_screen_width' ).val( o.attr( 'w' ) );
}
};
})(jQuery); | JavaScript |
var Sphere = function (radius, sides, numOfItems){
for (var j = sides ; j > 0; j--){
for (var i = numOfItems / sides ; i > 0; i--)
{
var angle = i * Math.PI / (numOfItems / sides + 1);
var angleB = j * Math.PI * 2 / (sides);
var x = Math.sin(angleB) * Math.sin(angle) * radius;
var y = Math.cos(angleB) * Math.sin(angle) * radius;
var z = Math.cos(angle) * radius;
this.pointsArray.push(this.make3DPoint(x,y,z));
}
};
};
Sphere.prototype = new DisplayObject3D();
| JavaScript |
/*
* DisplayObject3D ----------------------------------------------
*/
var DisplayObject3D = function(){
return this;
};
DisplayObject3D.prototype._x = 0;
DisplayObject3D.prototype._y = 0;
//Create 3d Points
DisplayObject3D.prototype.make3DPoint = function(x,y,z) {
var point = {};
point.x = x;
point.y = y;
point.z = z;
return point;
};
//Create 2d Points
DisplayObject3D.prototype.make2DPoint = function(x, y, depth, scaleFactor){
var point = {};
point.x = x;
point.y = y;
point.depth = depth;
point.scaleFactor = scaleFactor;
return point;
};
DisplayObject3D.prototype.container = undefined;
DisplayObject3D.prototype.pointsArray = [];
DisplayObject3D.prototype.init = function (container){
this.container = container;
this.containerId = this.container.attr("id");
//if there isn't a ul than it creates a list of +'s
if (container.has("ul").length === 0){
for (i=0; i < this.pointsArray.length; i++){
this.container.append('<b id="tags_cloud_item'+i+'">+</b>');
}
}
};
/*
* DisplayObject3D End ----------------------------------------------
*/
/*
* Camera3D ----------------------------------------------
*/
var Camera3D = function (){};
Camera3D.prototype.x = 0;
Camera3D.prototype.y = 0;
Camera3D.prototype.z = 500;
Camera3D.prototype.focalLength = 1000;
Camera3D.prototype.scaleRatio = function(item){
return this.focalLength / (this.focalLength + item.z - this.z);
};
Camera3D.prototype.init = function (x, y, z, focalLength){
this.x = x;
this.y = y;
this.z = z;
this.focalLength = focalLength;
};
/*
* Camera3D End ----------------------------------------------
*/
/*
* Object3D ----------------------------------------------
*/
var Object3D = function (container){
this.container = container;
};
Object3D.prototype.objects = [];
Object3D.prototype.addChild = function (object3D){
this.objects.push(object3D);
object3D.init(this.container);
return object3D;
};
/*
* Object3D End ----------------------------------------------
*/
/*
* Scene3D ----------------------------------------------
*/
var Scene3D = function (){};
Scene3D.prototype.sceneItems = [];
Scene3D.prototype.addToScene = function (object){
this.sceneItems.push(object);
};
Scene3D.prototype.Transform3DPointsTo2DPoints = function(points, axisRotations, camera){
var TransformedPointsArray = [];
var sx = Math.sin(axisRotations.x);
var cx = Math.cos(axisRotations.x);
var sy = Math.sin(axisRotations.y);
var cy = Math.cos(axisRotations.y);
var sz = Math.sin(axisRotations.z);
var cz = Math.cos(axisRotations.z);
var x,y,z, xy,xz, yx,yz, zx,zy, scaleFactor;
var i = points.length;
while (i--){
x = points[i].x;
y = points[i].y;
z = points[i].z;
// rotation around x
xy = cx * y - sx * z;
xz = sx * y + cx * z;
// rotation around y
yz = cy * xz - sy * x;
yx = sy * xz + cy * x;
// rotation around z
zx = cz * yx - sz * xy;
zy = sz * yx + cz * xy;
scaleFactor = camera.focalLength / (camera.focalLength + yz);
x = zx * scaleFactor;
y = zy * scaleFactor;
z = yz;
var displayObject = new DisplayObject3D();
TransformedPointsArray[i] = displayObject.make2DPoint(x, y, -z, scaleFactor);
}
return TransformedPointsArray;
};
Scene3D.prototype.renderCamera = function (camera){
for(var i = 0 ; i < this.sceneItems.length; i++){
var obj = this.sceneItems[i].objects[0];
var screenPoints = this.Transform3DPointsTo2DPoints(obj.pointsArray, axisRotation, camera);
var hasList = (document.getElementById(obj.containerId).getElementsByTagName("ul").length > 0);
for (k=0; k < obj.pointsArray.length; k++){
var currItem = null;
if (hasList){
currItem = document.getElementById(obj.containerId).getElementsByTagName("ul")[0].getElementsByTagName("li")[k];
}else{
currItem = document.getElementById(obj.containerId).getElementsByTagName("*")[k];
}
if(currItem){
currItem._x = screenPoints[k].x;
currItem._y = screenPoints[k].y;
currItem.scale = screenPoints[k].scaleFactor;
currItem.style.position = "absolute";
currItem.style.top = (currItem._y + jQuery("#" + obj.containerId).height() * 0.4)+'px';
currItem.style.left = (currItem._x + jQuery("#" + obj.containerId).width() * 0.4)+'px';
currItem.style.fontSize = 100 * currItem.scale + '%';
jQuery(currItem).css({opacity:(currItem.scale-.5)});
curChild = jQuery(currItem).find("#imgg");
if (curChild) {
jQuery(currItem).css("zIndex", Math.round(currItem.scale * 100));
curChild.css({maxWidth:(currItem.scale*50)});
curChild.css({maxHeight:(currItem.scale*50)});
}
}
}
}
};
/*
* Scene3D End ----------------------------------------------
*/
//Center for rotation
var axisRotation = new DisplayObject3D().make3DPoint(0,0,0);
| JavaScript |
/*
* jQuery.fullscreen library v0.4.0
* Copyright (c) 2013 Vladimir Zhuravlev
*
* @license https://github.com/private-face/jquery.fullscreen/blob/master/LICENSE
*
* Date: Wed Dec 11 22:45:17 ICT 2013
**/
;(function($) {
function defined(a) {
return typeof a !== 'undefined';
}
function extend(child, parent, prototype) {
var F = function() {};
F.prototype = parent.prototype;
child.prototype = new F();
child.prototype.constructor = child;
parent.prototype.constructor = parent;
child._super = parent.prototype;
if (prototype) {
$.extend(child.prototype, prototype);
}
}
var SUBST = [
['', ''], // spec
['exit', 'cancel'], // firefox & old webkits expect cancelFullScreen instead of exitFullscreen
['screen', 'Screen'] // firefox expects FullScreen instead of Fullscreen
];
var VENDOR_PREFIXES = ['', 'o', 'ms', 'moz', 'webkit', 'webkitCurrent'];
function native(obj, name) {
var prefixed;
if (typeof obj === 'string') {
name = obj;
obj = document;
}
for (var i = 0; i < SUBST.length; ++i) {
name = name.replace(SUBST[i][0], SUBST[i][1]);
for (var j = 0; j < VENDOR_PREFIXES.length; ++j) {
prefixed = VENDOR_PREFIXES[j];
prefixed += j === 0 ? name : name.charAt(0).toUpperCase() + name.substr(1);
if (defined(obj[prefixed])) {
return obj[prefixed];
}
}
}
return void 0;
}var ua = navigator.userAgent;
var fsEnabled = native('fullscreenEnabled');
var IS_ANDROID_CHROME = ua.indexOf('Android') !== -1 && ua.indexOf('Chrome') !== -1;
var IS_NATIVELY_SUPPORTED =
!IS_ANDROID_CHROME &&
defined(native('fullscreenElement')) &&
(!defined(fsEnabled) || fsEnabled === true);
var version = $.fn.jquery.split('.');
var JQ_LT_17 = (parseInt(version[0]) < 2 && parseInt(version[1]) < 7);
var FullScreenAbstract = function() {
this.__options = null;
this._fullScreenElement = null;
this.__savedStyles = {};
};
FullScreenAbstract.prototype = {
_DEFAULT_OPTIONS: {
styles: {
'boxSizing': 'border-box',
'MozBoxSizing': 'border-box',
'WebkitBoxSizing': 'border-box'
},
toggleClass: null
},
__documentOverflow: '',
__htmlOverflow: '',
_preventDocumentScroll: function() {
this.__documentOverflow = $('body')[0].style.overflow;
this.__htmlOverflow = $('html')[0].style.overflow;
// $('body, html').css('overflow', 'hidden');
},
_allowDocumentScroll: function() {
// $('body')[0].style.overflow = this.__documentOverflow;
// $('html')[0].style.overflow = this.__htmlOverflow;
},
_fullScreenChange: function() {
if (!this.isFullScreen()) {
this._allowDocumentScroll();
this._revertStyles();
this._triggerEvents();
this._fullScreenElement = null;
} else {
this._preventDocumentScroll();
this._triggerEvents();
}
},
_fullScreenError: function(e) {
this._revertStyles();
this._fullScreenElement = null;
if (e) {
$(document).trigger('fscreenerror', [e]);
}
},
_triggerEvents: function() {
$(this._fullScreenElement).trigger(this.isFullScreen() ? 'fscreenopen' : 'fscreenclose');
$(document).trigger('fscreenchange', [this.isFullScreen(), this._fullScreenElement]);
},
_saveAndApplyStyles: function() {
var $elem = $(this._fullScreenElement);
this.__savedStyles = {};
for (var property in this.__options.styles) {
// save
this.__savedStyles[property] = this._fullScreenElement.style[property];
// apply
this._fullScreenElement.style[property] = this.__options.styles[property];
}
if (this.__options.toggleClass) {
$elem.addClass(this.__options.toggleClass);
}
},
_revertStyles: function() {
var $elem = $(this._fullScreenElement);
for (var property in this.__options.styles) {
this._fullScreenElement.style[property] = this.__savedStyles[property];
}
if (this.__options.toggleClass) {
$elem.removeClass(this.__options.toggleClass);
}
},
open: function(elem, options) {
// do nothing if request is for already fullscreened element
if (elem === this._fullScreenElement) {
return;
}
// exit active fullscreen before opening another one
if (this.isFullScreen()) {
this.exit();
}
// save fullscreened element
this._fullScreenElement = elem;
// apply options, if any
this.__options = $.extend(true, {}, this._DEFAULT_OPTIONS, options);
// save current element styles and apply new
this._saveAndApplyStyles();
},
exit: null,
isFullScreen: null,
isNativelySupported: function() {
return IS_NATIVELY_SUPPORTED;
}
};
var FullScreenNative = function() {
FullScreenNative._super.constructor.apply(this, arguments);
this.exit = $.proxy(native('exitFullscreen'), document);
this._DEFAULT_OPTIONS = $.extend(true, {}, this._DEFAULT_OPTIONS, {
'styles': {
'width': '100%',
'height': '100%'
}
});
$(document)
.bind(this._prefixedString('fullscreenchange') + ' MSFullscreenChange', $.proxy(this._fullScreenChange, this))
.bind(this._prefixedString('fullscreenerror') + ' MSFullscreenError', $.proxy(this._fullScreenError, this));
};
extend(FullScreenNative, FullScreenAbstract, {
VENDOR_PREFIXES: ['', 'o', 'moz', 'webkit'],
_prefixedString: function(str) {
return $.map(this.VENDOR_PREFIXES, function(s) {
return s + str;
}).join(' ');
},
open: function(elem, options) {
FullScreenNative._super.open.apply(this, arguments);
var requestFS = native(elem, 'requestFullscreen');
requestFS.call(elem);
},
exit: $.noop,
isFullScreen: function() {
return native('fullscreenElement') !== null;
},
element: function() {
return native('fullscreenElement');
}
});
var FullScreenFallback = function() {
FullScreenFallback._super.constructor.apply(this, arguments);
this._DEFAULT_OPTIONS = $.extend({}, this._DEFAULT_OPTIONS, {
'styles': {
'position': 'fixed',
'zIndex': '2147483647',
'left': 0,
'top': 0,
'bottom': 0,
'right': 0
}
});
this.__delegateKeydownHandler();
};
extend(FullScreenFallback, FullScreenAbstract, {
__isFullScreen: false,
__delegateKeydownHandler: function() {
var $doc = $(document);
$doc.delegate('*', 'keydown.fullscreen', $.proxy(this.__keydownHandler, this));
var data = JQ_LT_17 ? $doc.data('events') : $._data(document).events;
var events = data['keydown'];
if (!JQ_LT_17) {
events.splice(0, 0, events.splice(events.delegateCount - 1, 1)[0]);
} else {
data.live.unshift(data.live.pop());
}
},
__keydownHandler: function(e) {
if (this.isFullScreen() && e.which === 27) {
this.exit();
return false;
}
return true;
},
_revertStyles: function() {
FullScreenFallback._super._revertStyles.apply(this, arguments);
// force redraw (fixes bug in IE7 with content dissapearing)
this._fullScreenElement.offsetHeight;
},
open: function(elem) {
FullScreenFallback._super.open.apply(this, arguments);
this.__isFullScreen = true;
this._fullScreenChange();
},
exit: function() {
this.__isFullScreen = false;
this._fullScreenChange();
},
isFullScreen: function() {
return this.__isFullScreen;
},
element: function() {
return this.__isFullScreen ? this._fullScreenElement : null;
}
});$.fullscreen = IS_NATIVELY_SUPPORTED
? new FullScreenNative()
: new FullScreenFallback();
$.fn.fullscreen = function(options) {
var elem = this[0];
options = $.extend({
toggleClass: null,
// overflow: 'hidden'
}, options);
options.styles = {
// overflow: options.overflow
};
// delete options.overflow;
if (elem) {
$.fullscreen.open(elem, options);
}
return this;
};
})(jQuery);
| JavaScript |
function spider_frontend_ajax(form_id, current_view, id, album_gallery_id, cur_album_id, type, srch_btn, title) {
var page_number = jQuery("#page_number_" + current_view).val();
var bwg_previous_album_ids = jQuery('#bwg_previous_album_id_' + current_view).val();
var bwg_previous_album_page_numbers = jQuery('#bwg_previous_album_page_number_' + current_view).val();
var post_data = {};
if (album_gallery_id == 'back') { // Back from album.
var bwg_previous_album_id = bwg_previous_album_ids.split(",");
album_gallery_id = bwg_previous_album_id[0];
jQuery('#bwg_previous_album_id_' + current_view).val(bwg_previous_album_ids.replace(bwg_previous_album_id[0] + ',', ''));
var bwg_previous_album_page_number = bwg_previous_album_page_numbers.split(",");
page_number = bwg_previous_album_page_number[0];
jQuery('#bwg_previous_album_page_number_' + current_view).val(bwg_previous_album_page_numbers.replace(bwg_previous_album_page_number[0] + ',', ''));
}
else if (cur_album_id != '') { // Enter album (not change the page).
jQuery('#bwg_previous_album_id_' + current_view).val(cur_album_id + ',' + bwg_previous_album_ids);
if (page_number) {
jQuery('#bwg_previous_album_page_number_' + current_view).val(page_number + ',' + bwg_previous_album_page_numbers);
}
page_number = 1;
}
if (srch_btn) { // Start search.
page_number = 1;
}
if (typeof title == "undefined") {
var title = "";
}
post_data["page_number_" + current_view] = page_number;
post_data["album_gallery_id_" + current_view] = album_gallery_id;
post_data["bwg_previous_album_id_" + current_view] = jQuery('#bwg_previous_album_id_' + current_view).val();
post_data["bwg_previous_album_page_number_" + current_view] = jQuery('#bwg_previous_album_page_number_' + current_view).val();
post_data["type_" + current_view] = type;
post_data["title_" + current_view] = title;
if (jQuery("#bwg_search_input_" + current_view).length > 0) { // Search box exists.
post_data["bwg_search_" + current_view] = jQuery("#bwg_search_input_" + current_view).val();
}
// Loading.
jQuery("#ajax_loading_" + current_view).css('display', '');
jQuery.post(
window.location,
post_data,
function (data) {
var str = jQuery(data).find('#' + form_id).html();
jQuery('#' + form_id).html(str);
// There are no images.
if (jQuery("#bwg_search_input_" + current_view).length > 0 && album_gallery_id == 0) { // Search box exists and not album view.
var bwg_images_count = jQuery('#bwg_images_count_' + current_view).val();
if (bwg_images_count == 0) {
var cont = jQuery("#" + id).parent().html();
var error_msg = '<div style="width:95%"><div class="error"><p><strong>' + bwg_objectL10n.bwg_search_result + '</strong></p></div></div>';
jQuery("#" + id).parent().html(error_msg + cont)
}
}
}
).success(function(jqXHR, textStatus, errorThrown) {
justified_layout();
jQuery("#ajax_loading_" + current_view).css('display', 'none');
// window.scroll(0, spider_get_pos(document.getElementById(form_id)));
jQuery("html, body").animate({scrollTop: jQuery('#' + form_id).offset().top - 150}, 500);
// For masonry view.
var cccount = 0;
var obshicccount = jQuery(".bwg_masonry_thumb_spun_" + current_view + " a").length;
jQuery(".bwg_masonry_thumb_spun_" + current_view + " a img").on("load", function() {
if (++cccount == obshicccount) {
window["bwg_masonry_" + current_view]();
}
});
});
// if (event.preventDefault) {
// event.preventDefault();
// }
// else {
// event.returnValue = false;
// }
function justified_layout()
{
var total_width=0;
var start_img=1;
var end_img=1;
var count=0;
jQuery( ".justified_layout" ).find( ".justfied_img" ).each(function( index ) {
count++;
});
console.log(count);
var container_w=jQuery(".justified_layout").width()-50;
jQuery( ".justified_layout" ).find( ".justfied_img" ).each(function( index ) {
var w=jQuery(this).width();
var h =jQuery(this).height();
var scale_current_w=250*w/h;//lay chieu rong cua anh khi chiu cao len 200.
var subtraction=0;//luu lai doi dai can giam
total_width+=scale_current_w;//tong chieu dai cac anh
if(total_width>container_w || (end_img==count&& total_width>(container_w*2/3)))//khi do dai lon hon 100 hoac anh da gap anh cuoi cung
{
subtraction=total_width-container_w;
var scale_h_reduce=250*container_w/total_width;
var start_loop=1;
var test=0;
jQuery( ".justified_layout" ).find( ".justfied_img" ).each(function( index ) {
if(start_loop>=start_img && start_loop<=end_img)//khi gap dong anh can sua
{
jQuery(this).height(scale_h_reduce);
jQuery(this).find(".image_info").height(scale_h_reduce);
jQuery(this).css({'width':'auto'});
test+=jQuery(this).width();
}
start_loop++;
});
console.log('test'+test+' h:'+scale_h_reduce);
console.log(start_img+' end :'+end_img+' scale_h_reduce: '+scale_h_reduce+'total_width:'+total_width);
start_img=end_img+1;
total_width=0;
}
if(end_img==count&& total_width<(container_w*2/3))//neu anh cuoi nho hon 2/3 thi set lai chieu cao la 250
{
jQuery( ".justified_layout" ).find( ".justfied_img" ).each(function( index ) {
var start=1;
if(start>=start_img && start<=end_img)
{
jQuery(this).height(250);
jQuery(this).css({'width':'auto'});
}
start++;
});
}
end_img++;
});
}
return false;
}
jQuery(document).ready(function()
{
justified_layout();
divH = divW = 0;
divW = jQuery(".justified_layout").width();
function checkResize(){
var w = jQuery(".justified_layout").width();
if (w!=divW) {
/*what ever*/
justified_layout();
divW = w;
}
}
jQuery(window).resize(checkResize);
var timer = setInterval(checkResize, 2000);
function justified_layout()
{
var total_width=0;
var start_img=1;
var end_img=1;
var count=0;
jQuery( ".justified_layout" ).find( ".justfied_img" ).each(function( index ) {
count++;
});
console.log(count);
var container_w=jQuery(".justified_layout").width()-50;
jQuery( ".justified_layout" ).find( ".justfied_img" ).each(function( index ) {
var w=jQuery(this).width();
var h =jQuery(this).height();
var scale_current_w=250*w/h;//lay chieu rong cua anh khi chiu cao len 200.
var subtraction=0;//luu lai doi dai can giam
total_width+=scale_current_w;//tong chieu dai cac anh
if(total_width>container_w || (end_img==count&& total_width>(container_w*2/3)))//khi do dai lon hon 100 hoac anh da gap anh cuoi cung
{
subtraction=total_width-container_w;
var scale_h_reduce=250*container_w/total_width;
var start_loop=1;
var test=0;
jQuery( ".justified_layout" ).find( ".justfied_img" ).each(function( index ) {
if(start_loop>=start_img && start_loop<=end_img)//khi gap dong anh can sua
{
jQuery(this).height(scale_h_reduce);
jQuery(this).find(".image_info").height(scale_h_reduce);
jQuery(this).css({'width':'auto'});
test+=jQuery(this).width();
}
start_loop++;
});
start_img=end_img+1;
total_width=0;
}
if(end_img==count&& total_width<(container_w*2/3))//neu anh cuoi nho hon 2/3 thi set lai chieu cao la 250
{
jQuery( ".justified_layout" ).find( ".justfied_img" ).each(function( index ) {
var start=1;
if(start>=start_img && start<=end_img)
{
jQuery(this).height(250);
jQuery(this).css({'width':'auto'});
}
start++;
});
}
end_img++;
});
}
}); | JavaScript |
/**
* jscolor, JavaScript Color Picker
* @version 1.3.9
* @license GNU Lesser General Public License,
* http://www.gnu.org/copyleft/lesser.html
* @author Jan Odvarko, http://odvarko.cz
* @created 2008-06-15
* @updated 2011-07-28
* @link http://jscolor.com
*/
var jscolor = {
// location of jscolor directory (leave empty to autodetect)
dir : '',
//class name
bindClass : 'color',
//automatic binding via <input class="...">
binding : true,
//use image preloading?
preloading : true,
install : function() {
jscolor.addEvent(window, 'load', jscolor.init);
},
init : function() {
if (jscolor.binding) {
jscolor.bind();
}
if (jscolor.preloading) {
jscolor.preload();
}
},
getDir : function() {
if (!jscolor.dir) {
var detected = jscolor.detectDir();
jscolor.dir = detected !== false ? detected : 'jscolor/';
}
return jscolor.dir;
},
detectDir : function() {
var base = location.href;
var e = document.getElementsByTagName('base');
for (var i = 0; i < e.length; i += 1) {
if (e[i].href) {
base = e[i].href;
}
}
var e = document.getElementsByTagName('script');
for (var i = 0; i < e.length; i += 1) {
if (e[i].src && /(^|\/)jscolor\.js([?#].*)?$/i.test(e[i].src)) {
var src = new jscolor.URI(e[i].src);
var srcAbs = src.toAbsolute(base);
srcAbs.path = srcAbs.path.replace(/[^\/]+$/, '');
srcAbs.query = null;
srcAbs.fragment = null;
return srcAbs.toString();
}
}
return false;
},
bind : function() {
var matchClass = new RegExp('(^|\\s)(' + jscolor.bindClass
+ ')\\s*(\\{[^}]*\\})?', 'i');
var e = document.getElementsByTagName('input');
for (var i = 0; i < e.length; i += 1) {
var m;
if (!e[i].color && e[i].className
&& (m = e[i].className.match(matchClass))) {
var prop = {};
if (m[3]) {
try {
eval('prop=' + m[3]);
} catch (eInvalidProp) {
}
}
e[i].color = new jscolor.color(e[i], prop);
}
}
},
preload : function() {
for (var fn in jscolor.imgRequire) {
if (jscolor.imgRequire.hasOwnProperty(fn)) {
jscolor.loadImage(fn);
}
}
},
images : {
pad : [ 181, 101 ],
sld : [ 16, 101 ],
cross : [ 15, 15 ],
arrow : [ 7, 11 ]
},
imgRequire : {},
imgLoaded : {},
requireImage : function(filename) {
jscolor.imgRequire[filename] = true;
},
loadImage : function(filename) {
if (!jscolor.imgLoaded[filename]) {
jscolor.imgLoaded[filename] = new Image();
jscolor.imgLoaded[filename].src = jscolor.getDir() + filename;
}
},
fetchElement : function(mixed) {
return typeof mixed === 'string' ? document.getElementById(mixed) : mixed;
},
addEvent : function(el, evnt, func) {
if (el.addEventListener) {
el.addEventListener(evnt, func, false);
} else if (el.attachEvent) {
el.attachEvent('on' + evnt, func);
}
},
fireEvent : function(el, evnt) {
if (!el) {
return;
}
if (document.createEvent) {
var ev = document.createEvent('HTMLEvents');
ev.initEvent(evnt, true, true);
el.dispatchEvent(ev);
} else if (document.createEventObject) {
var ev = document.createEventObject();
el.fireEvent('on' + evnt, ev);
} else if (el['on' + evnt]) {
// model (IE5)
el['on' + evnt]();
}
},
getElementPos : function(e) {
var e1 = e, e2 = e;
var x = 0, y = 0;
if (e1.offsetParent) {
do {
x += e1.offsetLeft;
y += e1.offsetTop;
} while (e1 = e1.offsetParent);
}
while ((e2 = e2.parentNode) && e2.nodeName.toUpperCase() !== 'BODY') {
x -= e2.scrollLeft;
y -= e2.scrollTop;
}
return [ x, y ];
},
getElementSize : function(e) {
return [ e.offsetWidth, e.offsetHeight ];
},
getRelMousePos : function(e) {
var x = 0, y = 0;
if (!e) {
e = window.event;
}
if (typeof e.offsetX === 'number') {
x = e.offsetX;
y = e.offsetY;
} else if (typeof e.layerX === 'number') {
x = e.layerX;
y = e.layerY;
}
return {
x : x,
y : y
};
},
getViewPos : function() {
if (typeof window.pageYOffset === 'number') {
return [ window.pageXOffset, window.pageYOffset ];
} else if (document.body
&& (document.body.scrollLeft || document.body.scrollTop)) {
return [ document.body.scrollLeft, document.body.scrollTop ];
} else if (document.documentElement
&& (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
return [ document.documentElement.scrollLeft,
document.documentElement.scrollTop ];
} else {
return [ 0, 0 ];
}
},
getViewSize : function() {
if (typeof window.innerWidth === 'number') {
return [ window.innerWidth, window.innerHeight ];
} else if (document.body
&& (document.body.clientWidth || document.body.clientHeight)) {
return [ document.body.clientWidth, document.body.clientHeight ];
} else if (document.documentElement
&& (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
return [ document.documentElement.clientWidth,
document.documentElement.clientHeight ];
} else {
return [ 0, 0 ];
}
},
URI : function(uri) {
this.scheme = null;
this.authority = null;
this.path = '';
this.query = null;
this.fragment = null;
this.parse = function(uri) {
var m = uri
.match(/^(([A-Za-z][0-9A-Za-z+.-]*)(:))?((\/\/)([^\/?#]*))?([^?#]*)((\?)([^#]*))?((#)(.*))?/);
this.scheme = m[3] ? m[2] : null;
this.authority = m[5] ? m[6] : null;
this.path = m[7];
this.query = m[9] ? m[10] : null;
this.fragment = m[12] ? m[13] : null;
return this;
};
this.toString = function() {
var result = '';
if (this.scheme !== null) {
result = result + this.scheme + ':';
}
if (this.authority !== null) {
result = result + '//' + this.authority;
}
if (this.path !== null) {
result = result + this.path;
}
if (this.query !== null) {
result = result + '?' + this.query;
}
if (this.fragment !== null) {
result = result + '#' + this.fragment;
}
return result;
};
this.toAbsolute = function(base) {
var base = new jscolor.URI(base);
var r = this;
var t = new jscolor.URI;
if (base.scheme === null) {
return false;
}
if (r.scheme !== null
&& r.scheme.toLowerCase() === base.scheme.toLowerCase()) {
r.scheme = null;
}
if (r.scheme !== null) {
t.scheme = r.scheme;
t.authority = r.authority;
t.path = removeDotSegments(r.path);
t.query = r.query;
} else {
if (r.authority !== null) {
t.authority = r.authority;
t.path = removeDotSegments(r.path);
t.query = r.query;
} else {
if (r.path === '') {
t.path = base.path;
if (r.query !== null) {
t.query = r.query;
} else {
t.query = base.query;
}
} else {
if (r.path.substr(0, 1) === '/') {
t.path = removeDotSegments(r.path);
} else {
if (base.authority !== null && base.path === '') {
// === ?
t.path = '/' + r.path;
} else {
t.path = base.path.replace(/[^\/]+$/, '') + r.path;
}
t.path = removeDotSegments(t.path);
}
t.query = r.query;
}
t.authority = base.authority;
}
t.scheme = base.scheme;
}
t.fragment = r.fragment;
return t;
};
function removeDotSegments(path) {
var out = '';
while (path) {
if (path.substr(0, 3) === '../' || path.substr(0, 2) === './') {
path = path.replace(/^\.+/, '').substr(1);
} else if (path.substr(0, 3) === '/./' || path === '/.') {
path = '/' + path.substr(3);
} else if (path.substr(0, 4) === '/../' || path === '/..') {
path = '/' + path.substr(4);
out = out.replace(/\/?[^\/]*$/, '');
} else if (path === '.' || path === '..') {
path = '';
} else {
var rm = path.match(/^\/?[^\/]*/)[0];
path = path.substr(rm.length);
out = out + rm;
}
}
return out;
}
if (uri) {
this.parse(uri);
}
},
/*
* Usage example: var myColor = new jscolor.color(myInputElement)
*/
color : function(target, prop) {
this.required = true;
this.adjust = true;
this.hash = false;
this.caps = true;
this.slider = true;
this.valueElement = target;
this.styleElement = target;
this.hsv = [ 0, 0, 1 ];
this.rgb = [ 1, 1, 1 ];
this.pickerOnfocus = true;
this.pickerMode = 'HSV';
this.pickerPosition = 'bottom';
this.pickerButtonHeight = 20;
this.pickerClosable = false;
this.pickerCloseText = 'Close';
this.pickerButtonColor = 'ButtonText';
this.pickerFace = 10;
this.pickerFaceColor = 'ThreeDFace';
this.pickerBorder = 1;
this.pickerBorderColor = 'ThreeDHighlight ThreeDShadow ThreeDShadow ThreeDHighlight';
// color
this.pickerInset = 1;
this.pickerInsetColor = 'ThreeDShadow ThreeDHighlight ThreeDHighlight ThreeDShadow';
// color
this.pickerZIndex = 10000;
for (var p in prop) {
if (prop.hasOwnProperty(p)) {
this[p] = prop[p];
}
}
this.hidePicker = function() {
if (isPickerOwner()) {
removePicker();
}
};
this.showPicker = function() {
if (!isPickerOwner()) {
var tp = jscolor.getElementPos(target);
var ts = jscolor.getElementSize(target);
var vp = jscolor.getViewPos();
var vs = jscolor.getViewSize();
var ps = getPickerDims(this);
var a, b, c;
switch (this.pickerPosition.toLowerCase()) {
case 'left':
a = 1;
b = 0;
c = -1;
break;
case 'right':
a = 1;
b = 0;
c = 1;
break;
case 'top':
a = 0;
b = 1;
c = -1;
break;
default:
a = 0;
b = 1;
c = 1;
break;
}
var l = (ts[b] + ps[b]) / 2;
var pp = [
-vp[a] + tp[a] + ps[a] > vs[a] ? (-vp[a] + tp[a] + ts[a] / 2 > vs[a] / 2
&& tp[a] + ts[a] - ps[a] >= 0 ? tp[a] + ts[a] - ps[a] : tp[a])
: tp[a],
-vp[b] + tp[b] + ts[b] + ps[b] - l + l * c > vs[b] ? (-vp[b]
+ tp[b] + ts[b] / 2 > vs[b] / 2
&& tp[b] + ts[b] - l - l * c >= 0 ? tp[b] + ts[b] - l - l * c
: tp[b] + ts[b] - l + l * c)
: (tp[b] + ts[b] - l + l * c >= 0 ? tp[b] + ts[b] - l + l * c
: tp[b] + ts[b] - l - l * c) ];
drawPicker(pp[a], pp[b]);
}
};
this.importColor = function() {
if (!valueElement) {
this.exportColor();
} else {
if (!this.adjust) {
if (!this.fromString(valueElement.value, leaveValue)) {
styleElement.style.backgroundColor = styleElement.jscStyle.backgroundColor;
styleElement.style.color = styleElement.jscStyle.color;
this.exportColor(leaveValue | leaveStyle);
}
} else if (!this.required && /^\s*$/.test(valueElement.value)) {
valueElement.value = '';
styleElement.style.backgroundColor = styleElement.jscStyle.backgroundColor;
styleElement.style.color = styleElement.jscStyle.color;
this.exportColor(leaveValue | leaveStyle);
} else if (this.fromString(valueElement.value)) {
// OK
} else {
this.exportColor();
}
}
};
this.exportColor = function(flags) {
if (!(flags & leaveValue) && valueElement) {
var value = this.toString();
if (this.caps) {
value = value.toUpperCase();
}
if (this.hash) {
value = '#' + value;
}
valueElement.value = value;
}
if (!(flags & leaveStyle) && styleElement) {
styleElement.style.backgroundColor = '#' + this.toString();
styleElement.style.color = 0.213 * this.rgb[0] + 0.715 * this.rgb[1]
+ 0.072 * this.rgb[2] < 0.5 ? '#FFF' : '#000';
}
if (!(flags & leavePad) && isPickerOwner()) {
redrawPad();
}
if (!(flags & leaveSld) && isPickerOwner()) {
redrawSld();
}
};
this.fromHSV = function(h, s, v, flags) {
h < 0 && (h = 0) || h > 6 && (h = 6);
s < 0 && (s = 0) || s > 1 && (s = 1);
v < 0 && (v = 0) || v > 1 && (v = 1);
this.rgb = HSV_RGB(h === null ? this.hsv[0] : (this.hsv[0] = h),
s === null ? this.hsv[1] : (this.hsv[1] = s),
v === null ? this.hsv[2] : (this.hsv[2] = v));
this.exportColor(flags);
};
this.fromRGB = function(r, g, b, flags) {
r < 0 && (r = 0) || r > 1 && (r = 1);
g < 0 && (g = 0) || g > 1 && (g = 1);
b < 0 && (b = 0) || b > 1 && (b = 1);
var hsv = RGB_HSV(r === null ? this.rgb[0] : (this.rgb[0] = r),
g === null ? this.rgb[1] : (this.rgb[1] = g),
b === null ? this.rgb[2] : (this.rgb[2] = b));
if (hsv[0] !== null) {
this.hsv[0] = hsv[0];
}
if (hsv[2] !== 0) {
this.hsv[1] = hsv[1];
}
this.hsv[2] = hsv[2];
this.exportColor(flags);
};
this.fromString = function(hex, flags) {
var m = hex.match(/^\W*([0-9A-F]{3}([0-9A-F]{3})?)\W*$/i);
if (!m) {
return false;
} else {
if (m[1].length === 6) {
this.fromRGB(parseInt(m[1].substr(0, 2), 16) / 255, parseInt(m[1]
.substr(2, 2), 16) / 255, parseInt(m[1].substr(4, 2), 16) / 255,
flags);
} else {
this.fromRGB(parseInt(m[1].charAt(0) + m[1].charAt(0), 16) / 255,
parseInt(m[1].charAt(1) + m[1].charAt(1), 16) / 255, parseInt(
m[1].charAt(2) + m[1].charAt(2), 16) / 255, flags);
}
return true;
}
};
this.toString = function() {
return ((0x100 | Math.round(255 * this.rgb[0])).toString(16).substr(1)
+ (0x100 | Math.round(255 * this.rgb[1])).toString(16).substr(1) + (0x100 | Math
.round(255 * this.rgb[2])).toString(16).substr(1));
};
function RGB_HSV(r, g, b) {
var n = Math.min(Math.min(r, g), b);
var v = Math.max(Math.max(r, g), b);
var m = v - n;
if (m === 0) {
return [ null, 0, v ];
}
var h = r === n ? 3 + (b - g) / m : (g === n ? 5 + (r - b) / m : 1
+ (g - r) / m);
return [ h === 6 ? 0 : h, m / v, v ];
}
function HSV_RGB(h, s, v) {
if (h === null) {
return [ v, v, v ];
}
var i = Math.floor(h);
var f = i % 2 ? h - i : 1 - (h - i);
var m = v * (1 - s);
var n = v * (1 - s * f);
switch (i) {
case 6:
case 0:
return [ v, n, m ];
case 1:
return [ n, v, m ];
case 2:
return [ m, v, n ];
case 3:
return [ m, n, v ];
case 4:
return [ n, m, v ];
case 5:
return [ v, m, n ];
}
}
function removePicker() {
delete jscolor.picker.owner;
document.getElementsByTagName('body')[0].removeChild(jscolor.picker.boxB);
}
function drawPicker(x, y) {
if (!jscolor.picker) {
jscolor.picker = {
box : document.createElement('div'),
boxB : document.createElement('div'),
pad : document.createElement('div'),
padB : document.createElement('div'),
padM : document.createElement('div'),
sld : document.createElement('div'),
sldB : document.createElement('div'),
sldM : document.createElement('div'),
btn : document.createElement('div'),
btnS : document.createElement('span'),
btnT : document.createTextNode(THIS.pickerCloseText)
};
for (var i = 0, segSize = 4; i < jscolor.images.sld[1]; i += segSize) {
var seg = document.createElement('div');
seg.style.height = segSize + 'px';
seg.style.fontSize = '1px';
seg.style.lineHeight = '0';
jscolor.picker.sld.appendChild(seg);
}
jscolor.picker.sldB.appendChild(jscolor.picker.sld);
jscolor.picker.box.appendChild(jscolor.picker.sldB);
jscolor.picker.box.appendChild(jscolor.picker.sldM);
jscolor.picker.padB.appendChild(jscolor.picker.pad);
jscolor.picker.box.appendChild(jscolor.picker.padB);
jscolor.picker.box.appendChild(jscolor.picker.padM);
jscolor.picker.btnS.appendChild(jscolor.picker.btnT);
jscolor.picker.btn.appendChild(jscolor.picker.btnS);
jscolor.picker.box.appendChild(jscolor.picker.btn);
jscolor.picker.boxB.appendChild(jscolor.picker.box);
}
var p = jscolor.picker;
// controls interaction
p.box.onmouseup = p.box.onmouseout = function() {
target.focus();
};
p.box.onmousedown = function() {
abortBlur = true;
};
p.box.onmousemove = function(e) {
if (holdPad || holdSld) {
holdPad && setPad(e);
holdSld && setSld(e);
if (document.selection) {
document.selection.empty();
} else if (window.getSelection) {
window.getSelection().removeAllRanges();
}
}
};
p.padM.onmouseup = p.padM.onmouseout = function() {
if (holdPad) {
holdPad = false;
jscolor.fireEvent(valueElement, 'change');
}
};
p.padM.onmousedown = function(e) {
holdPad = true;
setPad(e);
};
p.sldM.onmouseup = p.sldM.onmouseout = function() {
if (holdSld) {
holdSld = false;
jscolor.fireEvent(valueElement, 'change');
}
};
p.sldM.onmousedown = function(e) {
holdSld = true;
setSld(e);
};
// picker
var dims = getPickerDims(THIS);
p.box.style.width = dims[0] + 'px';
p.box.style.height = dims[1] + 'px';
// picker border
p.boxB.style.position = 'absolute';
p.boxB.style.clear = 'both';
p.boxB.style.left = x + 'px';
p.boxB.style.top = y + 'px';
p.boxB.style.zIndex = THIS.pickerZIndex;
p.boxB.style.border = THIS.pickerBorder + 'px solid';
p.boxB.style.borderColor = THIS.pickerBorderColor;
p.boxB.style.background = THIS.pickerFaceColor;
// pad image
p.pad.style.width = jscolor.images.pad[0] + 'px';
p.pad.style.height = jscolor.images.pad[1] + 'px';
// pad border
p.padB.style.position = 'absolute';
p.padB.style.left = THIS.pickerFace + 'px';
p.padB.style.top = THIS.pickerFace + 'px';
p.padB.style.border = THIS.pickerInset + 'px solid';
p.padB.style.borderColor = THIS.pickerInsetColor;
// pad mouse area
p.padM.style.position = 'absolute';
p.padM.style.left = '0';
p.padM.style.top = '0';
p.padM.style.width = THIS.pickerFace + 2 * THIS.pickerInset
+ jscolor.images.pad[0] + jscolor.images.arrow[0] + 'px';
p.padM.style.height = p.box.style.height;
p.padM.style.cursor = 'crosshair';
// slider image
p.sld.style.overflow = 'hidden';
p.sld.style.width = jscolor.images.sld[0] + 'px';
p.sld.style.height = jscolor.images.sld[1] + 'px';
// slider border
p.sldB.style.display = THIS.slider ? 'block' : 'none';
p.sldB.style.position = 'absolute';
p.sldB.style.right = THIS.pickerFace + 'px';
p.sldB.style.top = THIS.pickerFace + 'px';
p.sldB.style.border = THIS.pickerInset + 'px solid';
p.sldB.style.borderColor = THIS.pickerInsetColor;
// slider mouse area
p.sldM.style.display = THIS.slider ? 'block' : 'none';
p.sldM.style.position = 'absolute';
p.sldM.style.right = '0';
p.sldM.style.top = '0';
p.sldM.style.width = jscolor.images.sld[0] + jscolor.images.arrow[0]
+ THIS.pickerFace + 2 * THIS.pickerInset + 'px';
p.sldM.style.height = p.box.style.height;
try {
p.sldM.style.cursor = 'pointer';
} catch (eOldIE) {
p.sldM.style.cursor = 'hand';
}
// "close" button
function setBtnBorder() {
var insetColors = THIS.pickerInsetColor.split(/\s+/);
var pickerOutsetColor = insetColors.length < 2 ? insetColors[0]
: insetColors[1] + ' ' + insetColors[0] + ' ' + insetColors[0]
+ ' ' + insetColors[1];
p.btn.style.borderColor = pickerOutsetColor;
}
p.btn.style.display = THIS.pickerClosable ? 'block' : 'none';
p.btn.style.position = 'absolute';
p.btn.style.left = THIS.pickerFace + 'px';
p.btn.style.bottom = THIS.pickerFace + 'px';
p.btn.style.padding = '0 15px';
p.btn.style.height = '18px';
p.btn.style.border = THIS.pickerInset + 'px solid';
setBtnBorder();
p.btn.style.color = THIS.pickerButtonColor;
p.btn.style.font = '12px sans-serif';
p.btn.style.textAlign = 'center';
try {
p.btn.style.cursor = 'pointer';
} catch (eOldIE) {
p.btn.style.cursor = 'hand';
}
p.btn.onmousedown = function() {
THIS.hidePicker();
};
p.btnS.style.lineHeight = p.btn.style.height;
// load images in optimal order
switch (modeID) {
case 0:
var padImg = 'hs.png';
break;
case 1:
var padImg = 'hv.png';
break;
}
p.padM.style.backgroundImage = "url('" + jscolor.getDir() + "cross.gif')";
p.padM.style.backgroundRepeat = "no-repeat";
p.sldM.style.backgroundImage = "url('" + jscolor.getDir() + "arrow.gif')";
p.sldM.style.backgroundRepeat = "no-repeat";
p.pad.style.backgroundImage = "url('" + jscolor.getDir() + padImg + "')";
p.pad.style.backgroundRepeat = "no-repeat";
p.pad.style.backgroundPosition = "0 0";
// place pointers
redrawPad();
redrawSld();
jscolor.picker.owner = THIS;
document.getElementsByTagName('body')[0].appendChild(p.boxB);
}
function getPickerDims(o) {
var dims = [
2
* o.pickerInset
+ 2
* o.pickerFace
+ jscolor.images.pad[0]
+ (o.slider ? 2 * o.pickerInset + 2 * jscolor.images.arrow[0]
+ jscolor.images.sld[0] : 0),
o.pickerClosable ? 4 * o.pickerInset + 3 * o.pickerFace
+ jscolor.images.pad[1] + o.pickerButtonHeight : 2
* o.pickerInset + 2 * o.pickerFace + jscolor.images.pad[1] ];
return dims;
}
function redrawPad() {
// redraw the pad pointer
switch (modeID) {
case 0:
var yComponent = 1;
break;
case 1:
var yComponent = 2;
break;
}
var x = Math.round((THIS.hsv[0] / 6) * (jscolor.images.pad[0] - 1));
var y = Math.round((1 - THIS.hsv[yComponent])
* (jscolor.images.pad[1] - 1));
jscolor.picker.padM.style.backgroundPosition = (THIS.pickerFace
+ THIS.pickerInset + x - Math.floor(jscolor.images.cross[0] / 2))
+ 'px '
+ (THIS.pickerFace + THIS.pickerInset + y - Math
.floor(jscolor.images.cross[1] / 2)) + 'px';
// redraw the slider image
var seg = jscolor.picker.sld.childNodes;
switch (modeID) {
case 0:
var rgb = HSV_RGB(THIS.hsv[0], THIS.hsv[1], 1);
for (var i = 0; i < seg.length; i += 1) {
seg[i].style.backgroundColor = 'rgb('
+ (rgb[0] * (1 - i / seg.length) * 100) + '%,'
+ (rgb[1] * (1 - i / seg.length) * 100) + '%,'
+ (rgb[2] * (1 - i / seg.length) * 100) + '%)';
}
break;
case 1:
var rgb, s, c = [ THIS.hsv[2], 0, 0 ];
var i = Math.floor(THIS.hsv[0]);
var f = i % 2 ? THIS.hsv[0] - i : 1 - (THIS.hsv[0] - i);
switch (i) {
case 6:
case 0:
rgb = [ 0, 1, 2 ];
break;
case 1:
rgb = [ 1, 0, 2 ];
break;
case 2:
rgb = [ 2, 0, 1 ];
break;
case 3:
rgb = [ 2, 1, 0 ];
break;
case 4:
rgb = [ 1, 2, 0 ];
break;
case 5:
rgb = [ 0, 2, 1 ];
break;
}
for (var i = 0; i < seg.length; i += 1) {
s = 1 - 1 / (seg.length - 1) * i;
c[1] = c[0] * (1 - s * f);
c[2] = c[0] * (1 - s);
seg[i].style.backgroundColor = 'rgb(' + (c[rgb[0]] * 100) + '%,'
+ (c[rgb[1]] * 100) + '%,' + (c[rgb[2]] * 100) + '%)';
}
break;
}
}
function redrawSld() {
// redraw the slider pointer
switch (modeID) {
case 0:
var yComponent = 2;
break;
case 1:
var yComponent = 1;
break;
}
var y = Math.round((1 - THIS.hsv[yComponent])
* (jscolor.images.sld[1] - 1));
jscolor.picker.sldM.style.backgroundPosition = '0 '
+ (THIS.pickerFace + THIS.pickerInset + y - Math
.floor(jscolor.images.arrow[1] / 2)) + 'px';
}
function isPickerOwner() {
return jscolor.picker && jscolor.picker.owner === THIS;
}
function blurTarget() {
if (valueElement === target) {
THIS.importColor();
}
if (THIS.pickerOnfocus) {
THIS.hidePicker();
}
}
function blurValue() {
if (valueElement !== target) {
THIS.importColor();
}
}
function setPad(e) {
var mpos = jscolor.getRelMousePos(e);
var x = mpos.x - THIS.pickerFace - THIS.pickerInset;
var y = mpos.y - THIS.pickerFace - THIS.pickerInset;
switch (modeID) {
case 0:
THIS.fromHSV(x * (6 / (jscolor.images.pad[0] - 1)), 1 - y
/ (jscolor.images.pad[1] - 1), null, leaveSld);
break;
case 1:
THIS.fromHSV(x * (6 / (jscolor.images.pad[0] - 1)), null, 1 - y
/ (jscolor.images.pad[1] - 1), leaveSld);
break;
}
}
function setSld(e) {
var mpos = jscolor.getRelMousePos(e);
var y = mpos.y - THIS.pickerFace - THIS.pickerInset;
switch (modeID) {
case 0:
THIS.fromHSV(null, null, 1 - y / (jscolor.images.sld[1] - 1), leavePad);
break;
case 1:
THIS.fromHSV(null, 1 - y / (jscolor.images.sld[1] - 1), null, leavePad);
break;
}
}
var THIS = this;
var modeID = this.pickerMode.toLowerCase() === 'hvs' ? 1 : 0;
var abortBlur = false;
var valueElement = jscolor.fetchElement(this.valueElement), styleElement = jscolor
.fetchElement(this.styleElement);
var holdPad = false, holdSld = false;
//var leaveValue = 1 << 0, leaveStyle = 1 << 1, leavePad = 1 << 2, leaveSld = 1 << 3;
var leaveValue = 1, leaveStyle = 2, leavePad = 4, leaveSld = 8;
// target
jscolor.addEvent(target, 'focus', function() {
if (THIS.pickerOnfocus) {
THIS.showPicker();
}
});
jscolor.addEvent(target, 'blur', function() {
if (!abortBlur) {
window.setTimeout(function() {
abortBlur || blurTarget();
abortBlur = false;
}, 0);
} else {
abortBlur = false;
}
});
// valueElement
if (valueElement) {
var updateField = function() {
THIS.fromString(valueElement.value, leaveValue);
};
jscolor.addEvent(valueElement, 'keyup', updateField);
jscolor.addEvent(valueElement, 'input', updateField);
jscolor.addEvent(valueElement, 'blur', blurValue);
valueElement.setAttribute('autocomplete', 'off');
}
// styleElement
if (styleElement) {
styleElement.jscStyle = {
backgroundColor : styleElement.style.backgroundColor,
color : styleElement.style.color
};
}
// require images
switch (modeID) {
case 0:
jscolor.requireImage('hs.png');
break;
case 1:
jscolor.requireImage('hv.png');
break;
}
jscolor.requireImage('cross.gif');
jscolor.requireImage('arrow.gif');
this.importColor();
}
};
jscolor.install();
| JavaScript |
(function () {
tinymce.create('tinymce.plugins.bwg_mce', {
init:function (ed, url) {
var c = this;
c.url = url;
c.editor = ed;
ed.addCommand('mcebwg_mce', function () {
ed.windowManager.open({
file:bwg_admin_ajax,
width:1100 + ed.getLang('bwg_mce.delta_width', 0),
height:550 + ed.getLang('bwg_mce.delta_height', 0),
inline:1
}, {
plugin_url:url
});
var e = ed.selection.getNode(), d = wp.media.gallery, f;
if (typeof wp === "undefined" || !wp.media || !wp.media.gallery) {
return
}
if (e.nodeName != "IMG" || ed.dom.getAttrib(e, "class").indexOf("bwg_shortcode") == -1) {
return
}
f = d.edit("[" + ed.dom.getAttrib(e, "title") + "]");
});
ed.addButton('bwg_mce', {
title:'Insert Photo Gallery',
cmd:'mcebwg_mce',
image: url + '/images/bwg_edit_but.png'
});
ed.onMouseDown.add(function (d, f) {
if (f.target.nodeName == "IMG" && d.dom.hasClass(f.target, "bwg_shortcode")) {
var g = tinymce.activeEditor;
g.wpGalleryBookmark = g.selection.getBookmark("simple");
g.execCommand("mcebwg_mce");
}
});
ed.onBeforeSetContent.add(function (d, e) {
e.content = c._do_bwg(e.content)
});
ed.onPostProcess.add(function (d, e) {
if (e.get) {
e.content = c._get_bwg(e.content)
}
})
},
_do_bwg:function (ed) {
return ed.replace(/\[Best_Wordpress_Gallery([^\]]*)\]/g, function (d, c) {
return '<img src="' + bwg_plugin_url + '/images/bwg_shortcode.png" class="bwg_shortcode mceItem" title="Best_Wordpress_Gallery' + tinymce.DOM.encode(c) + '" />';
})
},
_get_bwg:function (b) {
function ed(c, d) {
d = new RegExp(d + '="([^"]+)"', "g").exec(c);
return d ? tinymce.DOM.decode(d[1]) : "";
}
return b.replace(/(?:<p[^>]*>)*(<img[^>]+>)(?:<\/p>)*/g, function (e, d) {
var c = ed(d, "class");
if (c.indexOf("bwg_shortcode") != -1) {
return "<p>[" + tinymce.trim(ed(d, "title")) + "]</p>"
}
return e
})
}
});
tinymce.PluginManager.add('bwg_mce', tinymce.plugins.bwg_mce);
})(); | JavaScript |
var isPopUpOpened = false;
function spider_createpopup(url, current_view, width, height, duration, description, lifetime) {
if (isPopUpOpened) { return };
isPopUpOpened = true;
if (spider_hasalreadyreceivedpopup(description) || spider_isunsupporteduseragent()) {
return;
}
jQuery("html").attr("style", "overflow:hidden !important;");
jQuery("#spider_popup_loading_" + current_view).css({display: "block"});
jQuery("#spider_popup_overlay_" + current_view).css({display: "block"});
jQuery.get(url, function(data) {
var popup = jQuery(
'<div id="spider_popup_wrap" class="spider_popup_wrap" style="' +
' width:' + width + 'px;' +
' height:' + height + 'px;' +
' margin-top:-' + height / 2 + 'px;' +
' margin-left: -' + width / 2 + 'px; ">' +
data +
'</div>')
.hide()
.appendTo("body");
spider_showpopup(description, lifetime, popup, duration);
}).success(function(jqXHR, textStatus, errorThrown) {
jQuery("#spider_popup_loading_" + current_view).css({display: "none !important;"});
});
}
function spider_showpopup(description, lifetime, popup, duration) {
isPopUpOpened = true;
popup.show();
spider_receivedpopup(description, lifetime);
}
function spider_hasalreadyreceivedpopup(description) {
if (document.cookie.indexOf(description) > -1) {
delete document.cookie[document.cookie.indexOf(description)];
}
return false;
}
function spider_receivedpopup(description, lifetime) {
var date = new Date();
date.setDate(date.getDate() + lifetime);
document.cookie = description + "=true;expires=" + date.toUTCString() + ";path=/";
}
function spider_isunsupporteduseragent() {
return (!window.XMLHttpRequest);
}
function spider_destroypopup(duration) {
if (document.getElementById("spider_popup_wrap") != null) {
jQuery(".spider_popup_wrap").remove();
jQuery(".spider_popup_loading").css({display: "none"});
jQuery(".spider_popup_overlay").css({display: "none"});
jQuery(document).off("keydown");
jQuery("html").attr("style", "overflow:auto !important");
}
isPopUpOpened = false;
var isMobile = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));
var viewportmeta = document.querySelector('meta[name="viewport"]');
if (isMobile && viewportmeta) {
viewportmeta.content = 'width=device-width, initial-scale=1';
}
clearInterval(bwg_playInterval);
}
// Submit popup.
function spider_ajax_save(form_id) {
var post_data = {};
post_data["bwg_name"] = jQuery("#bwg_name").val();
post_data["bwg_comment"] = jQuery("#bwg_comment").val();
post_data["bwg_email"] = jQuery("#bwg_email").val();
post_data["bwg_captcha_input"] = jQuery("#bwg_captcha_input").val();
post_data["ajax_task"] = jQuery("#ajax_task").val();
post_data["image_id"] = jQuery("#image_id").val();
post_data["comment_id"] = jQuery("#comment_id").val();
// Loading.
jQuery("#ajax_loading").css('height', jQuery(".bwg_comments").css('height'));
jQuery("#opacity_div").css('width', jQuery(".bwg_comments").css('width'));
jQuery("#opacity_div").css('height', jQuery(".bwg_comments").css('height'));
jQuery("#loading_div").css('width', jQuery(".bwg_comments").css('width'));
jQuery("#loading_div").css('height', jQuery(".bwg_comments").css('height'));
document.getElementById("opacity_div").style.display = '';
document.getElementById("loading_div").style.display = 'table-cell';
jQuery.post(
jQuery('#' + form_id).attr('action'),
post_data,
function (data) {
var str = jQuery(data).find('.bwg_comments').html();
jQuery('.bwg_comments').html(str);
}
).success(function(jqXHR, textStatus, errorThrown) {
document.getElementById("opacity_div").style.display = 'none';
document.getElementById("loading_div").style.display = 'none';
// Update scrollbar.
jQuery(".bwg_comments").mCustomScrollbar({scrollInertia: 150});
// Bind comment container close function to close button.
jQuery(".bwg_comments_close_btn").click(bwg_comment);
});
// if (event.preventDefault) {
// event.preventDefault();
// }
// else {
// event.returnValue = false;
// }
return false;
}
// Submit rating.
function spider_rate_ajax_save(form_id) {
var post_data = {};
post_data["image_id"] = jQuery("#" + form_id + " input[name='image_id']").val();
post_data["rate"] = jQuery("#" + form_id + " input[name='score']").val();
post_data["ajax_task"] = jQuery("#rate_ajax_task").val();
jQuery.post(
jQuery('#' + form_id).attr('action'),
post_data,
function (data) {
var str = jQuery(data).find('#' + form_id).html();
jQuery('#' + form_id).html(str);
}
).success(function(jqXHR, textStatus, errorThrown) {
});
// if (event.preventDefault) {
// event.preventDefault();
// }
// else {
// event.returnValue = false;
// }
return false;
}
// Set value by ID.
function spider_set_input_value(input_id, input_value) {
if (document.getElementById(input_id)) {
document.getElementById(input_id).value = input_value;
}
}
// Submit form by ID.
function spider_form_submit(event, form_id) {
if (document.getElementById(form_id)) {
document.getElementById(form_id).submit();
}
if (event.preventDefault) {
event.preventDefault();
}
else {
event.returnValue = false;
}
}
// Check if required field is empty.
function spider_check_required(id, name) {
if (jQuery('#' + id).val() == '') {
jQuery('#' + id).attr('style', 'border-color: #FF0000;');
jQuery('#' + id).focus();
return true;
}
else {
return false;
}
}
// Check Email.
function spider_check_email(id) {
if (jQuery('#' + id).val() != '') {
var email = jQuery('#' + id).val().replace(/^\s+|\s+$/g, '');
if (email.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) == -1) {
alert(bwg_objectL10n.bwg_mail_validation);
return true;
}
return false;
}
}
// Refresh captcha.
function bwg_captcha_refresh(id) {
if (document.getElementById(id + "_img") && document.getElementById(id + "_input")) {
srcArr = document.getElementById(id + "_img").src.split("&r=");
document.getElementById(id + "_img").src = srcArr[0] + '&r=' + Math.floor(Math.random() * 100);
document.getElementById(id + "_img").style.display = "inline-block";
document.getElementById(id + "_input").value = "";
}
}
| JavaScript |
function edit_tag(m) {
var name, slug, tr;
name = jQuery("#name" + m).html();
slug = jQuery("#slug" + m).html();
tr = ' <td id="td_check_'+m+'" ></td> <td id="td_id_'+m+'" ></td> <td id="td_name_'+m+'" class="edit_input"><input id="edit_tagname" name="tagname'+m+'" class="input_th2" type="text" value="'+name+'"></td> <td id="td_slug_'+m+'" class="edit_input"><input id="edit_slug" class="input_th2" name="slug'+m+'" type="text" value="'+slug+'"></td> <td id="td_count_'+m+'" ></td> <td id="td_edit_'+m+'" class="table_big_col"><a class="button-primary button button-small" onclick="save_tag('+m+')" >Lưu Tag</a></td><td id="td_delete_'+m+'" class="table_big_col" ></td> ';
jQuery("#tr_" + m).html(tr);
jQuery("#td_id_" + m).attr('class', 'table_big_col');
}
function save_tag(tag_id) {
var tagname=jQuery('input[name=tagname'+tag_id+']').val();
var slug = jQuery('input[name=slug'+tag_id+']').val();
var datas = "tagname="+tagname+"&"+"slug="+slug+"&"+"tag_id="+tag_id;
var td_check,td_name,td_slug,td_count,td_edit,td_delete,massege;
jQuery.ajax({
type: "POST",
url: ajax_url + "=bwg_edit_tag",
data: datas,
success: function(html) {
var tagname_slug=html;
var array = tagname_slug.split(".");
if (array[0] == "The slug must be unique.") {
massege = array[0];
}
else {
massege = "Item Succesfully Saved.";
jQuery("#td_check_" + tag_id).attr('class', 'table_small_col check-column');
td_check='<input id="check_'+tag_id+'" name="check_'+tag_id+'" type="checkbox" />';
jQuery("#td_check_" + tag_id).html(td_check);
jQuery("#td_id_" + tag_id).attr('class', 'table_small_col');
jQuery("#td_id_" + tag_id).html(tag_id);
jQuery("#td_name_" + tag_id).removeClass();
td_name='<a class="pointer" id="name'+tag_id+'" onclick="edit_tag('+tag_id+')" title="Edit">'+array[0]+'</a>';
jQuery("#td_name_" + tag_id).html(td_name);
jQuery("#td_slug_" + tag_id).removeClass();
td_slug='<a class="pointer" id="slug'+tag_id+'" onclick="edit_tag('+tag_id+')" title="Edit">'+array[1]+'</a>';
jQuery("#td_slug_" + tag_id).html(td_slug);
jQuery("#td_count_" + tag_id).attr('class', 'table_big_col');
td_count='<a class="pointer" id="count'+tag_id+'" onclick="edit_tag('+tag_id+')" title="Edit">'+array[2]+'</a>';
jQuery("#td_count_" + tag_id).html(td_count);
td_edit='<a class="pointer" onclick="edit_tag('+tag_id+')" >Sửa</a>';
jQuery("#td_edit_" + tag_id).html(td_edit);
var func1="spider_set_input_value('task', 'delete');";
var func2="spider_set_input_value('current_id', "+tag_id+");";
var func3="spider_form_submit('event', 'tags_form')";
td_delete='<a class="pointer" onclick="'+func1+func2+func3+'" >Xóa</a>';
jQuery("#td_delete_" + tag_id).html(td_delete);
}
if ((jQuery( ".updated" ) && jQuery( ".updated" ).attr("id")!='wordpress_message_2' ) || (jQuery( ".error" ) && jQuery( ".error" ).css("display")=="block")) {
if (jQuery( ".updated" ) && jQuery( ".updated" ).attr("id")!='wordpress_message_2' ){
jQuery(".updated").html("<strong><p>"+massege+"</p></strong>");
}
else {
jQuery(".error").html("<strong><p>"+massege+"</p></strong>");
jQuery(".error").attr('class', 'updated');
}
}
else {
jQuery("#wordpress_message_1").css("display", "block");
}
}
});
}
var bwg_save_count = 50;
function spider_ajax_save(form_id, tr_group) {
var ajax_task = jQuery("#ajax_task").val();
if (!tr_group) {
var tr_group = 1;
}
else if (ajax_task == 'ajax_apply' || ajax_task == 'ajax_save') {
ajax_task = '';
}
var name = jQuery("#name").val();
var slug = jQuery("#slug").val();
if ((typeof tinyMCE != "undefined") && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden() && tinyMCE.activeEditor.getContent) {
var description = tinyMCE.activeEditor.getContent();
}
else {
var description = jQuery("#description").val();
}
var preview_image = jQuery("#preview_image").val();
var published = jQuery("input[name=published]:checked").val();
var search_value = jQuery("#search_value").val();
var current_id = jQuery("#current_id").val();
var page_number = jQuery("#page_number").val();
var search_or_not = jQuery("#search_or_not").val();
var ids_string = jQuery("#ids_string").val();
var image_order_by = jQuery("#image_order_by").val();
var asc_or_desc = jQuery("#asc_or_desc").val();
var image_current_id = jQuery("#image_current_id").val();
ids_array = ids_string.split(",");
var tr_count = ids_array.length;
if (tr_count > bwg_save_count) {
// Remove items form begin and end of array.
ids_array.splice(tr_group * bwg_save_count, ids_array.length);
ids_array.splice(0, (tr_group - 1) * bwg_save_count);
ids_string = ids_array.join(",");
}
var post_data = {};
post_data["name"] = name;
post_data["slug"] = slug;
post_data["description"] = description;
post_data["preview_image"] = preview_image;
post_data["published"] = published;
post_data["search_value"] = search_value;
post_data["current_id"] = current_id;
post_data["page_number"] = page_number;
post_data["image_order_by"] = image_order_by;
post_data["asc_or_desc"] = asc_or_desc;
post_data["ids_string"] = ids_string;
post_data["task"] = "ajax_search";
post_data["ajax_task"] = ajax_task;
post_data["image_current_id"] = image_current_id;
post_data["image_width"] = jQuery("#image_width").val();
post_data["image_height"] = jQuery("#image_height").val();
//TODO: luu lai the loai
post_data["album_category"] = jQuery("#category").val();
var flag = false;
if (jQuery("#check_all_items").attr('checked') == 'checked') {
post_data["check_all_items"] = jQuery("#check_all_items").val();
post_data["added_tags_select_all"] = jQuery("#added_tags_select_all").val();
flag = true;
jQuery('#check_all_items').attr('checked', false);
}
for (var i in ids_array) {
if (ids_array.hasOwnProperty(i) && ids_array[i]) {
if (jQuery("#check_" + ids_array[i]).attr('checked') == 'checked') {
post_data["check_" + ids_array[i]] = jQuery("#check_" + ids_array[i]).val();
flag = true;
}
post_data["input_filename_" + ids_array[i]] = jQuery("#input_filename_" + ids_array[i]).val();
post_data["image_url_" + ids_array[i]] = jQuery("#image_url_" + ids_array[i]).val();
post_data["thumb_url_" + ids_array[i]] = jQuery("#thumb_url_" + ids_array[i]).val();
post_data["image_description_" + ids_array[i]] = jQuery("#image_description_" + ids_array[i]).val();
post_data["image_alt_text_" + ids_array[i]] = jQuery("#image_alt_text_" + ids_array[i]).val();
post_data["redirect_url_" + ids_array[i]] = jQuery("#redirect_url_" + ids_array[i]).val();
post_data["input_date_modified_" + ids_array[i]] = jQuery("#input_date_modified_" + ids_array[i]).val();
post_data["input_size_" + ids_array[i]] = jQuery("#input_size_" + ids_array[i]).val();
post_data["input_filetype_" + ids_array[i]] = jQuery("#input_filetype_" + ids_array[i]).val();
post_data["input_resolution_" + ids_array[i]] = jQuery("#input_resolution_" + ids_array[i]).val();
post_data["input_crop_" + ids_array[i]] = jQuery("#input_crop_" + ids_array[i]).val();
post_data["order_input_" + ids_array[i]] = jQuery("#order_input_" + ids_array[i]).val();
post_data["tags_" + ids_array[i]] = jQuery("#tags_" + ids_array[i]).val();
}
}
// Loading.
jQuery('#opacity_div').show();
jQuery('#loading_div').show();
jQuery.post(
jQuery('#' + form_id).action,
post_data,
function (data) {
var str = jQuery(data).find("#current_id").val();
jQuery("#current_id").val(str);
}
).success(function (data, textStatus, errorThrown) {
if (tr_count > bwg_save_count * tr_group) {
spider_ajax_save(form_id, ++tr_group);
return;
}
else {
var str = jQuery(data).find('#images_table').html();
jQuery('#images_table').html(str);
var str = jQuery(data).find('.tablenav').html();
jQuery('.tablenav').html(str);
jQuery("#show_hide_weights").val("Ẩn thứ tự cột");
spider_show_hide_weights();
spider_run_checkbox();
if (ajax_task == 'ajax_apply') {
jQuery('#message_div').html("<strong><p>Lưu thành công.</p></strong>");
jQuery('#message_div').show();
}
else if (ajax_task == 'recover') {
jQuery('#draganddrop').html("<strong><p>Phục hồi thành công.</p></strong>");
jQuery('#draganddrop').show();
}
else if (ajax_task == 'image_publish') {
jQuery('#draganddrop').html("<strong><p>Hiển thị công cộng thành công.</p></strong>");
jQuery('#draganddrop').show();
}
else if (ajax_task == 'image_unpublish') {
jQuery('#draganddrop').html("<strong><p>Hiển thị riêng tư thành công.</p></strong>");
jQuery('#draganddrop').show();
}
else if (ajax_task == 'image_delete') {
jQuery('#draganddrop').html("<strong><p>Xóa thành công.</p></strong>");
jQuery('#draganddrop').show();
}
else if (!flag && ((ajax_task == 'image_publish_all') || (ajax_task == 'image_unpublish_all') || (ajax_task == 'image_delete_all') || (ajax_task == 'image_set_watermark') || (ajax_task == 'image_recover_all') || (ajax_task == 'image_resize'))) {
jQuery('#draganddrop').html("<strong><p>Bạn phải chọn ít nhất một mục.</p></strong>");
jQuery('#draganddrop').show();
}
else if (ajax_task == 'image_publish_all') {
jQuery('#draganddrop').html("<strong><p>Hiển thị công cộng thành công.</p></strong>");
jQuery('#draganddrop').show();
}
else if (ajax_task == 'image_unpublish_all') {
jQuery('#draganddrop').html("<strong><p>Hiển thị riêng tư thành công.</p></strong>");
jQuery('#draganddrop').show();
}
else if (ajax_task == 'image_delete_all') {
jQuery('#draganddrop').html("<strong><p>Xóa thành công.</p></strong>");
jQuery('#draganddrop').show();
}
else if (ajax_task == 'image_set_watermark') {
jQuery('#draganddrop').html("<strong><p>Làm mờ thành công.</p></strong>");
jQuery('#draganddrop').show();
}
else if (ajax_task == 'image_resize') {
jQuery('#draganddrop').html("<strong><p>Đổi kích cở thành công.</p></strong>");
jQuery('#draganddrop').show();
}
else if (ajax_task == 'image_recover_all') {
jQuery('#draganddrop').html("<strong><p>Đặt lại thành công.</p></strong>");
jQuery('#draganddrop').show();
}
else {
jQuery('#draganddrop').html("<strong><p>Lưu thành công.</p></strong>");
jQuery('#draganddrop').show();
}
if (ajax_task == "ajax_save") {
jQuery('#' + form_id).submit();
}
jQuery('#opacity_div').hide();
jQuery('#loading_div').hide();
}
});
// if (event.preventDefault) {
// event.preventDefault();
// }
// else {
// event.returnValue = false;
// }
return false;
}
function save_location_all(url)
{
var ids_string = jQuery('#ids_string').val();
var ids_array = ids_string.split(',');
var post_ids=[];
for(var i in ids_array)
{
if (ids_array.hasOwnProperty(i) && ids_array[i]) {
if (jQuery("#check_" + ids_array[i]).attr('checked') == 'checked') {
post_ids.push(ids_array[i]);
}
}
}
if (post_ids.length==0)
{
jQuery('#draganddrop').html("<strong><p>Bạn phải chọn ít nhất một ảnh.</p></strong>");
jQuery('#draganddrop').show();
return;
}
else
jQuery('#draganddrop').hide();
var mapForm = document.createElement("form");
mapForm.target = "Map";
mapForm.method = "POST"; // or "post" if appropriate
mapForm.action = url;
var mapInput = document.createElement("input");
mapInput.type = "hidden";
mapInput.name = "image_ids";
mapInput.value = post_ids;
mapForm.appendChild(mapInput);
document.body.appendChild(mapForm);
map=window.open('','Map','height=1000,width=1000');
if (map) {
mapForm.submit();
if (window.focus) {map.focus();}
var timer = setInterval( function(){
if(!map.closed) return;
clearInterval(timer);
var album_id=jQuery("#current_id").val();
spider_set_input_value('task', 'edit');
spider_set_input_value('page_number', '1');
spider_set_input_value('search_value', '');
spider_set_input_value('search_or_not', '');
spider_set_input_value('asc_or_desc', 'asc');
spider_set_input_value('order_by', 'order');
spider_set_input_value('current_id', album_id);
spider_form_submit(event, 'galleries_form');
},1000);
} else {
alert('Popup cần được cho phép để thực hiện chức năng.');
}
///load lại trang hiện tại
}
function save_location(url,id)
{
var mapForm = document.createElement("form");
mapForm.target = "Map";
mapForm.method = "POST"; // or "post" if appropriate
mapForm.action = url;
var mapInput = document.createElement("input");
mapInput.type = "hidden";
mapInput.name = "image_ids";
mapInput.value = id;
mapForm.appendChild(mapInput);
document.body.appendChild(mapForm);
map=window.open('','Map','height=1000,width=1000');
if (map) {
mapForm.submit();
if (window.focus) {map.focus();}
var timer = setInterval(function() {
if(map.closed) {
clearInterval(timer);
var album_id=jQuery("#current_id").val();
spider_set_input_value('task', 'edit');
spider_set_input_value('page_number', '1');
spider_set_input_value('search_value', '');
spider_set_input_value('search_or_not', '');
spider_set_input_value('asc_or_desc', 'asc');
spider_set_input_value('order_by', 'order');
spider_set_input_value('current_id', album_id);
spider_form_submit(event, 'galleries_form');
}
}, 1000);
} else {
alert('Popup cần được cho phép để thực hiện chức năng.');
}
///load lại trang hiện tại
///var timer = setInterval(function() {
}
function spider_run_checkbox() {
jQuery("tbody").children().children(".check-column").find(":checkbox").click(function (l) {
if ("undefined" == l.shiftKey) {
return true
}
if (l.shiftKey) {
if (!i) {
return true
}
d = jQuery(i).closest("form").find(":checkbox");
f = d.index(i);
j = d.index(this);
h = jQuery(this).prop("checked");
if (0 < f && 0 < j && f != j) {
d.slice(f, j).prop("checked", function () {
if (jQuery(this).closest("tr").is(":visible")) {
return h
}
return false
})
}
}
i = this;
var k = jQuery(this).closest("tbody").find(":checkbox").filter(":visible").not(":checked");
jQuery(this).closest("table").children("thead, tfoot").find(":checkbox").prop("checked", function () {
return(0 == k.length)
});
return true
});
jQuery("thead, tfoot").find(".check-column :checkbox").click(function (m) {
var n = jQuery(this).prop("checked"), l = "undefined" == typeof toggleWithKeyboard ? false : toggleWithKeyboard, k = m.shiftKey || l;
jQuery(this).closest("table").children("tbody").filter(":visible").children().children(".check-column").find(":checkbox").prop("checked", function () {
if (jQuery(this).is(":hidden")) {
return false
}
if (k) {
return jQuery(this).prop("checked")
} else {
if (n) {
return true
}
}
return false
});
jQuery(this).closest("table").children("thead, tfoot").filter(":visible").children().children(".check-column").find(":checkbox").prop("checked", function () {
if (k) {
return false
} else {
if (n) {
return true
}
}
return false
})
});
}
// Set value by id.
function spider_set_input_value(input_id, input_value) {
if (document.getElementById(input_id)) {
document.getElementById(input_id).value = input_value;
}
}
// Submit form by id.
function spider_form_submit(event, form_id) {
if (document.getElementById(form_id)) {
document.getElementById(form_id).submit();
}
if (event.preventDefault) {
event.preventDefault();
}
else {
event.returnValue = false;
}
}
// Check if required field is empty.
function spider_check_required(id, name) {
if (jQuery('#' + id).val() == '') {
alert(name + '* field is required.');
jQuery('#' + id).attr('style', 'border-color: #FF0000;');
jQuery('#' + id).focus();
jQuery('html, body').animate({
scrollTop:jQuery('#' + id).offset().top - 200
}, 500);
return true;
}
else {
return false;
}
}
// Show/hide order column and drag and drop column.
function spider_show_hide_weights() {
if (jQuery("#show_hide_weights").val() == 'Hiện thứ tự cột') {
jQuery(".connectedSortable").css("cursor", "default");
jQuery("#tbody_arr").find(".handle").hide(0);
jQuery("#th_order").show(0);
jQuery("#tbody_arr").find(".spider_order").show(0);
jQuery("#show_hide_weights").val("Ẩn thứ tự cột");
if (jQuery("#tbody_arr").sortable()) {
jQuery("#tbody_arr").sortable("disable");
}
}
else {
jQuery(".connectedSortable").css("cursor", "move");
var page_number;
if (jQuery("#page_number") && jQuery("#page_number").val() != '' && jQuery("#page_number").val() != 1) {
page_number = (jQuery("#page_number").val() - 1) * 20 + 1;
}
else {
page_number = 1;
}
jQuery("#tbody_arr").sortable({
handle:".connectedSortable",
connectWith:".connectedSortable",
update:function (event, tr) {
jQuery("#draganddrop").attr("style", "");
jQuery("#draganddrop").html("<strong><p>Thay đổi nên được lưu lại.</p></strong>");
var i = page_number;
jQuery('.spider_order').each(function (e) {
if (jQuery(this).find('input').val()) {
jQuery(this).find('input').val(i++);
}
});
}
});//.disableSelection();
jQuery("#tbody_arr").sortable("enable");
jQuery("#tbody_arr").find(".handle").show(0);
jQuery("#tbody_arr").find(".handle").attr('class', 'handle connectedSortable');
jQuery("#th_order").hide(0);
jQuery("#tbody_arr").find(".spider_order").hide(0);
jQuery("#show_hide_weights").val("Hiện thứ tự cột");
}
}
// Check all items.
function spider_check_all_items() {
spider_check_all_items_checkbox();
// if (!jQuery('#check_all').attr('checked')) {
jQuery('#check_all').trigger('click');
// }
}
function spider_check_all_items_checkbox() {
if (jQuery('#check_all_items').attr('checked')) {
jQuery('#check_all_items').attr('checked', false);
jQuery('#draganddrop').hide();
}
else {
var saved_items = (parseInt(jQuery(".displaying-num").html()) ? parseInt(jQuery(".displaying-num").html()) : 0);
var added_items = (jQuery('input[id^="check_pr_"]').length ? parseInt(jQuery('input[id^="check_pr_"]').length) : 0);
var items_count = added_items + saved_items;
jQuery('#check_all_items').attr('checked', true);
if (items_count) {
jQuery('#draganddrop').html("<strong><p>Selected " + items_count + " item" + (items_count > 1 ? "s" : "") + ".</p></strong>");
jQuery('#draganddrop').show();
}
}
}
function spider_check_all(current) {
if (!jQuery(current).attr('checked')) {
jQuery('#check_all_items').attr('checked', false);
jQuery('#draganddrop').hide();
}
}
// Set uploader to button class.
function spider_uploader(button_id, input_id, delete_id, img_id) {
if (typeof img_id == 'undefined') {
img_id = '';
}
jQuery(function () {
var formfield = null;
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function (html) {
if (formfield) {
var fileurl = jQuery('img', html).attr('src');
if (!fileurl) {
var exploded_html;
var exploded_html_askofen;
exploded_html = html.split('"');
for (i = 0; i < exploded_html.length; i++) {
exploded_html_askofen = exploded_html[i].split("'");
}
for (i = 0; i < exploded_html.length; i++) {
for (j = 0; j < exploded_html_askofen.length; j++) {
if (exploded_html_askofen[j].search("href")) {
fileurl = exploded_html_askofen[i + 1];
break;
}
}
}
if (img_id != '') {
alert('Bạn phải chọn một ảnh.');
tb_remove();
return;
}
window.parent.document.getElementById(input_id).value = fileurl;
window.parent.document.getElementById(button_id).style.display = "none";
window.parent.document.getElementById(input_id).style.display = "inline-block";
window.parent.document.getElementById(delete_id).style.display = "inline-block";
}
else {
if (img_id == '') {
alert('You must select an audio file.');
tb_remove();
return;
}
window.parent.document.getElementById(input_id).value = fileurl;
window.parent.document.getElementById(button_id).style.display = "none";
window.parent.document.getElementById(delete_id).style.display = "inline-block";
if ((img_id != '') && window.parent.document.getElementById(img_id)) {
window.parent.document.getElementById(img_id).src = fileurl;
window.parent.document.getElementById(img_id).style.display = "inline-block";
}
}
formfield.val(fileurl);
tb_remove();
}
else {
window.original_send_to_editor(html);
}
formfield = null;
};
formfield = jQuery(this).parent().parent().find(".url_input");
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
jQuery('#TB_overlay,#TB_closeWindowButton').bind("click", function () {
formfield = null;
});
return false;
});
}
// Remove uploaded file.
function spider_remove_url(button_id, input_id, delete_id, img_id) {
if (typeof img_id == 'undefined') {
img_id = '';
}
if (document.getElementById(button_id)) {
document.getElementById(button_id).style.display = '';
}
if (document.getElementById(input_id)) {
document.getElementById(input_id).value = '';
document.getElementById(input_id).style.display = 'none';
}
if (document.getElementById(delete_id)) {
document.getElementById(delete_id).style.display = 'none';
}
if ((img_id != '') && window.parent.document.getElementById(img_id)) {
document.getElementById(img_id).src = '';
document.getElementById(img_id).style.display = 'none';
}
}
function spider_reorder_items(tbody_id) {
jQuery("#" + tbody_id).sortable({
handle:".connectedSortable",
connectWith:".connectedSortable",
update:function (event, tr) {
spider_sortt(tbody_id);
}
});
}
function spider_sortt(tbody_id) {
var str = "";
var counter = 0;
jQuery("#" + tbody_id).children().each(function () {
str += ((jQuery(this).attr("id")).substr(3) + ",");
counter++;
});
jQuery("#albums_galleries").val(str);
if (!counter) {
document.getElementById("table_albums_galleries").style.display = "none";
}
}
function spider_remove_row(tbody_id, event, obj) {
var span = obj;
var tr = jQuery(span).closest("tr");
jQuery(tr).remove();
spider_sortt(tbody_id);
}
function spider_jslider(idtaginp) {
jQuery(function () {
var inpvalue = jQuery("#" + idtaginp).val();
if (inpvalue == "") {
inpvalue = 50;
}
jQuery("#slider-" + idtaginp).slider({
range:"min",
value:inpvalue,
min:1,
max:100,
slide:function (event, ui) {
jQuery("#" + idtaginp).val("" + ui.value);
}
});
jQuery("#" + idtaginp).val("" + jQuery("#slider-" + idtaginp).slider("value"));
});
}
function spider_get_items(e) {
if (e.preventDefault) {
e.preventDefault();
}
else {
e.returnValue = false;
}
var trackIds = [];
var titles = [];
var types = [];
var tbody = document.getElementById('tbody_albums_galleries');
var trs = tbody.getElementsByTagName('tr');
for (j = 0; j < trs.length; j++) {
i = trs[j].getAttribute('id').substr(3);
if (document.getElementById('check_' + i).checked) {
trackIds.push(document.getElementById("id_" + i).innerHTML);
titles.push(document.getElementById("a_" + i).innerHTML);
types.push(document.getElementById("url_" + i).innerHTML == "Album" ? 1 : 0);
}
}
window.parent.bwg_add_items(trackIds, titles, types);
}
function bwg_check_checkboxes() {
var flag = false;
var ids_string = jQuery("#ids_string").val();
ids_array = ids_string.split(",");
for (var i in ids_array) {
if (ids_array.hasOwnProperty(i) && ids_array[i]) {
if (jQuery("#check_" + ids_array[i]).attr('checked') == 'checked') {
flag = true;
}
}
}
if(flag) {
if(jQuery(".buttons_div_right").find("a").hasClass( "thickbox" )) {
return true;
}
else {
jQuery(".buttons_div_right").find("a").addClass( "thickbox thickbox-preview" );
jQuery('#draganddrop').hide();
return true;
}
}
else {
jQuery(".buttons_div_right").find("a").removeClass( "thickbox thickbox-preview" );
jQuery('#draganddrop').html("<strong><p>Bạn phải chọn ít nhất một mục.</p></strong>");
jQuery('#draganddrop').show();
return false;
}
}
function bwg_get_tags(image_id, e) {
if (e.preventDefault) {
e.preventDefault();
}
else {
e.returnValue = false;
}
var tagIds = [];
var titles = [];
var tbody = document.getElementById('tbody_arr');
var trs = tbody.getElementsByTagName('tr');
for (j = 0; j < trs.length; j++) {
i = trs[j].getAttribute('id').substr(3);
if (document.getElementById('check_' + i).checked) {
tagIds.push(i);
titles.push(document.getElementById("a_" + i).innerHTML);
}
}
window.parent.bwg_add_tag(image_id, tagIds, titles);
}
function bwg_add_tag(image_id, tagIds, titles) {
if (image_id == '0') {
var flag = false;
var ids_string = jQuery("#ids_string").val();
ids_array = ids_string.split(",");
if (jQuery("#check_all_items").attr("checked")) {
var added_tags = '';
for (i = 0; i < tagIds.length; i++) {
added_tags = added_tags + tagIds[i] + ',';
}
jQuery("#added_tags_select_all").val(added_tags);
}
}
else {
image_id = image_id + ',';
ids_array = image_id.split(",");
var flag = true;
}
for (var i in ids_array) {
if (ids_array.hasOwnProperty(i) && ids_array[i]) {
if (jQuery("#check_" + ids_array[i]).attr('checked') == 'checked' || flag) {
image_id = ids_array[i];
var tag_ids = document.getElementById('tags_' + image_id).value;
tags_array = tag_ids.split(',');
var div = document.getElementById('tags_div_' + image_id);
var counter = 0;
for (i = 0; i < tagIds.length; i++) {
if (tags_array.indexOf(tagIds[i]) == -1) {
tag_ids = tag_ids + tagIds[i] + ',';
var tag_div = document.createElement('div');
tag_div.setAttribute('id', image_id + "_tag_" + tagIds[i]);
tag_div.setAttribute('class', "tag_div");
div.appendChild(tag_div);
var tag_name_span = document.createElement('span');
tag_name_span.setAttribute('class', "tag_name");
tag_name_span.innerHTML = titles[i];
tag_div.appendChild(tag_name_span);
var tag_delete_span = document.createElement('span');
tag_delete_span.setAttribute('class', "spider_delete_img_small");
tag_delete_span.setAttribute('onclick', "bwg_remove_tag('" + tagIds[i] + "', '" + image_id + "')");
tag_delete_span.setAttribute('style', "float:right;");
tag_div.appendChild(tag_delete_span);
counter++;
}
}
document.getElementById('tags_' + image_id).value = tag_ids;
if (counter) {
div.style.display = "block";
}
}
}
}
tb_remove();
}
function bwg_remove_tag(tag_id, image_id) {
if (jQuery('#' + image_id + '_tag_' + tag_id)) {
jQuery('#' + image_id + '_tag_' + tag_id).remove();
var tag_ids_string = jQuery("#tags_" + image_id).val();
tag_ids_string = tag_ids_string.replace(tag_id + ',', '');
jQuery("#tags_" + image_id).val(tag_ids_string);
if (jQuery("#tags_" + image_id).val() == '') {
jQuery("#tags_div_" + image_id).hide();
}
}
}
function preview_watermark() {
setTimeout(function() {
watermark_type = window.parent.document.getElementById('watermark_type_text').checked;
if (watermark_type) {
watermark_text = document.getElementById('watermark_text').value;
watermark_link = document.getElementById('watermark_link').value;
watermark_font_size = document.getElementById('watermark_font_size').value;
watermark_font = document.getElementById('watermark_font').value;
watermark_color = document.getElementById('watermark_color').value;
watermark_opacity = document.getElementById('watermark_opacity').value;
watermark_position = jQuery("input[name=watermark_position]:checked").val().split('-');
document.getElementById("preview_watermark").style.verticalAlign = watermark_position[0];
document.getElementById("preview_watermark").style.textAlign = watermark_position[1];
stringHTML = (watermark_link ? '<a href="' + watermark_link + '" target="_blank" style="text-decoration: none;' : '<span style="cursor:default;') + 'margin:4px;font-size:' + watermark_font_size + 'px;font-family:' + watermark_font + ';color:#' + watermark_color + ';opacity:' + (watermark_opacity / 100) + ';" class="non_selectable">' + watermark_text + (watermark_link ? '</a>' : '</span>');
document.getElementById("preview_watermark").innerHTML = stringHTML;
}
watermark_type = window.parent.document.getElementById('watermark_type_image').checked;
if (watermark_type) {
watermark_url = document.getElementById('watermark_url').value;
watermark_link = document.getElementById('watermark_link').value;
watermark_width = document.getElementById('watermark_width').value;
watermark_height = document.getElementById('watermark_height').value;
watermark_opacity = document.getElementById('watermark_opacity').value;
watermark_position = jQuery("input[name=watermark_position]:checked").val().split('-');
document.getElementById("preview_watermark").style.verticalAlign = watermark_position[0];
document.getElementById("preview_watermark").style.textAlign = watermark_position[1];
stringHTML = (watermark_link ? '<a href="' + watermark_link + '" target="_blank">' : '') + '<img class="non_selectable" src="' + watermark_url + '" style="margin:0 4px 0 4px;max-width:' + watermark_width + 'px;max-height:' + watermark_height + 'px;opacity:' + (watermark_opacity / 100) + ';" />' + (watermark_link ? '</a>' : '');
document.getElementById("preview_watermark").innerHTML = stringHTML;
}
}, 50);
}
function preview_built_in_watermark() {
setTimeout(function(){
watermark_type = window.parent.document.getElementById('built_in_watermark_type_text').checked;
if (watermark_type) {
watermark_text = document.getElementById('built_in_watermark_text').value;
watermark_font_size = document.getElementById('built_in_watermark_font_size').value * 400 / 500;
watermark_font = 'bwg_' + document.getElementById('built_in_watermark_font').value.replace('.TTF', '').replace('.ttf', '');
watermark_color = document.getElementById('built_in_watermark_color').value;
watermark_opacity = document.getElementById('built_in_watermark_opacity').value;
watermark_position = jQuery("input[name=built_in_watermark_position]:checked").val().split('-');
document.getElementById("preview_built_in_watermark").style.verticalAlign = watermark_position[0];
document.getElementById("preview_built_in_watermark").style.textAlign = watermark_position[1];
stringHTML = '<span style="cursor:default;margin:4px;font-size:' + watermark_font_size + 'px;font-family:' + watermark_font + ';color:#' + watermark_color + ';opacity:' + (watermark_opacity / 100) + ';" class="non_selectable">' + watermark_text + '</span>';
document.getElementById("preview_built_in_watermark").innerHTML = stringHTML;
}
watermark_type = window.parent.document.getElementById('built_in_watermark_type_image').checked;
if (watermark_type) {
watermark_url = document.getElementById('built_in_watermark_url').value;
watermark_size = document.getElementById('built_in_watermark_size').value;
watermark_position = jQuery("input[name=built_in_watermark_position]:checked").val().split('-');
document.getElementById("preview_built_in_watermark").style.verticalAlign = watermark_position[0];
document.getElementById("preview_built_in_watermark").style.textAlign = watermark_position[1];
stringHTML = '<img class="non_selectable" src="' + watermark_url + '" style="margin:0 4px 0 4px;max-width:95%;width:' + watermark_size + '%;" />';
document.getElementById("preview_built_in_watermark").innerHTML = stringHTML;
}
}, 50);
}
function bwg_watermark(watermark_type) {
jQuery("#" + watermark_type).attr('checked', 'checked');
jQuery("#tr_watermark_url").css('display', 'none');
jQuery("#tr_watermark_width_height").css('display', 'none');
jQuery("#tr_watermark_opacity").css('display', 'none');
jQuery("#tr_watermark_text").css('display', 'none');
jQuery("#tr_watermark_link").css('display', 'none');
jQuery("#tr_watermark_font_size").css('display', 'none');
jQuery("#tr_watermark_font").css('display', 'none');
jQuery("#tr_watermark_color").css('display', 'none');
jQuery("#tr_watermark_position").css('display', 'none');
jQuery("#tr_watermark_preview").css('display', 'none');
jQuery("#preview_watermark").css('display', 'none');
switch (watermark_type) {
case 'watermark_type_text':
{
jQuery("#tr_watermark_opacity").css('display', '');
jQuery("#tr_watermark_text").css('display', '');
jQuery("#tr_watermark_link").css('display', '');
jQuery("#tr_watermark_font_size").css('display', '');
jQuery("#tr_watermark_font").css('display', '');
jQuery("#tr_watermark_color").css('display', '');
jQuery("#tr_watermark_position").css('display', '');
jQuery("#tr_watermark_preview").css('display', '');
jQuery("#preview_watermark").css('display', 'table-cell');
break;
}
case 'watermark_type_image':
{
jQuery("#tr_watermark_url").css('display', '');
jQuery("#tr_watermark_link").css('display', '');
jQuery("#tr_watermark_width_height").css('display', '');
jQuery("#tr_watermark_opacity").css('display', '');
jQuery("#tr_watermark_position").css('display', '');
jQuery("#tr_watermark_preview").css('display', '');
jQuery("#preview_watermark").css('display', 'table-cell');
break;
}
}
}
function bwg_built_in_watermark(watermark_type) {
jQuery("#built_in_" + watermark_type).attr('checked', 'checked');
jQuery("#tr_built_in_watermark_url").css('display', 'none');
jQuery("#tr_built_in_watermark_size").css('display', 'none');
jQuery("#tr_built_in_watermark_opacity").css('display', 'none');
jQuery("#tr_built_in_watermark_text").css('display', 'none');
jQuery("#tr_built_in_watermark_font_size").css('display', 'none');
jQuery("#tr_built_in_watermark_font").css('display', 'none');
jQuery("#tr_built_in_watermark_color").css('display', 'none');
jQuery("#tr_built_in_watermark_position").css('display', 'none');
jQuery("#tr_built_in_watermark_preview").css('display', 'none');
jQuery("#preview_built_in_watermark").css('display', 'none');
switch (watermark_type) {
case 'watermark_type_text':
{
jQuery("#tr_built_in_watermark_opacity").css('display', '');
jQuery("#tr_built_in_watermark_text").css('display', '');
jQuery("#tr_built_in_watermark_font_size").css('display', '');
jQuery("#tr_built_in_watermark_font").css('display', '');
jQuery("#tr_built_in_watermark_color").css('display', '');
jQuery("#tr_built_in_watermark_position").css('display', '');
jQuery("#tr_built_in_watermark_preview").css('display', '');
jQuery("#preview_built_in_watermark").css('display', 'table-cell');
break;
}
case 'watermark_type_image':
{
jQuery("#tr_built_in_watermark_url").css('display', '');
jQuery("#tr_built_in_watermark_size").css('display', '');
jQuery("#tr_built_in_watermark_position").css('display', '');
jQuery("#tr_built_in_watermark_preview").css('display', '');
jQuery("#preview_built_in_watermark").css('display', 'table-cell');
break;
}
}
}
function bwg_change_option_type(type) {
type = (type == '' ? 1 : type);
document.getElementById('type').value = type;
for (var i = 1; i <= 8; i++) {
if (i == type) {
document.getElementById('div_content_' + i).style.display = 'block';
document.getElementById('div_' + i).style.background = '#C5C5C5';
}
else {
document.getElementById('div_content_' + i).style.display = 'none';
document.getElementById('div_' + i).style.background = '#F4F4F4';
}
}
document.getElementById('display_panel').style.display = 'inline-block';
}
function bwg_inputs() {
jQuery(".spider_int_input").keypress(function (event) {
var chCode1 = event.which || event.paramlist_keyCode;
if (chCode1 > 31 && (chCode1 < 48 || chCode1 > 57) && (chCode1 != 46) && (chCode1 != 45)) {
return false;
}
return true;
});
}
function bwg_enable_disable(display, id, current) {
jQuery("#" + current).attr('checked', 'checked');
jQuery("#" + id).css('display', display);
}
function bwg_popup_fullscreen(num) {
if (num) {
jQuery("#tr_popup_dimensions").css('display', 'none');
}
else {
jQuery("#tr_popup_dimensions").css('display', '');
}
}
function bwg_change_album_view_type(type) {
if (type == 'thumbnail') {
jQuery("#album_thumb_dimensions").html('Kích thước ảnh đại diện album: ');
jQuery("#album_thumb_dimensions_x").css('display', '');
jQuery("#album_thumb_height").css('display', '');
}
else {
jQuery("#album_thumb_dimensions").html('Chiều rộng ảnh đại diện album: ');
jQuery("#album_thumb_dimensions_x").css('display', 'none');
jQuery("#album_thumb_height").css('display', 'none');
}
}
function spider_check_isnum(e) {
var chCode1 = e.which || e.paramlist_keyCode;
if (chCode1 > 31 && (chCode1 < 48 || chCode1 > 57) && (chCode1 != 46) && (chCode1 != 45)) {
return false;
}
return true;
}
function bwg_change_theme_type(type) {
var button_name = jQuery("#button_name").val();
jQuery("#Thumbnail").hide();
jQuery("#Masonry").hide();
jQuery("#Slideshow").hide();
jQuery("#Compact_album").hide();
jQuery("#Extended_album").hide();
jQuery("#Image_browser").hide();
jQuery("#Blog_style").hide();
jQuery("#Lightbox").hide();
jQuery("#Navigation").hide();
jQuery("#" + type).show();
jQuery("#type_menu").show();
jQuery(".spider_fieldset").show();
jQuery("#current_type").val(type);
jQuery("#type_Thumbnail").attr("style", "background-color: #F4F4F4;");
jQuery("#type_Masonry").attr("style", "background-color: #F4F4F4; opacity: 0.4; filter: Alpha(opacity=40);");
jQuery("#type_Slideshow").attr("style", "background-color: #F4F4F4;");
jQuery("#type_Compact_album").attr("style", "background-color: #F4F4F4;");
jQuery("#type_Extended_album").attr("style", "background-color: #F4F4F4;");
jQuery("#type_Image_browser").attr("style", "background-color: #F4F4F4;");
jQuery("#type_Blog_style").attr("style", "background-color: #F4F4F4; opacity: 0.4; filter: Alpha(opacity=40);");
jQuery("#type_Lightbox").attr("style", "background-color: #F4F4F4;");
jQuery("#type_Navigation").attr("style", "background-color: #F4F4F4;");
jQuery("#type_" + type).attr("style", "background-color: #CFCBCB;");
}
function bwg_get_video_host(url) {
if ((/youtu\.be/i).test(url) || (/youtube\.com\/watch/i).test(url) || (/youtube\.com\/.*/i).test(url)) {
return 'YOUTUBE';
}
if ((/vimeo\.com/i).test(url)) {
return 'VIMEO';
}
alert('Enter only YouTube or Vimeo url.');
return '';
}
function bwg_get_youtube_video_id(url) {
// pattern = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
// var matches = url.match(pattern);
// if (matches && (matches[7]).length == 11) {
// return matches[7];
// }
// return '';
var video_id;
var url_parts = url.split('v=');
if (url_parts.length <= 1) {
url_parts = url.split('/v/');
if (url_parts.length <= 1) {
url_parts = url_parts[url_parts.length - 1].split('/');
if (url_parts.length <= 1) {
url_parts = url_parts[0].split('?');
}
}
url_parts = url_parts[url_parts.length - 1].split('&');
if (url_parts.length <= 1) {
url_parts = url_parts[url_parts.length - 1].split('?');
}
}
else {
url_parts = url_parts[url_parts.length - 1].split('&');
if (url_parts.length <= 1) {
url_parts = url_parts[url_parts.length - 1].split('#');
}
}
video_id = url_parts[0].split('?')[0];
return video_id ? video_id : false;
}
function bwg_get_vimeo_video_id(url) {
// pattern = /\/\/(www\.)?vimeo.com\/(\d+)($|\/)/;
// var matches = url.match(pattern);
// if (matches) {
// return matches[2];
// }
// return '';
var url_parts
var video_id;
url_parts = url.split('/');
url_parts = url_parts[url_parts.length - 1].split('?');
video_id = url_parts[0];
return video_id ? video_id : false;
}
function bwg_get_video_info(input_id) {
var url = jQuery("#" + input_id).val();
if (!url) {
alert('Please enter video url to add.');
return '';
}
var host = bwg_get_video_host(url);
var filesValid = [];
var fileData = [];
switch (host) {
case 'YOUTUBE':
var video_id = bwg_get_youtube_video_id(url);
if (video_id) {
jQuery.getJSON('http://gdata.youtube.com/feeds/api/videos/'+video_id+'?v=2&alt=jsonc',function(data,status,xhr){
fileData['name'] = data.data.title;
fileData['description'] = data.data.description;
fileData['filename'] = video_id;
fileData['url'] = url;
fileData['reliative_url'] = url;
fileData['thumb_url'] = data.data.thumbnail.hqDefault;
fileData['thumb'] = data.data.thumbnail.hqDefault;
fileData['size'] = bwg_convert_seconds(data.data.duration);
fileData['filetype'] = 'YOUTUBE';
fileData['date_modified'] = bwg_convert_date(data.data.uploaded, 'T');
fileData['resolution'] = '';
fileData['redirect_url'] = '';
filesValid.push(fileData);
bwg_add_image(filesValid);
document.getElementById(input_id).value = '';
});
return 'ok';
}
else {
alert('Please enter a valid YouTube link.');
return '';
}
case 'VIMEO':
var video_id = bwg_get_vimeo_video_id(url);
if (video_id) {
jQuery.getJSON('http://vimeo.com/api/v2/video/'+video_id+'.json',function(data,status,xhr){
fileData['name'] = data[0].title;
fileData['description'] = data[0].description;
fileData['filename'] = video_id;
fileData['url'] = url;
fileData['reliative_url'] = url;
fileData['thumb_url'] = data[0].thumbnail_large;
fileData['thumb'] = data[0].thumbnail_large;
fileData['size'] = bwg_convert_seconds(data[0].duration);
fileData['filetype'] = 'VIMEO';
fileData['date_modified'] = bwg_convert_date(data[0].upload_date, ' ');
fileData['resolution'] = '';
fileData['redirect_url'] = '';
filesValid.push(fileData);
bwg_add_image(filesValid);
document.getElementById(input_id).value = '';
});
return 'ok';
}
else {
alert('Please enter a valid Vimeo link.');
return '';
}
default:
return '';
}
}
function bwg_convert_seconds(seconds) {
var sec_num = parseInt(seconds, 10);
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (minutes < 10 && hours != 0) {minutes = "0" + minutes;}
if (seconds < 10) {seconds = "0" + seconds;}
var time = (hours != 0 ? hours + ':' : '') + minutes + ':' + seconds;
return time;
}
function bwg_convert_date(date, separator) {
var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
date = date.split(separator);
var dateArray = date[0].split("-");
return dateArray[2] + " " + m_names[dateArray[1] - 1] + " " + dateArray[0] + ", " + date[1].substring(0, 5);
}
jQuery(window).ready(function()
{
jQuery('#wpcontent').css('margin','0');
jQuery('.update-nag').css('display','none');
if(jQuery('.update-nag').next().is("div"))
jQuery('.update-nag').next().css('display','none');
jQuery('#wpfooter').css('display','none');
jQuery('body').css('visibility','visible');
var h=jQuery(document).height();//lấy chiều cao bằng chiều cao của nôi dung
window.parent.jQuery('iframe').css('min-height',h+50);
var w=jQuery("#images_table").width()+100;
window.parent.jQuery('iframe').css({'min-width':w, "overflow":'visible'});
if (w>1200)
window.parent.jQuery("#primary").css({"margin-left":"50px"});
});
| JavaScript |
function bwg_shortcode_load() {
jQuery(".spider_int_input").keypress(function (event) {
var chCode1 = event.which || event.paramlist_keyCode;
if (chCode1 > 31 && (chCode1 < 48 || chCode1 > 57) && (chCode1 != 46)) {
return false;
}
return true;
});
jQuery("#display_panel").tooltip({
track: true,
content: function () {
return jQuery(this).prop('title');
}
});
}
function bwg_watermark(watermark_type) {
jQuery("#" + watermark_type).prop('checked', true);
jQuery("#tr_watermark_link").css('display', 'none');
jQuery("#tr_watermark_url").css('display', 'none');
jQuery("#tr_watermark_width_height").css('display', 'none');
jQuery("#tr_watermark_opacity").css('display', 'none');
jQuery("#tr_watermark_text").css('display', 'none');
jQuery("#tr_watermark_font_size").css('display', 'none');
jQuery("#tr_watermark_font").css('display', 'none');
jQuery("#tr_watermark_color").css('display', 'none');
jQuery("#tr_watermark_position").css('display', 'none');
bwg_enable_disable('', '', 'watermark_bottom_right');
switch (watermark_type) {
case 'watermark_type_text': {
jQuery("#tr_watermark_link").css('display', '');
jQuery("#tr_watermark_opacity").css('display', '');
jQuery("#tr_watermark_text").css('display', '');
jQuery("#tr_watermark_font_size").css('display', '');
jQuery("#tr_watermark_font").css('display', '');
jQuery("#tr_watermark_color").css('display', '');
jQuery("#tr_watermark_position").css('display', '');
break;
}
case 'watermark_type_image': {
jQuery("#tr_watermark_link").css('display', '');
jQuery("#tr_watermark_url").css('display', '');
jQuery("#tr_watermark_width_height").css('display', '');
jQuery("#tr_watermark_opacity").css('display', '');
jQuery("#tr_watermark_position").css('display', '');
break;
}
}
}
function bwg_enable_disable(display, id, current) {
jQuery("#" + current).prop('checked', true);
jQuery("#" + id).css('display', display);
}
function bwg_popup_fullscreen() {
if (jQuery("#popup_fullscreen_1").is(':checked')) {
jQuery("#tr_popup_width_height").css('display', 'none');
}
else {
jQuery("#tr_popup_width_height").css('display', '');
}
}
function bwg_thumb_click_action() {
if (!jQuery("#thumb_click_action_2").is(':checked')) {
jQuery("#tr_thumb_link_target").css('display', 'none');
jQuery("#tbody_popup").css('display', '');
jQuery("#tr_popup_width_height").css('display', '');
jQuery("#tr_popup_effect").css('display', '');
jQuery("#tr_popup_interval").css('display', '');
jQuery("#tr_popup_enable_filmstrip").css('display', '');
if (jQuery("input[name=popup_enable_filmstrip]:checked").val() == 1) {
bwg_enable_disable('', 'tr_popup_filmstrip_height', 'popup_filmstrip_yes');
}
else {
bwg_enable_disable('none', 'tr_popup_filmstrip_height', 'popup_filmstrip_no');
}
jQuery("#tr_popup_enable_ctrl_btn").css('display', '');
if (jQuery("input[name=popup_enable_ctrl_btn]:checked").val() == 1) {
bwg_enable_disable('', 'tbody_popup_ctrl_btn', 'popup_ctrl_btn_yes');
}
else {
bwg_enable_disable('none', 'tbody_popup_ctrl_btn', 'popup_ctrl_btn_no');
}
jQuery("#tr_popup_enable_fullscreen").css('display', '');
jQuery("#tr_popup_enable_info").css('display', '');
jQuery("#tr_popup_enable_rate").css('display', '');
jQuery("#tr_popup_enable_comment").css('display', '');
jQuery("#tr_popup_enable_facebook").css('display', '');
jQuery("#tr_popup_enable_twitter").css('display', '');
jQuery("#tr_popup_enable_google").css('display', '');
jQuery("#tr_popup_enable_pinterest").css('display', '');
jQuery("#tr_popup_enable_tumblr").css('display', '');
bwg_popup_fullscreen();
}
else {
jQuery("#tr_thumb_link_target").css('display', '');
jQuery("#tbody_popup").css('display', 'none');
jQuery("#tbody_popup_ctrl_btn").css('display', 'none');
}
}
function bwg_show_search_box() {
if (jQuery("#show_search_box_1").is(':checked')) {
jQuery("#tr_search_box_width").css('display', '');
}
else {
jQuery("#tr_search_box_width").css('display', 'none');
}
}
function bwg_change_compuct_album_view_type() {
if (jQuery("input[name=compuct_album_view_type]:checked").val() == 'thumbnail') {
jQuery("#compuct_album_image_thumb_dimensions").html('Image thumbnail dimensions: ');
jQuery("#compuct_album_image_thumb_dimensions_x").css('display', '');
jQuery("#compuct_album_image_thumb_height").css('display', '');
jQuery("#tr_compuct_album_image_title").css('display', '');
}
else {
jQuery("#compuct_album_image_thumb_dimensions").html('Image thumbnail width: ');
jQuery("#compuct_album_image_thumb_dimensions_x").css('display', 'none');
jQuery("#compuct_album_image_thumb_height").css('display', 'none');
jQuery("#tr_compuct_album_image_title").css('display', 'none');
}
}
function bwg_change_extended_album_view_type() {
if (jQuery("input[name=extended_album_view_type]:checked").val() == 'thumbnail') {
jQuery("#extended_album_image_thumb_dimensions").html('Image thumbnail dimensions: ');
jQuery("#extended_album_image_thumb_dimensions_x").css('display', '');
jQuery("#extended_album_image_thumb_height").css('display', '');
jQuery("#tr_extended_album_image_title").css('display', '');
}
else {
jQuery("#extended_album_image_thumb_dimensions").html('Image thumbnail width: ');
jQuery("#extended_album_image_thumb_dimensions_x").css('display', 'none');
jQuery("#extended_album_image_thumb_height").css('display', 'none');
jQuery("#tr_extended_album_image_title").css('display', 'none');
}
}
function bwg_change_label(id, text) {
jQuery('#' + id).html(text);
}
function bwg_gallery_type(gallery_type) {
jQuery("#" + gallery_type).prop('checked', true);
jQuery("#tr_gallery").css('display', 'none');
jQuery("#tr_sort_by").css('display', 'none');
jQuery("#tr_order_by").css('display', 'none');
jQuery("#tr_show_search_box").css('display', 'none');
jQuery("#tr_search_box_width").css('display', 'none');
jQuery("#tr_album").css('display', 'none');
// Thumbnails, Masonry.
jQuery("#tr_masonry_hor_ver").css('display', 'none');
bwg_change_label("col_num_label", 'Max. number of image columns');
jQuery("#tr_image_column_number").css('display', 'none');
jQuery("#tr_images_per_page").css('display', 'none');
jQuery("#tr_image_title_hover").css('display', 'none');
jQuery("#tr_image_enable_page").css('display', 'none');
jQuery("#tr_thumb_width_height").css('display', 'none');
// Compact Album.
jQuery("#tr_compuct_album_column_number").css('display', 'none');
jQuery("#tr_compuct_albums_per_page").css('display', 'none');
jQuery("#tr_compuct_album_title_hover").css('display', 'none');
jQuery("#tr_compuct_album_view_type").css('display', 'none');
jQuery("#tr_compuct_album_thumb_width_height").css('display', 'none');
jQuery("#tr_compuct_album_image_column_number").css('display', 'none');
jQuery("#tr_compuct_album_images_per_page").css('display', 'none');
jQuery("#tr_compuct_album_image_title").css('display', 'none');
jQuery("#tr_compuct_album_image_title").css('display', 'none');
jQuery("#tr_compuct_album_image_thumb_width_height").css('display', 'none');
jQuery("#tr_compuct_album_enable_page").css('display', 'none');
// Extended Album.
jQuery("#tr_extended_albums_per_page").css('display', 'none');
jQuery("#tr_extended_album_height").css('display', 'none');
jQuery("#tr_extended_album_description_enable").css('display', 'none');
jQuery("#tr_extended_album_view_type").css('display', 'none');
jQuery("#tr_extended_album_thumb_width_height").css('display', 'none');
jQuery("#tr_extended_album_image_column_number").css('display', 'none');
jQuery("#tr_extended_album_images_per_page").css('display', 'none');
jQuery("#tr_extended_album_image_title").css('display', 'none');
jQuery("#tr_extended_album_image_thumb_width_height").css('display', 'none');
jQuery("#tr_extended_album_enable_page").css('display', 'none');
// Image Browser.
jQuery("#tr_image_browser_width_height").css('display', 'none');
jQuery("#tr_image_browser_title_enable").css('display', 'none');
jQuery("#tr_image_browser_description_enable").css('display', 'none');
// Blog Style.
jQuery("#tr_blog_style_width_height").css('display', 'none');
jQuery("#tr_blog_style_title_enable").css('display', 'none');
jQuery("#tr_blog_style_images_per_page").css('display', 'none');
jQuery("#tr_blog_style_enable_page").css('display', 'none');
// Slideshow.
jQuery("#tbody_slideshow").css('display', 'none');
jQuery("#tr_slideshow_effect").css('display', 'none');
jQuery("#tr_slideshow_interval").css('display', 'none');
jQuery("#tr_slideshow_width_height").css('display', 'none');
jQuery("#tr_enable_slideshow_autoplay").css('display', 'none');
jQuery("#tr_enable_slideshow_shuffle").css('display', 'none');
jQuery("#tr_enable_slideshow_ctrl").css('display', 'none');
jQuery("#tr_enable_slideshow_filmstrip").css('display', 'none');
jQuery("#tr_slideshow_filmstrip_height").css('display', 'none');
jQuery("#tr_slideshow_enable_title").css('display', 'none');
jQuery("#tr_slideshow_title_position").css('display', 'none');
jQuery("#tr_slideshow_enable_description").css('display', 'none');
jQuery("#tr_slideshow_description_position").css('display', 'none');
jQuery("#tr_enable_slideshow_music").css('display', 'none');
jQuery("#tr_slideshow_music_url").css('display', 'none');
// Popup.
jQuery("#tbody_popup_other").css('display', 'none');
jQuery("#tbody_popup").css('display', 'none');
jQuery("#tr_popup_width_height").css('display', 'none');
jQuery("#tr_popup_effect").css('display', 'none');
jQuery("#tr_popup_interval").css('display', 'none');
jQuery("#tr_popup_enable_filmstrip").css('display', 'none');
jQuery("#tr_popup_filmstrip_height").css('display', 'none');
jQuery("#tr_popup_enable_ctrl_btn").css('display', 'none');
jQuery("#tr_popup_enable_fullscreen").css('display', 'none');
jQuery("#tr_popup_enable_info").css('display', 'none');
jQuery("#tr_popup_enable_rate").css('display', 'none');
jQuery("#tr_popup_enable_comment").css('display', 'none');
jQuery("#tr_popup_enable_facebook").css('display', 'none');
jQuery("#tr_popup_enable_twitter").css('display', 'none');
jQuery("#tr_popup_enable_google").css('display', 'none');
jQuery("#tr_popup_enable_pinterest").css('display', 'none');
jQuery("#tr_popup_enable_tumblr").css('display', 'none');
// Watermark.
jQuery("#tr_watermark_type").css('display', '');
if (jQuery("input[name=watermark_type]:checked").val() == 'image') {
bwg_watermark('watermark_type_image');
}
else if (jQuery("input[name=watermark_type]:checked").val() == 'text'){
bwg_watermark('watermark_type_text');
}
else {
bwg_watermark('watermark_type_none');
}
switch (gallery_type) {
case 'thumbnails': {
jQuery("#tr_gallery").css('display', '');
jQuery("#tr_sort_by").css('display', '');
jQuery("#tr_order_by").css('display', '');
jQuery("#tr_show_search_box").css('display', '');
bwg_change_label('image_column_number_label', 'Max. number of image columns: ');
bwg_change_label('thumb_width_height_label', 'Image thumbnail dimensions: ');
jQuery('#thumb_width').show();
jQuery('#thumb_height').show();
jQuery('#thumb_width_height_separator').show();
jQuery("#tr_image_column_number").css('display', '');
jQuery("#tr_images_per_page").css('display', '');
jQuery("#tr_image_title_hover").css('display', '');
jQuery("#tr_image_enable_page").css('display', '');
jQuery("#tr_thumb_width_height").css('display', '');
bwg_show_search_box();
jQuery("#bwg_pro_version").html('Thumbnails');
jQuery("#bwg_pro_version_link").attr("href", "http://wpdemo.web-dorado.com/thumbnails-view-2/");
break;
}
case 'thumbnails_masonry': {
jQuery("#tr_gallery").css('display', '');
jQuery("#tr_sort_by").css('display', '');
jQuery("#tr_order_by").css('display', '');
jQuery("#tr_show_search_box").css('display', '');
if (jQuery("input[name=masonry_hor_ver]:checked").val() == 'horizontal') {
bwg_change_label('image_column_number_label', 'Number of image rows: ');
bwg_change_label('thumb_width_height_label', 'Image thumbnail height: ');
jQuery('#thumb_width').hide();
jQuery('#thumb_height').show();
}
else {
bwg_change_label('image_column_number_label', 'Max. number of image columns: ');
bwg_change_label('thumb_width_height_label', 'Image thumbnail width: ');
jQuery('#thumb_width').show();
jQuery('#thumb_height').hide();
}
jQuery("#tr_masonry_hor_ver").css('display', '');
jQuery('#thumb_width_height_separator').hide();
jQuery("#tr_image_column_number").css('display', '');
jQuery("#tr_images_per_page").css('display', '');
jQuery("#tr_image_enable_page").css('display', '');
jQuery("#tr_thumb_width_height").css('display', '');
bwg_show_search_box();
break;
}
case 'slideshow': {
jQuery("#tr_gallery").css('display', '');
jQuery("#tr_sort_by").css('display', '');
jQuery("#tr_order_by").css('display', '');
jQuery("#tr_slideshow_effect").css('display', '');
jQuery("#tr_slideshow_interval").css('display', '');
jQuery("#tr_slideshow_width_height").css('display', '');
jQuery("#tbody_slideshow").css('display', '');
jQuery("#tr_enable_slideshow_autoplay").css('display', '');
jQuery("#tr_enable_slideshow_shuffle").css('display', '');
jQuery("#tr_enable_slideshow_ctrl").css('display', '');
jQuery("#tr_enable_slideshow_filmstrip").css('display', '');
if (jQuery("input[name=enable_slideshow_filmstrip]:checked").val() == 1) {
bwg_enable_disable('', 'tr_slideshow_filmstrip_height', 'slideshow_filmstrip_yes');
}
else {
bwg_enable_disable('none', 'tr_slideshow_filmstrip_height', 'slideshow_filmstrip_no');
}
jQuery("#tr_slideshow_enable_title").css('display', '');
if (jQuery("input[name=slideshow_enable_title]:checked").val() == 1) {
bwg_enable_disable('', 'tr_slideshow_title_position', 'slideshow_title_yes');
}
else {
bwg_enable_disable('none', 'tr_slideshow_title_position', 'slideshow_title_no');
}
jQuery("#tr_slideshow_enable_description").css('display', '');
if (jQuery("input[name=slideshow_enable_description]:checked").val() == 1) {
bwg_enable_disable('', 'tr_slideshow_description_position', 'slideshow_description_yes');
}
else {
bwg_enable_disable('none', 'tr_slideshow_description_position', 'slideshow_description_no');
}
jQuery("#tr_enable_slideshow_music").css('display', '');
if (jQuery("input[name=enable_slideshow_music]:checked").val() == 1) {
bwg_enable_disable('', 'tr_slideshow_music_url', 'slideshow_music_yes');
}
else {
bwg_enable_disable('none', 'tr_slideshow_music_url', 'slideshow_music_no');
}
jQuery("#bwg_pro_version").html('Slideshow');
jQuery("#bwg_pro_version_link").attr("href", "http://wpdemo.web-dorado.com/slideshow-view/");
break;
}
case 'image_browser': {
jQuery("#tr_gallery").css('display', '');
jQuery("#tr_sort_by").css('display', '');
jQuery("#tr_order_by").css('display', '');
jQuery("#tr_show_search_box").css('display', '');
jQuery("#tr_image_browser_width_height").css('display', '');
jQuery("#tr_image_browser_title_enable").css('display', '');
jQuery("#tr_image_browser_description_enable").css('display', '');
bwg_show_search_box();
jQuery("#bwg_pro_version").html('Image Browser');
jQuery("#bwg_pro_version_link").attr("href", "http://wpdemo.web-dorado.com/image-browser-view/");
break;
}
case 'album_compact_preview': {
jQuery("#tr_album").css('display', '');
jQuery("#tr_sort_by").css('display', '');
jQuery("#tr_order_by").css('display', '');
jQuery("#tr_show_search_box").css('display', '');
jQuery("#tr_compuct_album_column_number").css('display', '');
jQuery("#tr_compuct_albums_per_page").css('display', '');
jQuery("#tr_compuct_album_title_hover").css('display', '');
jQuery("#tr_compuct_album_view_type").css('display', '');
jQuery("#tr_compuct_album_thumb_width_height").css('display', '');
jQuery("#tr_compuct_album_image_column_number").css('display', '');
jQuery("#tr_compuct_album_images_per_page").css('display', '');
jQuery("#tr_compuct_album_image_title").css('display', '');
jQuery("#tr_compuct_album_image_title").css('display', '');
jQuery("#tr_compuct_album_image_thumb_width_height").css('display', '');
jQuery("#tr_compuct_album_enable_page").css('display', '');
bwg_change_compuct_album_view_type();
bwg_show_search_box();
jQuery("#bwg_pro_version").html('Compact Album');
jQuery("#bwg_pro_version_link").attr("href", "http://wpdemo.web-dorado.com/compact-album-view/");
break;
}
case 'album_extended_preview': {
jQuery("#tr_album").css('display', '');
jQuery("#tr_sort_by").css('display', '');
jQuery("#tr_order_by").css('display', '');
jQuery("#tr_show_search_box").css('display', '');
jQuery("#tr_extended_albums_per_page").css('display', '');
jQuery("#tr_extended_album_height").css('display', '');
jQuery("#tr_extended_album_description_enable").css('display', '');
jQuery("#tr_extended_album_view_type").css('display', '');
jQuery("#tr_extended_album_thumb_width_height").css('display', '');
jQuery("#tr_extended_album_image_column_number").css('display', '');
jQuery("#tr_extended_album_images_per_page").css('display', '');
jQuery("#tr_extended_album_image_title").css('display', '');
jQuery("#tr_extended_album_image_thumb_width_height").css('display', '');
jQuery("#tr_extended_album_enable_page").css('display', '');
bwg_change_extended_album_view_type();
bwg_show_search_box();
jQuery("#bwg_pro_version").html('Extended Album');
jQuery("#bwg_pro_version_link").attr("href", "http://wpdemo.web-dorado.com/extended-album-view/");
break;
}
case 'blog_style': {
jQuery("#tr_gallery").css('display', '');
jQuery("#tr_sort_by").css('display', '');
jQuery("#tr_order_by").css('display', '');
jQuery("#tr_show_search_box").css('display', '');
jQuery("#tr_blog_style_width_height").css('display', '');
jQuery("#tr_blog_style_title_enable").css('display', '');
jQuery("#tr_blog_style_images_per_page").css('display', '');
jQuery("#tr_blog_style_enable_page").css('display', '');
bwg_show_search_box();
break;
}
}
if (gallery_type != 'slideshow') {
jQuery("#tbody_popup_other").css('display', '');
jQuery("#tbody_popup").css('display', '');
jQuery("#tr_popup_width_height").css('display', '');
jQuery("#tr_popup_effect").css('display', '');
jQuery("#tr_popup_interval").css('display', '');
jQuery("#tr_popup_enable_filmstrip").css('display', '');
if (jQuery("input[name=popup_enable_filmstrip]:checked").val() == 1) {
bwg_enable_disable('', 'tr_popup_filmstrip_height', 'popup_filmstrip_yes');
}
else {
bwg_enable_disable('none', 'tr_popup_filmstrip_height', 'popup_filmstrip_no');
}
jQuery("#tr_popup_enable_ctrl_btn").css('display', '');
if (jQuery("input[name=popup_enable_ctrl_btn]:checked").val() == 1) {
bwg_enable_disable('', 'tbody_popup_ctrl_btn', 'popup_ctrl_btn_yes');
}
else {
bwg_enable_disable('none', 'tbody_popup_ctrl_btn', 'popup_ctrl_btn_no');
}
jQuery("#tr_popup_enable_fullscreen").css('display', '');
jQuery("#tr_popup_enable_info").css('display', '');
jQuery("#tr_popup_enable_rate").css('display', '');
jQuery("#tr_popup_enable_comment").css('display', '');
jQuery("#tr_popup_enable_facebook").css('display', '');
jQuery("#tr_popup_enable_twitter").css('display', '');
jQuery("#tr_popup_enable_google").css('display', '');
jQuery("#tr_popup_enable_pinterest").css('display', '');
jQuery("#tr_popup_enable_tumblr").css('display', '');
bwg_popup_fullscreen();
bwg_thumb_click_action();
}
}
function bwg_onKeyDown(e) {
var e = e || window.event;
var chCode1 = e.which || e.paramlist_keyCode;
if (chCode1 != 37 && chCode1 != 38 && chCode1 != 39 && chCode1 != 40) {
if ((!e.ctrlKey && !e.metaKey) || (chCode1 != 86 && chCode1 != 67 && chCode1 != 65 && chCode1 != 88)) {
e.preventDefault();
}
}
}
| JavaScript |
/**
* Author: Rob
* Date: 4/18/13
* Time: 3:56 PM
*/
////////////////////////////////////////////////////////////////////////////////////////
// Events //
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
// Constants //
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
// Variables //
////////////////////////////////////////////////////////////////////////////////////////
var keyFileSelected;
var keyFileSelectedML;
var filesSelected;
var filesSelectedML;
var dragFiles;
var isUploading;
////////////////////////////////////////////////////////////////////////////////////////
// Constructor //
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
// Public Methods //
////////////////////////////////////////////////////////////////////////////////////////
jQuery(document).ready(function () {
filesSelected = [];
filesSelectedML = [];
dragFiles = [];
//file manager under system messages
jQuery("#wrapper").css("top", jQuery("#file_manager_message").css("height"));
jQuery(window).resize(function () {
jQuery("#container").css("top", jQuery("#file_manager_message").css("height"));
});
isUploading = false;
jQuery("#uploader").css("display", "none");
jQuery("#uploader_progress_bar").css("display", "none");
jQuery("#importer").css("display", "none");
//decrease explorer header width by scroller width
jQuery(".scrollbar_filler").css("width", getScrollBarWidth() + "px");
jQuery(document).keydown(function(e) {
onKeyDown(e);
});
});
////////////////////////////////////////////////////////////////////////////////////////
// Getters & Setters //
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
// Private Methods //
////////////////////////////////////////////////////////////////////////////////////////
function getClipboardFiles() {
return jQuery("form[name=adminForm]").find("input[name=clipboard_file]").val();
}
function submit(task, sortBy, sortOrder, itemsView, destDir, fileNewName, newDirName, clipboardTask, clipboardFiles, clipboardSrc, clipboardDest) {
fileNames = filesSelected.join("**#**");
fileNamesML = filesSelectedML.join("**@**");
switch (task) {
case "rename_item":
destDir = dir;
newDirName = "";
clipboardTask = ""
clipboardDest = "";
break;
case "remove_items":
destDir = dir;
fileNewName = "";
newDirName = "";
clipboardTask = ""
clipboardDest = "";
break;
case "make_dir":
destDir = dir;
fileNewName = "";
clipboardTask = ""
clipboardDest = "";
break;
case "paste_items":
destDir = dir;
fileNewName = "";
newDirName = "";
break;
case "import_items":
destDir = dir;
fileNewName = "";
newDirName = "";
break;
default:
task = "";
break;
}
jQuery("form[name=adminForm]").find("input[name=task]").val(task);
if (sortBy != null) {
jQuery("form[name=adminForm]").find("input[name=sort_by]").val(sortBy);
}
if (sortOrder != null) {
jQuery("form[name=adminForm]").find("input[name=sort_order]").val(sortOrder);
}
if (itemsView != null) {
jQuery("form[name=adminForm]").find("input[name=items_view]").val(itemsView);
}
if (destDir != null) {
jQuery("form[name=adminForm]").find("input[name=dir]").val(destDir);
}
if (fileNames != null) {
jQuery("form[name=adminForm]").find("input[name=file_names]").val(fileNames);
}
if (fileNamesML != null) {
jQuery("form[name=adminForm]").find("input[name=file_namesML]").val(fileNamesML);
}
if (fileNewName != null) {
jQuery("form[name=adminForm]").find("input[name=file_new_name]").val(fileNewName);
}
if (newDirName != null) {
jQuery("form[name=adminForm]").find("input[name=new_dir_name]").val(newDirName);
}
if (clipboardTask != null) {
jQuery("form[name=adminForm]").find("input[name=clipboard_task]").val(clipboardTask);
}
if (clipboardFiles != null) {
jQuery("form[name=adminForm]").find("input[name=clipboard_files]").val(clipboardFiles);
}
if (clipboardSrc != null) {
jQuery("form[name=adminForm]").find("input[name=clipboard_src]").val(clipboardSrc);
}
if (clipboardDest != null) {
jQuery("form[name=adminForm]").find("input[name=clipboard_dest]").val(clipboardDest);
}
jQuery("form[name=adminForm]").submit();
}
function updateFileNames() {
var result = "";
if (filesSelected.length > 0) {
var fileNames = [];
for (var i = 0; i < filesSelected.length; i++) {
fileNames[i] = "'" + filesSelected[i] + "'";
}
result = fileNames.join(" ");
}
jQuery("#file_names_span span").html(result);
}
// submit file
function submitFiles() {
if (filesSelected.length == 0) {
return;
}
var filesValid = [];
for (var i = 0; i < filesSelected.length; i++) {
var file_object = jQuery(".explorer_item[name='" + filesSelected[i] + "']");
if (jQuery(file_object).attr("isDir") == "false") {
var fileData = [];
fileData['name'] = filesSelected[i];
fileData['filename'] = jQuery(file_object).attr("filename");
fileData['url'] = dir + "/" + filesSelected[i];
fileData['reliative_url'] = dirUrl + "/" + filesSelected[i];
fileData['thumb_url'] = dir + "/thumb/" + filesSelected[i];
fileData['thumb'] = jQuery(file_object).attr("filethumb");
fileData['size'] = jQuery(file_object).attr("filesize");
fileData['filetype'] = jQuery(file_object).attr("filetype");
fileData['date_modified'] = jQuery(file_object).attr("date_modified");
fileData['resolution'] = jQuery(file_object).attr("fileresolution");
filesValid.push(fileData);
}
}
window.parent[callback](filesValid);
window.parent.tb_remove();
}
function importFiles() {
if (filesSelectedML.length == 0) {
alert("Select at least one file to import.");
return;
}
else {
submit("import_items", null, null, null, null, null, null, null, null, null, dir);
}
}
function getScrollBarWidth() {
var inner = document.createElement("p");
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.createElement("div");
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild(inner);
document.body.appendChild(outer);
var w1 = inner.offsetWidth;
outer.style.overflow = "scroll";
var w2 = inner.offsetWidth;
if (w1 == w2) {
w2 = outer.clientWidth;
}
document.body.removeChild(outer);
return (w1 - w2);
}
function getFileName(file) {
var dotIndex = file.lastIndexOf('.');
return file.substring(0, dotIndex < 0 ? file.length : dotIndex);
}
function getFileExtension(file) {
return file.substring(file.lastIndexOf('.') + 1);
}
////////////////////////////////////////////////////////////////////////////////////////
// Listeners //
////////////////////////////////////////////////////////////////////////////////////////
//ctrls bar handlers
function onBtnUpClick(event, obj) {
var destDir = dir.substring(0, dir.lastIndexOf(DS));
submit("", null, null, null, destDir, null, null, null, null, null, null);
}
function onBtnMakeDirClick(event, obj) {
var newDirName = prompt(messageEnterDirName);
if ((newDirName) && (newDirName != "")) {
submit("make_dir", null, null, null, null, null, newDirName, null, null, null, null);
}
}
function onBtnRenameItemClick(event, obj) {
if (filesSelected.length != 0) {
var newName = prompt(messageEnterNewName, getFileName(filesSelected[0]));
if ((newName != null) && (newName != "")) {
submit("rename_item", null, null, null, null, newName, null, null, null, null, null);
}
}
}
function onBtnCopyClick(event, obj) {
if (filesSelected.length != 0) {
submit("", null, null, null, null, null, null, "copy", filesSelected.join("**#**"), dir, null);
}
}
function onBtnCutClick(event, obj) {
if (filesSelected.length != 0) {
submit("", null, null, null, null, null, null, "cut", filesSelected.join("**#**"), dir, null);
}
}
function onBtnPasteClick(event, obj) {
if (getClipboardFiles() != "") {
submit("paste_items", null, null, null, null, null, null, null, null, null, dir);
}
}
function onBtnRemoveItemsClick(event, obj) {
if ((filesSelected.length != 0) && (confirm(warningRemoveItems) == true)) {
submit("remove_items", null, null, null, null, null, null, null, null, null, null);
}
}
function onBtnShowUploaderClick(event, obj) {
jQuery("#uploader").fadeIn();
}
function onBtnViewThumbsClick(event, obj) {
submit("", null, null, "thumbs", null, null, null, null, null, null, null);
}
function onBtnViewListClick(event, obj) {
submit("", null, null, "list", null, null, null, null, null, null, null);
}
function onBtnBackClick(event, obj) {
if ((isUploading == false) || (confirm(warningCancelUploads) == true)) {
// jQuery("#uploader").fadeOut(function () {
submit("", null, null, null, null, null, null, null, null, null, null);
// });
}
}
function onPathComponentClick(event, obj, path) {
submit("", null, null, null, path, null, null, null, null, null, null);
}
function onBtnShowImportClick(event, obj) {
jQuery("#importer").fadeIn();
}
function onNameHeaderClick(event, obj) {
var newSortOrder = ((sortBy == "name") && (sortOrder == "asc")) ? "desc" : "asc";
submit("", "name", newSortOrder, null, null, null, null, null, null, null, null);
}
function onSizeHeaderClick(event, obj) {
var newSortOrder = ((sortBy == "size") && (sortOrder == "asc")) ? "desc" : "asc";
submit("", "size", newSortOrder, null, null, null, null, null, null, null, null);
}
function onDateModifiedHeaderClick(event, obj) {
var newSortOrder = ((sortBy == "date_modified") && (sortOrder == "asc")) ? "desc" : "asc";
submit("", "date_modified", newSortOrder, null, null, null, null, null, null, null, null);
}
//file handlers
function onKeyDown(e) {
var e = e || window.event;
var chCode1 = e.which || e.paramlist_keyCode;
if ((e.ctrlKey || e.metaKey) && chCode1 == 65) {
jQuery(".explorer_item").addClass("explorer_item_select");
jQuery(".importer_item").addClass("importer_item_select");
filesSelected = [];
filesSelectedML = [];
jQuery(".explorer_item").each(function() {
var objName = jQuery(this).attr("name");
if (filesSelected.indexOf(objName) == -1) {
filesSelected.push(objName);
keyFileSelected = this;
}
});
jQuery(".importer_item").each(function() {
var objName = jQuery(this).attr("path");
if (filesSelectedML.indexOf(objName) == -1) {
filesSelectedML.push(objName);
keyFileSelectedML = this;
}
});
e.preventDefault();
}
}
function onFileMOver(event, obj) {
jQuery(obj).addClass("explorer_item_hover");
}
function onFileMOverML(event, obj) {
jQuery(obj).addClass("importer_item_hover");
}
function onFileMOut(event, obj) {
jQuery(obj).removeClass("explorer_item_hover");
}
function onFileMOutML(event, obj) {
jQuery(obj).removeClass("importer_item_hover");
}
function onFileClick(event, obj) {
jQuery(".explorer_item").removeClass("explorer_item_select");
var objName = jQuery(obj).attr("name");
if (event.ctrlKey == true || event.metaKey == true) {
if (filesSelected.indexOf(objName) == -1) {
filesSelected.push(objName);
keyFileSelected = obj;
}
else {
filesSelected.splice(filesSelected.indexOf(objName), 1);
jQuery(obj).removeClass("explorer_item_select");
}
}
else if (event.shiftKey == true) {
filesSelected = [];
var explorerItems = jQuery(".explorer_item");
var curFileIndex = explorerItems.index(jQuery(obj));
var keyFileIndex = explorerItems.index(keyFileSelected);
var startIndex = Math.min(keyFileIndex, curFileIndex);
var endIndex = startIndex + Math.abs(curFileIndex - keyFileIndex);
for (var i = startIndex; i < endIndex + 1; i++) {
filesSelected.push(jQuery(explorerItems[i]).attr("name"));
}
}
else {
filesSelected = [jQuery(obj).attr("name")];
keyFileSelected = obj;
}
for (var i = 0; i < filesSelected.length; i++) {
jQuery(".explorer_item[name='" + filesSelected[i] + "']").addClass("explorer_item_select");
}
updateFileNames();
}
function onFileClickML(event, obj) {
jQuery(".importer_item").removeClass("importer_item_select");
var objName = jQuery(obj).attr("path");
if (event.ctrlKey == true || event.metaKey == true) {
if (filesSelectedML.indexOf(objName) == -1) {
filesSelectedML.push(objName);
keyFileSelectedML = obj;
}
else {
filesSelectedML.splice(filesSelectedML.indexOf(objName), 1);
jQuery(obj).removeClass("importer_item_select");
}
}
else if (event.shiftKey == true) {
filesSelectedML = [];
var explorerItems = jQuery(".importer_item");
var curFileIndex = explorerItems.index(jQuery(obj));
var keyFileIndex = explorerItems.index(keyFileSelectedML);
var startIndex = Math.min(keyFileIndex, curFileIndex);
var endIndex = startIndex + Math.abs(curFileIndex - keyFileIndex);
for (var i = startIndex; i < endIndex + 1; i++) {
filesSelectedML.push(jQuery(explorerItems[i]).attr("path"));
}
}
else {
filesSelectedML = [jQuery(obj).attr("path")];
keyFileSelectedML = obj;
}
for (var i = 0; i < filesSelectedML.length; i++) {
jQuery(".importer_item[path='" + filesSelectedML[i] + "']").addClass("importer_item_select");
}
updateFileNames();
}
function onFileDblClick(event, obj) {
if (jQuery(obj).attr("isDir") == "true") {
submit("", null, null, null, dir + DS + jQuery(obj).attr("name"), null, null, null, null, null, null);
}
else {
filesSelected = [];
filesSelected.push(jQuery(obj).attr("name"));
submitFiles();
}
}
function onFileDblClickML(event, obj) {
filesSelectedML = [];
filesSelectedML.push(jQuery(obj).attr("path"));
importFiles();
}
function onFileDragStart(event, obj) {
var objName = jQuery(obj).attr("name");
if (filesSelected.indexOf(objName) < 0) {
jQuery(".explorer_item").removeClass("explorer_item_select");
if (event.ctrlKey == true || event.metaKey == true) {
if (filesSelected.indexOf(objName) == -1) {
filesSelected.push(objName);
keyFileSelected = obj;
}
}
else if (event.shiftKey == true) {
filesSelected = [];
var explorerItems = jQuery(".explorer_item");
var curFileIndex = explorerItems.index(jQuery(obj));
var keyFileIndex = explorerItems.index(keyFileSelected);
var startIndex = Math.min(keyFileIndex, curFileIndex);
var endIndex = startIndex + Math.abs(curFileIndex - keyFileIndex);
for (var i = startIndex; i < endIndex + 1; i++) {
filesSelected.push(jQuery(explorerItems[i]).attr("name"));
}
}
else {
filesSelected = [jQuery(obj).attr("name")];
keyFileSelected = obj;
}
for (var i = 0; i < filesSelected.length; i++) {
jQuery(".explorer_item[name='" + filesSelected[i] + "']").addClass("explorer_item_select");
}
updateFileNames();
}
dragFiles = filesSelected;
}
function onFileDragOver(event, obj) {
event.preventDefault();
}
function onFileDrop(event, obj) {
var destDirName = jQuery(obj).attr("name");
if ((dragFiles.length == 0) || (dragFiles.indexOf(destDirName) >= 0)) {
return false;
}
var clipboardTask = (event.ctrlKey == true || event.metaKey == true) ? "copy" : "cut";
var clipboardDest = dir + DS + destDirName;
submit("paste_items", null, null, null, null, null, null, clipboardTask, dragFiles.join("**#**"), dir, clipboardDest);
event.preventDefault();
}
function onBtnOpenClick(event, obj) {
if (jQuery(".explorer_item[name='" + filesSelected[0] + "']").attr("isDir") == true) {
filesSelected.length = 1;
submit("", null, null, null, dir + DS + filesSelected[0], null, null, null, null, null, null);
}
else {
submitFiles();
}
}
function onBtnImportClick(event, obj) {
importFiles();
}
function onBtnCancelClick(event, obj) {
window.parent.tb_remove();
}
function onBtnSelectAllClick() {
jQuery(".explorer_item").addClass("explorer_item_select");
filesSelected = [];
jQuery(".explorer_item").each(function() {
var objName = jQuery(this).attr("name");
if (filesSelected.indexOf(objName) == -1) {
filesSelected.push(objName);
keyFileSelected = this;
}
});
}
function onBtnSelectAllMediLibraryClick() {
jQuery(".importer_item").addClass("importer_item_select");
filesSelectedML = [];
jQuery(".importer_item").each(function() {
var objName = jQuery(this).attr("path");
if (filesSelectedML.indexOf(objName) == -1) {
filesSelectedML.push(objName);
keyFileSelectedML = this;
}
});
} | JavaScript |
/*
* jQuery Iframe Transport Plugin 1.6.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint unparam: true, nomen: true */
/*global define, window, document */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['jquery'], factory);
} else {
// Browser globals:
factory(window.jQuery);
}
}(function ($) {
'use strict';
// Helper variable to create unique names for the transport iframes:
var counter = 0;
// The iframe transport accepts three additional options:
// options.fileInput: a jQuery collection of file input fields
// options.paramName: the parameter name for the file form data,
// overrides the name property of the file input field(s),
// can be a string or an array of strings.
// options.formData: an array of objects with name and value properties,
// equivalent to the return data of .serializeArray(), e.g.:
// [{name: 'a', value: 1}, {name: 'b', value: 2}]
$.ajaxTransport('iframe', function (options) {
if (options.async) {
var form,
iframe,
addParamChar;
return {
send: function (_, completeCallback) {
form = $('<form style="display:none;"></form>');
form.attr('accept-charset', options.formAcceptCharset);
addParamChar = /\?/.test(options.url) ? '&' : '?';
// XDomainRequest only supports GET and POST:
if (options.type === 'DELETE') {
options.url = options.url + addParamChar + '_method=DELETE';
options.type = 'POST';
} else if (options.type === 'PUT') {
options.url = options.url + addParamChar + '_method=PUT';
options.type = 'POST';
} else if (options.type === 'PATCH') {
options.url = options.url + addParamChar + '_method=PATCH';
options.type = 'POST';
}
// javascript:false as initial iframe src
// prevents warning popups on HTTPS in IE6.
// IE versions below IE8 cannot set the name property of
// elements that have already been added to the DOM,
// so we set the name along with the iframe HTML markup:
iframe = $(
'<iframe src="javascript:false;" name="iframe-transport-' +
(counter += 1) + '"></iframe>'
).bind('load', function () {
var fileInputClones,
paramNames = $.isArray(options.paramName) ?
options.paramName : [options.paramName];
iframe
.unbind('load')
.bind('load', function () {
var response;
// Wrap in a try/catch block to catch exceptions thrown
// when trying to access cross-domain iframe contents:
try {
response = iframe.contents();
// Google Chrome and Firefox do not throw an
// exception when calling iframe.contents() on
// cross-domain requests, so we unify the response:
if (!response.length || !response[0].firstChild) {
throw new Error();
}
} catch (e) {
response = undefined;
}
// The complete callback returns the
// iframe content document as response object:
completeCallback(
200,
'success',
{'iframe': response}
);
// Fix for IE endless progress bar activity bug
// (happens on form submits to iframe targets):
$('<iframe src="javascript:false;"></iframe>')
.appendTo(form);
form.remove();
});
form
.prop('target', iframe.prop('name'))
.prop('action', options.url)
.prop('method', options.type);
if (options.formData) {
$.each(options.formData, function (index, field) {
$('<input type="hidden"/>')
.prop('name', field.name)
.val(field.value)
.appendTo(form);
});
}
if (options.fileInput && options.fileInput.length &&
options.type === 'POST') {
fileInputClones = options.fileInput.clone();
// Insert a clone for each file input field:
options.fileInput.after(function (index) {
return fileInputClones[index];
});
if (options.paramName) {
options.fileInput.each(function (index) {
$(this).prop(
'name',
paramNames[index] || options.paramName
);
});
}
// Appending the file input fields to the hidden form
// removes them from their original location:
form
.append(options.fileInput)
.prop('enctype', 'multipart/form-data')
// enctype must be set as encoding for IE:
.prop('encoding', 'multipart/form-data');
}
form.submit();
// Insert the file input fields at their original location
// by replacing the clones with the originals:
if (fileInputClones && fileInputClones.length) {
options.fileInput.each(function (index, input) {
var clone = $(fileInputClones[index]);
$(input).prop('name', clone.prop('name'));
clone.replaceWith(input);
});
}
});
form.append(iframe).appendTo(document.body);
},
abort: function () {
if (iframe) {
// javascript:false as iframe src aborts the request
// and prevents warning popups on HTTPS in IE6.
// concat is used to avoid the "Script URL" JSLint error:
iframe
.unbind('load')
.prop('src', 'javascript'.concat(':false;'));
}
if (form) {
form.remove();
}
}
};
}
});
// The iframe transport returns the iframe content document as response.
// The following adds converters from iframe to text, json, html, and script:
$.ajaxSetup({
converters: {
'iframe text': function (iframe) {
return iframe && $(iframe[0].body).text();
},
'iframe json': function (iframe) {
return iframe && $.parseJSON($(iframe[0].body).text());
},
'iframe html': function (iframe) {
return iframe && $(iframe[0].body).html();
},
'iframe script': function (iframe) {
return iframe && $.globalEval($(iframe[0].body).text());
}
}
});
}));
| JavaScript |
/*
* jQuery.upload v1.0.2
*
* Copyright (c) 2010 lagos
* Dual licensed under the MIT and GPL licenses.
*
* http://lagoscript.org
*/
(function($) {
var uuid = 0;
$.fn.upload = function(url, data, callback, type) {
var self = this, inputs, checkbox, checked,
iframeName = 'jquery_upload' + ++uuid,
iframe = $('<iframe name="' + iframeName + '" style="position:absolute;top:-9999px" />').appendTo('body'),
form = '<form target="' + iframeName + '" method="post" enctype="multipart/form-data" />';
if ($.isFunction(data)) {
type = callback;
callback = data;
data = {};
}
checkbox = $('input:checkbox', this);
checked = $('input:checked', this);
form = self.wrapAll(form).parent('form').attr('action', url);
// Make sure radios and checkboxes keep original values
// (IE resets checkd attributes when appending)
checkbox.removeAttr('checked');
checked.attr('checked', true);
inputs = createInputs(data);
inputs = inputs ? $(inputs).appendTo(form) : null;
form.submit(function() {
iframe.load(function() {
var data = handleData(this, type),
checked = $('input:checked', self);
form.after(self).remove();
checkbox.removeAttr('checked');
checked.attr('checked', true);
if (inputs) {
inputs.remove();
}
setTimeout(function() {
iframe.remove();
if (type === 'script') {
$.globalEval(data);
}
if (callback) {
callback.call(self, data);
}
}, 0);
});
}).submit();
return this;
};
function createInputs(data) {
return $.map(param(data), function(param) {
return '<input type="hidden" name="' + param.name + '" value="' + param.value + '"/>';
}).join('');
}
function param(data) {
if ($.isArray(data)) {
return data;
}
var params = [];
function add(name, value) {
params.push({name:name, value:value});
}
if (typeof data === 'object') {
$.each(data, function(name) {
if ($.isArray(this)) {
$.each(this, function() {
add(name, this);
});
} else {
add(name, $.isFunction(this) ? this() : this);
}
});
} else if (typeof data === 'string') {
$.each(data.split('&'), function() {
var param = $.map(this.split('='), function(v) {
return decodeURIComponent(v.replace(/\+/g, ' '));
});
add(param[0], param[1]);
});
}
return params;
}
function handleData(iframe, type) {
var data, contents = $(iframe).contents().get(0);
if ($.isXMLDoc(contents) || contents.XMLDocument) {
return contents.XMLDocument || contents;
}
data = $(contents).find('body').html();
switch (type) {
case 'xml':
data = parseXml(data);
break;
case 'json':
data = window.eval('(' + data + ')');
break;
}
return data;
}
function parseXml(text) {
if (window.DOMParser) {
return new DOMParser().parseFromString(text, 'application/xml');
} else {
var xml = new ActiveXObject('Microsoft.XMLDOM');
xml.async = false;
xml.loadXML(text);
return xml;
}
}
})(jQuery);
| JavaScript |
/*
* Superfish v1.4.8 - jQuery menu widget
* Copyright (c) 2008 Joel Birch
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
*/
/*
* Superfish v1.4.8 - jQuery menu widget
* Copyright (c) 2008 Joel Birch
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
*/
(function($) {
$.fn.superfish = function(op) {
var sf = $.fn.superfish,
c = sf.c,
$arrow = $(['<span class="', c.arrowClass, '"> »</span>'].join("")),
over = function() {
var $$ = $(this),
menu = getMenu($$);
clearTimeout(menu.sfTimer);
$$.showSuperfishUl().siblings().hideSuperfishUl();
}, out = function() {
var $$ = $(this),
menu = getMenu($$),
o = sf.op;
clearTimeout(menu.sfTimer);
menu.sfTimer = setTimeout(function() {
o.retainPath = ($.inArray($$[0], o.$path) > -1);
$$.hideSuperfishUl();
if (o.$path.length && $$.parents(["li.", o.hoverClass].join("")).length < 1) {
over.call(o.$path);
}
}, o.delay);
}, getMenu = function($menu) {
var menu = $menu.parents(["ul.", c.menuClass, ":first"].join(""))[0];
sf.op = sf.o[menu.serial];
return menu;
}, addArrow = function($a) {
// $a.addClass(c.anchorClass).append($arrow.clone());
};
return this.each(function() {
var s = this.serial = sf.o.length;
var o = $.extend({}, sf.defaults, op);
o.$path = $("li." + o.pathClass, this).slice(0, o.pathLevels).each(function() {
$(this).addClass([o.hoverClass, c.bcClass].join(" ")).filter("li:has(ul)").removeClass(o.pathClass);
});
sf.o[s] = sf.op = o;
$("li:has(ul)", this)[($.fn.hoverIntent && !o.disableHI) ? "hoverIntent" : "hover"](over, out).each(function() {
if (o.autoArrows) {
addArrow($(">a:first-child", this));
}
}).not("." + c.bcClass).hideSuperfishUl();
var $a = $("a", this);
$a.each(function(i) {
var $li = $a.eq(i).parents("li");
$a.eq(i).focus(function() {
over.call($li);
}).blur(function() {
out.call($li);
});
});
o.onInit.call(this);
}).each(function() {
var menuClasses = [c.menuClass];
if (sf.op.dropShadows && !($.browser.msie && $.browser.version < 7)) {
menuClasses.push(c.shadowClass);
}
$(this).addClass(menuClasses.join(" "));
});
};
var sf = $.fn.superfish;
sf.o = [];
sf.op = {};
sf.IE7fix = function() {
var o = sf.op;
if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity != undefined) {
this.toggleClass(sf.c.shadowClass + "-off");
}
};
sf.c = {
bcClass: "sf-breadcrumb",
menuClass: "sf-js-enabled",
anchorClass: "sf-with-ul",
arrowClass: "sf-sub-indicator",
shadowClass: "sf-shadow"
};
sf.defaults = {
hoverClass: "sfHover",
pathClass: "overideThisToUse",
pathLevels: 1,
delay: 800,
animation: {
opacity: "show"
},
speed: "normal",
autoArrows: true,
dropShadows: true,
disableHI: false,
onInit: function() {},
onBeforeShow: function() {},
onShow: function() {},
onHide: function() {}
};
$.fn.extend({
hideSuperfishUl: function() {
var o = sf.op,
not = (o.retainPath === true) ? o.$path : "";
o.retainPath = false;
var $ul = $(["li.", o.hoverClass].join(""), this).add(this).not(not).removeClass(o.hoverClass).find(">ul").hide().css("visibility", "hidden");
o.onHide.call($ul);
return this;
},
showSuperfishUl: function() {
var o = sf.op,
sh = sf.c.shadowClass + "-off",
$ul = this.addClass(o.hoverClass).find(">ul:hidden").css("visibility", "visible");
sf.IE7fix.call($ul);
o.onBeforeShow.call($ul);
$ul.animate(o.animation, o.speed, function() {
sf.IE7fix.call($ul);
o.onShow.call($ul);
});
return this;
}
});
})(jQuery);
// (function($){$.fn.superfish=function(op){var sf=$.fn.superfish,c=sf.c,$arrow=$(['<span class="',c.arrowClass,'"> »</span>'].join("")),over=function(){var $$=$(this),menu=getMenu($$);clearTimeout(menu.sfTimer);$$.showSuperfishUl().siblings().hideSuperfishUl();},out=function(){var $$=$(this),menu=getMenu($$),o=sf.op;clearTimeout(menu.sfTimer);menu.sfTimer=setTimeout(function(){o.retainPath=($.inArray($$[0],o.$path)>-1);$$.hideSuperfishUl();if(o.$path.length&&$$.parents(["li.",o.hoverClass].join("")).length<1){over.call(o.$path);}},o.delay);},getMenu=function($menu){var menu=$menu.parents(["ul.",c.menuClass,":first"].join(""))[0];sf.op=sf.o[menu.serial];return menu;},addArrow=function($a){$a.addClass(c.anchorClass).append($arrow.clone());};return this.each(function(){var s=this.serial=sf.o.length;var o=$.extend({},sf.defaults,op);o.$path=$("li."+o.pathClass,this).slice(0,o.pathLevels).each(function(){$(this).addClass([o.hoverClass,c.bcClass].join(" ")).filter("li:has(ul)").removeClass(o.pathClass);});sf.o[s]=sf.op=o;$("li:has(ul)",this)[($.fn.hoverIntent&&!o.disableHI)?"hoverIntent":"hover"](over,out).each(function(){if(o.autoArrows){addArrow($(">a:first-child",this));}}).not("."+c.bcClass).hideSuperfishUl();var $a=$("a",this);$a.each(function(i){var $li=$a.eq(i).parents("li");$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});});o.onInit.call(this);}).each(function(){var menuClasses=[c.menuClass];if(sf.op.dropShadows&&!($.browser.msie&&$.browser.version<7)){menuClasses.push(c.shadowClass);}$(this).addClass(menuClasses.join(" "));});};var sf=$.fn.superfish;sf.o=[];sf.op={};sf.IE7fix=function(){var o=sf.op;if($.browser.msie&&$.browser.version>6&&o.dropShadows&&o.animation.opacity!=undefined){this.toggleClass(sf.c.shadowClass+"-off");}};sf.c={bcClass:"sf-breadcrumb",menuClass:"sf-js-enabled",anchorClass:"sf-with-ul",arrowClass:"sf-sub-indicator",shadowClass:"sf-shadow"};sf.defaults={hoverClass:"sfHover",pathClass:"overideThisToUse",pathLevels:1,delay:800,animation:{opacity:"show"},speed:"normal",autoArrows:true,dropShadows:true,disableHI:false,onInit:function(){},onBeforeShow:function(){},onShow:function(){},onHide:function(){}};$.fn.extend({hideSuperfishUl:function(){var o=sf.op,not=(o.retainPath===true)?o.$path:"";o.retainPath=false;var $ul=$(["li.",o.hoverClass].join(""),this).add(this).not(not).removeClass(o.hoverClass).find(">ul").hide().css("visibility","hidden");o.onHide.call($ul);return this;},showSuperfishUl:function(){var o=sf.op,sh=sf.c.shadowClass+"-off",$ul=this.addClass(o.hoverClass).find(">ul:hidden").css("visibility","visible");sf.IE7fix.call($ul);o.onBeforeShow.call($ul);$ul.animate(o.animation,o.speed,function(){sf.IE7fix.call($ul);o.onShow.call($ul);});return this;}});})(jQuery); | JavaScript |
jQuery(window).load(function() {
/* Navigation */
jQuery('#submenu ul.sfmenu').superfish({
delay: 500, // 0.1 second delay on mouseout
animation: { opacity:'show',height:'show'}, // fade-in and slide-down animation
dropShadows: true // disable drop shadows
});
/* Hover block */
jQuery('.portfolio-box').hover(function(){
jQuery(this).find('div').animate({opacity:'1'},{queue:false,duration:500});
}, function(){
jQuery(this).find('div').animate({opacity:'0'},{queue:false,duration:500});
});
/* equal column */
var biggestHeight = 0;
//check each of them
jQuery('.equal_height').each(function(){
//if the height of the current element is
//bigger then the current biggestHeight value
if(jQuery(this).height() > biggestHeight){
//update the biggestHeight with the
//height of the current elements
biggestHeight = jQuery(this).height();
}
});
//when checking for biggestHeight is done set that
//height to all the elements
jQuery('.equal_height').height(biggestHeight);
//cài css cho iframe them album/anh
jQuery(".toggle_button").click(function()
{
toogle();
});
function toogle()
{
if(jQuery("#secondary").is(":visible"))
{
jQuery("#secondary").hide(500,function(){
jQuery("#toggle_icon").css({'transition-duration': '0.5s','-webkit-transform' : 'rotate(90deg)',
'-moz-transform' : 'rotate(90deg)',
'-ms-transform' : 'rotate(90deg)',
'transform' : 'rotate(90deg)'});
//jQuery("#primary").css({'transition-duration': '0.5s','-webkit-transition':'margin-left 0.5s','margin-left':'50px' });
jQuery(".grid_12").css({'transition-duration': '0.5s','-webkit-transition':'margin-left 0.5s','margin-left':'0px','width':'100%'});
// jQuery(".grid_12").css({'transition-duration': '0.5s','-webkit-transition':'width 0.5s','width':'100%' });
});
// var r=jQuery("iframe").width()+100;
// if (r>1300)
// else
// jQuery("#primary").css({'transition-duration': '0.5s','-webkit-transition':'margin-left 0.5s','margin-left':'150px', });
SetCookie('Is_SideBar_Showing',0,1);
}
else
{
jQuery("#secondary").show(500);
jQuery("#secondary").css({'transition-duration': '0.5s','-webkit-transition':'width 150px','width':'150px' });
jQuery("#toggle_icon").css({'transition-duration': '0.5s','-webkit-transform' : 'rotate(0deg)',
'-moz-transform' : 'rotate(0deg)',
'-ms-transform' : 'rotate(0deg)',
'transform' : 'rotate(0deg)'});
//jQuery("#primary").css({'transition-duration': '0.5s','-webkit-transition': 'margin-left 0.5s width 0.5s','margin-left':'50px' });
jQuery(".grid_12").css({'transition-duration': '0.5s','-webkit-transition':'margin-left 0.5s','margin-left':'130px','width':'auto'});
// jQuery(".grid_12").css({'width':'auto' });
SetCookie('Is_SideBar_Showing',1,1);
}
}
function SetCookie(cookieName,cookieValue,nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString();
}
function ReadCookie(cookieName) {
var theCookie=" "+document.cookie;
var ind=theCookie.indexOf(" "+cookieName+"=");
if (ind==-1) ind=theCookie.indexOf(";"+cookieName+"=");
if (ind==-1 || cookieName=="") return "";
var ind1=theCookie.indexOf(";",ind+1);
if (ind1==-1) ind1=theCookie.length;
return unescape(theCookie.substring(ind+cookieName.length+2,ind1));
}
if(ReadCookie('Is_SideBar_Showing')==0)
{
jQuery("#secondary").hide(500,function(){
jQuery("#toggle_icon").css({'transition-duration': '0.5s','-webkit-transform' : 'rotate(90deg)',
'-moz-transform' : 'rotate(90deg)',
'-ms-transform' : 'rotate(90deg)',
'transform' : 'rotate(90deg)'});
//jQuery("#primary").css({'transition-duration': '0.5s','-webkit-transition':'margin-left 0.5s','margin-left':'50px' });
jQuery(".grid_12").css({'transition-duration': '0.5s','-webkit-transition':'margin-left 0.5s','margin-left':'0px','width':'100%'});
// jQuery(".grid_12").css({'transition-duration': '0.5s','-webkit-transition':'width 0.5s','width':'100%' });
});
}
else
{
jQuery("#secondary").show();
jQuery("#secondary").css({'width':'150px' });
jQuery("#toggle_icon").css({
'-moz-transform' : 'rotate(0deg)',
'-ms-transform' : 'rotate(0deg)',
'transform' : 'rotate(0deg)'});
//jQuery("#primary").css({'transition-duration': '0.5s','-webkit-transition': 'margin-left 0.5s width 0.5s','margin-left':'50px' });
jQuery(".grid_12").css({'margin-left':'130px','width':'auto'});
}
});
jQuery(document).ready(function(){
//tao doi tuong websocket
// var wsUri = "ws://localhost:9070/server.php";
// wsocket = new WebSocket(wsUri);
//khi ket noi duoc mo
//khi nhan dc message tu sever
// wsocket.onmessage = function(ev) {
// var msg = JSON.parse(ev.data); //chuyen chuoi JSON thanh doi tuong JSON
// var type = msg.notification_type; //kieu message
// var counter=msg.counter;
// if(type == 'like') //neu la message cua user
// {
// jQuery('.comment_counter').css({opacity: 0});
// jQuery('.comment_counter').text(counter);
// jQuery('.comment_counter').css({top: '-10px'});
// jQuery('.comment_counter').animate({top: '-2px', opacity: 1});
// }
// if(type == 'comment') //neu la message cua he thong
// {
// jQuery('.like_counter').css({opacity: 0});
// jQuery('.like_counter').text(counter);
// jQuery('.like_counter').css({top: '-10px'});
// jQuery('.like_counter').animate({top: '-2px', opacity: 1});
// }
// if(type == 'image') //neu la message cua he thong
// {
// jQuery('.image_counter').css({opacity: 0});
// jQuery('.image_counter').text(counter);
// jQuery('.image_counter').css({top: '-10px'});
// jQuery('.image_counter').animate({top: '-2px', opacity: 1});
// }
// if(type == 'message') //neu la message cua he thong
// {
// jQuery('.image_counter').css({opacity: 0});
// jQuery('.image_counter').text(counter);
// jQuery('.image_counter').css({top: '-10px'});
// jQuery('.image_counter').animate({top: '-2px', opacity: 1});
// }
// };
}); | JavaScript |
jQuery(document).ready(function () {
// Установка реального цвета с учётом прозрачности
function setIColor(fake_i, color, opacity) {
var id = fake_i.attr("id");
var name = id.substring(5);
jQuery('#' + name).val(color);
jQuery('#' + name + '_opacity').val(opacity);
}
function setColorPicker() {
jQuery("input.color-picker").css({"height": "auto", "padding-top": "7px", "padding-right": "7px", "padding-bottom": "7px"});
jQuery("input.color-picker").minicolors({
'control': "wheel",
'defaultValue': "#FFFFFF",
'changeDelay': 25,
'inline': false,
'position': "bottom left",
'letterCase': "lowercase",
'theme': "bootstrap",
'opacity': true,
'change': function(hex, opacity) {
var color = hex;
if (opacity != 1)
color = jQuery(this).minicolors('rgbaString');
setIColor(jQuery(this), color, opacity);
},
'hide': function() {
var opacity = jQuery(this).minicolors('opacity');
var color = jQuery(this).val();
if (opacity != 1)
color = jQuery(this).minicolors('rgbaString');
setIColor(jQuery(this), color, opacity);
}
});
jQuery(".minicolors").css({"width": "100%"});
jQuery(".minicolors-swatch").css({"top": "4px"});
}
// + Выставляем opacity
// + Запоняем скрытые поля из знач по умолчанию
jQuery("input[type=hidden]").each(function() {
var id = jQuery(this).attr('id');
// Запоняем скрытые поля из знач по умолчанию
if (typeof(id) != 'undefined' && id.substring(10) != 'opacity' && jQuery("#fake_" + id.substring(0, 9)).length > 0) {
if (jQuery(this).val() == '')
jQuery(this).val( jQuery("#fake_" + id.substring(0, 9)).val() );
}
if (typeof(id) == 'undefined' || id.substring(10) != 'opacity' || jQuery("#fake_" + id.substring(0, 9)).length <= 0)
return;
jQuery("#fake_" + id.substring(0, 9)).attr('data-opacity', jQuery(this).val());
});
setColorPicker();
}); | JavaScript |
jQuery(document).ready(function($){
var optionsframework_upload;
var optionsframework_selector;
function optionsframework_add_file(event, selector) {
var upload = $(".uploaded-file"), frame;
var $el = $(this);
optionsframework_selector = selector;
event.preventDefault();
// If the media frame already exists, reopen it.
if ( optionsframework_upload ) {
optionsframework_upload.open();
} else {
// Create the media frame.
optionsframework_upload = wp.media.frames.optionsframework_upload = wp.media({
// Set the title of the modal.
title: $el.data('choose'),
// Customize the submit button.
button: {
// Set the text of the button.
text: $el.data('update'),
// Tell the button not to close the modal, since we're
// going to refresh the page when the image is selected.
close: false
}
});
// When an image is selected, run a callback.
optionsframework_upload.on( 'select', function() {
// Grab the selected attachment.
var attachment = optionsframework_upload.state().get('selection').first();
optionsframework_upload.close();
optionsframework_selector.find('.upload').val(attachment.attributes.url);
if ( attachment.attributes.type == 'image' ) {
optionsframework_selector.find('.screenshot').empty().hide().append('<img src="' + attachment.attributes.url + '"><a class="remove-image">Remove</a>').slideDown('fast');
}
optionsframework_selector.find('.upload-button').unbind().addClass('remove-file').removeClass('upload-button').val(optionsframework_l10n.remove);
optionsframework_selector.find('.of-background-properties').slideDown();
optionsframework_selector.find('.remove-image, .remove-file').on('click', function() {
optionsframework_remove_file( $(this).parents('.section') );
});
});
}
// Finally, open the modal.
optionsframework_upload.open();
}
function optionsframework_remove_file(selector) {
selector.find('.remove-image').hide();
selector.find('.upload').val('');
selector.find('.of-background-properties').hide();
selector.find('.screenshot').slideUp();
selector.find('.remove-file').unbind().addClass('upload-button').removeClass('remove-file').val(optionsframework_l10n.upload);
// We don't display the upload button if .upload-notice is present
// This means the user doesn't have the WordPress 3.5 Media Library Support
if ( $('.section-upload .upload-notice').length > 0 ) {
$('.upload-button').remove();
}
selector.find('.upload-button').on('click', function(event) {
optionsframework_add_file(event, $(this).parents('.section'));
});
}
$('.remove-image, .remove-file').on('click', function() {
optionsframework_remove_file( $(this).parents('.section') );
});
$('.upload-button').click( function( event ) {
optionsframework_add_file(event, $(this).parents('.section'));
});
}); | JavaScript |
/**
* Custom scripts needed for the colorpicker, image button selectors,
* and navigation tabs.
*/
jQuery(document).ready(function($) {
// Loads the color pickers
$('.of-color').wpColorPicker();
// Image Options
$('.of-radio-img-img').click(function(){
$(this).parent().parent().find('.of-radio-img-img').removeClass('of-radio-img-selected');
$(this).addClass('of-radio-img-selected');
});
$('.of-radio-img-label').hide();
$('.of-radio-img-img').show();
$('.of-radio-img-radio').hide();
// Loads tabbed sections if they exist
if ( $('.nav-tab-wrapper').length > 0 ) {
options_framework_tabs();
}
function options_framework_tabs() {
// Hides all the .group sections to start
$('.group').hide();
// Find if a selected tab is saved in localStorage
var active_tab = '';
if ( typeof(localStorage) != 'undefined' ) {
active_tab = localStorage.getItem("active_tab");
}
// If active tab is saved and exists, load it's .group
if (active_tab != '' && $(active_tab).length ) {
$(active_tab).fadeIn();
$(active_tab + '-tab').addClass('nav-tab-active');
} else {
$('.group:first').fadeIn();
$('.nav-tab-wrapper a:first').addClass('nav-tab-active');
}
// Bind tabs clicks
$('.nav-tab-wrapper a').click(function(evt) {
evt.preventDefault();
// Remove active class from all tabs
$('.nav-tab-wrapper a').removeClass('nav-tab-active');
$(this).addClass('nav-tab-active').blur();
var group = $(this).attr('href');
if (typeof(localStorage) != 'undefined' ) {
localStorage.setItem("active_tab", $(this).attr('href') );
}
$('.group').hide();
$(group).fadeIn();
// Editor height sometimes needs adjustment when unhidden
$('.wp-editor-wrap').each(function() {
var editor_iframe = $(this).find('iframe');
if ( editor_iframe.height() < 30 ) {
editor_iframe.css({'height':'auto'});
}
});
});
}
}); | JavaScript |
/*!
* imagesLoaded PACKAGED v3.1.8
* JavaScript is all like "You images are done yet or what?"
* MIT License
*/
/*!
* EventEmitter v4.2.6 - git.io/ee
* Oliver Caldwell
* MIT license
* @preserve
*/
(function () {
/**
* Class for managing events.
* Can be extended to provide event functionality in other classes.
*
* @class EventEmitter Manages event registering and emitting.
*/
function EventEmitter() {}
// Shortcuts to improve speed and size
var proto = EventEmitter.prototype;
var exports = this;
var originalGlobalValue = exports.EventEmitter;
/**
* Finds the index of the listener for the event in it's storage array.
*
* @param {Function[]} listeners Array of listeners to search through.
* @param {Function} listener Method to look for.
* @return {Number} Index of the specified listener, -1 if not found
* @api private
*/
function indexOfListener(listeners, listener) {
var i = listeners.length;
while (i--) {
if (listeners[i].listener === listener) {
return i;
}
}
return -1;
}
/**
* Alias a method while keeping the context correct, to allow for overwriting of target method.
*
* @param {String} name The name of the target method.
* @return {Function} The aliased method
* @api private
*/
function alias(name) {
return function aliasClosure() {
return this[name].apply(this, arguments);
};
}
/**
* Returns the listener array for the specified event.
* Will initialise the event object and listener arrays if required.
* Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them.
* Each property in the object response is an array of listener functions.
*
* @param {String|RegExp} evt Name of the event to return the listeners from.
* @return {Function[]|Object} All listener functions for the event.
*/
proto.getListeners = function getListeners(evt) {
var events = this._getEvents();
var response;
var key;
// Return a concatenated array of all matching events if
// the selector is a regular expression.
if (typeof evt === 'object') {
response = {};
for (key in events) {
if (events.hasOwnProperty(key) && evt.test(key)) {
response[key] = events[key];
}
}
}
else {
response = events[evt] || (events[evt] = []);
}
return response;
};
/**
* Takes a list of listener objects and flattens it into a list of listener functions.
*
* @param {Object[]} listeners Raw listener objects.
* @return {Function[]} Just the listener functions.
*/
proto.flattenListeners = function flattenListeners(listeners) {
var flatListeners = [];
var i;
for (i = 0; i < listeners.length; i += 1) {
flatListeners.push(listeners[i].listener);
}
return flatListeners;
};
/**
* Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful.
*
* @param {String|RegExp} evt Name of the event to return the listeners from.
* @return {Object} All listener functions for an event in an object.
*/
proto.getListenersAsObject = function getListenersAsObject(evt) {
var listeners = this.getListeners(evt);
var response;
if (listeners instanceof Array) {
response = {};
response[evt] = listeners;
}
return response || listeners;
};
/**
* Adds a listener function to the specified event.
* The listener will not be added if it is a duplicate.
* If the listener returns true then it will be removed after it is called.
* If you pass a regular expression as the event name then the listener will be added to all events that match it.
*
* @param {String|RegExp} evt Name of the event to attach the listener to.
* @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.addListener = function addListener(evt, listener) {
var listeners = this.getListenersAsObject(evt);
var listenerIsWrapped = typeof listener === 'object';
var key;
for (key in listeners) {
if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) {
listeners[key].push(listenerIsWrapped ? listener : {
listener: listener,
once: false
});
}
}
return this;
};
/**
* Alias of addListener
*/
proto.on = alias('addListener');
/**
* Semi-alias of addListener. It will add a listener that will be
* automatically removed after it's first execution.
*
* @param {String|RegExp} evt Name of the event to attach the listener to.
* @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.addOnceListener = function addOnceListener(evt, listener) {
return this.addListener(evt, {
listener: listener,
once: true
});
};
/**
* Alias of addOnceListener.
*/
proto.once = alias('addOnceListener');
/**
* Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad.
* You need to tell it what event names should be matched by a regex.
*
* @param {String} evt Name of the event to create.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.defineEvent = function defineEvent(evt) {
this.getListeners(evt);
return this;
};
/**
* Uses defineEvent to define multiple events.
*
* @param {String[]} evts An array of event names to define.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.defineEvents = function defineEvents(evts) {
for (var i = 0; i < evts.length; i += 1) {
this.defineEvent(evts[i]);
}
return this;
};
/**
* Removes a listener function from the specified event.
* When passed a regular expression as the event name, it will remove the listener from all events that match it.
*
* @param {String|RegExp} evt Name of the event to remove the listener from.
* @param {Function} listener Method to remove from the event.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.removeListener = function removeListener(evt, listener) {
var listeners = this.getListenersAsObject(evt);
var index;
var key;
for (key in listeners) {
if (listeners.hasOwnProperty(key)) {
index = indexOfListener(listeners[key], listener);
if (index !== -1) {
listeners[key].splice(index, 1);
}
}
}
return this;
};
/**
* Alias of removeListener
*/
proto.off = alias('removeListener');
/**
* Adds listeners in bulk using the manipulateListeners method.
* If you pass an object as the second argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added.
* You can also pass it a regular expression to add the array of listeners to all events that match it.
* Yeah, this function does quite a bit. That's probably a bad thing.
*
* @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once.
* @param {Function[]} [listeners] An optional array of listener functions to add.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.addListeners = function addListeners(evt, listeners) {
// Pass through to manipulateListeners
return this.manipulateListeners(false, evt, listeners);
};
/**
* Removes listeners in bulk using the manipulateListeners method.
* If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
* You can also pass it an event name and an array of listeners to be removed.
* You can also pass it a regular expression to remove the listeners from all events that match it.
*
* @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once.
* @param {Function[]} [listeners] An optional array of listener functions to remove.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.removeListeners = function removeListeners(evt, listeners) {
// Pass through to manipulateListeners
return this.manipulateListeners(true, evt, listeners);
};
/**
* Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level.
* The first argument will determine if the listeners are removed (true) or added (false).
* If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
* You can also pass it an event name and an array of listeners to be added/removed.
* You can also pass it a regular expression to manipulate the listeners of all events that match it.
*
* @param {Boolean} remove True if you want to remove listeners, false if you want to add.
* @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once.
* @param {Function[]} [listeners] An optional array of listener functions to add/remove.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) {
var i;
var value;
var single = remove ? this.removeListener : this.addListener;
var multiple = remove ? this.removeListeners : this.addListeners;
// If evt is an object then pass each of it's properties to this method
if (typeof evt === 'object' && !(evt instanceof RegExp)) {
for (i in evt) {
if (evt.hasOwnProperty(i) && (value = evt[i])) {
// Pass the single listener straight through to the singular method
if (typeof value === 'function') {
single.call(this, i, value);
}
else {
// Otherwise pass back to the multiple function
multiple.call(this, i, value);
}
}
}
}
else {
// So evt must be a string
// And listeners must be an array of listeners
// Loop over it and pass each one to the multiple method
i = listeners.length;
while (i--) {
single.call(this, evt, listeners[i]);
}
}
return this;
};
/**
* Removes all listeners from a specified event.
* If you do not specify an event then all listeners will be removed.
* That means every event will be emptied.
* You can also pass a regex to remove all events that match it.
*
* @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.removeEvent = function removeEvent(evt) {
var type = typeof evt;
var events = this._getEvents();
var key;
// Remove different things depending on the state of evt
if (type === 'string') {
// Remove all listeners for the specified event
delete events[evt];
}
else if (type === 'object') {
// Remove all events matching the regex.
for (key in events) {
if (events.hasOwnProperty(key) && evt.test(key)) {
delete events[key];
}
}
}
else {
// Remove all listeners in all events
delete this._events;
}
return this;
};
/**
* Alias of removeEvent.
*
* Added to mirror the node API.
*/
proto.removeAllListeners = alias('removeEvent');
/**
* Emits an event of your choice.
* When emitted, every listener attached to that event will be executed.
* If you pass the optional argument array then those arguments will be passed to every listener upon execution.
* Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately.
* So they will not arrive within the array on the other side, they will be separate.
* You can also pass a regular expression to emit to all events that match it.
*
* @param {String|RegExp} evt Name of the event to emit and execute listeners for.
* @param {Array} [args] Optional array of arguments to be passed to each listener.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.emitEvent = function emitEvent(evt, args) {
var listeners = this.getListenersAsObject(evt);
var listener;
var i;
var key;
var response;
for (key in listeners) {
if (listeners.hasOwnProperty(key)) {
i = listeners[key].length;
while (i--) {
// If the listener returns true then it shall be removed from the event
// The function is executed either with a basic call or an apply if there is an args array
listener = listeners[key][i];
if (listener.once === true) {
this.removeListener(evt, listener.listener);
}
response = listener.listener.apply(this, args || []);
if (response === this._getOnceReturnValue()) {
this.removeListener(evt, listener.listener);
}
}
}
}
return this;
};
/**
* Alias of emitEvent
*/
proto.trigger = alias('emitEvent');
/**
* Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on.
* As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it.
*
* @param {String|RegExp} evt Name of the event to emit and execute listeners for.
* @param {...*} Optional additional arguments to be passed to each listener.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.emit = function emit(evt) {
var args = Array.prototype.slice.call(arguments, 1);
return this.emitEvent(evt, args);
};
/**
* Sets the current value to check against when executing listeners. If a
* listeners return value matches the one set here then it will be removed
* after execution. This value defaults to true.
*
* @param {*} value The new value to check for when executing listeners.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.setOnceReturnValue = function setOnceReturnValue(value) {
this._onceReturnValue = value;
return this;
};
/**
* Fetches the current value to check against when executing listeners. If
* the listeners return value matches this one then it should be removed
* automatically. It will return true by default.
*
* @return {*|Boolean} The current value to check for or the default, true.
* @api private
*/
proto._getOnceReturnValue = function _getOnceReturnValue() {
if (this.hasOwnProperty('_onceReturnValue')) {
return this._onceReturnValue;
}
else {
return true;
}
};
/**
* Fetches the events object and creates one if required.
*
* @return {Object} The events storage object.
* @api private
*/
proto._getEvents = function _getEvents() {
return this._events || (this._events = {});
};
/**
* Reverts the global {@link EventEmitter} to its previous value and returns a reference to this version.
*
* @return {Function} Non conflicting EventEmitter class.
*/
EventEmitter.noConflict = function noConflict() {
exports.EventEmitter = originalGlobalValue;
return EventEmitter;
};
// Expose the class either via AMD, CommonJS or the global object
if (typeof define === 'function' && define.amd) {
define('eventEmitter/EventEmitter',[],function () {
return EventEmitter;
});
}
else if (typeof module === 'object' && module.exports){
module.exports = EventEmitter;
}
else {
this.EventEmitter = EventEmitter;
}
}.call(this));
/*!
* eventie v1.0.4
* event binding helper
* eventie.bind( elem, 'click', myFn )
* eventie.unbind( elem, 'click', myFn )
*/
/*jshint browser: true, undef: true, unused: true */
/*global define: false */
( function( window ) {
var docElem = document.documentElement;
var bind = function() {};
function getIEEvent( obj ) {
var event = window.event;
// add event.target
event.target = event.target || event.srcElement || obj;
return event;
}
if ( docElem.addEventListener ) {
bind = function( obj, type, fn ) {
obj.addEventListener( type, fn, false );
};
} else if ( docElem.attachEvent ) {
bind = function( obj, type, fn ) {
obj[ type + fn ] = fn.handleEvent ?
function() {
var event = getIEEvent( obj );
fn.handleEvent.call( fn, event );
} :
function() {
var event = getIEEvent( obj );
fn.call( obj, event );
};
obj.attachEvent( "on" + type, obj[ type + fn ] );
};
}
var unbind = function() {};
if ( docElem.removeEventListener ) {
unbind = function( obj, type, fn ) {
obj.removeEventListener( type, fn, false );
};
} else if ( docElem.detachEvent ) {
unbind = function( obj, type, fn ) {
obj.detachEvent( "on" + type, obj[ type + fn ] );
try {
delete obj[ type + fn ];
} catch ( err ) {
// can't delete window object properties
obj[ type + fn ] = undefined;
}
};
}
var eventie = {
bind: bind,
unbind: unbind
};
// transport
if ( typeof define === 'function' && define.amd ) {
// AMD
define( 'eventie/eventie',eventie );
} else {
// browser global
window.eventie = eventie;
}
})( this );
/*!
* imagesLoaded v3.1.8
* JavaScript is all like "You images are done yet or what?"
* MIT License
*/
( function( window, factory ) {
// universal module definition
/*global define: false, module: false, require: false */
if ( typeof define === 'function' && define.amd ) {
// AMD
define( [
'eventEmitter/EventEmitter',
'eventie/eventie'
], function( EventEmitter, eventie ) {
return factory( window, EventEmitter, eventie );
});
} else if ( typeof exports === 'object' ) {
// CommonJS
module.exports = factory(
window,
require('wolfy87-eventemitter'),
require('eventie')
);
} else {
// browser global
window.imagesLoaded = factory(
window,
window.EventEmitter,
window.eventie
);
}
})( window,
// -------------------------- factory -------------------------- //
function factory( window, EventEmitter, eventie ) {
var $ = window.jQuery;
var console = window.console;
var hasConsole = typeof console !== 'undefined';
// -------------------------- helpers -------------------------- //
// extend objects
function extend( a, b ) {
for ( var prop in b ) {
a[ prop ] = b[ prop ];
}
return a;
}
var objToString = Object.prototype.toString;
function isArray( obj ) {
return objToString.call( obj ) === '[object Array]';
}
// turn element or nodeList into an array
function makeArray( obj ) {
var ary = [];
if ( isArray( obj ) ) {
// use object if already an array
ary = obj;
} else if ( typeof obj.length === 'number' ) {
// convert nodeList to array
for ( var i=0, len = obj.length; i < len; i++ ) {
ary.push( obj[i] );
}
} else {
// array of single index
ary.push( obj );
}
return ary;
}
// -------------------------- imagesLoaded -------------------------- //
/**
* @param {Array, Element, NodeList, String} elem
* @param {Object or Function} options - if function, use as callback
* @param {Function} onAlways - callback function
*/
function ImagesLoaded( elem, options, onAlways ) {
// coerce ImagesLoaded() without new, to be new ImagesLoaded()
if ( !( this instanceof ImagesLoaded ) ) {
return new ImagesLoaded( elem, options );
}
// use elem as selector string
if ( typeof elem === 'string' ) {
elem = document.querySelectorAll( elem );
}
this.elements = makeArray( elem );
this.options = extend( {}, this.options );
if ( typeof options === 'function' ) {
onAlways = options;
} else {
extend( this.options, options );
}
if ( onAlways ) {
this.on( 'always', onAlways );
}
this.getImages();
if ( $ ) {
// add jQuery Deferred object
this.jqDeferred = new $.Deferred();
}
// HACK check async to allow time to bind listeners
var _this = this;
setTimeout( function() {
_this.check();
});
}
ImagesLoaded.prototype = new EventEmitter();
ImagesLoaded.prototype.options = {};
ImagesLoaded.prototype.getImages = function() {
this.images = [];
// filter & find items if we have an item selector
for ( var i=0, len = this.elements.length; i < len; i++ ) {
var elem = this.elements[i];
// filter siblings
if ( elem.nodeName === 'IMG' ) {
this.addImage( elem );
}
// find children
// no non-element nodes, #143
var nodeType = elem.nodeType;
if ( !nodeType || !( nodeType === 1 || nodeType === 9 || nodeType === 11 ) ) {
continue;
}
var childElems = elem.querySelectorAll('img');
// concat childElems to filterFound array
for ( var j=0, jLen = childElems.length; j < jLen; j++ ) {
var img = childElems[j];
this.addImage( img );
}
}
};
/**
* @param {Image} img
*/
ImagesLoaded.prototype.addImage = function( img ) {
var loadingImage = new LoadingImage( img );
this.images.push( loadingImage );
};
ImagesLoaded.prototype.check = function() {
var _this = this;
var checkedCount = 0;
var length = this.images.length;
this.hasAnyBroken = false;
// complete if no images
if ( !length ) {
this.complete();
return;
}
function onConfirm( image, message ) {
if ( _this.options.debug && hasConsole ) {
console.log( 'confirm', image, message );
}
_this.progress( image );
checkedCount++;
if ( checkedCount === length ) {
_this.complete();
}
return true; // bind once
}
for ( var i=0; i < length; i++ ) {
var loadingImage = this.images[i];
loadingImage.on( 'confirm', onConfirm );
loadingImage.check();
}
};
ImagesLoaded.prototype.progress = function( image ) {
this.hasAnyBroken = this.hasAnyBroken || !image.isLoaded;
// HACK - Chrome triggers event before object properties have changed. #83
var _this = this;
setTimeout( function() {
_this.emit( 'progress', _this, image );
if ( _this.jqDeferred && _this.jqDeferred.notify ) {
_this.jqDeferred.notify( _this, image );
}
});
};
ImagesLoaded.prototype.complete = function() {
var eventName = this.hasAnyBroken ? 'fail' : 'done';
this.isComplete = true;
var _this = this;
// HACK - another setTimeout so that confirm happens after progress
setTimeout( function() {
_this.emit( eventName, _this );
_this.emit( 'always', _this );
if ( _this.jqDeferred ) {
var jqMethod = _this.hasAnyBroken ? 'reject' : 'resolve';
_this.jqDeferred[ jqMethod ]( _this );
}
});
};
// -------------------------- jquery -------------------------- //
if ( $ ) {
$.fn.imagesLoaded = function( options, callback ) {
var instance = new ImagesLoaded( this, options, callback );
return instance.jqDeferred.promise( $(this) );
};
}
// -------------------------- -------------------------- //
function LoadingImage( img ) {
this.img = img;
}
LoadingImage.prototype = new EventEmitter();
LoadingImage.prototype.check = function() {
// first check cached any previous images that have same src
var resource = cache[ this.img.src ] || new Resource( this.img.src );
if ( resource.isConfirmed ) {
this.confirm( resource.isLoaded, 'cached was confirmed' );
return;
}
// If complete is true and browser supports natural sizes,
// try to check for image status manually.
if ( this.img.complete && this.img.naturalWidth !== undefined ) {
// report based on naturalWidth
this.confirm( this.img.naturalWidth !== 0, 'naturalWidth' );
return;
}
// If none of the checks above matched, simulate loading on detached element.
var _this = this;
resource.on( 'confirm', function( resrc, message ) {
_this.confirm( resrc.isLoaded, message );
return true;
});
resource.check();
};
LoadingImage.prototype.confirm = function( isLoaded, message ) {
this.isLoaded = isLoaded;
this.emit( 'confirm', this, message );
};
// -------------------------- Resource -------------------------- //
// Resource checks each src, only once
// separate class from LoadingImage to prevent memory leaks. See #115
var cache = {};
function Resource( src ) {
this.src = src;
// add to cache
cache[ src ] = this;
}
Resource.prototype = new EventEmitter();
Resource.prototype.check = function() {
// only trigger checking once
if ( this.isChecked ) {
return;
}
// simulate loading on detached element
var proxyImage = new Image();
eventie.bind( proxyImage, 'load', this );
eventie.bind( proxyImage, 'error', this );
proxyImage.src = this.src;
// set flag
this.isChecked = true;
};
// ----- events ----- //
// trigger specified handler for event type
Resource.prototype.handleEvent = function( event ) {
var method = 'on' + event.type;
if ( this[ method ] ) {
this[ method ]( event );
}
};
Resource.prototype.onload = function( event ) {
this.confirm( true, 'onload' );
this.unbindProxyEvents( event );
};
Resource.prototype.onerror = function( event ) {
this.confirm( false, 'onerror' );
this.unbindProxyEvents( event );
};
// ----- confirm ----- //
Resource.prototype.confirm = function( isLoaded, message ) {
this.isConfirmed = true;
this.isLoaded = isLoaded;
this.emit( 'confirm', this, message );
};
Resource.prototype.unbindProxyEvents = function( event ) {
eventie.unbind( event.target, 'load', this );
eventie.unbind( event.target, 'error', this );
};
// ----- ----- //
return ImagesLoaded;
});
| JavaScript |
/**
* This file adds some LIVE to the Theme Customizer live preview. To leverage
* this, set your custom settings to 'postMessage' and then add your handling
* here. Your javascript should grab settings from customizer controls, and
* then make any necessary changes to the page using jQuery.
*/
( function( $ ) {
//Update site accent color in real time...
wp.customize( 'accent_color', function( value ) {
value.bind( function( newval ) {
$('.post-title a:hover').css('color', newval );
$('.main-menu .current-menu-item:before').css('color', newval );
$('.main-menu .current_page_item:before').css('color', newval );
$('.post-content blockquote:before').css('color', newval );
} );
} );
} )( jQuery ); | JavaScript |
jQuery(document).ready(function($) {
//Masonry blocks
$blocks = $(".posts");
$blocks.imagesLoaded(function(){
$blocks.masonry({
itemSelector: '.post-container'
});
// Fade blocks in after images are ready (prevents jumping and re-rendering)
$(".post-container").fadeIn();
});
$(document).ready( function() { setTimeout( function() { $blocks.masonry(); }, 500); });
$(window).resize(function () {
$blocks.masonry();
});
// Toggle navigation
$(".nav-toggle").on("click", function(){
$(this).toggleClass("active");
$(".mobile-navigation").slideToggle();
});
// Hide mobile-menu > 1000
$(window).resize(function() {
if ($(window).width() > 1000) {
$(".nav-toggle").removeClass("active");
$(".mobile-navigation").hide();
}
});
// Load Flexslider
$(".flexslider").flexslider({
animation: "slide",
controlNav: false,
smoothHeight: true,
start: $blocks.masonry(),
});
// resize videos after container
var vidSelector = ".post iframe, .post object, .post video, .widget-content iframe, .widget-content object, .widget-content iframe";
var resizeVideo = function(sSel) {
$( sSel ).each(function() {
var $video = $(this),
$container = $video.parent(),
iTargetWidth = $container.width();
if ( !$video.attr("data-origwidth") ) {
$video.attr("data-origwidth", $video.attr("width"));
$video.attr("data-origheight", $video.attr("height"));
}
var ratio = iTargetWidth / $video.attr("data-origwidth");
$video.css("width", iTargetWidth + "px");
$video.css("height", ( $video.attr("data-origheight") * ratio ) + "px");
});
};
resizeVideo(vidSelector);
$(window).resize(function() {
resizeVideo(vidSelector);
});
// When Jetpack Infinite scroll posts have loaded
$( document.body ).on( 'post-load', function () {
var $container = $('.posts');
$container.masonry( 'reloadItems' );
$blocks.imagesLoaded(function(){
$blocks.masonry({
itemSelector: '.post-container'
});
// Fade blocks in after images are ready (prevents jumping and re-rendering)
$(".post-container").fadeIn();
});
// Rerun video resizing
resizeVideo(vidSelector);
$container.masonry( 'reloadItems' );
// Load Flexslider
$(".flexslider").flexslider({
animation: "slide",
controlNav: false,
prevText: "Previous",
nextText: "Next",
smoothHeight: true
});
$(document).ready( function() { setTimeout( function() { $blocks.masonry(); }, 500); });
});
}); | JavaScript |
/**
* Handles toggling the navigation menu for small screens and
* accessibility for submenu items.
*/
( function() {
var nav = document.getElementById( 'site-navigation' ), button, menu;
if ( ! nav ) {
return;
}
button = nav.getElementsByTagName( 'h3' )[0];
menu = nav.getElementsByTagName( 'ul' )[0];
if ( ! button ) {
return;
}
// Hide button if menu is missing or empty.
if ( ! menu || ! menu.childNodes.length ) {
button.style.display = 'none';
return;
}
button.onclick = function() {
if ( -1 === menu.className.indexOf( 'nav-menu' ) ) {
menu.className = 'nav-menu';
}
if ( -1 !== button.className.indexOf( 'toggled-on' ) ) {
button.className = button.className.replace( ' toggled-on', '' );
menu.className = menu.className.replace( ' toggled-on', '' );
} else {
button.className += ' toggled-on';
menu.className += ' toggled-on';
}
};
} )();
// Better focus for hidden submenu items for accessibility.
( function( $ ) {
$( '.main-navigation' ).find( 'a' ).on( 'focus.twentytwelve blur.twentytwelve', function() {
$( this ).parents( '.menu-item, .page_item' ).toggleClass( 'focus' );
} );
} )( jQuery );
| JavaScript |
/**
* Theme Customizer enhancements for a better user experience.
*
* Contains handlers to make Theme Customizer preview reload changes asynchronously.
* Things like site title, description, and background color changes.
*/
( function( $ ) {
// Site title and description.
wp.customize( 'blogname', function( value ) {
value.bind( function( to ) {
$( '.site-title a' ).text( to );
} );
} );
wp.customize( 'blogdescription', function( value ) {
value.bind( function( to ) {
$( '.site-description' ).text( to );
} );
} );
// Header text color
wp.customize( 'header_textcolor', function( value ) {
value.bind( function( to ) {
if ( 'blank' === to ) {
$( '.site-title, .site-title a, .site-description' ).css( {
'clip': 'rect(1px, 1px, 1px, 1px)',
'position': 'absolute'
} );
} else {
$( '.site-title, .site-title a, .site-description' ).css( {
'clip': 'auto',
'color': to,
'position': 'relative'
} );
}
} );
} );
// Hook into background color/image change and adjust body class value as needed.
wp.customize( 'background_color', function( value ) {
value.bind( function( to ) {
var body = $( 'body' );
if ( ( '#ffffff' == to || '#fff' == to ) && 'none' == body.css( 'background-image' ) )
body.addClass( 'custom-background-white' );
else if ( '' == to && 'none' == body.css( 'background-image' ) )
body.addClass( 'custom-background-empty' );
else
body.removeClass( 'custom-background-empty custom-background-white' );
} );
} );
wp.customize( 'background_image', function( value ) {
value.bind( function( to ) {
var body = $( 'body' );
if ( '' != to )
body.removeClass( 'custom-background-empty custom-background-white' );
else if ( 'rgb(255, 255, 255)' == body.css( 'background-color' ) )
body.addClass( 'custom-background-white' );
else if ( 'rgb(230, 230, 230)' == body.css( 'background-color' ) && '' == _wpCustomizeSettings.values.background_color )
body.addClass( 'custom-background-empty' );
} );
} );
} )( jQuery );
| JavaScript |
/**
* jQuery Masonry v2.0.110927
* A dynamic layout plugin for jQuery
* The flip-side of CSS Floats
* http://masonry.desandro.com
*
* Licensed under the MIT license.
* Copyright 2011 David DeSandro
*/
(function( window, $, undefined ){
/*
* smartresize: debounced resize event for jQuery
*
* latest version and complete README available on Github:
* https://github.com/louisremi/jquery.smartresize.js
*
* Copyright 2011 @louis_remi
* Licensed under the MIT license.
*/
var $event = $.event,
resizeTimeout;
$event.special.smartresize = {
setup: function() {
$(this).bind( "resize", $event.special.smartresize.handler );
},
teardown: function() {
$(this).unbind( "resize", $event.special.smartresize.handler );
},
handler: function( event, execAsap ) {
// Save the context
var context = this,
args = arguments;
// set correct event type
event.type = "smartresize";
if ( resizeTimeout ) { clearTimeout( resizeTimeout ); }
resizeTimeout = setTimeout(function() {
jQuery.event.handle.apply( context, args );
}, execAsap === "execAsap"? 0 : 100 );
}
};
$.fn.smartresize = function( fn ) {
return fn ? this.bind( "smartresize", fn ) : this.trigger( "smartresize", ["execAsap"] );
};
// ========================= Masonry ===============================
// our "Widget" object constructor
$.Mason = function( options, element ){
this.element = $( element );
this._create( options );
this._init();
};
// styles of container element we want to keep track of
var masonryContainerStyles = [ 'position', 'height' ];
$.Mason.settings = {
isResizable: true,
isAnimated: false,
animationOptions: {
queue: false,
duration: 500
},
gutterWidth: 0,
isRTL: false,
isFitWidth: false
};
$.Mason.prototype = {
_filterFindBricks: function( $elems ) {
var selector = this.options.itemSelector;
// if there is a selector
// filter/find appropriate item elements
return !selector ? $elems : $elems.filter( selector ).add( $elems.find( selector ) );
},
_getBricks: function( $elems ) {
var $bricks = this._filterFindBricks( $elems )
.css({ position: 'absolute' })
.addClass('masonry-brick');
return $bricks;
},
// sets up widget
_create : function( options ) {
this.options = $.extend( true, {}, $.Mason.settings, options );
this.styleQueue = [];
// need to get bricks
this.reloadItems();
// get original styles in case we re-apply them in .destroy()
var elemStyle = this.element[0].style;
this.originalStyle = {};
for ( var i=0, len = masonryContainerStyles.length; i < len; i++ ) {
var prop = masonryContainerStyles[i];
this.originalStyle[ prop ] = elemStyle[ prop ] || '';
}
this.element.css({
position : 'relative'
});
this.horizontalDirection = this.options.isRTL ? 'right' : 'left';
this.offset = {};
// get top left position of where the bricks should be
var $cursor = $( document.createElement('div') );
this.element.prepend( $cursor );
this.offset.y = Math.round( $cursor.position().top );
// get horizontal offset
if ( !this.options.isRTL ) {
this.offset.x = Math.round( $cursor.position().left );
} else {
$cursor.css({ 'float': 'right', display: 'inline-block'});
this.offset.x = Math.round( this.element.outerWidth() - $cursor.position().left );
}
$cursor.remove();
// add masonry class first time around
var instance = this;
setTimeout( function() {
instance.element.addClass('masonry');
}, 0 );
// bind resize method
if ( this.options.isResizable ) {
$(window).bind( 'smartresize.masonry', function() {
instance.resize();
});
}
},
// _init fires when instance is first created
// and when instance is triggered again -> $el.masonry();
_init : function( callback ) {
this._getColumns('masonry');
this._reLayout( callback );
},
option: function( key, value ){
// set options AFTER initialization:
// signature: $('#foo').bar({ cool:false });
if ( $.isPlainObject( key ) ){
this.options = $.extend(true, this.options, key);
}
},
// ====================== General Layout ======================
// used on collection of atoms (should be filtered, and sorted before )
// accepts atoms-to-be-laid-out to start with
layout : function( $bricks, callback ) {
// layout logic
var $brick, colSpan, groupCount, groupY, groupColY, j;
for (var i=0, len = $bricks.length; i < len; i++) {
$brick = $( $bricks[i] );
//how many columns does this brick span
colSpan = Math.ceil( $brick.outerWidth(true) / this.columnWidth );
colSpan = Math.min( colSpan, this.cols );
if ( colSpan === 1 ) {
// if brick spans only one column, just like singleMode
this._placeBrick( $brick, this.colYs );
} else {
// brick spans more than one column
// how many different places could this brick fit horizontally
groupCount = this.cols + 1 - colSpan;
groupY = [];
// for each group potential horizontal position
for ( j=0; j < groupCount; j++ ) {
// make an array of colY values for that one group
groupColY = this.colYs.slice( j, j+colSpan );
// and get the max value of the array
groupY[j] = Math.max.apply( Math, groupColY );
}
this._placeBrick( $brick, groupY );
}
}
// set the size of the container
var containerSize = {};
containerSize.height = Math.max.apply( Math, this.colYs ) - this.offset.y;
if ( this.options.isFitWidth ) {
var unusedCols = 0,
i = this.cols;
// count unused columns
while ( --i ) {
if ( this.colYs[i] !== this.offset.y ) {
break;
}
unusedCols++;
}
// fit container to columns that have been used;
containerSize.width = (this.cols - unusedCols) * this.columnWidth - this.options.gutterWidth;
}
this.styleQueue.push({ $el: this.element, style: containerSize });
// are we animating the layout arrangement?
// use plugin-ish syntax for css or animate
var styleFn = !this.isLaidOut ? 'css' : (
this.options.isAnimated ? 'animate' : 'css'
),
animOpts = this.options.animationOptions;
// process styleQueue
var obj;
for (i=0, len = this.styleQueue.length; i < len; i++) {
obj = this.styleQueue[i];
obj.$el[ styleFn ]( obj.style, animOpts );
}
// clear out queue for next time
this.styleQueue = [];
// provide $elems as context for the callback
if ( callback ) {
callback.call( $bricks );
}
this.isLaidOut = true;
},
// calculates number of columns
// i.e. this.columnWidth = 200
_getColumns : function() {
var container = this.options.isFitWidth ? this.element.parent() : this.element,
containerWidth = container.width();
this.columnWidth = this.options.columnWidth ||
// or use the size of the first item
this.$bricks.outerWidth(true) ||
// if there's no items, use size of container
containerWidth;
this.columnWidth += this.options.gutterWidth;
this.cols = Math.floor( ( containerWidth + this.options.gutterWidth ) / this.columnWidth );
this.cols = Math.max( this.cols, 1 );
},
_placeBrick : function( $brick, setY ) {
// get the minimum Y value from the columns
var minimumY = Math.min.apply( Math, setY ),
shortCol = 0;
// Find index of short column, the first from the left
for (var i=0, len = setY.length; i < len; i++) {
if ( setY[i] === minimumY ) {
shortCol = i;
break;
}
}
// position the brick
var position = {
top : minimumY
};
// position.left or position.right
position[ this.horizontalDirection ] = this.columnWidth * shortCol + this.offset.x;
this.styleQueue.push({ $el: $brick, style: position });
// apply setHeight to necessary columns
var setHeight = minimumY + $brick.outerHeight(true),
setSpan = this.cols + 1 - len;
for ( i=0; i < setSpan; i++ ) {
this.colYs[ shortCol + i ] = setHeight;
}
},
resize : function() {
var prevColCount = this.cols;
// get updated colCount
this._getColumns('masonry');
if ( this.cols !== prevColCount ) {
// if column count has changed, trigger new layout
this._reLayout();
}
},
_reLayout : function( callback ) {
// reset columns
var i = this.cols;
this.colYs = [];
while (i--) {
this.colYs.push( this.offset.y );
}
// apply layout logic to all bricks
this.layout( this.$bricks, callback );
},
// ====================== Convenience methods ======================
// goes through all children again and gets bricks in proper order
reloadItems : function() {
this.$bricks = this._getBricks( this.element.children() );
},
reload : function( callback ) {
this.reloadItems();
this._init( callback );
},
// convienence method for working with Infinite Scroll
appended : function( $content, isAnimatedFromBottom, callback ) {
if ( isAnimatedFromBottom ) {
// set new stuff to the bottom
this._filterFindBricks( $content ).css({ top: this.element.height() });
var instance = this;
setTimeout( function(){
instance._appended( $content, callback );
}, 1 );
} else {
this._appended( $content, callback );
}
},
_appended : function( $content, callback ) {
var $newBricks = this._getBricks( $content );
// add new bricks to brick pool
this.$bricks = this.$bricks.add( $newBricks );
this.layout( $newBricks, callback );
},
// removes elements from Masonry widget
remove : function( $content ) {
this.$bricks = this.$bricks.not( $content );
$content.remove();
},
// destroys widget, returns elements and container back (close) to original style
destroy : function() {
this.$bricks
.removeClass('masonry-brick')
.each(function(){
this.style.position = '';
this.style.top = '';
this.style.left = '';
});
// re-apply saved container styles
var elemStyle = this.element[0].style;
for ( var i=0, len = masonryContainerStyles.length; i < len; i++ ) {
var prop = masonryContainerStyles[i];
elemStyle[ prop ] = this.originalStyle[ prop ];
}
this.element
.unbind('.masonry')
.removeClass('masonry')
.removeData('masonry');
$(window).unbind('.masonry');
}
};
// ======================= imagesLoaded Plugin ===============================
/*!
* jQuery imagesLoaded plugin v1.0.3
* http://github.com/desandro/imagesloaded
*
* MIT License. by Paul Irish et al.
*/
// $('#my-container').imagesLoaded(myFunction)
// or
// $('img').imagesLoaded(myFunction)
// execute a callback when all images have loaded.
// needed because .load() doesn't work on cached images
// callback function gets image collection as argument
// `this` is the container
$.fn.imagesLoaded = function( callback ) {
var $this = this,
$images = $this.find('img').add( $this.filter('img') ),
len = $images.length,
blank = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
function triggerCallback() {
callback.call( $this, $images );
}
function imgLoaded() {
if ( --len <= 0 && this.src !== blank ){
setTimeout( triggerCallback );
$images.unbind( 'load error', imgLoaded );
}
}
if ( !len ) {
triggerCallback();
}
$images.bind( 'load error', imgLoaded ).each( function() {
// cached images don't fire load sometimes, so we reset src.
if (this.complete || this.complete === undefined){
var src = this.src;
// webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
// data uri bypasses webkit log warning (thx doug jones)
this.src = blank;
this.src = src;
}
});
return $this;
};
// helper function for logging errors
// $.error breaks jQuery chaining
var logError = function( message ) {
if ( this.console ) {
console.error( message );
}
};
// ======================= Plugin bridge ===============================
// leverages data method to either create or return $.Mason constructor
// A bit from jQuery UI
// https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.widget.js
// A bit from jcarousel
// https://github.com/jsor/jcarousel/blob/master/lib/jquery.jcarousel.js
$.fn.masonry = function( options ) {
if ( typeof options === 'string' ) {
// call method
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function(){
var instance = $.data( this, 'masonry' );
if ( !instance ) {
logError( "cannot call methods on masonry prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for masonry instance" );
return;
}
// apply method
instance[ options ].apply( instance, args );
});
} else {
this.each(function() {
var instance = $.data( this, 'masonry' );
if ( instance ) {
// apply options & init
instance.option( options || {} );
instance._init();
} else {
// initialize new instance
$.data( this, 'masonry', new $.Mason( options, this ) );
}
});
}
return this;
};
})( window, jQuery ); | JavaScript |
/**
* AJAX Upload ( http://valums.com/ajax-upload/ )
* Copyright (c) Andrew Valums
* Licensed under the MIT license
*/
(function () {
/**
* Attaches event to a dom element.
* @param {Element} el
* @param type event name
* @param fn callback This refers to the passed element
*/
function addEvent(el, type, fn){
if (el.addEventListener) {
el.addEventListener(type, fn, false);
} else if (el.attachEvent) {
el.attachEvent('on' + type, function(){
fn.call(el);
});
} else {
throw new Error('not supported or DOM not loaded');
}
}
/**
* Attaches resize event to a window, limiting
* number of event fired. Fires only when encounteres
* delay of 100 after series of events.
*
* Some browsers fire event multiple times when resizing
* http://www.quirksmode.org/dom/events/resize.html
*
* @param fn callback This refers to the passed element
*/
function addResizeEvent(fn){
var timeout;
addEvent(window, 'resize', function(){
if (timeout){
clearTimeout(timeout);
}
timeout = setTimeout(fn, 100);
});
}
// Needs more testing, will be rewriten for next version
// getOffset function copied from jQuery lib (http://jquery.com/)
if (document.documentElement.getBoundingClientRect){
// Get Offset using getBoundingClientRect
// http://ejohn.org/blog/getboundingclientrect-is-awesome/
var getOffset = function(el){
var box = el.getBoundingClientRect();
var doc = el.ownerDocument;
var body = doc.body;
var docElem = doc.documentElement; // for ie
var clientTop = docElem.clientTop || body.clientTop || 0;
var clientLeft = docElem.clientLeft || body.clientLeft || 0;
// In Internet Explorer 7 getBoundingClientRect property is treated as physical,
// while others are logical. Make all logical, like in IE8.
var zoom = 1;
if (body.getBoundingClientRect) {
var bound = body.getBoundingClientRect();
zoom = (bound.right - bound.left) / body.clientWidth;
}
if (zoom > 1) {
clientTop = 0;
clientLeft = 0;
}
var top = box.top / zoom + (window.pageYOffset || docElem && docElem.scrollTop / zoom || body.scrollTop / zoom) - clientTop, left = box.left / zoom + (window.pageXOffset || docElem && docElem.scrollLeft / zoom || body.scrollLeft / zoom) - clientLeft;
return {
top: top,
left: left
};
};
} else {
// Get offset adding all offsets
var getOffset = function(el){
var top = 0, left = 0;
do {
top += el.offsetTop || 0;
left += el.offsetLeft || 0;
el = el.offsetParent;
} while (el);
return {
left: left,
top: top
};
};
}
/**
* Returns left, top, right and bottom properties describing the border-box,
* in pixels, with the top-left relative to the body
* @param {Element} el
* @return {Object} Contains left, top, right,bottom
*/
function getBox(el){
var left, right, top, bottom;
var offset = getOffset(el);
left = offset.left;
top = offset.top;
right = left + el.offsetWidth;
bottom = top + el.offsetHeight;
return {
left: left,
right: right,
top: top,
bottom: bottom
};
}
/**
* Helper that takes object literal
* and add all properties to element.style
* @param {Element} el
* @param {Object} styles
*/
function addStyles(el, styles){
for (var name in styles) {
if (styles.hasOwnProperty(name)) {
el.style[name] = styles[name];
}
}
}
/**
* Function places an absolutely positioned
* element on top of the specified element
* copying position and dimentions.
* @param {Element} from
* @param {Element} to
*/
function copyLayout(from, to){
var box = getBox(from);
addStyles(to, {
position: 'absolute',
left : box.left + 'px',
top : box.top + 'px',
width : from.offsetWidth + 'px',
height : from.offsetHeight + 'px'
});
}
/**
* Creates and returns element from html chunk
* Uses innerHTML to create an element
*/
var toElement = (function(){
var div = document.createElement('div');
return function(html){
div.innerHTML = html;
var el = div.firstChild;
return div.removeChild(el);
};
})();
/**
* Function generates unique id
* @return unique id
*/
var getUID = (function(){
var id = 0;
return function(){
return 'ValumsAjaxUpload' + id++;
};
})();
/**
* Get file name from path
* @param {String} file path to file
* @return filename
*/
function fileFromPath(file){
return file.replace(/.*(\/|\\)/, "");
}
/**
* Get file extension lowercase
* @param {String} file name
* @return file extenstion
*/
function getExt(file){
return (-1 !== file.indexOf('.')) ? file.replace(/.*[.]/, '') : '';
}
function hasClass(el, name){
var re = new RegExp('\\b' + name + '\\b');
return re.test(el.className);
}
function addClass(el, name){
if ( ! hasClass(el, name)){
el.className += ' ' + name;
}
}
function removeClass(el, name){
var re = new RegExp('\\b' + name + '\\b');
el.className = el.className.replace(re, '');
}
function removeNode(el){
el.parentNode.removeChild(el);
}
/**
* Easy styling and uploading
* @constructor
* @param button An element you want convert to
* upload button. Tested dimentions up to 500x500px
* @param {Object} options See defaults below.
*/
window.AjaxUpload = function(button, options){
this._settings = {
// Location of the server-side upload script
action: 'upload.php',
// File upload name
name: 'userfile',
// Select & upload multiple files at once FF3.6+, Chrome 4+
multiple: false,
// Additional data to send
data: {},
// Submit file as soon as it's selected
autoSubmit: true,
// The type of data that you're expecting back from the server.
// html and xml are detected automatically.
// Only useful when you are using json data as a response.
// Set to "json" in that case.
responseType: false,
// Class applied to button when mouse is hovered
hoverClass: 'hover',
// Class applied to button when button is focused
focusClass: 'focus',
// Class applied to button when AU is disabled
disabledClass: 'disabled',
// When user selects a file, useful with autoSubmit disabled
// You can return false to cancel upload
onChange: function(file, extension){
},
// Callback to fire before file is uploaded
// You can return false to cancel upload
onSubmit: function(file, extension){
},
// Fired when file upload is completed
// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
onComplete: function(file, response){
}
};
// Merge the users options with our defaults
for (var i in options) {
if (options.hasOwnProperty(i)){
this._settings[i] = options[i];
}
}
// button isn't necessary a dom element
if (button.jquery){
// jQuery object was passed
button = button[0];
} else if (typeof button == "string") {
if (/^#.*/.test(button)){
// If jQuery user passes #elementId don't break it
button = button.slice(1);
}
button = document.getElementById(button);
}
if ( ! button || button.nodeType !== 1){
throw new Error("Please make sure that you're passing a valid element");
}
if ( button.nodeName.toUpperCase() == 'A'){
// disable link
addEvent(button, 'click', function(e){
if (e && e.preventDefault){
e.preventDefault();
} else if (window.event){
window.event.returnValue = false;
}
});
}
// DOM element
this._button = button;
// DOM element
this._input = null;
// If disabled clicking on button won't do anything
this._disabled = false;
// if the button was disabled before refresh if will remain
// disabled in FireFox, let's fix it
this.enable();
this._rerouteClicks();
};
// assigning methods to our class
AjaxUpload.prototype = {
setData: function(data){
this._settings.data = data;
},
disable: function(){
addClass(this._button, this._settings.disabledClass);
this._disabled = true;
var nodeName = this._button.nodeName.toUpperCase();
if (nodeName == 'INPUT' || nodeName == 'BUTTON'){
this._button.setAttribute('disabled', 'disabled');
}
// hide input
if (this._input){
if (this._input.parentNode) {
// We use visibility instead of display to fix problem with Safari 4
// The problem is that the value of input doesn't change if it
// has display none when user selects a file
this._input.parentNode.style.visibility = 'hidden';
}
}
},
enable: function(){
removeClass(this._button, this._settings.disabledClass);
this._button.removeAttribute('disabled');
this._disabled = false;
},
/**
* Creates invisible file input
* that will hover above the button
* <div><input type='file' /></div>
*/
_createInput: function(){
var self = this;
var input = document.createElement("input");
input.setAttribute('type', 'file');
input.setAttribute('name', this._settings.name);
if(this._settings.multiple) input.setAttribute('multiple', 'multiple');
addStyles(input, {
'position' : 'absolute',
// in Opera only 'browse' button
// is clickable and it is located at
// the right side of the input
'right' : 0,
'margin' : 0,
'padding' : 0,
'fontSize' : '480px',
// in Firefox if font-family is set to
// 'inherit' the input doesn't work
'fontFamily' : 'sans-serif',
'cursor' : 'pointer'
});
var div = document.createElement("div");
addStyles(div, {
'display' : 'block',
'position' : 'absolute',
'overflow' : 'hidden',
'margin' : 0,
'padding' : 0,
'opacity' : 0,
// Make sure browse button is in the right side
// in Internet Explorer
'direction' : 'ltr',
//Max zIndex supported by Opera 9.0-9.2
'zIndex': 2147483583
});
// Make sure that element opacity exists.
// Otherwise use IE filter
if ( div.style.opacity !== "0") {
if (typeof(div.filters) == 'undefined'){
throw new Error('Opacity not supported by the browser');
}
div.style.filter = "alpha(opacity=0)";
}
addEvent(input, 'change', function(){
if ( ! input || input.value === ''){
return;
}
// Get filename from input, required
// as some browsers have path instead of it
var file = fileFromPath(input.value);
if (false === self._settings.onChange.call(self, file, getExt(file))){
self._clearInput();
return;
}
// Submit form when value is changed
if (self._settings.autoSubmit) {
self.submit();
}
});
addEvent(input, 'mouseover', function(){
addClass(self._button, self._settings.hoverClass);
});
addEvent(input, 'mouseout', function(){
removeClass(self._button, self._settings.hoverClass);
removeClass(self._button, self._settings.focusClass);
if (input.parentNode) {
// We use visibility instead of display to fix problem with Safari 4
// The problem is that the value of input doesn't change if it
// has display none when user selects a file
input.parentNode.style.visibility = 'hidden';
}
});
addEvent(input, 'focus', function(){
addClass(self._button, self._settings.focusClass);
});
addEvent(input, 'blur', function(){
removeClass(self._button, self._settings.focusClass);
});
div.appendChild(input);
document.body.appendChild(div);
this._input = input;
},
_clearInput : function(){
if (!this._input){
return;
}
// this._input.value = ''; Doesn't work in IE6
removeNode(this._input.parentNode);
this._input = null;
this._createInput();
removeClass(this._button, this._settings.hoverClass);
removeClass(this._button, this._settings.focusClass);
},
/**
* Function makes sure that when user clicks upload button,
* the this._input is clicked instead
*/
_rerouteClicks: function(){
var self = this;
// IE will later display 'access denied' error
// if you use using self._input.click()
// other browsers just ignore click()
addEvent(self._button, 'mouseover', function(){
if (self._disabled){
return;
}
if ( ! self._input){
self._createInput();
}
var div = self._input.parentNode;
copyLayout(self._button, div);
div.style.visibility = 'visible';
});
// commented because we now hide input on mouseleave
/**
* When the window is resized the elements
* can be misaligned if button position depends
* on window size
*/
//addResizeEvent(function(){
// if (self._input){
// copyLayout(self._button, self._input.parentNode);
// }
//});
},
/**
* Creates iframe with unique name
* @return {Element} iframe
*/
_createIframe: function(){
// We can't use getTime, because it sometimes return
// same value in safari :(
var id = getUID();
// We can't use following code as the name attribute
// won't be properly registered in IE6, and new window
// on form submit will open
// var iframe = document.createElement('iframe');
// iframe.setAttribute('name', id);
var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
// src="javascript:false; was added
// because it possibly removes ie6 prompt
// "This page contains both secure and nonsecure items"
// Anyway, it doesn't do any harm.
iframe.setAttribute('id', id);
iframe.style.display = 'none';
document.body.appendChild(iframe);
return iframe;
},
/**
* Creates form, that will be submitted to iframe
* @param {Element} iframe Where to submit
* @return {Element} form
*/
_createForm: function(iframe){
var settings = this._settings;
// We can't use the following code in IE6
// var form = document.createElement('form');
// form.setAttribute('method', 'post');
// form.setAttribute('enctype', 'multipart/form-data');
// Because in this case file won't be attached to request
var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
form.setAttribute('action', settings.action);
form.setAttribute('target', iframe.name);
form.style.display = 'none';
document.body.appendChild(form);
// Create hidden input element for each data key
for (var prop in settings.data) {
if (settings.data.hasOwnProperty(prop)){
var el = document.createElement("input");
el.setAttribute('type', 'hidden');
el.setAttribute('name', prop);
el.setAttribute('value', settings.data[prop]);
form.appendChild(el);
}
}
return form;
},
/**
* Gets response from iframe and fires onComplete event when ready
* @param iframe
* @param file Filename to use in onComplete callback
*/
_getResponse : function(iframe, file){
// getting response
var toDeleteFlag = false, self = this, settings = this._settings;
addEvent(iframe, 'load', function(){
if (// For Safari
iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
// For FF, IE
iframe.src == "javascript:'<html></html>';"){
// First time around, do not delete.
// We reload to blank page, so that reloading main page
// does not re-submit the post.
if (toDeleteFlag) {
// Fix busy state in FF3
setTimeout(function(){
removeNode(iframe);
}, 0);
}
return;
}
var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document;
// fixing Opera 9.26,10.00
if (doc.readyState && doc.readyState != 'complete') {
// Opera fires load event multiple times
// Even when the DOM is not ready yet
// this fix should not affect other browsers
return;
}
// fixing Opera 9.64
if (doc.body && doc.body.innerHTML == "false") {
// In Opera 9.64 event was fired second time
// when body.innerHTML changed from false
// to server response approx. after 1 sec
return;
}
var response;
if (doc.XMLDocument) {
// response is a xml document Internet Explorer property
response = doc.XMLDocument;
} else if (doc.body){
// response is html document or plain text
response = doc.body.innerHTML;
if (settings.responseType && settings.responseType.toLowerCase() == 'json') {
// If the document was sent as 'application/javascript' or
// 'text/javascript', then the browser wraps the text in a <pre>
// tag and performs html encoding on the contents. In this case,
// we need to pull the original text content from the text node's
// nodeValue property to retrieve the unmangled content.
// Note that IE6 only understands text/html
if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE') {
doc.normalize();
response = doc.body.firstChild.firstChild.nodeValue;
}
if (response) {
response = eval("(" + response + ")");
} else {
response = {};
}
}
} else {
// response is a xml document
response = doc;
}
settings.onComplete.call(self, file, response);
// Reload blank page, so that reloading main page
// does not re-submit the post. Also, remember to
// delete the frame
toDeleteFlag = true;
// Fix IE mixed content issue
iframe.src = "javascript:'<html></html>';";
});
},
/**
* Upload file contained in this._input
*/
submit: function(){
var self = this, settings = this._settings;
if ( ! this._input || this._input.value === ''){
return;
}
var file = fileFromPath(this._input.value);
// user returned false to cancel upload
if (false === settings.onSubmit.call(this, file, getExt(file))){
this._clearInput();
return;
}
// sending request
var iframe = this._createIframe();
var form = this._createForm(iframe);
// assuming following structure
// div -> input type='file'
removeNode(this._input.parentNode);
removeClass(self._button, self._settings.hoverClass);
removeClass(self._button, self._settings.focusClass);
form.appendChild(this._input);
form.submit();
// request set, clean up
removeNode(form); form = null;
removeNode(this._input); this._input = null;
// Get response from iframe and fire onComplete event when ready
this._getResponse(iframe, file);
// get ready for next request
this._createInput();
}
};
})();
| JavaScript |
/// <reference path="../../../lib/jquery-1.2.6.js" />
/*
Masked Input plugin for jQuery
Copyright (c) 2007-2009 Josh Bush (digitalbush.com)
Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
Version: 1.2.2 (03/09/2009 22:39:06)
*/
(function($) {
var pasteEventName = ($.browser.msie ? 'paste' : 'input') + ".mask";
var iPhone = (window.orientation != undefined);
$.mask = {
//Predefined character definitions
definitions: {
'9': "[0-9]",
'a': "[A-Za-z]",
'*': "[A-Za-z0-9]"
}
};
$.fn.extend({
//Helper Function for Caret positioning
caret: function(begin, end) {
if (this.length == 0) return;
if (typeof begin == 'number') {
end = (typeof end == 'number') ? end : begin;
return this.each(function() {
if (this.setSelectionRange) {
this.focus();
this.setSelectionRange(begin, end);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', begin);
range.select();
}
});
} else {
if (this[0].setSelectionRange) {
begin = this[0].selectionStart;
end = this[0].selectionEnd;
} else if (document.selection && document.selection.createRange) {
var range = document.selection.createRange();
begin = 0 - range.duplicate().moveStart('character', -100000);
end = begin + range.text.length;
}
return { begin: begin, end: end };
}
},
unmask: function() { return this.trigger("unmask"); },
mask: function(mask, settings) {
if (!mask && this.length > 0) {
var input = $(this[0]);
var tests = input.data("tests");
return $.map(input.data("buffer"), function(c, i) {
return tests[i] ? c : null;
}).join('');
}
settings = $.extend({
placeholder: "_",
completed: null
}, settings);
var defs = $.mask.definitions;
var tests = [];
var partialPosition = mask.length;
var firstNonMaskPos = null;
var len = mask.length;
$.each(mask.split(""), function(i, c) {
if (c == '?') {
len--;
partialPosition = i;
} else if (defs[c]) {
tests.push(new RegExp(defs[c]));
if(firstNonMaskPos==null)
firstNonMaskPos = tests.length - 1;
} else {
tests.push(null);
}
});
return this.each(function() {
var input = $(this);
var buffer = $.map(mask.split(""), function(c, i) { if (c != '?') return defs[c] ? settings.placeholder : c });
var ignore = false; //Variable for ignoring control keys
var focusText = input.val();
input.data("buffer", buffer).data("tests", tests);
function seekNext(pos) {
while (++pos <= len && !tests[pos]);
return pos;
};
function shiftL(pos) {
while (!tests[pos] && --pos >= 0);
for (var i = pos; i < len; i++) {
if (tests[i]) {
buffer[i] = settings.placeholder;
var j = seekNext(i);
if (j < len && tests[i].test(buffer[j])) {
buffer[i] = buffer[j];
} else
break;
}
}
writeBuffer();
input.caret(Math.max(firstNonMaskPos, pos));
};
function shiftR(pos) {
for (var i = pos, c = settings.placeholder; i < len; i++) {
if (tests[i]) {
var j = seekNext(i);
var t = buffer[i];
buffer[i] = c;
if (j < len && tests[j].test(t))
c = t;
else
break;
}
}
};
function keydownEvent(e) {
var pos = $(this).caret();
var k = e.keyCode;
ignore = (k < 16 || (k > 16 && k < 32) || (k > 32 && k < 41));
//delete selection before proceeding
if ((pos.begin - pos.end) != 0 && (!ignore || k == 8 || k == 46))
clearBuffer(pos.begin, pos.end);
//backspace, delete, and escape get special treatment
if (k == 8 || k == 46 || (iPhone && k == 127)) {//backspace/delete
shiftL(pos.begin + (k == 46 ? 0 : -1));
return false;
} else if (k == 27) {//escape
input.val(focusText);
input.caret(0, checkVal());
return false;
}
};
function keypressEvent(e) {
if (ignore) {
ignore = false;
//Fixes Mac FF bug on backspace
return (e.keyCode == 8) ? false : null;
}
e = e || window.event;
var k = e.charCode || e.keyCode || e.which;
var pos = $(this).caret();
if (e.ctrlKey || e.altKey || e.metaKey) {//Ignore
return true;
} else if ((k >= 32 && k <= 125) || k > 186) {//typeable characters
var p = seekNext(pos.begin - 1);
if (p < len) {
var c = String.fromCharCode(k);
if (tests[p].test(c)) {
shiftR(p);
buffer[p] = c;
writeBuffer();
var next = seekNext(p);
$(this).caret(next);
if (settings.completed && next == len)
settings.completed.call(input);
}
}
}
return false;
};
function clearBuffer(start, end) {
for (var i = start; i < end && i < len; i++) {
if (tests[i])
buffer[i] = settings.placeholder;
}
};
function writeBuffer() { return input.val(buffer.join('')).val(); };
function checkVal(allow) {
//try to place characters where they belong
var test = input.val();
var lastMatch = -1;
for (var i = 0, pos = 0; i < len; i++) {
if (tests[i]) {
buffer[i] = settings.placeholder;
while (pos++ < test.length) {
var c = test.charAt(pos - 1);
if (tests[i].test(c)) {
buffer[i] = c;
lastMatch = i;
break;
}
}
if (pos > test.length)
break;
} else if (buffer[i] == test[pos] && i!=partialPosition) {
pos++;
lastMatch = i;
}
}
if (!allow && lastMatch + 1 < partialPosition) {
input.val("");
clearBuffer(0, len);
} else if (allow || lastMatch + 1 >= partialPosition) {
writeBuffer();
if (!allow) input.val(input.val().substring(0, lastMatch + 1));
}
return (partialPosition ? i : firstNonMaskPos);
};
if (!input.attr("readonly"))
input
.one("unmask", function() {
input
.unbind(".mask")
.removeData("buffer")
.removeData("tests");
})
.bind("focus.mask", function() {
focusText = input.val();
var pos = checkVal();
writeBuffer();
setTimeout(function() {
if (pos == mask.length)
input.caret(0, pos);
else
input.caret(pos);
}, 0);
})
.bind("blur.mask", function() {
checkVal();
if (input.val() != focusText)
input.change();
})
.bind("keydown.mask", keydownEvent)
.bind("keypress.mask", keypressEvent)
.bind(pasteEventName, function() {
setTimeout(function() { input.caret(checkVal(true)); }, 0);
});
checkVal(); //Perform initial check for existing values
});
}
});
})(jQuery); | JavaScript |
/**
*
* Color picker
* Author: Stefan Petre www.eyecon.ro
*
* Dependencies: jQuery
*
*/
(function ($) {
var ColorPicker = function () {
var
ids = {},
inAction,
charMin = 65,
visible,
tpl = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>',
defaults = {
eventName: 'click',
onShow: function () {},
onBeforeShow: function(){},
onHide: function () {},
onChange: function () {},
onSubmit: function () {},
color: 'ff0000',
livePreview: true,
flat: false
},
fillRGBFields = function (hsb, cal) {
var rgb = HSBToRGB(hsb);
$(cal).data('colorpicker').fields
.eq(1).val(rgb.r).end()
.eq(2).val(rgb.g).end()
.eq(3).val(rgb.b).end();
},
fillHSBFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(4).val(hsb.h).end()
.eq(5).val(hsb.s).end()
.eq(6).val(hsb.b).end();
},
fillHexFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(0).val(HSBToHex(hsb)).end();
},
setSelector = function (hsb, cal) {
$(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100}));
$(cal).data('colorpicker').selectorIndic.css({
left: parseInt(150 * hsb.s/100, 10),
top: parseInt(150 * (100-hsb.b)/100, 10)
});
},
setHue = function (hsb, cal) {
$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10));
},
setCurrentColor = function (hsb, cal) {
$(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
setNewColor = function (hsb, cal) {
$(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
keyDown = function (ev) {
var pressedKey = ev.charCode || ev.keyCode || -1;
if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) {
return false;
}
var cal = $(this).parent().parent();
if (cal.data('colorpicker').livePreview === true) {
change.apply(this);
}
},
change = function (ev) {
var cal = $(this).parent().parent(), col;
if (this.parentNode.className.indexOf('_hex') > 0) {
cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value));
} else if (this.parentNode.className.indexOf('_hsb') > 0) {
cal.data('colorpicker').color = col = fixHSB({
h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10),
s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10)
});
} else {
cal.data('colorpicker').color = col = RGBToHSB(fixRGB({
r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10),
g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10)
}));
}
if (ev) {
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
}
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]);
},
blur = function (ev) {
var cal = $(this).parent().parent();
cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus')
},
focus = function () {
charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');
$(this).parent().addClass('colorpicker_focus');
},
downIncrement = function (ev) {
var field = $(this).parent().find('input').focus();
var current = {
el: $(this).parent().addClass('colorpicker_slider'),
max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
y: ev.pageY,
field: field,
val: parseInt(field.val(), 10),
preview: $(this).parent().parent().data('colorpicker').livePreview
};
$(document).bind('mouseup', current, upIncrement);
$(document).bind('mousemove', current, moveIncrement);
},
moveIncrement = function (ev) {
ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
if (ev.data.preview) {
change.apply(ev.data.field.get(0), [true]);
}
return false;
},
upIncrement = function (ev) {
change.apply(ev.data.field.get(0), [true]);
ev.data.el.removeClass('colorpicker_slider').find('input').focus();
$(document).unbind('mouseup', upIncrement);
$(document).unbind('mousemove', moveIncrement);
return false;
},
downHue = function (ev) {
var current = {
cal: $(this).parent(),
y: $(this).offset().top
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upHue);
$(document).bind('mousemove', current, moveHue);
},
moveHue = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(4)
.val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upHue = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upHue);
$(document).unbind('mousemove', moveHue);
return false;
},
downSelector = function (ev) {
var current = {
cal: $(this).parent(),
pos: $(this).offset()
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upSelector);
$(document).bind('mousemove', current, moveSelector);
},
moveSelector = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(6)
.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
.end()
.eq(5)
.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upSelector = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upSelector);
$(document).unbind('mousemove', moveSelector);
return false;
},
enterSubmit = function (ev) {
$(this).addClass('colorpicker_focus');
},
leaveSubmit = function (ev) {
$(this).removeClass('colorpicker_focus');
},
clickSubmit = function (ev) {
var cal = $(this).parent();
var col = cal.data('colorpicker').color;
cal.data('colorpicker').origColor = col;
setCurrentColor(col, cal.get(0));
cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col));
cal.hide();
},
show = function (ev) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
var pos = $(this).offset();
var viewPort = getViewport();
var top = pos.top + this.offsetHeight;
var left = pos.left;
if (top + 176 > viewPort.t + viewPort.h) {
top -= this.offsetHeight + 176;
} else {
top += 5;
}
if (left + 356 > viewPort.l + viewPort.w) {
left -= 356;
}
cal.css({left: left + 'px', top: top + 'px'});
if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) {
cal.show();
}
$(document).bind('mousedown', {cal: cal}, hide);
return false;
},
hide = function (ev) {
if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
ev.data.cal.hide();
}
$(document).unbind('mousedown', hide);
}
},
isChildOf = function(parentEl, el, container) {
if (parentEl == el) {
return true;
}
if (parentEl.contains) {
return parentEl.contains(el);
}
if ( parentEl.compareDocumentPosition ) {
return !!(parentEl.compareDocumentPosition(el) & 16);
}
var prEl = el.parentNode;
while(prEl && prEl != container) {
if (prEl == parentEl)
return true;
prEl = prEl.parentNode;
}
return false;
},
getViewport = function () {
var m = document.compatMode == 'CSS1Compat';
return {
l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
};
},
fixHSB = function (hsb) {
return {
h: Math.min(360, Math.max(0, hsb.h)),
s: Math.min(100, Math.max(0, hsb.s)),
b: Math.min(100, Math.max(0, hsb.b))
};
},
fixRGB = function (rgb) {
return {
r: Math.min(255, Math.max(0, rgb.r)),
g: Math.min(255, Math.max(0, rgb.g)),
b: Math.min(255, Math.max(0, rgb.b))
};
},
fixHex = function (hex) {
var len = 6 - hex.length;
if (len > 0) {
var o = [];
for (var i=0; i<len; i++) {
o.push('0');
}
o.push(hex);
hex = o.join('');
}
return hex;
},
HexToRGB = function (hex) {
var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)};
},
HexToHSB = function (hex) {
return RGBToHSB(HexToRGB(hex));
},
RGBToHSB = function (rgb) {
var hsb = {};
hsb.b = Math.max(Math.max(rgb.r,rgb.g),rgb.b);
hsb.s = (hsb.b <= 0) ? 0 : Math.round(100*(hsb.b - Math.min(Math.min(rgb.r,rgb.g),rgb.b))/hsb.b);
hsb.b = Math.round((hsb.b /255)*100);
if((rgb.r==rgb.g) && (rgb.g==rgb.b)) hsb.h = 0;
else if(rgb.r>=rgb.g && rgb.g>=rgb.b) hsb.h = 60*(rgb.g-rgb.b)/(rgb.r-rgb.b);
else if(rgb.g>=rgb.r && rgb.r>=rgb.b) hsb.h = 60 + 60*(rgb.g-rgb.r)/(rgb.g-rgb.b);
else if(rgb.g>=rgb.b && rgb.b>=rgb.r) hsb.h = 120 + 60*(rgb.b-rgb.r)/(rgb.g-rgb.r);
else if(rgb.b>=rgb.g && rgb.g>=rgb.r) hsb.h = 180 + 60*(rgb.b-rgb.g)/(rgb.b-rgb.r);
else if(rgb.b>=rgb.r && rgb.r>=rgb.g) hsb.h = 240 + 60*(rgb.r-rgb.g)/(rgb.b-rgb.g);
else if(rgb.r>=rgb.b && rgb.b>=rgb.g) hsb.h = 300 + 60*(rgb.r-rgb.b)/(rgb.r-rgb.g);
else hsb.h = 0;
hsb.h = Math.round(hsb.h);
return hsb;
},
HSBToRGB = function (hsb) {
var rgb = {};
var h = Math.round(hsb.h);
var s = Math.round(hsb.s*255/100);
var v = Math.round(hsb.b*255/100);
if(s == 0) {
rgb.r = rgb.g = rgb.b = v;
} else {
var t1 = v;
var t2 = (255-s)*v/255;
var t3 = (t1-t2)*(h%60)/60;
if(h==360) h = 0;
if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3}
else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3}
else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3}
else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3}
else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3}
else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3}
else {rgb.r=0; rgb.g=0; rgb.b=0}
}
return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
},
RGBToHex = function (rgb) {
var hex = [
rgb.r.toString(16),
rgb.g.toString(16),
rgb.b.toString(16)
];
$.each(hex, function (nr, val) {
if (val.length == 1) {
hex[nr] = '0' + val;
}
});
return hex.join('');
},
HSBToHex = function (hsb) {
return RGBToHex(HSBToRGB(hsb));
};
return {
init: function (options) {
options = $.extend({}, defaults, options||{});
if (typeof options.color == 'string') {
options.color = HexToHSB(options.color);
} else if (options.color.r != undefined && options.color.g != undefined && options.color.b != undefined) {
options.color = RGBToHSB(options.color);
} else if (options.color.h != undefined && options.color.s != undefined && options.color.b != undefined) {
options.color = fixHSB(options.color);
} else {
return this;
}
options.origColor = options.color;
return this.each(function () {
if (!$(this).data('colorpickerId')) {
var id = 'collorpicker_' + parseInt(Math.random() * 1000);
$(this).data('colorpickerId', id);
var cal = $(tpl).attr('id', id);
if (options.flat) {
cal.appendTo(this).show();
} else {
cal.appendTo(document.body);
}
options.fields = cal
.find('input')
.bind('keydown', keyDown)
.bind('change', change)
.bind('blur', blur)
.bind('focus', focus);
cal.find('span').bind('mousedown', downIncrement);
options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
options.selectorIndic = options.selector.find('div div');
options.hue = cal.find('div.colorpicker_hue div');
cal.find('div.colorpicker_hue').bind('mousedown', downHue);
options.newColor = cal.find('div.colorpicker_new_color');
options.currentColor = cal.find('div.colorpicker_current_color');
cal.data('colorpicker', options);
cal.find('div.colorpicker_submit')
.bind('mouseenter', enterSubmit)
.bind('mouseleave', leaveSubmit)
.bind('click', clickSubmit);
fillRGBFields(options.color, cal.get(0));
fillHSBFields(options.color, cal.get(0));
fillHexFields(options.color, cal.get(0));
setHue(options.color, cal.get(0));
setSelector(options.color, cal.get(0));
setCurrentColor(options.color, cal.get(0));
setNewColor(options.color, cal.get(0));
if (options.flat) {
cal.css({
position: 'relative',
display: 'block'
});
} else {
$(this).bind(options.eventName, show);
}
}
});
},
showPicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
show.apply(this);
}
});
},
hidePicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
$('#' + $(this).data('colorpickerId')).hide();
}
});
},
setColor: function(col) {
if (typeof col == 'string') {
col = HexToHSB(col);
} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
col = RGBToHSB(col);
} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
col = fixHSB(col);
} else {
return this;
}
return this.each(function(){
if ($(this).data('colorpickerId')) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').color = col;
cal.data('colorpicker').origColor = col;
fillRGBFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
setHue(col, cal.get(0));
setSelector(col, cal.get(0));
setCurrentColor(col, cal.get(0));
setNewColor(col, cal.get(0));
}
});
}
};
}();
$.fn.extend({
ColorPicker: ColorPicker.init,
ColorPickerHide: ColorPicker.hide,
ColorPickerShow: ColorPicker.show,
ColorPickerSetColor: ColorPicker.setColor
});
})(jQuery) | JavaScript |
/**
* Functionality specific to Twenty Thirteen.
*
* Provides helper functions to enhance the theme experience.
*/
( function( $ ) {
var body = $( 'body' ),
_window = $( window );
/**
* Adds a top margin to the footer if the sidebar widget area is higher
* than the rest of the page, to help the footer always visually clear
* the sidebar.
*/
$( function() {
if ( body.is( '.sidebar' ) ) {
var sidebar = $( '#secondary .widget-area' ),
secondary = ( 0 === sidebar.length ) ? -40 : sidebar.height(),
margin = $( '#tertiary .widget-area' ).height() - $( '#content' ).height() - secondary;
if ( margin > 0 && _window.innerWidth() > 999 ) {
$( '#colophon' ).css( 'margin-top', margin + 'px' );
}
}
} );
/**
* Enables menu toggle for small screens.
*/
( function() {
var nav = $( '#site-navigation' ), button, menu;
if ( ! nav ) {
return;
}
button = nav.find( '.menu-toggle' );
if ( ! button ) {
return;
}
// Hide button if menu is missing or empty.
menu = nav.find( '.nav-menu' );
if ( ! menu || ! menu.children().length ) {
button.hide();
return;
}
button.on( 'click.twentythirteen', function() {
nav.toggleClass( 'toggled-on' );
} );
// Better focus for hidden submenu items for accessibility.
menu.find( 'a' ).on( 'focus.twentythirteen blur.twentythirteen', function() {
$( this ).parents( '.menu-item, .page_item' ).toggleClass( 'focus' );
} );
} )();
/**
* Makes "skip to content" link work correctly in IE9 and Chrome for better
* accessibility.
*
* @link http://www.nczonline.net/blog/2013/01/15/fixing-skip-to-content-links/
*/
_window.on( 'hashchange.twentythirteen', function() {
var element = document.getElementById( location.hash.substring( 1 ) );
if ( element ) {
if ( ! /^(?:a|select|input|button|textarea)$/i.test( element.tagName ) ) {
element.tabIndex = -1;
}
element.focus();
}
} );
/**
* Arranges footer widgets vertically.
*/
if ( $.isFunction( $.fn.masonry ) ) {
var columnWidth = body.is( '.sidebar' ) ? 228 : 245;
$( '#secondary .widget-area' ).masonry( {
itemSelector: '.widget',
columnWidth: columnWidth,
gutterWidth: 20,
isRTL: body.is( '.rtl' )
} );
}
} )( jQuery ); | JavaScript |
/**
* Theme Customizer enhancements for a better user experience.
*
* Contains handlers to make Theme Customizer preview reload changes asynchronously.
* Things like site title and description changes.
*/
( function( $ ) {
// Site title and description.
wp.customize( 'blogname', function( value ) {
value.bind( function( to ) {
$( '.site-title' ).text( to );
} );
} );
wp.customize( 'blogdescription', function( value ) {
value.bind( function( to ) {
$( '.site-description' ).text( to );
} );
} );
// Header text color.
wp.customize( 'header_textcolor', function( value ) {
value.bind( function( to ) {
if ( 'blank' == to ) {
if ( 'remove-header' == _wpCustomizeSettings.values.header_image )
$( '.home-link' ).css( 'min-height', '0' );
$( '.site-title, .site-description' ).css( {
'clip': 'rect(1px, 1px, 1px, 1px)',
'position': 'absolute'
} );
} else {
$( '.home-link' ).css( 'min-height', '230px' );
$( '.site-title, .site-description' ).css( {
'clip': 'auto',
'color': to,
'position': 'relative'
} );
}
} );
} );
} )( jQuery );
| JavaScript |
jQuery(window).load(function() {
/* Navigation */
jQuery('#submenu ul.sfmenu').superfish({
delay: 500, // 0.1 second delay on mouseout
animation: { opacity:'show',height:'show'}, // fade-in and slide-down animation
dropShadows: true // disable drop shadows
});
/* Hover block */
jQuery('.portfolio-box').hover(function(){
jQuery(this).find('div').animate({opacity:'1'},{queue:false,duration:500});
}, function(){
jQuery(this).find('div').animate({opacity:'0'},{queue:false,duration:500});
});
/* equal column */
var biggestHeight = 0;
//check each of them
jQuery('.equal_height').each(function(){
//if the height of the current element is
//bigger then the current biggestHeight value
if(jQuery(this).height() > biggestHeight){
//update the biggestHeight with the
//height of the current elements
biggestHeight = jQuery(this).height();
}
});
//when checking for biggestHeight is done set that
//height to all the elements
jQuery('.equal_height').height(biggestHeight);
}); | JavaScript |
jQuery(document).ready(function () {
// Установка реального цвета с учётом прозрачности
function setIColor(fake_i, color, opacity) {
var id = fake_i.attr("id");
var name = id.substring(5);
jQuery('#' + name).val(color);
jQuery('#' + name + '_opacity').val(opacity);
}
function setColorPicker() {
jQuery("input.color-picker").css({"height": "auto", "padding-top": "7px", "padding-right": "7px", "padding-bottom": "7px"});
jQuery("input.color-picker").minicolors({
'control': "wheel",
'defaultValue': "#FFFFFF",
'changeDelay': 25,
'inline': false,
'position': "bottom left",
'letterCase': "lowercase",
'theme': "bootstrap",
'opacity': true,
'change': function(hex, opacity) {
var color = hex;
if (opacity != 1)
color = jQuery(this).minicolors('rgbaString');
setIColor(jQuery(this), color, opacity);
},
'hide': function() {
var opacity = jQuery(this).minicolors('opacity');
var color = jQuery(this).val();
if (opacity != 1)
color = jQuery(this).minicolors('rgbaString');
setIColor(jQuery(this), color, opacity);
}
});
jQuery(".minicolors").css({"width": "100%"});
jQuery(".minicolors-swatch").css({"top": "4px"});
}
// + Выставляем opacity
// + Запоняем скрытые поля из знач по умолчанию
jQuery("input[type=hidden]").each(function() {
var id = jQuery(this).attr('id');
// Запоняем скрытые поля из знач по умолчанию
if (typeof(id) != 'undefined' && id.substring(10) != 'opacity' && jQuery("#fake_" + id.substring(0, 9)).length > 0) {
if (jQuery(this).val() == '')
jQuery(this).val( jQuery("#fake_" + id.substring(0, 9)).val() );
}
if (typeof(id) == 'undefined' || id.substring(10) != 'opacity' || jQuery("#fake_" + id.substring(0, 9)).length <= 0)
return;
jQuery("#fake_" + id.substring(0, 9)).attr('data-opacity', jQuery(this).val());
});
setColorPicker();
}); | JavaScript |
jQuery(document).ready(function($){
var optionsframework_upload;
var optionsframework_selector;
function optionsframework_add_file(event, selector) {
var upload = $(".uploaded-file"), frame;
var $el = $(this);
optionsframework_selector = selector;
event.preventDefault();
// If the media frame already exists, reopen it.
if ( optionsframework_upload ) {
optionsframework_upload.open();
} else {
// Create the media frame.
optionsframework_upload = wp.media.frames.optionsframework_upload = wp.media({
// Set the title of the modal.
title: $el.data('choose'),
// Customize the submit button.
button: {
// Set the text of the button.
text: $el.data('update'),
// Tell the button not to close the modal, since we're
// going to refresh the page when the image is selected.
close: false
}
});
// When an image is selected, run a callback.
optionsframework_upload.on( 'select', function() {
// Grab the selected attachment.
var attachment = optionsframework_upload.state().get('selection').first();
optionsframework_upload.close();
optionsframework_selector.find('.upload').val(attachment.attributes.url);
if ( attachment.attributes.type == 'image' ) {
optionsframework_selector.find('.screenshot').empty().hide().append('<img src="' + attachment.attributes.url + '"><a class="remove-image">Remove</a>').slideDown('fast');
}
optionsframework_selector.find('.upload-button').unbind().addClass('remove-file').removeClass('upload-button').val(optionsframework_l10n.remove);
optionsframework_selector.find('.of-background-properties').slideDown();
optionsframework_selector.find('.remove-image, .remove-file').on('click', function() {
optionsframework_remove_file( $(this).parents('.section') );
});
});
}
// Finally, open the modal.
optionsframework_upload.open();
}
function optionsframework_remove_file(selector) {
selector.find('.remove-image').hide();
selector.find('.upload').val('');
selector.find('.of-background-properties').hide();
selector.find('.screenshot').slideUp();
selector.find('.remove-file').unbind().addClass('upload-button').removeClass('remove-file').val(optionsframework_l10n.upload);
// We don't display the upload button if .upload-notice is present
// This means the user doesn't have the WordPress 3.5 Media Library Support
if ( $('.section-upload .upload-notice').length > 0 ) {
$('.upload-button').remove();
}
selector.find('.upload-button').on('click', function(event) {
optionsframework_add_file(event, $(this).parents('.section'));
});
}
$('.remove-image, .remove-file').on('click', function() {
optionsframework_remove_file( $(this).parents('.section') );
});
$('.upload-button').click( function( event ) {
optionsframework_add_file(event, $(this).parents('.section'));
});
}); | JavaScript |
/**
* Custom scripts needed for the colorpicker, image button selectors,
* and navigation tabs.
*/
jQuery(document).ready(function($) {
// Loads the color pickers
$('.of-color').wpColorPicker();
// Image Options
$('.of-radio-img-img').click(function(){
$(this).parent().parent().find('.of-radio-img-img').removeClass('of-radio-img-selected');
$(this).addClass('of-radio-img-selected');
});
$('.of-radio-img-label').hide();
$('.of-radio-img-img').show();
$('.of-radio-img-radio').hide();
// Loads tabbed sections if they exist
if ( $('.nav-tab-wrapper').length > 0 ) {
options_framework_tabs();
}
function options_framework_tabs() {
// Hides all the .group sections to start
$('.group').hide();
// Find if a selected tab is saved in localStorage
var active_tab = '';
if ( typeof(localStorage) != 'undefined' ) {
active_tab = localStorage.getItem("active_tab");
}
// If active tab is saved and exists, load it's .group
if (active_tab != '' && $(active_tab).length ) {
$(active_tab).fadeIn();
$(active_tab + '-tab').addClass('nav-tab-active');
} else {
$('.group:first').fadeIn();
$('.nav-tab-wrapper a:first').addClass('nav-tab-active');
}
// Bind tabs clicks
$('.nav-tab-wrapper a').click(function(evt) {
evt.preventDefault();
// Remove active class from all tabs
$('.nav-tab-wrapper a').removeClass('nav-tab-active');
$(this).addClass('nav-tab-active').blur();
var group = $(this).attr('href');
if (typeof(localStorage) != 'undefined' ) {
localStorage.setItem("active_tab", $(this).attr('href') );
}
$('.group').hide();
$(group).fadeIn();
// Editor height sometimes needs adjustment when unhidden
$('.wp-editor-wrap').each(function() {
var editor_iframe = $(this).find('iframe');
if ( editor_iframe.height() < 30 ) {
editor_iframe.css({'height':'auto'});
}
});
});
}
}); | JavaScript |
$(function() {
$("<div id='tweet'>adsa</div>").appendTo("#tweeter").lastTwitterMessage('chriscoyier');
}); | JavaScript |
/**
* Theme functions file
*
* Contains handlers for navigation, accessibility, header sizing
* footer widgets and Featured Content slider
*
*/
( function( $ ) {
var body = $( 'body' ),
_window = $( window );
// Enable menu toggle for small screens.
( function() {
var nav = $( '#primary-navigation' ), button, menu;
if ( ! nav ) {
return;
}
button = nav.find( '.menu-toggle' );
if ( ! button ) {
return;
}
// Hide button if menu is missing or empty.
menu = nav.find( '.nav-menu' );
if ( ! menu || ! menu.children().length ) {
button.hide();
return;
}
$( '.menu-toggle' ).on( 'click.twentyfourteen', function() {
nav.toggleClass( 'toggled-on' );
} );
} )();
/*
* Makes "skip to content" link work correctly in IE9 and Chrome for better
* accessibility.
*
* @link http://www.nczonline.net/blog/2013/01/15/fixing-skip-to-content-links/
*/
_window.on( 'hashchange.twentyfourteen', function() {
var element = document.getElementById( location.hash.substring( 1 ) );
if ( element ) {
if ( ! /^(?:a|select|input|button|textarea)$/i.test( element.tagName ) ) {
element.tabIndex = -1;
}
element.focus();
// Repositions the window on jump-to-anchor to account for header height.
window.scrollBy( 0, -80 );
}
} );
$( function() {
// Search toggle.
$( '.search-toggle' ).on( 'click.twentyfourteen', function( event ) {
var that = $( this ),
wrapper = $( '.search-box-wrapper' );
that.toggleClass( 'active' );
wrapper.toggleClass( 'hide' );
if ( that.is( '.active' ) || $( '.search-toggle .screen-reader-text' )[0] === event.target ) {
wrapper.find( '.search-field' ).focus();
}
} );
/*
* Fixed header for large screen.
* If the header becomes more than 48px tall, unfix the header.
*
* The callback on the scroll event is only added if there is a header
* image and we are not on mobile.
*/
if ( _window.width() > 781 ) {
var mastheadHeight = $( '#masthead' ).height(),
toolbarOffset, mastheadOffset;
if ( mastheadHeight > 48 ) {
body.removeClass( 'masthead-fixed' );
}
if ( body.is( '.header-image' ) ) {
toolbarOffset = body.is( '.admin-bar' ) ? $( '#wpadminbar' ).height() : 0;
mastheadOffset = $( '#masthead' ).offset().top - toolbarOffset;
_window.on( 'scroll.twentyfourteen', function() {
if ( ( window.scrollY > mastheadOffset ) && ( mastheadHeight < 49 ) ) {
body.addClass( 'masthead-fixed' );
} else {
body.removeClass( 'masthead-fixed' );
}
} );
}
}
// Focus styles for menus.
$( '.primary-navigation, .secondary-navigation' ).find( 'a' ).on( 'focus.twentyfourteen blur.twentyfourteen', function() {
$( this ).parents().toggleClass( 'focus' );
} );
} );
_window.load( function() {
// Arrange footer widgets vertically.
if ( $.isFunction( $.fn.masonry ) ) {
$( '#footer-sidebar' ).masonry( {
itemSelector: '.widget',
columnWidth: function( containerWidth ) {
return containerWidth / 4;
},
gutterWidth: 0,
isResizable: true,
isRTL: $( 'body' ).is( '.rtl' )
} );
}
// Initialize Featured Content slider.
if ( body.is( '.slider' ) ) {
$( '.featured-content' ).featuredslider( {
selector: '.featured-content-inner > article',
controlsContainer: '.featured-content'
} );
}
} );
} )( jQuery );
| JavaScript |
/*
* Twenty Fourteen Featured Content Slider
*
* Adapted from FlexSlider v2.2.0, copyright 2012 WooThemes
* @link http://www.woothemes.com/flexslider/
*/
/* global DocumentTouch:true,setImmediate:true,featuredSliderDefaults:true,MSGesture:true */
( function( $ ) {
// FeaturedSlider: object instance.
$.featuredslider = function( el, options ) {
var slider = $( el ),
msGesture = window.navigator && window.navigator.msPointerEnabled && window.MSGesture,
touch = ( ( 'ontouchstart' in window ) || msGesture || window.DocumentTouch && document instanceof DocumentTouch ), // MSFT specific.
eventType = 'click touchend MSPointerUp',
watchedEvent = '',
watchedEventClearTimer,
methods = {},
namespace;
// Make variables public.
slider.vars = $.extend( {}, $.featuredslider.defaults, options );
namespace = slider.vars.namespace,
// Store a reference to the slider object.
$.data( el, 'featuredslider', slider );
// Private slider methods.
methods = {
init: function() {
slider.animating = false;
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;
slider.prop = 'marginLeft';
slider.isRtl = $( 'body' ).hasClass( 'rtl' );
slider.args = {};
// TOUCH
slider.transitions = ( function() {
var obj = document.createElement( 'div' ),
props = ['perspectiveProperty', 'WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective'],
i;
for ( 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 );
}
slider.doMath();
// INIT
slider.setup( 'init' );
// CONTROLNAV
methods.controlNav.setup();
// DIRECTIONNAV
methods.directionNav.setup();
// KEYBOARD
if ( $( slider.containerSelector ).length === 1 ) {
$( document ).bind( 'keyup', function( event ) {
var keycode = event.keyCode,
target = false;
if ( ! slider.animating && ( keycode === 39 || keycode === 37 ) ) {
if ( keycode === 39 ) {
target = slider.getTarget( 'next' );
} else if ( keycode === 37 ) {
target = slider.getTarget( 'prev' );
}
slider.featureAnimate( target );
}
} );
}
// TOUCH
if ( touch ) {
methods.touch();
}
$( window ).bind( 'resize orientationchange focus', methods.resize );
slider.find( 'img' ).attr( 'draggable', 'false' );
},
controlNav: {
setup: function() {
methods.controlNav.setupPaging();
},
setupPaging: function() {
var type = 'control-paging',
j = 1,
item,
slide,
i;
slider.controlNavScaffold = $( '<ol class="' + namespace + 'control-nav ' + namespace + type + '"></ol>' );
if ( slider.pagingCount > 1 ) {
for ( i = 0; i < slider.pagingCount; i++ ) {
slide = slider.slides.eq( i );
item = '<a>' + j + '</a>';
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.featureAnimate( target );
}
}
// Set up flags to prevent event duplication.
if ( watchedEvent === '' ) {
watchedEvent = event.type;
}
methods.setToClearWatchedEvent();
} );
},
set: function() {
var selector = '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.featureAnimate( target );
}
// Set up 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 {
slider.directionNav.removeClass( disabledClass ).removeAttr( 'tabindex' );
}
}
},
touch: function() {
var startX,
startY,
offset,
cwidth,
dx,
startT,
scrolling = false,
localX = 0,
localY = 0,
accDx = 0;
if ( ! msGesture ) {
el.addEventListener( 'touchstart', onTouchStart, false );
} else {
el.style.msTouchAction = 'none';
el._gesture = new MSGesture(); // MSFT specific.
el._gesture.target = el;
el.addEventListener( 'MSPointerDown', onMSPointerDown, false );
el._slider = slider;
el.addEventListener( 'MSGestureChange', onMSGestureChange, false );
el.addEventListener( 'MSGestureEnd', onMSGestureEnd, false );
}
function onTouchStart( e ) {
if ( slider.animating ) {
e.preventDefault();
} else if ( ( window.navigator.msPointerEnabled ) || e.touches.length === 1 ) {
cwidth = slider.w;
startT = Number( new Date() );
// Local vars for X and Y points.
localX = e.touches[0].pageX;
localY = e.touches[0].pageY;
offset = ( slider.currentSlide + slider.cloneOffset ) * cwidth;
if ( slider.animatingTo === slider.last && slider.direction !== 'next' ) {
offset = 0;
}
startX = localX;
startY = 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 = startX - localX;
scrolling = Math.abs( dx ) < Math.abs( localY - startY );
if ( ! scrolling ) {
e.preventDefault();
if ( slider.transitions ) {
slider.setProps( offset + dx, 'setTouch' );
}
}
}
function onTouchEnd() {
// Finish the touch by undoing the touch session.
el.removeEventListener( 'touchmove', onTouchMove, false );
if ( slider.animatingTo === slider.currentSlide && ! scrolling && dx !== null ) {
var updateDx = dx,
target = ( updateDx > 0 ) ? slider.getTarget( 'next' ) : slider.getTarget( 'prev' );
slider.featureAnimate( target );
}
el.removeEventListener( 'touchend', onTouchEnd, false );
startX = null;
startY = null;
dx = null;
offset = null;
}
function onMSPointerDown( e ) {
e.stopPropagation();
if ( slider.animating ) {
e.preventDefault();
} else {
el._gesture.addPointer( e.pointerId );
accDx = 0;
cwidth = slider.w;
startT = Number( new Date() );
offset = ( slider.currentSlide + slider.cloneOffset ) * cwidth;
if ( slider.animatingTo === slider.last && slider.direction !== 'next' ) {
offset = 0;
}
}
}
function onMSGestureChange( e ) {
e.stopPropagation();
var slider = e.target._slider,
transX,
transY;
if ( ! slider ) {
return;
}
transX = -e.translationX,
transY = -e.translationY;
// Accumulate translations.
accDx = accDx + transX;
dx = accDx;
scrolling = Math.abs( accDx ) < Math.abs( -transY );
if ( e.detail === e.MSGESTURE_FLAG_INERTIA ) {
setImmediate( function () { // MSFT specific.
el._gesture.stop();
} );
return;
}
if ( ! scrolling || Number( new Date() ) - startT > 500 ) {
e.preventDefault();
if ( slider.transitions ) {
slider.setProps( offset + dx, 'setTouch' );
}
}
}
function onMSGestureEnd( e ) {
e.stopPropagation();
var slider = e.target._slider,
updateDx,
target;
if ( ! slider ) {
return;
}
if ( slider.animatingTo === slider.currentSlide && ! scrolling && dx !== null ) {
updateDx = dx,
target = ( updateDx > 0 ) ? slider.getTarget( 'next' ) : slider.getTarget( 'prev' );
slider.featureAnimate( target );
}
startX = null;
startY = null;
dx = null;
offset = null;
accDx = 0;
}
},
resize: function() {
if ( ! slider.animating && slider.is( ':visible' ) ) {
slider.doMath();
// SMOOTH HEIGHT
methods.smoothHeight();
slider.newSlides.width( slider.computedW );
slider.setProps( slider.computedW, 'setTotal' );
}
},
smoothHeight: function( dur ) {
var $obj = slider.viewport;
( dur ) ? $obj.animate( { 'height': slider.slides.eq( slider.animatingTo ).height() }, dur ) : $obj.height( slider.slides.eq( slider.animatingTo ).height() );
},
setToClearWatchedEvent: function() {
clearTimeout( watchedEventClearTimer );
watchedEventClearTimer = setTimeout( function() {
watchedEvent = '';
}, 3000 );
}
};
// Public methods.
slider.featureAnimate = function( target ) {
if ( target !== slider.currentSlide ) {
slider.direction = ( target > slider.currentSlide ) ? 'next' : 'prev';
}
if ( ! slider.animating && slider.is( ':visible' ) ) {
slider.animating = true;
slider.animatingTo = target;
// CONTROLNAV
methods.controlNav.active();
slider.slides.removeClass( namespace + 'active-slide' ).eq( target ).addClass( namespace + 'active-slide' );
slider.atEnd = target === 0 || target === slider.last;
// DIRECTIONNAV
methods.directionNav.update();
var dimension = slider.computedW,
slideString;
if ( slider.currentSlide === 0 && target === slider.count - 1 && slider.direction !== 'next' ) {
slideString = 0;
} else if ( slider.currentSlide === slider.last && target === 0 && slider.direction !== 'prev' ) {
slideString = ( slider.count + 1 ) * dimension;
} else {
slideString = ( target + slider.cloneOffset ) * dimension;
}
slider.setProps( slideString, '', slider.vars.animationSpeed );
if ( slider.transitions ) {
if ( ! 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, 'swing', function() {
slider.wrapup( dimension );
} );
}
// SMOOTH HEIGHT
methods.smoothHeight( slider.vars.animationSpeed );
}
};
slider.wrapup = function( dimension ) {
if ( slider.currentSlide === 0 && slider.animatingTo === slider.last ) {
slider.setProps( dimension, 'jumpEnd' );
} else if ( slider.currentSlide === slider.last && slider.animatingTo === 0 ) {
slider.setProps( dimension, 'jumpStart' );
}
slider.animating = false;
slider.currentSlide = slider.animatingTo;
};
slider.getTarget = function( dir ) {
slider.direction = dir;
// Swap for RTL.
if ( slider.isRtl ) {
dir = 'next' === dir ? 'prev' : 'next';
}
if ( dir === 'next' ) {
return ( slider.currentSlide === slider.last ) ? 0 : slider.currentSlide + 1;
} else {
return ( slider.currentSlide === 0 ) ? slider.last : slider.currentSlide - 1;
}
};
slider.setProps = function( pos, special, dur ) {
var target = ( function() {
var posCalc = ( function() {
switch ( special ) {
case 'setTotal': return ( slider.currentSlide + slider.cloneOffset ) * pos;
case 'setTouch': return pos;
case 'jumpEnd': return slider.count * pos;
case 'jumpStart': return pos;
default: return pos;
}
}() );
return ( posCalc * -1 ) + 'px';
}() );
if ( slider.transitions ) {
target = '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 ) {
var sliderOffset;
if ( type === 'init' ) {
slider.viewport = $( '<div class="' + namespace + 'viewport"></div>' ).css( { 'overflow': 'hidden', 'position': 'relative' } ).appendTo( slider ).append( slider.container );
slider.cloneCount = 0;
slider.cloneOffset = 0;
}
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 = slider.currentSlide + slider.cloneOffset;
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
methods.smoothHeight();
}, ( type === 'init' ) ? 100 : 0 );
slider.slides.removeClass( namespace + 'active-slide' ).eq( slider.currentSlide ).addClass( namespace + 'active-slide' );
};
slider.doMath = function() {
var slide = slider.slides.first();
slider.w = ( slider.viewport===undefined ) ? slider.width() : slider.viewport.width();
slider.h = slide.height();
slider.boxPadding = slide.outerWidth() - slide.width();
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 ( pos < slider.currentSlide ) {
slider.currentSlide += 1;
} else if ( pos <= slider.currentSlide && pos !== 0 ) {
slider.currentSlide -= 1;
}
slider.animatingTo = slider.currentSlide;
// Update controlNav.
if ( action === 'add' || slider.pagingCount > slider.controlNav.length ) {
methods.controlNav.update( 'add' );
} else if ( action === 'remove' || slider.pagingCount < slider.controlNav.length ) {
if ( slider.currentSlide > slider.last ) {
slider.currentSlide -= 1;
slider.animatingTo -= 1;
}
methods.controlNav.update( 'remove', slider.last );
}
// Update directionNav.
methods.directionNav.update();
};
// FeaturedSlider: initialize.
methods.init();
};
// Default settings.
$.featuredslider.defaults = {
namespace: 'slider-', // String: prefix string attached to the class of every element generated by the plugin.
selector: '.slides > li', // String: selector, must match a simple pattern.
animationSpeed: 600, // Integer: Set the speed of animations, in milliseconds.
controlsContainer: '', // jQuery Object/Selector: container navigation to append elements.
// Text labels.
prevText: featuredSliderDefaults.prevText, // String: Set the text for the "previous" directionNav item.
nextText: featuredSliderDefaults.nextText // String: Set the text for the "next" directionNav item.
};
// FeaturedSlider: plugin function.
$.fn.featuredslider = 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 || $slides.length === 0 ) {
$slides.fadeIn( 400 );
} else if ( $this.data( 'featuredslider' ) === undefined ) {
new $.featuredslider( this, options );
}
} );
}
};
} )( jQuery );
| JavaScript |
/**
* Twenty Fourteen Theme Customizer enhancements for a better user experience.
*
* Contains handlers to make Theme Customizer preview reload changes asynchronously.
*/
( function( $ ) {
// Site title and description.
wp.customize( 'blogname', function( value ) {
value.bind( function( to ) {
$( '.site-title a' ).text( to );
} );
} );
wp.customize( 'blogdescription', function( value ) {
value.bind( function( to ) {
$( '.site-description' ).text( to );
} );
} );
// Header text color.
wp.customize( 'header_textcolor', function( value ) {
value.bind( function( to ) {
if ( 'blank' === to ) {
$( '.site-title, .site-description' ).css( {
'clip': 'rect(1px, 1px, 1px, 1px)',
'position': 'absolute'
} );
} else {
$( '.site-title, .site-description' ).css( {
'clip': 'auto',
'position': 'static'
} );
$( '.site-title a' ).css( {
'color': to
} );
}
} );
} );
} )( jQuery ); | JavaScript |
/**
* Twenty Fourteen keyboard support for image navigation.
*/
( function( $ ) {
$( document ).on( 'keydown.twentyfourteen', function( e ) {
var url = false;
// Left arrow key code.
if ( e.which === 37 ) {
url = $( '.previous-image a' ).attr( 'href' );
// Right arrow key code.
} else if ( e.which === 39 ) {
url = $( '.entry-attachment a' ).attr( 'href' );
}
if ( url && ( !$( 'textarea, input' ).is( ':focus' ) ) ) {
window.location = url;
}
} );
} )( jQuery ); | JavaScript |
/**
* Twenty Fourteen Featured Content admin behavior: add a tag suggestion
* when changing the tag.
*/
/* global ajaxurl:true */
jQuery( document ).ready( function( $ ) {
$( '#customize-control-featured-content-tag-name input' ).suggest( ajaxurl + '?action=ajax-tag-search&tax=post_tag', { delay: 500, minchars: 2 } );
});
| JavaScript |
$(
function($){
$.fn.lastTwitterMessage = function(username){
var $base = this;
if(!username || username == "") return this;
var url = "http://twitter.com/statuses/user_timeline.json?callback=?";
$.getJSON(url,{count:10,screen_name:username
},
function(data){
if(data && data.length >= 1){
try{
var item = null;
for(var i = 0; i < data.length; i++){
if(/^@/i.test(data[i].text)) continue;
item = data[i]; break;
}
if(!item) return;
var $tweet = $("<p>aa</p> ").text(item.text);
$tweet.html(
$tweet.html().replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,
'<a href="$1">$1</a>')
.replace(/(^|\s)#(\w+)/g,'$1<a href="http://search.twitter.com/search?q=%23$2">#$2</a>')
.replace(/(^|\s)@(\w+)/g,'$1<a href="http://twitter.com/$2">@$2</a>')
)
$tweet.append(" <a href='http://twitter.com/" + username + "'>(∞)</a> ").wrapInner("<span>");
$base.empty().append($tweet).show();
} catch(e) { };
};
});
return this; // Don't break the chain
};
}); | JavaScript |
$(function() {
$("<div id='tweet'></div>").hide().appendTo("#footer")
.lastTwitterMessage('chriscoyier');
}); | JavaScript |
var class_records =
[
[ "act", "class_records.html#afe173842b94eacf97c9ee76a50894c73", null ],
[ "funciona", "class_records.html#ab25941bb7c2285becc24c7b9cad1ccce", null ]
]; | JavaScript |
var class_play =
[
[ "act", "class_play.html#a8bb5932cbd991a03a48b2822488bfd00", null ],
[ "funciona", "class_play.html#a4eabbc979faf6e9179282941f5d62184", null ]
]; | JavaScript |
var searchData=
[
['help',['Help',['../class_help.html',1,'']]]
];
| JavaScript |
var searchData=
[
['patricio',['Patricio',['../class_patricio.html',1,'Patricio'],['../class_patricio.html#a5d59e42f276cc76374dea8bcdd62c9af',1,'Patricio.Patricio()']]],
['patricio_2ejava',['Patricio.java',['../_patricio_8java.html',1,'']]],
['piedrita',['Piedrita',['../class_piedrita.html',1,'']]],
['piedrita_2ejava',['Piedrita.java',['../_piedrita_8java.html',1,'']]],
['piedritamecayoencima',['piedritaMeCayoEncima',['../class_maderota.html#a460688b513165fd88c7a880aa285d33c',1,'Maderota']]],
['play',['Play',['../class_play.html',1,'']]],
['play_2ejava',['Play.java',['../_play_8java.html',1,'']]],
['ponnivel',['ponNivel',['../class_fondo.html#a8aee4e540c7671ab2162bce02094e0b2',1,'Fondo']]],
['portador',['Portador',['../class_portador.html',1,'']]],
['portador_2ejava',['Portador.java',['../_portador_8java.html',1,'']]],
['prepare1',['prepare1',['../class_fondo.html#a7912ecda505a9fb4faceae7367bc12bf',1,'Fondo']]],
['puntajellegocero',['puntajeLlegoCero',['../class_score2.html#a08a210b8c46bde0a2c344e886d9cd67e',1,'Score2']]]
];
| JavaScript |
var searchData=
[
['letrero',['Letrero',['../class_letrero.html',1,'Letrero'],['../class_letrero.html#a6fb7d136cc91a443972e9071bb604ac5',1,'Letrero.Letrero()']]],
['letrero_2ejava',['Letrero.java',['../_letrero_8java.html',1,'']]]
];
| JavaScript |
var searchData=
[
['help',['Help',['../class_help.html',1,'']]],
['help_2ejava',['Help.java',['../_help_8java.html',1,'']]]
];
| JavaScript |
var searchData=
[
['globito_2ejava',['Globito.java',['../_globito_8java.html',1,'']]]
];
| JavaScript |
var searchData=
[
['maderacae',['maderaCae',['../class_maderota.html#a7e87571ca7fbd98acaa8bb262d1820e0',1,'Maderota']]],
['mark',['mark',['../class_simple_timer.html#abe5debfac2280fc4f432a496393ddfe8',1,'SimpleTimer']]],
['meencontreunacaja',['meEncontreUnaCaja',['../class_maderota.html#a48e7fa54c93dc02c1e1518ce734bc646',1,'Maderota']]],
['meencontreungloboloponcho',['meEncontreUnGloboLoPoncho',['../class_globito.html#a5477a2c09fbbeb77da5c7178d6cfc051',1,'Globito']]],
['metocounraton',['meTocoUnRaton',['../class_cajas.html#aca41fdb754ba69a3b57fec5cc53f110b',1,'Cajas.meTocoUnRaton()'],['../class_portador.html#a91fca9c9d44b7313a09273c8062584c4',1,'Portador.meTocoUnRaton()']]],
['milliselapsed',['millisElapsed',['../class_simple_timer.html#abe6ae784edd29f6ab2e29da7b7ea0b1b',1,'SimpleTimer']]],
['muestraletrero',['muestraLetrero',['../class_letrero.html#ac3a506f2181a857a512dc4c59b1c4777',1,'Letrero']]],
['muestrapuntaje',['muestraPuntaje',['../class_score2.html#aad1d2accb6f42a7bbb0de01c0c13078b',1,'Score2']]],
['mueve',['mueve',['../class_globito.html#a8d7e41001ec04be905233ed89e08c5dd',1,'Globito.mueve()'],['../class_objeto_sube.html#a7de738f515da8d3a587cd5e499aa35d0',1,'ObjetoSube.mueve()'],['../class_patricio.html#a6f27deb467412bc033067767d18b06fa',1,'Patricio.mueve()']]],
['muevex',['mueveX',['../class_obstaculo.html#a694b3e6131e32db73eadf807f3dc9519',1,'Obstaculo']]]
];
| JavaScript |
var searchData=
[
['patricio_2ejava',['Patricio.java',['../_patricio_8java.html',1,'']]],
['piedrita_2ejava',['Piedrita.java',['../_piedrita_8java.html',1,'']]],
['play_2ejava',['Play.java',['../_play_8java.html',1,'']]],
['portador_2ejava',['Portador.java',['../_portador_8java.html',1,'']]]
];
| JavaScript |
var searchData=
[
['patricio',['Patricio',['../class_patricio.html#a5d59e42f276cc76374dea8bcdd62c9af',1,'Patricio']]],
['piedritamecayoencima',['piedritaMeCayoEncima',['../class_maderota.html#a460688b513165fd88c7a880aa285d33c',1,'Maderota']]],
['ponnivel',['ponNivel',['../class_fondo.html#a8aee4e540c7671ab2162bce02094e0b2',1,'Fondo']]],
['prepare1',['prepare1',['../class_fondo.html#a7912ecda505a9fb4faceae7367bc12bf',1,'Fondo']]],
['puntajellegocero',['puntajeLlegoCero',['../class_score2.html#a08a210b8c46bde0a2c344e886d9cd67e',1,'Score2']]]
];
| JavaScript |
var searchData=
[
['globito',['Globito',['../class_globito.html',1,'']]]
];
| JavaScript |
var searchData=
[
['next',['Next',['../class_next.html',1,'']]],
['next_2ejava',['Next.java',['../_next_8java.html',1,'']]],
['noseencuetraglobo',['noSeEncuetraGlobo',['../class_patricio.html#aa82101df7af4858fb5f5f1b1bcac342d',1,'Patricio']]]
];
| JavaScript |
var searchData=
[
['next',['Next',['../class_next.html',1,'']]]
];
| JavaScript |
var searchData=
[
['recibeglobo',['recibeGlobo',['../class_patricio.html#ad25fd9059632307ae3f3c66948ec184f',1,'Patricio']]],
['recorduser',['RecordUser',['../class_record_user.html#ab13f637d4d8e0408ddc347c9603bb8a3',1,'RecordUser']]],
['regresamenu',['regresaMenu',['../class_fondo.html#a6cea3a5b0499050b257bd832718c5b88',1,'Fondo']]],
['reinicianivel',['reiniciaNivel',['../class_fondo.html#a1a9ef9436094fe86e9caa7022ce8b723',1,'Fondo']]],
['reiniciaposicion',['reiniciaPosicion',['../class_globito.html#a548c499f8850c11aa849e5fa147b952a',1,'Globito']]],
['remove',['remove',['../class_fondo.html#a91241a6342021f1364c2f99cc510c564',1,'Fondo']]],
['rotamadera',['rotaMadera',['../class_maderota.html#a96b99a015ea033561ff1d7dd91b7c7f9',1,'Maderota']]],
['rotamaderainclinada',['rotaMaderaInclinada',['../class_maderota.html#a6777dfe4794195c6d0e1f51a74c29004',1,'Maderota']]],
['rotamueveobstaculos',['rotaMueveObstaculos',['../class_maderota.html#a9f8d79b99b2abee616f15790612e8de7',1,'Maderota']]],
['rotamueveobstaculosinclinados',['rotaMueveObstaculosInclinados',['../class_maderota.html#a954d72f2eec05f526f3490f189959bc7',1,'Maderota']]]
];
| JavaScript |
var searchData=
[
['baja',['baja',['../class_obstaculo.html#a8cb2aeaf3c3ce2920e973c1560ec7648',1,'Obstaculo']]]
];
| JavaScript |
var searchData=
[
['back',['Back',['../class_back.html',1,'']]],
['button',['Button',['../class_button.html',1,'']]]
];
| JavaScript |
var searchData=
[
['score2_2ejava',['Score2.java',['../_score2_8java.html',1,'']]],
['simpletimer_2ejava',['SimpleTimer.java',['../_simple_timer_8java.html',1,'']]]
];
| JavaScript |
var searchData=
[
['objetosube_2ejava',['ObjetoSube.java',['../_objeto_sube_8java.html',1,'']]],
['obstaculo_2ejava',['Obstaculo.java',['../_obstaculo_8java.html',1,'']]]
];
| JavaScript |
var searchData=
[
['next_2ejava',['Next.java',['../_next_8java.html',1,'']]]
];
| JavaScript |
var searchData=
[
['gamerecords',['GameRecords',['../class_fondo.html#ac40c7c0e021e132c08c90d72b29d9846',1,'Fondo']]],
['getlives',['getLives',['../class_fondo.html#a6090581ed6699a2c087ddc44af07d366',1,'Fondo']]],
['getscore',['getScore',['../class_fondo.html#a3d44d436ac5c4d29b77021437ee76fb0',1,'Fondo']]],
['globito',['Globito',['../class_globito.html',1,'Globito'],['../class_globito.html#a3123d3f7082be25ebc81b508b9013cf9',1,'Globito.Globito()']]],
['globito_2ejava',['Globito.java',['../_globito_8java.html',1,'']]]
];
| JavaScript |
var searchData=
[
['letrero_2ejava',['Letrero.java',['../_letrero_8java.html',1,'']]]
];
| JavaScript |
var searchData=
[
['cactus',['Cactus',['../class_cactus.html',1,'']]],
['cactus_2ejava',['Cactus.java',['../_cactus_8java.html',1,'']]],
['cactusder',['Cactusder',['../class_cactusder.html',1,'']]],
['cactusder_2ejava',['Cactusder.java',['../_cactusder_8java.html',1,'']]],
['cactusizq',['Cactusizq',['../class_cactusizq.html',1,'']]],
['cactusizq_2ejava',['Cactusizq.java',['../_cactusizq_8java.html',1,'']]],
['caeobjeto',['caeObjeto',['../class_obstaculo.html#a20ffcfc83d21e3ee95578e105fab13de',1,'Obstaculo']]],
['caepatricio',['caePatricio',['../class_patricio.html#a1f4fd2f258d7382d1a83ea93980c1b1e',1,'Patricio']]],
['caja1',['Caja1',['../class_caja1.html',1,'']]],
['caja1_2ejava',['Caja1.java',['../_caja1_8java.html',1,'']]],
['caja2',['Caja2',['../class_caja2.html',1,'']]],
['caja2_2ejava',['Caja2.java',['../_caja2_8java.html',1,'']]],
['cajas',['Cajas',['../class_cajas.html',1,'']]],
['cajas_2ejava',['Cajas.java',['../_cajas_8java.html',1,'']]],
['cambiaimagenglobo',['cambiaImagenGlobo',['../class_globito.html#aba2590583e7128a5b2daa7feefb154be',1,'Globito']]],
['cambiajuego',['cambiaJuego',['../class_fondo.html#a1107d3ba2cdfba378867034379cc4379',1,'Fondo']]],
['contador',['contador',['../class_globito.html#a96c6f69159240041c9ed43234b339990',1,'Globito']]]
];
| JavaScript |
var searchData=
[
['letrero',['Letrero',['../class_letrero.html#a6fb7d136cc91a443972e9071bb604ac5',1,'Letrero']]]
];
| JavaScript |
var searchData=
[
['fondo',['Fondo',['../class_fondo.html',1,'']]]
];
| JavaScript |
var searchData=
[
['objetosube',['ObjetoSube',['../class_objeto_sube.html',1,'']]],
['obstaculo',['Obstaculo',['../class_obstaculo.html',1,'']]]
];
| JavaScript |
var searchData=
[
['objetosube',['ObjetoSube',['../class_objeto_sube.html',1,'']]],
['objetosube_2ejava',['ObjetoSube.java',['../_objeto_sube_8java.html',1,'']]],
['obstaculo',['Obstaculo',['../class_obstaculo.html',1,'Obstaculo'],['../class_obstaculo.html#aa5aaa7230da50c4c7a094f0a2158e85e',1,'Obstaculo.Obstaculo()']]],
['obstaculo_2ejava',['Obstaculo.java',['../_obstaculo_8java.html',1,'']]]
];
| JavaScript |
var searchData=
[
['damepuntaje',['damePuntaje',['../class_score2.html#aefbbeb7093f17f0d2eecbf3a5a0412a8',1,'Score2']]],
['decrementapuntaje',['decrementaPuntaje',['../class_score2.html#a561cc012e4db409856ada84ca032ea96',1,'Score2']]],
['detenpatricio',['detenPatricio',['../class_patricio.html#a428b9470ccc8f8e6d98d334afa86afa1',1,'Patricio']]],
['disparader',['disparaDer',['../class_espina.html#ad8a70b88b64446fe69f9f052b08399bb',1,'Espina']]],
['disparaizq',['disparaIzq',['../class_espina.html#a57eb765d3fb52d2c408f765fc9d6017f',1,'Espina']]],
['disparo',['Disparo',['../class_disparo.html',1,'']]],
['disparo_2ejava',['Disparo.java',['../_disparo_8java.html',1,'']]]
];
| JavaScript |
var searchData=
[
['cactus',['Cactus',['../class_cactus.html',1,'']]],
['cactusder',['Cactusder',['../class_cactusder.html',1,'']]],
['cactusizq',['Cactusizq',['../class_cactusizq.html',1,'']]],
['caja1',['Caja1',['../class_caja1.html',1,'']]],
['caja2',['Caja2',['../class_caja2.html',1,'']]],
['cajas',['Cajas',['../class_cajas.html',1,'']]]
];
| JavaScript |
var searchData=
[
['help_2ejava',['Help.java',['../_help_8java.html',1,'']]]
];
| JavaScript |
var searchData=
[
['patricio',['Patricio',['../class_patricio.html',1,'']]],
['piedrita',['Piedrita',['../class_piedrita.html',1,'']]],
['play',['Play',['../class_play.html',1,'']]],
['portador',['Portador',['../class_portador.html',1,'']]]
];
| JavaScript |
var searchData=
[
['back',['Back',['../class_back.html',1,'']]],
['back_2ejava',['Back.java',['../_back_8java.html',1,'']]],
['baja',['baja',['../class_obstaculo.html#a8cb2aeaf3c3ce2920e973c1560ec7648',1,'Obstaculo']]],
['button',['Button',['../class_button.html',1,'']]],
['button_2ejava',['Button.java',['../_button_8java.html',1,'']]]
];
| JavaScript |
var searchData=
[
['disparo',['Disparo',['../class_disparo.html',1,'']]]
];
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.