Skip to content

Instantly share code, notes, and snippets.

@dbkbali
Created May 7, 2012 08:41
Show Gist options
  • Save dbkbali/2626702 to your computer and use it in GitHub Desktop.
Save dbkbali/2626702 to your computer and use it in GitHub Desktop.
Application.JS file for Backbone Problem with JST/Handlebars Template
/*!
* jQuery JavaScript Library v1.7.2
* 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: Wed Mar 21 12:46:34 2012 -0700
*/
(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
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
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+$/,
// 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.]+))?/,
// Matches dashed string for camelizing
rdashAlpha = /-([a-z]|[0-9])/ig,
rmsPrefix = /^-ms-/,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// 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.7.2",
// 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.add( fn );
return this;
},
eq: function( i ) {
i = +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.fireWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).off( "ready" );
}
}
},
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery.Callbacks( "once memory" );
// 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";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( 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;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
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 new Error( 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
parseXML: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
var xml, tmp;
try {
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 );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
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 );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
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'
// 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, i ) {
var len;
if ( array ) {
if ( indexOf ) {
return indexOf.call( array, elem, i );
}
len = array.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in array && 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 optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
var exec,
bulk = key == null,
i = 0,
length = elems.length;
// Sets many values
if ( key && typeof key === "object" ) {
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
}
chainable = 1;
// Sets one value
} else if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = pass === undefined && jQuery.isFunction( value );
if ( bulk ) {
// Bulk operations only iterate when executing function values
if ( exec ) {
exec = fn;
fn = function( elem, key, value ) {
return exec.call( jQuery( elem ), value );
};
// Otherwise they run against the entire set
} else {
fn.call( elems, value );
fn = null;
}
}
if ( fn ) {
for (; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
}
chainable = 1;
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
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();
}
return jQuery;
})();
// String to Object flags format cache
var flagsCache = {};
// Convert String-formatted flags into Object-formatted ones and store in cache
function createFlags( flags ) {
var object = flagsCache[ flags ] = {},
i, length;
flags = flags.split( /\s+/ );
for ( i = 0, length = flags.length; i < length; i++ ) {
object[ flags[i] ] = true;
}
return object;
}
/*
* Create a callback list using the following parameters:
*
* flags: an optional list of space-separated flags that will change how
* the callback list behaves
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible flags:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( flags ) {
// Convert flags from String-formatted to Object-formatted
// (we check in cache first)
flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {};
var // Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = [],
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Add one or several callbacks to the list
add = function( args ) {
var i,
length,
elem,
type,
actual;
for ( i = 0, length = args.length; i < length; i++ ) {
elem = args[ i ];
type = jQuery.type( elem );
if ( type === "array" ) {
// Inspect recursively
add( elem );
} else if ( type === "function" ) {
// Add if not in unique mode and callback is not in
if ( !flags.unique || !self.has( elem ) ) {
list.push( elem );
}
}
}
},
// Fire callbacks
fire = function( context, args ) {
args = args || [];
memory = !flags.memory || [ context, args ];
fired = true;
firing = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) {
memory = true; // Mark as halted
break;
}
}
firing = false;
if ( list ) {
if ( !flags.once ) {
if ( stack && stack.length ) {
memory = stack.shift();
self.fireWith( memory[ 0 ], memory[ 1 ] );
}
} else if ( memory === true ) {
self.disable();
} else {
list = [];
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
var length = list.length;
add( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away, unless previous
// firing was halted (stopOnFalse)
} else if ( memory && memory !== true ) {
firingStart = length;
fire( memory[ 0 ], memory[ 1 ] );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
var args = arguments,
argIndex = 0,
argLength = args.length;
for ( ; argIndex < argLength ; argIndex++ ) {
for ( var i = 0; i < list.length; i++ ) {
if ( args[ argIndex ] === list[ i ] ) {
// Handle firingIndex and firingLength
if ( firing ) {
if ( i <= firingLength ) {
firingLength--;
if ( i <= firingIndex ) {
firingIndex--;
}
}
}
// Remove the element
list.splice( i--, 1 );
// If we have some unicity property then
// we only need to do this once
if ( flags.unique ) {
break;
}
}
}
}
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
if ( list ) {
var i = 0,
length = list.length;
for ( ; i < length; i++ ) {
if ( fn === list[ i ] ) {
return true;
}
}
}
return false;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory || memory === true ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( stack ) {
if ( firing ) {
if ( !flags.once ) {
stack.push( [ context, args ] );
}
} else if ( !( flags.once && memory ) ) {
fire( context, args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
var // Static reference to slice
sliceDeferred = [].slice;
jQuery.extend({
Deferred: function( func ) {
var doneList = jQuery.Callbacks( "once memory" ),
failList = jQuery.Callbacks( "once memory" ),
progressList = jQuery.Callbacks( "memory" ),
state = "pending",
lists = {
resolve: doneList,
reject: failList,
notify: progressList
},
promise = {
done: doneList.add,
fail: failList.add,
progress: progressList.add,
state: function() {
return state;
},
// Deprecated
isResolved: doneList.fired,
isRejected: failList.fired,
then: function( doneCallbacks, failCallbacks, progressCallbacks ) {
deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks );
return this;
},
always: function() {
deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments );
return this;
},
pipe: function( fnDone, fnFail, fnProgress ) {
return jQuery.Deferred(function( newDefer ) {
jQuery.each( {
done: [ fnDone, "resolve" ],
fail: [ fnFail, "reject" ],
progress: [ fnProgress, "notify" ]
}, 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, newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ 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 ) {
obj = promise;
} else {
for ( var key in promise ) {
obj[ key ] = promise[ key ];
}
}
return obj;
}
},
deferred = promise.promise({}),
key;
for ( key in lists ) {
deferred[ key ] = lists[ key ].fire;
deferred[ key + "With" ] = lists[ key ].fireWith;
}
// Handle state
deferred.done( function() {
state = "resolved";
}, failList.disable, progressList.lock ).fail( function() {
state = "rejected";
}, doneList.disable, progressList.lock );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( firstParam ) {
var args = sliceDeferred.call( arguments, 0 ),
i = 0,
length = args.length,
pValues = new Array( length ),
count = length,
pCount = length,
deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
firstParam :
jQuery.Deferred(),
promise = deferred.promise();
function resolveFunc( i ) {
return function( value ) {
args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
if ( !( --count ) ) {
deferred.resolveWith( deferred, args );
}
};
}
function progressFunc( i ) {
return function( value ) {
pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
deferred.notifyWith( promise, pValues );
};
}
if ( length > 1 ) {
for ( ; i < length; i++ ) {
if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) {
args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) );
} else {
--count;
}
}
if ( !count ) {
deferred.resolveWith( deferred, args );
}
} else if ( deferred !== firstParam ) {
deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
}
return promise;
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
tds,
events,
eventName,
i,
isSupported,
div = document.createElement( "div" ),
documentElement = document.documentElement;
// 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",
// Tests for enctype support on a form(#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
pixelMargin: true
};
// jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead
jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat");
// 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() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent( "onclick" );
}
// Check if a radio maintains its 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");
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "name", "t" );
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
// Technique from Juriy Zaytsev
// http://perfectionkills.com/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;
}
}
fragment.removeChild( div );
// Null elements to avoid leaks in IE
fragment = select = opt = div = input = null;
// Run tests that need a body at doc ready
jQuery(function() {
var container, outer, inner, table, td, offsetSupport,
marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight,
paddingMarginBorderVisibility, paddingMarginBorder,
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
conMarginTop = 1;
paddingMarginBorder = "padding:0;margin:0;border:";
positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;";
paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;";
style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;";
html = "<div " + style + "display:block;'><div style='" + paddingMarginBorder + "0;display:block;overflow:hidden;'></div></div>" +
"<table " + style + "' cellpadding='0' cellspacing='0'>" +
"<tr><td></td></tr></table>";
container = document.createElement("div");
container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// 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)
div.innerHTML = "<table><tr><td style='" + paddingMarginBorder + "0;display:none'></td><td>t</td></tr></table>";
tds = div.getElementsByTagName( "td" );
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 );
// 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 ( window.getComputedStyle ) {
div.innerHTML = "";
marginDiv = document.createElement( "div" );
marginDiv.style.width = "0";
marginDiv.style.marginRight = "0";
div.style.width = "2px";
div.appendChild( marginDiv );
support.reliableMarginRight =
( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
}
if ( typeof div.style.zoom !== "undefined" ) {
// 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.innerHTML = "";
div.style.width = div.style.padding = "1px";
div.style.border = 0;
div.style.overflow = "hidden";
div.style.display = "inline";
div.style.zoom = 1;
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "block";
div.style.overflow = "visible";
div.innerHTML = "<div style='width:5px;'></div>";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
}
div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility;
div.innerHTML = html;
outer = div.firstChild;
inner = outer.firstChild;
td = outer.nextSibling.firstChild.firstChild;
offsetSupport = {
doesNotAddBorder: ( inner.offsetTop !== 5 ),
doesAddBorderForTableAndCells: ( td.offsetTop === 5 )
};
inner.style.position = "fixed";
inner.style.top = "20px";
// safari subtracts parent border width here which is 5px
offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 );
inner.style.position = inner.style.top = "";
outer.style.overflow = "hidden";
outer.style.position = "relative";
offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 );
offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop );
if ( window.getComputedStyle ) {
div.style.marginTop = "1%";
support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%";
}
if ( typeof container.style.zoom !== "undefined" ) {
container.style.zoom = 1;
}
body.removeChild( container );
marginDiv = div = container = null;
jQuery.extend( support, offsetSupport );
});
return support;
})();
var rbrace = /^(?:\{.*\}|\[.*\])$/,
rmultiDash = /([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 privateCache, thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// 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[ internalKey ] : elem[ internalKey ] && internalKey,
isEvents = name === "events";
// 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 || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && 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[ internalKey ] = id = ++jQuery.uuid;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// 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 ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
privateCache = thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Users should not attempt to inspect the internal events object using jQuery.data,
// it is undocumented and subject to change. But does anyone listen? No.
if ( isEvents && !thisCache[ name ] ) {
return privateCache.events;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
// Reference to internal data cache key
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[ internalKey ] : internalKey;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split( " " );
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject(cache[ id ]) ) {
return;
}
}
// 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
// Ensure that `cache` is not a window object #10080
if ( jQuery.support.deleteExpando || !cache.setInterval ) {
delete cache[ id ];
} else {
cache[ id ] = null;
}
// We destroyed the cache and need to eliminate the expando on the node to avoid
// false lookups in the cache for entries that no longer exist
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[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = 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 parts, part, attr, name, l,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attr = elem.attributes;
for ( l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split( ".", 2 );
parts[1] = parts[1] ? "." + parts[1] : "";
part = parts[1] + "!";
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
data = this.triggerHandler( "getData" + part, [ parts[0] ] );
// Try to fetch any internally stored data first
if ( data === undefined && elem ) {
data = jQuery.data( elem, key );
data = dataAttr( elem, key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
}
parts[1] = value;
this.each(function() {
var self = jQuery( this );
self.triggerHandler( "setData" + part, parts );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + part, parts );
});
}, null, value, arguments.length > 1, null, false );
},
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" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
jQuery.isNumeric( data ) ? +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;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
for ( var name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
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 );
if ( defer &&
( src === "queue" || !jQuery._data(elem, queueDataKey) ) &&
( src === "mark" || !jQuery._data(elem, markDataKey) ) ) {
// 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 ) &&
!jQuery._data( elem, markDataKey ) ) {
jQuery.removeData( elem, deferDataKey, true );
defer.fire();
}
}, 0 );
}
}
jQuery.extend({
_mark: function( elem, type ) {
if ( elem ) {
type = ( type || "fx" ) + "mark";
jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 );
}
},
_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 ) || 1) - 1 );
if ( count ) {
jQuery._data( elem, key, count );
} else {
jQuery.removeData( elem, key, true );
handleQueueMarkDefer( elem, type, "mark" );
}
}
},
queue: function( elem, type, data ) {
var q;
if ( elem ) {
type = ( type || "fx" ) + "queue";
q = jQuery._data( elem, type );
// 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) );
} else {
q.push( data );
}
}
return q || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
fn = queue.shift(),
hooks = {};
// 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" );
}
jQuery._data( elem, type + ".run", hooks );
fn.call( elem, function() {
jQuery.dequeue( elem, type );
}, hooks );
}
if ( !queue.length ) {
jQuery.removeData( elem, type + "queue " + type + ".run", true );
handleQueueMarkDefer( elem, type, "queue" );
}
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
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( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
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.Callbacks( "once memory" ), true ) )) {
count++;
tmp.add( resolve );
}
}
resolve();
return defer.promise( object );
}
});
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,
getSetAttribute = jQuery.support.getSetAttribute,
nodeHook, boolHook, fixSpecified;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
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 ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classNames, i, l, elem, className, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
classNames = ( value || "" ).split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
if ( value ) {
className = (" " + elem.className + " ").replace( rclass, " " );
for ( 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 ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, 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 + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
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.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// 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, i, max, option,
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
i = one ? index : 0;
max = one ? index + 1 : options.length;
for ( ; i < max; i++ ) {
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
},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && name in jQuery.attrFn ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} 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 && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, l, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.toLowerCase().split( rspace );
l = attrNames.length;
for ( ; i < l; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
isBool = rboolean.test( name );
// See #9699 for explanation of this approach (setting first, then removal)
// Do not do this for boolean attributes (see #10870)
if ( !isBool ) {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( isBool && propName 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;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
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 ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = 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 )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
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;
}
}
}
});
// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional)
jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex;
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
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 ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
coords: true
};
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ?
ret.nodeValue :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.nodeValue = value + "" );
}
};
// Apply the nodeHook to tabindex
jQuery.attrHooks.tabindex.set = nodeHook.set;
// 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;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// 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;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// 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 rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/,
rhoverHack = /(?:^|\s)hover(\.\S+)?\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,
quickParse = function( selector ) {
var quick = rquickIs.exec( selector );
if ( quick ) {
// 0 1 2 3
// [ _, tag, id, class ]
quick[1] = ( quick[1] || "" ).toLowerCase();
quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" );
}
return quick;
},
quickIs = function( elem, m ) {
var attrs = elem.attributes || {};
return (
(!m[1] || elem.nodeName.toLowerCase() === m[1]) &&
(!m[2] || (attrs.id || {}).value === m[2]) &&
(!m[3] || m[3].test( (attrs[ "class" ] || {}).value ))
);
},
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, quick, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
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.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
quick: selector && quickParse( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// 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 to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever 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, selector, mappedTypes ) {
var elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
t, tns, type, origType, namespaces, origCount,
j, events, special, handle, eventType, handleObj;
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
handle = elemData.handle;
if ( handle ) {
handle.elem = null;
}
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, [ "events", "handle" ], 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 ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var type = event.type || event,
namespaces = [],
cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType;
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
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.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
old = null;
for ( ; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old && old === elem.ownerDocument ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === 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.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = [].slice.call( arguments, 0 ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [],
i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related;
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers that should run if there are delegated events
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {
// Pregenerate a single jQuery object for reuse with .is()
jqcur = jQuery(this);
jqcur.context = this.ownerDocument || this;
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process events on disabled elements (#6911, #8165)
if ( cur.disabled !== true ) {
selMatch = {};
matches = [];
jqcur[0] = cur;
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = (
handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel )
);
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = jQuery.Event( originalEvent );
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (#504, Safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8)
if ( event.metaKey === undefined ) {
event.metaKey = event.ctrlKey;
}
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
ready: {
// Make sure the ready event is setup
setup: jQuery.bindReady
},
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
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;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// 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.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
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 instanceof jQuery.Event) ) {
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 );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.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
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector,
ret;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !form._submit_attached ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
form._submit_attached = true;
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
jQuery.event.simulate( "change", this, event, true );
}
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
elem._change_attached = true;
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return rformElems.test( this.nodeName );
}
};
}
// 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,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) { // && selector != null
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
var handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( var type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn );
},
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 );
}
});
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 contextmenu").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.on( name, null, data, fn ) :
this.trigger( name );
};
if ( jQuery.attrFn ) {
jQuery.attrFn[ name ] = true;
}
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* 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,
expando = "sizcache" + (Math.random() + '').replace('.', ''),
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true,
rBackslash = /\\/g,
rReturn = /\r\n/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, seed );
} 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, seed );
}
}
} 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, i, len, match, type, left;
if ( !expr ) {
return [];
}
for ( i = 0, len = Expr.order.length; i < len; i++ ) {
type = Expr.order[i];
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
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,
type, found, item, filter, left,
i, pass,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
while ( expr && set.length ) {
for ( type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
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 ( i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
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 new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Utility function for retreiving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
var getText = Sizzle.getText = function( elem ) {
var i, node,
nodeType = elem.nodeType,
ret = "";
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent || innerText for elements
if ( typeof elem.textContent === 'string' ) {
return elem.textContent;
} else if ( typeof elem.innerText === 'string' ) {
// Replace IE's carriage returns
return elem.innerText.replace( rReturn, '' );
} else {
// Traverse it's children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
} else {
// If no nodeType, this is expected to be an array
for ( i = 0; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
if ( node.nodeType !== 8 ) {
ret += getText( node );
}
}
}
return ret;
};
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 || 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 first, last,
doneName, parent, cache,
count, diff,
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;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case "nth":
first = match[2];
last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
doneName = match[0];
parent = elem.parentNode;
if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) {
count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent[ expando ] = doneName;
}
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 && 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 = Sizzle.attr ?
Sizzle.attr( elem, name ) :
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 && Sizzle.attr ?
result != null :
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) );
}
// Expose origPOS
// "global" as in regardless of relation to brackets/parens
Expr.match.globalPOS = origPOS;
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;
};
}
// 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[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem[ expando ] = 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[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem[ expando ] = 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, seed ) {
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, seed );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
Sizzle.selectors.attrMap = {};
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.globalPOS,
// 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" ?
// If this is a positional selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
POS.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var ret = [], i, l, cur = this[0];
// Array (deprecated as of jQuery 1.7)
if ( jQuery.isArray( selectors ) ) {
var level = 1;
while ( cur && cur.ownerDocument && cur !== context ) {
for ( i = 0; i < selectors.length; i++ ) {
if ( jQuery( cur ).is( selectors[ i ] ) ) {
ret.push({ selector: selectors[ i ], 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 ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// 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 );
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, slice.call( arguments ).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;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
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+;/,
rnoInnerhtml = /<(?:script|style)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "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, "", "" ]
},
safeFragment = createSafeFragment( document );
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( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
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 ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : 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.clean( arguments );
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.clean(arguments) );
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 ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
null;
}
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName( "*" ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
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, function( i, elem ) {
if ( elem.src ) {
jQuery.ajax({
type: "GET",
global: false,
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 );
}
});
}
}
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 type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.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;
// IE blanks contents when cloning scripts
} else if ( nodeName === "script" && dest.text !== src.text ) {
dest.text = src.text;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
// Clear flags for bubbling special change/submit events, they must
// be reattached when the newly cloned events are first activated
dest.removeAttribute( "_submit_attached" );
dest.removeAttribute( "_change_attached" );
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults, doc,
first = args[ 0 ];
// nodes may contain either an explicit document object,
// a jQuery collection or context object.
// If nodes[0] contains a valid object to assign to doc
if ( nodes && nodes[0] ) {
doc = nodes[0].ownerDocument || nodes[0];
}
// Ensure that an attr object doesn't incorrectly stand in as a document object
// Chrome and Firefox seem to allow this to occur and will throw exception
// Fixes #8950
if ( !doc.createDocumentFragment ) {
doc = 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
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ first ];
if ( cacheresults && cacheresults !== 1 ) {
fragment = cacheresults;
}
}
if ( !fragment ) {
fragment = doc.createDocumentFragment();
jQuery.clean( args, doc, fragment, scripts );
}
if ( cacheable ) {
jQuery.fragments[ first ] = 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 ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
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 ) {
var nodeName = ( elem.nodeName || "" ).toLowerCase();
if ( nodeName === "input" ) {
fixDefaultChecked( elem );
// Skip scripts, get other children
} else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
// Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js
function shimCloneNode( elem ) {
var div = document.createElement( "div" );
safeFragment.appendChild( div );
div.innerHTML = elem.outerHTML;
return div.firstChild;
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
// IE<=8 does not properly clone detached, unknown element nodes
clone = jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ?
elem.cloneNode( true ) :
shimCloneNode( elem );
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 ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[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] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var checkScriptType, script, j,
ret = [];
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;
}
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"),
safeChildNodes = safeFragment.childNodes,
remove;
// Append wrapper element to unknown element safe doc fragment
if ( context === document ) {
// Use the fragment we've already created for this document
safeFragment.appendChild( div );
} else {
// Use a fragment created with the owner document
createSafeFragment( context ).appendChild( 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;
// Clear elements from DocumentFragment (safeFragment or otherwise)
// to avoid hoarding elements. Fixes #11356
if ( div ) {
div.parentNode.removeChild( div );
// Guard against -1 index exceptions in FF3.6
if ( safeChildNodes.length > 0 ) {
remove = safeChildNodes[ safeChildNodes.length - 1 ];
if ( remove && remove.parentNode ) {
remove.parentNode.removeChild( remove );
}
}
}
}
}
// 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++ ) {
script = ret[i];
if ( scripts && jQuery.nodeName( script, "script" ) && (!script.type || rscriptType.test( script.type )) ) {
scripts.push( script.parentNode ? script.parentNode.removeChild( script ) : script );
} else {
if ( script.nodeType === 1 ) {
var jsTags = jQuery.grep( script.getElementsByTagName( "script" ), checkScriptType );
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
}
fragment.appendChild( script );
}
}
}
return ret;
},
cleanData: function( elems ) {
var data, id,
cache = jQuery.cache,
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 ];
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 ];
}
}
}
});
var ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
// fixed for IE9, see #8346
rupper = /([A-Z]|^ms)/g,
rnum = /^[\-+]?(?:\d*\.)?\d+$/i,
rnumnonpx = /^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,
rrelNum = /^([\-+])=([\-+.\de]+)/,
rmargin = /^margin/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
// order is important!
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
curCSS,
getComputedStyle,
currentStyle;
jQuery.fn.css = function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
};
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" );
return ret === "" ? "1" : ret;
} else {
return elem.style.opacity;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": 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;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// 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 = {},
ret, name;
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// DEPRECATED in 1.3, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;
if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, name ) {
var ret, defaultView, computedStyle, width,
style = elem.style;
name = name.replace( rupper, "-$1" ).toLowerCase();
if ( (defaultView = elem.ownerDocument.defaultView) &&
(computedStyle = defaultView.getComputedStyle( elem, null )) ) {
ret = computedStyle.getPropertyValue( name );
if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
ret = jQuery.style( elem, name );
}
}
// A tribute to the "awesome hack by Dean Edwards"
// WebKit uses "computed value (percentage if specified)" instead of "used value" for margins
// which is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( !jQuery.support.pixelMargin && computedStyle && rmargin.test( name ) && rnumnonpx.test( ret ) ) {
width = style.width;
style.width = ret;
ret = computedStyle.width;
style.width = width;
}
return ret;
};
}
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
var left, rsLeft, uncomputed,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && (uncomputed = style[ name ]) ) {
ret = uncomputed;
}
// 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 ( rnumnonpx.test( ret ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.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;
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 getWidthOrHeight( elem, name, extra ) {
// Start with offset property
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
i = name === "width" ? 1 : 0,
len = 4;
if ( val > 0 ) {
if ( extra !== "border" ) {
for ( ; i < len; i += 2 ) {
if ( !extra ) {
val -= parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ] ) ) || 0;
} else {
val -= parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val + "px";
}
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
// Add padding, border, margin
if ( extra ) {
for ( ; i < len; i += 2 ) {
val += parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0;
if ( extra !== "padding" ) {
val += parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ]) ) || 0;
}
}
}
return val + "px";
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
if ( elem.offsetWidth !== 0 ) {
return getWidthOrHeight( elem, name, extra );
} else {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
}
}
},
set: function( elem, value ) {
return rnum.test( value ) ?
value + "px" :
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,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
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
return jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
return curCSS( elem, "margin-right" );
} else {
return elem.style.marginRight;
}
});
}
};
}
});
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 && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i,
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ],
expanded = {};
for ( i = 0; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
});
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|datetime-local|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|res|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,
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #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;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
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.on( 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 ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
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",
"*": allTypes
},
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
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
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.Callbacks( "once memory" ),
// 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, nativeStatusText, 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 > 0 ? 4 : 0;
var isSuccess,
success,
error,
statusText = nativeStatusText,
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 = "" + ( nativeStatusText || 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.fireWith( 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.add;
// 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 prefilter, 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;
// #9682: remove data so that it's not used in an eventual retry
delete 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 ] !== "*" ? ", " + allTypes + "; 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 ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw 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" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( 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 = ( typeof s.data === "string" ) && /^application\/x\-www\-form\-urlencoded/.test( s.contentType );
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;
}
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
try {
responses.text = xhr.responseText;
} catch( _ ) {
}
// 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;
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.contains( elem.ownerDocument.documentElement, elem ) ) {
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 {
var elem, display,
i = 0,
j = this.length;
for ( ; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = jQuery.css( elem, "display" );
if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) {
jQuery._data( elem, "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 );
function doAnimation() {
// 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, e, hooks, replace,
parts, start, end, unit,
method;
// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties = {};
// first pass over propertys to expand / normalize
for ( p in prop ) {
name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
}
if ( ( hooks = jQuery.cssHooks[ name ] ) && "expand" in hooks ) {
replace = hooks.expand( prop[ name ] );
delete prop[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'p' from above because we have the correct "name"
for ( p in replace ) {
if ( ! ( p in prop ) ) {
prop[ p ] = replace[ p ];
}
}
}
}
for ( name in prop ) {
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" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) {
this.style.display = "inline-block";
} else {
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 ) ) {
// Tracks whether to show or hide based on private
// data attached to the element
method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 );
if ( method ) {
jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" );
e[ method ]();
} else {
e[ 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;
}
return optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var index,
hadTimers = false,
timers = jQuery.timers,
data = jQuery._data( this );
// clear marker counters if we know they won't be
if ( !gotoEnd ) {
jQuery._unmark( true, this );
}
function stopQueue( elem, data, index ) {
var hooks = data[ index ];
jQuery.removeData( elem, index, true );
hooks.stop( gotoEnd );
}
if ( type == null ) {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) {
stopQueue( this, data, index );
}
}
} else if ( data[ index = type + ".run" ] && data[ index ].stop ){
stopQueue( this, data, index );
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
if ( gotoEnd ) {
// force the next step to be the last
timers[ index ]( true );
} else {
timers[ index ].saveState();
}
hadTimers = true;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( !( gotoEnd && hadTimers ) ) {
jQuery.dequeue( this, type );
}
});
}
});
// 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;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function( noUnmark ) {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
} else if ( noUnmark !== false ) {
jQuery._unmark( this );
}
};
return opt;
},
easing: {
linear: function( p ) {
return p;
},
swing: function( p ) {
return ( -Math.cos( p*Math.PI ) / 2 ) + 0.5;
}
},
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;
this.startTime = fxNow || createFxNow();
this.end = to;
this.now = this.start = from;
this.pos = this.state = 0;
this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
function t( gotoEnd ) {
return self.step( gotoEnd );
}
t.queue = this.options.queue;
t.elem = this.elem;
t.saveState = function() {
if ( jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) {
if ( self.options.hide ) {
jQuery._data( self.elem, "fxshow" + self.prop, self.start );
} else if ( self.options.show ) {
jQuery._data( self.elem, "fxshow" + self.prop, self.end );
}
}
};
if ( t() && jQuery.timers.push(t) && !timerId ) {
timerId = setInterval( fx.tick, fx.interval );
}
},
// Simple 'show' function
show: function() {
var dataShow = jQuery._data( this.elem, "fxshow" + this.prop );
// Remember where we started, so that we can go back to it later
this.options.orig[ this.prop ] = dataShow || 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
if ( dataShow !== undefined ) {
// This show is picking up where a previous hide or show left off
this.custom( this.cur(), dataShow );
} else {
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._data( this.elem, "fxshow" + 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 p, n, complete,
t = fxNow || createFxNow(),
done = true,
elem = this.elem,
options = this.options;
if ( gotoEnd || t >= options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
options.animatedProperties[ this.prop ] = true;
for ( p in options.animatedProperties ) {
if ( options.animatedProperties[ p ] !== 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 ( p in options.animatedProperties ) {
jQuery.style( elem, p, options.orig[ p ] );
jQuery.removeData( elem, "fxshow" + p, true );
// Toggle data is no longer needed
jQuery.removeData( elem, "toggle" + p, true );
}
}
// Execute the complete function
// in the event that the complete function throws an exception
// we must ensure it won't be called twice. #5684
complete = options.complete;
if ( complete ) {
options.complete = false;
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() {
var timer,
timers = jQuery.timers,
i = 0;
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
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.now + fx.unit;
} else {
fx.elem[ fx.prop ] = fx.now;
}
}
}
});
// Ensure props that can't be negative don't go there on undershoot easing
jQuery.each( fxAttrs.concat.apply( [], fxAttrs ), function( i, prop ) {
// exclude marginTop, marginLeft, marginBottom and marginRight from this list
if ( prop.indexOf( "margin" ) ) {
jQuery.fx.step[ prop ] = function( fx ) {
jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit );
};
}
});
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 body = document.body,
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;
}
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( ( jQuery.support.boxModel ? "<!doctype html>" : "" ) + "<html><body>" );
iframeDoc.close();
}
elem = iframeDoc.createElement( nodeName );
iframeDoc.body.appendChild( elem );
display = jQuery.css( elem, "display" );
body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return elemdisplay[ nodeName ];
}
var getOffset,
rtable = /^t(?:able|d|h)$/i,
rroot = /^(?:body|html)$/i;
if ( "getBoundingClientRect" in document.documentElement ) {
getOffset = function( elem, doc, docElem, box ) {
try {
box = elem.getBoundingClientRect();
} catch(e) {}
// 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 {
getOffset = function( elem, doc, docElem ) {
var computedStyle,
offsetParent = elem.offsetParent,
prevOffsetParent = elem,
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.support.fixedPosition && 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.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevOffsetParent = offsetParent;
offsetParent = elem.offsetParent;
}
if ( jQuery.support.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.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
top += Math.max( docElem.scrollTop, body.scrollTop );
left += Math.max( docElem.scrollLeft, body.scrollLeft );
}
return { top: top, left: left };
};
}
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var elem = this[0],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return null;
}
if ( elem === doc.body ) {
return jQuery.offset.bodyOffset( elem );
}
return getOffset( elem, doc, doc.documentElement );
};
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.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( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
var clientProp = "client" + name,
scrollProp = "scroll" + name,
offsetProp = "offset" + name;
// innerHeight and innerWidth
jQuery.fn[ "inner" + name ] = function() {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, "padding" ) ) :
this[ type ]() :
null;
};
// outerHeight and outerWidth
jQuery.fn[ "outer" + name ] = function( margin ) {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) :
this[ type ]() :
null;
};
jQuery.fn[ type ] = function( value ) {
return jQuery.access( this, function( elem, type, value ) {
var doc, docElemProp, orig, ret;
if ( jQuery.isWindow( elem ) ) {
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
doc = elem.document;
docElemProp = doc.documentElement[ clientProp ];
return jQuery.support.boxModel && docElemProp ||
doc.body && doc.body[ clientProp ] || docElemProp;
}
// Get document width or height
if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
doc = elem.documentElement;
// when a window > document, IE6 reports a offset[Width/Height] > client[Width/Height]
// so we can't use max, as it'll choose the incorrect offset[Width/Height]
// instead we use the correct client[Width/Height]
// support:IE6
if ( doc[ clientProp ] >= doc[ scrollProp ] ) {
return doc[ clientProp ];
}
return Math.max(
elem.body[ scrollProp ], doc[ scrollProp ],
elem.body[ offsetProp ], doc[ offsetProp ]
);
}
// Get width or height on the element
if ( value === undefined ) {
orig = jQuery.css( elem, type );
ret = parseFloat( orig );
return jQuery.isNumeric( ret ) ? ret : orig;
}
// Set the width or height on the element
jQuery( elem ).css( type, value );
}, type, value, arguments.length, null );
};
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
(function($, undefined) {
/**
* Unobtrusive scripting adapter for jQuery
*
* Requires jQuery 1.6.0 or later.
* https://github.com/rails/jquery-ujs
* Uploading file using rails.js
* =============================
*
* By default, browsers do not allow files to be uploaded via AJAX. As a result, if there are any non-blank file fields
* in the remote form, this adapter aborts the AJAX submission and allows the form to submit through standard means.
*
* The `ajax:aborted:file` event allows you to bind your own handler to process the form submission however you wish.
*
* Ex:
* $('form').live('ajax:aborted:file', function(event, elements){
* // Implement own remote file-transfer handler here for non-blank file inputs passed in `elements`.
* // Returning false in this handler tells rails.js to disallow standard form submission
* return false;
* });
*
* The `ajax:aborted:file` event is fired when a file-type input is detected with a non-blank value.
*
* Third-party tools can use this hook to detect when an AJAX file upload is attempted, and then use
* techniques like the iframe method to upload the file instead.
*
* Required fields in rails.js
* ===========================
*
* If any blank required inputs (required="required") are detected in the remote form, the whole form submission
* is canceled. Note that this is unlike file inputs, which still allow standard (non-AJAX) form submission.
*
* The `ajax:aborted:required` event allows you to bind your own handler to inform the user of blank required inputs.
*
* !! Note that Opera does not fire the form's submit event if there are blank required inputs, so this event may never
* get fired in Opera. This event is what causes other browsers to exhibit the same submit-aborting behavior.
*
* Ex:
* $('form').live('ajax:aborted:required', function(event, elements){
* // Returning false in this handler tells rails.js to submit the form anyway.
* // The blank required inputs are passed to this function in `elements`.
* return ! confirm("Would you like to submit the form with missing info?");
* });
*/
// Shorthand to make it a little easier to call public rails functions from within rails.js
var rails;
$.rails = rails = {
// Link elements bound by jquery-ujs
linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote], a[data-disable-with]',
// Select elements bound by jquery-ujs
inputChangeSelector: 'select[data-remote], input[data-remote], textarea[data-remote]',
// Form elements bound by jquery-ujs
formSubmitSelector: 'form',
// Form input elements bound by jquery-ujs
formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not(button[type])',
// Form input elements disabled during form submission
disableSelector: 'input[data-disable-with], button[data-disable-with], textarea[data-disable-with]',
// Form input elements re-enabled after form submission
enableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled',
// Form required input elements
requiredInputSelector: 'input[name][required]:not([disabled]),textarea[name][required]:not([disabled])',
// Form file input elements
fileInputSelector: 'input:file',
// Link onClick disable selector with possible reenable after remote submission
linkDisableSelector: 'a[data-disable-with]',
// Make sure that every Ajax request sends the CSRF token
CSRFProtection: function(xhr) {
var token = $('meta[name="csrf-token"]').attr('content');
if (token) xhr.setRequestHeader('X-CSRF-Token', token);
},
// Triggers an event on an element and returns false if the event result is false
fire: function(obj, name, data) {
var event = $.Event(name);
obj.trigger(event, data);
return event.result !== false;
},
// Default confirm dialog, may be overridden with custom confirm dialog in $.rails.confirm
confirm: function(message) {
return confirm(message);
},
// Default ajax function, may be overridden with custom function in $.rails.ajax
ajax: function(options) {
return $.ajax(options);
},
// Default way to get an element's href. May be overridden at $.rails.href.
href: function(element) {
return element.attr('href');
},
// Submits "remote" forms and links with ajax
handleRemote: function(element) {
var method, url, data, crossDomain, dataType, options;
if (rails.fire(element, 'ajax:before')) {
crossDomain = element.data('cross-domain') || null;
dataType = element.data('type') || ($.ajaxSettings && $.ajaxSettings.dataType);
if (element.is('form')) {
method = element.attr('method');
url = element.attr('action');
data = element.serializeArray();
// memoized value from clicked submit button
var button = element.data('ujs:submit-button');
if (button) {
data.push(button);
element.data('ujs:submit-button', null);
}
} else if (element.is(rails.inputChangeSelector)) {
method = element.data('method');
url = element.data('url');
data = element.serialize();
if (element.data('params')) data = data + "&" + element.data('params');
} else {
method = element.data('method');
url = rails.href(element);
data = element.data('params') || null;
}
options = {
type: method || 'GET', data: data, dataType: dataType, crossDomain: crossDomain,
// stopping the "ajax:beforeSend" event will cancel the ajax request
beforeSend: function(xhr, settings) {
if (settings.dataType === undefined) {
xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
}
return rails.fire(element, 'ajax:beforeSend', [xhr, settings]);
},
success: function(data, status, xhr) {
element.trigger('ajax:success', [data, status, xhr]);
},
complete: function(xhr, status) {
element.trigger('ajax:complete', [xhr, status]);
},
error: function(xhr, status, error) {
element.trigger('ajax:error', [xhr, status, error]);
}
};
// Only pass url to `ajax` options if not blank
if (url) { options.url = url; }
return rails.ajax(options);
} else {
return false;
}
},
// Handles "data-method" on links such as:
// <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a>
handleMethod: function(link) {
var href = rails.href(link),
method = link.data('method'),
target = link.attr('target'),
csrf_token = $('meta[name=csrf-token]').attr('content'),
csrf_param = $('meta[name=csrf-param]').attr('content'),
form = $('<form method="post" action="' + href + '"></form>'),
metadata_input = '<input name="_method" value="' + method + '" type="hidden" />';
if (csrf_param !== undefined && csrf_token !== undefined) {
metadata_input += '<input name="' + csrf_param + '" value="' + csrf_token + '" type="hidden" />';
}
if (target) { form.attr('target', target); }
form.hide().append(metadata_input).appendTo('body');
form.submit();
},
/* Disables form elements:
- Caches element value in 'ujs:enable-with' data store
- Replaces element text with value of 'data-disable-with' attribute
- Sets disabled property to true
*/
disableFormElements: function(form) {
form.find(rails.disableSelector).each(function() {
var element = $(this), method = element.is('button') ? 'html' : 'val';
element.data('ujs:enable-with', element[method]());
element[method](element.data('disable-with'));
element.prop('disabled', true);
});
},
/* Re-enables disabled form elements:
- Replaces element text with cached value from 'ujs:enable-with' data store (created in `disableFormElements`)
- Sets disabled property to false
*/
enableFormElements: function(form) {
form.find(rails.enableSelector).each(function() {
var element = $(this), method = element.is('button') ? 'html' : 'val';
if (element.data('ujs:enable-with')) element[method](element.data('ujs:enable-with'));
element.prop('disabled', false);
});
},
/* For 'data-confirm' attribute:
- Fires `confirm` event
- Shows the confirmation dialog
- Fires the `confirm:complete` event
Returns `true` if no function stops the chain and user chose yes; `false` otherwise.
Attaching a handler to the element's `confirm` event that returns a `falsy` value cancels the confirmation dialog.
Attaching a handler to the element's `confirm:complete` event that returns a `falsy` value makes this function
return false. The `confirm:complete` event is fired whether or not the user answered true or false to the dialog.
*/
allowAction: function(element) {
var message = element.data('confirm'),
answer = false, callback;
if (!message) { return true; }
if (rails.fire(element, 'confirm')) {
answer = rails.confirm(message);
callback = rails.fire(element, 'confirm:complete', [answer]);
}
return answer && callback;
},
// Helper function which checks for blank inputs in a form that match the specified CSS selector
blankInputs: function(form, specifiedSelector, nonBlank) {
var inputs = $(), input,
selector = specifiedSelector || 'input,textarea';
form.find(selector).each(function() {
input = $(this);
// Collect non-blank inputs if nonBlank option is true, otherwise, collect blank inputs
if (nonBlank ? input.val() : !input.val()) {
inputs = inputs.add(input);
}
});
return inputs.length ? inputs : false;
},
// Helper function which checks for non-blank inputs in a form that match the specified CSS selector
nonBlankInputs: function(form, specifiedSelector) {
return rails.blankInputs(form, specifiedSelector, true); // true specifies nonBlank
},
// Helper function, needed to provide consistent behavior in IE
stopEverything: function(e) {
$(e.target).trigger('ujs:everythingStopped');
e.stopImmediatePropagation();
return false;
},
// find all the submit events directly bound to the form and
// manually invoke them. If anyone returns false then stop the loop
callFormSubmitBindings: function(form, event) {
var events = form.data('events'), continuePropagation = true;
if (events !== undefined && events['submit'] !== undefined) {
$.each(events['submit'], function(i, obj){
if (typeof obj.handler === 'function') return continuePropagation = obj.handler(event);
});
}
return continuePropagation;
},
// replace element's html with the 'data-disable-with' after storing original html
// and prevent clicking on it
disableElement: function(element) {
element.data('ujs:enable-with', element.html()); // store enabled state
element.html(element.data('disable-with')); // set to disabled state
element.bind('click.railsDisable', function(e) { // prevent further clicking
return rails.stopEverything(e)
});
},
// restore element to its original state which was disabled by 'disableElement' above
enableElement: function(element) {
if (element.data('ujs:enable-with') !== undefined) {
element.html(element.data('ujs:enable-with')); // set to old enabled state
// this should be element.removeData('ujs:enable-with')
// but, there is currently a bug in jquery which makes hyphenated data attributes not get removed
element.data('ujs:enable-with', false); // clean up cache
}
element.unbind('click.railsDisable'); // enable element
}
};
$.ajaxPrefilter(function(options, originalOptions, xhr){ if ( !options.crossDomain ) { rails.CSRFProtection(xhr); }});
$(document).delegate(rails.linkDisableSelector, 'ajax:complete', function() {
rails.enableElement($(this));
});
$(document).delegate(rails.linkClickSelector, 'click.rails', function(e) {
var link = $(this), method = link.data('method'), data = link.data('params');
if (!rails.allowAction(link)) return rails.stopEverything(e);
if (link.is(rails.linkDisableSelector)) rails.disableElement(link);
if (link.data('remote') !== undefined) {
if ( (e.metaKey || e.ctrlKey) && (!method || method === 'GET') && !data ) { return true; }
if (rails.handleRemote(link) === false) { rails.enableElement(link); }
return false;
} else if (link.data('method')) {
rails.handleMethod(link);
return false;
}
});
$(document).delegate(rails.inputChangeSelector, 'change.rails', function(e) {
var link = $(this);
if (!rails.allowAction(link)) return rails.stopEverything(e);
rails.handleRemote(link);
return false;
});
$(document).delegate(rails.formSubmitSelector, 'submit.rails', function(e) {
var form = $(this),
remote = form.data('remote') !== undefined,
blankRequiredInputs = rails.blankInputs(form, rails.requiredInputSelector),
nonBlankFileInputs = rails.nonBlankInputs(form, rails.fileInputSelector);
if (!rails.allowAction(form)) return rails.stopEverything(e);
// skip other logic when required values are missing or file upload is present
if (blankRequiredInputs && form.attr("novalidate") == undefined && rails.fire(form, 'ajax:aborted:required', [blankRequiredInputs])) {
return rails.stopEverything(e);
}
if (remote) {
if (nonBlankFileInputs) {
return rails.fire(form, 'ajax:aborted:file', [nonBlankFileInputs]);
}
// If browser does not support submit bubbling, then this live-binding will be called before direct
// bindings. Therefore, we should directly call any direct bindings before remotely submitting form.
if (!$.support.submitBubbles && $().jquery < '1.7' && rails.callFormSubmitBindings(form, e) === false) return rails.stopEverything(e);
rails.handleRemote(form);
return false;
} else {
// slight timeout so that the submit button gets properly serialized
setTimeout(function(){ rails.disableFormElements(form); }, 13);
}
});
$(document).delegate(rails.formInputClickSelector, 'click.rails', function(event) {
var button = $(this);
if (!rails.allowAction(button)) return rails.stopEverything(event);
// register the pressed submit button
var name = button.attr('name'),
data = name ? {name:name, value:button.val()} : null;
button.closest('form').data('ujs:submit-button', data);
});
$(document).delegate(rails.formSubmitSelector, 'ajax:beforeSend.rails', function(event) {
if (this == event.target) rails.disableFormElements($(this));
});
$(document).delegate(rails.formSubmitSelector, 'ajax:complete.rails', function(event) {
if (this == event.target) rails.enableFormElements($(this));
});
})( jQuery );
/**
* jquery.Jcrop.js v0.9.9
* jQuery Image Cropping Plugin
* @author Kelly Hallman <khallman@gmail.com>
* Copyright (c) 2008-2011 Kelly Hallman - released under MIT License {{{
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* }}}
*/
(function ($) {
$.Jcrop = function (obj, opt) {
var options = $.extend({}, $.Jcrop.defaults),
docOffset, lastcurs, ie6mode = false;
// Internal Methods {{{
function px(n) {
return parseInt(n, 10) + 'px';
}
function pct(n) {
return parseInt(n, 10) + '%';
}
function cssClass(cl) {
return options.baseClass + '-' + cl;
}
function supportsColorFade() {
return $.fx.step.hasOwnProperty('backgroundColor');
}
function getPos(obj) //{{{
{
// Updated in v0.9.4 to use built-in dimensions plugin
var pos = $(obj).offset();
return [pos.left, pos.top];
}
//}}}
function mouseAbs(e) //{{{
{
return [(e.pageX - docOffset[0]), (e.pageY - docOffset[1])];
}
//}}}
function setOptions(opt) //{{{
{
if (typeof(opt) !== 'object') {
opt = {};
}
options = $.extend(options, opt);
if (typeof(options.onChange) !== 'function') {
options.onChange = function () {};
}
if (typeof(options.onSelect) !== 'function') {
options.onSelect = function () {};
}
if (typeof(options.onRelease) !== 'function') {
options.onRelease = function () {};
}
}
//}}}
function myCursor(type) //{{{
{
if (type !== lastcurs) {
Tracker.setCursor(type);
lastcurs = type;
}
}
//}}}
function startDragMode(mode, pos) //{{{
{
docOffset = getPos($img);
Tracker.setCursor(mode === 'move' ? mode : mode + '-resize');
if (mode === 'move') {
return Tracker.activateHandlers(createMover(pos), doneSelect);
}
var fc = Coords.getFixed();
var opp = oppLockCorner(mode);
var opc = Coords.getCorner(oppLockCorner(opp));
Coords.setPressed(Coords.getCorner(opp));
Coords.setCurrent(opc);
Tracker.activateHandlers(dragmodeHandler(mode, fc), doneSelect);
}
//}}}
function dragmodeHandler(mode, f) //{{{
{
return function (pos) {
if (!options.aspectRatio) {
switch (mode) {
case 'e':
pos[1] = f.y2;
break;
case 'w':
pos[1] = f.y2;
break;
case 'n':
pos[0] = f.x2;
break;
case 's':
pos[0] = f.x2;
break;
}
} else {
switch (mode) {
case 'e':
pos[1] = f.y + 1;
break;
case 'w':
pos[1] = f.y + 1;
break;
case 'n':
pos[0] = f.x + 1;
break;
case 's':
pos[0] = f.x + 1;
break;
}
}
Coords.setCurrent(pos);
Selection.update();
};
}
//}}}
function createMover(pos) //{{{
{
var lloc = pos;
KeyManager.watchKeys();
return function (pos) {
Coords.moveOffset([pos[0] - lloc[0], pos[1] - lloc[1]]);
lloc = pos;
Selection.update();
};
}
//}}}
function oppLockCorner(ord) //{{{
{
switch (ord) {
case 'n':
return 'sw';
case 's':
return 'nw';
case 'e':
return 'nw';
case 'w':
return 'ne';
case 'ne':
return 'sw';
case 'nw':
return 'se';
case 'se':
return 'nw';
case 'sw':
return 'ne';
}
}
//}}}
function createDragger(ord) //{{{
{
return function (e) {
if (options.disabled) {
return false;
}
if ((ord === 'move') && !options.allowMove) {
return false;
}
btndown = true;
startDragMode(ord, mouseAbs(e));
e.stopPropagation();
e.preventDefault();
return false;
};
}
//}}}
function presize($obj, w, h) //{{{
{
var nw = $obj.width(),
nh = $obj.height();
if ((nw > w) && w > 0) {
nw = w;
nh = (w / $obj.width()) * $obj.height();
}
if ((nh > h) && h > 0) {
nh = h;
nw = (h / $obj.height()) * $obj.width();
}
xscale = $obj.width() / nw;
yscale = $obj.height() / nh;
$obj.width(nw).height(nh);
}
//}}}
function unscale(c) //{{{
{
return {
x: parseInt(c.x * xscale, 10),
y: parseInt(c.y * yscale, 10),
x2: parseInt(c.x2 * xscale, 10),
y2: parseInt(c.y2 * yscale, 10),
w: parseInt(c.w * xscale, 10),
h: parseInt(c.h * yscale, 10)
};
}
//}}}
function doneSelect(pos) //{{{
{
var c = Coords.getFixed();
if ((c.w > options.minSelect[0]) && (c.h > options.minSelect[1])) {
Selection.enableHandles();
Selection.done();
} else {
Selection.release();
}
Tracker.setCursor(options.allowSelect ? 'crosshair' : 'default');
}
//}}}
function newSelection(e) //{{{
{
if (options.disabled) {
return false;
}
if (!options.allowSelect) {
return false;
}
btndown = true;
docOffset = getPos($img);
Selection.disableHandles();
myCursor('crosshair');
var pos = mouseAbs(e);
Coords.setPressed(pos);
Selection.update();
Tracker.activateHandlers(selectDrag, doneSelect);
KeyManager.watchKeys();
e.stopPropagation();
e.preventDefault();
return false;
}
//}}}
function selectDrag(pos) //{{{
{
Coords.setCurrent(pos);
Selection.update();
}
//}}}
function newTracker() //{{{
{
var trk = $('<div></div>').addClass(cssClass('tracker'));
if ($.browser.msie) {
trk.css({
opacity: 0,
backgroundColor: 'white'
});
}
return trk;
}
//}}}
// }}}
// Initialization {{{
// Sanitize some options {{{
if ($.browser.msie && ($.browser.version.split('.')[0] === '6')) {
ie6mode = true;
}
if (typeof(obj) !== 'object') {
obj = $(obj)[0];
}
if (typeof(opt) !== 'object') {
opt = {};
}
// }}}
setOptions(opt);
// Initialize some jQuery objects {{{
// The values are SET on the image(s) for the interface
// If the original image has any of these set, they will be reset
// However, if you destroy() the Jcrop instance the original image's
// character in the DOM will be as you left it.
var img_css = {
border: 'none',
margin: 0,
padding: 0,
position: 'absolute'
};
var $origimg = $(obj);
var $img = $origimg.clone().removeAttr('id').css(img_css);
$img.width($origimg.width());
$img.height($origimg.height());
$origimg.after($img).hide();
presize($img, options.boxWidth, options.boxHeight);
var boundx = $img.width(),
boundy = $img.height(),
$div = $('<div />').width(boundx).height(boundy).addClass(cssClass('holder')).css({
position: 'relative',
backgroundColor: options.bgColor
}).insertAfter($origimg).append($img);
delete(options.bgColor);
if (options.addClass) {
$div.addClass(options.addClass);
}
var $img2 = $('<img />')
.attr('src', $img.attr('src')).css(img_css).width(boundx).height(boundy),
$img_holder = $('<div />')
.width(pct(100)).height(pct(100)).css({
zIndex: 310,
position: 'absolute',
overflow: 'hidden'
}).append($img2),
$hdl_holder = $('<div />')
.width(pct(100)).height(pct(100)).css('zIndex', 320),
$sel = $('<div />')
.css({
position: 'absolute',
zIndex: 300
}).insertBefore($img).append($img_holder, $hdl_holder);
if (ie6mode) {
$sel.css({
overflowY: 'hidden'
});
}
var bound = options.boundary;
var $trk = newTracker().width(boundx + (bound * 2)).height(boundy + (bound * 2)).css({
position: 'absolute',
top: px(-bound),
left: px(-bound),
zIndex: 290
}).mousedown(newSelection);
/* }}} */
// Set more variables {{{
var bgopacity = options.bgOpacity,
xlimit, ylimit, xmin, ymin, xscale, yscale, enabled = true,
btndown, animating, shift_down;
docOffset = getPos($img);
// }}}
// }}}
// Internal Modules {{{
// Touch Module {{{
var Touch = (function () {
// Touch support detection function adapted (under MIT License)
// from code by Jeffrey Sambells - http://github.com/iamamused/
function hasTouchSupport() {
var support = {},
events = ['touchstart', 'touchmove', 'touchend'],
el = document.createElement('div'), i;
try {
for(i=0; i<events.length; i++) {
var eventName = events[i];
eventName = 'on' + eventName;
var isSupported = (eventName in el);
if (!isSupported) {
el.setAttribute(eventName, 'return;');
isSupported = typeof el[eventName] == 'function';
}
support[events[i]] = isSupported;
}
return support.touchstart && support.touchend && support.touchmove;
}
catch(err) {
return false;
}
}
function detectSupport() {
if ((options.touchSupport === true) || (options.touchSupport === false)) return options.touchSupport;
else return hasTouchSupport();
}
return {
createDragger: function (ord) {
return function (e) {
e.pageX = e.originalEvent.changedTouches[0].pageX;
e.pageY = e.originalEvent.changedTouches[0].pageY;
if (options.disabled) {
return false;
}
if ((ord === 'move') && !options.allowMove) {
return false;
}
btndown = true;
startDragMode(ord, mouseAbs(e));
e.stopPropagation();
e.preventDefault();
return false;
};
},
newSelection: function (e) {
e.pageX = e.originalEvent.changedTouches[0].pageX;
e.pageY = e.originalEvent.changedTouches[0].pageY;
return newSelection(e);
},
isSupported: hasTouchSupport,
support: detectSupport()
};
}());
// }}}
// Coords Module {{{
var Coords = (function () {
var x1 = 0,
y1 = 0,
x2 = 0,
y2 = 0,
ox, oy;
function setPressed(pos) //{{{
{
pos = rebound(pos);
x2 = x1 = pos[0];
y2 = y1 = pos[1];
}
//}}}
function setCurrent(pos) //{{{
{
pos = rebound(pos);
ox = pos[0] - x2;
oy = pos[1] - y2;
x2 = pos[0];
y2 = pos[1];
}
//}}}
function getOffset() //{{{
{
return [ox, oy];
}
//}}}
function moveOffset(offset) //{{{
{
var ox = offset[0],
oy = offset[1];
if (0 > x1 + ox) {
ox -= ox + x1;
}
if (0 > y1 + oy) {
oy -= oy + y1;
}
if (boundy < y2 + oy) {
oy += boundy - (y2 + oy);
}
if (boundx < x2 + ox) {
ox += boundx - (x2 + ox);
}
x1 += ox;
x2 += ox;
y1 += oy;
y2 += oy;
}
//}}}
function getCorner(ord) //{{{
{
var c = getFixed();
switch (ord) {
case 'ne':
return [c.x2, c.y];
case 'nw':
return [c.x, c.y];
case 'se':
return [c.x2, c.y2];
case 'sw':
return [c.x, c.y2];
}
}
//}}}
function getFixed() //{{{
{
if (!options.aspectRatio) {
return getRect();
}
// This function could use some optimization I think...
var aspect = options.aspectRatio,
min_x = options.minSize[0] / xscale,
//min_y = options.minSize[1]/yscale,
max_x = options.maxSize[0] / xscale,
max_y = options.maxSize[1] / yscale,
rw = x2 - x1,
rh = y2 - y1,
rwa = Math.abs(rw),
rha = Math.abs(rh),
real_ratio = rwa / rha,
xx, yy;
if (max_x === 0) {
max_x = boundx * 10;
}
if (max_y === 0) {
max_y = boundy * 10;
}
if (real_ratio < aspect) {
yy = y2;
w = rha * aspect;
xx = rw < 0 ? x1 - w : w + x1;
if (xx < 0) {
xx = 0;
h = Math.abs((xx - x1) / aspect);
yy = rh < 0 ? y1 - h : h + y1;
} else if (xx > boundx) {
xx = boundx;
h = Math.abs((xx - x1) / aspect);
yy = rh < 0 ? y1 - h : h + y1;
}
} else {
xx = x2;
h = rwa / aspect;
yy = rh < 0 ? y1 - h : y1 + h;
if (yy < 0) {
yy = 0;
w = Math.abs((yy - y1) * aspect);
xx = rw < 0 ? x1 - w : w + x1;
} else if (yy > boundy) {
yy = boundy;
w = Math.abs(yy - y1) * aspect;
xx = rw < 0 ? x1 - w : w + x1;
}
}
// Magic %-)
if (xx > x1) { // right side
if (xx - x1 < min_x) {
xx = x1 + min_x;
} else if (xx - x1 > max_x) {
xx = x1 + max_x;
}
if (yy > y1) {
yy = y1 + (xx - x1) / aspect;
} else {
yy = y1 - (xx - x1) / aspect;
}
} else if (xx < x1) { // left side
if (x1 - xx < min_x) {
xx = x1 - min_x;
} else if (x1 - xx > max_x) {
xx = x1 - max_x;
}
if (yy > y1) {
yy = y1 + (x1 - xx) / aspect;
} else {
yy = y1 - (x1 - xx) / aspect;
}
}
if (xx < 0) {
x1 -= xx;
xx = 0;
} else if (xx > boundx) {
x1 -= xx - boundx;
xx = boundx;
}
if (yy < 0) {
y1 -= yy;
yy = 0;
} else if (yy > boundy) {
y1 -= yy - boundy;
yy = boundy;
}
return makeObj(flipCoords(x1, y1, xx, yy));
}
//}}}
function rebound(p) //{{{
{
if (p[0] < 0) {
p[0] = 0;
}
if (p[1] < 0) {
p[1] = 0;
}
if (p[0] > boundx) {
p[0] = boundx;
}
if (p[1] > boundy) {
p[1] = boundy;
}
return [p[0], p[1]];
}
//}}}
function flipCoords(x1, y1, x2, y2) //{{{
{
var xa = x1,
xb = x2,
ya = y1,
yb = y2;
if (x2 < x1) {
xa = x2;
xb = x1;
}
if (y2 < y1) {
ya = y2;
yb = y1;
}
return [Math.round(xa), Math.round(ya), Math.round(xb), Math.round(yb)];
}
//}}}
function getRect() //{{{
{
var xsize = x2 - x1,
ysize = y2 - y1,
delta;
if (xlimit && (Math.abs(xsize) > xlimit)) {
x2 = (xsize > 0) ? (x1 + xlimit) : (x1 - xlimit);
}
if (ylimit && (Math.abs(ysize) > ylimit)) {
y2 = (ysize > 0) ? (y1 + ylimit) : (y1 - ylimit);
}
if (ymin / yscale && (Math.abs(ysize) < ymin / yscale)) {
y2 = (ysize > 0) ? (y1 + ymin / yscale) : (y1 - ymin / yscale);
}
if (xmin / xscale && (Math.abs(xsize) < xmin / xscale)) {
x2 = (xsize > 0) ? (x1 + xmin / xscale) : (x1 - xmin / xscale);
}
if (x1 < 0) {
x2 -= x1;
x1 -= x1;
}
if (y1 < 0) {
y2 -= y1;
y1 -= y1;
}
if (x2 < 0) {
x1 -= x2;
x2 -= x2;
}
if (y2 < 0) {
y1 -= y2;
y2 -= y2;
}
if (x2 > boundx) {
delta = x2 - boundx;
x1 -= delta;
x2 -= delta;
}
if (y2 > boundy) {
delta = y2 - boundy;
y1 -= delta;
y2 -= delta;
}
if (x1 > boundx) {
delta = x1 - boundy;
y2 -= delta;
y1 -= delta;
}
if (y1 > boundy) {
delta = y1 - boundy;
y2 -= delta;
y1 -= delta;
}
return makeObj(flipCoords(x1, y1, x2, y2));
}
//}}}
function makeObj(a) //{{{
{
return {
x: a[0],
y: a[1],
x2: a[2],
y2: a[3],
w: a[2] - a[0],
h: a[3] - a[1]
};
}
//}}}
return {
flipCoords: flipCoords,
setPressed: setPressed,
setCurrent: setCurrent,
getOffset: getOffset,
moveOffset: moveOffset,
getCorner: getCorner,
getFixed: getFixed
};
}());
//}}}
// Selection Module {{{
var Selection = (function () {
var awake, hdep = 370;
var borders = {};
var handle = {};
var seehandles = false;
var hhs = options.handleOffset;
// Private Methods
function insertBorder(type) //{{{
{
var jq = $('<div />').css({
position: 'absolute',
opacity: options.borderOpacity
}).addClass(cssClass(type));
$img_holder.append(jq);
return jq;
}
//}}}
function dragDiv(ord, zi) //{{{
{
var jq = $('<div />').mousedown(createDragger(ord)).css({
cursor: ord + '-resize',
position: 'absolute',
zIndex: zi
});
if (Touch.support) {
jq.bind('touchstart', Touch.createDragger(ord));
}
$hdl_holder.append(jq);
return jq;
}
//}}}
function insertHandle(ord) //{{{
{
return dragDiv(ord, hdep++).css({
top: px(-hhs + 1),
left: px(-hhs + 1),
opacity: options.handleOpacity
}).addClass(cssClass('handle'));
}
//}}}
function insertDragbar(ord) //{{{
{
var s = options.handleSize,
h = s,
w = s,
t = hhs,
l = hhs;
switch (ord) {
case 'n':
case 's':
w = pct(100);
break;
case 'e':
case 'w':
h = pct(100);
break;
}
return dragDiv(ord, hdep++).width(w).height(h).css({
top: px(-t + 1),
left: px(-l + 1)
});
}
//}}}
function createHandles(li) //{{{
{
var i;
for (i = 0; i < li.length; i++) {
handle[li[i]] = insertHandle(li[i]);
}
}
//}}}
function moveHandles(c) //{{{
{
var midvert = Math.round((c.h / 2) - hhs),
midhoriz = Math.round((c.w / 2) - hhs),
north = -hhs + 1,
west = -hhs + 1,
east = c.w - hhs,
south = c.h - hhs,
x, y;
if (handle.e) {
handle.e.css({
top: px(midvert),
left: px(east)
});
handle.w.css({
top: px(midvert)
});
handle.s.css({
top: px(south),
left: px(midhoriz)
});
handle.n.css({
left: px(midhoriz)
});
}
if (handle.ne) {
handle.ne.css({
left: px(east)
});
handle.se.css({
top: px(south),
left: px(east)
});
handle.sw.css({
top: px(south)
});
}
if (handle.b) {
handle.b.css({
top: px(south)
});
handle.r.css({
left: px(east)
});
}
}
//}}}
function moveto(x, y) //{{{
{
$img2.css({
top: px(-y),
left: px(-x)
});
$sel.css({
top: px(y),
left: px(x)
});
}
//}}}
function resize(w, h) //{{{
{
$sel.width(w).height(h);
}
//}}}
function refresh() //{{{
{
var c = Coords.getFixed();
Coords.setPressed([c.x, c.y]);
Coords.setCurrent([c.x2, c.y2]);
updateVisible();
}
//}}}
// Internal Methods
function updateVisible() //{{{
{
if (awake) {
return update();
}
}
//}}}
function update() //{{{
{
var c = Coords.getFixed();
resize(c.w, c.h);
moveto(c.x, c.y);
/*
options.drawBorders &&
borders.right.css({ left: px(c.w-1) }) &&
borders.bottom.css({ top: px(c.h-1) });
*/
if (seehandles) {
moveHandles(c);
}
if (!awake) {
show();
}
options.onChange.call(api, unscale(c));
}
//}}}
function show() //{{{
{
$sel.show();
if (options.bgFade) {
$img.fadeTo(options.fadeTime, bgopacity);
} else {
$img.css('opacity', bgopacity);
}
awake = true;
}
//}}}
function release() //{{{
{
disableHandles();
$sel.hide();
if (options.bgFade) {
$img.fadeTo(options.fadeTime, 1);
} else {
$img.css('opacity', 1);
}
awake = false;
options.onRelease.call(api);
}
//}}}
function showHandles() //{{{
{
if (seehandles) {
moveHandles(Coords.getFixed());
$hdl_holder.show();
}
}
//}}}
function enableHandles() //{{{
{
seehandles = true;
if (options.allowResize) {
moveHandles(Coords.getFixed());
$hdl_holder.show();
return true;
}
}
//}}}
function disableHandles() //{{{
{
seehandles = false;
$hdl_holder.hide();
}
//}}}
function animMode(v) //{{{
{
if (animating === v) {
disableHandles();
} else {
enableHandles();
}
}
//}}}
function done() //{{{
{
animMode(false);
refresh();
}
//}}}
/* Insert draggable elements {{{*/
// Insert border divs for outline
if (options.drawBorders) {
borders = {
top: insertBorder('hline'),
bottom: insertBorder('hline bottom'),
left: insertBorder('vline'),
right: insertBorder('vline right')
};
}
// Insert handles on edges
if (options.dragEdges) {
handle.t = insertDragbar('n');
handle.b = insertDragbar('s');
handle.r = insertDragbar('e');
handle.l = insertDragbar('w');
}
// Insert side and corner handles
if (options.sideHandles) {
createHandles(['n', 's', 'e', 'w']);
}
if (options.cornerHandles) {
createHandles(['sw', 'nw', 'ne', 'se']);
}
//}}}
var $track = newTracker().mousedown(createDragger('move')).css({
cursor: 'move',
position: 'absolute',
zIndex: 360
});
if (Touch.support) {
$track.bind('touchstart.jcrop', Touch.createDragger('move'));
}
$img_holder.append($track);
disableHandles();
return {
updateVisible: updateVisible,
update: update,
release: release,
refresh: refresh,
isAwake: function () {
return awake;
},
setCursor: function (cursor) {
$track.css('cursor', cursor);
},
enableHandles: enableHandles,
enableOnly: function () {
seehandles = true;
},
showHandles: showHandles,
disableHandles: disableHandles,
animMode: animMode,
done: done
};
}());
//}}}
// Tracker Module {{{
var Tracker = (function () {
var onMove = function () {},
onDone = function () {},
trackDoc = options.trackDocument;
function toFront() //{{{
{
$trk.css({
zIndex: 450
});
if (trackDoc) {
$(document)
.bind('mousemove',trackMove)
.bind('mouseup',trackUp);
}
}
//}}}
function toBack() //{{{
{
$trk.css({
zIndex: 290
});
if (trackDoc) {
$(document)
.unbind('mousemove', trackMove)
.unbind('mouseup', trackUp);
}
}
//}}}
function trackMove(e) //{{{
{
onMove(mouseAbs(e));
return false;
}
//}}}
function trackUp(e) //{{{
{
e.preventDefault();
e.stopPropagation();
if (btndown) {
btndown = false;
onDone(mouseAbs(e));
if (Selection.isAwake()) {
options.onSelect.call(api, unscale(Coords.getFixed()));
}
toBack();
onMove = function () {};
onDone = function () {};
}
return false;
}
//}}}
function activateHandlers(move, done) //{{{
{
btndown = true;
onMove = move;
onDone = done;
toFront();
return false;
}
//}}}
function trackTouchMove(e) //{{{
{
e.pageX = e.originalEvent.changedTouches[0].pageX;
e.pageY = e.originalEvent.changedTouches[0].pageY;
return trackMove(e);
}
//}}}
function trackTouchEnd(e) //{{{
{
e.pageX = e.originalEvent.changedTouches[0].pageX;
e.pageY = e.originalEvent.changedTouches[0].pageY;
return trackUp(e);
}
//}}}
function setCursor(t) //{{{
{
$trk.css('cursor', t);
}
//}}}
if (Touch.support) {
$(document)
.bind('touchmove', trackTouchMove)
.bind('touchend', trackTouchEnd);
}
if (!trackDoc) {
$trk.mousemove(trackMove).mouseup(trackUp).mouseout(trackUp);
}
$img.before($trk);
return {
activateHandlers: activateHandlers,
setCursor: setCursor
};
}());
//}}}
// KeyManager Module {{{
var KeyManager = (function () {
var $keymgr = $('<input type="radio" />').css({
position: 'fixed',
left: '-120px',
width: '12px'
}),
$keywrap = $('<div />').css({
position: 'absolute',
overflow: 'hidden'
}).append($keymgr);
function watchKeys() //{{{
{
if (options.keySupport) {
$keymgr.show();
$keymgr.focus();
}
}
//}}}
function onBlur(e) //{{{
{
$keymgr.hide();
}
//}}}
function doNudge(e, x, y) //{{{
{
if (options.allowMove) {
Coords.moveOffset([x, y]);
Selection.updateVisible();
}
e.preventDefault();
e.stopPropagation();
}
//}}}
function parseKey(e) //{{{
{
if (e.ctrlKey) {
return true;
}
shift_down = e.shiftKey ? true : false;
var nudge = shift_down ? 10 : 1;
switch (e.keyCode) {
case 37:
doNudge(e, -nudge, 0);
break;
case 39:
doNudge(e, nudge, 0);
break;
case 38:
doNudge(e, 0, -nudge);
break;
case 40:
doNudge(e, 0, nudge);
break;
case 27:
Selection.release();
break;
case 9:
return true;
}
return false;
}
//}}}
if (options.keySupport) {
$keymgr.keydown(parseKey).blur(onBlur);
if (ie6mode || !options.fixedSupport) {
$keymgr.css({
position: 'absolute',
left: '-20px'
});
$keywrap.append($keymgr).insertBefore($img);
} else {
$keymgr.insertBefore($img);
}
}
return {
watchKeys: watchKeys
};
}());
//}}}
// }}}
// API methods {{{
function setClass(cname) //{{{
{
$div.removeClass().addClass(cssClass('holder')).addClass(cname);
}
//}}}
function animateTo(a, callback) //{{{
{
var x1 = parseInt(a[0], 10) / xscale,
y1 = parseInt(a[1], 10) / yscale,
x2 = parseInt(a[2], 10) / xscale,
y2 = parseInt(a[3], 10) / yscale;
if (animating) {
return;
}
var animto = Coords.flipCoords(x1, y1, x2, y2),
c = Coords.getFixed(),
initcr = [c.x, c.y, c.x2, c.y2],
animat = initcr,
interv = options.animationDelay,
ix1 = animto[0] - initcr[0],
iy1 = animto[1] - initcr[1],
ix2 = animto[2] - initcr[2],
iy2 = animto[3] - initcr[3],
pcent = 0,
velocity = options.swingSpeed;
x = animat[0];
y = animat[1];
x2 = animat[2];
y2 = animat[3];
Selection.animMode(true);
var anim_timer;
function queueAnimator() {
window.setTimeout(animator, interv);
}
var animator = (function () {
return function () {
pcent += (100 - pcent) / velocity;
animat[0] = x + ((pcent / 100) * ix1);
animat[1] = y + ((pcent / 100) * iy1);
animat[2] = x2 + ((pcent / 100) * ix2);
animat[3] = y2 + ((pcent / 100) * iy2);
if (pcent >= 99.8) {
pcent = 100;
}
if (pcent < 100) {
setSelectRaw(animat);
queueAnimator();
} else {
Selection.done();
if (typeof(callback) === 'function') {
callback.call(api);
}
}
};
}());
queueAnimator();
}
//}}}
function setSelect(rect) //{{{
{
setSelectRaw([
parseInt(rect[0], 10) / xscale, parseInt(rect[1], 10) / yscale, parseInt(rect[2], 10) / xscale, parseInt(rect[3], 10) / yscale]);
}
//}}}
function setSelectRaw(l) //{{{
{
Coords.setPressed([l[0], l[1]]);
Coords.setCurrent([l[2], l[3]]);
Selection.update();
}
//}}}
function tellSelect() //{{{
{
return unscale(Coords.getFixed());
}
//}}}
function tellScaled() //{{{
{
return Coords.getFixed();
}
//}}}
function setOptionsNew(opt) //{{{
{
setOptions(opt);
interfaceUpdate();
}
//}}}
function disableCrop() //{{{
{
options.disabled = true;
Selection.disableHandles();
Selection.setCursor('default');
Tracker.setCursor('default');
}
//}}}
function enableCrop() //{{{
{
options.disabled = false;
interfaceUpdate();
}
//}}}
function cancelCrop() //{{{
{
Selection.done();
Tracker.activateHandlers(null, null);
}
//}}}
function destroy() //{{{
{
$div.remove();
$origimg.show();
$(obj).removeData('Jcrop');
}
//}}}
function setImage(src, callback) //{{{
{
Selection.release();
disableCrop();
var img = new Image();
img.onload = function () {
var iw = img.width;
var ih = img.height;
var bw = options.boxWidth;
var bh = options.boxHeight;
$img.width(iw).height(ih);
$img.attr('src', src);
$img2.attr('src', src);
presize($img, bw, bh);
boundx = $img.width();
boundy = $img.height();
$img2.width(boundx).height(boundy);
$trk.width(boundx + (bound * 2)).height(boundy + (bound * 2));
$div.width(boundx).height(boundy);
enableCrop();
if (typeof(callback) === 'function') {
callback.call(api);
}
};
img.src = src;
}
//}}}
function interfaceUpdate(alt) //{{{
// This method tweaks the interface based on options object.
// Called when options are changed and at end of initialization.
{
if (options.allowResize) {
if (alt) {
Selection.enableOnly();
} else {
Selection.enableHandles();
}
} else {
Selection.disableHandles();
}
Tracker.setCursor(options.allowSelect ? 'crosshair' : 'default');
Selection.setCursor(options.allowMove ? 'move' : 'default');
if (options.hasOwnProperty('setSelect')) {
setSelect(options.setSelect);
Selection.done();
delete(options.setSelect);
}
if (options.hasOwnProperty('trueSize')) {
xscale = options.trueSize[0] / boundx;
yscale = options.trueSize[1] / boundy;
}
if (options.hasOwnProperty('bgColor')) {
if (supportsColorFade() && options.fadeTime) {
$div.animate({
backgroundColor: options.bgColor
}, {
queue: false,
duration: options.fadeTime
});
} else {
$div.css('backgroundColor', options.bgColor);
}
delete(options.bgColor);
}
if (options.hasOwnProperty('bgOpacity')) {
bgopacity = options.bgOpacity;
if (Selection.isAwake()) {
if (options.fadeTime) {
$img.fadeTo(options.fadeTime, bgopacity);
} else {
$div.css('opacity', options.opacity);
}
}
delete(options.bgOpacity);
}
xlimit = options.maxSize[0] || 0;
ylimit = options.maxSize[1] || 0;
xmin = options.minSize[0] || 0;
ymin = options.minSize[1] || 0;
if (options.hasOwnProperty('outerImage')) {
$img.attr('src', options.outerImage);
delete(options.outerImage);
}
Selection.refresh();
}
//}}}
//}}}
if (Touch.support) {
$trk.bind('touchstart', Touch.newSelection);
}
$hdl_holder.hide();
interfaceUpdate(true);
var api = {
setImage: setImage,
animateTo: animateTo,
setSelect: setSelect,
setOptions: setOptionsNew,
tellSelect: tellSelect,
tellScaled: tellScaled,
setClass: setClass,
disable: disableCrop,
enable: enableCrop,
cancel: cancelCrop,
release: Selection.release,
destroy: destroy,
focus: KeyManager.watchKeys,
getBounds: function () {
return [boundx * xscale, boundy * yscale];
},
getWidgetSize: function () {
return [boundx, boundy];
},
getScaleFactor: function () {
return [xscale, yscale];
},
ui: {
holder: $div,
selection: $sel
}
};
if ($.browser.msie) {
$div.bind('selectstart', function () {
return false;
});
}
$origimg.data('Jcrop', api);
return api;
};
$.fn.Jcrop = function (options, callback) //{{{
{
function attachWhenDone(from) //{{{
{
var opt = (typeof(options) === 'object') ? options : {};
var loadsrc = opt.useImg || from.src;
var img = new Image();
img.onload = function () {
function attachJcrop() {
var api = $.Jcrop(from, opt);
if (typeof(callback) === 'function') {
callback.call(api);
}
}
function attachAttempt() {
if (!img.width || !img.height) {
window.setTimeout(attachAttempt, 50);
} else {
attachJcrop();
}
}
window.setTimeout(attachAttempt, 50);
};
img.src = loadsrc;
}
//}}}
// Iterate over each object, attach Jcrop
this.each(function () {
// If we've already attached to this object
if ($(this).data('Jcrop')) {
// The API can be requested this way (undocumented)
if (options === 'api') {
return $(this).data('Jcrop');
}
// Otherwise, we just reset the options...
else {
$(this).data('Jcrop').setOptions(options);
}
}
// If we haven't been attached, preload and attach
else {
attachWhenDone(this);
}
});
// Return "this" so the object is chainable (jQuery-style)
return this;
};
//}}}
// Global Defaults {{{
$.Jcrop.defaults = {
// Basic Settings
allowSelect: true,
allowMove: true,
allowResize: true,
trackDocument: true,
// Styling Options
baseClass: 'jcrop',
addClass: null,
bgColor: 'black',
bgOpacity: 0.6,
bgFade: false,
borderOpacity: 0.4,
handleOpacity: 0.5,
handleSize: 9,
handleOffset: 5,
aspectRatio: 0,
keySupport: true,
cornerHandles: true,
sideHandles: true,
drawBorders: true,
dragEdges: true,
fixedSupport: true,
touchSupport: null,
boxWidth: 0,
boxHeight: 0,
boundary: 2,
fadeTime: 400,
animationDelay: 20,
swingSpeed: 3,
minSelect: [0, 0],
maxSize: [0, 0],
minSize: [0, 0],
// Callbacks / Event Handlers
onChange: function () {},
onSelect: function () {},
onRelease: function () {}
};
// }}}
}(jQuery));
/*
* A time picker for jQuery
*
* Dual licensed under the MIT and GPL licenses.
* Copyright (c) 2009 Anders Fajerson
* @name timePicker
* @author Anders Fajerson (http://perifer.se)
* @example $("#mytime").timePicker();
* @example $("#mytime").timePicker({step:30, startTime:"15:00", endTime:"18:00"});
*
* Based on timePicker by Sam Collet (http://www.texotela.co.uk/code/jquery/timepicker/)
*
* Options:
* step: # of minutes to step the time by
* startTime: beginning of the range of acceptable times
* endTime: end of the range of acceptable times
* separator: separator string to use between hours and minutes (e.g. ':')
* show24Hours: use a 24-hour scheme
*/
(function($){
$.fn.timePicker = function(options) {
// Build main options before element iteration
var settings = $.extend({}, $.fn.timePicker.defaults, options);
return this.each(function() {
$.timePicker(this, settings);
});
};
$.timePicker = function (elm, settings) {
var e = $(elm)[0];
return e.timePicker || (e.timePicker = new jQuery._timePicker(e, settings));
};
$.timePicker.version = '0.3';
$._timePicker = function(elm, settings) {
var tpOver = false;
var keyDown = false;
var startTime = timeToDate(settings.startTime, settings);
var endTime = timeToDate(settings.endTime, settings);
var selectedClass = "selected";
var selectedSelector = "li." + selectedClass;
$(elm).attr('autocomplete', 'OFF'); // Disable browser autocomplete
var times = [];
var time = new Date(startTime); // Create a new date object.
while(time <= endTime) {
times[times.length] = formatTime(time, settings);
time = new Date(time.setMinutes(time.getMinutes() + settings.step));
}
var $tpDiv = $('<div class="time-picker'+ (settings.show24Hours ? '' : ' time-picker-12hours') +'"></div>');
var $tpList = $('<ul></ul>');
// Build the list.
for(var i = 0; i < times.length; i++) {
$tpList.append("<li>" + times[i] + "</li>");
}
$tpDiv.append($tpList);
// Append the timPicker to the body and position it.
$tpDiv.appendTo('body').hide();
// Store the mouse state, used by the blur event. Use mouseover instead of
// mousedown since Opera fires blur before mousedown.
$tpDiv.mouseover(function() {
tpOver = true;
}).mouseout(function() {
tpOver = false;
});
$("li", $tpList).mouseover(function() {
if (!keyDown) {
$(selectedSelector, $tpDiv).removeClass(selectedClass);
$(this).addClass(selectedClass);
}
}).mousedown(function() {
tpOver = true;
}).click(function() {
setTimeVal(elm, this, $tpDiv, settings);
tpOver = false;
});
var showPicker = function() {
if ($tpDiv.is(":visible")) {
return false;
}
$("li", $tpDiv).removeClass(selectedClass);
// Position
var elmOffset = $(elm).offset();
$tpDiv.css({'top':elmOffset.top + elm.offsetHeight, 'left':elmOffset.left});
// Show picker. This has to be done before scrollTop is set since that
// can't be done on hidden elements.
$tpDiv.show();
// Try to find a time in the list that matches the entered time.
var time = elm.value ? timeStringToDate(elm.value, settings) : startTime;
var startMin = startTime.getHours() * 60 + startTime.getMinutes();
var min = (time.getHours() * 60 + time.getMinutes()) - startMin;
var steps = Math.round(min / settings.step);
var roundTime = normaliseTime(new Date(0, 0, 0, 0, (steps * settings.step + startMin), 0));
roundTime = (startTime < roundTime && roundTime <= endTime) ? roundTime : startTime;
var $matchedTime = $("li:contains(" + formatTime(roundTime, settings) + ")", $tpDiv);
if ($matchedTime.length) {
$matchedTime.addClass(selectedClass);
// Scroll to matched time.
$tpDiv[0].scrollTop = $matchedTime[0].offsetTop;
}
return true;
};
// Attach to click as well as focus so timePicker can be shown again when
// clicking on the input when it already has focus.
$(elm).focus(showPicker).click(showPicker);
// Hide timepicker on blur
$(elm).blur(function() {
if (!tpOver) {
$tpDiv.hide();
}
});
// Keypress doesn't repeat on Safari for non-text keys.
// Keydown doesn't repeat on Firefox and Opera on Mac.
// Using kepress for Opera and Firefox and keydown for the rest seems to
// work with up/down/enter/esc.
var event = ($.browser.opera || $.browser.mozilla) ? 'keypress' : 'keydown';
$(elm)[event](function(e) {
var $selected;
keyDown = true;
var top = $tpDiv[0].scrollTop;
switch (e.keyCode) {
case 38: // Up arrow.
// Just show picker if it's hidden.
if (showPicker()) {
return false;
};
$selected = $(selectedSelector, $tpList);
var prev = $selected.prev().addClass(selectedClass)[0];
if (prev) {
$selected.removeClass(selectedClass);
// Scroll item into view.
if (prev.offsetTop < top) {
$tpDiv[0].scrollTop = top - prev.offsetHeight;
}
}
else {
// Loop to next item.
$selected.removeClass(selectedClass);
prev = $("li:last", $tpList).addClass(selectedClass)[0];
$tpDiv[0].scrollTop = prev.offsetTop - prev.offsetHeight;
}
return false;
break;
case 40: // Down arrow, similar in behaviour to up arrow.
if (showPicker()) {
return false;
};
$selected = $(selectedSelector, $tpList);
var next = $selected.next().addClass(selectedClass)[0];
if (next) {
$selected.removeClass(selectedClass);
if (next.offsetTop + next.offsetHeight > top + $tpDiv[0].offsetHeight) {
$tpDiv[0].scrollTop = top + next.offsetHeight;
}
}
else {
$selected.removeClass(selectedClass);
next = $("li:first", $tpList).addClass(selectedClass)[0];
$tpDiv[0].scrollTop = 0;
}
return false;
break;
case 13: // Enter
if ($tpDiv.is(":visible")) {
var sel = $(selectedSelector, $tpList)[0];
setTimeVal(elm, sel, $tpDiv, settings);
}
return false;
break;
case 27: // Esc
$tpDiv.hide();
return false;
break;
}
return true;
});
$(elm).keyup(function(e) {
keyDown = false;
});
// Helper function to get an inputs current time as Date object.
// Returns a Date object.
this.getTime = function() {
return timeStringToDate(elm.value, settings);
};
// Helper function to set a time input.
// Takes a Date object or string.
this.setTime = function(time) {
elm.value = formatTime(timeToDate(time, settings), settings);
// Trigger element's change events.
$(elm).change();
};
}; // End fn;
// Plugin defaults.
$.fn.timePicker.defaults = {
step:30,
startTime: new Date(0, 0, 0, 0, 0, 0),
endTime: new Date(0, 0, 0, 23, 30, 0),
separator: ':',
show24Hours: true
};
// Private functions.
function setTimeVal(elm, sel, $tpDiv, settings) {
// Update input field
elm.value = $(sel).text();
// Trigger element's change events.
$(elm).change();
// Keep focus for all but IE (which doesn't like it)
if (!$.browser.msie) {
elm.focus();
}
// Hide picker
$tpDiv.hide();
}
function formatTime(time, settings) {
var h = time.getHours();
var hours = settings.show24Hours ? h : (((h + 11) % 12) + 1);
var minutes = time.getMinutes();
return formatNumber(hours) + settings.separator + formatNumber(minutes) + (settings.show24Hours ? '' : ((h < 12) ? ' AM' : ' PM'));
}
function formatNumber(value) {
return (value < 10 ? '0' : '') + value;
}
function timeToDate(input, settings) {
return (typeof input == 'object') ? normaliseTime(input) : timeStringToDate(input, settings);
}
function timeStringToDate(input, settings) {
if (input) {
var array = input.split(settings.separator);
var hours = parseFloat(array[0]);
var minutes = parseFloat(array[1]);
// Convert AM/PM hour to 24-hour format.
if (!settings.show24Hours) {
if (hours === 12 && input.indexOf('AM') !== -1) {
hours = 0;
}
else if (hours !== 12 && input.indexOf('PM') !== -1) {
hours += 12;
}
}
var time = new Date(0, 0, 0, hours, minutes, 0);
return normaliseTime(time);
}
return null;
}
/* Normalise time object to a common date. */
function normaliseTime(time) {
time.setFullYear(2001);
time.setMonth(0);
time.setDate(0);
return time;
}
})(jQuery);
/*!
* jQuery UI @VERSION
*
* Copyright 2012, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI
*/
(function( $, undefined ) {
// prevent duplicate loading
// this is only a problem because we proxy existing functions
// and we don't want to double proxy them
$.ui = $.ui || {};
if ( $.ui.version ) {
return;
}
$.extend( $.ui, {
version: "@VERSION",
keyCode: {
ALT: 18,
BACKSPACE: 8,
CAPS_LOCK: 20,
COMMA: 188,
COMMAND: 91,
COMMAND_LEFT: 91, // COMMAND
COMMAND_RIGHT: 93,
CONTROL: 17,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
MENU: 93, // COMMAND_RIGHT
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SHIFT: 16,
SPACE: 32,
TAB: 9,
UP: 38,
WINDOWS: 91 // COMMAND
}
});
// plugins
$.fn.extend({
propAttr: $.fn.prop || $.fn.attr,
_focus: $.fn.focus,
focus: function( delay, fn ) {
return typeof delay === "number" ?
this.each(function() {
var elem = this;
setTimeout(function() {
$( elem ).focus();
if ( fn ) {
fn.call( elem );
}
}, delay );
}) :
this._focus.apply( this, arguments );
},
scrollParent: function() {
var scrollParent;
if (($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
scrollParent = this.parents().filter(function() {
return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
}).eq(0);
} else {
scrollParent = this.parents().filter(function() {
return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
}).eq(0);
}
return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
},
zIndex: function( zIndex ) {
if ( zIndex !== undefined ) {
return this.css( "zIndex", zIndex );
}
if ( this.length ) {
var elem = $( this[ 0 ] ), position, value;
while ( elem.length && elem[ 0 ] !== document ) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css( "position" );
if ( position === "absolute" || position === "relative" || position === "fixed" ) {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt( elem.css( "zIndex" ), 10 );
if ( !isNaN( value ) && value !== 0 ) {
return value;
}
}
elem = elem.parent();
}
}
return 0;
},
disableSelection: function() {
return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
".ui-disableSelection", function( event ) {
event.preventDefault();
});
},
enableSelection: function() {
return this.unbind( ".ui-disableSelection" );
}
});
$.each( [ "Width", "Height" ], function( i, name ) {
var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
type = name.toLowerCase(),
orig = {
innerWidth: $.fn.innerWidth,
innerHeight: $.fn.innerHeight,
outerWidth: $.fn.outerWidth,
outerHeight: $.fn.outerHeight
};
function reduce( elem, size, border, margin ) {
$.each( side, function() {
size -= parseFloat( $.curCSS( elem, "padding" + this, true) ) || 0;
if ( border ) {
size -= parseFloat( $.curCSS( elem, "border" + this + "Width", true) ) || 0;
}
if ( margin ) {
size -= parseFloat( $.curCSS( elem, "margin" + this, true) ) || 0;
}
});
return size;
}
$.fn[ "inner" + name ] = function( size ) {
if ( size === undefined ) {
return orig[ "inner" + name ].call( this );
}
return this.each(function() {
$( this ).css( type, reduce( this, size ) + "px" );
});
};
$.fn[ "outer" + name] = function( size, margin ) {
if ( typeof size !== "number" ) {
return orig[ "outer" + name ].call( this, size );
}
return this.each(function() {
$( this).css( type, reduce( this, size, true, margin ) + "px" );
});
};
});
// selectors
function focusable( element, isTabIndexNotNaN ) {
var nodeName = element.nodeName.toLowerCase();
if ( "area" === nodeName ) {
var map = element.parentNode,
mapName = map.name,
img;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap=#" + mapName + "]" )[0];
return !!img && visible( img );
}
return ( /input|select|textarea|button|object/.test( nodeName )
? !element.disabled
: "a" == nodeName
? element.href || isTabIndexNotNaN
: isTabIndexNotNaN)
// the element and all of its ancestors must be visible
&& visible( element );
}
function visible( element ) {
return !$( element ).parents().andSelf().filter(function() {
return $.curCSS( this, "visibility" ) === "hidden" ||
$.expr.filters.hidden( this );
}).length;
}
$.extend( $.expr[ ":" ], {
data: function( elem, i, match ) {
return !!$.data( elem, match[ 3 ] );
},
focusable: function( element ) {
return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
},
tabbable: function( element ) {
var tabIndex = $.attr( element, "tabindex" ),
isTabIndexNaN = isNaN( tabIndex );
return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
}
});
// support
$(function() {
var body = document.body,
div = body.appendChild( div = document.createElement( "div" ) );
// access offsetHeight before setting the style to prevent a layout bug
// in IE 9 which causes the elemnt to continue to take up space even
// after it is removed from the DOM (#8026)
div.offsetHeight;
$.extend( div.style, {
minHeight: "100px",
height: "auto",
padding: 0,
borderWidth: 0
});
$.support.minHeight = div.offsetHeight === 100;
$.support.selectstart = "onselectstart" in div;
// set display to none to avoid a layout bug in IE
// http://dev.jquery.com/ticket/4014
body.removeChild( div ).style.display = "none";
});
// deprecated
$.extend( $.ui, {
// $.ui.plugin is deprecated. Use the proxy pattern instead.
plugin: {
add: function( module, option, set ) {
var proto = $.ui[ module ].prototype;
for ( var i in set ) {
proto.plugins[ i ] = proto.plugins[ i ] || [];
proto.plugins[ i ].push( [ option, set[ i ] ] );
}
},
call: function( instance, name, args ) {
var set = instance.plugins[ name ];
if ( !set || !instance.element[ 0 ].parentNode ) {
return;
}
for ( var i = 0; i < set.length; i++ ) {
if ( instance.options[ set[ i ][ 0 ] ] ) {
set[ i ][ 1 ].apply( instance.element, args );
}
}
}
},
// will be deprecated when we switch to jQuery 1.4 - use jQuery.contains()
contains: function( a, b ) {
return document.compareDocumentPosition ?
a.compareDocumentPosition( b ) & 16 :
a !== b && a.contains( b );
},
// only used by resizable
hasScroll: function( el, a ) {
//If overflow is hidden, the element might have extra content, but the user wants to hide it
if ( $( el ).css( "overflow" ) === "hidden") {
return false;
}
var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
has = false;
if ( el[ scroll ] > 0 ) {
return true;
}
// TODO: determine which cases actually cause this to happen
// if the element doesn't have the scroll set, see if it's possible to
// set the scroll
el[ scroll ] = 1;
has = ( el[ scroll ] > 0 );
el[ scroll ] = 0;
return has;
},
// these are odd functions, fix the API or move into individual plugins
isOverAxis: function( x, reference, size ) {
//Determines when x coordinate is over "b" element axis
return ( x > reference ) && ( x < ( reference + size ) );
},
isOver: function( y, x, top, left, height, width ) {
//Determines when x, y coordinates is over "b" element
return $.ui.isOverAxis( y, top, height ) && $.ui.isOverAxis( x, left, width );
}
});
})( jQuery );
/*!
* jQuery UI Widget @VERSION
*
* Copyright 2012, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Widget
*/
(function( $, undefined ) {
// jQuery 1.4+
if ( $.cleanData ) {
var _cleanData = $.cleanData;
$.cleanData = function( elems ) {
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
try {
$( elem ).triggerHandler( "remove" );
// http://bugs.jquery.com/ticket/8235
} catch( e ) {}
}
_cleanData( elems );
};
} else {
var _remove = $.fn.remove;
$.fn.remove = function( selector, keepData ) {
return this.each(function() {
if ( !keepData ) {
if ( !selector || $.filter( selector, [ this ] ).length ) {
$( "*", this ).add( [ this ] ).each(function() {
try {
$( this ).triggerHandler( "remove" );
// http://bugs.jquery.com/ticket/8235
} catch( e ) {}
});
}
}
return _remove.call( $(this), selector, keepData );
});
};
}
$.widget = function( name, base, prototype ) {
var namespace = name.split( "." )[ 0 ],
fullName;
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[ ":" ][ fullName ] = function( elem ) {
return !!$.data( elem, name );
};
$[ namespace ] = $[ namespace ] || {};
$[ namespace ][ name ] = function( options, element ) {
// allow instantiation without initializing for simple inheritance
if ( arguments.length ) {
this._createWidget( options, element );
}
};
var basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
// $.each( basePrototype, function( key, val ) {
// if ( $.isPlainObject(val) ) {
// basePrototype[ key ] = $.extend( {}, val );
// }
// });
basePrototype.options = $.extend( true, {}, basePrototype.options );
$[ namespace ][ name ].prototype = $.extend( true, basePrototype, {
namespace: namespace,
widgetName: name,
widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name,
widgetBaseClass: fullName
}, prototype );
$.widget.bridge( name, $[ namespace ][ name ] );
};
$.widget.bridge = function( name, object ) {
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string",
args = Array.prototype.slice.call( arguments, 1 ),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.extend.apply( null, [ true, options ].concat(args) ) :
options;
// prevent calls to internal methods
if ( isMethodCall && options.charAt( 0 ) === "_" ) {
return returnValue;
}
if ( isMethodCall ) {
this.each(function() {
var instance = $.data( this, name ),
methodValue = instance && $.isFunction( instance[options] ) ?
instance[ options ].apply( instance, args ) :
instance;
// TODO: add this back in 1.9 and use $.error() (see #5972)
// if ( !instance ) {
// throw "cannot call methods on " + name + " prior to initialization; " +
// "attempted to call method '" + options + "'";
// }
// if ( !$.isFunction( instance[options] ) ) {
// throw "no such method '" + options + "' for " + name + " widget instance";
// }
// var methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, name );
if ( instance ) {
instance.option( options || {} )._init();
} else {
$.data( this, name, new object( options, this ) );
}
});
}
return returnValue;
};
};
$.Widget = function( options, element ) {
// allow instantiation without initializing for simple inheritance
if ( arguments.length ) {
this._createWidget( options, element );
}
};
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
options: {
disabled: false
},
_createWidget: function( options, element ) {
// $.widget.bridge stores the plugin instance, but we do it anyway
// so that it's stored even before the _create function runs
$.data( element, this.widgetName, this );
this.element = $( element );
this.options = $.extend( true, {},
this.options,
this._getCreateOptions(),
options );
var self = this;
this.element.bind( "remove." + this.widgetName, function() {
self.destroy();
});
this._create();
this._trigger( "create" );
this._init();
},
_getCreateOptions: function() {
return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ];
},
_create: function() {},
_init: function() {},
destroy: function() {
this.element
.unbind( "." + this.widgetName )
.removeData( this.widgetName );
this.widget()
.unbind( "." + this.widgetName )
.removeAttr( "aria-disabled" )
.removeClass(
this.widgetBaseClass + "-disabled " +
"ui-state-disabled" );
},
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key;
if ( arguments.length === 0 ) {
// don't return a reference to the internal hash
return $.extend( {}, this.options );
}
if (typeof key === "string" ) {
if ( value === undefined ) {
return this.options[ key ];
}
options = {};
options[ key ] = value;
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var self = this;
$.each( options, function( key, value ) {
self._setOption( key, value );
});
return this;
},
_setOption: function( key, value ) {
this.options[ key ] = value;
if ( key === "disabled" ) {
this.widget()
[ value ? "addClass" : "removeClass"](
this.widgetBaseClass + "-disabled" + " " +
"ui-state-disabled" )
.attr( "aria-disabled", value );
}
return this;
},
enable: function() {
return this._setOption( "disabled", false );
},
disable: function() {
return this._setOption( "disabled", true );
},
_trigger: function( type, event, data ) {
var prop, orig,
callback = this.options[ type ];
data = data || {};
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// the original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// copy original event properties over to the new event
orig = event.originalEvent;
if ( orig ) {
for ( prop in orig ) {
if ( !( prop in event ) ) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger( event, data );
return !( $.isFunction(callback) &&
callback.call( this.element[0], event, data ) === false ||
event.isDefaultPrevented() );
}
};
})( jQuery );
/*!
* jQuery UI Mouse @VERSION
*
* Copyright 2012, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Mouse
*
* Depends:
* jquery.ui.widget.js
*/
(function( $, undefined ) {
var mouseHandled = false;
$( document ).mouseup( function( e ) {
mouseHandled = false;
});
$.widget("ui.mouse", {
options: {
cancel: ':input,option',
distance: 1,
delay: 0
},
_mouseInit: function() {
var self = this;
this.element
.bind('mousedown.'+this.widgetName, function(event) {
return self._mouseDown(event);
})
.bind('click.'+this.widgetName, function(event) {
if (true === $.data(event.target, self.widgetName + '.preventClickEvent')) {
$.removeData(event.target, self.widgetName + '.preventClickEvent');
event.stopImmediatePropagation();
return false;
}
});
this.started = false;
},
// TODO: make sure destroying one instance of mouse doesn't mess with
// other instances of mouse
_mouseDestroy: function() {
this.element.unbind('.'+this.widgetName);
$(document)
.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);
},
_mouseDown: function(event) {
// don't let more than one widget handle mouseStart
if( mouseHandled ) { return };
// we may have missed mouseup (out of window)
(this._mouseStarted && this._mouseUp(event));
this._mouseDownEvent = event;
var self = this,
btnIsLeft = (event.which == 1),
// event.target.nodeName works around a bug in IE 8 with
// disabled inputs (#7620)
elIsCancel = (typeof this.options.cancel == "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
return true;
}
this.mouseDelayMet = !this.options.delay;
if (!this.mouseDelayMet) {
this._mouseDelayTimer = setTimeout(function() {
self.mouseDelayMet = true;
}, this.options.delay);
}
if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
this._mouseStarted = (this._mouseStart(event) !== false);
if (!this._mouseStarted) {
event.preventDefault();
return true;
}
}
// Click event may never have fired (Gecko & Opera)
if (true === $.data(event.target, this.widgetName + '.preventClickEvent')) {
$.removeData(event.target, this.widgetName + '.preventClickEvent');
}
// these delegates are required to keep context
this._mouseMoveDelegate = function(event) {
return self._mouseMove(event);
};
this._mouseUpDelegate = function(event) {
return self._mouseUp(event);
};
$(document)
.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);
event.preventDefault();
mouseHandled = true;
return true;
},
_mouseMove: function(event) {
// IE mouseup check - mouseup happened when mouse was out of window
if ($.browser.msie && !(document.documentMode >= 9) && !event.button) {
return this._mouseUp(event);
}
if (this._mouseStarted) {
this._mouseDrag(event);
return event.preventDefault();
}
if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
this._mouseStarted =
(this._mouseStart(this._mouseDownEvent, event) !== false);
(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
}
return !this._mouseStarted;
},
_mouseUp: function(event) {
$(document)
.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);
if (this._mouseStarted) {
this._mouseStarted = false;
if (event.target == this._mouseDownEvent.target) {
$.data(event.target, this.widgetName + '.preventClickEvent', true);
}
this._mouseStop(event);
}
return false;
},
_mouseDistanceMet: function(event) {
return (Math.max(
Math.abs(this._mouseDownEvent.pageX - event.pageX),
Math.abs(this._mouseDownEvent.pageY - event.pageY)
) >= this.options.distance
);
},
_mouseDelayMet: function(event) {
return this.mouseDelayMet;
},
// These are placeholder methods, to be overriden by extending plugin
_mouseStart: function(event) {},
_mouseDrag: function(event) {},
_mouseStop: function(event) {},
_mouseCapture: function(event) { return true; }
});
})(jQuery);
/*!
* jQuery UI Position @VERSION
*
* Copyright 2012, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Position
*/
(function( $, undefined ) {
$.ui = $.ui || {};
var horizontalPositions = /left|center|right/,
verticalPositions = /top|center|bottom/,
center = "center",
support = {},
_position = $.fn.position,
_offset = $.fn.offset;
$.fn.position = function( options ) {
if ( !options || !options.of ) {
return _position.apply( this, arguments );
}
// make a copy, we don't want to modify arguments
options = $.extend( {}, options );
var target = $( options.of ),
targetElem = target[0],
collision = ( options.collision || "flip" ).split( " " ),
offset = options.offset ? options.offset.split( " " ) : [ 0, 0 ],
targetWidth,
targetHeight,
basePosition;
if ( targetElem.nodeType === 9 ) {
targetWidth = target.width();
targetHeight = target.height();
basePosition = { top: 0, left: 0 };
// TODO: use $.isWindow() in 1.9
} else if ( targetElem.setTimeout ) {
targetWidth = target.width();
targetHeight = target.height();
basePosition = { top: target.scrollTop(), left: target.scrollLeft() };
} else if ( targetElem.preventDefault ) {
// force left top to allow flipping
options.at = "left top";
targetWidth = targetHeight = 0;
basePosition = { top: options.of.pageY, left: options.of.pageX };
} else {
targetWidth = target.outerWidth();
targetHeight = target.outerHeight();
basePosition = target.offset();
}
// force my and at to have valid horizontal and veritcal positions
// if a value is missing or invalid, it will be converted to center
$.each( [ "my", "at" ], function() {
var pos = ( options[this] || "" ).split( " " );
if ( pos.length === 1) {
pos = horizontalPositions.test( pos[0] ) ?
pos.concat( [center] ) :
verticalPositions.test( pos[0] ) ?
[ center ].concat( pos ) :
[ center, center ];
}
pos[ 0 ] = horizontalPositions.test( pos[0] ) ? pos[ 0 ] : center;
pos[ 1 ] = verticalPositions.test( pos[1] ) ? pos[ 1 ] : center;
options[ this ] = pos;
});
// normalize collision option
if ( collision.length === 1 ) {
collision[ 1 ] = collision[ 0 ];
}
// normalize offset option
offset[ 0 ] = parseInt( offset[0], 10 ) || 0;
if ( offset.length === 1 ) {
offset[ 1 ] = offset[ 0 ];
}
offset[ 1 ] = parseInt( offset[1], 10 ) || 0;
if ( options.at[0] === "right" ) {
basePosition.left += targetWidth;
} else if ( options.at[0] === center ) {
basePosition.left += targetWidth / 2;
}
if ( options.at[1] === "bottom" ) {
basePosition.top += targetHeight;
} else if ( options.at[1] === center ) {
basePosition.top += targetHeight / 2;
}
basePosition.left += offset[ 0 ];
basePosition.top += offset[ 1 ];
return this.each(function() {
var elem = $( this ),
elemWidth = elem.outerWidth(),
elemHeight = elem.outerHeight(),
marginLeft = parseInt( $.curCSS( this, "marginLeft", true ) ) || 0,
marginTop = parseInt( $.curCSS( this, "marginTop", true ) ) || 0,
collisionWidth = elemWidth + marginLeft +
( parseInt( $.curCSS( this, "marginRight", true ) ) || 0 ),
collisionHeight = elemHeight + marginTop +
( parseInt( $.curCSS( this, "marginBottom", true ) ) || 0 ),
position = $.extend( {}, basePosition ),
collisionPosition;
if ( options.my[0] === "right" ) {
position.left -= elemWidth;
} else if ( options.my[0] === center ) {
position.left -= elemWidth / 2;
}
if ( options.my[1] === "bottom" ) {
position.top -= elemHeight;
} else if ( options.my[1] === center ) {
position.top -= elemHeight / 2;
}
// prevent fractions if jQuery version doesn't support them (see #5280)
if ( !support.fractions ) {
position.left = Math.round( position.left );
position.top = Math.round( position.top );
}
collisionPosition = {
left: position.left - marginLeft,
top: position.top - marginTop
};
$.each( [ "left", "top" ], function( i, dir ) {
if ( $.ui.position[ collision[i] ] ) {
$.ui.position[ collision[i] ][ dir ]( position, {
targetWidth: targetWidth,
targetHeight: targetHeight,
elemWidth: elemWidth,
elemHeight: elemHeight,
collisionPosition: collisionPosition,
collisionWidth: collisionWidth,
collisionHeight: collisionHeight,
offset: offset,
my: options.my,
at: options.at
});
}
});
if ( $.fn.bgiframe ) {
elem.bgiframe();
}
elem.offset( $.extend( position, { using: options.using } ) );
});
};
$.ui.position = {
fit: {
left: function( position, data ) {
var win = $( window ),
over = data.collisionPosition.left + data.collisionWidth - win.width() - win.scrollLeft();
position.left = over > 0 ? position.left - over : Math.max( position.left - data.collisionPosition.left, position.left );
},
top: function( position, data ) {
var win = $( window ),
over = data.collisionPosition.top + data.collisionHeight - win.height() - win.scrollTop();
position.top = over > 0 ? position.top - over : Math.max( position.top - data.collisionPosition.top, position.top );
}
},
flip: {
left: function( position, data ) {
if ( data.at[0] === center ) {
return;
}
var win = $( window ),
over = data.collisionPosition.left + data.collisionWidth - win.width() - win.scrollLeft(),
myOffset = data.my[ 0 ] === "left" ?
-data.elemWidth :
data.my[ 0 ] === "right" ?
data.elemWidth :
0,
atOffset = data.at[ 0 ] === "left" ?
data.targetWidth :
-data.targetWidth,
offset = -2 * data.offset[ 0 ];
position.left += data.collisionPosition.left < 0 ?
myOffset + atOffset + offset :
over > 0 ?
myOffset + atOffset + offset :
0;
},
top: function( position, data ) {
if ( data.at[1] === center ) {
return;
}
var win = $( window ),
over = data.collisionPosition.top + data.collisionHeight - win.height() - win.scrollTop(),
myOffset = data.my[ 1 ] === "top" ?
-data.elemHeight :
data.my[ 1 ] === "bottom" ?
data.elemHeight :
0,
atOffset = data.at[ 1 ] === "top" ?
data.targetHeight :
-data.targetHeight,
offset = -2 * data.offset[ 1 ];
position.top += data.collisionPosition.top < 0 ?
myOffset + atOffset + offset :
over > 0 ?
myOffset + atOffset + offset :
0;
}
}
};
// offset setter from jQuery 1.4
if ( !$.offset.setOffset ) {
$.offset.setOffset = function( elem, options ) {
// set position first, in-case top/left are set even on static elem
if ( /static/.test( $.curCSS( elem, "position" ) ) ) {
elem.style.position = "relative";
}
var curElem = $( elem ),
curOffset = curElem.offset(),
curTop = parseInt( $.curCSS( elem, "top", true ), 10 ) || 0,
curLeft = parseInt( $.curCSS( elem, "left", true ), 10) || 0,
props = {
top: (options.top - curOffset.top) + curTop,
left: (options.left - curOffset.left) + curLeft
};
if ( 'using' in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
};
$.fn.offset = function( options ) {
var elem = this[ 0 ];
if ( !elem || !elem.ownerDocument ) { return null; }
if ( options ) {
return this.each(function() {
$.offset.setOffset( this, options );
});
}
return _offset.call( this );
};
}
// fraction support test (older versions of jQuery don't support fractions)
(function () {
var body = document.getElementsByTagName( "body" )[ 0 ],
div = document.createElement( "div" ),
testElement, testElementParent, testElementStyle, offset, offsetTotal;
//Create a "fake body" for testing based on method used in jQuery.support
testElement = document.createElement( body ? "div" : "body" );
testElementStyle = {
visibility: "hidden",
width: 0,
height: 0,
border: 0,
margin: 0,
background: "none"
};
if ( body ) {
$.extend( testElementStyle, {
position: "absolute",
left: "-1000px",
top: "-1000px"
});
}
for ( var i in testElementStyle ) {
testElement.style[ i ] = testElementStyle[ i ];
}
testElement.appendChild( div );
testElementParent = body || document.documentElement;
testElementParent.insertBefore( testElement, testElementParent.firstChild );
div.style.cssText = "position: absolute; left: 10.7432222px; top: 10.432325px; height: 30px; width: 201px;";
offset = $( div ).offset( function( _, offset ) {
return offset;
}).offset();
testElement.innerHTML = "";
testElementParent.removeChild( testElement );
offsetTotal = offset.top + offset.left + ( body ? 2000 : 0 );
support.fractions = offsetTotal > 21 && offsetTotal < 22;
})();
}( jQuery ));
/*!
* jQuery UI Slider @VERSION
*
* Copyright 2012, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Slider
*
* Depends:
* jquery.ui.core.js
* jquery.ui.mouse.js
* jquery.ui.widget.js
*/
(function( $, undefined ) {
// number of pages in a slider
// (how many times can you page up/down to go through the whole range)
var numPages = 5;
$.widget( "ui.slider", $.ui.mouse, {
widgetEventPrefix: "slide",
options: {
animate: false,
distance: 0,
max: 100,
min: 0,
orientation: "horizontal",
range: false,
step: 1,
value: 0,
values: null
},
_create: function() {
var self = this,
o = this.options,
existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ),
handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",
handleCount = ( o.values && o.values.length ) || 1,
handles = [];
this._keySliding = false;
this._mouseSliding = false;
this._animateOff = true;
this._handleIndex = null;
this._detectOrientation();
this._mouseInit();
this.element
.addClass( "ui-slider" +
" ui-slider-" + this.orientation +
" ui-widget" +
" ui-widget-content" +
" ui-corner-all" +
( o.disabled ? " ui-slider-disabled ui-disabled" : "" ) );
this.range = $([]);
if ( o.range ) {
if ( o.range === true ) {
if ( !o.values ) {
o.values = [ this._valueMin(), this._valueMin() ];
}
if ( o.values.length && o.values.length !== 2 ) {
o.values = [ o.values[0], o.values[0] ];
}
}
this.range = $( "<div></div>" )
.appendTo( this.element )
.addClass( "ui-slider-range" +
// note: this isn't the most fittingly semantic framework class for this element,
// but worked best visually with a variety of themes
" ui-widget-header" +
( ( o.range === "min" || o.range === "max" ) ? " ui-slider-range-" + o.range : "" ) );
}
for ( var i = existingHandles.length; i < handleCount; i += 1 ) {
handles.push( handle );
}
this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( self.element ) );
this.handle = this.handles.eq( 0 );
this.handles.add( this.range ).filter( "a" )
.click(function( event ) {
event.preventDefault();
})
.hover(function() {
if ( !o.disabled ) {
$( this ).addClass( "ui-state-hover" );
}
}, function() {
$( this ).removeClass( "ui-state-hover" );
})
.focus(function() {
if ( !o.disabled ) {
$( ".ui-slider .ui-state-focus" ).removeClass( "ui-state-focus" );
$( this ).addClass( "ui-state-focus" );
} else {
$( this ).blur();
}
})
.blur(function() {
$( this ).removeClass( "ui-state-focus" );
});
this.handles.each(function( i ) {
$( this ).data( "index.ui-slider-handle", i );
});
this.handles
.keydown(function( event ) {
var index = $( this ).data( "index.ui-slider-handle" ),
allowed,
curVal,
newVal,
step;
if ( self.options.disabled ) {
return;
}
switch ( event.keyCode ) {
case $.ui.keyCode.HOME:
case $.ui.keyCode.END:
case $.ui.keyCode.PAGE_UP:
case $.ui.keyCode.PAGE_DOWN:
case $.ui.keyCode.UP:
case $.ui.keyCode.RIGHT:
case $.ui.keyCode.DOWN:
case $.ui.keyCode.LEFT:
event.preventDefault();
if ( !self._keySliding ) {
self._keySliding = true;
$( this ).addClass( "ui-state-active" );
allowed = self._start( event, index );
if ( allowed === false ) {
return;
}
}
break;
}
step = self.options.step;
if ( self.options.values && self.options.values.length ) {
curVal = newVal = self.values( index );
} else {
curVal = newVal = self.value();
}
switch ( event.keyCode ) {
case $.ui.keyCode.HOME:
newVal = self._valueMin();
break;
case $.ui.keyCode.END:
newVal = self._valueMax();
break;
case $.ui.keyCode.PAGE_UP:
newVal = self._trimAlignValue( curVal + ( (self._valueMax() - self._valueMin()) / numPages ) );
break;
case $.ui.keyCode.PAGE_DOWN:
newVal = self._trimAlignValue( curVal - ( (self._valueMax() - self._valueMin()) / numPages ) );
break;
case $.ui.keyCode.UP:
case $.ui.keyCode.RIGHT:
if ( curVal === self._valueMax() ) {
return;
}
newVal = self._trimAlignValue( curVal + step );
break;
case $.ui.keyCode.DOWN:
case $.ui.keyCode.LEFT:
if ( curVal === self._valueMin() ) {
return;
}
newVal = self._trimAlignValue( curVal - step );
break;
}
self._slide( event, index, newVal );
})
.keyup(function( event ) {
var index = $( this ).data( "index.ui-slider-handle" );
if ( self._keySliding ) {
self._keySliding = false;
self._stop( event, index );
self._change( event, index );
$( this ).removeClass( "ui-state-active" );
}
});
this._refreshValue();
this._animateOff = false;
},
destroy: function() {
this.handles.remove();
this.range.remove();
this.element
.removeClass( "ui-slider" +
" ui-slider-horizontal" +
" ui-slider-vertical" +
" ui-slider-disabled" +
" ui-widget" +
" ui-widget-content" +
" ui-corner-all" )
.removeData( "slider" )
.unbind( ".slider" );
this._mouseDestroy();
return this;
},
_mouseCapture: function( event ) {
var o = this.options,
position,
normValue,
distance,
closestHandle,
self,
index,
allowed,
offset,
mouseOverHandle;
if ( o.disabled ) {
return false;
}
this.elementSize = {
width: this.element.outerWidth(),
height: this.element.outerHeight()
};
this.elementOffset = this.element.offset();
position = { x: event.pageX, y: event.pageY };
normValue = this._normValueFromMouse( position );
distance = this._valueMax() - this._valueMin() + 1;
self = this;
this.handles.each(function( i ) {
var thisDistance = Math.abs( normValue - self.values(i) );
if ( distance > thisDistance ) {
distance = thisDistance;
closestHandle = $( this );
index = i;
}
});
// workaround for bug #3736 (if both handles of a range are at 0,
// the first is always used as the one with least distance,
// and moving it is obviously prevented by preventing negative ranges)
if( o.range === true && this.values(1) === o.min ) {
index += 1;
closestHandle = $( this.handles[index] );
}
allowed = this._start( event, index );
if ( allowed === false ) {
return false;
}
this._mouseSliding = true;
self._handleIndex = index;
closestHandle
.addClass( "ui-state-active" )
.focus();
offset = closestHandle.offset();
mouseOverHandle = !$( event.target ).parents().andSelf().is( ".ui-slider-handle" );
this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
top: event.pageY - offset.top -
( closestHandle.height() / 2 ) -
( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) -
( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) +
( parseInt( closestHandle.css("marginTop"), 10 ) || 0)
};
if ( !this.handles.hasClass( "ui-state-hover" ) ) {
this._slide( event, index, normValue );
}
this._animateOff = true;
return true;
},
_mouseStart: function( event ) {
return true;
},
_mouseDrag: function( event ) {
var position = { x: event.pageX, y: event.pageY },
normValue = this._normValueFromMouse( position );
this._slide( event, this._handleIndex, normValue );
return false;
},
_mouseStop: function( event ) {
this.handles.removeClass( "ui-state-active" );
this._mouseSliding = false;
this._stop( event, this._handleIndex );
this._change( event, this._handleIndex );
this._handleIndex = null;
this._clickOffset = null;
this._animateOff = false;
return false;
},
_detectOrientation: function() {
this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
},
_normValueFromMouse: function( position ) {
var pixelTotal,
pixelMouse,
percentMouse,
valueTotal,
valueMouse;
if ( this.orientation === "horizontal" ) {
pixelTotal = this.elementSize.width;
pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 );
} else {
pixelTotal = this.elementSize.height;
pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 );
}
percentMouse = ( pixelMouse / pixelTotal );
if ( percentMouse > 1 ) {
percentMouse = 1;
}
if ( percentMouse < 0 ) {
percentMouse = 0;
}
if ( this.orientation === "vertical" ) {
percentMouse = 1 - percentMouse;
}
valueTotal = this._valueMax() - this._valueMin();
valueMouse = this._valueMin() + percentMouse * valueTotal;
return this._trimAlignValue( valueMouse );
},
_start: function( event, index ) {
var uiHash = {
handle: this.handles[ index ],
value: this.value()
};
if ( this.options.values && this.options.values.length ) {
uiHash.value = this.values( index );
uiHash.values = this.values();
}
return this._trigger( "start", event, uiHash );
},
_slide: function( event, index, newVal ) {
var otherVal,
newValues,
allowed;
if ( this.options.values && this.options.values.length ) {
otherVal = this.values( index ? 0 : 1 );
if ( ( this.options.values.length === 2 && this.options.range === true ) &&
( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) )
) {
newVal = otherVal;
}
if ( newVal !== this.values( index ) ) {
newValues = this.values();
newValues[ index ] = newVal;
// A slide can be canceled by returning false from the slide callback
allowed = this._trigger( "slide", event, {
handle: this.handles[ index ],
value: newVal,
values: newValues
} );
otherVal = this.values( index ? 0 : 1 );
if ( allowed !== false ) {
this.values( index, newVal, true );
}
}
} else {
if ( newVal !== this.value() ) {
// A slide can be canceled by returning false from the slide callback
allowed = this._trigger( "slide", event, {
handle: this.handles[ index ],
value: newVal
} );
if ( allowed !== false ) {
this.value( newVal );
}
}
}
},
_stop: function( event, index ) {
var uiHash = {
handle: this.handles[ index ],
value: this.value()
};
if ( this.options.values && this.options.values.length ) {
uiHash.value = this.values( index );
uiHash.values = this.values();
}
this._trigger( "stop", event, uiHash );
},
_change: function( event, index ) {
if ( !this._keySliding && !this._mouseSliding ) {
var uiHash = {
handle: this.handles[ index ],
value: this.value()
};
if ( this.options.values && this.options.values.length ) {
uiHash.value = this.values( index );
uiHash.values = this.values();
}
this._trigger( "change", event, uiHash );
}
},
value: function( newValue ) {
if ( arguments.length ) {
this.options.value = this._trimAlignValue( newValue );
this._refreshValue();
this._change( null, 0 );
return;
}
return this._value();
},
values: function( index, newValue ) {
var vals,
newValues,
i;
if ( arguments.length > 1 ) {
this.options.values[ index ] = this._trimAlignValue( newValue );
this._refreshValue();
this._change( null, index );
return;
}
if ( arguments.length ) {
if ( $.isArray( arguments[ 0 ] ) ) {
vals = this.options.values;
newValues = arguments[ 0 ];
for ( i = 0; i < vals.length; i += 1 ) {
vals[ i ] = this._trimAlignValue( newValues[ i ] );
this._change( null, i );
}
this._refreshValue();
} else {
if ( this.options.values && this.options.values.length ) {
return this._values( index );
} else {
return this.value();
}
}
} else {
return this._values();
}
},
_setOption: function( key, value ) {
var i,
valsLength = 0;
if ( $.isArray( this.options.values ) ) {
valsLength = this.options.values.length;
}
$.Widget.prototype._setOption.apply( this, arguments );
switch ( key ) {
case "disabled":
if ( value ) {
this.handles.filter( ".ui-state-focus" ).blur();
this.handles.removeClass( "ui-state-hover" );
this.handles.propAttr( "disabled", true );
this.element.addClass( "ui-disabled" );
} else {
this.handles.propAttr( "disabled", false );
this.element.removeClass( "ui-disabled" );
}
break;
case "orientation":
this._detectOrientation();
this.element
.removeClass( "ui-slider-horizontal ui-slider-vertical" )
.addClass( "ui-slider-" + this.orientation );
this._refreshValue();
break;
case "value":
this._animateOff = true;
this._refreshValue();
this._change( null, 0 );
this._animateOff = false;
break;
case "values":
this._animateOff = true;
this._refreshValue();
for ( i = 0; i < valsLength; i += 1 ) {
this._change( null, i );
}
this._animateOff = false;
break;
}
},
//internal value getter
// _value() returns value trimmed by min and max, aligned by step
_value: function() {
var val = this.options.value;
val = this._trimAlignValue( val );
return val;
},
//internal values getter
// _values() returns array of values trimmed by min and max, aligned by step
// _values( index ) returns single value trimmed by min and max, aligned by step
_values: function( index ) {
var val,
vals,
i;
if ( arguments.length ) {
val = this.options.values[ index ];
val = this._trimAlignValue( val );
return val;
} else {
// .slice() creates a copy of the array
// this copy gets trimmed by min and max and then returned
vals = this.options.values.slice();
for ( i = 0; i < vals.length; i+= 1) {
vals[ i ] = this._trimAlignValue( vals[ i ] );
}
return vals;
}
},
// returns the step-aligned value that val is closest to, between (inclusive) min and max
_trimAlignValue: function( val ) {
if ( val <= this._valueMin() ) {
return this._valueMin();
}
if ( val >= this._valueMax() ) {
return this._valueMax();
}
var step = ( this.options.step > 0 ) ? this.options.step : 1,
valModStep = (val - this._valueMin()) % step,
alignValue = val - valModStep;
if ( Math.abs(valModStep) * 2 >= step ) {
alignValue += ( valModStep > 0 ) ? step : ( -step );
}
// Since JavaScript has problems with large floats, round
// the final value to 5 digits after the decimal point (see #4124)
return parseFloat( alignValue.toFixed(5) );
},
_valueMin: function() {
return this.options.min;
},
_valueMax: function() {
return this.options.max;
},
_refreshValue: function() {
var oRange = this.options.range,
o = this.options,
self = this,
animate = ( !this._animateOff ) ? o.animate : false,
valPercent,
_set = {},
lastValPercent,
value,
valueMin,
valueMax;
if ( this.options.values && this.options.values.length ) {
this.handles.each(function( i, j ) {
valPercent = ( self.values(i) - self._valueMin() ) / ( self._valueMax() - self._valueMin() ) * 100;
_set[ self.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
$( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
if ( self.options.range === true ) {
if ( self.orientation === "horizontal" ) {
if ( i === 0 ) {
self.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate );
}
if ( i === 1 ) {
self.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
}
} else {
if ( i === 0 ) {
self.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate );
}
if ( i === 1 ) {
self.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
}
}
}
lastValPercent = valPercent;
});
} else {
value = this.value();
valueMin = this._valueMin();
valueMax = this._valueMax();
valPercent = ( valueMax !== valueMin ) ?
( value - valueMin ) / ( valueMax - valueMin ) * 100 :
0;
_set[ self.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
if ( oRange === "min" && this.orientation === "horizontal" ) {
this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate );
}
if ( oRange === "max" && this.orientation === "horizontal" ) {
this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
}
if ( oRange === "min" && this.orientation === "vertical" ) {
this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate );
}
if ( oRange === "max" && this.orientation === "vertical" ) {
this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
}
}
}
});
$.extend( $.ui.slider, {
version: "@VERSION"
});
}(jQuery));
// This [jQuery](http://jquery.com/) plugin implements an `<iframe>`
// [transport](http://api.jquery.com/extending-ajax/#Transports) so that
// `$.ajax()` calls support the uploading of files using standard HTML file
// input fields. This is done by switching the exchange from `XMLHttpRequest`
// to a hidden `iframe` element containing a form that is submitted.
// The [source for the plugin](http://github.com/cmlenz/jquery-iframe-transport)
// is available on [Github](http://github.com/) and dual licensed under the MIT
// or GPL Version 2 licenses.
// ## Usage
// To use this plugin, you simply add an `iframe` option with the value `true`
// to the Ajax settings an `$.ajax()` call, and specify the file fields to
// include in the submssion using the `files` option, which can be a selector,
// jQuery object, or a list of DOM elements containing one or more
// `<input type="file">` elements:
// $("#myform").submit(function() {
// $.ajax(this.action, {
// files: $(":file", this),
// iframe: true
// }).complete(function(data) {
// console.log(data);
// });
// });
// The plugin will construct a hidden `<iframe>` element containing a copy of
// the form the file field belongs to, will disable any form fields not
// explicitly included, submit that form, and process the response.
// If you want to include other form fields in the form submission, include
// them in the `data` option, and set the `processData` option to `false`:
// $("#myform").submit(function() {
// $.ajax(this.action, {
// data: $(":text", this).serializeArray(),
// files: $(":file", this),
// iframe: true,
// processData: false
// }).complete(function(data) {
// console.log(data);
// });
// });
// ### Response Data Types
// As the transport does not have access to the HTTP headers of the server
// response, it is not as simple to make use of the automatic content type
// detection provided by jQuery as with regular XHR. If you can't set the
// expected response data type (for example because it may vary), you will
// need to employ a workaround on the server side: Send back an HTML document
// containing just a `<textarea>` element with a `data-type` attribute that
// specifies the MIME type, and put the actual payload in the textarea:
// <textarea data-type="application/json">
// {"ok": true, "message": "Thanks so much"}
// </textarea>
// The iframe transport plugin will detect this and pass the value of the
// `data-type` attribute on to jQuery as if it was the "Content-Type" response
// header, thereby enabling the same kind of conversions that jQuery applies
// to regular responses. For the example above you should get a Javascript
// object as the `data` parameter of the `complete` callback, with the
// properties `ok: true` and `message: "Thanks so much"`.
// ### Handling Server Errors
// Another problem with using an `iframe` for file uploads is that it is
// impossible for the javascript code to determine the HTTP status code of the
// servers response. Effectively, all of the calls you make will look like they
// are getting successful responses, and thus invoke the `done()` or
// `complete()` callbacks. You can only determine communicate problems using
// the content of the response payload. For example, consider using a JSON
// response such as the following to indicate a problem with an uploaded file:
// <textarea data-type="application/json">
// {"ok": false, "message": "Please only upload reasonably sized files."}
// </textarea>
// ### Compatibility
// This plugin has primarily been tested on Safari 5 (or later), Firefox 4 (or
// later), and Internet Explorer (all the way back to version 6). While I
// haven't found any issues with it so far, I'm fairly sure it still doesn't
// work around all the quirks in all different browsers. But the code is still
// pretty simple overall, so you should be able to fix it and contribute a
// patch :)
// ## Annotated Source
(function($, undefined) {
"use strict";
// Register a prefilter that checks whether the `iframe` option is set, and
// switches to the "iframe" data type if it is `true`.
$.ajaxPrefilter(function(options, origOptions, jqXHR) {
if (options.iframe) {
return "iframe";
}
});
// Register a transport for the "iframe" data type. It will only activate
// when the "files" option has been set to a non-empty list of enabled file
// inputs.
$.ajaxTransport("iframe", function(options, origOptions, jqXHR) {
var form = null,
iframe = null,
name = "iframe-" + $.now(),
files = $(options.files).filter(":file:enabled"),
markers = null;
// This function gets called after a successful submission or an abortion
// and should revert all changes made to the page to enable the
// submission via this transport.
function cleanUp() {
markers.replaceWith(function(idx) {
return files.get(idx);
});
form.remove();
iframe.attr("src", "javascript:false;").remove();
}
// Remove "iframe" from the data types list so that further processing is
// based on the content type returned by the server, without attempting an
// (unsupported) conversion from "iframe" to the actual type.
options.dataTypes.shift();
if (files.length) {
form = $("<form enctype='multipart/form-data' method='post'></form>").
hide().attr({action: options.url, target: name});
// If there is any additional data specified via the `data` option,
// we add it as hidden fields to the form. This (currently) requires
// the `processData` option to be set to false so that the data doesn't
// get serialized to a string.
if (typeof(options.data) === "string" && options.data.length > 0) {
$.error("data must not be serialized");
}
$.each(options.data || {}, function(name, value) {
if ($.isPlainObject(value)) {
name = value.name;
value = value.value;
}
$("<input type='hidden'>").attr({name: name, value: value}).
appendTo(form);
});
// Add a hidden `X-Requested-With` field with the value `IFrame` to the
// field, to help server-side code to determine that the upload happened
// through this transport.
$("<input type='hidden' value='IFrame' name='X-Requested-With'>").
appendTo(form);
// Move the file fields into the hidden form, but first remember their
// original locations in the document by replacing them with disabled
// clones. This should also avoid introducing unwanted changes to the
// page layout during submission.
markers = files.after(function(idx) {
return $(this).clone().prop("disabled", true);
}).next();
files.appendTo(form);
return {
// The `send` function is called by jQuery when the request should be
// sent.
send: function(headers, completeCallback) {
iframe = $("<iframe src='javascript:false;' name='" + name +
"' style='display:none'></iframe>");
// The first load event gets fired after the iframe has been injected
// into the DOM, and is used to prepare the actual submission.
iframe.bind("load", function() {
// The second load event gets fired when the response to the form
// submission is received. The implementation detects whether the
// actual payload is embedded in a `<textarea>` element, and
// prepares the required conversions to be made in that case.
iframe.unbind("load").bind("load", function() {
var doc = this.contentWindow ? this.contentWindow.document :
(this.contentDocument ? this.contentDocument : this.document),
root = doc.documentElement ? doc.documentElement : doc.body,
textarea = root.getElementsByTagName("textarea")[0],
type = textarea ? textarea.getAttribute("data-type") : null,
content = {
html: root.innerHTML,
text: type ?
textarea.value :
root ? (root.textContent || root.innerText) : null
};
cleanUp();
completeCallback(200, "OK", content, type ?
("Content-Type: " + type) :
null);
});
// Now that the load handler has been set up, submit the form.
form[0].submit();
});
// After everything has been set up correctly, the form and iframe
// get injected into the DOM so that the submission can be
// initiated.
$("body").append(form, iframe);
},
// The `abort` function is called by jQuery when the request should be
// aborted.
abort: function() {
if (iframe !== null) {
iframe.unbind("load").attr("src", "javascript:false;");
cleanUp();
}
}
};
}
});
})(jQuery);
// lib/handlebars/base.js
var Handlebars = {};
Handlebars.VERSION = "1.0.beta.6";
Handlebars.helpers = {};
Handlebars.partials = {};
Handlebars.registerHelper = function(name, fn, inverse) {
if(inverse) { fn.not = inverse; }
this.helpers[name] = fn;
};
Handlebars.registerPartial = function(name, str) {
this.partials[name] = str;
};
Handlebars.registerHelper('helperMissing', function(arg) {
if(arguments.length === 2) {
return undefined;
} else {
throw new Error("Could not find property '" + arg + "'");
}
});
var toString = Object.prototype.toString, functionType = "[object Function]";
Handlebars.registerHelper('blockHelperMissing', function(context, options) {
var inverse = options.inverse || function() {}, fn = options.fn;
var ret = "";
var type = toString.call(context);
if(type === functionType) { context = context.call(this); }
if(context === true) {
return fn(this);
} else if(context === false || context == null) {
return inverse(this);
} else if(type === "[object Array]") {
if(context.length > 0) {
for(var i=0, j=context.length; i<j; i++) {
ret = ret + fn(context[i]);
}
} else {
ret = inverse(this);
}
return ret;
} else {
return fn(context);
}
});
Handlebars.registerHelper('each', function(context, options) {
var fn = options.fn, inverse = options.inverse;
var ret = "";
if(context && context.length > 0) {
for(var i=0, j=context.length; i<j; i++) {
ret = ret + fn(context[i]);
}
} else {
ret = inverse(this);
}
return ret;
});
Handlebars.registerHelper('if', function(context, options) {
var type = toString.call(context);
if(type === functionType) { context = context.call(this); }
if(!context || Handlebars.Utils.isEmpty(context)) {
return options.inverse(this);
} else {
return options.fn(this);
}
});
Handlebars.registerHelper('unless', function(context, options) {
var fn = options.fn, inverse = options.inverse;
options.fn = inverse;
options.inverse = fn;
return Handlebars.helpers['if'].call(this, context, options);
});
Handlebars.registerHelper('with', function(context, options) {
return options.fn(context);
});
Handlebars.registerHelper('log', function(context) {
Handlebars.log(context);
});
;
// lib/handlebars/utils.js
Handlebars.Exception = function(message) {
var tmp = Error.prototype.constructor.apply(this, arguments);
for (var p in tmp) {
if (tmp.hasOwnProperty(p)) { this[p] = tmp[p]; }
}
this.message = tmp.message;
};
Handlebars.Exception.prototype = new Error;
// Build out our basic SafeString type
Handlebars.SafeString = function(string) {
this.string = string;
};
Handlebars.SafeString.prototype.toString = function() {
return this.string.toString();
};
(function() {
var escape = {
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#x27;",
"`": "&#x60;"
};
var badChars = /&(?!\w+;)|[<>"'`]/g;
var possible = /[&<>"'`]/;
var escapeChar = function(chr) {
return escape[chr] || "&amp;";
};
Handlebars.Utils = {
escapeExpression: function(string) {
// don't escape SafeStrings, since they're already safe
if (string instanceof Handlebars.SafeString) {
return string.toString();
} else if (string == null || string === false) {
return "";
}
if(!possible.test(string)) { return string; }
return string.replace(badChars, escapeChar);
},
isEmpty: function(value) {
if (typeof value === "undefined") {
return true;
} else if (value === null) {
return true;
} else if (value === false) {
return true;
} else if(Object.prototype.toString.call(value) === "[object Array]" && value.length === 0) {
return true;
} else {
return false;
}
}
};
})();;
// lib/handlebars/runtime.js
Handlebars.VM = {
template: function(templateSpec) {
// Just add water
var container = {
escapeExpression: Handlebars.Utils.escapeExpression,
invokePartial: Handlebars.VM.invokePartial,
programs: [],
program: function(i, fn, data) {
var programWrapper = this.programs[i];
if(data) {
return Handlebars.VM.program(fn, data);
} else if(programWrapper) {
return programWrapper;
} else {
programWrapper = this.programs[i] = Handlebars.VM.program(fn);
return programWrapper;
}
},
programWithDepth: Handlebars.VM.programWithDepth,
noop: Handlebars.VM.noop
};
return function(context, options) {
options = options || {};
return templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data);
};
},
programWithDepth: function(fn, data, $depth) {
var args = Array.prototype.slice.call(arguments, 2);
return function(context, options) {
options = options || {};
return fn.apply(this, [context, options.data || data].concat(args));
};
},
program: function(fn, data) {
return function(context, options) {
options = options || {};
return fn(context, options.data || data);
};
},
noop: function() { return ""; },
invokePartial: function(partial, name, context, helpers, partials, data) {
options = { helpers: helpers, partials: partials, data: data };
if(partial === undefined) {
throw new Handlebars.Exception("The partial " + name + " could not be found");
} else if(partial instanceof Function) {
return partial(context, options);
} else if (!Handlebars.compile) {
throw new Handlebars.Exception("The partial " + name + " could not be compiled when running in runtime-only mode");
} else {
partials[name] = Handlebars.compile(partial);
return partials[name](context, options);
}
}
};
Handlebars.template = Handlebars.VM.template;
;
/* ============================================================
* bootstrap-button.js v2.0.1
* http://twitter.github.com/bootstrap/javascript.html#buttons
* ============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================ */
!function( $ ){
"use strict"
/* BUTTON PUBLIC CLASS DEFINITION
* ============================== */
var Button = function ( element, options ) {
this.$element = $(element)
this.options = $.extend({}, $.fn.button.defaults, options)
}
Button.prototype = {
constructor: Button
, setState: function ( state ) {
var d = 'disabled'
, $el = this.$element
, data = $el.data()
, val = $el.is('input') ? 'val' : 'html'
state = state + 'Text'
data.resetText || $el.data('resetText', $el[val]())
$el[val](data[state] || this.options[state])
// push to event loop to allow forms to submit
setTimeout(function () {
state == 'loadingText' ?
$el.addClass(d).attr(d, d) :
$el.removeClass(d).removeAttr(d)
}, 0)
}
, toggle: function () {
var $parent = this.$element.parent('[data-toggle="buttons-radio"]')
$parent && $parent
.find('.active')
.removeClass('active')
this.$element.toggleClass('active')
}
}
/* BUTTON PLUGIN DEFINITION
* ======================== */
$.fn.button = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('button')
, options = typeof option == 'object' && option
if (!data) $this.data('button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
$.fn.button.defaults = {
loadingText: 'loading...'
}
$.fn.button.Constructor = Button
/* BUTTON DATA-API
* =============== */
$(function () {
$('body').on('click.button.data-api', '[data-toggle^=button]', function ( e ) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
$btn.button('toggle')
})
})
}( window.jQuery );
// fdfdsfds
;
/* ============================================================
* bootstrap-dropdown.js v2.0.2
* http://twitter.github.com/bootstrap/javascript.html#dropdowns
* ============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================ */
!function( $ ){
"use strict"
/* DROPDOWN CLASS DEFINITION
* ========================= */
var toggle = '[data-toggle="dropdown"]'
, Dropdown = function ( element ) {
var $el = $(element).on('click.dropdown.data-api', this.toggle)
$('html').on('click.dropdown.data-api', function () {
$el.parent().removeClass('open')
})
}
Dropdown.prototype = {
constructor: Dropdown
, toggle: function ( e ) {
var $this = $(this)
, selector = $this.attr('data-target')
, $parent
, isActive
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
$parent = $(selector)
$parent.length || ($parent = $this.parent())
isActive = $parent.hasClass('open')
clearMenus()
!isActive && $parent.toggleClass('open')
return false
}
}
function clearMenus() {
$(toggle).parent().removeClass('open')
}
/* DROPDOWN PLUGIN DEFINITION
* ========================== */
$.fn.dropdown = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('dropdown')
if (!data) $this.data('dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
$.fn.dropdown.Constructor = Dropdown
/* APPLY TO STANDARD DROPDOWN ELEMENTS
* =================================== */
$(function () {
$('html').on('click.dropdown.data-api', clearMenus)
$('body').on('click.dropdown.data-api', toggle, Dropdown.prototype.toggle)
})
}( window.jQuery );
/* ========================================================
* bootstrap-tab.js v2.0.2
* http://twitter.github.com/bootstrap/javascript.html#tabs
* ========================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ======================================================== */
!function( $ ){
"use strict"
/* TAB CLASS DEFINITION
* ==================== */
var Tab = function ( element ) {
this.element = $(element)
}
Tab.prototype = {
constructor: Tab
, show: function () {
var $this = this.element
, $ul = $this.closest('ul:not(.dropdown-menu)')
, selector = $this.attr('data-target')
, previous
, $target
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
if ( $this.parent('li').hasClass('active') ) return
previous = $ul.find('.active a').last()[0]
$this.trigger({
type: 'show'
, relatedTarget: previous
})
$target = $(selector)
this.activate($this.parent('li'), $ul)
this.activate($target, $target.parent(), function () {
$this.trigger({
type: 'shown'
, relatedTarget: previous
})
})
}
, activate: function ( element, container, callback) {
var $active = container.find('> .active')
, transition = callback
&& $.support.transition
&& $active.hasClass('fade')
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
element.addClass('active')
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if ( element.parent('.dropdown-menu') ) {
element.closest('li.dropdown').addClass('active')
}
callback && callback()
}
transition ?
$active.one($.support.transition.end, next) :
next()
$active.removeClass('in')
}
}
/* TAB PLUGIN DEFINITION
* ===================== */
$.fn.tab = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('tab')
if (!data) $this.data('tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
$.fn.tab.Constructor = Tab
/* TAB DATA-API
* ============ */
$(function () {
$('body').on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
e.preventDefault()
$(this).tab('show')
})
})
}( window.jQuery );
/* ===================================================
* bootstrap-transition.js v2.0.2
* http://twitter.github.com/bootstrap/javascript.html#transitions
* ===================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
!function( $ ) {
$(function () {
"use strict"
/* CSS TRANSITION SUPPORT (https://gist.github.com/373874)
* ======================================================= */
$.support.transition = (function () {
var thisBody = document.body || document.documentElement
, thisStyle = thisBody.style
, support = thisStyle.transition !== undefined || thisStyle.WebkitTransition !== undefined || thisStyle.MozTransition !== undefined || thisStyle.MsTransition !== undefined || thisStyle.OTransition !== undefined
return support && {
end: (function () {
var transitionEnd = "TransitionEnd"
if ( $.browser.webkit ) {
transitionEnd = "webkitTransitionEnd"
} else if ( $.browser.mozilla ) {
transitionEnd = "transitionend"
} else if ( $.browser.opera ) {
transitionEnd = "oTransitionEnd"
}
return transitionEnd
}())
}
})()
})
}( window.jQuery );
/* ==========================================================
* bootstrap-alert.js v2.0.2
* http://twitter.github.com/bootstrap/javascript.html#alerts
* ==========================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
!function( $ ){
"use strict"
/* ALERT CLASS DEFINITION
* ====================== */
var dismiss = '[data-dismiss="alert"]'
, Alert = function ( el ) {
$(el).on('click', dismiss, this.close)
}
Alert.prototype = {
constructor: Alert
, close: function ( e ) {
var $this = $(this)
, selector = $this.attr('data-target')
, $parent
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
$parent = $(selector)
$parent.trigger('close')
e && e.preventDefault()
$parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent())
$parent
.trigger('close')
.removeClass('in')
function removeElement() {
$parent
.trigger('closed')
.remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent.on($.support.transition.end, removeElement) :
removeElement()
}
}
/* ALERT PLUGIN DEFINITION
* ======================= */
$.fn.alert = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('alert')
if (!data) $this.data('alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
$.fn.alert.Constructor = Alert
/* ALERT DATA-API
* ============== */
$(function () {
$('body').on('click.alert.data-api', dismiss, Alert.prototype.close)
})
}( window.jQuery );
/* ============================================================
* bootstrap-button.js v2.0.2
* http://twitter.github.com/bootstrap/javascript.html#buttons
* ============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================ */
!function( $ ){
"use strict"
/* BUTTON PUBLIC CLASS DEFINITION
* ============================== */
var Button = function ( element, options ) {
this.$element = $(element)
this.options = $.extend({}, $.fn.button.defaults, options)
}
Button.prototype = {
constructor: Button
, setState: function ( state ) {
var d = 'disabled'
, $el = this.$element
, data = $el.data()
, val = $el.is('input') ? 'val' : 'html'
state = state + 'Text'
data.resetText || $el.data('resetText', $el[val]())
$el[val](data[state] || this.options[state])
// push to event loop to allow forms to submit
setTimeout(function () {
state == 'loadingText' ?
$el.addClass(d).attr(d, d) :
$el.removeClass(d).removeAttr(d)
}, 0)
}
, toggle: function () {
var $parent = this.$element.parent('[data-toggle="buttons-radio"]')
$parent && $parent
.find('.active')
.removeClass('active')
this.$element.toggleClass('active')
}
}
/* BUTTON PLUGIN DEFINITION
* ======================== */
$.fn.button = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('button')
, options = typeof option == 'object' && option
if (!data) $this.data('button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
$.fn.button.defaults = {
loadingText: 'loading...'
}
$.fn.button.Constructor = Button
/* BUTTON DATA-API
* =============== */
$(function () {
$('body').on('click.button.data-api', '[data-toggle^=button]', function ( e ) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
$btn.button('toggle')
})
})
}( window.jQuery );
/* ==========================================================
* bootstrap-carousel.js v2.0.2
* http://twitter.github.com/bootstrap/javascript.html#carousel
* ==========================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
!function( $ ){
"use strict"
/* CAROUSEL CLASS DEFINITION
* ========================= */
var Carousel = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, $.fn.carousel.defaults, options)
this.options.slide && this.slide(this.options.slide)
this.options.pause == 'hover' && this.$element
.on('mouseenter', $.proxy(this.pause, this))
.on('mouseleave', $.proxy(this.cycle, this))
}
Carousel.prototype = {
cycle: function () {
this.interval = setInterval($.proxy(this.next, this), this.options.interval)
return this
}
, to: function (pos) {
var $active = this.$element.find('.active')
, children = $active.parent().children()
, activePos = children.index($active)
, that = this
if (pos > (children.length - 1) || pos < 0) return
if (this.sliding) {
return this.$element.one('slid', function () {
that.to(pos)
})
}
if (activePos == pos) {
return this.pause().cycle()
}
return this.slide(pos > activePos ? 'next' : 'prev', $(children[pos]))
}
, pause: function () {
clearInterval(this.interval)
this.interval = null
return this
}
, next: function () {
if (this.sliding) return
return this.slide('next')
}
, prev: function () {
if (this.sliding) return
return this.slide('prev')
}
, slide: function (type, next) {
var $active = this.$element.find('.active')
, $next = next || $active[type]()
, isCycling = this.interval
, direction = type == 'next' ? 'left' : 'right'
, fallback = type == 'next' ? 'first' : 'last'
, that = this
this.sliding = true
isCycling && this.pause()
$next = $next.length ? $next : this.$element.find('.item')[fallback]()
if ($next.hasClass('active')) return
if (!$.support.transition && this.$element.hasClass('slide')) {
this.$element.trigger('slide')
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger('slid')
} else {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
this.$element.trigger('slide')
this.$element.one($.support.transition.end, function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () { that.$element.trigger('slid') }, 0)
})
}
isCycling && this.cycle()
return this
}
}
/* CAROUSEL PLUGIN DEFINITION
* ========================== */
$.fn.carousel = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('carousel')
, options = typeof option == 'object' && option
if (!data) $this.data('carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (typeof option == 'string' || (option = options.slide)) data[option]()
else data.cycle()
})
}
$.fn.carousel.defaults = {
interval: 5000
, pause: 'hover'
}
$.fn.carousel.Constructor = Carousel
/* CAROUSEL DATA-API
* ================= */
$(function () {
$('body').on('click.carousel.data-api', '[data-slide]', function ( e ) {
var $this = $(this), href
, $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
, options = !$target.data('modal') && $.extend({}, $target.data(), $this.data())
$target.carousel(options)
e.preventDefault()
})
})
}( window.jQuery );
/* =============================================================
* bootstrap-collapse.js v2.0.2
* http://twitter.github.com/bootstrap/javascript.html#collapse
* =============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================ */
!function( $ ){
"use strict"
var Collapse = function ( element, options ) {
this.$element = $(element)
this.options = $.extend({}, $.fn.collapse.defaults, options)
if (this.options["parent"]) {
this.$parent = $(this.options["parent"])
}
this.options.toggle && this.toggle()
}
Collapse.prototype = {
constructor: Collapse
, dimension: function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
, show: function () {
var dimension = this.dimension()
, scroll = $.camelCase(['scroll', dimension].join('-'))
, actives = this.$parent && this.$parent.find('.in')
, hasData
if (actives && actives.length) {
hasData = actives.data('collapse')
actives.collapse('hide')
hasData || actives.data('collapse', null)
}
this.$element[dimension](0)
this.transition('addClass', 'show', 'shown')
this.$element[dimension](this.$element[0][scroll])
}
, hide: function () {
var dimension = this.dimension()
this.reset(this.$element[dimension]())
this.transition('removeClass', 'hide', 'hidden')
this.$element[dimension](0)
}
, reset: function ( size ) {
var dimension = this.dimension()
this.$element
.removeClass('collapse')
[dimension](size || 'auto')
[0].offsetWidth
this.$element[size ? 'addClass' : 'removeClass']('collapse')
return this
}
, transition: function ( method, startEvent, completeEvent ) {
var that = this
, complete = function () {
if (startEvent == 'show') that.reset()
that.$element.trigger(completeEvent)
}
this.$element
.trigger(startEvent)
[method]('in')
$.support.transition && this.$element.hasClass('collapse') ?
this.$element.one($.support.transition.end, complete) :
complete()
}
, toggle: function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
}
/* COLLAPSIBLE PLUGIN DEFINITION
* ============================== */
$.fn.collapse = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('collapse')
, options = typeof option == 'object' && option
if (!data) $this.data('collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.collapse.defaults = {
toggle: true
}
$.fn.collapse.Constructor = Collapse
/* COLLAPSIBLE DATA-API
* ==================== */
$(function () {
$('body').on('click.collapse.data-api', '[data-toggle=collapse]', function ( e ) {
var $this = $(this), href
, target = $this.attr('data-target')
|| e.preventDefault()
|| (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
, option = $(target).data('collapse') ? 'toggle' : $this.data()
$(target).collapse(option)
})
})
}( window.jQuery );
/* =========================================================
* bootstrap-modal.js v2.0.2
* http://twitter.github.com/bootstrap/javascript.html#modals
* =========================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================= */
!function( $ ){
"use strict"
/* MODAL CLASS DEFINITION
* ====================== */
var Modal = function ( content, options ) {
this.options = options
this.$element = $(content)
.delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this))
}
Modal.prototype = {
constructor: Modal
, toggle: function () {
return this[!this.isShown ? 'show' : 'hide']()
}
, show: function () {
var that = this
if (this.isShown) return
$('body').addClass('modal-open')
this.isShown = true
this.$element.trigger('show')
escape.call(this)
backdrop.call(this, function () {
var transition = $.support.transition && that.$element.hasClass('fade')
!that.$element.parent().length && that.$element.appendTo(document.body) //don't move modals dom position
that.$element
.show()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element.addClass('in')
transition ?
that.$element.one($.support.transition.end, function () { that.$element.trigger('shown') }) :
that.$element.trigger('shown')
})
}
, hide: function ( e ) {
e && e.preventDefault()
if (!this.isShown) return
var that = this
this.isShown = false
$('body').removeClass('modal-open')
escape.call(this)
this.$element
.trigger('hide')
.removeClass('in')
$.support.transition && this.$element.hasClass('fade') ?
hideWithTransition.call(this) :
hideModal.call(this)
}
}
/* MODAL PRIVATE METHODS
* ===================== */
function hideWithTransition() {
var that = this
, timeout = setTimeout(function () {
that.$element.off($.support.transition.end)
hideModal.call(that)
}, 500)
this.$element.one($.support.transition.end, function () {
clearTimeout(timeout)
hideModal.call(that)
})
}
function hideModal( that ) {
this.$element
.hide()
.trigger('hidden')
backdrop.call(this)
}
function backdrop( callback ) {
var that = this
, animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
.appendTo(document.body)
if (this.options.backdrop != 'static') {
this.$backdrop.click($.proxy(this.hide, this))
}
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
doAnimate ?
this.$backdrop.one($.support.transition.end, callback) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
$.support.transition && this.$element.hasClass('fade')?
this.$backdrop.one($.support.transition.end, $.proxy(removeBackdrop, this)) :
removeBackdrop.call(this)
} else if (callback) {
callback()
}
}
function removeBackdrop() {
this.$backdrop.remove()
this.$backdrop = null
}
function escape() {
var that = this
if (this.isShown && this.options.keyboard) {
$(document).on('keyup.dismiss.modal', function ( e ) {
e.which == 27 && that.hide()
})
} else if (!this.isShown) {
$(document).off('keyup.dismiss.modal')
}
}
/* MODAL PLUGIN DEFINITION
* ======================= */
$.fn.modal = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('modal')
, options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option]()
else if (options.show) data.show()
})
}
$.fn.modal.defaults = {
backdrop: true
, keyboard: true
, show: true
}
$.fn.modal.Constructor = Modal
/* MODAL DATA-API
* ============== */
$(function () {
$('body').on('click.modal.data-api', '[data-toggle="modal"]', function ( e ) {
var $this = $(this), href
, $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
, option = $target.data('modal') ? 'toggle' : $.extend({}, $target.data(), $this.data())
e.preventDefault()
$target.modal(option)
})
})
}( window.jQuery );
/* =============================================================
* bootstrap-scrollspy.js v2.0.2
* http://twitter.github.com/bootstrap/javascript.html#scrollspy
* =============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================== */
!function ( $ ) {
"use strict"
/* SCROLLSPY CLASS DEFINITION
* ========================== */
function ScrollSpy( element, options) {
var process = $.proxy(this.process, this)
, $element = $(element).is('body') ? $(window) : $(element)
, href
this.options = $.extend({}, $.fn.scrollspy.defaults, options)
this.$scrollElement = $element.on('scroll.scroll.data-api', process)
this.selector = (this.options.target
|| ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
|| '') + ' .nav li > a'
this.$body = $('body').on('click.scroll.data-api', this.selector, process)
this.refresh()
this.process()
}
ScrollSpy.prototype = {
constructor: ScrollSpy
, refresh: function () {
this.targets = this.$body
.find(this.selector)
.map(function () {
var href = $(this).attr('href')
return /^#\w/.test(href) && $(href).length ? href : null
})
this.offsets = $.map(this.targets, function (id) {
return $(id).position().top
})
}
, process: function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
, offsets = this.offsets
, targets = this.targets
, activeTarget = this.activeTarget
, i
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (!offsets[i + 1] || scrollTop <= offsets[i + 1])
&& this.activate( targets[i] )
}
}
, activate: function (target) {
var active
this.activeTarget = target
this.$body
.find(this.selector).parent('.active')
.removeClass('active')
active = this.$body
.find(this.selector + '[href="' + target + '"]')
.parent('li')
.addClass('active')
if ( active.parent('.dropdown-menu') ) {
active.closest('li.dropdown').addClass('active')
}
}
}
/* SCROLLSPY PLUGIN DEFINITION
* =========================== */
$.fn.scrollspy = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('scrollspy')
, options = typeof option == 'object' && option
if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.scrollspy.Constructor = ScrollSpy
$.fn.scrollspy.defaults = {
offset: 10
}
/* SCROLLSPY DATA-API
* ================== */
$(function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
$spy.scrollspy($spy.data())
})
})
}( window.jQuery );
/* ===========================================================
* bootstrap-tooltip.js v2.0.2
* http://twitter.github.com/bootstrap/javascript.html#tooltips
* Inspired by the original jQuery.tipsy by Jason Frame
* ===========================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
!function( $ ) {
"use strict"
/* TOOLTIP PUBLIC CLASS DEFINITION
* =============================== */
var Tooltip = function ( element, options ) {
this.init('tooltip', element, options)
}
Tooltip.prototype = {
constructor: Tooltip
, init: function ( type, element, options ) {
var eventIn
, eventOut
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.enabled = true
if (this.options.trigger != 'manual') {
eventIn = this.options.trigger == 'hover' ? 'mouseenter' : 'focus'
eventOut = this.options.trigger == 'hover' ? 'mouseleave' : 'blur'
this.$element.on(eventIn, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut, this.options.selector, $.proxy(this.leave, this))
}
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
, getOptions: function ( options ) {
options = $.extend({}, $.fn[this.type].defaults, options, this.$element.data())
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay
, hide: options.delay
}
}
return options
}
, enter: function ( e ) {
var self = $(e.currentTarget)[this.type](this._options).data(this.type)
if (!self.options.delay || !self.options.delay.show) {
self.show()
} else {
self.hoverState = 'in'
setTimeout(function() {
if (self.hoverState == 'in') {
self.show()
}
}, self.options.delay.show)
}
}
, leave: function ( e ) {
var self = $(e.currentTarget)[this.type](this._options).data(this.type)
if (!self.options.delay || !self.options.delay.hide) {
self.hide()
} else {
self.hoverState = 'out'
setTimeout(function() {
if (self.hoverState == 'out') {
self.hide()
}
}, self.options.delay.hide)
}
}
, show: function () {
var $tip
, inside
, pos
, actualWidth
, actualHeight
, placement
, tp
if (this.hasContent() && this.enabled) {
$tip = this.tip()
this.setContent()
if (this.options.animation) {
$tip.addClass('fade')
}
placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
inside = /in/.test(placement)
$tip
.remove()
.css({ top: 0, left: 0, display: 'block' })
.appendTo(inside ? this.$element : document.body)
pos = this.getPosition(inside)
actualWidth = $tip[0].offsetWidth
actualHeight = $tip[0].offsetHeight
switch (inside ? placement.split(' ')[1] : placement) {
case 'bottom':
tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}
break
case 'top':
tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2}
break
case 'left':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}
break
case 'right':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}
break
}
$tip
.css(tp)
.addClass(placement)
.addClass('in')
}
}
, setContent: function () {
var $tip = this.tip()
$tip.find('.tooltip-inner').html(this.getTitle())
$tip.removeClass('fade in top bottom left right')
}
, hide: function () {
var that = this
, $tip = this.tip()
$tip.removeClass('in')
function removeWithAnimation() {
var timeout = setTimeout(function () {
$tip.off($.support.transition.end).remove()
}, 500)
$tip.one($.support.transition.end, function () {
clearTimeout(timeout)
$tip.remove()
})
}
$.support.transition && this.$tip.hasClass('fade') ?
removeWithAnimation() :
$tip.remove()
}
, fixTitle: function () {
var $e = this.$element
if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').removeAttr('title')
}
}
, hasContent: function () {
return this.getTitle()
}
, getPosition: function (inside) {
return $.extend({}, (inside ? {top: 0, left: 0} : this.$element.offset()), {
width: this.$element[0].offsetWidth
, height: this.$element[0].offsetHeight
})
}
, getTitle: function () {
var title
, $e = this.$element
, o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
title = (title || '').toString().replace(/(^\s*|\s*$)/, "")
return title
}
, tip: function () {
return this.$tip = this.$tip || $(this.options.template)
}
, validate: function () {
if (!this.$element[0].parentNode) {
this.hide()
this.$element = null
this.options = null
}
}
, enable: function () {
this.enabled = true
}
, disable: function () {
this.enabled = false
}
, toggleEnabled: function () {
this.enabled = !this.enabled
}
, toggle: function () {
this[this.tip().hasClass('in') ? 'hide' : 'show']()
}
}
/* TOOLTIP PLUGIN DEFINITION
* ========================= */
$.fn.tooltip = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('tooltip')
, options = typeof option == 'object' && option
if (!data) $this.data('tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.tooltip.Constructor = Tooltip
$.fn.tooltip.defaults = {
animation: true
, delay: 0
, selector: false
, placement: 'top'
, trigger: 'hover'
, title: ''
, template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
}
}( window.jQuery );
/* ===========================================================
* bootstrap-popover.js v2.0.2
* http://twitter.github.com/bootstrap/javascript.html#popovers
* ===========================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================================================== */
!function( $ ) {
"use strict"
var Popover = function ( element, options ) {
this.init('popover', element, options)
}
/* NOTE: POPOVER EXTENDS BOOTSTRAP-TOOLTIP.js
========================================== */
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype, {
constructor: Popover
, setContent: function () {
var $tip = this.tip()
, title = this.getTitle()
, content = this.getContent()
$tip.find('.popover-title')[ $.type(title) == 'object' ? 'append' : 'html' ](title)
$tip.find('.popover-content > *')[ $.type(content) == 'object' ? 'append' : 'html' ](content)
$tip.removeClass('fade top bottom left right in')
}
, hasContent: function () {
return this.getTitle() || this.getContent()
}
, getContent: function () {
var content
, $e = this.$element
, o = this.options
content = $e.attr('data-content')
|| (typeof o.content == 'function' ? o.content.call($e[0]) : o.content)
content = content.toString().replace(/(^\s*|\s*$)/, "")
return content
}
, tip: function() {
if (!this.$tip) {
this.$tip = $(this.options.template)
}
return this.$tip
}
})
/* POPOVER PLUGIN DEFINITION
* ======================= */
$.fn.popover = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('popover')
, options = typeof option == 'object' && option
if (!data) $this.data('popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.popover.Constructor = Popover
$.fn.popover.defaults = $.extend({} , $.fn.tooltip.defaults, {
placement: 'right'
, content: ''
, template: '<div class="popover"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>'
})
}( window.jQuery );
/* =============================================================
* bootstrap-typeahead.js v2.0.2
* http://twitter.github.com/bootstrap/javascript.html#typeahead
* =============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================ */
!function( $ ){
"use strict"
var Typeahead = function ( element, options ) {
this.$element = $(element)
this.options = $.extend({}, $.fn.typeahead.defaults, options)
this.matcher = this.options.matcher || this.matcher
this.sorter = this.options.sorter || this.sorter
this.highlighter = this.options.highlighter || this.highlighter
this.$menu = $(this.options.menu).appendTo('body')
this.source = this.options.source
this.shown = false
this.listen()
}
Typeahead.prototype = {
constructor: Typeahead
, select: function () {
var val = this.$menu.find('.active').attr('data-value')
this.$element.val(val)
this.$element.change();
return this.hide()
}
, show: function () {
var pos = $.extend({}, this.$element.offset(), {
height: this.$element[0].offsetHeight
})
this.$menu.css({
top: pos.top + pos.height
, left: pos.left
})
this.$menu.show()
this.shown = true
return this
}
, hide: function () {
this.$menu.hide()
this.shown = false
return this
}
, lookup: function (event) {
var that = this
, items
, q
this.query = this.$element.val()
if (!this.query) {
return this.shown ? this.hide() : this
}
items = $.grep(this.source, function (item) {
if (that.matcher(item)) return item
})
items = this.sorter(items)
if (!items.length) {
return this.shown ? this.hide() : this
}
return this.render(items.slice(0, this.options.items)).show()
}
, matcher: function (item) {
return ~item.toLowerCase().indexOf(this.query.toLowerCase())
}
, sorter: function (items) {
var beginswith = []
, caseSensitive = []
, caseInsensitive = []
, item
while (item = items.shift()) {
if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item)
else if (~item.indexOf(this.query)) caseSensitive.push(item)
else caseInsensitive.push(item)
}
return beginswith.concat(caseSensitive, caseInsensitive)
}
, highlighter: function (item) {
return item.replace(new RegExp('(' + this.query + ')', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>'
})
}
, render: function (items) {
var that = this
items = $(items).map(function (i, item) {
i = $(that.options.item).attr('data-value', item)
i.find('a').html(that.highlighter(item))
return i[0]
})
items.first().addClass('active')
this.$menu.html(items)
return this
}
, next: function (event) {
var active = this.$menu.find('.active').removeClass('active')
, next = active.next()
if (!next.length) {
next = $(this.$menu.find('li')[0])
}
next.addClass('active')
}
, prev: function (event) {
var active = this.$menu.find('.active').removeClass('active')
, prev = active.prev()
if (!prev.length) {
prev = this.$menu.find('li').last()
}
prev.addClass('active')
}
, listen: function () {
this.$element
.on('blur', $.proxy(this.blur, this))
.on('keypress', $.proxy(this.keypress, this))
.on('keyup', $.proxy(this.keyup, this))
if ($.browser.webkit || $.browser.msie) {
this.$element.on('keydown', $.proxy(this.keypress, this))
}
this.$menu
.on('click', $.proxy(this.click, this))
.on('mouseenter', 'li', $.proxy(this.mouseenter, this))
}
, keyup: function (e) {
switch(e.keyCode) {
case 40: // down arrow
case 38: // up arrow
break
case 9: // tab
case 13: // enter
if (!this.shown) return
this.select()
break
case 27: // escape
if (!this.shown) return
this.hide()
break
default:
this.lookup()
}
e.stopPropagation()
e.preventDefault()
}
, keypress: function (e) {
if (!this.shown) return
switch(e.keyCode) {
case 9: // tab
case 13: // enter
case 27: // escape
e.preventDefault()
break
case 38: // up arrow
e.preventDefault()
this.prev()
break
case 40: // down arrow
e.preventDefault()
this.next()
break
}
e.stopPropagation()
}
, blur: function (e) {
var that = this
setTimeout(function () { that.hide() }, 150)
}
, click: function (e) {
e.stopPropagation()
e.preventDefault()
this.select()
}
, mouseenter: function (e) {
this.$menu.find('.active').removeClass('active')
$(e.currentTarget).addClass('active')
}
}
/* TYPEAHEAD PLUGIN DEFINITION
* =========================== */
$.fn.typeahead = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('typeahead')
, options = typeof option == 'object' && option
if (!data) $this.data('typeahead', (data = new Typeahead(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.typeahead.defaults = {
source: []
, items: 8
, menu: '<ul class="typeahead dropdown-menu"></ul>'
, item: '<li><a href="#"></a></li>'
}
$.fn.typeahead.Constructor = Typeahead
/* TYPEAHEAD DATA-API
* ================== */
$(function () {
$('body').on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
var $this = $(this)
if ($this.data('typeahead')) return
e.preventDefault()
$this.typeahead($this.data())
})
})
}( window.jQuery );
/*
json2.js
2011-10-19
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or '&nbsp;'),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
var JSON;
if (!JSON) {
JSON = {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
// Underscore.js 1.3.3
// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore is freely distributable under the MIT license.
// Portions of Underscore are inspired or borrowed from Prototype,
// Oliver Steele's Functional, and John Resig's Micro-Templating.
// For all details and documentation:
// http://documentcloud.github.com/underscore
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `global` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Establish the object that gets returned to break out of a loop iteration.
var breaker = {};
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var slice = ArrayProto.slice,
unshift = ArrayProto.unshift,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeForEach = ArrayProto.forEach,
nativeMap = ArrayProto.map,
nativeReduce = ArrayProto.reduce,
nativeReduceRight = ArrayProto.reduceRight,
nativeFilter = ArrayProto.filter,
nativeEvery = ArrayProto.every,
nativeSome = ArrayProto.some,
nativeIndexOf = ArrayProto.indexOf,
nativeLastIndexOf = ArrayProto.lastIndexOf,
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) { return new wrapper(obj); };
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object via a string identifier,
// for Closure Compiler "advanced" mode.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root['_'] = _;
}
// Current version.
_.VERSION = '1.3.3';
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (_.has(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
// Return the results of applying the iterator to each element.
// Delegates to **ECMAScript 5**'s native `map` if available.
_.map = _.collect = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
each(obj, function(value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
if (obj.length === +obj.length) results.length = obj.length;
return results;
};
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
_.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduce && obj.reduce === nativeReduce) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
}
each(obj, function(value, index, list) {
if (!initial) {
memo = value;
initial = true;
} else {
memo = iterator.call(context, memo, value, index, list);
}
});
if (!initial) throw new TypeError('Reduce of empty array with no initial value');
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
// Delegates to **ECMAScript 5**'s native `reduceRight` if available.
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
}
var reversed = _.toArray(obj).reverse();
if (context && !initial) iterator = _.bind(iterator, context);
return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator);
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, iterator, context) {
var result;
any(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Delegates to **ECMAScript 5**'s native `filter` if available.
// Aliased as `select`.
_.filter = _.select = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
each(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
each(obj, function(value, index, list) {
if (!iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Determine whether all of the elements match a truth test.
// Delegates to **ECMAScript 5**'s native `every` if available.
// Aliased as `all`.
_.every = _.all = function(obj, iterator, context) {
var result = true;
if (obj == null) return result;
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
each(obj, function(value, index, list) {
if (!(result = result && iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if at least one element in the object matches a truth test.
// Delegates to **ECMAScript 5**'s native `some` if available.
// Aliased as `any`.
var any = _.some = _.any = function(obj, iterator, context) {
iterator || (iterator = _.identity);
var result = false;
if (obj == null) return result;
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
each(obj, function(value, index, list) {
if (result || (result = iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if a given value is included in the array or object using `===`.
// Aliased as `contains`.
_.include = _.contains = function(obj, target) {
var found = false;
if (obj == null) return found;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
found = any(obj, function(value) {
return value === target;
});
return found;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
return _.map(obj, function(value) {
return (_.isFunction(method) ? method || value : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, function(value){ return value[key]; });
};
// Return the maximum element or (element-based computation).
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0]) return Math.max.apply(Math, obj);
if (!iterator && _.isEmpty(obj)) return -Infinity;
var result = {computed : -Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed >= result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0]) return Math.min.apply(Math, obj);
if (!iterator && _.isEmpty(obj)) return Infinity;
var result = {computed : Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed < result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Shuffle an array.
_.shuffle = function(obj) {
var shuffled = [], rand;
each(obj, function(value, index, list) {
rand = Math.floor(Math.random() * (index + 1));
shuffled[index] = shuffled[rand];
shuffled[rand] = value;
});
return shuffled;
};
// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, val, context) {
var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
return _.pluck(_.map(obj, function(value, index, list) {
return {
value : value,
criteria : iterator.call(context, value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
if (a === void 0) return 1;
if (b === void 0) return -1;
return a < b ? -1 : a > b ? 1 : 0;
}), 'value');
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = function(obj, val) {
var result = {};
var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
each(obj, function(value, index) {
var key = iterator(value, index);
(result[key] || (result[key] = [])).push(value);
});
return result;
};
// Use a comparator function to figure out at what index an object should
// be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iterator) {
iterator || (iterator = _.identity);
var low = 0, high = array.length;
while (low < high) {
var mid = (low + high) >> 1;
iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
}
return low;
};
// Safely convert anything iterable into a real, live array.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (_.isArguments(obj)) return slice.call(obj);
if (obj.toArray && _.isFunction(obj.toArray)) return obj.toArray();
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
return _.isArray(obj) ? obj.length : _.keys(obj).length;
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
};
// Returns everything but the last entry of the array. Especcialy useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N. The **guard** check allows it to work with
// `_.map`.
_.initial = function(array, n, guard) {
return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
if ((n != null) && !guard) {
return slice.call(array, Math.max(array.length - n, 0));
} else {
return array[array.length - 1];
}
};
// Returns everything but the first entry of the array. Aliased as `tail`.
// Especially useful on the arguments object. Passing an **index** will return
// the rest of the values in the array from that index onward. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = function(array, index, guard) {
return slice.call(array, (index == null) || guard ? 1 : index);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, function(value){ return !!value; });
};
// Return a completely flattened version of an array.
_.flatten = function(array, shallow) {
return _.reduce(array, function(memo, value) {
if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));
memo[memo.length] = value;
return memo;
}, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iterator) {
var initial = iterator ? _.map(array, iterator) : array;
var results = [];
// The `isSorted` flag is irrelevant if the array only contains two elements.
if (array.length < 3) isSorted = true;
_.reduce(initial, function (memo, value, index) {
if (isSorted ? _.last(memo) !== value || !memo.length : !_.include(memo, value)) {
memo.push(value);
results.push(array[index]);
}
return memo;
}, []);
return results;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(_.flatten(arguments, true));
};
// Produce an array that contains every item shared between all the
// passed-in arrays. (Aliased as "intersect" for back-compat.)
_.intersection = _.intersect = function(array) {
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.indexOf(other, item) >= 0;
});
});
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = _.flatten(slice.call(arguments, 1), true);
return _.filter(array, function(value){ return !_.include(rest, value); });
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
var args = slice.call(arguments);
var length = _.max(_.pluck(args, 'length'));
var results = new Array(length);
for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
return results;
};
// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
// we need this function. Return the position of the first occurrence of an
// item in an array, or -1 if the item is not included in the array.
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i, l;
if (isSorted) {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i;
return -1;
};
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
_.lastIndexOf = function(array, item) {
if (array == null) return -1;
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
var i = array.length;
while (i--) if (i in array && array[i] === item) return i;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = arguments[2] || 1;
var len = Math.max(Math.ceil((stop - start) / step), 0);
var idx = 0;
var range = new Array(len);
while(idx < len) {
range[idx++] = start;
start += step;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Reusable constructor function for prototype setting.
var ctor = function(){};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Binding with arguments is also known as `curry`.
// Delegates to **ECMAScript 5**'s native `Function.bind` if available.
// We check for `func.bind` first, to fail fast when `func` is undefined.
_.bind = function bind(func, context) {
var bound, args;
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError;
args = slice.call(arguments, 2);
return bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
ctor.prototype = func.prototype;
var self = new ctor;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) return result;
return self;
};
};
// Bind all of an object's methods to that object. Useful for ensuring that
// all callbacks defined on an object belong to it.
_.bindAll = function(obj) {
var funcs = slice.call(arguments, 1);
if (funcs.length == 0) funcs = _.functions(obj);
each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memo = {};
hasher || (hasher = _.identity);
return function() {
var key = hasher.apply(this, arguments);
return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
};
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){ return func.apply(null, args); }, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time.
_.throttle = function(func, wait) {
var context, args, timeout, throttling, more, result;
var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
return function() {
context = this; args = arguments;
var later = function() {
timeout = null;
if (more) func.apply(context, args);
whenDone();
};
if (!timeout) timeout = setTimeout(later, wait);
if (throttling) {
more = true;
} else {
result = func.apply(context, args);
}
whenDone();
throttling = true;
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
if (immediate && !timeout) func.apply(context, args);
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
return memo = func.apply(this, arguments);
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return function() {
var args = [func].concat(slice.call(arguments, 0));
return wrapper.apply(this, args);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var funcs = arguments;
return function() {
var args = arguments;
for (var i = funcs.length - 1; i >= 0; i--) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
if (times <= 0) return func();
return function() {
if (--times < 1) { return func.apply(this, arguments); }
};
};
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = nativeKeys || function(obj) {
if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
return _.map(obj, _.identity);
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
obj[prop] = source[prop];
}
});
return obj;
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(obj) {
var result = {};
each(_.flatten(slice.call(arguments, 1)), function(key) {
if (key in obj) result[key] = obj[key];
});
return result;
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
if (obj[prop] == null) obj[prop] = source[prop];
}
});
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Internal recursive comparison function.
function eq(a, b, stack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
if (a === b) return a !== 0 || 1 / a == 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a._chain) a = a._wrapped;
if (b._chain) b = b._wrapped;
// Invoke a custom `isEqual` method if one is provided.
if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b);
if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a);
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className != toString.call(b)) return false;
switch (className) {
// Strings, numbers, dates, and booleans are compared by value.
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return a == String(b);
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
// other numeric values.
return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a == +b;
// RegExps are compared by their source patterns and flags.
case '[object RegExp]':
return a.source == b.source &&
a.global == b.global &&
a.multiline == b.multiline &&
a.ignoreCase == b.ignoreCase;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = stack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (stack[length] == a) return true;
}
// Add the first object to the stack of traversed objects.
stack.push(a);
var size = 0, result = true;
// Recursively compare objects and arrays.
if (className == '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size == b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
// Ensure commutative equality for sparse arrays.
if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;
}
}
} else {
// Objects with different constructors are not equivalent.
if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false;
// Deep compare objects.
for (var key in a) {
if (_.has(a, key)) {
// Count the expected number of properties.
size++;
// Deep compare each member.
if (!(result = _.has(b, key) && eq(a[key], b[key], stack))) break;
}
}
// Ensure that both objects contain the same number of properties.
if (result) {
for (key in b) {
if (_.has(b, key) && !(size--)) break;
}
result = !size;
}
}
// Remove the first object from the stack of traversed objects.
stack.pop();
return result;
}
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b, []);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (_.has(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType == 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) == '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
return obj === Object(obj);
};
// Is a given variable an arguments object?
_.isArguments = function(obj) {
return toString.call(obj) == '[object Arguments]';
};
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return !!(obj && _.has(obj, 'callee'));
};
}
// Is a given value a function?
_.isFunction = function(obj) {
return toString.call(obj) == '[object Function]';
};
// Is a given value a string?
_.isString = function(obj) {
return toString.call(obj) == '[object String]';
};
// Is a given value a number?
_.isNumber = function(obj) {
return toString.call(obj) == '[object Number]';
};
// Is a given object a finite number?
_.isFinite = function(obj) {
return _.isNumber(obj) && isFinite(obj);
};
// Is the given value `NaN`?
_.isNaN = function(obj) {
// `NaN` is the only value for which `===` is not reflexive.
return obj !== obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};
// Is a given value a date?
_.isDate = function(obj) {
return toString.call(obj) == '[object Date]';
};
// Is the given value a regular expression?
_.isRegExp = function(obj) {
return toString.call(obj) == '[object RegExp]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Has own property?
_.has = function(obj, key) {
return hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iterators.
_.identity = function(value) {
return value;
};
// Run a function **n** times.
_.times = function (n, iterator, context) {
for (var i = 0; i < n; i++) iterator.call(context, i);
};
// Escape a string for HTML interpolation.
_.escape = function(string) {
return (''+string).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;');
};
// If the value of the named property is a function then invoke it;
// otherwise, return it.
_.result = function(object, property) {
if (object == null) return null;
var value = object[property];
return _.isFunction(value) ? value.call(object) : value;
};
// Add your own custom functions to the Underscore object, ensuring that
// they're correctly added to the OOP wrapper as well.
_.mixin = function(obj) {
each(_.functions(obj), function(name){
addToWrapper(name, _[name] = obj[name]);
});
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = idCounter++;
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /.^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
'\\': '\\',
"'": "'",
'r': '\r',
'n': '\n',
't': '\t',
'u2028': '\u2028',
'u2029': '\u2029'
};
for (var p in escapes) escapes[escapes[p]] = p;
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
var unescaper = /\\(\\|'|r|n|t|u2028|u2029)/g;
// Within an interpolation, evaluation, or escaping, remove HTML escaping
// that had been previously added.
var unescape = function(code) {
return code.replace(unescaper, function(match, escape) {
return escapes[escape];
});
};
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(text, data, settings) {
settings = _.defaults(settings || {}, _.templateSettings);
// Compile the template source, taking care to escape characters that
// cannot be included in a string literal and then unescape them in code
// blocks.
var source = "__p+='" + text
.replace(escaper, function(match) {
return '\\' + escapes[match];
})
.replace(settings.escape || noMatch, function(match, code) {
return "'+\n_.escape(" + unescape(code) + ")+\n'";
})
.replace(settings.interpolate || noMatch, function(match, code) {
return "'+\n(" + unescape(code) + ")+\n'";
})
.replace(settings.evaluate || noMatch, function(match, code) {
return "';\n" + unescape(code) + "\n;__p+='";
}) + "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __p='';" +
"var print=function(){__p+=Array.prototype.join.call(arguments, '')};\n" +
source + "return __p;\n";
var render = new Function(settings.variable || 'obj', '_', source);
if (data) return render(data, _);
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled function source as a convenience for build time
// precompilation.
template.source = 'function(' + (settings.variable || 'obj') + '){\n' +
source + '}';
return template;
};
// Add a "chain" function, which will delegate to the wrapper.
_.chain = function(obj) {
return _(obj).chain();
};
// The OOP Wrapper
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
var wrapper = function(obj) { this._wrapped = obj; };
// Expose `wrapper.prototype` as `_.prototype`
_.prototype = wrapper.prototype;
// Helper function to continue chaining intermediate results.
var result = function(obj, chain) {
return chain ? _(obj).chain() : obj;
};
// A method to easily add functions to the OOP wrapper.
var addToWrapper = function(name, func) {
wrapper.prototype[name] = function() {
var args = slice.call(arguments);
unshift.call(args, this._wrapped);
return result(func.apply(_, args), this._chain);
};
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
wrapper.prototype[name] = function() {
var wrapped = this._wrapped;
method.apply(wrapped, arguments);
var length = wrapped.length;
if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0];
return result(wrapped, this._chain);
};
});
// Add all accessor Array functions to the wrapper.
each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
wrapper.prototype[name] = function() {
return result(method.apply(this._wrapped, arguments), this._chain);
};
});
// Start chaining a wrapped Underscore object.
wrapper.prototype.chain = function() {
this._chain = true;
return this;
};
// Extracts the result from a wrapped and chained object.
wrapper.prototype.value = function() {
return this._wrapped;
};
}).call(this);
// Underscore.string
// (c) 2010 Esa-Matti Suuronen <esa-matti aet suuronen dot org>
// Underscore.strings is freely distributable under the terms of the MIT license.
// Documentation: https://github.com/epeli/underscore.string
// Some code is borrowed from MooTools and Alexandru Marasteanu.
// Version 2.0.0
(function(root){
'use strict';
// Defining helper functions.
var nativeTrim = String.prototype.trim;
var nativeTrimRight = String.prototype.trimRight;
var nativeTrimLeft = String.prototype.trimLeft;
var parseNumber = function(source) { return source * 1 || 0; };
var strRepeat = function(i, m) {
for (var o = []; m > 0; o[--m] = i) {}
return o.join('');
};
var slice = function(a){
return Array.prototype.slice.call(a);
};
var defaultToWhiteSpace = function(characters){
if (characters != null) {
return '[' + _s.escapeRegExp(''+characters) + ']';
}
return '\\s';
};
// sprintf() for JavaScript 0.7-beta1
// http://www.diveintojavascript.com/projects/javascript-sprintf
//
// Copyright (c) Alexandru Marasteanu <alexaholic [at) gmail (dot] com>
// All rights reserved.
var sprintf = (function() {
function get_type(variable) {
return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
}
var str_repeat = strRepeat;
var str_format = function() {
if (!str_format.cache.hasOwnProperty(arguments[0])) {
str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
}
return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
};
str_format.format = function(parse_tree, argv) {
var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
for (i = 0; i < tree_length; i++) {
node_type = get_type(parse_tree[i]);
if (node_type === 'string') {
output.push(parse_tree[i]);
}
else if (node_type === 'array') {
match = parse_tree[i]; // convenience purposes only
if (match[2]) { // keyword argument
arg = argv[cursor];
for (k = 0; k < match[2].length; k++) {
if (!arg.hasOwnProperty(match[2][k])) {
throw new Error(sprintf('[_.sprintf] property "%s" does not exist', match[2][k]));
}
arg = arg[match[2][k]];
}
} else if (match[1]) { // positional argument (explicit)
arg = argv[match[1]];
}
else { // positional argument (implicit)
arg = argv[cursor++];
}
if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
throw new Error(sprintf('[_.sprintf] expecting number but found %s', get_type(arg)));
}
switch (match[8]) {
case 'b': arg = arg.toString(2); break;
case 'c': arg = String.fromCharCode(arg); break;
case 'd': arg = parseInt(arg, 10); break;
case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
case 'o': arg = arg.toString(8); break;
case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
case 'u': arg = Math.abs(arg); break;
case 'x': arg = arg.toString(16); break;
case 'X': arg = arg.toString(16).toUpperCase(); break;
}
arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
pad_length = match[6] - String(arg).length;
pad = match[6] ? str_repeat(pad_character, pad_length) : '';
output.push(match[5] ? arg + pad : pad + arg);
}
}
return output.join('');
};
str_format.cache = {};
str_format.parse = function(fmt) {
var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
while (_fmt) {
if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
parse_tree.push(match[0]);
}
else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
parse_tree.push('%');
}
else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
if (match[2]) {
arg_names |= 1;
var field_list = [], replacement_field = match[2], field_match = [];
if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
}
else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
}
else {
throw new Error('[_.sprintf] huh?');
}
}
}
else {
throw new Error('[_.sprintf] huh?');
}
match[2] = field_list;
}
else {
arg_names |= 2;
}
if (arg_names === 3) {
throw new Error('[_.sprintf] mixing positional and named placeholders is not (yet) supported');
}
parse_tree.push(match);
}
else {
throw new Error('[_.sprintf] huh?');
}
_fmt = _fmt.substring(match[0].length);
}
return parse_tree;
};
return str_format;
})();
// Defining underscore.string
var _s = {
VERSION: '2.0.0',
isBlank: function(str){
return (/^\s*$/).test(str);
},
stripTags: function(str){
return (''+str).replace(/<\/?[^>]+>/ig, '');
},
capitalize : function(str) {
str = ''+str;
return str.charAt(0).toUpperCase() + str.substring(1).toLowerCase();
},
chop: function(str, step){
str = str+'';
step = ~~step || str.length;
var arr = [];
for (var i = 0; i < str.length;) {
arr.push(str.slice(i,i + step));
i = i + step;
}
return arr;
},
clean: function(str){
return _s.strip((''+str).replace(/\s+/g, ' '));
},
count: function(str, substr){
str = ''+str; substr = ''+substr;
var count = 0, index;
for (var i=0; i < str.length;) {
index = str.indexOf(substr, i);
index >= 0 && count++;
i = i + (index >= 0 ? index : 0) + substr.length;
}
return count;
},
chars: function(str) {
return (''+str).split('');
},
escapeHTML: function(str) {
return (''+str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')
.replace(/"/g, '&quot;').replace(/'/g, "&apos;");
},
unescapeHTML: function(str) {
return (''+str).replace(/&lt;/g, '<').replace(/&gt;/g, '>')
.replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, '&');
},
escapeRegExp: function(str){
// From MooTools core 1.2.4
return str.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1');
},
insert: function(str, i, substr){
var arr = (''+str).split('');
arr.splice(~~i, 0, ''+substr);
return arr.join('');
},
include: function(str, needle){
return (''+str).indexOf(needle) !== -1;
},
join: function(sep) {
var args = slice(arguments);
return args.join(args.shift());
},
lines: function(str) {
return (''+str).split("\n");
},
reverse: function(str){
return Array.prototype.reverse.apply(String(str).split('')).join('');
},
splice: function(str, i, howmany, substr){
var arr = (''+str).split('');
arr.splice(~~i, ~~howmany, substr);
return arr.join('');
},
startsWith: function(str, starts){
str = ''+str; starts = ''+starts;
return str.length >= starts.length && str.substring(0, starts.length) === starts;
},
endsWith: function(str, ends){
str = ''+str; ends = ''+ends;
return str.length >= ends.length && str.substring(str.length - ends.length) === ends;
},
succ: function(str){
str = ''+str;
var arr = str.split('');
arr.splice(str.length-1, 1, String.fromCharCode(str.charCodeAt(str.length-1) + 1));
return arr.join('');
},
titleize: function(str){
return (''+str).replace(/\b./g, function(ch){ return ch.toUpperCase(); });
},
camelize: function(str){
return _s.trim(str).replace(/(\-|_|\s)+(.)?/g, function(match, separator, chr) {
return chr ? chr.toUpperCase() : '';
});
},
underscored: function(str){
return _s.trim(str).replace(/([a-z\d])([A-Z]+)/g, '$1_$2').replace(/[-\s]+/g, '_').toLowerCase();
},
dasherize: function(str){
return _s.trim(str).replace(/[_\s]+/g, '-').replace(/([A-Z])/g, '-$1').replace(/-+/g, '-').toLowerCase();
},
humanize: function(str){
return _s.capitalize(this.underscored(str).replace(/_id$/,'').replace(/_/g, ' '));
},
trim: function(str, characters){
str = ''+str;
if (!characters && nativeTrim) {
return nativeTrim.call(str);
}
characters = defaultToWhiteSpace(characters);
return str.replace(new RegExp('\^' + characters + '+|' + characters + '+$', 'g'), '');
},
ltrim: function(str, characters){
if (!characters && nativeTrimLeft) {
return nativeTrimLeft.call(str);
}
characters = defaultToWhiteSpace(characters);
return (''+str).replace(new RegExp('\^' + characters + '+', 'g'), '');
},
rtrim: function(str, characters){
if (!characters && nativeTrimRight) {
return nativeTrimRight.call(str);
}
characters = defaultToWhiteSpace(characters);
return (''+str).replace(new RegExp(characters + '+$', 'g'), '');
},
truncate: function(str, length, truncateStr){
str = ''+str; truncateStr = truncateStr || '...';
length = ~~length;
return str.length > length ? str.slice(0, length) + truncateStr : str;
},
/**
* _s.prune: a more elegant version of truncate
* prune extra chars, never leaving a half-chopped word.
* @author github.com/sergiokas
*/
prune: function(str, length, pruneStr){
str = ''+str; length = ~~length;
pruneStr = pruneStr != null ? ''+pruneStr : '...';
var pruned, borderChar, template = str.replace(/\W/g, function(ch){
return (ch.toUpperCase() !== ch.toLowerCase()) ? 'A' : ' ';
});
borderChar = template[length];
pruned = template.slice(0, length);
// Check if we're in the middle of a word
if (borderChar && borderChar.match(/\S/))
pruned = pruned.replace(/\s\S+$/, '');
pruned = _s.rtrim(pruned);
return (pruned+pruneStr).length > str.length ? str : str.substring(0, pruned.length)+pruneStr;
},
words: function(str, delimiter) {
return (''+str).split(delimiter || " ");
},
pad: function(str, length, padStr, type) {
str = ''+str;
var padding = '', padlen = 0;
length = ~~length;
if (!padStr) {
padStr = ' ';
} else if (padStr.length > 1) {
padStr = padStr.charAt(0);
}
switch(type) {
case 'right':
padlen = (length - str.length);
padding = strRepeat(padStr, padlen);
str = str+padding;
break;
case 'both':
padlen = (length - str.length);
padding = {
'left' : strRepeat(padStr, Math.ceil(padlen/2)),
'right': strRepeat(padStr, Math.floor(padlen/2))
};
str = padding.left+str+padding.right;
break;
default: // 'left'
padlen = (length - str.length);
padding = strRepeat(padStr, padlen);;
str = padding+str;
}
return str;
},
lpad: function(str, length, padStr) {
return _s.pad(str, length, padStr);
},
rpad: function(str, length, padStr) {
return _s.pad(str, length, padStr, 'right');
},
lrpad: function(str, length, padStr) {
return _s.pad(str, length, padStr, 'both');
},
sprintf: sprintf,
vsprintf: function(fmt, argv){
argv.unshift(fmt);
return sprintf.apply(null, argv);
},
toNumber: function(str, decimals) {
var num = parseNumber(parseNumber(str).toFixed(~~decimals));
return num === 0 && ''+str !== '0' ? Number.NaN : num;
},
strRight: function(str, sep){
str = ''+str; sep = sep != null ? ''+sep : sep;
var pos = (!sep) ? -1 : str.indexOf(sep);
return (pos != -1) ? str.slice(pos+sep.length, str.length) : str;
},
strRightBack: function(str, sep){
str = ''+str; sep = sep != null ? ''+sep : sep;
var pos = (!sep) ? -1 : str.lastIndexOf(sep);
return (pos != -1) ? str.slice(pos+sep.length, str.length) : str;
},
strLeft: function(str, sep){
str = ''+str; sep = sep != null ? ''+sep : sep;
var pos = (!sep) ? -1 : str.indexOf(sep);
return (pos != -1) ? str.slice(0, pos) : str;
},
strLeftBack: function(str, sep){
str = ''+str; sep = sep != null ? ''+sep : sep;
var pos = str.lastIndexOf(sep);
return (pos != -1) ? str.slice(0, pos) : str;
},
toSentence: function(array, separator, lastSeparator) {
separator || (separator = ', ');
lastSeparator || (lastSeparator = ' and ');
var length = array.length, str = '';
for (var i = 0; i < length; i++) {
str += array[i];
if (i === (length - 2)) { str += lastSeparator; }
else if (i < (length - 1)) { str += separator; }
}
return str;
},
slugify: function(str) {
var from = "à áäâèéëêìíïîòóöôùúüûñç·/_:;",
to = "aaaaeeeeiiiioooouuuunc",
regex = new RegExp(defaultToWhiteSpace(from), 'g');
str = (''+str).toLowerCase();
str = str.replace(regex, function(ch){ return to[from.indexOf(ch)] || '-'; });
return _s.trim(str.replace(/[^\w\s-]/g, '').replace(/[-\s]+/g, '-'), '-');
},
exports: function() {
var result = {};
for (var prop in this) {
if (!this.hasOwnProperty(prop) || prop == 'include' || prop == 'contains' || prop == 'reverse') continue;
result[prop] = this[prop];
}
return result;
},
repeat: function(str, qty, separator){
str = ''+str; qty = ~~qty;
if (separator == null) separator = '';
var repeat = [];
for(var i = 0; i < qty; i++) repeat.push(str);
return repeat.join(separator);
}
};
// Aliases
_s.strip = _s.trim;
_s.lstrip = _s.ltrim;
_s.rstrip = _s.rtrim;
_s.center = _s.lrpad;
_s.rjust = _s.lpad;
_s.ljust = _s.rpad;
_s.contains = _s.include;
// CommonJS module is defined
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
// Export module
module.exports = _s;
}
exports._s = _s;
} else if (typeof define === 'function' && define.amd) {
// Register as a named module with AMD.
define('underscore.string', function() {
return _s;
});
// Integrate with Underscore.js
} else if (typeof root._ !== 'undefined') {
// root._.mixin(_s);
root._.string = _s;
root._.str = root._.string;
// Or define it
} else {
root._ = {
string: _s,
str: _s
};
}
}(this || window));
// Backbone.js 0.9.2
// (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc.
// Backbone may be freely distributed under the MIT license.
// For all details and documentation:
// http://backbonejs.org
(function(){
// Initial Setup
// -------------
// Save a reference to the global object (`window` in the browser, `global`
// on the server).
var root = this;
// Save the previous value of the `Backbone` variable, so that it can be
// restored later on, if `noConflict` is used.
var previousBackbone = root.Backbone;
// Create a local reference to slice/splice.
var slice = Array.prototype.slice;
var splice = Array.prototype.splice;
// The top-level namespace. All public Backbone classes and modules will
// be attached to this. Exported for both CommonJS and the browser.
var Backbone;
if (typeof exports !== 'undefined') {
Backbone = exports;
} else {
Backbone = root.Backbone = {};
}
// Current version of the library. Keep in sync with `package.json`.
Backbone.VERSION = '0.9.2';
// Require Underscore, if we're on the server, and it's not already present.
var _ = root._;
if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
// For Backbone's purposes, jQuery, Zepto, or Ender owns the `$` variable.
var $ = root.jQuery || root.Zepto || root.ender;
// Set the JavaScript library that will be used for DOM manipulation and
// Ajax calls (a.k.a. the `$` variable). By default Backbone will use: jQuery,
// Zepto, or Ender; but the `setDomLibrary()` method lets you inject an
// alternate JavaScript library (or a mock library for testing your views
// outside of a browser).
Backbone.setDomLibrary = function(lib) {
$ = lib;
};
// Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
// to its previous owner. Returns a reference to this Backbone object.
Backbone.noConflict = function() {
root.Backbone = previousBackbone;
return this;
};
// Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
// will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
// set a `X-Http-Method-Override` header.
Backbone.emulateHTTP = false;
// Turn on `emulateJSON` to support legacy servers that can't deal with direct
// `application/json` requests ... will encode the body as
// `application/x-www-form-urlencoded` instead and will send the model in a
// form param named `model`.
Backbone.emulateJSON = false;
// Backbone.Events
// -----------------
// Regular expression used to split event strings
var eventSplitter = /\s+/;
// A module that can be mixed in to *any object* in order to provide it with
// custom events. You may bind with `on` or remove with `off` callback functions
// to an event; trigger`-ing an event fires all callbacks in succession.
//
// var object = {};
// _.extend(object, Backbone.Events);
// object.on('expand', function(){ alert('expanded'); });
// object.trigger('expand');
//
var Events = Backbone.Events = {
// Bind one or more space separated events, `events`, to a `callback`
// function. Passing `"all"` will bind the callback to all events fired.
on: function(events, callback, context) {
var calls, event, node, tail, list;
if (!callback) return this;
events = events.split(eventSplitter);
calls = this._callbacks || (this._callbacks = {});
// Create an immutable callback list, allowing traversal during
// modification. The tail is an empty object that will always be used
// as the next node.
while (event = events.shift()) {
list = calls[event];
node = list ? list.tail : {};
node.next = tail = {};
node.context = context;
node.callback = callback;
calls[event] = {tail: tail, next: list ? list.next : node};
}
return this;
},
// Remove one or many callbacks. If `context` is null, removes all callbacks
// with that function. If `callback` is null, removes all callbacks for the
// event. If `events` is null, removes all bound callbacks for all events.
off: function(events, callback, context) {
var event, calls, node, tail, cb, ctx;
// No events, or removing *all* events.
if (!(calls = this._callbacks)) return;
if (!(events || callback || context)) {
delete this._callbacks;
return this;
}
// Loop through the listed events and contexts, splicing them out of the
// linked list of callbacks if appropriate.
events = events ? events.split(eventSplitter) : _.keys(calls);
while (event = events.shift()) {
node = calls[event];
delete calls[event];
if (!node || !(callback || context)) continue;
// Create a new list, omitting the indicated callbacks.
tail = node.tail;
while ((node = node.next) !== tail) {
cb = node.callback;
ctx = node.context;
if ((callback && cb !== callback) || (context && ctx !== context)) {
this.on(event, cb, ctx);
}
}
}
return this;
},
// Trigger one or many events, firing all bound callbacks. Callbacks are
// passed the same arguments as `trigger` is, apart from the event name
// (unless you're listening on `"all"`, which will cause your callback to
// receive the true name of the event as the first argument).
trigger: function(events) {
var event, node, calls, tail, args, all, rest;
if (!(calls = this._callbacks)) return this;
all = calls.all;
events = events.split(eventSplitter);
rest = slice.call(arguments, 1);
// For each event, walk through the linked list of callbacks twice,
// first to trigger the event, then to trigger any `"all"` callbacks.
while (event = events.shift()) {
if (node = calls[event]) {
tail = node.tail;
while ((node = node.next) !== tail) {
node.callback.apply(node.context || this, rest);
}
}
if (node = all) {
tail = node.tail;
args = [event].concat(rest);
while ((node = node.next) !== tail) {
node.callback.apply(node.context || this, args);
}
}
}
return this;
}
};
// Aliases for backwards compatibility.
Events.bind = Events.on;
Events.unbind = Events.off;
// Backbone.Model
// --------------
// Create a new model, with defined attributes. A client id (`cid`)
// is automatically generated and assigned for you.
var Model = Backbone.Model = function(attributes, options) {
var defaults;
attributes || (attributes = {});
if (options && options.parse) attributes = this.parse(attributes);
if (defaults = getValue(this, 'defaults')) {
attributes = _.extend({}, defaults, attributes);
}
if (options && options.collection) this.collection = options.collection;
this.attributes = {};
this._escapedAttributes = {};
this.cid = _.uniqueId('c');
this.changed = {};
this._silent = {};
this._pending = {};
this.set(attributes, {silent: true});
// Reset change tracking.
this.changed = {};
this._silent = {};
this._pending = {};
this._previousAttributes = _.clone(this.attributes);
this.initialize.apply(this, arguments);
};
// Attach all inheritable methods to the Model prototype.
_.extend(Model.prototype, Events, {
// A hash of attributes whose current and previous value differ.
changed: null,
// A hash of attributes that have silently changed since the last time
// `change` was called. Will become pending attributes on the next call.
_silent: null,
// A hash of attributes that have changed since the last `'change'` event
// began.
_pending: null,
// The default name for the JSON `id` attribute is `"id"`. MongoDB and
// CouchDB users may want to set this to `"_id"`.
idAttribute: 'id',
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// Return a copy of the model's `attributes` object.
toJSON: function(options) {
return _.clone(this.attributes);
},
// Get the value of an attribute.
get: function(attr) {
return this.attributes[attr];
},
// Get the HTML-escaped value of an attribute.
escape: function(attr) {
var html;
if (html = this._escapedAttributes[attr]) return html;
var val = this.get(attr);
return this._escapedAttributes[attr] = _.escape(val == null ? '' : '' + val);
},
// Returns `true` if the attribute contains a value that is not null
// or undefined.
has: function(attr) {
return this.get(attr) != null;
},
// Set a hash of model attributes on the object, firing `"change"` unless
// you choose to silence it.
set: function(key, value, options) {
var attrs, attr, val;
// Handle both
if (_.isObject(key) || key == null) {
attrs = key;
options = value;
} else {
attrs = {};
attrs[key] = value;
}
// Extract attributes and options.
options || (options = {});
if (!attrs) return this;
if (attrs instanceof Model) attrs = attrs.attributes;
if (options.unset) for (attr in attrs) attrs[attr] = void 0;
// Run validation.
if (!this._validate(attrs, options)) return false;
// Check for changes of `id`.
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
var changes = options.changes = {};
var now = this.attributes;
var escaped = this._escapedAttributes;
var prev = this._previousAttributes || {};
// For each `set` attribute...
for (attr in attrs) {
val = attrs[attr];
// If the new and current value differ, record the change.
if (!_.isEqual(now[attr], val) || (options.unset && _.has(now, attr))) {
delete escaped[attr];
(options.silent ? this._silent : changes)[attr] = true;
}
// Update or delete the current value.
options.unset ? delete now[attr] : now[attr] = val;
// If the new and previous value differ, record the change. If not,
// then remove changes for this attribute.
if (!_.isEqual(prev[attr], val) || (_.has(now, attr) != _.has(prev, attr))) {
this.changed[attr] = val;
if (!options.silent) this._pending[attr] = true;
} else {
delete this.changed[attr];
delete this._pending[attr];
}
}
// Fire the `"change"` events.
if (!options.silent) this.change(options);
return this;
},
// Remove an attribute from the model, firing `"change"` unless you choose
// to silence it. `unset` is a noop if the attribute doesn't exist.
unset: function(attr, options) {
(options || (options = {})).unset = true;
return this.set(attr, null, options);
},
// Clear all attributes on the model, firing `"change"` unless you choose
// to silence it.
clear: function(options) {
(options || (options = {})).unset = true;
return this.set(_.clone(this.attributes), options);
},
// Fetch the model from the server. If the server's representation of the
// model differs from its current attributes, they will be overriden,
// triggering a `"change"` event.
fetch: function(options) {
options = options ? _.clone(options) : {};
var model = this;
var success = options.success;
options.success = function(resp, status, xhr) {
if (!model.set(model.parse(resp, xhr), options)) return false;
if (success) success(model, resp);
};
options.error = Backbone.wrapError(options.error, model, options);
return (this.sync || Backbone.sync).call(this, 'read', this, options);
},
// Set a hash of model attributes, and sync the model to the server.
// If the server returns an attributes hash that differs, the model's
// state will be `set` again.
save: function(key, value, options) {
var attrs, current;
// Handle both `("key", value)` and `({key: value})` -style calls.
if (_.isObject(key) || key == null) {
attrs = key;
options = value;
} else {
attrs = {};
attrs[key] = value;
}
options = options ? _.clone(options) : {};
// If we're "wait"-ing to set changed attributes, validate early.
if (options.wait) {
if (!this._validate(attrs, options)) return false;
current = _.clone(this.attributes);
}
// Regular saves `set` attributes before persisting to the server.
var silentOptions = _.extend({}, options, {silent: true});
if (attrs && !this.set(attrs, options.wait ? silentOptions : options)) {
return false;
}
// After a successful server-side save, the client is (optionally)
// updated with the server-side state.
var model = this;
var success = options.success;
options.success = function(resp, status, xhr) {
var serverAttrs = model.parse(resp, xhr);
if (options.wait) {
delete options.wait;
serverAttrs = _.extend(attrs || {}, serverAttrs);
}
if (!model.set(serverAttrs, options)) return false;
if (success) {
success(model, resp);
} else {
model.trigger('sync', model, resp, options);
}
};
// Finish configuring and sending the Ajax request.
options.error = Backbone.wrapError(options.error, model, options);
var method = this.isNew() ? 'create' : 'update';
var xhr = (this.sync || Backbone.sync).call(this, method, this, options);
if (options.wait) this.set(current, silentOptions);
return xhr;
},
// Destroy this model on the server if it was already persisted.
// Optimistically removes the model from its collection, if it has one.
// If `wait: true` is passed, waits for the server to respond before removal.
destroy: function(options) {
options = options ? _.clone(options) : {};
var model = this;
var success = options.success;
var triggerDestroy = function() {
model.trigger('destroy', model, model.collection, options);
};
if (this.isNew()) {
triggerDestroy();
return false;
}
options.success = function(resp) {
if (options.wait) triggerDestroy();
if (success) {
success(model, resp);
} else {
model.trigger('sync', model, resp, options);
}
};
options.error = Backbone.wrapError(options.error, model, options);
var xhr = (this.sync || Backbone.sync).call(this, 'delete', this, options);
if (!options.wait) triggerDestroy();
return xhr;
},
// Default URL for the model's representation on the server -- if you're
// using Backbone's restful methods, override this to change the endpoint
// that will be called.
url: function() {
var base = getValue(this, 'urlRoot') || getValue(this.collection, 'url') || urlError();
if (this.isNew()) return base;
return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id);
},
// **parse** converts a response into the hash of attributes to be `set` on
// the model. The default implementation is just to pass the response along.
parse: function(resp, xhr) {
return resp;
},
// Create a new model with identical attributes to this one.
clone: function() {
return new this.constructor(this.attributes);
},
// A model is new if it has never been saved to the server, and lacks an id.
isNew: function() {
return this.id == null;
},
// Call this method to manually fire a `"change"` event for this model and
// a `"change:attribute"` event for each changed attribute.
// Calling this will cause all objects observing the model to update.
change: function(options) {
options || (options = {});
var changing = this._changing;
this._changing = true;
// Silent changes become pending changes.
for (var attr in this._silent) this._pending[attr] = true;
// Silent changes are triggered.
var changes = _.extend({}, options.changes, this._silent);
this._silent = {};
for (var attr in changes) {
this.trigger('change:' + attr, this, this.get(attr), options);
}
if (changing) return this;
// Continue firing `"change"` events while there are pending changes.
while (!_.isEmpty(this._pending)) {
this._pending = {};
this.trigger('change', this, options);
// Pending and silent changes still remain.
for (var attr in this.changed) {
if (this._pending[attr] || this._silent[attr]) continue;
delete this.changed[attr];
}
this._previousAttributes = _.clone(this.attributes);
}
this._changing = false;
return this;
},
// Determine if the model has changed since the last `"change"` event.
// If you specify an attribute name, determine if that attribute has changed.
hasChanged: function(attr) {
if (!arguments.length) return !_.isEmpty(this.changed);
return _.has(this.changed, attr);
},
// Return an object containing all the attributes that have changed, or
// false if there are no changed attributes. Useful for determining what
// parts of a view need to be updated and/or what attributes need to be
// persisted to the server. Unset attributes will be set to undefined.
// You can also pass an attributes object to diff against the model,
// determining if there *would be* a change.
changedAttributes: function(diff) {
if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
var val, changed = false, old = this._previousAttributes;
for (var attr in diff) {
if (_.isEqual(old[attr], (val = diff[attr]))) continue;
(changed || (changed = {}))[attr] = val;
}
return changed;
},
// Get the previous value of an attribute, recorded at the time the last
// `"change"` event was fired.
previous: function(attr) {
if (!arguments.length || !this._previousAttributes) return null;
return this._previousAttributes[attr];
},
// Get all of the attributes of the model at the time of the previous
// `"change"` event.
previousAttributes: function() {
return _.clone(this._previousAttributes);
},
// Check if the model is currently in a valid state. It's only possible to
// get into an *invalid* state if you're using silent changes.
isValid: function() {
return !this.validate(this.attributes);
},
// Run validation against the next complete set of model attributes,
// returning `true` if all is well. If a specific `error` callback has
// been passed, call that instead of firing the general `"error"` event.
_validate: function(attrs, options) {
if (options.silent || !this.validate) return true;
attrs = _.extend({}, this.attributes, attrs);
var error = this.validate(attrs, options);
if (!error) return true;
if (options && options.error) {
options.error(this, error, options);
} else {
this.trigger('error', this, error, options);
}
return false;
}
});
// Backbone.Collection
// -------------------
// Provides a standard collection class for our sets of models, ordered
// or unordered. If a `comparator` is specified, the Collection will maintain
// its models in sort order, as they're added and removed.
var Collection = Backbone.Collection = function(models, options) {
options || (options = {});
if (options.model) this.model = options.model;
if (options.comparator) this.comparator = options.comparator;
this._reset();
this.initialize.apply(this, arguments);
if (models) this.reset(models, {silent: true, parse: options.parse});
};
// Define the Collection's inheritable methods.
_.extend(Collection.prototype, Events, {
// The default model for a collection is just a **Backbone.Model**.
// This should be overridden in most cases.
model: Model,
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// The JSON representation of a Collection is an array of the
// models' attributes.
toJSON: function(options) {
return this.map(function(model){ return model.toJSON(options); });
},
// Add a model, or list of models to the set. Pass **silent** to avoid
// firing the `add` event for every new model.
add: function(models, options) {
var i, index, length, model, cid, id, cids = {}, ids = {}, dups = [];
options || (options = {});
models = _.isArray(models) ? models.slice() : [models];
// Begin by turning bare objects into model references, and preventing
// invalid models or duplicate models from being added.
for (i = 0, length = models.length; i < length; i++) {
if (!(model = models[i] = this._prepareModel(models[i], options))) {
throw new Error("Can't add an invalid model to a collection");
}
cid = model.cid;
id = model.id;
if (cids[cid] || this._byCid[cid] || ((id != null) && (ids[id] || this._byId[id]))) {
dups.push(i);
continue;
}
cids[cid] = ids[id] = model;
}
// Remove duplicates.
i = dups.length;
while (i--) {
models.splice(dups[i], 1);
}
// Listen to added models' events, and index models for lookup by
// `id` and by `cid`.
for (i = 0, length = models.length; i < length; i++) {
(model = models[i]).on('all', this._onModelEvent, this);
this._byCid[model.cid] = model;
if (model.id != null) this._byId[model.id] = model;
}
// Insert models into the collection, re-sorting if needed, and triggering
// `add` events unless silenced.
this.length += length;
index = options.at != null ? options.at : this.models.length;
splice.apply(this.models, [index, 0].concat(models));
if (this.comparator) this.sort({silent: true});
if (options.silent) return this;
for (i = 0, length = this.models.length; i < length; i++) {
if (!cids[(model = this.models[i]).cid]) continue;
options.index = i;
model.trigger('add', model, this, options);
}
return this;
},
// Remove a model, or a list of models from the set. Pass silent to avoid
// firing the `remove` event for every model removed.
remove: function(models, options) {
var i, l, index, model;
options || (options = {});
models = _.isArray(models) ? models.slice() : [models];
for (i = 0, l = models.length; i < l; i++) {
model = this.getByCid(models[i]) || this.get(models[i]);
if (!model) continue;
delete this._byId[model.id];
delete this._byCid[model.cid];
index = this.indexOf(model);
this.models.splice(index, 1);
this.length--;
if (!options.silent) {
options.index = index;
model.trigger('remove', model, this, options);
}
this._removeReference(model);
}
return this;
},
// Add a model to the end of the collection.
push: function(model, options) {
model = this._prepareModel(model, options);
this.add(model, options);
return model;
},
// Remove a model from the end of the collection.
pop: function(options) {
var model = this.at(this.length - 1);
this.remove(model, options);
return model;
},
// Add a model to the beginning of the collection.
unshift: function(model, options) {
model = this._prepareModel(model, options);
this.add(model, _.extend({at: 0}, options));
return model;
},
// Remove a model from the beginning of the collection.
shift: function(options) {
var model = this.at(0);
this.remove(model, options);
return model;
},
// Get a model from the set by id.
get: function(id) {
if (id == null) return void 0;
return this._byId[id.id != null ? id.id : id];
},
// Get a model from the set by client id.
getByCid: function(cid) {
return cid && this._byCid[cid.cid || cid];
},
// Get the model at the given index.
at: function(index) {
return this.models[index];
},
// Return models with matching attributes. Useful for simple cases of `filter`.
where: function(attrs) {
if (_.isEmpty(attrs)) return [];
return this.filter(function(model) {
for (var key in attrs) {
if (attrs[key] !== model.get(key)) return false;
}
return true;
});
},
// Force the collection to re-sort itself. You don't need to call this under
// normal circumstances, as the set will maintain sort order as each item
// is added.
sort: function(options) {
options || (options = {});
if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
var boundComparator = _.bind(this.comparator, this);
if (this.comparator.length == 1) {
this.models = this.sortBy(boundComparator);
} else {
this.models.sort(boundComparator);
}
if (!options.silent) this.trigger('reset', this, options);
return this;
},
// Pluck an attribute from each model in the collection.
pluck: function(attr) {
return _.map(this.models, function(model){ return model.get(attr); });
},
// When you have more items than you want to add or remove individually,
// you can reset the entire set with a new list of models, without firing
// any `add` or `remove` events. Fires `reset` when finished.
reset: function(models, options) {
models || (models = []);
options || (options = {});
for (var i = 0, l = this.models.length; i < l; i++) {
this._removeReference(this.models[i]);
}
this._reset();
this.add(models, _.extend({silent: true}, options));
if (!options.silent) this.trigger('reset', this, options);
return this;
},
// Fetch the default set of models for this collection, resetting the
// collection when they arrive. If `add: true` is passed, appends the
// models to the collection instead of resetting.
fetch: function(options) {
options = options ? _.clone(options) : {};
if (options.parse === undefined) options.parse = true;
var collection = this;
var success = options.success;
options.success = function(resp, status, xhr) {
collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
if (success) success(collection, resp);
};
options.error = Backbone.wrapError(options.error, collection, options);
return (this.sync || Backbone.sync).call(this, 'read', this, options);
},
// Create a new instance of a model in this collection. Add the model to the
// collection immediately, unless `wait: true` is passed, in which case we
// wait for the server to agree.
create: function(model, options) {
var coll = this;
options = options ? _.clone(options) : {};
model = this._prepareModel(model, options);
if (!model) return false;
if (!options.wait) coll.add(model, options);
var success = options.success;
options.success = function(nextModel, resp, xhr) {
if (options.wait) coll.add(nextModel, options);
if (success) {
success(nextModel, resp);
} else {
nextModel.trigger('sync', model, resp, options);
}
};
model.save(null, options);
return model;
},
// **parse** converts a response into a list of models to be added to the
// collection. The default implementation is just to pass it through.
parse: function(resp, xhr) {
return resp;
},
// Proxy to _'s chain. Can't be proxied the same way the rest of the
// underscore methods are proxied because it relies on the underscore
// constructor.
chain: function () {
return _(this.models).chain();
},
// Reset all internal state. Called when the collection is reset.
_reset: function(options) {
this.length = 0;
this.models = [];
this._byId = {};
this._byCid = {};
},
// Prepare a model or hash of attributes to be added to this collection.
_prepareModel: function(model, options) {
options || (options = {});
if (!(model instanceof Model)) {
var attrs = model;
options.collection = this;
model = new this.model(attrs, options);
if (!model._validate(model.attributes, options)) model = false;
} else if (!model.collection) {
model.collection = this;
}
return model;
},
// Internal method to remove a model's ties to a collection.
_removeReference: function(model) {
if (this == model.collection) {
delete model.collection;
}
model.off('all', this._onModelEvent, this);
},
// Internal method called every time a model in the set fires an event.
// Sets need to update their indexes when models change ids. All other
// events simply proxy through. "add" and "remove" events that originate
// in other collections are ignored.
_onModelEvent: function(event, model, collection, options) {
if ((event == 'add' || event == 'remove') && collection != this) return;
if (event == 'destroy') {
this.remove(model, options);
}
if (model && event === 'change:' + model.idAttribute) {
delete this._byId[model.previous(model.idAttribute)];
this._byId[model.id] = model;
}
this.trigger.apply(this, arguments);
}
});
// Underscore methods that we want to implement on the Collection.
var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find',
'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any',
'include', 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex',
'toArray', 'size', 'first', 'initial', 'rest', 'last', 'without', 'indexOf',
'shuffle', 'lastIndexOf', 'isEmpty', 'groupBy'];
// Mix in each Underscore method as a proxy to `Collection#models`.
_.each(methods, function(method) {
Collection.prototype[method] = function() {
return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
};
});
// Backbone.Router
// -------------------
// Routers map faux-URLs to actions, and fire events when routes are
// matched. Creating a new one sets its `routes` hash, if not set statically.
var Router = Backbone.Router = function(options) {
options || (options = {});
if (options.routes) this.routes = options.routes;
this._bindRoutes();
this.initialize.apply(this, arguments);
};
// Cached regular expressions for matching named param parts and splatted
// parts of route strings.
var namedParam = /:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g;
// Set up all inheritable **Backbone.Router** properties and methods.
_.extend(Router.prototype, Events, {
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// Manually bind a single named route to a callback. For example:
//
// this.route('search/:query/p:num', 'search', function(query, num) {
// ...
// });
//
route: function(route, name, callback) {
Backbone.history || (Backbone.history = new History);
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (!callback) callback = this[name];
Backbone.history.route(route, _.bind(function(fragment) {
var args = this._extractParameters(route, fragment);
callback && callback.apply(this, args);
this.trigger.apply(this, ['route:' + name].concat(args));
Backbone.history.trigger('route', this, name, args);
}, this));
return this;
},
// Simple proxy to `Backbone.history` to save a fragment into the history.
navigate: function(fragment, options) {
Backbone.history.navigate(fragment, options);
},
// Bind all defined routes to `Backbone.history`. We have to reverse the
// order of the routes here to support behavior where the most general
// routes can be defined at the bottom of the route map.
_bindRoutes: function() {
if (!this.routes) return;
var routes = [];
for (var route in this.routes) {
routes.unshift([route, this.routes[route]]);
}
for (var i = 0, l = routes.length; i < l; i++) {
this.route(routes[i][0], routes[i][1], this[routes[i][1]]);
}
},
// Convert a route string into a regular expression, suitable for matching
// against the current location hash.
_routeToRegExp: function(route) {
route = route.replace(escapeRegExp, '\\$&')
.replace(namedParam, '([^\/]+)')
.replace(splatParam, '(.*?)');
return new RegExp('^' + route + '$');
},
// Given a route, and a URL fragment that it matches, return the array of
// extracted parameters.
_extractParameters: function(route, fragment) {
return route.exec(fragment).slice(1);
}
});
// Backbone.History
// ----------------
// Handles cross-browser history management, based on URL fragments. If the
// browser does not support `onhashchange`, falls back to polling.
var History = Backbone.History = function() {
this.handlers = [];
_.bindAll(this, 'checkUrl');
};
// Cached regex for cleaning leading hashes and slashes .
var routeStripper = /^[#\/]/;
// Cached regex for detecting MSIE.
var isExplorer = /msie [\w.]+/;
// Has the history handling already been started?
History.started = false;
// Set up all inheritable **Backbone.History** properties and methods.
_.extend(History.prototype, Events, {
// The default interval to poll for hash changes, if necessary, is
// twenty times a second.
interval: 50,
// Gets the true hash value. Cannot use location.hash directly due to bug
// in Firefox where location.hash will always be decoded.
getHash: function(windowOverride) {
var loc = windowOverride ? windowOverride.location : window.location;
var match = loc.href.match(/#(.*)$/);
return match ? match[1] : '';
},
// Get the cross-browser normalized URL fragment, either from the URL,
// the hash, or the override.
getFragment: function(fragment, forcePushState) {
if (fragment == null) {
if (this._hasPushState || forcePushState) {
fragment = window.location.pathname;
var search = window.location.search;
if (search) fragment += search;
} else {
fragment = this.getHash();
}
}
if (!fragment.indexOf(this.options.root)) fragment = fragment.substr(this.options.root.length);
return fragment.replace(routeStripper, '');
},
// Start the hash change handling, returning `true` if the current URL matches
// an existing route, and `false` otherwise.
start: function(options) {
if (History.started) throw new Error("Backbone.history has already been started");
History.started = true;
// Figure out the initial configuration. Do we need an iframe?
// Is pushState desired ... is it available?
this.options = _.extend({}, {root: '/'}, this.options, options);
this._wantsHashChange = this.options.hashChange !== false;
this._wantsPushState = !!this.options.pushState;
this._hasPushState = !!(this.options.pushState && window.history && window.history.pushState);
var fragment = this.getFragment();
var docMode = document.documentMode;
var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
if (oldIE) {
this.iframe = $('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
this.navigate(fragment);
}
// Depending on whether we're using pushState or hashes, and whether
// 'onhashchange' is supported, determine how we check the URL state.
if (this._hasPushState) {
$(window).bind('popstate', this.checkUrl);
} else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
$(window).bind('hashchange', this.checkUrl);
} else if (this._wantsHashChange) {
this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
}
// Determine if we need to change the base url, for a pushState link
// opened by a non-pushState browser.
this.fragment = fragment;
var loc = window.location;
var atRoot = loc.pathname == this.options.root;
// If we've started off with a route from a `pushState`-enabled browser,
// but we're currently in a browser that doesn't support it...
if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
this.fragment = this.getFragment(null, true);
window.location.replace(this.options.root + '#' + this.fragment);
// Return immediately as browser will do redirect to new url
return true;
// Or if we've started out with a hash-based route, but we're currently
// in a browser where it could be `pushState`-based instead...
} else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
this.fragment = this.getHash().replace(routeStripper, '');
window.history.replaceState({}, document.title, loc.protocol + '//' + loc.host + this.options.root + this.fragment);
}
if (!this.options.silent) {
return this.loadUrl();
}
},
// Disable Backbone.history, perhaps temporarily. Not useful in a real app,
// but possibly useful for unit testing Routers.
stop: function() {
$(window).unbind('popstate', this.checkUrl).unbind('hashchange', this.checkUrl);
clearInterval(this._checkUrlInterval);
History.started = false;
},
// Add a route to be tested when the fragment changes. Routes added later
// may override previous routes.
route: function(route, callback) {
this.handlers.unshift({route: route, callback: callback});
},
// Checks the current URL to see if it has changed, and if it has,
// calls `loadUrl`, normalizing across the hidden iframe.
checkUrl: function(e) {
var current = this.getFragment();
if (current == this.fragment && this.iframe) current = this.getFragment(this.getHash(this.iframe));
if (current == this.fragment) return false;
if (this.iframe) this.navigate(current);
this.loadUrl() || this.loadUrl(this.getHash());
},
// Attempt to load the current URL fragment. If a route succeeds with a
// match, returns `true`. If no defined routes matches the fragment,
// returns `false`.
loadUrl: function(fragmentOverride) {
var fragment = this.fragment = this.getFragment(fragmentOverride);
var matched = _.any(this.handlers, function(handler) {
if (handler.route.test(fragment)) {
handler.callback(fragment);
return true;
}
});
return matched;
},
// Save a fragment into the hash history, or replace the URL state if the
// 'replace' option is passed. You are responsible for properly URL-encoding
// the fragment in advance.
//
// The options object can contain `trigger: true` if you wish to have the
// route callback be fired (not usually desirable), or `replace: true`, if
// you wish to modify the current URL without adding an entry to the history.
navigate: function(fragment, options) {
if (!History.started) return false;
if (!options || options === true) options = {trigger: options};
var frag = (fragment || '').replace(routeStripper, '');
if (this.fragment == frag) return;
// If pushState is available, we use it to set the fragment as a real URL.
if (this._hasPushState) {
if (frag.indexOf(this.options.root) != 0) frag = this.options.root + frag;
this.fragment = frag;
window.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, frag);
// If hash changes haven't been explicitly disabled, update the hash
// fragment to store history.
} else if (this._wantsHashChange) {
this.fragment = frag;
this._updateHash(window.location, frag, options.replace);
if (this.iframe && (frag != this.getFragment(this.getHash(this.iframe)))) {
// Opening and closing the iframe tricks IE7 and earlier to push a history entry on hash-tag change.
// When replace is true, we don't want this.
if(!options.replace) this.iframe.document.open().close();
this._updateHash(this.iframe.location, frag, options.replace);
}
// If you've told us that you explicitly don't want fallback hashchange-
// based history, then `navigate` becomes a page refresh.
} else {
window.location.assign(this.options.root + fragment);
}
if (options.trigger) this.loadUrl(fragment);
},
// Update the hash location, either replacing the current entry, or adding
// a new one to the browser history.
_updateHash: function(location, fragment, replace) {
if (replace) {
location.replace(location.toString().replace(/(javascript:|#).*$/, '') + '#' + fragment);
} else {
location.hash = fragment;
}
}
});
// Backbone.View
// -------------
// Creating a Backbone.View creates its initial element outside of the DOM,
// if an existing element is not provided...
var View = Backbone.View = function(options) {
this.cid = _.uniqueId('view');
this._configure(options || {});
this._ensureElement();
this.initialize.apply(this, arguments);
this.delegateEvents();
};
// Cached regex to split keys for `delegate`.
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
// List of view options to be merged as properties.
var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName'];
// Set up all inheritable **Backbone.View** properties and methods.
_.extend(View.prototype, Events, {
// The default `tagName` of a View's element is `"div"`.
tagName: 'div',
// jQuery delegate for element lookup, scoped to DOM elements within the
// current view. This should be prefered to global lookups where possible.
$: function(selector) {
return this.$el.find(selector);
},
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// **render** is the core function that your view should override, in order
// to populate its element (`this.el`), with the appropriate HTML. The
// convention is for **render** to always return `this`.
render: function() {
return this;
},
// Remove this view from the DOM. Note that the view isn't present in the
// DOM by default, so calling this method may be a no-op.
remove: function() {
this.$el.remove();
return this;
},
// For small amounts of DOM Elements, where a full-blown template isn't
// needed, use **make** to manufacture elements, one at a time.
//
// var el = this.make('li', {'class': 'row'}, this.model.escape('title'));
//
make: function(tagName, attributes, content) {
var el = document.createElement(tagName);
if (attributes) $(el).attr(attributes);
if (content) $(el).html(content);
return el;
},
// Change the view's element (`this.el` property), including event
// re-delegation.
setElement: function(element, delegate) {
if (this.$el) this.undelegateEvents();
this.$el = (element instanceof $) ? element : $(element);
this.el = this.$el[0];
if (delegate !== false) this.delegateEvents();
return this;
},
// Set callbacks, where `this.events` is a hash of
//
// *{"event selector": "callback"}*
//
// {
// 'mousedown .title': 'edit',
// 'click .button': 'save'
// 'click .open': function(e) { ... }
// }
//
// pairs. Callbacks will be bound to the view, with `this` set properly.
// Uses event delegation for efficiency.
// Omitting the selector binds the event to `this.el`.
// This only works for delegate-able events: not `focus`, `blur`, and
// not `change`, `submit`, and `reset` in Internet Explorer.
delegateEvents: function(events) {
if (!(events || (events = getValue(this, 'events')))) return;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method)) method = this[events[key]];
if (!method) throw new Error('Method "' + events[key] + '" does not exist');
var match = key.match(delegateEventSplitter);
var eventName = match[1], selector = match[2];
method = _.bind(method, this);
eventName += '.delegateEvents' + this.cid;
if (selector === '') {
this.$el.bind(eventName, method);
} else {
this.$el.delegate(selector, eventName, method);
}
}
},
// Clears all callbacks previously bound to the view with `delegateEvents`.
// You usually don't need to use this, but may wish to if you have multiple
// Backbone views attached to the same DOM element.
undelegateEvents: function() {
this.$el.unbind('.delegateEvents' + this.cid);
},
// Performs the initial configuration of a View with a set of options.
// Keys with special meaning *(model, collection, id, className)*, are
// attached directly to the view.
_configure: function(options) {
if (this.options) options = _.extend({}, this.options, options);
for (var i = 0, l = viewOptions.length; i < l; i++) {
var attr = viewOptions[i];
if (options[attr]) this[attr] = options[attr];
}
this.options = options;
},
// Ensure that the View has a DOM element to render into.
// If `this.el` is a string, pass it through `$()`, take the first
// matching element, and re-assign it to `el`. Otherwise, create
// an element from the `id`, `className` and `tagName` properties.
_ensureElement: function() {
if (!this.el) {
var attrs = getValue(this, 'attributes') || {};
if (this.id) attrs.id = this.id;
if (this.className) attrs['class'] = this.className;
this.setElement(this.make(this.tagName, attrs), false);
} else {
this.setElement(this.el, false);
}
}
});
// The self-propagating extend function that Backbone classes use.
var extend = function (protoProps, classProps) {
var child = inherits(this, protoProps, classProps);
child.extend = this.extend;
return child;
};
// Set up inheritance for the model, collection, and view.
Model.extend = Collection.extend = Router.extend = View.extend = extend;
// Backbone.sync
// -------------
// Map from CRUD to HTTP for our default `Backbone.sync` implementation.
var methodMap = {
'create': 'POST',
'update': 'PUT',
'delete': 'DELETE',
'read': 'GET'
};
// Override this function to change the manner in which Backbone persists
// models to the server. You will be passed the type of request, and the
// model in question. By default, makes a RESTful Ajax request
// to the model's `url()`. Some possible customizations could be:
//
// * Use `setTimeout` to batch rapid-fire updates into a single request.
// * Send up the models as XML instead of JSON.
// * Persist models via WebSockets instead of Ajax.
//
// Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
// as `POST`, with a `_method` parameter containing the true HTTP method,
// as well as all requests with the body as `application/x-www-form-urlencoded`
// instead of `application/json` with the model in a param named `model`.
// Useful when interfacing with server-side languages like **PHP** that make
// it difficult to read the body of `PUT` requests.
Backbone.sync = function(method, model, options) {
var type = methodMap[method];
// Default options, unless specified.
options || (options = {});
// Default JSON-request options.
var params = {type: type, dataType: 'json'};
// Ensure that we have a URL.
if (!options.url) {
params.url = getValue(model, 'url') || urlError();
}
// Ensure that we have the appropriate request data.
if (!options.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = JSON.stringify(model.toJSON());
}
// For older servers, emulate JSON by encoding the request into an HTML-form.
if (Backbone.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.data = params.data ? {model: params.data} : {};
}
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
// And an `X-HTTP-Method-Override` header.
if (Backbone.emulateHTTP) {
if (type === 'PUT' || type === 'DELETE') {
if (Backbone.emulateJSON) params.data._method = type;
params.type = 'POST';
params.beforeSend = function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', type);
};
}
}
// Don't process data on a non-GET request.
if (params.type !== 'GET' && !Backbone.emulateJSON) {
params.processData = false;
}
// Make the request, allowing the user to override any Ajax options.
return $.ajax(_.extend(params, options));
};
// Wrap an optional error callback with a fallback error event.
Backbone.wrapError = function(onError, originalModel, options) {
return function(model, resp) {
resp = model === originalModel ? resp : model;
if (onError) {
onError(originalModel, resp, options);
} else {
originalModel.trigger('error', originalModel, resp, options);
}
};
};
// Helpers
// -------
// Shared empty constructor function to aid in prototype-chain creation.
var ctor = function(){};
// Helper function to correctly set up the prototype chain, for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
var inherits = function(parent, protoProps, staticProps) {
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && protoProps.hasOwnProperty('constructor')) {
child = protoProps.constructor;
} else {
child = function(){ parent.apply(this, arguments); };
}
// Inherit class (static) properties from parent.
_.extend(child, parent);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
ctor.prototype = parent.prototype;
child.prototype = new ctor();
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) _.extend(child.prototype, protoProps);
// Add static properties to the constructor function, if supplied.
if (staticProps) _.extend(child, staticProps);
// Correctly set child's `prototype.constructor`.
child.prototype.constructor = child;
// Set a convenience property in case the parent's prototype is needed later.
child.__super__ = parent.prototype;
return child;
};
// Helper function to get a value from a Backbone object as a property
// or as a function.
var getValue = function(object, prop) {
if (!(object && object[prop])) return null;
return _.isFunction(object[prop]) ? object[prop]() : object[prop];
};
// Throw an error when a URL is needed, and none is supplied.
var urlError = function() {
throw new Error('A "url" property or function must be specified');
};
}).call(this);
// Instantiate the object
var I18n = I18n || {};
// Set default locale to english
I18n.defaultLocale = "en";
// Set default handling of translation fallbacks to false
I18n.fallbacks = false;
// Set default separator
I18n.defaultSeparator = ".";
// Set current locale to null
I18n.locale = null;
// Set the placeholder format. Accepts `{{placeholder}}` and `%{placeholder}`.
I18n.PLACEHOLDER = /(?:\{\{|%\{)(.*?)(?:\}\}?)/gm;
I18n.isValidNode = function(obj, node, undefined) {
return obj[node] !== null && obj[node] !== undefined;
}
I18n.lookup = function(scope, options) {
var options = options || {}
, lookupInitialScope = scope
, translations = this.prepareOptions(I18n.translations)
, messages = translations[options.locale || I18n.currentLocale()]
, options = this.prepareOptions(options)
, currentScope
;
if (!messages){
return;
}
if (typeof(scope) == "object") {
scope = scope.join(this.defaultSeparator);
}
if (options.scope) {
scope = options.scope.toString() + this.defaultSeparator + scope;
}
scope = scope.split(this.defaultSeparator);
while (scope.length > 0) {
currentScope = scope.shift();
messages = messages[currentScope];
if (!messages) {
if (I18n.fallbacks && !options.fallback) {
messages = I18n.lookup(lookupInitialScope, this.prepareOptions({ locale: I18n.defaultLocale, fallback: true }, options));
}
break;
}
}
if (!messages && this.isValidNode(options, "defaultValue")) {
messages = options.defaultValue;
}
return messages;
};
// Merge serveral hash options, checking if value is set before
// overwriting any value. The precedence is from left to right.
//
// I18n.prepareOptions({name: "John Doe"}, {name: "Mary Doe", role: "user"});
// #=> {name: "John Doe", role: "user"}
//
I18n.prepareOptions = function() {
var options = {}
, opts
, count = arguments.length
;
for (var i = 0; i < count; i++) {
opts = arguments[i];
if (!opts) {
continue;
}
for (var key in opts) {
if (!this.isValidNode(options, key)) {
options[key] = opts[key];
}
}
}
return options;
};
I18n.interpolate = function(message, options) {
options = this.prepareOptions(options);
var matches = message.match(this.PLACEHOLDER)
, placeholder
, value
, name
;
if (!matches) {
return message;
}
for (var i = 0; placeholder = matches[i]; i++) {
name = placeholder.replace(this.PLACEHOLDER, "$1");
value = options[name];
if (!this.isValidNode(options, name)) {
value = "[missing " + placeholder + " value]";
}
regex = new RegExp(placeholder.replace(/\{/gm, "\\{").replace(/\}/gm, "\\}"));
message = message.replace(regex, value);
}
return message;
};
I18n.translate = function(scope, options) {
options = this.prepareOptions(options);
var translation = this.lookup(scope, options);
try {
if (typeof(translation) == "object") {
if (typeof(options.count) == "number") {
return this.pluralize(options.count, scope, options);
} else {
return translation;
}
} else {
return this.interpolate(translation, options);
}
} catch(err) {
return this.missingTranslation(scope);
}
};
I18n.localize = function(scope, value) {
switch (scope) {
case "currency":
return this.toCurrency(value);
case "number":
scope = this.lookup("number.format");
return this.toNumber(value, scope);
case "percentage":
return this.toPercentage(value);
default:
if (scope.match(/^(date|time)/)) {
return this.toTime(scope, value);
} else {
return value.toString();
}
}
};
I18n.parseDate = function(date) {
var matches, convertedDate;
// we have a date, so just return it.
if (typeof(date) == "object") {
return date;
};
// it matches the following formats:
// yyyy-mm-dd
// yyyy-mm-dd[ T]hh:mm::ss
// yyyy-mm-dd[ T]hh:mm::ss
// yyyy-mm-dd[ T]hh:mm::ssZ
// yyyy-mm-dd[ T]hh:mm::ss+0000
//
matches = date.toString().match(/(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2}):(\d{2}))?(Z|\+0000)?/);
if (matches) {
for (var i = 1; i <= 6; i++) {
matches[i] = parseInt(matches[i], 10) || 0;
}
// month starts on 0
matches[2] -= 1;
if (matches[7]) {
convertedDate = new Date(Date.UTC(matches[1], matches[2], matches[3], matches[4], matches[5], matches[6]));
} else {
convertedDate = new Date(matches[1], matches[2], matches[3], matches[4], matches[5], matches[6]);
}
} else if (typeof(date) == "number") {
// UNIX timestamp
convertedDate = new Date();
convertedDate.setTime(date);
} else if (date.match(/\d+ \d+:\d+:\d+ [+-]\d+ \d+/)) {
// a valid javascript format with timezone info
convertedDate = new Date();
convertedDate.setTime(Date.parse(date))
} else {
// an arbitrary javascript string
convertedDate = new Date();
convertedDate.setTime(Date.parse(date));
}
return convertedDate;
};
I18n.toTime = function(scope, d) {
var date = this.parseDate(d)
, format = this.lookup(scope)
;
if (date.toString().match(/invalid/i)) {
return date.toString();
}
if (!format) {
return date.toString();
}
return this.strftime(date, format);
};
I18n.strftime = function(date, format) {
var options = this.lookup("date");
if (!options) {
return date.toString();
}
options.meridian = options.meridian || ["AM", "PM"];
var weekDay = date.getDay()
, day = date.getDate()
, year = date.getFullYear()
, month = date.getMonth() + 1
, hour = date.getHours()
, hour12 = hour
, meridian = hour > 11 ? 1 : 0
, secs = date.getSeconds()
, mins = date.getMinutes()
, offset = date.getTimezoneOffset()
, absOffsetHours = Math.floor(Math.abs(offset / 60))
, absOffsetMinutes = Math.abs(offset) - (absOffsetHours * 60)
, timezoneoffset = (offset > 0 ? "-" : "+") + (absOffsetHours.toString().length < 2 ? "0" + absOffsetHours : absOffsetHours) + (absOffsetMinutes.toString().length < 2 ? "0" + absOffsetMinutes : absOffsetMinutes)
;
if (hour12 > 12) {
hour12 = hour12 - 12;
} else if (hour12 === 0) {
hour12 = 12;
}
var padding = function(n) {
var s = "0" + n.toString();
return s.substr(s.length - 2);
};
var f = format;
f = f.replace("%a", options.abbr_day_names[weekDay]);
f = f.replace("%A", options.day_names[weekDay]);
f = f.replace("%b", options.abbr_month_names[month]);
f = f.replace("%B", options.month_names[month]);
f = f.replace("%d", padding(day));
f = f.replace("%e", day);
f = f.replace("%-d", day);
f = f.replace("%H", padding(hour));
f = f.replace("%-H", hour);
f = f.replace("%I", padding(hour12));
f = f.replace("%-I", hour12);
f = f.replace("%m", padding(month));
f = f.replace("%-m", month);
f = f.replace("%M", padding(mins));
f = f.replace("%-M", mins);
f = f.replace("%p", options.meridian[meridian]);
f = f.replace("%S", padding(secs));
f = f.replace("%-S", secs);
f = f.replace("%w", weekDay);
f = f.replace("%y", padding(year));
f = f.replace("%-y", padding(year).replace(/^0+/, ""));
f = f.replace("%Y", year);
f = f.replace("%z", timezoneoffset);
return f;
};
I18n.toNumber = function(number, options) {
options = this.prepareOptions(
options,
this.lookup("number.format"),
{precision: 3, separator: ".", delimiter: ",", strip_insignificant_zeros: false}
);
var negative = number < 0
, string = Math.abs(number).toFixed(options.precision).toString()
, parts = string.split(".")
, precision
, buffer = []
, formattedNumber
;
number = parts[0];
precision = parts[1];
while (number.length > 0) {
buffer.unshift(number.substr(Math.max(0, number.length - 3), 3));
number = number.substr(0, number.length -3);
}
formattedNumber = buffer.join(options.delimiter);
if (options.precision > 0) {
formattedNumber += options.separator + parts[1];
}
if (negative) {
formattedNumber = "-" + formattedNumber;
}
if (options.strip_insignificant_zeros) {
var regex = {
separator: new RegExp(options.separator.replace(/\./, "\\.") + "$")
, zeros: /0+$/
};
formattedNumber = formattedNumber
.replace(regex.zeros, "")
.replace(regex.separator, "")
;
}
return formattedNumber;
};
I18n.toCurrency = function(number, options) {
options = this.prepareOptions(
options,
this.lookup("number.currency.format"),
this.lookup("number.format"),
{unit: "$", precision: 2, format: "%u%n", delimiter: ",", separator: "."}
);
number = this.toNumber(number, options);
number = options.format
.replace("%u", options.unit)
.replace("%n", number)
;
return number;
};
I18n.toHumanSize = function(number, options) {
var kb = 1024
, size = number
, iterations = 0
, unit
, precision
;
while (size >= kb && iterations < 4) {
size = size / kb;
iterations += 1;
}
if (iterations === 0) {
unit = this.t("number.human.storage_units.units.byte", {count: size});
precision = 0;
} else {
unit = this.t("number.human.storage_units.units." + [null, "kb", "mb", "gb", "tb"][iterations]);
precision = (size - Math.floor(size) === 0) ? 0 : 1;
}
options = this.prepareOptions(
options,
{precision: precision, format: "%n%u", delimiter: ""}
);
number = this.toNumber(size, options);
number = options.format
.replace("%u", unit)
.replace("%n", number)
;
return number;
};
I18n.toPercentage = function(number, options) {
options = this.prepareOptions(
options,
this.lookup("number.percentage.format"),
this.lookup("number.format"),
{precision: 3, separator: ".", delimiter: ""}
);
number = this.toNumber(number, options);
return number + "%";
};
I18n.pluralize = function(count, scope, options) {
var translation;
try {
translation = this.lookup(scope, options);
} catch (error) {}
if (!translation) {
return this.missingTranslation(scope);
}
var message;
options = this.prepareOptions(options);
options.count = count.toString();
switch(Math.abs(count)) {
case 0:
message = this.isValidNode(translation, "zero") ? translation.zero :
this.isValidNode(translation, "none") ? translation.none :
this.isValidNode(translation, "other") ? translation.other :
this.missingTranslation(scope, "zero");
break;
case 1:
message = this.isValidNode(translation, "one") ? translation.one : this.missingTranslation(scope, "one");
break;
default:
message = this.isValidNode(translation, "other") ? translation.other : this.missingTranslation(scope, "other");
}
return this.interpolate(message, options);
};
I18n.missingTranslation = function() {
var message = '[missing "' + this.currentLocale()
, count = arguments.length
;
for (var i = 0; i < count; i++) {
message += "." + arguments[i];
}
message += '" translation]';
return message;
};
I18n.currentLocale = function() {
return (I18n.locale || I18n.defaultLocale);
};
// shortcuts
I18n.t = I18n.translate;
I18n.l = I18n.localize;
I18n.p = I18n.pluralize;
var I18n = I18n || {};
I18n.translations = {"en":{"date":{"formats":{"default":"%Y-%m-%d","short":"%b %d","long":"%B %d, %Y"},"day_names":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"abbr_day_names":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"month_names":[null,"January","February","March","April","May","June","July","August","September","October","November","December"],"abbr_month_names":[null,"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],"order":["year","month","day"]},"time":{"formats":{"default":"%a, %d %b %Y %H:%M:%S %z","short":"%d %b %H:%M","long":"%B %d, %Y %H:%M"},"am":"am","pm":"pm"},"support":{"array":{"words_connector":", ","two_words_connector":" and ","last_word_connector":", and "}},"errors":{"format":"%{attribute} %{message}","messages":{"inclusion":"is not included in the list","exclusion":"is reserved","invalid":"is invalid","confirmation":"doesn't match confirmation","accepted":"must be accepted","empty":"can't be empty","blank":"can't be blank","too_long":"is too long (maximum is %{count} characters)","too_short":"is too short (minimum is %{count} characters)","wrong_length":"is the wrong length (should be %{count} characters)","not_a_number":"is not a number","not_an_integer":"must be an integer","greater_than":"must be greater than %{count}","greater_than_or_equal_to":"must be greater than or equal to %{count}","equal_to":"must be equal to %{count}","less_than":"must be less than %{count}","less_than_or_equal_to":"must be less than or equal to %{count}","odd":"must be odd","even":"must be even","expired":"has expired, please request a new one","not_found":"not found","already_confirmed":"was already confirmed, please try signing in","not_locked":"was not locked","not_saved":{"one":"1 error prohibited this %{resource} from being saved:","other":"%{count} errors prohibited this %{resource} from being saved:"}}},"number":{"format":{"separator":".","delimiter":",","precision":3,"significant":false,"strip_insignificant_zeros":false},"currency":{"format":{"format":"%u%n","unit":"$","separator":".","delimiter":",","precision":2,"significant":false,"strip_insignificant_zeros":false}},"percentage":{"format":{"delimiter":""}},"precision":{"format":{"delimiter":""}},"human":{"format":{"delimiter":"","precision":3,"significant":true,"strip_insignificant_zeros":true},"storage_units":{"format":"%n %u","units":{"byte":{"one":"Byte","other":"Bytes"},"kb":"KB","mb":"MB","gb":"GB","tb":"TB"}},"decimal_units":{"format":"%n %u","units":{"unit":"","thousand":"Thousand","million":"Million","billion":"Billion","trillion":"Trillion","quadrillion":"Quadrillion"}}}},"datetime":{"distance_in_words":{"half_a_minute":"half a minute","less_than_x_seconds":{"one":"less than 1 second","other":"less than %{count} seconds"},"x_seconds":{"one":"1 second","other":"%{count} seconds"},"less_than_x_minutes":{"one":"less than a minute","other":"less than %{count} minutes"},"x_minutes":{"one":"1 minute","other":"%{count} minutes"},"about_x_hours":{"one":"about 1 hour","other":"about %{count} hours"},"x_days":{"one":"1 day","other":"%{count} days"},"about_x_months":{"one":"about 1 month","other":"about %{count} months"},"x_months":{"one":"1 month","other":"%{count} months"},"about_x_years":{"one":"about 1 year","other":"about %{count} years"},"over_x_years":{"one":"over 1 year","other":"over %{count} years"},"almost_x_years":{"one":"almost 1 year","other":"almost %{count} years"}},"prompts":{"year":"Year","month":"Month","day":"Day","hour":"Hour","minute":"Minute","second":"Seconds"}},"helpers":{"select":{"prompt":"Please select"},"submit":{"create":"Create %{model}","update":"Update %{model}","submit":"Save %{model}"},"button":{"create":"Create %{model}","update":"Update %{model}","submit":"Save %{model}"}},"mongoid":{"errors":{"messages":{"blank":"can't be blank","taken":"is already taken","callbacks":"Calling %{method} on %{klass} resulted in a false return from a callback.","document_not_found":"Document not found for class %{klass} with id(s) %{identifiers}.","eager_load":"Eager loading :%{name} is not supported due to it being a many-to-many or polymorphic belongs_to relation.","invalid_database":"Database should be a Mongo::DB, not %{name}.","invalid_time":"'%{value}' is not a valid Time.","invalid_options":"Invalid option :%{invalid} provided to relation :%{name}. Valid options are: %{valid}.","invalid_type":"Field was defined as a(n) %{klass}, but received a %{other} with the value %{value}.","unsupported_version":"MongoDB %{version} not supported, please upgrade to %{mongo_version}.","validations":"Validation failed - %{errors}.","invalid_collection":"Access to the collection for %{klass} is not allowed since it is an embedded document, please access a collection from the root document.","invalid_field":"Defining a field named %{name} is not allowed. Do not define fields that conflict with Mongoid internal attributes or method names. Use Mongoid.destructive_fields to see what names this includes.","too_many_nested_attribute_records":"Accepting nested attributes for %{association} is limited to %{limit} records.","embedded_in_must_have_inverse_of":"Options for embedded_in association must include inverse_of.","dependent_only_references_one_or_many":"The dependent => destroy|delete option that was supplied is only valid on references_one or references_many associations.","association_cant_have_inverse_of":"Defining an inverse_of on this association is not allowed. Only use this option on embedded_in or references_many as array.","calling_document_find_with_nil_is_invalid":"Calling Document#find with nil is invalid","unsaved_document":"You cannot call create or create! through a relational association relation (%{document}) who's parent (%{base}) is not already saved.","mixed_relations":"Referencing a(n) %{embedded} document from the %{root} document via a relational association is not allowed since the %{embedded} is embedded.","no_environment":"Mongoid attempted to find the appropriate environment but no Rails.env, Sinatra::Base.environment, or RACK_ENV could be found.","scope_overwrite":"Cannot create scope :%{scope_name}, because of existing method %{model_name}.%{scope_name}.","blank_on_locale":"can't be blank in %{location}"}}},"devise":{"failure":{"already_authenticated":"You are already signed in.","unauthenticated":"You need to sign in or sign up before continuing.","unconfirmed":"You have to confirm your account before continuing.","locked":"Your account is locked.","invalid":"Invalid email or password.","invalid_token":"Invalid authentication token.","timeout":"Your session expired, please sign in again to continue.","inactive":"Your account was not activated yet."},"sessions":{"signed_in":"Signed in successfully.","signed_out":"Signed out successfully."},"passwords":{"send_instructions":"You will receive an email with instructions about how to reset your password in a few minutes.","updated":"Your password was changed successfully. You are now signed in.","updated_not_active":"Your password was changed successfully.","send_paranoid_instructions":"If your e-mail exists on our database, you will receive a password recovery link on your e-mail"},"confirmations":{"send_instructions":"You will receive an email with instructions about how to confirm your account in a few minutes.","send_paranoid_instructions":"If your e-mail exists on our database, you will receive an email with instructions about how to confirm your account in a few minutes.","confirmed":"Your account was successfully confirmed. You are now signed in."},"registrations":{"signed_up":"Welcome! You have signed up successfully.","signed_up_but_unconfirmed":"A message with a confirmation link has been sent to your email address. Please open the link to activate your account.","signed_up_but_inactive":"You have signed up successfully. However, we could not sign you in because your account is not yet activated.","signed_up_but_locked":"You have signed up successfully. However, we could not sign you in because your account is locked.","updated":"You updated your account successfully.","update_needs_confirmation":"You updated your account successfully, but we need to verify your new email address. Please check your email and click on the confirm link to finalize confirming your new email address.","destroyed":"Bye! Your account was successfully cancelled. We hope to see you again soon."},"unlocks":{"send_instructions":"You will receive an email with instructions about how to unlock your account in a few minutes.","unlocked":"Your account has been unlocked successfully. Please sign in to continue.","send_paranoid_instructions":"If your account exists, you will receive an email with instructions about how to unlock it in a few minutes."},"omniauth_callbacks":{"success":"Successfully authorized from %{kind} account.","failure":"Could not authorize you from %{kind} because \"%{reason}\"."},"mailer":{"confirmation_instructions":{"subject":"Confirmation instructions"},"reset_password_instructions":{"subject":"Reset password instructions"},"unlock_instructions":{"subject":"Unlock Instructions"}}},"views":{"pagination":{"first":"&laquo; First","last":"Last &raquo;","previous":"&lsaquo; Prev","next":"Next &rsaquo;","truncate":"..."}},"models":{"categories":"categories","destinations":"destinations","country":"country","region":"region","area":"area","account":"account","accounts":"accounts","activities":"activities"},"actions":{"new_category":"new category","new_subcategory":"new subcategory","new_activity":"new activity","new_country":"new country","new_region":"new region","new_area":"new area","new_account":"new account","new":"new","edit_category":"edit category","edit_activity":"edit activity","assign_category":"assign category","edit_country":"edit country","edit_region":"edit region","edit_area":"edit area","edit":"edit","delete":"delete","search":"search","next":"next","previous":"previous","save":"save","cancel":"cancel","select_day":"select day"},"category_attributes":{"name":"name","description":"description","subcategories":"subcategories","activities_assigned":"activities assigned","categories_assigned":"categories assigned"},"times":{"from_day":"from day","to_day":"to day","from_time":"from time","to_time":"to time","add_time":"add time","delete_time":"delete time"},"feature":{"parking":"parking","valet_parking":"valet parking","wheelchair_access":"wheelchair access","credit_cards":"credit cards","internet":"internet","transportation":"transportation","reservations":"reservations","restaurant_facilities":"restaurant facilities","picnic_facilities":"picnic facilities","kid_friendly":"kid friendly","group_friendly":"group friendly","childcare":"childcare","equipment_rentals":"equipment_rentals","lockers":"lockers","changing_rooms":"changing rooms","first_aid":"first aid","life_guards":"life guards","tour_guides":"tour guides"}},"id":{"date":{"abbr_day_names":["Min","Sen","Sel","Rab","Kam","Jum","Sab"],"abbr_month_names":[null,"Jan","Feb","Mar","Apr","Mei","Jun","Jul","Agu","Sep","Okt","Nov","Des"],"day_names":["Minggu","Senin","Selasa","Rabu","Kamis","Jum'at","Sabtu"],"formats":{"default":"%d %B %Y","long":"%A, %d %B %Y","short":"%d.%m.%Y"},"month_names":[null,"Januari","Februari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","November","Desember"],"order":["day","month","year"]},"datetime":{"distance_in_words":{"about_x_hours":{"one":"sekitar satu jam","other":"sekitar %{count} jam"},"about_x_months":{"one":"sekitar sebulan","other":"sekitar %{count} bulan"},"about_x_years":{"one":"setahun","other":"noin %{count} tahun"},"almost_x_years":{"one":"hampir setahun","other":"hampir %{count} tahun"},"half_a_minute":"setengah menit","less_than_x_minutes":{"one":"kurang dari 1 menit","other":"kurang dari %{count} menit","zero":"kurang dari 1 menit"},"less_than_x_seconds":{"one":"kurang dari 1 detik","other":"kurang dari %{count} detik","zero":"kurang dari 1 detik"},"over_x_years":{"one":"lebih dari setahun","other":"lebih dari %{count} tahun"},"x_days":{"one":"sehari","other":"%{count} hari"},"x_minutes":{"one":"satu menit","other":"%{count} menit"},"x_months":{"one":"sebulan","other":"%{count} bulan"},"x_seconds":{"one":"satu detik","other":"%{count} detik"}},"prompts":{"day":"Hari","hour":"Jam","minute":"Menit","month":"Bulan","second":"Detik","year":"Tahun"}},"errors":{"format":"%{attribute} %{message}","messages":{"accepted":"harus diterima","blank":"tidak bisa kosong","confirmation":"tidak sesuai dengan konfirmasi","empty":"tidak bisa kosong","equal_to":"harus sama dengan %{count}","even":"harus genap","exclusion":"sudah digunakan","greater_than":"harus lebih besar dari %{count}","greater_than_or_equal_to":"harus sama atau lebih besar dari %{count}","inclusion":"tidak termasuk","invalid":"tidak valid","less_than":"harus lebih kecil dari %{count}","less_than_or_equal_to":"harus sama atau lebih kecil dari %{count}","not_a_number":"bukan angka","odd":"harus ganjil","record_invalid":"Verifikasi gagal: %{errors}","taken":"sudah digunakan","too_long":"terlalu panjang (maksimum %{count} karakter)","too_short":"terlalu pendek (minimum %{count} karakter)","wrong_length":"jumlah karakter salah (seharusnya %{count} karakter)"},"template":{"body":"Ada masalah dengan field berikut:","header":{"one":"1 kesalahan mengakibatkan %{model} ini tidak bisa disimpan","other":"%{count} kesalahan mengakibatkan %{model} ini tidak bisa disimpan"}}},"helpers":{"select":{"prompt":"Silahkan pilih"},"submit":{"create":"Buat %{model}","submit":"Simpan %{model}","update":"Update %{model}"}},"number":{"currency":{"format":{"delimiter":".","format":"%u%n","precision":2,"separator":",","significant":false,"strip_insignificant_zeros":false,"unit":"Rp"}},"format":{"delimiter":".","precision":3,"separator":",","significant":false,"strip_insignificant_zeros":false},"human":{"decimal_units":{"format":"%n %u","units":{"billion":"Miliar","million":"Juta","quadrillion":"Quadriliun","thousand":"Ribu","trillion":"Triliun","unit":""}},"format":{"delimiter":"","precision":3,"significant":true,"strip_insignificant_zeros":true},"storage_units":{"format":"%n %u","units":{"byte":{"one":"Byte","other":"Byte"},"gb":"GB","kb":"KB","mb":"MB","tb":"TB"}}},"percentage":{"format":{"delimiter":""}},"precision":{"format":{"delimiter":""}}},"support":{"array":{"last_word_connector":" dan ","two_words_connector":", ","words_connector":", "}},"time":{"am":"am","formats":{"default":"%a, %d %b %Y %H.%M.%S %z","long":"%d %B %Y %H.%M","short":"%d %b %H.%M"},"pm":"pm"},"activemodel":{"errors":{"format":"%{attribute} %{message}","messages":{"accepted":"harus diterima","blank":"tidak bisa kosong","confirmation":"tidak sesuai dengan konfirmasi","empty":"tidak bisa kosong","equal_to":"harus sama dengan %{count}","even":"harus genap","exclusion":"sudah digunakan","greater_than":"harus lebih besar dari %{count}","greater_than_or_equal_to":"harus sama atau lebih besar dari %{count}","inclusion":"tidak termasuk","invalid":"tidak valid","less_than":"harus lebih kecil dari %{count}","less_than_or_equal_to":"harus sama atau lebih kecil dari %{count}","not_a_number":"bukan angka","odd":"harus ganjil","record_invalid":"Verifikasi gagal: %{errors}","taken":"sudah digunakan","too_long":"terlalu panjang (maksimum %{count} karakter)","too_short":"terlalu pendek (minimum %{count} karakter)","wrong_length":"jumlah karakter salah (seharusnya %{count} karakter)"},"template":{"body":"Ada masalah dengan field berikut:","header":{"one":"1 kesalahan mengakibatkan %{model} ini tidak bisa disimpan","other":"%{count} kesalahan mengakibatkan %{model} ini tidak bisa disimpan"}}}},"activerecord":{"errors":{"format":"%{attribute} %{message}","messages":{"accepted":"harus diterima","blank":"tidak bisa kosong","confirmation":"tidak sesuai dengan konfirmasi","empty":"tidak bisa kosong","equal_to":"harus sama dengan %{count}","even":"harus genap","exclusion":"sudah digunakan","greater_than":"harus lebih besar dari %{count}","greater_than_or_equal_to":"harus sama atau lebih besar dari %{count}","inclusion":"tidak termasuk","invalid":"tidak valid","less_than":"harus lebih kecil dari %{count}","less_than_or_equal_to":"harus sama atau lebih kecil dari %{count}","not_a_number":"bukan angka","odd":"harus ganjil","record_invalid":"Verifikasi gagal: %{errors}","taken":"sudah digunakan","too_long":"terlalu panjang (maksimum %{count} karakter)","too_short":"terlalu pendek (minimum %{count} karakter)","wrong_length":"jumlah karakter salah (seharusnya %{count} karakter)"},"template":{"body":"Ada masalah dengan field berikut:","header":{"one":"1 kesalahan mengakibatkan %{model} ini tidak bisa disimpan","other":"%{count} kesalahan mengakibatkan %{model} ini tidak bisa disimpan"}}}},"models":{"categories":"kategori-kategori","destinations":"tujuan","country":"negara","region":"daerah","area":"kabupaten","account":"akun","accounts":"akun-akun","activities":"aktivitas"},"actions":{"new_category":"kategori baru","new_subcategory":"subketori baru","new_activity":"aktivitas baru","new_country":"negara baru","new_region":"daerah baru","new_area":"kabupaten baru","new_account":"akun baru","edit_category":"rubah kategory","edit_activity":"rubah aktivitas","assign_category":"menetapkan kategory","new":"baru","edit":"rubah","delete":"buang","search":"pencarian","next":"berikut","previous":"sebelum","save":"simpan","cancel":"batalkan","select_day":"select day"},"category_attributes":{"name":"nama","description":"deskripsi","subcategories":"subcategories","activities_assigned":"aktivitas ditugaskan","categories_assigned":"kategori ditugaskan"},"times":{"from_day":"dari hari","to_day":"sampai hari","from_time":"dari jam","to_time":"sampai jam","add_time":"tambah jam","delete_time":"hapus jam"},"feature":{"parking":"parking","valet_parking":"valet parking","wheelchair_access":"wheelchair access","credit_cards":"credit cards","internet":"internet","transportation":"transportation","reservations":"reservations","restaurant_facilities":"restaurant facilities","picnic_facilities":"picnic facilities","kid_friendly":"kid friendly","group_friendly":"group friendly","childcare":"childcare","equipment_rentals":"equipment_rentals","lockers":"lockers","changing_rooms":"changing rooms","first_aid":"first aid","life_guards":"life guards","tour_guides":"tour guides"}}};
Support = {};
Support.VERSION = "0.0.1";
Support.CompositeView = function(options) {
this.children = _([]);
Backbone.View.apply(this, [options]);
};
_.extend(Support.CompositeView.prototype, Backbone.View.prototype, {
leave: function() {
this.unbind();
this.remove();
this._leaveChildren();
this._removeFromParent();
},
renderChild: function(view) {
view.render();
this.children.push(view);
view.parent = this;
},
appendChild: function(view) {
this.renderChild(view);
$(this.el).append(view.el);
},
renderChildInto: function(view, container) {
this.renderChild(view);
$(container).empty().append(view.el);
},
_leaveChildren: function() {
this.children.chain().clone().each(function(view) {
if (view.leave)
view.leave();
});
},
_removeFromParent: function() {
if (this.parent)
this.parent._removeChild(this);
},
_removeChild: function(view) {
var index = this.children.indexOf(view);
this.children.splice(index, 1);
}
});
Support.CompositeView.extend = Backbone.View.extend;
Support.SwappingRouter = function(options) {
Backbone.Router.apply(this, [options]);
};
_.extend(Support.SwappingRouter.prototype, Backbone.Router.prototype, {
swap: function(newView) {
if (this.currentView && this.currentView.leave) {
this.currentView.leave();
}
this.currentView = newView;
$(this.el).empty().append(this.currentView.render().el);
}
});
Support.SwappingRouter.extend = Backbone.Router.extend;
(function() {
var _this = this;
_.templateSettings = {
interpolate: /\{\{([\s\S]+?)\}\}/g
};
_.mixin(_.str.exports());
_.str.include('Underscore.string', 'string');
Backbone.Model.prototype.idAttribute = "_id";
_.mixin(_.str.exports());
_.str.include('Underscore.string', 'string');
this.t = function(inputString) {
return I18n.t(inputString);
};
I18n.available_locales = ["en", "id"];
Handlebars.registerHelper("localize", function(obj) {
debug(obj);
if (obj[I18n.locale] != null) {
return obj[I18n.locale];
} else {
return obj[I18n.default_locale];
}
});
Handlebars.registerHelper("I18nDays", function() {
var day, days, index, out, _i, _len;
days = I18n.t("date.abbr_day_names");
out = "";
for (index = _i = 0, _len = days.length; _i < _len; index = ++_i) {
day = days[index];
out += "<option value=" + index + ">" + day + "</option>";
}
return out;
});
Handlebars.registerHelper("I18nDayFormat", function(daynum) {
var days;
days = I18n.t("date.abbr_day_names");
return days[parseInt(daynum)];
});
Handlebars.registerHelper("destHeader", function(type) {
if (type === "country") {
return _(I18n.t("models.country")).titleize();
}
if (type === "region") {
return _(I18n.t("models.region")).titleize();
}
if (type === "area") {
return _(I18n.t("models.area")).titleize();
}
});
Handlebars.registerHelper("Pager", function(pagination) {
var index, out, text, _i, _j, _ref, _ref1, _ref2, _ref3;
if (pagination.pages > 1) {
out = '<div class="pagination"> <ul>';
if (pagination.previous) {
text = _(I18n.t("actions.previous")).titleize();
out = out + '<li><a href ="#" class="previous">' + text + '</a></li>';
}
if (pagination.current !== 1) {
out = out + '<li><a href = "#" class="page">1</a></li><li class="disabled"><a href="#">...</a></li>';
}
for (index = _i = _ref = pagination.current - 3, _ref1 = pagination.current - 1; _ref <= _ref1 ? _i < _ref1 : _i > _ref1; index = _ref <= _ref1 ? ++_i : --_i) {
if (index > 1) {
out = out + '<li><a href="#" class="page">' + index + '</a></li>';
}
}
out = out + '<li class="active"><a href="#">' + pagination.current + '</a></li>';
for (index = _j = _ref2 = pagination.current + 1, _ref3 = pagination.current + 3; _ref2 <= _ref3 ? _j < _ref3 : _j > _ref3; index = _ref2 <= _ref3 ? ++_j : --_j) {
if (index < pagination.pages) {
out = out + '<li><a href="#" class="page">' + index + '</a></li>';
}
}
if (pagination.pages > pagination.current) {
out = out + '<li class="disabled"><a href="#">...</a></li>';
out = out + '<li><a href="#" class="page">' + pagination.pages + '</a></li>';
}
if (pagination.next) {
text = _(I18n.t("actions.next")).titleize();
out = out + '<li><a href="#" class="next">' + text + '</a></li>';
}
out = out + '</ul></div>';
}
return out;
});
Handlebars.registerHelper("I18n", function(str) {
if (I18n !== undefined) {
return _(I18n.t(str)).titleize();
} else {
return str;
}
});
Handlebars.registerHelper("GeoLat", function(arry) {
if (arry != null) {
return arry[1];
} else {
return "";
}
});
Handlebars.registerHelper("GeoLng", function(arry) {
if (arry != null) {
return arry[0];
} else {
return "";
}
});
Handlebars.registerHelper("translations", function(object) {
return object[this];
});
Handlebars.registerHelper("upCase", function(object) {
return object.toUpperCase();
});
Handlebars.registerHelper("checkEd", function(object) {
var result;
if (object === true) {
debug(object);
debug("checked");
result = 'checked="checked"';
return new Handlebars.SafeString(result);
} else if (object === false || object === void 0) {
result = ' ';
return new Handlebars.SafeString(result);
}
});
window.debug = function(object) {
if (window.console) {
return window.console.log(object);
}
};
window.AdminApp = null;
window.AdminApp = {
initialize: function() {
var _this = this;
if (this.admin && this.config) {
new AdminApp.NavbarView({
admin: this.admin,
config: this.config
}).render().el;
this.categoriesRouter = new AdminApp.CategoriesRouter({
admin: this.admin,
config: this.config
});
this.activitiesRouter = new AdminApp.ActivitiesRouter({
admin: this.admin,
config: this.config
});
this.destinationsRouter = new AdminApp.DestinationsRouter({
admin: this.admin,
config: this.config
});
this.accountsRouter = new AdminApp.AccountsRouter({
admin: this.admin,
config: this.config
});
this.config.on("change:locale", function() {
return I18n.locale = _this.config.get("locale");
});
return Backbone.history.start({
pushState: true
});
}
}
};
}).call(this);
(function() {
AdminApp.AccountsRouter = Support.SwappingRouter.extend({
initialize: function(options) {
debug("initialize router");
this.el = $("#admin-app");
this.admin = options.admin;
this.accounts = new AdminApp.Accounts;
this.config = options.config;
this.destinations = new AdminApp.Destinations;
this.destinations.reset();
this.categories = new AdminApp.Categories;
this.categories.reset();
this.destinations.lazy_load();
return this.categories.lazy_load();
},
routes: {
"admin/accounts": "showAccounts",
"admin/accounts/new": "newAccount",
"admin/accounts/:id/edit": "editAccount"
},
showAccounts: function() {
var view;
view = new AdminApp.AccountsView({
collection: this.accounts,
config: this.config
});
return this.swap(view);
},
newAccount: function() {
var view;
view = new AdminApp.EditAccountView({
config: this.config,
categories: this.categories,
destinations: this.destinations
});
return this.swap(view);
},
editAccount: function(id) {
var _this = this;
return this.accounts.lazy_load({
success: function() {
var view;
_this.account = _this.accounts.get(id);
view = new AdminApp.EditAccountView({
model: _this.account,
config: _this.config,
categories: _this.categories,
destinations: _this.destinations
});
return _this.swap(view);
}
});
}
});
}).call(this);
(function() {
AdminApp.ActivitiesRouter = Support.SwappingRouter.extend({
initialize: function(options) {
this.el = $("#admin-app");
this.collection = new AdminApp.Activities;
return this.config = options.config;
},
routes: {
"admin/activities": "showActivities",
"admin/activities/new": "newActivity",
"admin/activities/:id/edit": "editActivity"
},
showActivities: function() {
var view;
view = new AdminApp.ActivitiesView({
collection: this.collection,
config: this.config
});
return this.swap(view);
},
newActivity: function() {
var view;
view = new AdminApp.EditActivityView({
config: this.config
});
return this.swap(view);
},
editActivity: function(id) {
var _this = this;
return this.preloadActivities(function() {
var activity, view;
activity = _this.collection.get(id);
view = new AdminApp.EditActivityView({
model: activity,
config: _this.config
});
return _this.swap(view);
});
},
preloadActivities: function(callback) {
var _this = this;
if (this.collection && this.collection.length > 0) {
return callback();
} else {
return this.collection.fetch({
success: function() {
return callback();
}
});
}
}
});
}).call(this);
(function() {
AdminApp.CategoriesRouter = Support.SwappingRouter.extend({
initialize: function(options) {
this.el = $("#admin-app");
this.collection = new AdminApp.Categories;
return this.config = options.config;
},
routes: {
"admin/categories": "showCategories",
"admin/categories/new": "newCategory",
"admin/categories/:id/edit": "editCategory",
"admin/categories/:id/new": "newSubcategory"
},
showCategories: function() {
var view;
view = new AdminApp.CategoriesView({
collection: this.collection,
config: this.config
});
return this.swap(view);
},
newCategory: function() {
var view;
view = new AdminApp.EditCategoryView({
config: this.config
});
return this.swap(view);
},
editCategory: function(id) {
var _this = this;
return this.collection.lazy_load({
success: function() {
var view;
_this.model = _this.collection.get(id);
view = new AdminApp.EditCategoryView({
model: _this.model,
config: _this.config
});
return _this.swap(view);
}
});
},
newSubcategory: function(id) {
var _this = this;
return this.collection.lazy_load({
success: function() {
var view;
_this.parent = _this.collection.get(id);
view = new AdminApp.EditCategoryView({
parent: _this.parent,
config: _this.config
});
return _this.swap(view);
}
});
}
});
}).call(this);
(function() {
AdminApp.DestinationsRouter = Support.SwappingRouter.extend({
initialize: function(options) {
this.el = $("#admin-app");
this.collection = new AdminApp.Destinations;
return this.config = options.config;
},
routes: {
"admin/destinations": "showDestinations",
"admin/destinations/new": "newDestination",
"admin/destinations/:id/edit": "editDestination",
"admin/destinations/:id/new": "newSubDestination"
},
showDestinations: function() {
var view;
view = new AdminApp.DestinationsView({
collection: this.collection,
config: this.config
});
return this.swap(view);
},
newDestination: function() {
var view;
view = new AdminApp.EditDestinationView;
return this.swap(view);
},
newSubDestination: function(id) {
var _this = this;
return this.collection.lazy_load({
success: function() {
var view;
_this.parent = _this.collection.get(id);
view = new AdminApp.EditDestinationView({
parent: _this.parent,
config: _this.config
});
return _this.swap(view);
}
});
},
editDestination: function(id) {
var _this = this;
return this.collection.lazy_load({
success: function() {
var view;
_this.model = _this.collection.get(id);
view = new AdminApp.EditDestinationView({
model: _this.model,
config: _this.config
});
return _this.swap(view);
}
});
}
});
}).call(this);
(function() {
AdminApp.Account = Backbone.Model.extend({
initialize: function() {
this.on("change:account_image", this.parseImage);
this.parseImage();
return this.parseBranches();
},
parseBranches: function() {
var data;
if (!this.isNew()) {
if (this.get('locations')) {
data = this.get('locations');
debug("location data");
debug(data);
delete this.attributes.locations;
this.branches = new AdminApp.Branches(data);
} else {
this.branches = new AdminApp.Branches;
}
} else {
if (!(this.branches != null)) {
this.branches = new AdminApp.Branches;
}
}
debug(this);
return this.branches.on("destroy", this.deleteBranch, this);
},
addBranch: function(branch) {
this.branches.add(branch);
debug(this.branches);
return console.log("1 branch added");
},
updateBranch: function(branch) {
var _this = this;
this.updated_location = branch;
return this.branches.each(function(loc) {
debug("LOCATION TO UPDATE");
debug(_this.updated_location.get('id'));
debug(loc.get('id'));
if (loc.get('id') === _this.updated_location.get('id')) {
loc.destroy;
return _this.branchs.add(_this.updated_location);
}
});
},
deleteBranch: function(acc_location) {
var branch, location_id;
console.log("destroy detected");
location_id = acc_location.get('id');
branch = new AdminApp.Branch({
id: location_id,
_destroy: true
});
return this.branches.add(branch, {
silent: true
});
},
parseImage: function() {
var photo_id;
if (!this.isNew() && (this.get('account_image') != null)) {
if (this.get('account_image')['_id'] != null) {
photo_id = this.get('account_image')['_id'];
if (this.get('account_image') != null) {
this.image = new AdminApp.Photo({
id: photo_id
});
}
this.image.fetch();
}
} else {
this.image = new AdminApp.Photo;
}
return this.image.on("change", this.updateImageAttributes, this);
},
image_attributes: function() {
return {
photo_id: this.image.get('_id')
};
},
updateImageAttributes: function() {
return this.set(this.image_attributes(), {
silent: true
});
},
url: function() {
var auth_token;
auth_token = "?auth_token=" + (AdminApp.admin.get('auth_token'));
if (this.id) {
return "/api/accounts/" + this.id + auth_token;
} else {
return "/api/accounts" + auth_token;
}
},
locales: ["en", "id"],
defaultLocale: "en",
idAttribute: "_id",
toJSON: function() {
var attributes, json;
attributes = _.clone(this.attributes);
delete attributes['country'];
delete attributes['category'];
delete attributes['admin'];
delete attributes['account_image'];
delete attributes['locations'];
delete attributes['locations_attributes'];
json = {
account: attributes
};
json.account.locations_attributes = this.processLocations();
_.extend(json.account, this.image_attributes());
return json;
},
processLocations: function() {
return this.branches.map(function(branch) {
var parse_location;
parse_location = {};
return parse_location = {
address: branch.get('address'),
contact: branch.get('contact'),
feature: branch.get('feature'),
operating_times: branch.get('operating_times'),
area: branch.get('area') != null ? branch.get('area') : void 0,
region: branch.get('region') != null ? branch.get('region') : void 0,
country: branch.get('country') != null ? branch.get('country') : void 0,
geo: branch.get('geo'),
zoom: branch.get('zoom'),
_id: branch.get('id') != null ? branch.get('id') : void 0,
_destroy: branch.get('_destroy') != null ? branch.get('_destroy') : void 0
};
});
},
fetch_success: function() {
this.branches = new AdminApp.Branches(this.get('locations'));
return this.image = this.get('account_image');
}
});
AdminApp.Accounts = Backbone.Collection.extend({
model: AdminApp.Account,
url: "/api/accounts",
initialize: function() {
return this.pagination = {};
},
parse: function(response) {
this.pagination = response.pagination;
return this.collection = response.collection;
},
lazy_load: function(callbacks) {
if (callbacks == null) {
callbacks = {};
}
if (this.length) {
if (callbacks.success) {
return callbacks.success();
}
} else {
return this.fetch(callbacks);
}
}
});
}).call(this);
(function() {
AdminApp.Activity = Backbone.Model.extend({
url: function() {
var auth_token;
auth_token = "?auth_token=" + (AdminApp.admin.get('auth_token'));
if (this.id) {
return "/api/activities/" + this.id + auth_token;
} else {
return "/api/activities" + auth_token;
}
},
toJSON: function() {
var attributes;
attributes = _.clone(this.attributes);
return {
activity: attributes
};
},
locales: ["en", "id"],
defaultLocale: "en",
idAttribute: "_id"
});
AdminApp.Activities = Backbone.Collection.extend({
model: AdminApp.Activity,
url: "/api/activities",
comparator: function(category) {
return category.get("name")["" + window.I18n.locale];
},
lazy_load: function(callbacks) {
if (callbacks == null) {
callbacks = {};
}
if (this.length) {
if (callbacks.success) {
return callbacks.success();
}
} else {
return this.fetch(callbacks);
}
}
});
}).call(this);
(function() {
AdminApp.Admin = Backbone.Model.extend({
initialize: function() {
return this.admin = AdminApp.admin;
},
urlRoot: "/admins",
toJSON: function() {
var attributes;
attributes = _.clone(this.attributes);
return {
user: attributes
};
},
locales: ["en", "id"],
defaultLocale: "en",
idAttribute: "_id"
});
}).call(this);
(function() {
AdminApp.Branch = Backbone.Model.extend({
validate: function() {
console.log("Baa");
debug("IN Validate");
return debug(this.attributes);
}
});
AdminApp.Branches = Backbone.Collection.extend({
model: AdminApp.Branch
});
}).call(this);
(function() {
AdminApp.Category = Backbone.Model.extend({
url: function() {
var auth_token;
auth_token = "?auth_token=" + (AdminApp.admin.get('auth_token'));
if (this.id) {
return '/api/categories/' + this.id + auth_token;
} else {
return '/api/categories' + auth_token;
}
},
toJSON: function() {
var attributes;
attributes = _.clone(this.attributes);
return {
category: attributes
};
},
locales: ["en", "id"],
defaultLocale: "en",
idAttribute: "_id"
});
AdminApp.Categories = Backbone.Collection.extend({
model: AdminApp.Category,
url: '/api/categories',
comparator: function(category) {
return category.get("name")["" + window.I18n.locale];
},
filterByLevel: function(level) {
return this.models.filter(function(d) {
return d.get("level") === level;
});
},
filterByParent: function(parent) {
return this.models.filter(function(d) {
return d.get("parent_id") === parent;
});
},
lazy_load: function(callbacks) {
if (callbacks == null) {
callbacks = {};
}
if (this.length) {
if (callbacks.success) {
return callbacks.success();
}
} else {
return this.fetch(callbacks);
}
}
});
}).call(this);
(function() {
AdminApp.Config = Backbone.Model.extend({
initialize: function() {
return this.set({
locale: window.I18n.locale
});
},
locales: ["en", "id"],
defaultLocale: "en"
});
}).call(this);
(function() {
AdminApp.Destination = Backbone.Model.extend({
url: function() {
var auth_token;
auth_token = "?auth_token=" + (AdminApp.admin.get('auth_token'));
if (this.id) {
return '/api/destinations/' + this.id + auth_token;
} else {
return '/api/destinations' + auth_token;
}
},
locales: ["en", "id"],
defaultLocale: "en",
idAttribute: "_id",
toJSON: function() {
var attributes;
attributes = _.clone(this.attributes);
return {
destination: attributes
};
}
});
AdminApp.Destinations = Backbone.Collection.extend({
model: AdminApp.Destination,
url: '/api/destinations',
comparator: function(destination) {
return destination.get("name")["" + window.I18n.locale];
},
filterByLevel: function(level) {
return this.models.filter(function(d) {
return d.get("level") === level;
});
},
filterByParent: function(parent) {
return this.models.filter(function(d) {
return d.get("parent_id") === parent;
});
},
lazy_load: function(callbacks) {
if (callbacks == null) {
callbacks = {};
}
if (this.length) {
if (callbacks.success) {
return callbacks.success();
}
} else {
return this.fetch(callbacks);
}
}
});
}).call(this);
(function() {
AdminApp.Photo = Backbone.Model.extend({
initialize: function() {
if (this.attributes.id) {
return this.id = this.attributes.id;
}
},
url: function() {
var auth_token;
auth_token = "?auth_token=" + (AdminApp.admin.get('auth_token'));
if (this.id) {
return '/api/photos/' + this.id + auth_token;
} else {
return '/api/photos/' + auth_token;
}
},
toJSON: function() {
var attributes;
attributes = _.clone(this.attributes);
return {
photo: attributes
};
},
locales: ["en", "id"],
defaultLocale: "en",
idAttribute: "_id"
});
AdminApp.Photos = Backbone.Collection.extend({
model: AdminApp.Photo,
url: "/api/photos",
lazy_load: function(callbacks) {
if (callbacks == null) {
callbacks = {};
}
if (this.length) {
if (callbacks.success) {
return callbacks.success();
}
} else {
return this.fetch(callbacks);
}
}
});
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/accounts/account"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/accounts/account"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
buffer += "<td>";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.account_name);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.account_name", { hash: {} }); }
buffer += escapeExpression(stack1) + "</td>\n<td>";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.company_name_translations);
foundHelper = helpers.localize;
stack2 = foundHelper || depth0.localize;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "localize", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</td>\n<td>";
foundHelper = helpers.category;
stack1 = foundHelper || depth0.category;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.name);
foundHelper = helpers.localize;
stack2 = foundHelper || depth0.localize;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "localize", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</td>\n<td class=\"span3\">\n<div class=\"btn-group actions inline-block\" data-toggle=\"buttons-radio\">\n <a href=\"\" class=\"btn btn-mini edit\">";
stack1 = "actions.edit";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n <a href=\"\" class=\"btn btn-mini delete\">";
stack1 = "actions.delete";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n</div>\n</td>\n";
return buffer;});
return HandlebarsTemplates["templates/admin/accounts/account"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/accounts/branch"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/accounts/branch"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, tmp1, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
function program1(depth0,data) {
var stack1, stack2;
foundHelper = helpers.area;
stack1 = foundHelper || depth0.area;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.name);
foundHelper = helpers.localize;
stack2 = foundHelper || depth0.localize;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "localize", stack1, { hash: {} }); }
else { stack1 = stack2; }
return escapeExpression(stack1);}
function program3(depth0,data) {
var buffer = "", stack1;
stack1 = depth0.address;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.street1);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this.address.street1", { hash: {} }); }
buffer += escapeExpression(stack1) + "</br>";
return buffer;}
function program5(depth0,data) {
var buffer = "", stack1;
stack1 = depth0.address;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.street2);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this.address.street2", { hash: {} }); }
buffer += escapeExpression(stack1) + "</br>";
return buffer;}
function program7(depth0,data) {
var stack1;
foundHelper = helpers.contact;
stack1 = foundHelper || depth0.contact;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.main_tel);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "contact.main_tel", { hash: {} }); }
return escapeExpression(stack1);}
function program9(depth0,data) {
var stack1;
foundHelper = helpers.contact;
stack1 = foundHelper || depth0.contact;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.email);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "contact.email", { hash: {} }); }
return escapeExpression(stack1);}
function program11(depth0,data) {
var stack1;
foundHelper = helpers.contact;
stack1 = foundHelper || depth0.contact;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.name);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "contact.name", { hash: {} }); }
return escapeExpression(stack1);}
function program13(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "\n <div class=\"open-times block\">\n <span class=\"op-day\">";
stack1 = depth0.from_day;
foundHelper = helpers.I18nDayFormat;
stack2 = foundHelper || depth0.I18nDayFormat;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18nDayFormat", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "-";
stack1 = depth0.to_day;
foundHelper = helpers.I18nDayFormat;
stack2 = foundHelper || depth0.I18nDayFormat;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18nDayFormat", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</span>\n ";
stack1 = depth0.from_time;
stack2 = helpers['if'];
tmp1 = self.program(14, program14, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n </div>\n ";
return buffer;}
function program14(depth0,data) {
var buffer = "", stack1;
buffer += "\n <span class=\"op-time\">";
stack1 = depth0.from_time;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this.from_time", { hash: {} }); }
buffer += escapeExpression(stack1) + " - ";
stack1 = depth0.to_time;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this.to_time", { hash: {} }); }
buffer += escapeExpression(stack1) + "</span>\n ";
return buffer;}
function program16(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "<li class=\"feature-icon features-parking\">";
stack1 = "feature.parking";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</li>";
return buffer;}
function program18(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "<li class=\"feature-icon features-valet_parking\">";
stack1 = "feature.valet_parking";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</li>";
return buffer;}
function program20(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "<li class=\"feature-icon features-wheelchair_access\">";
stack1 = "feature.wheelchair_access";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</li>";
return buffer;}
function program22(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "<li class=\"feature-icon features-credit_cards\">";
stack1 = "feature.credit_cards";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</li>";
return buffer;}
function program24(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "<li class=\"feature-icon features-internet\">";
stack1 = "feature.internet";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</li>";
return buffer;}
function program26(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "<li class=\"feature-icon features-transportation\">";
stack1 = "feature.transportation";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</li>";
return buffer;}
function program28(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "<li class=\"feature-icon features-reservations\">";
stack1 = "feature.reservations";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</li>";
return buffer;}
function program30(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "<li class=\"feature-icon features-restauramt_facilities\">";
stack1 = "feature.restauramt_facilities";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</li>";
return buffer;}
function program32(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "<li class=\"feature-icon features-picnic_facilities\">";
stack1 = "feature.picnic_facilities";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</li>";
return buffer;}
function program34(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "<li class=\"feature-icon features-kid_friendly\">";
stack1 = "feature.kid_friendly";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</li>";
return buffer;}
function program36(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "<li class=\"feature-icon features-group_friendly\">";
stack1 = "feature.group_friendly";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</li>";
return buffer;}
function program38(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "<li class=\"feature-icon features-childcare\">";
stack1 = "feature.childcare";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</li>";
return buffer;}
function program40(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "<li class=\"feature-icon features-equipment_rentalslockers\">";
stack1 = "feature.equipment_rentalslockers";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</li>";
return buffer;}
function program42(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "<li class=\"feature-icon features-lockers\">";
stack1 = "feature.lockers";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</li>";
return buffer;}
function program44(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "<li class=\"feature-icon features-changing_rooms\">";
stack1 = "feature.changing_rooms";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</li>";
return buffer;}
function program46(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "<li class=\"feature-icon features-first_aid\">";
stack1 = "feature.first_aid";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</li>";
return buffer;}
function program48(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "<li class=\"feature-icon features-life_guards\">";
stack1 = "feature.life_guards";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</li>";
return buffer;}
function program50(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "<li class=\"feature-icon features-tour_guides\">";
stack1 = "feature.tour_guides";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</li>";
return buffer;}
buffer += " <div class=\"one-location\">\n <div class=\"control-group location-bar\">\n <div class = \"span12\">\n <h4 class=\"span6 inline pull-left\">";
foundHelper = helpers.country;
stack1 = foundHelper || depth0.country;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.name);
foundHelper = helpers.localize;
stack2 = foundHelper || depth0.localize;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "localize", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + " > ";
foundHelper = helpers.region;
stack1 = foundHelper || depth0.region;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.name);
foundHelper = helpers.localize;
stack2 = foundHelper || depth0.localize;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "localize", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + " > ";
foundHelper = helpers.area;
stack1 = foundHelper || depth0.area;
stack2 = helpers['if'];
tmp1 = self.program(1, program1, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "</h4>\n <button class=\"btn btn-mini inline pull-right btn-danger delete-location\" href=\"#\"><i class=\"icon-trash\"></i> Delete</button>\n <button class=\"btn btn-mini inline pull-right edit-location\" href=\"#\"><i class=\"icon-edit\"></i> Edit Location</button>\n </div>\n </div>\n </br>\n <div class =\"row\">\n <div class=\"span12\">\n <div class =\"row\">\n <div class = \"span3\">\n <div class=\"summary inline-block\">\n <h4>Address Details:</h4>\n <br/> \n ";
foundHelper = helpers.address;
stack1 = foundHelper || depth0.address;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.street1);
stack2 = helpers['if'];
tmp1 = self.program(3, program3, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
foundHelper = helpers.address;
stack1 = foundHelper || depth0.address;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.street2);
stack2 = helpers['if'];
tmp1 = self.program(5, program5, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
stack1 = depth0.address;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.city);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this.address.city", { hash: {} }); }
buffer += escapeExpression(stack1) + ",";
stack1 = depth0.address;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.province);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this.address.province", { hash: {} }); }
buffer += escapeExpression(stack1) + "</br>\n ";
stack1 = depth0.address;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.postal_code);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this.address.postal_code", { hash: {} }); }
buffer += escapeExpression(stack1) + "\n </div>\n </div>\n <div class= \"span3\">\n <div class=\"summary inline-block\">\n <h4>Contact Details:</h4>\n <br/>\n Tel: ";
foundHelper = helpers.contact;
stack1 = foundHelper || depth0.contact;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.main_tel);
stack2 = helpers['if'];
tmp1 = self.program(7, program7, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "</br>\n Email: ";
foundHelper = helpers.contact;
stack1 = foundHelper || depth0.contact;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.email);
stack2 = helpers['if'];
tmp1 = self.program(9, program9, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "</br>\n Name: ";
foundHelper = helpers.contact;
stack1 = foundHelper || depth0.contact;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.name);
stack2 = helpers['if'];
tmp1 = self.program(11, program11, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "</br>\n </div> \n </div>\n <div class= \"span3\">\n <div class=\"summary inline-block\">\n <h4>Operating Times:</h4>\n <br/>\n ";
foundHelper = helpers.operating_times;
stack1 = foundHelper || depth0.operating_times;
stack2 = helpers.each;
tmp1 = self.program(13, program13, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n </div>\n </div>\n <div class= \"span3\">\n <div class=\"summary inline-block\">\n <h4>Map</h4>\n <br/>\n <div class= \"small-map inline-block\">\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"span12\">\n <h4>Location Features</h4>\n <ul class=\"location-features span12 inline-block\">\n ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.parking);
stack2 = helpers['if'];
tmp1 = self.program(16, program16, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.valet_parking);
stack2 = helpers['if'];
tmp1 = self.program(18, program18, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.wheelchair_access);
stack2 = helpers['if'];
tmp1 = self.program(20, program20, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.credit_cards);
stack2 = helpers['if'];
tmp1 = self.program(22, program22, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.internet);
stack2 = helpers['if'];
tmp1 = self.program(24, program24, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.transportation);
stack2 = helpers['if'];
tmp1 = self.program(26, program26, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.reservations);
stack2 = helpers['if'];
tmp1 = self.program(28, program28, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.restauramt_facilities);
stack2 = helpers['if'];
tmp1 = self.program(30, program30, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.picnic_facilities);
stack2 = helpers['if'];
tmp1 = self.program(32, program32, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.kid_friendly);
stack2 = helpers['if'];
tmp1 = self.program(34, program34, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
foundHelper = helpers['b'];
stack1 = foundHelper || depth0['b'];
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.group_friendly);
stack2 = helpers['if'];
tmp1 = self.program(36, program36, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.childcare);
stack2 = helpers['if'];
tmp1 = self.program(38, program38, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.equipment_rentalslockers);
stack2 = helpers['if'];
tmp1 = self.program(40, program40, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.lockers);
stack2 = helpers['if'];
tmp1 = self.program(42, program42, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.changing_rooms);
stack2 = helpers['if'];
tmp1 = self.program(44, program44, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.first_aid);
stack2 = helpers['if'];
tmp1 = self.program(46, program46, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.life_guards);
stack2 = helpers['if'];
tmp1 = self.program(48, program48, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.tour_guides);
stack2 = helpers['if'];
tmp1 = self.program(50, program50, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n </ul>\n </div>\n </div>\n </div>\n</div>\n";
return buffer;});
return HandlebarsTemplates["templates/admin/accounts/branch"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/accounts/branch_form"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/accounts/branch_form"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, tmp1, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
function program1(depth0,data) {
var stack1, stack2;
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.geo);
foundHelper = helpers.GeoLat;
stack2 = foundHelper || depth0.GeoLat;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "GeoLat", stack1, { hash: {} }); }
else { stack1 = stack2; }
return escapeExpression(stack1);}
function program3(depth0,data) {
var stack1, stack2;
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.geo);
foundHelper = helpers.GeoLng;
stack2 = foundHelper || depth0.GeoLng;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "GeoLng", stack1, { hash: {} }); }
else { stack1 = stack2; }
return escapeExpression(stack1);}
function program5(depth0,data) {
var stack1;
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.geo);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "location.geo", { hash: {} }); }
return escapeExpression(stack1);}
buffer += "<form action=\"\" method=\"post\" enctype=\"multipart/form-data\" name=\"loc\" class=\"form account\" id=\"location-form\">\n<div class = \"fieldset-header\">\n <h3>New/Edit Location</h3>\n</div>\n <div class= \"span12 field-line\">\n <div class=\"row\">\n <div class=\"span6\">\n <fieldset id=\"location-address\">\n <legend class=\"small\">Address</legend>\n <div class=\"control-group location address\">\n <label class=\"control-label\">Street Address 1:</label>\n <div class=\"controls\">\n <input type=\"text\" name=\"loc[address]{street1]\" id=\"location_address_street1\" class=\"span4\" value=\"";
foundHelper = helpers.address;
stack1 = foundHelper || depth0.address;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.street1);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "address.street1", { hash: {} }); }
buffer += escapeExpression(stack1) + "\">\n </div>\n </div>\n <div class=\"control-group location address\">\n <label class=\"control-label\">Street Address 2:</label>\n <div class=\"controls\">\n <input type=\"text\" name=\"loc[address][street2]\" id=\"location_address_street2\" class=\"span4\" value=\"\">\n </div>\n </div>\n <div class=\"control-group location address\">\n <label class=\"control-label\">City/Region:</label>\n <div class=\"controls\">\n <input type=\"text\" name=\"address.city\" id=\"location_address_city\" class=\"span3\" value=\"\">\n </div>\n </div>\n <div class=\"control-group location address\">\n <label class=\"control-label\">Province/State:</label>\n <div class=\"controls\">\n <input type=\"text\" name=\"address.province\" id=\"location_address_province\" class=\"span3\" value=\"\">\n </div>\n </div>\n <div class=\"control-group location address\">\n <label class=\"control-label inline\">Country:</label>\n <div class=\"controls inline\">\n <input type=\"text\" name=\"address.country\" id=\"location_address_country\" class=\"span2\" value=\"\">\n </div>\n <label class=\"control-label inline\">Postal Code:</label>\n <div class=\"controls inline\">\n <input type=\"text\" name=\"address.postal_code\" id=\"location_address_postal_code\" class=\"span2\" value=\"\">\n </div>\n </div>\n </fieldset>\n </div>\n <div class=\"span6\">\n <fieldset id = \"map-space\">\n <legend class=\"small\">Location Map</legend>\n <div>\n <p class=\"help-block\"><small>Enter the location address on the left and the adjust the map zoom and marker to set a default map for this location</small></p>\n </br>\n </div>\n <div class=\"control-group location map\">\n <div id=\"location-map\">\n </div>\n <div class=\"controls\" style= \"display:none\">\n <input name=\"destination_latitude\" id=\"destination_latitude\" value=\"";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.geo);
stack2 = helpers['if'];
tmp1 = self.program(1, program1, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\" type=\"hidden\">\n <input name=\"destination_longitude\" id=\"destination_longitude\" value=\"";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.geo);
stack2 = helpers['if'];
tmp1 = self.program(3, program3, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\" type=\"hidden\">\n <input name=\"destination_zoom\" id=\"destination_zoom\" value=\"";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.zoom);
stack2 = helpers['if'];
tmp1 = self.program(5, program5, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\" type=\"hidden\">\n <input name=\"destination_swlat\" id=\"destination_swlat\" value=\"";
foundHelper = helpers.destination;
stack1 = foundHelper || depth0.destination;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.swlat);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "destination.swlat", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" type=\"hidden\">\n <input name=\"destination_swlng\" id=\"destination_swlng\" value=\"";
foundHelper = helpers.destination;
stack1 = foundHelper || depth0.destination;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.swlng);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "destination.swlng", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" type=\"hidden\">\n <input name=\"destination_nelat\" id=\"destination_nelat\" value=\"";
foundHelper = helpers.destination;
stack1 = foundHelper || depth0.destination;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.nelat);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "destination.nelat", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" type=\"hidden\">\n <input name=\"destination_nelng\" id=\"destination_nelng\" value=\"";
foundHelper = helpers.destination;
stack1 = foundHelper || depth0.destination;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.nelng);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "destination.nelng", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" type=\"hidden\">\n </div>\n </div>\n </fieldset>\n </div>\n </div>\n </div>\n <div class=\"span12 field-line\">\n <div class=\"row\">\n <div class=\"span6\">\n <fieldset>\n <legend class=\"small\">Contact</legend>\n <div class=\"control-group location contact\">\n <label class=\"control-label\">Name:</label>\n <div class=\"controls\">\n <input type=\"text\" name=\"contact.name\" id=\"location_contact_name\" class=\"span3\" value=\"\">\n </div>\n </div>\n <div class=\"control-group location contact\">\n <label class=\"control-label\">Main Tel:</label>\n <div class=\"controls\">\n <input type=\"text\" name=\"contact.main_tel\" id=\"location_contact_main_tel\" value=\"\">\n </div>\n </div>\n <div class=\"control-group location contact\">\n <label class=\"control-label\">Email:</label>\n <div class=\"controls\">\n <input type=\"text\" name=\"contact.email\" id=\"location_contact_email\" class=\"span3\" value=\"\">\n </div>\n </div>\n <p class=\"help-block\"><small>These are the contact details that will be publicly displayed for the business</small></p>\n </fieldset>\n </div>\n <div class=\"span6\">\n <fieldset>\n <legend class=\"small\">What2do Region/Area</legend>\n <input type=\"hidden\" name=\"location[country]\" value= \"\" id = \"location_country_id\">\n <p class=\"help-block\"><strong>a What2do REGION and AREA for display of this location must be selected, select a REGION and then AREAS will be displayed</strong></p>\n </br>\n <div class=\"control-group country\">\n <label class=\"control-label\">Region</label>\n <div class=\"controls\">\n <select id=\"location_region_id\" name=\"location[region][_id]\">\n </select>\n </div>\n </div>\n <div class='control-group area'>\n <div id=\"area\" style='\"display\":\"none\"'>\n <label class=\"control-label\">Area</label>\n <div class=\"controls\">\n <select id=\"location_area_id\" name=\"location[area][_id]\">\n </select> \n </div>\n </div>\n </div>\n </fieldset>\n </div>\n </div>\n </div>\n <div class=\"span12 field-line\">\n <div class=\"row\">\n <div class=\"span7\">\n <fieldset>\n <legend class=\"small\">Location Features</legend>\n <div class=\"features-container\">\n <div class=\"feature\">\n <label class=\"checkbox inline-block\">\n <input type=\"checkbox\" name=\"location[feature][parking]\" value=\"";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.parking);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "feature.parking", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.parking);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">Parking</label>\n </div>\n <div class=\"feature \">\n <label class=\"checkbox inline-block\">\n <input type=\"checkbox\" name=\"location[feature][valet_parking]\" value=\"";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.valet_parking);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "feature.valet_parking", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.valet_parking);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">Valet Parking</label>\n </div>\n <div class=\"feature\">\n <label class=\"checkbox inline-block\">\n <input type=\"checkbox\" name=\"location[feature][wheelchair_access]\" value=\"";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.wheelchair_access);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "feature.wheelchair_access", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.wheelchair_access);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">Wheelchair Access</label>\n </div>\n <div class=\"feature\">\n <label class=\"checkbox inline-block\">\n <input type=\"checkbox\" name=\"location[feature][credit_cards]\" value=\"";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.credit_cards);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "feature.credit_cards", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.credit_cards);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">Credit Cards</label>\n </div>\n <div class=\"feature \">\n <label class=\"checkbox inline-block\">\n <input type=\"checkbox\" name=\"location[feature][internet]\" value=\"";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.internet);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "feature.internet", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.internet);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">Internet</label>\n </div>\n <div class=\"feature\">\n <label class=\"checkbox inline-block\">\n <input type=\"checkbox\" name=\"location[feature][transportation]\" value=\"";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.transportation);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "feature.transportation", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.feature;
stack1 = foundHelper || depth0.feature;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.transportation);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">Transportation</label>\n </div>\n <div class=\"feature\">\n <label class=\"checkbox inline-block\">\n <input type=\"checkbox\" name=\"location[feature][reservations]\" value=\"";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.reservations);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "location.feature.reservations", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.reservations);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">\n Reservations</label>\n </div>\n <div class=\"feature \">\n <label class=\"checkbox inline-block\">\n <input type=\"checkbox\" name=\"location[feature][restaurant_facilities]\" value=\"";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.restaurant_facilities);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "location.feature.restaurant_facilities", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.restaurant_facilities);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">\n Restaurant Facilities</label>\n </div>\n <div class=\"feature\">\n <label class=\"checkbox inline-block\">\n <input type=\"checkbox\" name=\"location[feature][picnic_facilities]\" value=\"";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.picnic_facilities);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "location.feature.picnic_facilities", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.picnic_facilities);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">\n Picnic Facilities</label>\n </div>\n <div class=\"feature\">\n <label class=\"checkbox inline-block\">\n <input type=\"checkbox\" name=\"location[feature][kid_friendly]\" value=\"";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.kid_friendly);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "location.feature.kid_friendly", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.kid_friendly);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">\n Kid Friendly</label>\n </div>\n <div class=\"feature\">\n <label class=\"checkbox inline-block\">\n <input type=\"checkbox\" name=\"location[feature][group_friendly]\" value=\"";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.group_friendly);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "location.feature.group_friendly", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.group_friendly);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">\n Group Friendly</label>\n </div>\n <div class=\"feature\">\n <label class=\"checkbox inline-block\">\n <input type=\"checkbox\" name=\"location[feature][childcare]\" value=\"";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.childcare);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "location.feature.childcare", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.childcare);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">\n Childcare</label>\n </div>\n <div class=\"feature\">\n <label class=\"checkbox inline-block\">\n <input type=\"checkbox\" name=\"location[feature][equipment_rentals]\" value=\"";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.equipment_rentals);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "location.feature.equipment_rentals", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.equipment_rentals);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">\n Equipment Rentals</label>\n </div>\n <div class=\"feature \">\n <label class=\"checkbox inline-block\">\n <input type=\"checkbox\" name=\"location[feature][lockers]\" value=\"";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.lockers);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "location.feature.lockers", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.lockers);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">\n Lockers</label>\n </div>\n <div class=\"feature\">\n <label class=\"checkbox inline-block\">\n <input type=\"checkbox\" name=\"location[feature][changing_rooms]\" value=\"";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.changing_rooms);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "location.feature.changing_rooms", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.changing_rooms);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">\n Changing Rooms</label>\n </div>\n <div class=\"feature\"> \n <label class=\"checkbox inline-block \">\n <input type=\"checkbox\" name=\"location[feature][first_aid]\" ";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.first_aid);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">First Aid\n </label>\n </div>\n <div class=\"feature\">\n <label class=\"checkbox inline-block\">\n <input type=\"checkbox\" name=\"location[feature][life_guards]\" value=\"";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.life_guards);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "location.feature.life_guards", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.life_guards);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">Life Guards</label>\n </div>\n <div class=\"feature\">\n <label class=\"checkbox inline-block\">\n <input type=\"checkbox\" name=\"location[feature][tour_guides]\" value=\"";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.tour_guides);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "location.feature.tour_guides", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.location;
stack1 = foundHelper || depth0.location;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.feature);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.tour_guides);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">\n Tour Guides</label>\n </div>\n </div>\n </fieldset>\n </div>\n <div class= \"span5\">\n <fieldset>\n <legend class=\"small\">Operating Times</legend>\n <div class=\"control-group operating-time\" id=\"times-operation\">\n </div>\n <div class=\"help span6\">\n <p class=\"help-inline\"><em>Leave time blank if always open</em></p>\n <div>\n </fieldset>\n </div> \n </div>\n </div>\n <div class = \"span12 field-line\">\n <div class=\"form-actions\">\n <div class=\"controls pull-right\">\n <a class=\"btn btn-primary save-location\">Add Location</a>\n <a class=\"btn cancel-location\">Cancel</a>\n </div>\n </div>\n </div>\n</form>\n";
return buffer;});
return HandlebarsTemplates["templates/admin/accounts/branch_form"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/accounts/branch_list"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/accounts/branch_list"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var foundHelper, self=this;
return "<div class= \"fieldset-header\">\n <h2>Operating Locations</h2>\n</div>\n<div id=\"account-locations\">\n</div> \n<div class=\"span12\">\n <button class =\"btn btn-inverse add-location\" href=\"\"><i class=\"icon-plus-sign\"></i> Add Location </button>\n</div>\n";});
return HandlebarsTemplates["templates/admin/accounts/branch_list"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/accounts/edit"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/accounts/edit"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, tmp1, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
function program1(depth0,data) {
var stack1, stack2;
stack1 = "actions.edit";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
return escapeExpression(stack1);}
function program3(depth0,data) {
var stack1, stack2;
stack1 = "actions.new";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
return escapeExpression(stack1);}
function program5(depth0,data) {
var buffer = "", stack1;
buffer += ": <span class=\"account-name\">";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.account_name);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.account_name", { hash: {} }); }
buffer += escapeExpression(stack1) + "</span>";
return buffer;}
function program7(depth0,data,depth1) {
var buffer = "", stack1, stack2;
buffer += "\n <input type=\"text\" name=\"company_name\" value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth1.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.company_name_translations);
foundHelper = helpers.translations;
stack2 = foundHelper || depth0.translations;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "translations", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "\" id=\"account_company_name_";
stack1 = depth0;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" class=\"span4\" style=\"display:none\">\n ";
return buffer;}
function program9(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "\n <button class=\"btn\" data-locale=\"";
stack1 = depth0;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" data-field=\"company_name\">";
stack1 = depth0;
foundHelper = helpers.upCase;
stack2 = foundHelper || depth0.upCase;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "upCase", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</button>\n ";
return buffer;}
function program11(depth0,data,depth1) {
var buffer = "", stack1, stack2;
buffer += "\n <input type=\"text\" name=\"master_information[teaser][";
stack1 = depth0;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this", { hash: {} }); }
buffer += escapeExpression(stack1) + "]\" value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth1.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.master_information);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.teaser_translations);
foundHelper = helpers.translations;
stack2 = foundHelper || depth0.translations;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "translations", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "\" id=\"account_master_information_teaser_";
stack1 = depth0;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" class=\"span10\" style=\"display:none\">\n ";
return buffer;}
function program13(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "\n <button class=\"btn\" data-locale=\"";
stack1 = depth0;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" data-field=\"teaser\">";
stack1 = depth0;
foundHelper = helpers.upCase;
stack2 = foundHelper || depth0.upCase;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "upCase", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</button>\n ";
return buffer;}
function program15(depth0,data,depth1) {
var buffer = "", stack1, stack2;
buffer += "\n <textarea name=\"master_information[description][";
stack1 = depth0;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this", { hash: {} }); }
buffer += escapeExpression(stack1) + "]\" id=\"account_master_information_description_";
stack1 = depth0;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" class=\"span10\" rows=\"6\" style=\"display:none\">";
foundHelper = helpers.account;
stack1 = foundHelper || depth1.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.master_information);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.description_translations);
foundHelper = helpers.translations;
stack2 = foundHelper || depth0.translations;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "translations", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</textarea>\n ";
return buffer;}
function program17(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "\n <button class=\"btn\" data-locale=\"";
stack1 = depth0;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" data-field=\"description\">";
stack1 = depth0;
foundHelper = helpers.upCase;
stack2 = foundHelper || depth0.upCase;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "upCase", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</button>\n ";
return buffer;}
buffer += "<header class=\"subhead\">\n <div class=\"subnav subnav-fixed\">\n <ul class=\"nav nav-pills\">\n <li ><a href=\"#account_info\">Account Information</a></li>\n <li ><a href=\"#w2d_contact_info\">Private Contact Information</a></li>\n <li><a href=\"#business_info\">Business Information [Public]</a></li>\n <li><a href=\"#logo_cover\">Company Logo/Cover Image</a></li>\n <li><a href=\"#locations\">Operating Locations</a></li>\n </ul>\n </div>\n</header>\n<div class=\"page-header\">\n <div class=\"row\">\n <h1>";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1._id);
stack2 = helpers['if'];
tmp1 = self.program(1, program1, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.program(3, program3, data);
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += " ";
stack1 = "models.account";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1);
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.account_name);
stack2 = helpers['if'];
tmp1 = self.program(5, program5, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "</h1>\n </div>\n</div>\n<div class=\"row accounts\">\n <section id=\"account_info\">\n <div class = \"fieldset-header\">\n <h2>Account Information</h2>\n </div>\n <form action=\"\" method=\"post\" enctype=\"multipart/form-data\" name=\"account\" class=\"form accounts\">\n <div class= \"span12\">\n <fieldset>\n <div class=\"row\">\n <div class=\"span7\">\n <div class=\"control-group account_name\">\n <label class=\"control-label\">Account Name</label>\n <div class=\"controls\">\n <input type=\"text\" name=\"account_name\" id=\"account_account_name\" class=\"span4\" value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.account_name);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.account_name", { hash: {} }); }
buffer += escapeExpression(stack1) + "\">\n </div>\n </div>\n <div class=\"control-group company_name\">\n <label class=\"control-label\">Company Display Name</label>\n <div class=\"controls\">\n ";
foundHelper = helpers.locales;
stack1 = foundHelper || depth0.locales;
stack2 = helpers.each;
tmp1 = self.programWithDepth(program7, data, depth0);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n <div class=\"btn-group inline-block translations\" data-toggle=\"buttons-radio\">\n ";
foundHelper = helpers.locales;
stack1 = foundHelper || depth0.locales;
stack2 = helpers.each;
tmp1 = self.program(9, program9, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n </div>\n </div>\n </div>\n </div>\n <div class=\"span5\">\n <div class=\"control-group country\">\n <label class=\"control-label\">Country</label>\n <div class=\"controls\">\n <select id=\"account_country_id\" name=\"country_id\" >\n </select>\n </div>\n </div>\n <div class=\"control-group category\">\n <label class=\"control-label\">Main Business Category</label>\n <div class=\"controls\">\n <select id=\"account_category_id\" name=\"category_id\">\n </select> \n </div>\n </div>\n </div>\n </div>\n </fieldset>\n </div> \n </form>\n </section>\n</div>\n<div class=\"row accounts\">\n <section id=\"w2d_contact_info\">\n <div class = \"fieldset-header\">\n <h2>Private Contact Information</h2>\n <p class=\"help-block\"><small>This information is not displayed to users and will be kept private. It is required to verify your right to manage the place, event and directory listings associated with this account</small></p>\n </div>\n <form action=\"\" method=\"post\" enctype=\"multipart/form-data\" name=\"account\" class=\"form-horizontal accounts\"> \n <div class= \"span12\">\n <div class=\"row\">\n <div class= \"span6\">\n <fieldset>\n <legend>Name and Contacts</legend>\n <div class=\"control-group account membership_detail company_legal_name\">\n <label class=\"control-label\">Legal Name of Company</label>\n <div class=\"controls\">\n <input type=\"text\" name=\"membership_detail[company_legal_name]\" id=\"account_company_legal_name\"\n value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.membership_detail);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.company_legal_name);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.membership_detail.company_legal_name", { hash: {} }); }
buffer += escapeExpression(stack1) + "\">\n </div>\n </div> \n <div class=\"control-group account membership_detail contact\">\n <label class=\"control-label\">Company Contact Name</label>\n <div class=\"controls\">\n <input type=\"text\" name=\"membership_detail[contact][name]\" id=\"account_contact_name\"\n value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.membership_detail);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.contact);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.name);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.membership_detail.contact.name", { hash: {} }); }
buffer += escapeExpression(stack1) + "\">\n </div>\n </div>\n <div class=\"control-group account membership_detail main_tel\">\n <label class=\"control-label\">Company Contact Telephone</label>\n <div class=\"controls\">\n <input type=\"tel\" name=\"membership_detail[contact][main_tel]\" id=\"account_contact_main_tel\" \n value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.membership_detail);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.contact);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.main_tel);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.membership_detail.contact.main_tel", { hash: {} }); }
buffer += escapeExpression(stack1) + "\">\n </div>\n </div>\n <div class=\"control-group account membership_detail contact_hp\">\n <label class=\"control-label\">Company Contact HP</label>\n <div class=\"controls\">\n <input type=\"tel\" name=\"membership_detail[contact][contact_hp]\" id=\"account_contact_contact_hp\"\n value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.membership_detail);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.contact);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.contact_hp);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.membership_detail.contact.contact_hp", { hash: {} }); }
buffer += escapeExpression(stack1) + "\">\n </div>\n </div>\n <div class=\"control-group account membership_detail email\">\n <label class=\"control-label\">Company Contact Email</label>\n <div class=\"controls\">\n <input type=\"email\" name=\"membership_detail[contact][email]\" id=\"account_contact_email\" \n value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.membership_detail);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.contact);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.email);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.membership_detail.contact.email", { hash: {} }); }
buffer += escapeExpression(stack1) + "\">\n </div>\n </div>\n </fieldset>\n </div>\n <div class= \"span6\">\n <fieldset>\n <legend>Company Registered Address</legend>\n <div class=\"control-group account membership_detail address\">\n <label class=\"control-label\">Street Address 1:</label>\n <div class=\"controls\">\n <input type=\"text\" name=\"membership_detail[address][street1]\" id=\"account_address_street1\"\n value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.membership_detail);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.address);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.street1);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.membership_detail.address.street1", { hash: {} }); }
buffer += escapeExpression(stack1) + "\">\n </div>\n </div>\n <div class=\"control-group account membership_detail address\">\n <label class=\"control-label\">Street Address 2:</label>\n <div class=\"controls\">\n <input type=\"text\" name=\"membership_detail[address][street2]\" id=\"account_address_street2\" \n value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.membership_detail);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.address);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.street2);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.membership_detail.address.street2", { hash: {} }); }
buffer += escapeExpression(stack1) + "\">\n </div>\n </div>\n <div class=\"control-group account membership_detail address\">\n <label class=\"control-label\">City/Region:</label>\n <div class=\"controls\">\n <input type=\"text\" name=\"membership_detail[address][city]\" id=\"account_address_city\" \n value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.membership_detail);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.address);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.city);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.membership_detail.address.city", { hash: {} }); }
buffer += escapeExpression(stack1) + "\">\n </div>\n </div>\n <div class=\"control-group account membership_detail address\">\n <label class=\"control-label\">Province/State:</label>\n <div class=\"controls\">\n <input type=\"text\" name=\"membership_detail[address][province]\" id=\"account_address_province\" \n value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.membership_detail);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.address);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.province);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.membership_detail.address.province", { hash: {} }); }
buffer += escapeExpression(stack1) + "\">\n </div>\n </div> \n <div class=\"control-group account membership_detail address\">\n <label class=\"control-label\">Country:</label>\n <div class=\"controls\">\n <input type=\"text\" name=\"membership_detail[address][country]\" id=\"account_address_country\"\n value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.membership_detail);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.address);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.country);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.membership_detail.address.country", { hash: {} }); }
buffer += escapeExpression(stack1) + "\">\n </div>\n </div> \n <div class=\"control-group account membership_detail address\">\n <label class=\"control-label\">Postal Code:</label>\n <div class=\"controls\">\n <input type=\"text\" name=\"membership_detail[address][postal_code]\" id=\"account_address_postal_code\" \n value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.membership_detail);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.address);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.postal_code);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.membership_detail.address.postal_code", { hash: {} }); }
buffer += escapeExpression(stack1) + "\">\n </div>\n </div> \n </fieldset>\n </div>\n </div> \n </div>\n </form>\n </section>\n</div>\n<div class=\"row accounts\">\n <section id=\"business_info\">\n <form action=\"\" method=\"post\" enctype=\"multipart/form-data\" name=\"account\" class=\"form accounts\"> \n <div class = \"fieldset-header\">\n <h2>Business Information [Public]</h2>\n <p class= \"help-block\"><small>This information will be publicly displayed in your place, events, and deals listings - select the language buttons where available to add information in other languages</small></p>\n </div>\n <div class= \"span12\">\n <fieldset>\n <div class=\"control-group account_teaser\">\n <label class=\"control-label\">Business Teaser</label>\n <div class=\"controls\">\n ";
foundHelper = helpers.locales;
stack1 = foundHelper || depth0.locales;
stack2 = helpers.each;
tmp1 = self.programWithDepth(program11, data, depth0);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n <div class=\"btn-group inline-block translations\" data-toggle=\"buttons-radio\">\n ";
foundHelper = helpers.locales;
stack1 = foundHelper || depth0.locales;
stack2 = helpers.each;
tmp1 = self.program(13, program13, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n </div>\n <p class=\"help-block\"><em>Add a short business summary here that you would like included \n with tweets and postings to social media (keep it less than 100 characters)</em></p>\n </div>\n </div>\n </br>\n <div class=\"control-group account_description\">\n <label class=\"control-label\">Business Company/Description</label>\n <div class=\"controls\">\n ";
foundHelper = helpers.locales;
stack1 = foundHelper || depth0.locales;
stack2 = helpers.each;
tmp1 = self.programWithDepth(program15, data, depth0);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n <div class=\"btn-group inline-block translations\" data-toggle=\"buttons-radio\">\n ";
foundHelper = helpers.locales;
stack1 = foundHelper || depth0.locales;
stack2 = helpers.each;
tmp1 = self.program(17, program17, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n </div> \n <p class=\"help-block\"><em>Add a longer description of your company and business here to highlight and promote your services and products</em></p>\n </br>\n </div>\n </div>\n <div class=\"row\">\n <div class= \"span12\">\n <div class=\"row\">\n <div class=\"span6\"> \n <div class=\"control-group account website url\">\n <label class=\"control-label\">Website Address</label>\n <div class=\"controls\">\n <input type=\"url\" name=\"master_information[website_url]\" id=\"account_website_url\" class=\"span4\" value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.master_information);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.website_url);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.master_information.website_url", { hash: {} }); }
buffer += escapeExpression(stack1) + "\">\n </div>\n </div>\n </br>\n <input type=\"hidden\" id=\"master_information_category_id\" name=\"account[master_information][category_id]\">\n <div class=\"control-group subcategory\">\n <label class=\"control-label\">Business SubCategory</label>\n <div class=\"controls\">\n <select id=\"master_info_subcategory_id\" name=\"master_information[subcategory_id\">\n </select> \n </div>\n <p class=\"help-block\"><em>select a subcategory for this business/entity - if blank please ensure a category is selected on the first tab of this form</em></p>\n </div>\n </br>\n </div>\n <div class=\"span6\"> \n <div class=\"control-group account info-source\">\n <label class=\"control-label\">Information Source</label>\n <div class=\"controls\">\n <input type=\"text\" name=\"master_information[info_source]\" id=\"account_website_url\" class=\"span4\" value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.master_information);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.info_source);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.master_information.info_source", { hash: {} }); }
buffer += escapeExpression(stack1) + "\">\n </div>\n <p class=\"help-block\"><em>Please provide a reference/link for information added to this account by admin</em></p> \n </div>\n </br>\n <div class=\"control-group recommended_for\">\n <div class =\"controls\">\n <label>Recommended For:</label>\n <label class=\"checkbox inline\">\n <input type=\"checkbox\" name=\"account[master_information][recommended_for_tag][expat]\" value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.master_information);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.recommended_for_tag);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.expat);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.master_information.recommended_for_tag.expat", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.master_information);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.recommended_for_tag);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.expat);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">\n Expatriates\n </label>\n <label class=\"checkbox inline\">\n <input type=\"checkbox\" name=\"account[master_information][recommended_for_tag][tourist]\" value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.master_information);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.recommended_for_tag);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.tourist);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.master_information.recommended_for_tag.tourist", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.master_information);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.recommended_for_tag);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.tourist);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">\n Tourists\n </label>\n <label class=\"checkbox inline\">\n <input type=\"checkbox\" name=\"account[master_information][recommended_for_tag][business]\" value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.master_information);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.recommended_for_tag);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.business);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.master_information.recommended_for_tag.business", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" ";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.master_information);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.recommended_for_tag);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.business);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + ">\n Business\n </label>\n <label class=\"checkbox inline\">\n <input type=\"checkbox\" name=\"account[master_information][recommended_for_tag][kids]\" value=\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.master_information);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.recommended_for_tag);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.kids);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "account.master_information.recommended_for_tag.kids", { hash: {} }); }
buffer += escapeExpression(stack1) + "\"";
foundHelper = helpers.account;
stack1 = foundHelper || depth0.account;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.master_information);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.recommended_for_tag);
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.kids);
foundHelper = helpers.checkEd;
stack2 = foundHelper || depth0.checkEd;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "checkEd", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + " >\n Kids\n </label>\n </div>\n </div>\n </div>\n </div>\n </div>\n </fieldset>\n </div>\n </form>\n </section>\n</div>\n<div class=\"row accounts\">\n <section id=\"logo_cover\">\n <div class = \"fieldset-header\">\n <h2>Company Logo/Cover Image</h2>\n </div>\n <div class=\"span12\">\n <div class = \"control-group\" id=\"media\" >\n </div>\n </div>\n </section>\n</div>\n<div class=\"row accounts\">\n <div class=\"existing-locations\">\n <section id=\"locations\">\n\n </section>\n <section class=\"popin-form\">\n <div id=\"add-location\">\n </div>\n </section>\n <div>\n</div>\n<div class=\"row\">\n <div class=\"span12\">\n <form action=\"\" method=\"put\" enctype=\"multipart/form-data\" class=\"form-vertical accounts container\" name=\"account\">\n <div class=\"form-actions\">\n <div class=\"span2 pull-right \">\n <button class=\"btn btn-primary update\" name=\"account\">Save</button>\n <button class=\"btn btn-danger cancel\" name=\"account\">Cancel</button>\n </div>\n </div>\n </form>\n </div>\n</div>\n";
return buffer;});
return HandlebarsTemplates["templates/admin/accounts/edit"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/accounts/index"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/accounts/index"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
buffer += "<div class=\"page-header\">\n <h1>";
stack1 = "models.accounts";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</h1>\n <div class=\"toolbar\">\n <a href=\"\" class=\"btn new-account\">";
stack1 = "actions.new_account";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n <div style=\"float:right;\">\n <input type=\"text\" placeholder=\"";
stack1 = "actions.search";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "\" class=\"search\" value=\"";
foundHelper = helpers.keywords;
stack1 = foundHelper || depth0.keywords;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "keywords", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" />\n </div>\n </div>\n</div>\n\n<div class=\"accounts\">\n <table class=\"table table-striped table-bordered table-condensed\">\n <thead>\n <tr>\n <th>Account Name</th>\n <th>Company Name</th>\n <th>Business Category</th>\n <th>Actions</th>\n </tr>\n </thead>\n <tbody>\n </tbody>\n </table>\n</div>\n";
foundHelper = helpers.pagination;
stack1 = foundHelper || depth0.pagination;
foundHelper = helpers.Pager;
stack2 = foundHelper || depth0.Pager;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "Pager", stack1, { hash: {} }); }
else { stack1 = stack2; }
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n\n\n\n";
return buffer;});
return HandlebarsTemplates["templates/admin/accounts/index"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/activities/activity"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/activities/activity"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, tmp1, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
function program1(depth0,data,depth1) {
var buffer = "", stack1, stack2;
buffer += "\n <li class = \"activity_category \">\n <span> ";
stack1 = depth0.name;
foundHelper = helpers.localize;
stack2 = foundHelper || depth0.localize;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "localize", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</span>\n <a href=\"\" class=\"btn btn-mini btn-danger pull-right remove\" data-id=\"";
foundHelper = helpers.activity;
stack1 = foundHelper || depth1.activity;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1._id);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "...activity._id", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" data-category_id=\"";
stack1 = depth0.id;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this.id", { hash: {} }); }
buffer += escapeExpression(stack1) + "\">\n <i class=\"icon-minus icon-white\"></i></a> \n </li>\n ";
return buffer;}
buffer += "<td class=\"span5\">\n <h3>";
foundHelper = helpers.activity;
stack1 = foundHelper || depth0.activity;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.name);
foundHelper = helpers.localize;
stack2 = foundHelper || depth0.localize;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "localize", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</h3>\n <div class=\"btn-group actions inline-block\" data-toggle=\"buttons-radio\">\n <a href=\"#\" class=\"btn btn-mini assign\" data-id=\"";
foundHelper = helpers.activity;
stack1 = foundHelper || depth0.activity;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1._id);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "activity._id", { hash: {} }); }
buffer += escapeExpression(stack1) + "\">";
stack1 = "actions.assign_category";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n <a href=\"#\" class=\"btn btn-mini edit\">";
stack1 = "actions.edit";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n <a href=\"#\" class=\"btn btn-mini delete\">";
stack1 = "actions.delete";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n </div> \n</td>\n<td class = \"span5\">\n<ul class = \"unstyled span5 activity-category\">\n ";
foundHelper = helpers.activity;
stack1 = foundHelper || depth0.activity;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.categories_assigned);
stack2 = helpers.each;
tmp1 = self.programWithDepth(program1, data, depth0);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n</ul>\n<ul class=\"category-assignment span4 block\" id= \"activity_";
foundHelper = helpers.activity;
stack1 = foundHelper || depth0.activity;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1._id);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "activity._id", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" style = \"display:none\"></ul>\n</td>\n";
return buffer;});
return HandlebarsTemplates["templates/admin/activities/activity"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/activities/assign"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/activities/assign"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, tmp1, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
function program1(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "\n <option value=";
foundHelper = helpers.category;
stack1 = foundHelper || depth0.category;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1._id);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "category._id", { hash: {} }); }
buffer += escapeExpression(stack1) + ">";
foundHelper = helpers.category;
stack1 = foundHelper || depth0.category;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.name);
foundHelper = helpers.localize;
stack2 = foundHelper || depth0.localize;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "localize", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</option>\n ";
return buffer;}
buffer += "<div class=\"modal-header\">\n <a class=\"close\" data-dismiss=\"modal\">×</a>\n </div>\n<form action=\"\" method=\"put\" class=\"form-inline\">\n <fieldset>\n <div class=\"control-group name\">\n <div class=\"controls\">\n <select name=\"activity_categories\" id = \"activity_categories_";
foundHelper = helpers.activity;
stack1 = foundHelper || depth0.activity;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1._id);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "activity._id", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" class=\"update\">\n <option>Select Category to Add</option>\n ";
foundHelper = helpers.categories;
stack1 = foundHelper || depth0.categories;
stack2 = helpers.each;
tmp1 = self.program(1, program1, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n </select>\n </div>\n </div>\n </fieldset>\n</form>\n";
return buffer;});
return HandlebarsTemplates["templates/admin/activities/assign"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/activities/edit"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/activities/edit"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, tmp1, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
function program1(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "\n ";
stack1 = "actions.edit_activity";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "\n ";
return buffer;}
function program3(depth0,data) {
var buffer = "", stack1, stack2;
buffer += " \n ";
stack1 = "actions.new_activity";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "\n ";
return buffer;}
function program5(depth0,data,depth1) {
var buffer = "", stack1, stack2;
buffer += "\n <input type=\"text\" name=\"activity_name\" value=\"";
foundHelper = helpers.activity;
stack1 = foundHelper || depth1.activity;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.name);
foundHelper = helpers.translations;
stack2 = foundHelper || depth0.translations;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "translations", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "\" id=\"activity_name_";
stack1 = depth0;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" class=\"span6\" style=\"display:none\">\n ";
return buffer;}
function program7(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "\n <button class=\"btn\" data-locale=\"";
stack1 = depth0;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" data-field=\"name\">";
stack1 = depth0;
foundHelper = helpers.upCase;
stack2 = foundHelper || depth0.upCase;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "upCase", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</button>\n ";
return buffer;}
buffer += "<div class=\"page-header\">\n <h1>\n ";
foundHelper = helpers.activity;
stack1 = foundHelper || depth0.activity;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.id);
stack2 = helpers['if'];
tmp1 = self.program(1, program1, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.program(3, program3, data);
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n </h1>\n</div>\n\n<form action=\"\" method=\"post\" class=\"form-horizontal\">\n <fieldset>\n <div class=\"control-group name\">\n <label class=\"control-label\">";
stack1 = "category_attributes.name";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</label>\n <div class=\"controls\">\n ";
foundHelper = helpers.locales;
stack1 = foundHelper || depth0.locales;
stack2 = helpers.each;
tmp1 = self.programWithDepth(program5, data, depth0);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n <div class=\"btn-group inline-block translations\" data-toggle=\"buttons-radio\">\n ";
foundHelper = helpers.locales;
stack1 = foundHelper || depth0.locales;
stack2 = helpers.each;
tmp1 = self.program(7, program7, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n </div>\n </div>\n </div>\n <div class=\"form-actions\">\n <div class=\"row\">\n <div class=\"span3\">\n <button class=\"btn btn-primary update\">";
stack1 = "actions.save";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</button>\n <button class=\"btn btn-danger cancel\">";
stack1 = "actions.cancel";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</button>\n </div>\n </div>\n </div>\n </fieldset>\n</form>\n";
return buffer;});
return HandlebarsTemplates["templates/admin/activities/edit"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/activities/index"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/activities/index"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
buffer += "<div class=\"page-header\">\n <h1>";
stack1 = "models.activities";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</h1>\n <div class=\"toolbar\">\n <a href=\"\"/admin/activities/new\"\" class=\"btn new-activity\">";
stack1 = "actions.new_activity";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n </div>\n</div>\n\n<div class=\"categories\">\n <table class=\"table table-striped table-bordered table-condensed\">\n <thead>\n <tr>\n <th>";
stack1 = "category_attributes.name";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</th>\n <th>";
stack1 = "category_attributes.categories_assigned";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</th>\n </tr>\n </thead>\n <tbody>\n </tbody>\n </table>\n</div>\n";
return buffer;});
return HandlebarsTemplates["templates/admin/activities/index"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/categories/category"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/categories/category"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, tmp1, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
function program1(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "\n <li> <span> ";
stack1 = depth0.name;
foundHelper = helpers.localize;
stack2 = foundHelper || depth0.localize;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "localize", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</span></li>\n ";
return buffer;}
buffer += "<td class=\"span4\">\n <h3>";
foundHelper = helpers.category;
stack1 = foundHelper || depth0.category;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.name);
foundHelper = helpers.localize;
stack2 = foundHelper || depth0.localize;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "localize", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</h3>\n <div class=\"btn-group actions inline-block\" data-toggle=\"buttons-radio\">\n <a href=\"\" class=\"btn btn-mini new-subcategory\">";
stack1 = "actions.new";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n <a href=\"\" class=\"btn btn-mini edit\">";
stack1 = "actions.edit";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n <a href=\"\" class=\"btn btn-mini delete\">";
stack1 = "actions.delete";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n </div> \n</td>\n<td class=\"subcategories span5\">\n</td>\n<td class=\"span3\">\n <ul class = \"unstyled span4 category-activity\">\n ";
foundHelper = helpers.category;
stack1 = foundHelper || depth0.category;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.activities_assigned);
stack2 = helpers.each;
tmp1 = self.program(1, program1, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n </ul>\n</td>\n \n";
return buffer;});
return HandlebarsTemplates["templates/admin/categories/category"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/categories/edit"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/categories/edit"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, tmp1, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
function program1(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "\n ";
stack1 = "actions.edit_category";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "\n ";
return buffer;}
function program3(depth0,data) {
var buffer = "", stack1, stack2;
buffer += " \n ";
stack1 = "actions.new_category";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "\n ";
return buffer;}
function program5(depth0,data,depth1) {
var buffer = "", stack1, stack2;
buffer += "\n <input type=\"text\" name=\"category_name\" value=\"";
foundHelper = helpers.category;
stack1 = foundHelper || depth1.category;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.name);
foundHelper = helpers.translations;
stack2 = foundHelper || depth0.translations;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "translations", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "\" id=\"category_name_";
stack1 = depth0;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" class=\"span6\" style=\"display:none\">\n ";
return buffer;}
function program7(depth0,data) {
var buffer = "", stack1, stack2;
buffer += "\n <button class=\"btn\" data-locale=\"";
stack1 = depth0;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" data-field=\"name\">";
stack1 = depth0;
foundHelper = helpers.upCase;
stack2 = foundHelper || depth0.upCase;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "upCase", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</button>\n ";
return buffer;}
buffer += "<div class=\"page-header\">\n <h1>\n ";
foundHelper = helpers.category;
stack1 = foundHelper || depth0.category;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1._id);
stack2 = helpers['if'];
tmp1 = self.program(1, program1, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.program(3, program3, data);
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n </h1>\n</div>\n\n<form action=\"\" method=\"post\" class=\"form-horizontal\">\n <fieldset>\n <div class=\"control-group name\">\n <label class=\"control-label\">";
stack1 = "category_attributes.name";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</label>\n <div class=\"controls\">\n ";
foundHelper = helpers.locales;
stack1 = foundHelper || depth0.locales;
stack2 = helpers.each;
tmp1 = self.programWithDepth(program5, data, depth0);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n <div class=\"btn-group inline-block translations\" data-toggle=\"buttons-radio\">\n ";
foundHelper = helpers.locales;
stack1 = foundHelper || depth0.locales;
stack2 = helpers.each;
tmp1 = self.program(7, program7, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n </div>\n </div>\n </div>\n \n <div class=\"control-group description\">\n <label class=\"control-label\">";
stack1 = "category_attributes.description";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</label>\n <div class=\"controls\">\n <textarea name=\"category_description\" id=\"category_description\" class=\"span6\">";
foundHelper = helpers.category;
stack1 = foundHelper || depth0.category;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.description);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "category.description", { hash: {} }); }
buffer += escapeExpression(stack1) + "</textarea>\n </div>\n </div>\n \n <div class=\"form-actions\">\n <div class=\"row\">\n <div class=\"span3\">\n <button class=\"btn btn-primary update\">";
stack1 = "actions.save";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</button>\n <button class=\"btn btn-danger cancel\">";
stack1 = "actions.cancel";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</button>\n </div>\n </div>\n </div>\n </fieldset>\n</form>\n";
return buffer;});
return HandlebarsTemplates["templates/admin/categories/edit"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/categories/index"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/categories/index"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
buffer += "<div class=\"page-header\">\n <h1>";
stack1 = "models.categories";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</h1>\n <div class=\"toolbar\">\n <a href=\"/admin/categories/new\" class=\"btn new-category\">";
stack1 = "actions.new_category";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n </div>\n</div>\n\n<div class=\"categories\">\n <table class=\"table table-striped table-bordered table-condensed\">\n <thead>\n <tr>\n <th class=\"span4\">";
stack1 = "category_attributes.name";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</th>\n <th class=\"span5\">";
stack1 = "category_attributes.subcategories";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</th>\n <th class=\"span3\">";
stack1 = "category_attributes.activities_assigned";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</th>\n </tr>\n </thead>\n <tbody>\n </tbody>\n </table>\n</div>\n";
return buffer;});
return HandlebarsTemplates["templates/admin/categories/index"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/categories/subcategory"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/categories/subcategory"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
buffer += "<h5 class=\"inline-block span3\">";
foundHelper = helpers.category;
stack1 = foundHelper || depth0.category;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.name);
foundHelper = helpers.localize;
stack2 = foundHelper || depth0.localize;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "localize", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</h5>\n<div class=\"btn-group actions inline-block pull-right span2\" data-toggle=\"buttons-radio\">\n <a href=\"\" class=\"btn btn-mini edit\">";
stack1 = "actions.edit";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n <a href=\"\" class=\"btn btn-mini delete\">";
stack1 = "actions.delete";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n</div> \n";
return buffer;});
return HandlebarsTemplates["templates/admin/categories/subcategory"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/destinations/area"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/destinations/area"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
buffer += "<h5 class=\"inline-block\">";
foundHelper = helpers.destination;
stack1 = foundHelper || depth0.destination;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.name);
foundHelper = helpers.localize;
stack2 = foundHelper || depth0.localize;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "localize", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</h5>\n<div class=\"btn-group actions inline-block pull-right\" data-toggle=\"buttons-radio\">\n <a href=\"\" class=\"btn btn-mini edit\">";
stack1 = "actions.edit";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n <a href=\"\" class=\"btn btn-mini delete\">";
stack1 = "actions.delete";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n</div>\n";
return buffer;});
return HandlebarsTemplates["templates/admin/destinations/area"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/destinations/country"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/destinations/country"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
buffer += "<td colspan=\"2\">\n <h3>";
foundHelper = helpers.destination;
stack1 = foundHelper || depth0.destination;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.name);
foundHelper = helpers.localize;
stack2 = foundHelper || depth0.localize;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "localize", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</h3>\n <div class=\"btn-group actions inline-block\" data-toggle=\"buttons-radio\">\n <a href=\"\" class=\"btn btn-mini new-region\">";
stack1 = "actions.new_region";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n <a href=\"\" class=\"btn btn-mini edit\">";
stack1 = "actions.edit";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n <a href=\"\" class=\"btn btn-mini delete\">";
stack1 = "actions.delete";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n </div> \n</td>\n";
return buffer;});
return HandlebarsTemplates["templates/admin/destinations/country"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/destinations/edit"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/destinations/edit"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, tmp1, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
function program1(depth0,data,depth1) {
var buffer = "", stack1, stack2;
buffer += "\n ";
stack1 = "actions.edit";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + " ";
foundHelper = helpers.type;
stack1 = foundHelper || depth1.type;
foundHelper = helpers.destHeader;
stack2 = foundHelper || depth0.destHeader;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "destHeader", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "\n ";
return buffer;}
function program3(depth0,data,depth1) {
var buffer = "", stack1, stack2;
buffer += " \n ";
stack1 = "actions.new";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + " ";
foundHelper = helpers.type;
stack1 = foundHelper || depth1.type;
foundHelper = helpers.destHeader;
stack2 = foundHelper || depth0.destHeader;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "destHeader", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "\n ";
return buffer;}
function program5(depth0,data,depth1) {
var buffer = "", stack1, stack2;
buffer += "\n <input type=\"text\" name=\"destination[name]\" value=\"";
foundHelper = helpers.destination;
stack1 = foundHelper || depth1.destination;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.name);
foundHelper = helpers.localize;
stack2 = foundHelper || depth0.localize;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "localize", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "\" id=\"destination_name_";
stack1 = depth0;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" class=\"span4\" style=\"display:none\">\n ";
return buffer;}
function program7(depth0,data) {
var buffer = "", stack1, stack2;
buffer += " \n <button class=\"btn\" data-locale=\"";
stack1 = depth0;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" data-field=\"name\">";
stack1 = depth0;
foundHelper = helpers.upCase;
stack2 = foundHelper || depth0.upCase;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "upCase", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</button>\n ";
return buffer;}
buffer += " <div class=\"page-header\">\n <h1>\n ";
foundHelper = helpers.destination;
stack1 = foundHelper || depth0.destination;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1._id);
stack2 = helpers['if'];
tmp1 = self.programWithDepth(program1, data, depth0);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.programWithDepth(program3, data, depth0);
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n </h1>\n</div>\n<div class=\"row\">\n <div class=\"span12\">\n <form action=\"\" method=\"post\" class=\"form-horizontal span10 offset1\">\n <fieldset>\n <div class=\"control-group name\">\n <label class=\"control-label\">";
stack1 = "category_attributes.name";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</label>\n <div class=\"controls\">\n ";
foundHelper = helpers.locales;
stack1 = foundHelper || depth0.locales;
stack2 = helpers.each;
tmp1 = self.programWithDepth(program5, data, depth0);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n <div class=\"control-group btn-group inline translations span2 pull-right\" data-toggle=\"buttons-radio\">\n ";
foundHelper = helpers.locales;
stack1 = foundHelper || depth0.locales;
stack2 = helpers.each;
tmp1 = self.program(7, program7, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n </div>\n </fieldset>\n <div class = \"row\">\n <div class=\"span8\"> \n <div class=\"map-holder\">\n </div>\n <div class=\"map-caption\">\n <p>Drag the marker, pan the map, or change the zoom to set the default map for the defined destination.</p>\n </div> \n </div>\n </div>\n <div class=\"controls\" style= \"display:none\">\n <input name=\"destination_latitude\" id=\"destination_latitude\" value=\"";
foundHelper = helpers.destination;
stack1 = foundHelper || depth0.destination;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.lat);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "destination.lat", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" type=\"hidden\">\n <input name=\"destination_longitude\" id=\"destination_longitude\" value=\"";
foundHelper = helpers.destination;
stack1 = foundHelper || depth0.destination;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.lng);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "destination.lng", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" type=\"hidden\">\n <input name=\"destination_zoom\" id=\"destination_zoom\" value=\"";
foundHelper = helpers.destination;
stack1 = foundHelper || depth0.destination;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.zoom);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "destination.zoom", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" type=\"hidden\">\n <input name=\"destination_swlat\" id=\"destination_swlat\" value=\"";
foundHelper = helpers.destination;
stack1 = foundHelper || depth0.destination;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.swlat);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "destination.swlat", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" type=\"hidden\">\n <input name=\"destination_swlng\" id=\"destination_swlng\" value=\"";
foundHelper = helpers.destination;
stack1 = foundHelper || depth0.destination;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.swlng);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "destination.swlng", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" type=\"hidden\">\n <input name=\"destination_nelat\" id=\"destination_nelat\" value=\"";
foundHelper = helpers.destination;
stack1 = foundHelper || depth0.destination;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.nelat);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "destination.nelat", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" type=\"hidden\">\n <input name=\"destination_nelng\" id=\"destination_nelng\" value=\"";
foundHelper = helpers.destination;
stack1 = foundHelper || depth0.destination;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.nelng);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "destination.nelng", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" type=\"hidden\">\n </div>\n <div class=\"form-actions\">\n <div class=\"row\">\n <div class=\"span3\">\n <button class=\"btn btn-primary update\">";
stack1 = "actions.save";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</button>\n <button class=\"btn btn-danger cancel\">";
stack1 = "actions.cancel";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</button>\n </div>\n </div>\n </div>\n \n </form>\n </div>\n</div>\n";
return buffer;});
return HandlebarsTemplates["templates/admin/destinations/edit"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/destinations/index"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/destinations/index"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
buffer += "<div class=\"page-header\">\n <h1 class=\"inline span6\">";
stack1 = "models.destinations";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</h1>\n <a href=\"/admin/destinations/new\" class=\"btn new-destination pull-right\">";
stack1 = "actions.new_country";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n</div>\n<table class=\"table table-striped table-bordered table-condensed\">\n <tbody>\n </tbody>\n</table>\n\n";
return buffer;});
return HandlebarsTemplates["templates/admin/destinations/index"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/destinations/region"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/destinations/region"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
buffer += "<td class=\"region span6\">\n <h5 class=\"inline-block\">";
foundHelper = helpers.destination;
stack1 = foundHelper || depth0.destination;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.name);
foundHelper = helpers.localize;
stack2 = foundHelper || depth0.localize;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "localize", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</h5>\n <div class=\"btn-group actions inline-block pull-right\" data-toggle=\"buttons-radio\">\n <a href=\"\" class=\"btn btn-mini new-area\">";
stack1 = "actions.new_area";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n <a href=\"\" class=\"btn btn-mini edit\">";
stack1 = "actions.edit";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n <a href=\"\" class=\"btn btn-mini delete\">";
stack1 = "actions.delete";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</a>\n </div>\n</td>\n<td class=\"areas span6\"> \n</td>\n";
return buffer;});
return HandlebarsTemplates["templates/admin/destinations/region"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/media/fileinput"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/media/fileinput"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, foundHelper, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
buffer += "<label class=\"control-label\">";
foundHelper = helpers.text;
stack1 = foundHelper || depth0.text;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "text", { hash: {} }); }
buffer += escapeExpression(stack1) + "</label>\n<input type=\"";
foundHelper = helpers.input_type;
stack1 = foundHelper || depth0.input_type;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "input_type", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" name=\"";
foundHelper = helpers.name;
stack1 = foundHelper || depth0.name;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "name", { hash: {} }); }
buffer += escapeExpression(stack1) + "\">\n";
return buffer;});
return HandlebarsTemplates["templates/admin/media/fileinput"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/media/imageitem"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/media/imageitem"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, foundHelper, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
buffer += "</br>\n<li class=\"btn-group\">\n <button class=\".btn-mini danger delete-image\" name=\"photo['delete']\" type=\"button\">\n <a href=\"#\" class=\".delete-image\">Delete</a>\n </button>\n <button class=\".btn-mini crop crop-image image\" name= \"photo[crop]\" type=\"button\">\n <a href=\"#\" class=\".crop-image\">Crop</a>\n </button>\n <button class=\".btn-mini update-image image\" name= \"photo[update]\" type=\"button\">\n <a href=\"#\" class=\".update-image\">Update</a>\n </button>\n</li> \n</br>\n<div class=\"control-group image-edit\" id=\"image-panel\" style=\"display:none\">\n<li class=\"control-group image-edit\"> \n <img src=\"";
foundHelper = helpers.photo;
stack1 = foundHelper || depth0.photo;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.image_url);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "photo.image_url", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" id=\"cropbox\" class=\"image-edit\">\n <input type=\"hidden\" name=\"photo['crop_x']\" value= \"";
foundHelper = helpers.photo;
stack1 = foundHelper || depth0.photo;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.crop_x);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "photo.crop_x", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" id = \"crop_x\">\n <input type=\"hidden\" name=\"photo['crop_y']\" value= \"";
foundHelper = helpers.photo;
stack1 = foundHelper || depth0.photo;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.crop_y);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "photo.crop_y", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" id = \"crop_y\">\n <input type=\"hidden\" name=\"photo['crop_h']\" value= \"";
foundHelper = helpers.photo;
stack1 = foundHelper || depth0.photo;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.crop_h);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "photo.crop_h", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" id = \"crop_h\">\n <input type=\"hidden\" name=\"photo['crop_w']\" value= \"";
foundHelper = helpers.photo;
stack1 = foundHelper || depth0.photo;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.crop_w);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "photo.crop_w", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" id = \"crop_w\">\n </li>\n<li class=\"control-group image-edit\">\n <h4>Preview</h4>\n <div style=\"width:180px; height:120px; overflow:hidden\">\n <img src=\"";
foundHelper = helpers.photo;
stack1 = foundHelper || depth0.photo;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.image_url);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "photo.image_url", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" id=\"preview\" class= \"image-edit\">\n </div>\n</li>\n</div>\n";
return buffer;});
return HandlebarsTemplates["templates/admin/media/imageitem"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/media/mediapanel"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/media/mediapanel"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, tmp1, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
function program1(depth0,data) {
var buffer = "", stack1;
buffer += "\n <img src = \"";
stack1 = depth0.crop_url;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "this.crop_url", { hash: {} }); }
buffer += escapeExpression(stack1) + "\" id= \"current\" style=\"width:180px; height:120px; overflow:hidden\">\n ";
return buffer;}
buffer += " <p><strong>Edit the image</strong></p>\n <ul id=\"current-image\" class= \"unstyled\">\n <div class = \"control-group image\">\n ";
stack1 = depth0.crop_url;
stack2 = helpers['if'];
tmp1 = self.program(1, program1, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n </div>\n </ul>\n";
return buffer;});
return HandlebarsTemplates["templates/admin/media/mediapanel"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/media/uploadpanel"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/media/uploadpanel"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var foundHelper, self=this;
return "<legend>Company Logo/Cover Image</legend>\n<p><strong>Choose a file to upload or input a url for the image</strong></p>\n<div class=\"control-group account master_info cover_image\"> \n <ul id=\"media-upload\" class= \"unstyled\">\n </ul>\n <ul id=\"upload-inputs\" class= \"unstyled\">\n </ul>\n</div>\n";});
return HandlebarsTemplates["templates/admin/media/uploadpanel"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/optime/operating_time"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/optime/operating_time"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
buffer += "<div class= \"control-group\" id=\"operating-times\">\n \n</div>\n<div class= \"control-group inline-block operating-times\" id=\"select-operating-times\"> \n <label for=\"from_day\">";
stack1 = "times.from_day";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "\n <select name=\"location[operating_time][from_day]\" id=\"widget-from-day\">\n ";
foundHelper = helpers.I18nDays;
stack1 = foundHelper || depth0.I18nDays;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "I18nDays", { hash: {} }); }
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n </select>\n </label>\n <label for=\"from_day\">";
stack1 = "times.to_day";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "\n <select name=\"location[operating_time][to_day]\" id= \"widget-to-day\">\n ";
foundHelper = helpers.I18nDays;
stack1 = foundHelper || depth0.I18nDays;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "I18nDays", { hash: {} }); }
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n </select>\n </label>\n <label for=\"from_time\">";
stack1 = "times.from_time";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "\n <input type=\"text\" name=\"from_time\" id=\"widget-from-time\" autocomplete=\"OFF\" size=\"10\" class=\"span1\">\n </label>\n <label for=\"to_time\">";
stack1 = "times.to_time";
foundHelper = helpers.I18n;
stack2 = foundHelper || depth0.I18n;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18n", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "\n <input type=\"text\" name=\"to_time\" id=\"widget-to-time\" autocomplete=\"OFF\" size=\"10\" class=\"span1\">\n </label>\n <a class=\"btn btn-mini add-time btn-primary\"><i class=\"icon-plus\"></i></a>\n</div>\n";
return buffer;});
return HandlebarsTemplates["templates/admin/optime/operating_time"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/optime/operating_time_row"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/optime/operating_time_row"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, stack2, foundHelper, tmp1, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;
function program1(depth0,data) {
var buffer = "", stack1;
buffer += "\n <span class=\"op-time\">";
foundHelper = helpers.operating_time;
stack1 = foundHelper || depth0.operating_time;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.from_time);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "operating_time.from_time", { hash: {} }); }
buffer += escapeExpression(stack1) + " - ";
foundHelper = helpers.operating_time;
stack1 = foundHelper || depth0.operating_time;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.to_time);
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "operating_time.to_time", { hash: {} }); }
buffer += escapeExpression(stack1) + "</span>\n ";
return buffer;}
buffer += "<div class = \"open-times span6 block\" >\n <span class=\"op-day\">";
foundHelper = helpers.operating_time;
stack1 = foundHelper || depth0.operating_time;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.from_day);
foundHelper = helpers.I18nDayFormat;
stack2 = foundHelper || depth0.I18nDayFormat;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18nDayFormat", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "-";
foundHelper = helpers.operating_time;
stack1 = foundHelper || depth0.operating_time;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.to_day);
foundHelper = helpers.I18nDayFormat;
stack2 = foundHelper || depth0.I18nDayFormat;
if(typeof stack2 === functionType) { stack1 = stack2.call(depth0, stack1, { hash: {} }); }
else if(stack2=== undef) { stack1 = helperMissing.call(depth0, "I18nDayFormat", stack1, { hash: {} }); }
else { stack1 = stack2; }
buffer += escapeExpression(stack1) + "</span>\n ";
foundHelper = helpers.operating_time;
stack1 = foundHelper || depth0.operating_time;
stack1 = (stack1 === null || stack1 === undefined || stack1 === false ? stack1 : stack1.from_time);
stack2 = helpers['if'];
tmp1 = self.program(1, program1, data);
tmp1.hash = {};
tmp1.fn = tmp1;
tmp1.inverse = self.noop;
stack1 = stack2.call(depth0, stack1, tmp1);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\n <a class=\"btn btn-mini delete-time inline-block\" data-index=\"";
foundHelper = helpers.tindex;
stack1 = foundHelper || depth0.tindex;
if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "tindex", { hash: {} }); }
buffer += escapeExpression(stack1) + "\"><i class=\"icon-trash\"></i></a>\n</div>\n";
return buffer;});
return HandlebarsTemplates["templates/admin/optime/operating_time_row"];
}).call(this);;
}).call(this);
(function() {
this.JST || (this.JST = {});
this.JST["templates/admin/usersession/sign_in"] = (function() {
this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
this.HandlebarsTemplates["templates/admin/usersession/sign_in"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var foundHelper, self=this;
return "<div class=\"page-header\">\n <h1>\n Sign In\n </h1>\n</div>\n\n<form action=\"\" method=\"post\" class=\"form-horizontal\">\n <fieldset>\n <div class=\"control-group name\">\n <label class=\"control-label\">Name</label>\n <div class=\"controls\">\n <input type=\"text\" name=\"user[email]\" id=\"email\" class=\"span6\">\n </div>\n </div>\n </div>\n \n <div class=\"control-group description\">\n <label class=\"control-label\">Password</label>\n <div class=\"controls\">\n <textarea name=\"user[password]\" id=\"password\" class=\"span6\"></textarea>\n </div>\n </div>\n \n <div class=\"form-actions\">\n <div class=\"row\">\n <div class=\"span2\">\n <button class=\"btn btn-primary submit\">Submit</button>\n <button class=\"btn btn-danger cancel\">Cancel</button>\n </div>\n </div>\n </div>\n </fieldset>\n</form>\n";});
return HandlebarsTemplates["templates/admin/usersession/sign_in"];
}).call(this);;
}).call(this);
(function() {
AdminApp.AccountView = Backbone.View.extend({
tagName: "tr",
events: {
"click .edit": "editAccount",
"click .delete": "deleteAccount"
},
template: JST["templates/admin/accounts/account"],
initialize: function(options) {
return _.bindAll(this, "render");
},
render: function() {
var account, category, country, data;
data = {};
category = {
category: this.model.attributes.category
};
country = {
country: this.model.attributes.country
};
data['category'] = this.model.attributes.category;
data['country'] = this.model.attributes.country;
account = $.extend(this.model.toJSON(), data);
this.$el.html(this.template(account));
return this;
},
editAccount: function(ev) {
ev.preventDefault();
this.parent.leave();
return AdminApp.accountsRouter.navigate("/admin/accounts/" + this.model.id + "/edit", {
trigger: true
});
},
deleteAccount: function(ev) {
ev.preventDefault();
if (confirm("Are you sure?")) {
return this.model.destroy();
}
}
});
}).call(this);
(function() {
AdminApp.BranchView = Support.CompositeView.extend({
events: {
"click .edit-location": "editLocation",
"click .delete-location": "deleteLocation"
},
template: JST["templates/admin/accounts/branch"],
initialize: function(options) {
this.parent = options.parent;
this.config = options.config;
this.model = options.model;
this.destinations = options.destinations;
_.bindAll(this, "render");
this.config.on("change:locale", this.render, this);
this.model.on("destroy", this.remove, this);
return this.model.on("change", this.render, this);
},
render: function() {
var context, locales;
$(this.el).empty();
locales = {
locales: I18n.available_locales
};
debug("Branch Render");
context = $.extend(this.model.toJSON(), locales);
debug(context);
$(this.el).html(this.template(context));
return this;
},
remove: function() {
return $(this.el).remove();
},
renderMap: function() {
var lat, latlng, lng, map, mapOptions, marker, zoom, _ref;
zoom = (_ref = this.model.get('zoom')) != null ? _ref : 10;
if (!(this.model.get('geo') != null) && this.model.get('country')) {
if (this.model.get('country')['_id'] != null) {
lat = this.model.get('country')['lat'];
lng = this.model.get('country')['lng'];
}
if ((this.model.get('region') != null) && (this.model.get('region')['_id'] != null)) {
lat = this.model.get('region')['lat'];
lng = this.model.get('region')['lng'];
}
if ((this.model.get('area') != null) && (this.model.get('area')['_id'] != null)) {
lat = this.model.get('area')['lat'];
lng = this.model.get('area')['lng'];
}
}
latlng = new google.maps.LatLng(lat, lng);
mapOptions = {
streetViewControl: false,
mapTypeControl: false,
mapTypeControlOptions: {
position: "TOP_RIGHT"
},
overviewMapControl: false,
zoom: zoom,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($(this.el).find(".small-map").get(0), mapOptions);
return marker = new google.maps.Marker({
position: latlng,
map: map
});
},
editLocation: function(ev) {
debug("model after click edit");
debug(this.model);
ev.preventDefault();
if (this.popup != null) {
this.popup.remove;
}
$("#add-location").empty();
this.popup_container = $("#add-location");
this.popup = new AdminApp.BranchFormView({
model: this.model,
parent: this.parent,
destinations: this.destinations,
config: this.config
});
return this.renderChildInto(this.popup, this.popup_container);
},
deleteLocation: function(ev) {
return this.model.destroy();
}
});
}).call(this);
(function() {
var _this = this;
AdminApp.BranchFormView = Support.CompositeView.extend({
tagName: "div",
id: "popup-form",
events: {
"click .save-location": "saveLocation",
"click .cancel-location": "cancelLocation",
"change select#location_region_id": "changeRegionSelect",
"change select#location_area_id": "setArea",
"change input": "getGeoValues"
},
initialize: function(options) {
_.bindAll(this, "render", "renderTemplate", "renderMap", "renderTimes", "getGeoValues");
debug("branch form");
this.config = options.config;
this.parent = options.parent;
this.destinations = options.destinations;
if (options.model) {
this.model = options.model;
}
if (!(this.model.get('region') != null)) {
this.header = "New Location";
} else {
this.header = "Edit Location";
}
$('button.add-location').hide();
return this.config.on("change:locale", this.render, this);
},
template: function() {
return JST["templates/admin/accounts/branch_form"];
},
render: function() {
var address;
if (this.region_select != null) {
this.region_select.remove;
}
if (this.area_select != null) {
this.area_select.remove;
}
this.$el.empty();
this.initFeature();
this.renderTemplate();
this.renderTimes();
if ((this.model.get('country') != null) && this.model.get('country')['_id']) {
this.renderRegionSelect(this.model.get('country')['_id']);
this.renderMap();
if (this.model.get('region') && this.model.get('region')['_id']) {
$('.controls a.save-location').text("Save Location");
address = this.model.get('address');
this.address = "" + address['street1'] + ", " + address['street2'] + ", " + address['city'] + ", " + address['province'] + ", " + address['country'] + ", " + address['postal_code'];
}
this.initForm();
this.setFeatures();
} else {
alert("Please select the Account Country in the Account Information section");
}
return this;
},
renderTemplate: function() {
this.heading = {
header: this.header
};
debug("rendering template");
this.context = $.extend(this.heading, this.model.toJSON());
debug("context passed to template");
debug(this.context);
debug(this.model);
debug(this.el);
this.$el.html(this.template(this.context));
this.region_el = this.$el.find("#location_region_id");
return this.area_el = this.$el.find("#location_area_id");
},
renderTimes: function() {
if (this.times != null) {
this.times.remove;
}
this.times = new AdminApp.TimesView({
model: this.model,
config: this.config
});
return $(this.el).find("#times-operation").append((this.times.render().el));
},
renderMap: function() {
if (this.map != null) {
this.map.remove;
}
$("#location-map").empty();
this.map_holder = $(this.el).find('#location-map');
this.map = new AdminApp.GeocodeMapView({
model: this.model,
destinations: this.destinations
});
return this.renderChildInto(this.map, this.map_holder);
},
renderRegionSelect: function(value) {
this.regions = this.destinations.filterByParent(value);
this.select_model = new AdminApp.Destination;
if ((this.model.get("region") != null) && (this.model.get('region')['_id'] != null)) {
this.selected = this.model.get('region')['_id'];
} else {
$('#area').hide();
}
this.region_select = new AdminApp.SelectView({
model: this.select_model,
config: this.config,
collection: this.regions,
el: this.region_el,
selected: this.selected
});
$(this.region_el).prepend("<option>Select Region</option>");
if ((this.model.get('region') != null) && (this.model.get('region')['_id'] != null)) {
$(this.region_el).val(this.model.get('region')['_id']);
this.renderAreaSelect(this.model.get('region')['_id']);
$(this.area_el).prepend("<option>Select Area</option>");
return $(this.area_el).val(this.model.get('area')['_id']);
}
},
renderAreaSelect: function(value) {
this.areas = this.destinations.filterByParent(value);
this.select_model = new AdminApp.Destination;
if ((this.model.get('area') != null) && (this.model.get('area')['_id'] != null)) {
this.selected = this.model.get('area')['_id'];
}
return this.area_select = new AdminApp.SelectView({
model: this.select_model,
config: this.config,
collection: this.areas,
el: this.area_el,
selected: this.selected
});
},
changeRegionSelect: function(ev) {
ev.preventDefault();
this.region_sel = $(ev.currentTarget).find("option:selected").attr('selected', true);
this.selected_region = this.region_sel.val();
$(ev.currentTarget).find("option").attr('selected', false);
this.region_sel.attr('selected', true);
this.model.set({
region: this.destinations.get(this.selected_region).attributes
}, {
silent: true
});
this.renderAreaSelect(this.selected_region);
$(this.area_el).prepend("<option>Select Area</option>");
return $('#area').fadeIn();
},
cancelLocation: function(ev) {
ev.preventDefault();
if (this.region_select != null) {
this.region_select.remove;
}
if (this.area_select != null) {
this.area_select.remove;
}
$(this.el).remove();
return $('button.add-location').show();
},
saveLocation: function(e) {
e.preventDefault();
debug("SAVE CLICKED");
debug(this.model);
if ((this.model.get('region') != null) && this.model.get('region')['_id']) {
debug(this.model);
if (!(this.model.get('id') != null)) {
this.model.unbind();
this.parent.addBranch(this.model);
}
this.el.empty();
$("#add-location").empty();
} else {
alert("Please select the What2Do regions for this location");
}
return $('button.add-location').show();
},
setArea: function(e) {
e.preventDefault();
this.area_sel = $(e.currentTarget);
this.area_val = $(e.currentTarget).val();
this.area_sel.find("option:selected").attr('selected', false);
this.area_sel.find('option [value="#{@area_val}"]').attr('selected', true);
this.area_sel.val(this.area_val);
this.selected_area = this.destinations.get(this.area_val);
return this.model.set({
area: this.selected_area.attributes
}, {
silent: true
});
},
extractFormData: function() {
var values;
this.form_inputs = $("#location-form :input");
values = {};
this.form_inputs.each(function() {
return values[this.name] = $(this).val();
});
debug("Form Values");
return debug(values);
},
getGeoValues: function() {
var address, geocoderParams, results,
_this = this;
debug("change detected on address");
this.old_address = "" + this.address;
debug(this.old_address);
this.extractAddress();
address = this.model.get('address');
this.address = "" + address['street1'] + ", " + address['street2'] + ", " + address['city'] + ", " + address['province'] + ", " + address['country'] + ", " + address['postal_code'];
if (this.old_address !== this.address) {
debug("calling geocode map");
this.geocoder = new google.maps.Geocoder;
geocoderParams = {
address: this.address
};
return results = this.geocoder.geocode(geocoderParams, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
debug("geocoding.....");
_this.latlng = results[0].geometry.location;
_this.model.set({
geo: [_this.latlng.lng(), _this.latlng.lat()],
zoom: 13
}, {
silent: true
});
return _this.renderMap();
}
});
}
},
extractAddress: function() {
var city, country, data, postal_code, province, street1, street2;
street1 = $("input#location_address_street1").val();
street2 = $("input#location_address_street2").val();
city = $("input#location_address_city").val();
province = $("input#location_address_province").val();
country = $("input#location_address_country").val();
postal_code = $("input#location_address_postal_code").val();
data = {
address: {
street1: street1,
street2: street2,
city: city,
province: province,
country: country,
postal_code: postal_code
}
};
return this.model.set(data, {
silent: true
});
},
initFeature: function() {
var data, feature, _i, _len, _ref;
this.features = ["parking", "valet_parking", "wheelchair_access", "credit_cards", "internet", "transportation", "reservations", "restaurant_facilities", "picnic_facilities", "kid_friendly", "group_friendly", "childcare", "equipment_rentals", "lockers", "changing_rooms", "first_aid", "life_guards", "tour_guides"];
if (!(this.model.get('region') != null)) {
data = {};
data['feature'] = {};
_ref = this.features;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
feature = _ref[_i];
data['feature'][feature] = false;
}
return this.model.set(data, {
silent: true
});
}
},
setFeatures: function() {
var feature, input_feature, _i, _len, _ref, _results;
_ref = this.features;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
feature = _ref[_i];
debug(feature);
if ((this.model.get('feature')[feature] != null) && this.model.get('feature')[feature] === true) {
input_feature = 'input[name=' + '"location[feature][' + ("" + feature) + ']"]';
debug(input_feature);
_results.push($("" + input_feature).attr('checked', true));
} else {
_results.push($("" + input_feature).attr('checked', false));
}
}
return _results;
},
initForm: function() {
var city, country, email, main_tel, name, postal_code, province, street1, street2, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7;
country = this.model.get('country')['name'][this.config.get('locale')];
if (this.model.get('address') != null) {
street1 = (_ref = this.model.get('address')['street1']) != null ? _ref : "";
street2 = (_ref1 = this.model.get('address')['street2']) != null ? _ref1 : "";
city = (_ref2 = this.model.get('address')['city']) != null ? _ref2 : "";
province = (_ref3 = this.model.get('address')['province']) != null ? _ref3 : "";
postal_code = (_ref4 = this.model.get('address')['postal_code']) != null ? _ref4 : "";
}
$("input#location_address_street1").val(street1 != null ? street1 : "");
$("input#location_address_street2").val(street2 != null ? street2 : "");
$("input#location_address_city").val(city != null ? city : "");
$("input#location_address_province").val(province != null ? province : "");
$("input#location_address_country").val(country != null ? country : "");
$("input#location_address_postal_code").val(postal_code != null ? postal_code : "");
this.extractAddress();
if (this.model.get('contact') != null) {
name = (_ref5 = this.model.get('contact')['name']) != null ? _ref5 : "";
main_tel = (_ref6 = this.model.get('contact')['main_tel']) != null ? _ref6 : "";
email = (_ref7 = this.model.get('contact')['email']) != null ? _ref7 : "";
}
$("input#location_contact_name").val(name != null ? name : "");
$("input#location_contact_main_tel").val(main_tel != null ? main_tel : "");
return $("input#location_contact_email").val(email != null ? email : "");
}
});
}).call(this);
(function() {
AdminApp.BranchesListView = Support.CompositeView.extend({
initialize: function(options) {
debug("IN INITIALIZE BRANCH LIST VIEW");
_.bindAll(this, "render");
this.config = options.config;
this.model = options.model;
this.branches = this.model.branches;
this.destinations = options.destinations;
this.config.on("change:locale", this.render, this);
this.branches.on("change", this.render, this);
return this.branches.on("add", this.render, this);
},
template: JST["templates/admin/accounts/branch_list"],
templateLocation: JST["templates/admin/accounts/branch"],
render: function() {
this.$el.empty();
this.renderLayout();
this.renderBranches();
return this;
},
renderLayout: function() {
return this.$el.html(this.template);
},
renderBranches: function() {
var branch_location, _i, _len, _ref, _results;
this.locationsContainer = this.$el.find('#account-locations');
this.locationsContainer.html(' ');
debug("render @branches");
debug(this.branches);
_ref = this.branches.models;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
branch_location = _ref[_i];
debug(branch_location);
if (!((branch_location.get('_destroy') != null) && branch_location.get('_destroy') === true)) {
_results.push(this.renderBranch(branch_location));
} else {
_results.push(void 0);
}
}
return _results;
},
renderBranch: function(branch_location) {
var branch_view;
debug("model before location view");
debug(branch_location);
branch_view = new AdminApp.BranchView({
model: branch_location,
parent: this.model,
config: this.config,
destinations: this.destinations
});
this.locationHtml = branch_view.render().el;
this.locationsContainer.append(this.locationHtml);
return branch_view.renderMap();
}
});
}).call(this);
(function() {
AdminApp.EditAccountView = Support.CompositeView.extend({
events: {
"change select#account_country_id": "changeForm",
"change select#account_category_id": "changeForm",
"click .cancel": "cancelAccount",
"click .update": "updateAccount",
"click .translations .btn": "changeTranslation",
"click .add-location": "addBranch",
"click .subnav ul li a": "activeSection"
},
initialize: function(options) {
this.config = options.config;
if (!this.model) {
this.model = new AdminApp.Account;
}
if (!this.model.isNew()) {
this.model.fetch();
}
if (this.model.isNew()) {
this.initializeAccount(this.model);
}
this.config.on("change:locale", this.render, this);
this.destinations = options.destinations;
this.categories = options.categories;
_.bindAll(this, "render", "renderDestinationSelects", "renderCategorySelects");
this.categories.on("reset", this.renderDestinationSelects, this);
return this.destinations.on("reset", this.renderCategorySelects, this);
},
template: JST["templates/admin/accounts/edit"],
render: function() {
var _this = this;
$(".navbar li").removeClass("active");
this.renderTemplate();
this.renderBranchesList();
this.renderUploads();
this.destinations.lazy_load({
success: function() {
return _this.renderDestinationSelects();
}
});
this.categories.lazy_load({
success: function() {
return _this.renderCategorySelects();
}
});
this.delegateEvents();
return this;
},
renderTemplate: function() {
var context, locales;
locales = {
locales: I18n.available_locales
};
context = $.extend(this.model.toJSON(), locales);
this.$el.html(this.template(context));
this.$el.find("#account_company_name_" + (this.config.get('locale'))).show();
this.$el.find("#account_master_information_teaser_" + this.model.defaultLocale).show();
this.$el.find("#account_master_information_description_" + this.model.defaultLocale).show();
this.$el.find(".translations .btn[data-locale='" + this.model.defaultLocale + "']").addClass("active");
this.$el.find('ul.nav.nav-tabs li:first, #lA').addClass("active");
this.dest_el = this.$el.find("#account_country_id");
this.cat_el = this.$el.find("#account_category_id");
return this.subcat_el = this.$el.find("#master_info_subcategory_id");
},
renderBranchesList: function() {
this.branchesList = new AdminApp.BranchesListView({
model: this.model,
config: this.config,
destinations: this.destinations
});
this.locationsContainer = this.$('section#locations');
return this.renderChildInto(this.branchesList, this.locationsContainer);
},
renderDestinationSelects: function() {
this.countries = this.destinations.filterByLevel(0);
this.select_model = new AdminApp.Destination;
if (!this.model.isNew()) {
this.selected = this.model.get('country_id');
} else {
this.selected = "";
}
new AdminApp.SelectView({
model: this.select_model,
config: this.config,
collection: this.countries,
el: this.dest_el,
selected: this.selected
});
return $(this.dest_el).prepend("<option>Select Country</option>");
},
renderCategorySelects: function() {
var value;
this.main_categories = this.categories.filterByLevel(0);
this.select_model = new AdminApp.Category;
if (!this.model.isNew()) {
this.selected = this.model.get('category_id');
} else {
this.selected = "";
}
new AdminApp.SelectView({
model: this.select_model,
config: this.config,
collection: this.main_categories,
el: this.cat_el,
selected: this.selected
});
$(this.cat_el).prepend("<option>Select Category</option>");
if (!this.model.isNew()) {
value = this.model.get("category_id");
return this.renderSubcategorySelect(value);
}
},
renderUploads: function() {
$('#media').html(' ');
this.media_el = this.$el.find('#media');
if (this.mediapanel != null) {
this.mediapanel.remove;
}
return this.mediapanel = new AdminApp.MediaPanelView({
model: this.model,
el: this.media_el
});
},
renderSubcategorySelect: function(value) {
var subcat_select;
this.subcategories = this.categories.filterByParent(value);
this.select_model = new AdminApp.Category;
if (!this.model.isNew()) {
this.selected = this.model.get('master_information')['subcategory_id'];
} else {
this.selected = "";
}
subcat_select = new AdminApp.SelectView({
model: this.select_model,
config: this.config,
collection: this.subcategories,
el: this.subcat_el,
selected: this.selected
});
return $(this.subcat_el).prepend("<option>Select Subcategory</option>");
},
addBranch: function(ev) {
var country_id;
if (this.model.isNew() && $('#account_country_id option[selected="selected"]').length > 0) {
country_id = $('#account_country_id option[selected="selected"]').val();
this.country = this.destinations.get(country_id);
} else {
this.country = this.destinations.get(this.model.get("country_id"));
}
if (this.country != null) {
$("#add-location").empty();
this.popup_container = this.$el.find("#add-location");
this.branch = new AdminApp.Branch({
country: this.country.attributes
});
this.popup = new AdminApp.BranchFormView({
model: this.branch,
parent: this.model,
destinations: this.destinations,
config: this.config
});
return this.renderChildInto(this.popup, this.popup_container);
} else {
return alert("Please select the account country in the Account Information section at the top of the form");
}
},
cancelAccount: function(e) {
e.preventDefault();
return AdminApp.accountsRouter.navigate("/admin/accounts", {
trigger: true
});
},
updateAccount: function(e) {
var data,
_this = this;
e.preventDefault();
data = this.extractFormData();
return this.model.save(data, {
success: function(model, response) {
_this.$el.remove();
return AdminApp.accountsRouter.navigate("/admin/accounts", {
trigger: true
});
},
error: function(model, response) {
var errors;
errors = $.parseJSON(response.responseText);
_this.$el.find(".control-group.error span.help-inline").remove();
_this.$el.find(".control-group").removeClass("error");
return _(errors).each(function(value, key) {
var $controlGroup;
debug(key);
$controlGroup = _this.$el.find(".control-group." + key);
$controlGroup.addClass("error");
return $controlGroup.find(".controls").append("<span class='help-inline'>" + value + "</span>");
});
}
});
},
initializeAccount: function(model) {
var data, initlang, locale, newlang, _i, _len, _ref;
newlang = {};
_ref = I18n.available_locales;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
locale = _ref[_i];
newlang["" + locale] = "";
initlang = $.extend(newlang, initlang);
}
data = {
account_name: "",
company_name_translations: initlang,
membership_detail: {
contact: {
name: "",
main_tel: "",
contact_hp: "",
email: ""
},
company_legal_name: "",
address: {
street1: "",
street2: "",
city: "",
province: "",
country: "",
postal_code: ""
}
},
master_information: {
website_url: "",
teaser_translations: initlang,
description_translations: initlang,
info_source: "",
recommended_for_tag: {
expat: false,
tourist: false,
business: false,
kids: false
}
}
};
return model.set(data, {
silent: true
});
},
extractFormData: function() {
var company_name_translations, data, description_translations, locale, string, teaser_translations, _i, _len, _ref, _ref1, _ref2;
data = {
account_name: this.$("#account_account_name").val(),
country_id: (_ref = this.$("#account_country_id option:selected").val()) != null ? _ref : "",
category_id: (_ref1 = this.$("#account_category_id option:selected").val()) != null ? _ref1 : "",
membership_detail: {
contact: {
name: this.$("#account_contact_name").val(),
main_tel: this.$("#account_contact_main_tel").val(),
contact_hp: this.$("#account_contact_contact_hp").val(),
email: this.$("#account_contact_email").val()
},
company_legal_name: this.$("#account_company_legal_name").val(),
address: {
street1: this.$("#account_address_street1").val(),
street2: this.$("#account_address_street2").val(),
city: this.$("#account_address_city").val(),
province: this.$("#account_address_province").val(),
country: this.$("#account_address_country").val(),
postal_code: this.$("#account_address_postal_code").val()
}
},
master_information: {
website_url: this.$("#account_website_url").val(),
info_source: this.$("#account_address_postal_code").val(),
recommended_for_tag: {
expat: this.$('input[name="account[master_information][recommended_for_tag][expat]"]').prop('checked'),
tourist: this.$('input[name="account[master_information][recommended_for_tag][tourist]"]').prop('checked'),
business: this.$('input[name="account[master_information][recommended_for_tag][business]"]').prop('checked'),
kids: this.$('input[name="account[master_information][recommended_for_tag][kids]"]').prop('checked')
}
}
};
data["company_name_translations"] = {};
data["master_information"]["teaser_translations"] = {};
data["master_information"]["description_translations"] = {};
company_name_translations = {};
teaser_translations = {};
description_translations = {};
_ref2 = I18n.available_locales;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
locale = _ref2[_i];
string = this.$("#account_company_name_" + locale).val();
company_name_translations[locale] = string;
string = this.$("#account_master_information_teaser_" + locale).val();
teaser_translations[locale] = string;
string = this.$("#account_master_information_description_" + locale).val();
description_translations[locale] = string;
}
data['company_name_translations'] = company_name_translations;
data['master_information']['teaser_translations'] = teaser_translations;
data['master_information']['description_translations'] = description_translations;
return data;
},
changeTranslation: function(ev) {
var $el, field, field_locale, locale, _i, _len, _ref;
ev.preventDefault();
$el = $(ev.currentTarget);
field_locale = $el.data("locale");
field = $el.data("field");
_ref = I18n.available_locales;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
locale = _ref[_i];
if (("" + field) === "company_name") {
this.$("input[name='" + field + "']").hide();
}
if (field === "teaser") {
this.$("input[name='master_information[" + field + "][" + locale + "]']").hide();
}
if (field === "description") {
this.$("#account_master_information_" + field + "_" + locale).hide();
}
}
if (field === "company_name") {
this.$("#account_" + field + "_" + field_locale).show();
}
if (field === "teaser" || field === "description") {
return this.$("#account_master_information_" + field + "_" + field_locale).show();
}
},
changeForm: function(ev) {
var $el, model_key, text_val, value;
ev.preventDefault();
$el = $(ev.currentTarget);
value = $el.val();
model_key = $el.attr('name').match(/(\w+)/)[1];
debug(model_key);
this.model.set("" + model_key, value, {
silent: true
});
$el.find("option").each(function() {
return $(this).attr('selected', false);
});
text_val = $el.find("option[value='" + value + "']").attr('selected', true).text();
if ($el.attr('id') === "account_category_id") {
$("#master_information_category_id").val(value);
this.renderSubcategorySelect(value);
}
if ($el.attr('id') === "account_country_id") {
return $("#account_address_country").val(text_val);
}
},
activeSection: function(ev) {
var clicked;
clicked = $(ev.currentTarget);
$(".subnav ul li.active").removeClass('active');
return clicked.parent().addClass('active');
}
});
}).call(this);
(function() {
AdminApp.GeocodeMapView = Support.CompositeView.extend({
tagName: "div",
id: "map-canvas",
initialize: function(options) {
debug("Render Map");
debug("map");
debug(options);
if (options.destinations != null) {
this.destinations = options.destinations;
}
return this.model = options.model;
},
render: function() {
var default_geo, myOptions, pinColor, pinIcon;
if (this.map != null) {
this.map.remove;
}
if (this.marker != null) {
this.marker.remove;
}
if (!(this.model.get('geo') != null)) {
default_geo = this.destinations.get(this.model.get('country')['_id']);
this.latitude = default_geo.get('lat');
this.longitude = default_geo.get('lng');
this.zoom = default_geo.get('zoom');
} else {
this.latitude = this.model.get('geo')[1];
this.longitude = this.model.get('geo')[0];
this.zoom = this.model.get('zoom');
}
this.latlng = new google.maps.LatLng(this.latitude, this.longitude);
myOptions = {
zoom: this.zoom,
center: this.latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false,
mapTypeControl: false
};
this.map = new google.maps.Map(this.el, myOptions);
pinColor = "CA0000";
pinIcon = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor, null, null, null, new google.maps.Size(21, 34));
this.marker = new google.maps.Marker({
map: this.map,
position: this.latlng,
draggable: true,
title: "Map Center"
});
this.marker.setIcon(pinIcon);
_.bindAll(this, 'dragMarker', 'dragMap', 'zoomChange', 'setmapCenter');
google.maps.event.addListener(this.marker, "dragend", this.dragMarker);
google.maps.event.addListener(this.map, "dragend", this.dragMap);
google.maps.event.addListener(this.map, 'zoom_changed', this.zoomChange);
google.maps.event.addListener(this.map, 'tilesloaded', this.setmapCenter);
google.maps.event.addListener(this.map, 'tilesloaded', this.setmapCenter);
return this;
},
getGeoValues: function() {
var geocoderParams, results,
_this = this;
debug("change detected on address");
this.address = "" + (this.model.get('address.street1')) + ", " + (this.model.get('address.street2')) + ", " + (this.model.get('address.city')) + ", " + (this.model.get('address.province')) + ", " + (this.model.get('address.country')) + ", " + (this.model.get('address.postal_code'));
this.geocoder = new google.maps.Geocoder;
geocoderParams = {
address: this.address
};
return results = this.geocoder.geocode(geocoderParams, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
_this.latlng = results[0].geometry.location;
_this.map.setCenter(_this.latlng);
return _this.updateGeoValues();
}
});
},
dragMarker: function() {
this.latlng = this.marker.getPosition();
this.map.panTo(this.latlng);
return this.updateGeoValues();
},
setmapCenter: function() {
google.maps.event.trigger(this.map, 'resize');
return this.map.setCenter(this.latlng);
},
dragMap: function() {
this.latlng = this.map.getCenter();
this.marker.setPosition(this.latlng);
return this.updateGeoValues();
},
zoomChange: function() {
this.zoom = this.map.getZoom();
return this.updateGeoValues();
},
updateGeoValues: function() {
var bounds;
bounds = this.map.getBounds();
this.ne = bounds.getNorthEast();
this.sw = bounds.getSouthWest();
$("#destination_latitude").val(this.latlng.lat());
$("#destination_longitude").val(this.latlng.lng());
$("#destination_zoom").val(this.zoom);
$("#destination_swlat").val(this.sw.lat());
$("#destination_swlng").val(this.sw.lng());
$("#destination_nelat").val(this.ne.lat());
$("#destination_nelng").val(this.ne.lng());
return this.model.set({
geo: [this.latlng.lng(), this.latlng.lat()],
zoom: this.zoom
}, {
silent: true
});
}
});
}).call(this);
(function() {
AdminApp.AccountsView = Support.CompositeView.extend({
template: JST["templates/admin/accounts/index"],
initialize: function(options) {
_.bindAll(this, "render");
this.config = options.config;
this.collectionForSearch = new AdminApp.Accounts;
this.collection.lazy_load();
this.searchKeywords = "";
this.collection.on("reset", this.render, this);
this.collection.on("add", this.render, this);
this.collection.on("remove", this.render, this);
this.collectionForSearch.on("reset", this.renderList, this);
this.config.on("change:locale", this.render, this);
return this.render();
},
events: {
"click a.new-account": "newAccount",
"keyup input.search": "search",
"click .pagination a.next": "nextPage",
"click .pagination a.previous": "previousPage",
"click .pagination a.page": "goToPage"
},
render: function() {
$(".navbar li").removeClass("active");
$(".navbar li.accounts").addClass("active");
this.renderTemplate();
this.renderAccounts();
return this;
},
renderTemplate: function() {
var context, pagination, search_key;
search_key = {
keywords: this.searchKeywords
};
pagination = {
pagination: this.collection.pagination
};
context = $.extend(pagination, search_key);
return this.$el.html(this.template(context));
},
renderAccounts: function() {
var self;
self = this;
return this.collection.each(function(account) {
var row;
row = new AdminApp.AccountView({
model: account
});
self.renderChild(row);
return self.$("tbody").append(row.el);
});
},
renderList: function() {
this.$("tbody").empty();
return this.collectionForSearch.each(this.addOne);
},
newAccount: function(ev) {
ev.preventDefault();
return AdminApp.accountsRouter.navigate("/admin/accounts/new", {
trigger: true
});
},
search: function(ev) {
var $el;
ev.preventDefault();
$el = $(ev.currentTarget);
this.searchKeywords = $el.val();
if (ev.keyCode === 13) {
return this.collection.fetch({
data: {
keywords: this.searchKeywords
}
});
}
},
nextPage: function(ev) {
var $el;
ev.preventDefault();
$el = $(ev.currentTarget);
return this.collection.fetch({
data: {
page: this.collection.pagination.next
}
});
},
previousPage: function(ev) {
var $el;
ev.preventDefault();
$el = $(ev.currentTarget);
return this.collection.fetch({
data: {
page: this.collection.pagination.previous
}
});
},
goToPage: function(ev) {
var $el;
ev.preventDefault();
$el = $(ev.currentTarget);
return this.collection.fetch({
data: {
page: $el.html()
}
});
}
});
}).call(this);
(function() {
AdminApp.SelectView = Backbone.View.extend({
initialize: function(options) {
if (options && options.config) {
this.config = options.config;
}
this.el = options.el;
this.selected = options.selected;
this.model = options.model;
this.collection = options.collection;
return this.render();
},
render: function() {
var item, _i, _len, _ref;
this.el.empty();
_ref = this.collection;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
item = _ref[_i];
this.addOne(item, this.selected);
}
return this;
},
addOne: function(option_item, selected) {
return $(this.el).append(new AdminApp.SelectOptionView({
model: option_item,
config: this.config,
selected: selected
}).render().el);
}
});
}).call(this);
(function() {
AdminApp.SelectOptionView = Backbone.View.extend({
tagName: "option",
initialize: function(options) {
if (options && options.config) {
this.config = options.config;
return this.selected = options.selected;
}
},
render: function() {
var text;
if (this.model.get('name')["" + window.I18n.locale] != null) {
text = this.model.get('name')["" + window.I18n.locale];
} else {
text = "No Translation";
}
$(this.el).attr('value', this.model.get('_id')).html(text);
if (this.selected !== "" && this.model.get('_id') === this.selected) {
$(this.el).attr('selected', true);
}
return this;
}
});
}).call(this);
(function() {
AdminApp.TimeView = Support.CompositeView.extend({
tagName: "tr",
events: {
"click .delete-time": "deleteTime"
},
template: JST["templates/admin/optime/operating_time_row"],
initialize: function(options) {
this.parent = options.parent;
this.config = options.config;
this.model = options.model;
_.bindAll(this, "render", "remove");
this.config.on("change:locale", this.render, this);
this.model.on("destroy", this.remove, this);
return this.model.on("change", this.render, this);
},
render: function() {
var context, locales;
$(this.el).empty();
locales = {
locales: I18n.available_locales
};
context = $.extend(this.model.attributes, locales);
$(this.el).append(this.template(context));
return this;
},
remove: function() {
return $(this.el).remove();
},
deleteLocation: function(ev) {
return this.model.destroy();
}
});
}).call(this);
(function() {
AdminApp.TimesView = Backbone.View.extend({
id: "time-widget",
events: {
"click a.add-time": "addTime",
"click a.delete-time": "deleteTime",
"change select": "setSelectedDay"
},
template: JST["templates/admin/optime/operating_time"],
templateTime: JST["templates/admin/optime/operating_time_row"],
initialize: function(options) {
if (options && options.config) {
this.config = options.config;
}
this.model = options.model;
this.config.on("change:locale", this.render, this);
this.model.on("change:operating_times", this.render, this);
return _.bindAll(this, "render");
},
render: function() {
this.$el.empty();
this.renderTemplate();
this.renderTimes();
this.$el.find("#widget-to-time").timePicker();
this.$el.find("#widget-from-time").timePicker();
this.delegateEvents();
return this;
},
renderTemplate: function() {
return this.$el.append(this.template());
},
renderTimes: function() {
var index, op_time, _i, _len, _ref, _results;
this.$el.find('#operating-times').empty();
debug("RENDERTIME MODEL NEXT");
if (this.model.get('operating_times') != null) {
this.operating_times = _.clone(this.model.get('operating_times'));
_ref = this.operating_times;
_results = [];
for (index = _i = 0, _len = _ref.length; _i < _len; index = ++_i) {
op_time = _ref[index];
if (op_time != null) {
_results.push(this.renderTime(op_time, index));
} else {
_results.push(void 0);
}
}
return _results;
}
},
renderTime: function(op_time, index) {
var data;
data = {
tindex: index,
operating_time: op_time
};
return this.$el.find('#operating-times').append(this.templateTime(data));
},
addTime: function(ev) {
var data, _ref, _ref1, _ref2, _ref3;
this.from_day = (_ref = this.$el.find('#widget-from-day option:selected').val()) != null ? _ref : null;
this.to_day = (_ref1 = this.$el.find('#widget-to-day option:selected').val()) != null ? _ref1 : null;
this.from_time = (_ref2 = this.$el.find('input#widget-from-time').val()) != null ? _ref2 : null;
this.to_time = (_ref3 = this.$el.find('input#widget-to-time').val()) != null ? _ref3 : null;
data = {
from_day: this.from_day,
to_day: this.to_day,
from_time: this.from_time,
to_time: this.to_time
};
if (this.model.get('operating_times') != null) {
this.operating_times = _.clone(this.model.get('operating_times'));
this.operating_times.push(data);
} else {
this.operating_times = [];
this.operating_times.push(data);
}
return this.model.set({
operating_times: this.operating_times
});
},
setSelectedDay: function(ev) {
this.selected = $(ev.currentTarget).val();
$(ev.currentTarget).find("option:selected").attr('selected', false);
return $(ev.currentTarget).find("option[value=" + this.selected + "]").attr('selected', true);
},
deleteTime: function(ev) {
var index_to_delete;
index_to_delete = $(ev.currentTarget).data("index");
this.operating_times = _.clone(this.model.get('operating_times'));
delete this.operating_times[parseFloat(index_to_delete)];
return this.model.set({
operating_times: _.compact(this.operating_times)
});
}
});
}).call(this);
(function() {
AdminApp.ActivityView = Support.CompositeView.extend({
tagName: "tr",
events: {
"click .edit": "editActivity",
"click .delete": "deleteActivity",
"click .remove": "removeCategory"
},
template: JST["templates/admin/activities/activity"],
initialize: function(options) {
_.bindAll(this, "render");
return this.model.on("change:categories_assigned", this.render);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
editActivity: function(ev) {
ev.preventDefault();
return AdminApp.activitiesRouter.navigate("/admin/activities/" + this.model.id + "/edit", {
trigger: true
});
},
deleteActivity: function(ev) {
ev.preventDefault();
ev.stopPropagation();
if (confirm("Are you sure?")) {
return this.model.destroy();
}
},
removeCategory: function(ev) {
var activity, cat, categories, id, removed_category, _i, _len,
_this = this;
ev.preventDefault();
id = $(ev.currentTarget).data("id");
activity = this.model.get(id);
categories = this.model.get('category_ids');
removed_category = $(ev.currentTarget).data('category_id');
this.updated_categories = [];
for (_i = 0, _len = categories.length; _i < _len; _i++) {
cat = categories[_i];
if (cat !== removed_category) {
this.updated_categories.push(cat);
}
}
return this.model.save({
category_ids: this.updated_categories
}, {
error: function(model, response) {
var errors;
errors = $.parseJSON(response.responseText);
return alert("" + errors);
}
});
},
renderMessage: function() {
return alert("this is an error");
}
});
}).call(this);
(function() {
var __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
AdminApp.AssignActivityView = Support.CompositeView.extend({
tagName: "div",
className: "assignments",
events: {
"click .close": "cancelAssignment",
"change .update": "addCategory"
},
initialize: function(options) {
_.bindAll(this, "render");
return this.categories = options.categories;
},
template: JST["templates/admin/activities/assign"],
render: function() {
var context;
context = $.extend(JSON.parse(JSON.stringify(this.model)), JSON.parse(JSON.stringify({
categories: this.categories
})));
this.$el.html(this.template(context));
return this;
},
cancelAssignment: function(e) {
e.preventDefault();
$("a.assign").removeClass('active');
$("ul#activity_" + (this.model.get('_id'))).toggle();
return this.leave();
},
addCategory: function(e) {
var existing_categories, new_category,
_this = this;
e.preventDefault();
new_category = this.$("option:selected").val();
existing_categories = this.model.get("category_ids");
if (__indexOf.call(existing_categories, new_category) >= 0) {
return this.renderMessage();
} else {
existing_categories.push(new_category);
return this.model.save({
category_ids: existing_categories
}, {
success: function(model, response) {
$("a.assign").removeClass('active');
debug(model);
$("ul#activity_" + (model.get('id'))).toggle();
return _this.leave();
},
error: function(model, response) {
var errors;
errors = $.parseJSON(response.responseText);
_this.$el.find(".control-group.error span.help-inline").remove();
_this.$el.find(".control-group").removeClass("error");
return _(errors).each(function(value, key) {
var $controlGroup;
debug(key);
$controlGroup = _this.$el.find(".control-group." + key);
$controlGroup.addClass("error");
return $controlGroup.find(".controls").append("<span class='help-inline'>" + value + "</span>");
});
}
});
}
},
renderMessage: function() {
return alert("This is already assigned");
}
});
}).call(this);
(function() {
AdminApp.EditActivityView = Support.CompositeView.extend({
events: {
"click .cancel": "cancelActivity",
"click .update": "updateActivity",
"click .translations .btn": "changeTranslation"
},
initialize: function(options) {
if (!this.model) {
this.model = new AdminApp.Activity;
}
if (!this.model.isNew()) {
this.model.fetch();
}
if (this.model.isNew()) {
this.initializeAccount(this.model);
}
this.config = options.config;
this.config.on("change:locale", this.render, this);
return _.bindAll(this, "render");
},
template: JST["templates/admin/activities/edit"],
render: function() {
var context, locales;
locales = {
locales: I18n.available_locales
};
context = $.extend(JSON.parse(JSON.stringify(this.model)), locales);
this.$el.html(this.template(context));
this.$el.find("#activity_name_" + this.model.defaultLocale).show();
this.$el.find(".translations .btn[data-locale='" + this.model.defaultLocale + "']").addClass("active");
return this;
},
cancelActivity: function(e) {
e.preventDefault();
return AdminApp.activitiesRouter.navigate("/admin/activities", {
trigger: true
});
},
updateActivity: function(e) {
var data,
_this = this;
e.preventDefault();
data = this.extractFormData();
return this.model.save(data, {
success: function() {
return AdminApp.activitiesRouter.navigate("/admin/activities", {
trigger: true
});
},
error: function(model, response) {
var errors;
errors = $.parseJSON(response.responseText);
_this.$el.find(".control-group.error span.help-inline").remove();
_this.$el.find(".control-group").removeClass("error");
return _(errors).each(function(value, key) {
var $controlGroup;
debug(key);
$controlGroup = _this.$el.find(".control-group." + key);
$controlGroup.addClass("error");
return $controlGroup.find(".controls").append("<span class='help-inline'>" + value + "</span>");
});
}
});
},
extractFormData: function() {
var data, locale, string, _i, _len, _ref;
data = {};
data["name"] = {};
_ref = this.model.locales;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
locale = _ref[_i];
string = this.$("#activity_name_" + locale).val();
if (string !== "") {
data["name"][locale] = string;
}
}
return data;
},
changeTranslation: function(ev) {
var $el, field, locale;
ev.preventDefault();
$el = $(ev.currentTarget);
locale = $el.data("locale");
field = $el.data("field");
this.$("input[name='activity_" + field + "']").hide();
return this.$("#activity_" + field + "_" + locale).show();
},
initializeAccount: function(model) {
var data, initlang, locale, newlang, _i, _len, _ref;
newlang = {};
_ref = model.locales;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
locale = _ref[_i];
newlang["" + locale] = "";
initlang = $.extend(newlang, initlang);
}
data = {
name: initlang
};
return model.set(data, {
silent: true
});
}
});
}).call(this);
(function() {
AdminApp.ActivitiesView = Support.CompositeView.extend({
template: JST["templates/admin/activities/index"],
initialize: function(options) {
var _this = this;
this.config = options.config;
this.collection.fetch();
this.categories = new AdminApp.Categories;
this.categories.lazy_load({
success: function() {
return _this.categories = _this.categories.filterByLevel(0);
}
});
this.collection.on("reset", this.render, this);
this.collection.on("add", this.render, this);
this.collection.on("remove", this.render, this);
this.config.on("change:locale", this.render, this);
return _.bindAll(this, "render");
},
events: {
"click a.new-activity": "newActivity",
"click .assign": "categoryPopup"
},
render: function() {
$(".navbar li").removeClass("active");
$(".navbar li.activities").addClass("active");
this.renderTemplate();
this.renderActivities();
return this;
},
renderTemplate: function() {
return this.$el.html(this.template());
},
renderActivities: function() {
var self;
self = this;
return _(this.collection.models).each(function(activity) {
var view;
view = new AdminApp.ActivityView({
model: activity
});
self.renderChild(view);
return self.$("tbody").append(view.el);
});
},
categoryPopup: function(ev) {
var activity_id, popup_container;
ev.preventDefault();
activity_id = $(ev.currentTarget).data('id');
this.activity = this.collection.get(activity_id);
popup_container = $("ul#activity_" + activity_id);
this.popup = new AdminApp.AssignActivityView({
model: this.activity,
categories: this.categories
});
this.renderChildInto(this.popup, popup_container);
return popup_container.toggle();
},
newActivity: function(ev) {
ev.preventDefault();
return AdminApp.activitiesRouter.navigate("/admin/activities/new", {
trigger: true
});
}
});
}).call(this);
(function() {
AdminApp.CategoryView = Support.CompositeView.extend({
tagName: "tr",
events: {
"click .edit": "editCategory",
"click .delete": "deleteCategory",
"click .new-subcategory": "newSubcategory"
},
template: JST["templates/admin/categories/category"],
templateChild: JST["templates/admin/categories/subcategory"],
initialize: function() {
return _.bindAll(this, "render");
},
render: function() {
var child, children, self, view, _i, _len,
_this = this;
self = this;
if (this.model.get('level') === 0) {
this.$el.append(this.template(JSON.parse(JSON.stringify(this.model))));
this.$el.attr("data-id", "category-" + this.model.id);
} else {
this.$el.append(this.templateChild(JSON.parse(JSON.stringify(this.model))));
}
children = this.model.collection.filter(function(category) {
return category.get("parent_id") === _this.model.id;
});
if (children) {
this.$el.find("td.subcategories").last().append("<ul class='span5 unstyled'/>");
for (_i = 0, _len = children.length; _i < _len; _i++) {
child = children[_i];
view = new AdminApp.CategoryView({
model: child,
tagName: "li"
});
self.renderChild(view);
this.$el.find("> td.subcategories ul").last().append(view.el);
}
}
return this;
},
editCategory: function(ev) {
ev.preventDefault();
ev.stopPropagation();
return AdminApp.categoriesRouter.navigate("/admin/categories/" + this.model.id + "/edit", {
trigger: true
});
},
deleteCategory: function(ev) {
ev.preventDefault();
ev.stopPropagation();
if (confirm("Are you sure?")) {
return this.model.destroy();
}
},
newSubcategory: function(ev) {
ev.preventDefault();
ev.stopPropagation();
return AdminApp.categoriesRouter.navigate("/admin/categories/" + this.model.id + "/new", {
trigger: true
});
}
});
}).call(this);
(function() {
AdminApp.EditCategoryView = Support.CompositeView.extend({
events: {
"click .cancel": "cancelCategory",
"click .update": "updateCategory",
"click .translations .btn": "changeTranslation"
},
initialize: function(options) {
if (!this.model) {
this.model = new AdminApp.Category;
}
if (!this.model.isNew()) {
this.model.fetch();
}
if (this.model.isNew()) {
this.initializeAccount(this.model);
}
this.config = options.config;
if (options && options.parent) {
this.parent = options.parent;
}
this.config.on("change:locale", this.render, this);
return _.bindAll(this, "render");
},
template: JST["templates/admin/categories/edit"],
render: function() {
var context, locales;
locales = {
locales: I18n.available_locales
};
context = $.extend(JSON.parse(JSON.stringify(this.model)), locales);
this.$el.html(this.template(context));
this.$el.find("#category_name_" + this.model.defaultLocale).show();
this.$el.find(".translations .btn[data-locale='" + this.model.defaultLocale + "']").addClass("active");
return this;
},
cancelCategory: function(e) {
e.preventDefault();
return AdminApp.categoriesRouter.navigate("/admin/categories", {
trigger: true
});
},
updateCategory: function(e) {
var data,
_this = this;
e.preventDefault();
data = this.extractFormData();
return this.model.save(data, {
success: function() {
return AdminApp.categoriesRouter.navigate("/admin/categories", {
trigger: true
});
},
error: function(model, response) {
var errors;
errors = $.parseJSON(response.responseText);
_this.$el.find(".control-group.error span.help-inline").remove();
_this.$el.find(".control-group").removeClass("error");
return _(errors).each(function(value, key) {
var $controlGroup;
debug(key);
$controlGroup = _this.$el.find(".control-group." + key);
$controlGroup.addClass("error");
return $controlGroup.find(".controls").append("<span class='help-inline'>" + value + "</span>");
});
}
});
},
extractFormData: function() {
var data, locale, string, _i, _len, _ref;
data = {};
data["name"] = {};
_ref = this.model.locales;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
locale = _ref[_i];
string = this.$("#category_name_" + locale).val();
if (string !== "") {
data["name"][locale] = string;
}
}
data["description"] = this.$("#category_description").val();
if (this.parent) {
data["parent_id"] = this.parent.id;
data["level"] = 1;
}
return data;
},
changeTranslation: function(ev) {
var $el, field, locale;
ev.preventDefault();
$el = $(ev.currentTarget);
locale = $el.data("locale");
field = $el.data("field");
this.$("input[name='category_" + field + "']").hide();
return this.$("#category_" + field + "_" + locale).show();
},
initializeAccount: function(model) {
var data, initlang, locale, newlang, _i, _len, _ref;
newlang = {};
_ref = model.locales;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
locale = _ref[_i];
newlang["" + locale] = "";
initlang = $.extend(newlang, initlang);
}
data = {
name: initlang,
description: ""
};
return model.set(data, {
silent: true
});
}
});
}).call(this);
(function() {
AdminApp.CategoriesView = Support.CompositeView.extend({
template: JST["templates/admin/categories/index"],
initialize: function(options) {
this.config = options.config;
this.collection.lazy_load();
this.collection.on("reset", this.render, this);
this.collection.on("add", this.render, this);
this.collection.on("remove", this.render, this);
this.config.on("change:locale", this.render, this);
return _.bindAll(this, "render");
},
events: {
"click a.new-category": "newCategory"
},
render: function() {
$(".navbar li").removeClass("active");
$(".navbar li.categories").addClass("active");
this.renderTemplate();
this.renderCategories();
return this;
},
renderTemplate: function() {
return this.$el.html(this.template());
},
renderCategories: function() {
var firstLevelCategories, self;
self = this;
firstLevelCategories = this.collection.filterByLevel(0);
return _(firstLevelCategories).each(function(category) {
var view;
view = new AdminApp.CategoryView({
model: category
});
self.renderChild(view);
return self.$("tbody").append(view.el);
});
},
newCategory: function(ev) {
ev.preventDefault();
return AdminApp.categoriesRouter.navigate("/admin/categories/new", {
trigger: true
});
}
});
}).call(this);
(function() {
AdminApp.AreaView = Support.CompositeView.extend({
tagName: "li",
className: "area",
events: {
"click .edit": "editDestination",
"click .delete": "deleteDestination"
},
template: JST["templates/admin/destinations/area"],
render: function() {
this.$el.html(this.template(JSON.parse(JSON.stringify(this.model))));
this.$el.attr("data-id", "destination-" + this.model.id);
return this;
},
editDestination: function(ev) {
ev.preventDefault();
ev.stopPropagation();
return AdminApp.destinationsRouter.navigate("/admin/destinations/" + this.model.id + "/edit", {
trigger: true
});
},
deleteDestination: function(ev) {
ev.preventDefault();
ev.stopPropagation();
if (confirm("Are you sure?")) {
return this.model.destroy();
}
}
});
}).call(this);
(function() {
AdminApp.CountryView = Support.CompositeView.extend({
tagName: "tr",
className: "country",
events: {
"click .edit": "editDestination",
"click .delete": "deleteDestination",
"click .new-region": "newRegion"
},
template: JST["templates/admin/destinations/country"],
render: function() {
this.$el.html(this.template(JSON.parse(JSON.stringify(this.model))));
this.$el.attr("data-id", "destination-" + this.model.id);
return this;
},
editDestination: function(ev) {
ev.preventDefault();
ev.stopPropagation();
return AdminApp.destinationsRouter.navigate("/admin/destinations/" + this.model.id + "/edit", {
trigger: true
});
},
deleteDestination: function(ev) {
ev.preventDefault();
ev.stopPropagation();
if (confirm("Are you sure?")) {
return this.model.destroy();
}
},
newRegion: function(ev) {
ev.preventDefault();
ev.stopPropagation();
return AdminApp.destinationsRouter.navigate("/admin/destinations/" + this.model.id + "/new", {
trigger: true
});
}
});
}).call(this);
(function() {
AdminApp.EditDestinationView = Backbone.View.extend({
"class": "container",
events: {
"click .cancel": "cancelDestination",
"click .update": "updateDestination",
"click .translations .btn": "changeTranslation"
},
initialize: function(options) {
if (!this.model) {
this.model = new AdminApp.Destination;
this.initializeDestination(this.model);
}
if (!this.model.isNew()) {
this.model.fetch();
}
if (options && options.parent) {
this.parent = options.parent;
}
this.model.on("change", this.render, this);
return _.bindAll(this, "render");
},
template: JST["templates/admin/destinations/edit"],
render: function() {
this.renderTemplate();
this.renderMap();
return this;
},
renderTemplate: function() {
var context, data, locales;
locales = {
locales: I18n.available_locales
};
if (!this.parent || (this.model.get('level') === 0)) {
data = {
type: "country"
};
}
if (((this.parent != null) && this.parent.get('level') === 0) || ((this.model.get('level') != null) && this.model.get('level') === 1)) {
data = {
type: "region"
};
}
if (((this.parent != null) && this.parent.get('level') === 1) || ((this.model.get('level') != null) && this.model.get('level') === 2)) {
data = {
type: "area"
};
}
context = $.extend(JSON.parse(JSON.stringify(this.model)), locales);
context = $.extend(context, data);
this.$el.html(this.template(context));
this.$el.find("#destination_name_" + this.model.defaultLocale).show();
return this.$el.find(".translations .btn[data-locale='" + this.model.defaultLocale + "']").addClass("active");
},
renderMap: function() {
var self;
self = this;
$(".map-holder").empty();
if (this.map != null) {
return self.$(".map-holder").append(this.map.$el);
} else {
this.map = new AdminApp.MapView({
model: this.model
});
return self.$(".map-holder").append(this.map.render().el);
}
},
cancelDestination: function(e) {
e.preventDefault();
return AdminApp.destinationsRouter.navigate("/admin/destinations", {
trigger: true
});
},
updateDestination: function(e) {
var data,
_this = this;
e.preventDefault();
data = this.extractFormData();
debug(data);
return this.model.save(data, {
success: function() {
$("#admin-app").empty();
return AdminApp.destinationsRouter.navigate("/admin/destinations", {
trigger: true
});
},
error: function(model, response) {
var errors;
errors = $.parseJSON(response.responseText);
_this.$el.find(".control-group.error span.help-inline").remove();
_this.$el.find(".control-group").removeClass("error");
return _(errors).each(function(value, key) {
var $controlGroup;
debug(key);
$controlGroup = _this.$el.find(".control-group." + key);
$controlGroup.addClass("error");
return $controlGroup.find(".controls").append("<span class='help-inline'>" + value + "</span>");
});
}
});
},
extractFormData: function() {
var data, locale, string, _i, _len, _ref;
data = {};
data["name"] = {};
_ref = this.model.locales;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
locale = _ref[_i];
string = this.$("#destination_name_" + locale).val();
if (string !== "") {
data["name"][locale] = string;
}
}
data.lat = parseFloat($("#destination_latitude").val());
data.lng = parseFloat($("#destination_longitude").val());
data.zoom = $("#destination_zoom").val();
data.swlat = parseFloat($("#destination_swlat").val());
data.swlng = parseFloat($("#destination_swlng").val());
data.nelat = parseFloat($("#destination_nelat").val());
data.nelng = parseFloat($("#destination_nelng").val());
if (this.parent) {
data["parent_id"] = this.parent.id;
data["level"] = 1;
}
return data;
},
changeTranslation: function(ev) {
var $el, field, locale;
ev.preventDefault();
$el = $(ev.currentTarget);
locale = $el.data("locale");
field = $el.data("field");
this.$("input[name='destination[" + field + "]']").hide();
return this.$("#destination_" + field + "_" + locale).show();
},
initializeDestination: function(model) {
var data, initlang, locale, newlang, _i, _len, _ref;
newlang = {};
_ref = model.locales;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
locale = _ref[_i];
newlang["" + locale] = "";
initlang = $.extend(newlang, initlang);
}
data = {
name: initlang,
lat: 0,
lng: 0,
zoom: 0,
swlat: 0,
swlng: 0,
nelat: 0,
nelng: 0
};
return model.set(data, {
silent: true
});
}
});
}).call(this);
(function() {
AdminApp.DestinationsView = Support.CompositeView.extend({
template: JST["templates/admin/destinations/index"],
initialize: function(options) {
this.config = options.config;
this.collection.lazy_load();
this.collection.on("reset", this.render, this);
this.collection.on("add", this.render, this);
this.collection.on("remove", this.render, this);
this.config.on("change:locale", this.render, this);
return _.bindAll(this, "render");
},
events: {
"click a.new-destination": "newDestination"
},
render: function() {
$(".navbar li").removeClass("active");
$(".navbar li.destinations").addClass("active");
this.renderTemplate();
this.renderCountries();
return this;
},
renderTemplate: function() {
return this.$el.html(this.template());
},
renderCountries: function() {
var countries, self;
self = this;
countries = this.collection.filterByLevel(0);
return _(countries).each(function(country) {
var area, areas, region, regions, view, _i, _len, _results,
_this = this;
view = new AdminApp.CountryView({
model: country
});
self.renderChild(view);
self.$("tbody").last().append(view.el);
regions = country.collection.filter(function(destination) {
return destination.get("parent_id") === country.id;
});
if (regions.length > 0) {
_results = [];
for (_i = 0, _len = regions.length; _i < _len; _i++) {
region = regions[_i];
view = new AdminApp.RegionView({
model: region
});
self.renderChild(view);
self.$("tbody").last().append(view.el);
areas = region.collection.filter(function(destination) {
return destination.get("parent_id") === region.id;
});
if (areas.length > 0) {
self.$("td.areas").last().append("<ul class='areas span6 unstyled'/>");
_results.push((function() {
var _j, _len1, _results1;
_results1 = [];
for (_j = 0, _len1 = areas.length; _j < _len1; _j++) {
area = areas[_j];
view = new AdminApp.AreaView({
model: area
});
self.renderChild(view);
_results1.push(self.$("td.areas > ul").last().append(view.el));
}
return _results1;
})());
} else {
_results.push(void 0);
}
}
return _results;
}
});
},
newDestination: function(ev) {
ev.preventDefault();
return AdminApp.destinationsRouter.navigate("/admin/destinations/new", {
trigger: true
});
}
});
}).call(this);
(function() {
AdminApp.MapView = Backbone.View.extend({
tagName: "div",
id: "map-canvas",
initialize: function() {
var latitude, longitude, myOptions, pinColor, pinIcon;
if (this.map != null) {
this.map.remove;
}
if (this.marker != null) {
this.marker.remove;
}
if (this.model.isNew() || !(this.model.get('lat') != null) || !(this.model.get('lng') != null)) {
latitude = 1.289411;
longitude = 103.844147;
this.zoom = 5;
} else {
latitude = this.model.get('lat');
longitude = this.model.get('lng');
this.zoom = this.model.get('zoom');
}
this.latlng = new google.maps.LatLng(latitude, longitude);
myOptions = {
zoom: this.zoom,
center: this.latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
this.map = new google.maps.Map(this.el, myOptions);
pinColor = "CA0000";
pinIcon = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor, null, null, null, new google.maps.Size(21, 34));
this.marker = new google.maps.Marker({
map: this.map,
position: this.latlng,
draggable: true,
title: "Map Center"
});
this.marker.setIcon(pinIcon);
_.bindAll(this, 'dragMarker', 'dragMap', 'zoomChange', 'setmapCenter');
google.maps.event.addListener(this.marker, "dragend", this.dragMarker);
google.maps.event.addListener(this.map, "dragend", this.dragMap);
google.maps.event.addListener(this.map, 'zoom_changed', this.zoomChange);
return google.maps.event.addListener(this.map, 'tilesloaded', this.setmapCenter);
},
render: function() {
return this;
},
dragMarker: function() {
this.latlng = this.marker.getPosition();
this.map.panTo(this.latlng);
return this.updateGeoValues();
},
setmapCenter: function() {
google.maps.event.trigger(this.map, 'resize');
return this.map.setCenter(this.latlng);
},
dragMap: function() {
this.latlng = this.map.getCenter();
this.marker.setPosition(this.latlng);
return this.updateGeoValues();
},
zoomChange: function() {
this.zoom = this.map.getZoom();
return this.updateGeoValues();
},
updateGeoValues: function() {
var bounds;
bounds = this.map.getBounds();
this.ne = bounds.getNorthEast();
this.sw = bounds.getSouthWest();
$("#destination_latitude").val(this.latlng.lat());
$("#destination_longitude").val(this.latlng.lng());
$("#destination_zoom").val(this.zoom);
$("#destination_swlat").val(this.sw.lat());
$("#destination_swlng").val(this.sw.lng());
$("#destination_nelat").val(this.ne.lat());
return $("#destination_nelng").val(this.ne.lng());
}
});
}).call(this);
(function() {
AdminApp.RegionView = Support.CompositeView.extend({
tagName: "tr",
className: "regions",
events: {
"click .edit": "editDestination",
"click .delete": "deleteDestination",
"click .new-area": "newArea"
},
template: JST["templates/admin/destinations/region"],
render: function() {
this.$el.html(this.template(JSON.parse(JSON.stringify(this.model))));
this.$el.attr("data-id", "destination-" + this.model.id);
return this;
},
editDestination: function(ev) {
ev.preventDefault();
ev.stopPropagation();
return AdminApp.destinationsRouter.navigate("/admin/destinations/" + this.model.id + "/edit", {
trigger: true
});
},
deleteDestination: function(ev) {
ev.preventDefault();
ev.stopPropagation();
if (confirm("Are you sure?")) {
return this.model.destroy();
}
},
newArea: function(ev) {
ev.preventDefault();
ev.stopPropagation();
return AdminApp.destinationsRouter.navigate("/admin/destinations/" + this.model.id + "/new", {
trigger: true
});
}
});
}).call(this);
(function() {
AdminApp.FileInputView = Backbone.View.extend({
tagName: "input",
events: {
"change:input[type='file']": "change",
"blur:input[type='url']": "change"
},
initialize: function(options) {
_.bindAll(this, "render", "enable", 'fail', 'uploading', 'done', "change");
options = options || {};
this.model = options.model;
debug("MODEL PASSED TO FileInputView");
debug(this.model);
this.url = options.url || ("/api/photos?auth_token=" + (AdminApp.admin.get('auth_token')));
this.data = options.data || {};
this.enabled = options.enabled || true;
return this.name = options.name;
},
render: function() {
this.$el.attr("type", this.input_type).attr("name", this.name);
if (this.multiple) {
this.$el.attr("multiple", true);
}
if (!this.enabled) {
this.$el.attr("disabled", "disabled");
}
this.$input = this.$el;
return this;
},
enable: function(enable) {
if (this.enabled !== enable) {
this.enabled = enable;
if (enable) {
this.$input.removeAttr("disabled");
} else {
this.$input.attr("disabled", "disabled");
}
return this.trigger("enabled", enable);
}
},
toggle_enable: function() {
return this.enable(!this._enabled);
},
change: function(ev) {
var data,
_this = this;
debug("Change Event");
debug($(ev.currentTarget).attr('type'));
debug($(ev.currentTarget).val());
if (this.enabled) {
debug("IN CHANGE LOOP");
if ($(ev.currentTarget).attr('type') === "file") {
if ($(ev.currentTarget).val() !== "") {
return $.ajax(this.url, {
files: this.$input,
iframe: true,
dataType: "json",
data: this.data,
processData: false
}).always(this.uploading).done(this.done).fail(this.fail);
}
} else {
debug("detected URL TYPE");
if (this.validateURL($(ev.currentTarget).val()) === true) {
data = {
image_url: $(ev.currentTarget).val()
};
return this.model.save(data, {
success: function(model, response) {
debug("done a cgabfe");
return _this.trigger("done", _this.done);
}
});
} else {
return alert("Please enter a full web address for the image i.e. http:/images.image.com/image.jpg");
}
}
}
},
done: function(data, textStatus, jqXHR) {
return this.trigger("done", data);
},
fail: function(jqXHR) {
console.log(jqXHR);
return this.trigger("fail", JSON.parse(jqXHR.responseText), jqXHR);
},
uploading: function(data, textStatus, jqXHR) {
this.trigger("uploading");
return this.$input.val("");
},
validateURL: function(textval) {
var urlregex;
urlregex = new RegExp("^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([0-9A-Za-z]+\.)");
return urlregex.test(textval);
}
});
AdminApp.FileFieldView = AdminApp.FileInputView.extend({
tagName: "label",
className: "file-upload",
events: {
"change input[type='file']": "change",
"blur input[type='url']": "change"
},
template: JST["templates/admin/media/fileinput"],
initialize: function(options) {
options = options || {};
this.text = options.text || "Upload File";
this.input_type = options.input_type || "file";
this.template = this.template;
this.name = options.name || "file[]";
return AdminApp.FileInputView.prototype.initialize.call(this, options);
},
serialize: function() {
return {
text: this.text,
name: this.name,
multiple: this.multiple,
enabled: this.enabled,
input_type: this.input_type
};
},
render: function() {
this.$el.html(this.template(this.serialize()));
this.$input = this.$("input[type=" + this.input_type + "]");
if (!this.enabled) {
this.$el.addClass("disabled");
}
return this;
},
enable: function(enable) {
if (this.enabled !== enable) {
this.$el[(enable ? "removeClass" : "addClass")]("disabled");
return AdminApp.FileInputView.prototype.enable.call(this, enable);
}
}
});
}).call(this);
(function() {
AdminApp.MediaPanelView = Backbone.View.extend({
initialize: function(options) {
this.el = options.el;
this.model = options.model;
_.bindAll(this, "render");
this.model.image.on("change", this.render, this);
this.model.image.on("destroy", this.clearChildImage, this);
this.model.image.on("destroy", this.render, this);
return this.render();
},
template: JST["templates/admin/media/mediapanel"],
events: {
"click button.image": "showImageEdit"
},
render: function() {
if (this.image_edit_view != null) {
this.image_edit_view.remove();
}
if (this.input_fields != null) {
this.input_fields.remove;
}
this.el.empty();
if (this.model.image.get('image_uid') != null) {
this.renderTemplate();
this.renderImage();
} else {
this.renderFields();
}
return this;
},
renderTemplate: function() {
var photo;
photo = {
crop_url: this.model.image.get('crop_url')
};
return this.el.append(this.template(photo));
},
renderFields: function() {
var input_field, _i, _j, _len, _len1, _ref, _ref1, _results;
this.input_fields = [
new AdminApp.FileFieldView({
model: this.model.image,
multiple: false,
input_type: "file",
name: "file[]"
}), new AdminApp.FileFieldView({
model: this.model.image,
multiple: false,
text: "Image URL",
input_type: "url",
name: "url[]"
})
];
this.$el.append("<p><strong>Choose a file to upload or input a url for the image</strong></p>");
this.$el.append('<ul id="upload-inputs" class="unstyled"></ul>');
_ref = this.input_fields;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
input_field = _ref[_i];
input_field.on('uploading', this.uploading, this);
input_field.on('done', this.done, this);
input_field.on('fail', this.fail, this);
input_field.on('enabled', this.enable, this);
}
_ref1 = this.input_fields;
_results = [];
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
input_field = _ref1[_j];
_results.push(this.$el.find("#upload-inputs").append(input_field.render().el));
}
return _results;
},
renderImage: function() {
this.image_edit_view = new AdminApp.SingleUploadView({
model: this.model.image
});
return this.$el.append(this.image_edit_view.render().el);
},
showImageEdit: function() {
return this.el.find("#current-image").hide();
},
uploading: function() {
this.$(".file-upload").addClass("disabled");
return this.$(".uploads").append("<li>Uploading...</li>");
},
enable: function(enabled) {
return this.$(".file-upload")[(enabled ? "removeClass" : "addClass")]("disabled");
},
fail: function(data) {
console.error(data);
return this.$(".uploads").append("<li>Error</li>");
},
done: function(data) {
this.$(".file-upload").removeClass("disabled");
console.log("uploaded successfully");
return this.model.image.set(data);
},
clearChildImage: function() {
this.image_edit_view.remove;
this.model.image.clear();
return this.render();
}
});
}).call(this);
(function() {
var AvatarCropper,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
AdminApp.SingleUploadView = Backbone.View.extend({
tagName: "ul",
className: "unstyled",
id: "#media-upload",
events: {
"click .delete-image": "delete",
"click .crop-image": "crop",
"click .update-image": "updateImage"
},
template: JST["templates/admin/media/imageitem"],
initialize: function(options) {
options = options || {};
this.model = options.model;
this.model.on("change", this.render, this);
this.model.on("destroy", this.remove, this);
return _.bindAll(this, "render", "remove");
},
render: function() {
this.$el.append(this.template(this.model.toJSON()));
return this;
},
remove: function() {
return this.trigger("clearChildImage");
},
"delete": function(e) {
return this.model.destroy();
},
crop: function(e) {
$("#image-panel").show();
$(".crop-image").removeClass("crop-image");
e.preventDefault();
return this.cropper = new AvatarCropper(this.model);
},
updateImage: function(e) {
var data,
_this = this;
$("#image-panel").show();
delete this.cropper;
e.preventDefault;
data = {
_id: this.model.id,
crop_x: parseFloat($('#crop_x').val()),
crop_y: parseFloat($('#crop_y').val()),
crop_w: parseFloat($('#crop_w').val()),
crop_h: parseFloat($('#crop_h').val()),
image_height: this.model.get('image_height'),
image_uid: this.model.get('image_uid'),
image_width: this.model.get('image_width')
};
return this.model.save(data, {
error: function() {
return console.log("An error occured saving account photo");
}
});
}
});
AvatarCropper = (function() {
AvatarCropper.name = 'AvatarCropper';
function AvatarCropper(model) {
this.updatePreview = __bind(this.updatePreview, this);
this.update = __bind(this.update, this);
var aspect, aspect_ratio, crop_h, crop_w, crop_x, crop_y, height, landscape, portrait, truesize, width;
aspect_ratio = 1.5;
width = model.get('image_width');
height = model.get('image_height');
crop_x = model.get('crop_x');
crop_y = model.get('crop_y');
crop_w = model.get('crop_w');
crop_h = model.get('crop_h');
truesize = [width, height];
portrait = model.get('image_height') / model.get('image_width');
landscape = model.get('image_width') / model.get('image_height');
if (model.get('image_width') >= model.get('image_height')) {
aspect = landscape;
} else {
aspect = portrait;
}
$.Jcrop('#cropbox', {
aspectRatio: 1.5,
setSelect: [crop_x, crop_y, crop_w, crop_h],
onSelect: this.update,
onChange: this.update
});
}
AvatarCropper.prototype.update = function(coords) {
var scale;
scale = 1;
$('#crop_x').val(coords.x);
$('#crop_y').val(coords.y);
$('#crop_w').val(coords.w);
$('#crop_h').val(coords.h);
return this.updatePreview(coords);
};
AvatarCropper.prototype.updatePreview = function(coords) {
return $('#preview').css({
width: Math.round(180 / coords.w * $('#cropbox').width()) + 'px',
height: Math.round(120 / coords.h * $('#cropbox').height()) + 'px',
marginLeft: '-' + Math.round(180 / coords.w * coords.x) + 'px',
marginTop: '-' + Math.round(120 / coords.h * coords.y) + 'px'
});
};
return AvatarCropper;
})();
}).call(this);
(function() {
AdminApp.UploadListView = Backbone.View.extend({
initialize: function(options) {
options = options || {};
this.parent = options.parent;
return this.render();
},
render: function() {
$('#media-upload').empty();
$("#media-upload").append(new AdminApp.SingleUploadView({
model: this.model
}).render().el);
return this;
}
});
}).call(this);
(function() {
AdminApp.NavbarView = Backbone.View.extend({
el: "body > div.navbar",
initialize: function(options) {
this.admin = options.admin;
this.config = options.config;
this.config.on("change:locale", this.render, this);
return _.bindAll(this, "render");
},
render: function() {
this.$el.find("a.dropdown-toggle span.locale").html(this.config.get('locale').toUpperCase());
return this;
},
events: {
"click ul.dropdown-menu.locales a": "changeLocale"
},
changeLocale: function(ev) {
var $el;
ev.preventDefault();
$el = $(ev.currentTarget);
window.I18n.locale = $el.html().toLowerCase();
return this.config.set({
locale: $el.html().toLowerCase()
});
}
});
}).call(this);
(function() {
}).call(this);
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment